feat(role): 根据role判断用户的权限
This commit is contained in:
1 parent
80d78130f8
commit
a24bd94d43
93 files changed
+4472
-387
No files matched your search
@@ -16,6 +16,7 @@ import app.api.admin.faq_candidates # noqa: F401
|
||||
import app.api.admin.reports # noqa: F401
|
||||
import app.api.admin.database # noqa: F401
|
||||
import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.permission_roles # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.shipping_order_extraction # noqa: F401
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
api/admin/permission_roles.py
|
||||
|
||||
用途:管理端权限组列表、编辑、成员预览与确认调整。
|
||||
依赖:admin.blueprint、permission_roles.service。
|
||||
逻辑:/permission-roles* 路由;成员调整必须先 preview 再 apply。
|
||||
"""
|
||||
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.permission_roles import service as role_service
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_roles():
|
||||
"""列出全部权限组。"""
|
||||
return jsonify(role_service.list_roles())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def permission_role_catalog():
|
||||
"""角色编辑可选应用与应用内能力。"""
|
||||
return jsonify(role_service.grantable_catalog())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/picker-users', methods=['GET'])
|
||||
@require_admin
|
||||
def permission_role_picker_users():
|
||||
"""选人弹窗候选人(排除管理员)。"""
|
||||
return jsonify(role_service.list_picker_people())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_permission_role():
|
||||
"""新建权限组。"""
|
||||
data = request.get_json() or {}
|
||||
payload = role_service.create_role(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_permission_role(code: str):
|
||||
"""权限组详情。"""
|
||||
return jsonify(role_service.get_role_detail(code))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_permission_role(code: str):
|
||||
"""保存权限包并同步该组用户授权。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.update_role(code, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_permission_role(code: str):
|
||||
"""删除空的非内置权限组。"""
|
||||
return jsonify(role_service.delete_role(code))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>/members/preview', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_permission_role_members(code: str):
|
||||
"""确认前预览将改入/移出的人及来源角色。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.preview_role_members(code, data.get('selected_ids')))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>/members', methods=['POST'])
|
||||
@require_admin
|
||||
def apply_permission_role_members(code: str):
|
||||
"""确认后写回成员。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.apply_role_members(code, data.get('selected_ids')))
|
||||
@@ -42,6 +42,14 @@ def update_user(id: int):
|
||||
return jsonify(user_service.update_user(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch', methods=['PUT'])
|
||||
@require_admin
|
||||
def batch_update_users():
|
||||
"""批量更新用户部门 / 角色 / 状态。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.batch_update_users(data.get('user_ids', []), data.get('data') or {}))
|
||||
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@require_admin
|
||||
def cleanup_rejected_users():
|
||||
|
||||
@@ -37,7 +37,7 @@ def _serialize_agent_row(agent: Agent, *, visible_agent_ids: set[int] | None = N
|
||||
|
||||
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
|
||||
@@ -5,8 +5,8 @@ backend/app/api/contract_payment.py
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
鉴权:查询接口要求平台管理员或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -103,7 +103,7 @@ def _require_contract_payment_access():
|
||||
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_contract_payment_agent(user):
|
||||
if user.is_platform_admin() or _user_has_contract_payment_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
'Contract payment agent permission required',
|
||||
@@ -116,7 +116,7 @@ def _require_contract_payment_admin():
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
会改写外部系统或触发企微,因此仅平台管理员可调用。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
@@ -127,7 +127,7 @@ def _require_contract_payment_admin():
|
||||
ForbiddenError: 无合同付款访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
'Admin privilege required for contract payment jobs',
|
||||
code='CONTRACT_PAYMENT.ADMIN_REQUIRED',
|
||||
|
||||
@@ -54,7 +54,7 @@ def require_transfer_permission(f):
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
user = _require_user()
|
||||
if user.role == "admin":
|
||||
if user.is_platform_admin():
|
||||
return f(*args, **kwargs)
|
||||
agent = Agent.query.filter_by(agent_code=TRANSFER_AGENT_CODE, is_active=True).first()
|
||||
if agent is None or agent not in user.agents:
|
||||
|
||||
@@ -55,9 +55,9 @@ def _require_ledger_admin():
|
||||
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
return user
|
||||
if user.has_feature_permission('maintenance.ledger_write'):
|
||||
return user
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
|
||||
|
||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||
|
||||
@@ -435,7 +435,7 @@ def _build_login_payload(user: User, source: str='password', bind_status: str=No
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
**user.client_auth_fields(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
|
||||
@@ -185,7 +185,7 @@ def home():
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
@@ -213,7 +213,7 @@ def home():
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
@@ -297,7 +297,7 @@ def user_profile():
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'GET':
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
@@ -348,7 +348,7 @@ def get_agent_details(id):
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
if user.role != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
|
||||
@@ -184,7 +184,7 @@ def workspace_shipping_my_todos():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
@@ -209,7 +209,7 @@ def workspace_shipping_my_todos_count():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import count_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
return _ok(count_my_todos(user.id, is_admin=is_admin))
|
||||
|
||||
|
||||
@@ -234,7 +234,7 @@ def workspace_shipping_done_lines():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.done_line_report import list_done_notice_lines
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
@@ -261,7 +261,7 @@ def workspace_shipping_done_lines_export():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.done_line_report import build_done_lines_xlsx
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
stream, filename = build_done_lines_xlsx(
|
||||
user.id,
|
||||
is_admin=is_admin,
|
||||
@@ -287,7 +287,7 @@ def _batch_task_nos(data: dict) -> list[str]:
|
||||
|
||||
def _can_dispose_task(user, task) -> bool:
|
||||
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
|
||||
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
|
||||
return bool(user.is_platform_admin()) or task.user_id in {None, user.id}
|
||||
|
||||
|
||||
def _batch_dispose(action: str):
|
||||
@@ -330,7 +330,7 @@ def _batch_dispose(action: str):
|
||||
def workspace_batch_purge_shipping_tasks():
|
||||
"""仅管理员可永久清除回收站中的纯误建任务;每条均在行锁下重查全部引用。"""
|
||||
user = _require_user()
|
||||
if str(getattr(user, 'role', '')).lower() != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
from app.core.errors import ForbiddenError
|
||||
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
@@ -527,7 +527,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
position / user_mode / actions / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
@@ -547,7 +547,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
def workspace_shipping_task_odm_options(task_no: str):
|
||||
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
|
||||
@@ -561,7 +561,7 @@ def workspace_shipping_task_odm_options(task_no: str):
|
||||
def workspace_set_shipping_task_odm_choice(task_no: str):
|
||||
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.notice_odm_choice_service import set_notice_odm_choice
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
|
||||
@@ -586,7 +586,7 @@ def workspace_set_shipping_task_odm_choice(task_no: str):
|
||||
def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.audit_query_service import list_task_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
@@ -618,7 +618,7 @@ def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
def workspace_shipping_task_freight_notice_groups(task_no: str):
|
||||
"""读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_visible_to_user,
|
||||
list_freight_notice_groups_for_task,
|
||||
@@ -1589,7 +1589,7 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_run
|
||||
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
|
||||
@@ -1624,7 +1624,7 @@ def workspace_get_shipping_order_review_queue(run_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_queue
|
||||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
||||
@@ -1661,7 +1661,7 @@ def workspace_get_shipping_order_review_case(case_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_case_snapshot import (
|
||||
build_order_review_case_snapshot,
|
||||
@@ -1709,7 +1709,7 @@ def workspace_retry_shipping_order_stp_auto_create(case_no: str):
|
||||
要求前端切换到 reconcile-and-progress;通过后再委托 retry_stp_auto_create_for_case。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
retry_stp_auto_create_for_case,
|
||||
@@ -1747,7 +1747,7 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
|
||||
source_content_hash: string(可选,请求快照用于参数一致性)
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
payload = request.get_json(silent=True) if request.is_json else None
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
@@ -1806,7 +1806,7 @@ def workspace_audit_shipping_order_review_version_history(case_no: str):
|
||||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件,禁止仅改本地 UI 状态而不留痕。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
@@ -1852,7 +1852,7 @@ def workspace_audit_shipping_order_review_eligibility_details(case_no: str):
|
||||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
@@ -2120,7 +2120,7 @@ def workspace_revalidate_shipping_order_review_reservation(case_no: str):
|
||||
def workspace_list_shipping_order_review_audit_timeline(case_no: str):
|
||||
"""业务用户 Case 审计时间线(无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.audit_query_service import list_review_case_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
@@ -2161,7 +2161,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
decide_review_line_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
result = decide_review_line_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
@@ -2262,7 +2262,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
|
||||
close_remaining_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
result = close_remaining_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
@@ -2675,7 +2675,7 @@ def workspace_attempt_shipping_order_review_field_locate(case_no: str):
|
||||
def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||||
"""列出 Case 下 Dify 最小证据建议记录。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import list_case_suggestions
|
||||
|
||||
return _ok(list_case_suggestions(user_id=user.id, case_no=case_no, is_admin=is_admin))
|
||||
@@ -2685,7 +2685,7 @@ def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||||
def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
"""为指定字段请求 Dify 最小证据建议;Provider 不可用时不阻断人工复核。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import request_field_suggestion
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='request_llm_suggestion')
|
||||
@@ -2710,7 +2710,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, suggestion_no: str):
|
||||
"""人工裁决 LLM 建议:accept / modify / reject。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import decide_suggestion
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='adjudicate_llm_suggestion')
|
||||
|
||||
@@ -135,7 +135,7 @@ def workspace_post_process_gate_action(execution_no: str, gate_code: str):
|
||||
action_code=parsed['action_code'],
|
||||
expected_gate_version=parsed['expected_gate_version'],
|
||||
idempotency_key=parsed['idempotency_key'],
|
||||
actor_type='admin' if str(user.role or '').lower() == 'admin' else 'user',
|
||||
actor_type='admin' if user.is_platform_admin() else 'user',
|
||||
actor_id=int(user.id),
|
||||
payload=parsed['payload'],
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/api/workspace/voucher_check.py
|
||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||
查询要求平台 admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅 admin。
|
||||
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -42,7 +42,7 @@ def _user_has_voucher_check_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的立账凭证检核 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;平台管理员不走此判断。
|
||||
|
||||
Args:
|
||||
user: 已认证用户。
|
||||
@@ -58,18 +58,18 @@ def _require_voucher_check_access():
|
||||
"""
|
||||
确保当前用户已登录且具备立账凭证检核访问权限。
|
||||
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
核心逻辑:is_platform_admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Returns:
|
||||
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
|
||||
已认证且具备立账凭证 Agent 授权(或平台管理员)的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_voucher_check_agent(user):
|
||||
if user.is_platform_admin() or _user_has_voucher_check_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Voucher check agent permission required",
|
||||
@@ -81,7 +81,7 @@ def _require_admin():
|
||||
"""
|
||||
确保当前用户既有立账凭证访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 is_platform_admin。
|
||||
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
@@ -91,7 +91,7 @@ def _require_admin():
|
||||
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_voucher_check_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for voucher check jobs",
|
||||
code="VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||
@@ -181,7 +181,7 @@ def workspace_voucher_notifications():
|
||||
def workspace_voucher_notify_config_get():
|
||||
"""
|
||||
读取按文件类型的企微接收人配置。
|
||||
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
核心逻辑:仅 is_platform_admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
"""
|
||||
_require_admin()
|
||||
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
|
||||
@@ -191,7 +191,7 @@ def workspace_voucher_notify_config_get():
|
||||
def workspace_voucher_notify_config_put():
|
||||
"""
|
||||
保存按文件类型的企微接收人。
|
||||
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
核心逻辑:仅 is_platform_admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
"""
|
||||
user = _require_admin()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
|
||||
@@ -47,7 +47,7 @@ def _resolve_request_agent_id() -> str | None:
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → 平台管理员放行或检查 user.agents。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
@@ -66,7 +66,7 @@ def require_agent_permission(f):
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
@@ -77,8 +77,8 @@ def require_agent_permission(f):
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制仅 admin 角色可访问。
|
||||
核心逻辑:解析用户 → 校验 role == admin;JWT 必填时检查 Authorization 头。
|
||||
装饰器:限制仅平台管理员可访问。
|
||||
核心逻辑:解析用户 → 校验 is_platform_admin;JWT 必填时检查 Authorization 头。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
@@ -88,7 +88,7 @@ def require_admin(f):
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||
raise UnauthorizedError('JWT token is required')
|
||||
if user.role != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ backend/app/models/__init__.py
|
||||
|
||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
from app.models.permission_role import PermissionRole, permission_role_agents
|
||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||
from app.models.department import Department
|
||||
@@ -241,6 +242,8 @@ from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
__all__ = [
|
||||
'Base',
|
||||
'user_agent_permissions',
|
||||
'permission_role_agents',
|
||||
'PermissionRole',
|
||||
'ZlLanguage',
|
||||
'Department',
|
||||
'UserHomepageConfig',
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
models/permission_role.py
|
||||
|
||||
用途:可配置权限组(角色包)及角色与 Agent 的授权关系。
|
||||
依赖:models.base.Base、agents / 无直接 User FK(成员仍写在 users.role)。
|
||||
逻辑:Admin 角色配置读写本表;运行时按 users.role=code 取包,再同步到 user_agent_permissions。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.extensions import db
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
permission_role_agents = db.Table(
|
||||
'permission_role_agents',
|
||||
db.Column('role_id', ForeignKey('permission_roles.id', ondelete='CASCADE'), primary_key=True),
|
||||
db.Column('agent_id', ForeignKey('agents.id', ondelete='CASCADE'), primary_key=True),
|
||||
)
|
||||
|
||||
|
||||
class PermissionRole(Base):
|
||||
"""权限组:可用应用入口 + 应用内能力。"""
|
||||
|
||||
__tablename__ = 'permission_roles'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('code', name='uq_permission_roles_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
is_default: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_system: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_platform_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
agents: Mapped[List['Agent']] = relationship(
|
||||
'Agent',
|
||||
secondary=permission_role_agents,
|
||||
)
|
||||
+42
-16
@@ -2,8 +2,9 @@
|
||||
backend/app/models/user.py
|
||||
|
||||
用途:用户账户、首页偏好、登录审计相关模型。
|
||||
依赖:models.base(Base、user_agent_permissions)。
|
||||
逻辑:User 与 Agent 多对多经 user_agent_permissions;admin/user API 主要读写本模块。
|
||||
依赖:models.base(Base、user_agent_permissions);功能权限优先读 permission_roles。
|
||||
逻辑:User 与 Agent 多对多经 user_agent_permissions;角色包启用后个人 feature_permissions 仅作兼容覆盖。
|
||||
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -59,7 +60,7 @@ class User(Base):
|
||||
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
|
||||
email: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
role: Mapped[str] = mapped_column(String(20), default='user')
|
||||
role: Mapped[str] = mapped_column(String(64), default='user')
|
||||
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
|
||||
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
@@ -85,27 +86,41 @@ class User(Base):
|
||||
)
|
||||
|
||||
def _role_default_feature_permissions(self) -> dict[str, bool]:
|
||||
"""返回当前角色自带的功能权限默认值。"""
|
||||
"""
|
||||
返回未配置权限组时的功能权限默认值。
|
||||
|
||||
核心逻辑:只认 is_platform_admin;不再用 hr / maintenance_manager 角色名暗示能力。
|
||||
"""
|
||||
admin = self.is_platform_admin()
|
||||
return {
|
||||
'training_hr_manage': self.role in {'admin', 'hr'},
|
||||
# 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予
|
||||
'shipping_notice_force_create': self.role == 'admin',
|
||||
# 货代审计敏感快照/前后 Diff 读取:admin 默认开;不新建角色,可显式关闭或授予
|
||||
'shipping_notice.audit_sensitive_read': self.role == 'admin',
|
||||
# XFA 字段拆分:编辑 / 预览 / 发布审核;admin 默认开,可显式收紧
|
||||
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
|
||||
'training_hr_manage': admin,
|
||||
'shipping_notice_force_create': admin,
|
||||
'shipping_notice.audit_sensitive_read': admin,
|
||||
'shipping_notice.xfa_split_rule_edit': admin,
|
||||
'shipping_notice.xfa_split_rule_preview': admin,
|
||||
'shipping_notice.xfa_split_rule_publish': admin,
|
||||
'maintenance.ledger_write': admin,
|
||||
}
|
||||
|
||||
def is_platform_admin(self) -> bool:
|
||||
"""当前用户是否属于平台管理权限组。"""
|
||||
from app.services.permission_roles.service import user_is_platform_admin
|
||||
|
||||
return user_is_platform_admin(self)
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
"""
|
||||
返回当前用户的有效功能权限。
|
||||
|
||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训等业务权限硬编码在多个模块。
|
||||
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
|
||||
核心逻辑:已配置 permission_roles 时完全由权限组计算;否则先按写死角色生成默认值,再用用户 JSON 覆盖。
|
||||
输出约束:仅返回布尔型权限键。
|
||||
"""
|
||||
from app.services.permission_roles.service import effective_feature_permissions
|
||||
|
||||
packaged = effective_feature_permissions(self)
|
||||
if packaged is not None:
|
||||
return packaged
|
||||
defaults = self._role_default_feature_permissions()
|
||||
raw = self.feature_permissions if isinstance(self.feature_permissions, dict) else {}
|
||||
result: dict[str, bool] = {}
|
||||
@@ -121,7 +136,7 @@ class User(Base):
|
||||
保存用户显式配置的功能权限覆盖项。
|
||||
|
||||
用途:给管理后台用户编辑表单落库权限配置。
|
||||
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。合同付款预警改走 Agent 授权,不再占用功能权限键。
|
||||
核心逻辑:只持久化与默认值不同的权限。未种子权限组时默认仅平台管理员全开;其余角色靠 JSON 覆盖或权限组能力键。合同付款预警改走 Agent 授权,不再占用功能权限键。
|
||||
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
@@ -143,6 +158,17 @@ class User(Base):
|
||||
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
|
||||
return self.has_feature_permission('training_hr_manage')
|
||||
|
||||
def client_auth_fields(self) -> dict:
|
||||
"""登录态/首页共用的角色与功能权限字段。"""
|
||||
from app.services.permission_roles.service import list_role_name_map
|
||||
|
||||
names = list_role_name_map()
|
||||
return {
|
||||
'is_platform_admin': self.is_platform_admin(),
|
||||
'role_name': names.get(self.role) or self.role,
|
||||
'feature_permissions': self.get_feature_permissions(),
|
||||
}
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/admin/agent_service.py
|
||||
|
||||
用途:管理端 Agent CRUD、连通性测试、用户权限绑定。
|
||||
依赖:models、DifyService、agent_registry.admin_payload、agent_registry.serialization。
|
||||
依赖:models、DifyService、agent_registry.admin_payload、agent_registry.serialization、permission_roles。
|
||||
逻辑:由 api/admin/agents.py 调用;创建/更新写入 Registry 结构化列并清理 extra 已迁移键。
|
||||
权限组启用后 update_agent_permissions 拒绝按人改授权。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -291,7 +292,13 @@ def _parse_chatflow_test_response(resp, data, output_info: str, analysis: str, p
|
||||
|
||||
|
||||
def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||||
"""将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。"""
|
||||
"""
|
||||
将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。
|
||||
权限组启用后禁止按人改应用,须改角色包或调整角色成员。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
@@ -68,11 +68,11 @@ def _notify_batch_permission_update(user: User, agents: list[Agent], action: str
|
||||
def batch_update_permissions(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
批量更新多用户的 Agent 权限(add / remove / set)。
|
||||
Returns:
|
||||
{ status, updated_count }。
|
||||
Raises:
|
||||
ValidationError: 未选择用户。
|
||||
权限组启用后禁止按人改应用,须改角色包或调整角色成员。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
action = data.get('action', 'add')
|
||||
@@ -95,11 +95,11 @@ def batch_update_permissions(data: dict[str, Any]) -> dict:
|
||||
def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
将指定用户的 Agent 权限重置为 agent_ids 列表(全量替换)。
|
||||
Returns:
|
||||
{ status }。
|
||||
Raises:
|
||||
NotFoundError: 用户不存在。
|
||||
权限组启用后禁止按人改应用。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('Not found')
|
||||
@@ -123,9 +123,14 @@ def list_permission_requests() -> list[dict]:
|
||||
def approve_permission_request(request_id: int) -> dict:
|
||||
"""
|
||||
批准权限申请:更新状态并将 Agent 加入用户权限。
|
||||
权限组启用后禁止按人加应用,须改角色包或调整角色成员。
|
||||
Raises:
|
||||
NotFoundError: 申请不存在。
|
||||
ValidationError: 已启用角色包时禁止直接授权。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
req = db.session.get(PermissionRequest, request_id)
|
||||
if not req:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/admin/user_service.py
|
||||
|
||||
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service。
|
||||
逻辑:由 api/admin/users.py 调用。
|
||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service、permission_roles。
|
||||
逻辑:由 api/admin/users.py 调用;权限组启用后创建/改角色只同步角色包,不再按人勾应用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,6 +17,7 @@ from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.auth import casdoor_service
|
||||
from app.services.permission_roles import service as role_service
|
||||
from app.services.user_admin import delete_admin_users
|
||||
|
||||
|
||||
@@ -68,13 +69,16 @@ def assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None)
|
||||
raise ConflictError(message, code=code, details={'field': field})
|
||||
|
||||
|
||||
def serialize_admin_user(user: User) -> dict:
|
||||
def serialize_admin_user(user: User, role_names: dict[str, str] | None = None) -> dict:
|
||||
names = role_names if role_names is not None else role_service.list_role_name_map()
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'email': user.email,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'role_name': names.get(user.role) or user.role,
|
||||
'is_platform_admin': user.is_platform_admin(),
|
||||
'status': user.status,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
@@ -137,7 +141,8 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
order_by = resolve_users_order_by(query_params)
|
||||
if 'page' not in query_params:
|
||||
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
||||
return [serialize_admin_user(u) for u in users]
|
||||
names = role_service.list_role_name_map()
|
||||
return [serialize_admin_user(u, names) for u in users]
|
||||
|
||||
try:
|
||||
page = int(query_params.get('page') or 1)
|
||||
@@ -162,8 +167,9 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
names = role_service.list_role_name_map()
|
||||
return {
|
||||
'items': [serialize_admin_user(u) for u in users],
|
||||
'items': [serialize_admin_user(u, names) for u in users],
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
@@ -194,21 +200,28 @@ def create_user(data: dict[str, Any]) -> dict:
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
role_code = role_service.assert_role_assignable(
|
||||
data.get('role') or role_service.default_role_code(),
|
||||
allow_admin=True,
|
||||
)
|
||||
user = User(
|
||||
username=data['username'],
|
||||
email=email,
|
||||
department=empty_to_none(data.get('department')),
|
||||
role=data.get('role', 'user'),
|
||||
role=role_code,
|
||||
status=data.get('status', 'active'),
|
||||
real_name=empty_to_none(data.get('real_name')),
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user.set_feature_permissions(data.get('feature_permissions'))
|
||||
if not role_service.roles_configured():
|
||||
user.set_feature_permissions(data.get('feature_permissions'))
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
try:
|
||||
if data.get('agent_ids'):
|
||||
if role_service.roles_configured():
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
elif data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
casdoor_service.sync_create_user(
|
||||
@@ -268,13 +281,21 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
try:
|
||||
for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key in data:
|
||||
if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key == 'role':
|
||||
next_role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
||||
role_service.ensure_not_last_admin(user, next_role)
|
||||
user.role = next_role
|
||||
elif key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, key, empty_to_none(data[key]))
|
||||
else:
|
||||
setattr(user, key, data[key])
|
||||
if 'feature_permissions' in data or 'role' in data:
|
||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||
user.set_feature_permissions(permissions_payload)
|
||||
if role_service.roles_configured():
|
||||
if 'role' in data:
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
else:
|
||||
if 'feature_permissions' in data or 'role' in data:
|
||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||
user.set_feature_permissions(permissions_payload)
|
||||
if new_password and user.check_password(new_password):
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_UNCHANGED',
|
||||
@@ -283,7 +304,7 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
)
|
||||
if new_password:
|
||||
user.set_password(new_password)
|
||||
if 'agent_ids' in data:
|
||||
if 'agent_ids' in data and not role_service.roles_configured():
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
if new_password:
|
||||
@@ -301,6 +322,30 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def batch_update_users(user_ids: list[Any], data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
批量更新用户部门 / 角色 / 状态。改角色时同步权限包。
|
||||
"""
|
||||
if not user_ids:
|
||||
raise ValidationError('No users selected')
|
||||
payload = data if isinstance(data, dict) else {}
|
||||
next_role = None
|
||||
if payload.get('role'):
|
||||
next_role = role_service.assert_role_assignable(payload.get('role'), allow_admin=True)
|
||||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
for user in users:
|
||||
if 'department' in payload and payload.get('department') != '':
|
||||
user.department = empty_to_none(payload.get('department'))
|
||||
if 'status' in payload and payload.get('status') != '':
|
||||
user.status = payload.get('status')
|
||||
if next_role:
|
||||
role_service.ensure_not_last_admin(user, next_role)
|
||||
user.role = next_role
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'updated_count': len(users)}
|
||||
|
||||
|
||||
def cleanup_rejected_users() -> dict:
|
||||
rejected_ids = [row[0] for row in db.session.query(User.id).filter_by(status='rejected').all()]
|
||||
cnt = delete_admin_users(rejected_ids)
|
||||
|
||||
@@ -48,7 +48,7 @@ class LoginResult:
|
||||
'username': self.user.username,
|
||||
'role': self.user.role,
|
||||
'default_agent_id': self.user.default_agent_id,
|
||||
'feature_permissions': self.user.get_feature_permissions(),
|
||||
**self.user.client_auth_fields(),
|
||||
'source': 'casdoor',
|
||||
'access_token': self.access_token,
|
||||
'refresh_token': self.refresh_token,
|
||||
|
||||
@@ -91,7 +91,7 @@ def supports(*, user, agent, query: str) -> bool:
|
||||
普通知识问答、普通员工提问或其他 Agent 一律不命中。
|
||||
|
||||
Args:
|
||||
user: 当前聊天用户代理对象;需至少包含 role。
|
||||
user: 当前聊天用户;须能 has_feature_permission('training_hr_manage')。
|
||||
agent: 当前 Agent 代理对象;需能识别是否为员工培训 Agent。
|
||||
query: 用户原始问题。
|
||||
|
||||
@@ -100,7 +100,7 @@ def supports(*, user, agent, query: str) -> bool:
|
||||
"""
|
||||
if not is_training_chat_agent(agent):
|
||||
return False
|
||||
if str(getattr(user, 'role', '') or '').strip() not in {'admin', 'hr'}:
|
||||
if not bool(getattr(user, 'has_feature_permission', None) and user.has_feature_permission('training_hr_manage')):
|
||||
return False
|
||||
return (
|
||||
_matches_any(query, _TRAINING_TOTAL_PATTERNS)
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
"""合同付款预警默认排程种子:每日扫描与周五 18:00 汇总。"""
|
||||
"""
|
||||
services/contract_payment/schedule_seed.py
|
||||
|
||||
用途:合同付款预警默认排程种子:每日扫描与周五 18:00 汇总。
|
||||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||
逻辑:幂等创建;owner 优先平台管理员,否则任意用户。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.models import ScheduleTask
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
|
||||
@@ -24,7 +31,7 @@ def ensure_default_contract_payment_schedules(*, commit: bool = True):
|
||||
Returns:
|
||||
新建的 ScheduleTask 列表;无用户时返回空列表。
|
||||
"""
|
||||
owner = db.session.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or db.session.query(User).order_by(User.id.asc()).first()
|
||||
owner = first_schedule_owner_user()
|
||||
if owner is None:
|
||||
return []
|
||||
created = []
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/file_assets/cleanup_schedule.py
|
||||
|
||||
用途:确保 platform Job file-asset-cleanup 存在默认 ScheduleTask(迁移补种 + 启动/建用户补建)。
|
||||
依赖:models.ScheduleTask/User、schedule.timezone_util.compute_next_run_at、SQLAlchemy Session 事件。
|
||||
依赖:models.ScheduleTask/User、permission_roles.service.first_schedule_owner_user、schedule.timezone_util、SQLAlchemy Session 事件。
|
||||
逻辑:create_app 启动时 ensure 一次;User after_commit 用独立 Session 即时补建(原 session 已 committed 不可再发 SQL)。
|
||||
"""
|
||||
|
||||
@@ -17,6 +17,7 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -60,14 +61,7 @@ def ensure_default_file_asset_cleanup_schedule(
|
||||
if existing is not None:
|
||||
return existing
|
||||
|
||||
owner = (
|
||||
sess.query(User)
|
||||
.filter(User.role == "admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if owner is None:
|
||||
owner = sess.query(User).order_by(User.id.asc()).first()
|
||||
owner = first_schedule_owner_user(sess)
|
||||
if owner is None:
|
||||
_LOGGER.info("skip seed file-asset-cleanup schedule: no users yet")
|
||||
return None
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/lean_training_schedule_seed.py
|
||||
|
||||
用途:幂等创建精益培训默认排程(每日逾期提醒扫描 + 每周一 09:00 视频推送)。
|
||||
依赖:ScheduleTask、User、上海时区 next_run 计算。
|
||||
逻辑:应用启动时在存在管理员和排程表后创建两个默认任务,管理员可在排程中心停用或调整。
|
||||
依赖:ScheduleTask、permission_roles.service.first_platform_admin_user、上海时区 next_run 计算。
|
||||
逻辑:应用启动时在存在平台管理员和排程表后创建两个默认任务,管理员可在排程中心停用或调整。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,13 +11,14 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.models import ScheduleTask
|
||||
from app.services.permission_roles.service import first_platform_admin_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
|
||||
def ensure_default_lean_training_schedule(*, commit: bool = True) -> list[ScheduleTask]:
|
||||
"""幂等创建精益培训默认排程:每日 09:00 提醒扫描 + 每周一 09:00 视频推送。"""
|
||||
owner = db.session.query(User).filter(User.role == "admin").order_by(User.id.asc()).first()
|
||||
owner = first_platform_admin_user()
|
||||
if not owner:
|
||||
return []
|
||||
now = datetime.utcnow()
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
services/permission_roles/__init__.py
|
||||
|
||||
用途:可配置权限组服务包入口。
|
||||
依赖:catalog、service。
|
||||
逻辑:api/admin/permission_roles 与 user_service 按需 import service。
|
||||
"""
|
||||
@@ -0,0 +1,173 @@
|
||||
"""
|
||||
services/permission_roles/catalog.py
|
||||
|
||||
用途:角色包可勾选的应用内能力目录,以及按 Agent 属性匹配种子应用。
|
||||
依赖:Agent.handler_config.content_profile、agent_code。
|
||||
逻辑:角色编辑按已选 Agent 在应用卡片内展示能力;bind 支持 always / content_profile: / agent_code: / kind:;迁移种子用 match 规则给标准包勾入口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# 与 User.get_feature_permissions 输出键对齐。
|
||||
KNOWN_FEATURE_KEYS: tuple[str, ...] = (
|
||||
'training_hr_manage',
|
||||
'shipping_notice_force_create',
|
||||
'shipping_notice.audit_sensitive_read',
|
||||
'shipping_notice.xfa_split_rule_edit',
|
||||
'shipping_notice.xfa_split_rule_preview',
|
||||
'shipping_notice.xfa_split_rule_publish',
|
||||
'maintenance.ledger_write',
|
||||
)
|
||||
|
||||
FEATURE_CATALOG: tuple[dict[str, Any], ...] = (
|
||||
{
|
||||
'key': 'training_hr_manage',
|
||||
'bind': 'content_profile:training',
|
||||
'name': 'HR 管理',
|
||||
'hint': '查看统计、筛选记录并导出 Excel',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice_force_create',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '强制新建重复单据',
|
||||
'hint': '跳过重复拦截,新建发货通知',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice.audit_sensitive_read',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '读取敏感审计',
|
||||
'hint': '查看 before / after / Diff 正文',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice.xfa_split_rule_edit',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '编辑 XFA 拆分规则',
|
||||
'hint': '维护字段拆分规则',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice.xfa_split_rule_preview',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '预览拆分',
|
||||
'hint': '预览拆分结果',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice.xfa_split_rule_publish',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '发布拆分规则',
|
||||
'hint': '审核并发布规则',
|
||||
},
|
||||
{
|
||||
'key': 'maintenance.ledger_write',
|
||||
'bind': 'kind:maintenance',
|
||||
'name': '台账与维修维护',
|
||||
'hint': '维护设备台账与维修记录',
|
||||
},
|
||||
)
|
||||
|
||||
# 现网 users.role 枚举对应的标准权限组。admin/user/hr 为内置;rd/shipping 可后续增删应用。
|
||||
SYSTEM_ROLE_SEEDS: tuple[dict[str, Any], ...] = (
|
||||
{
|
||||
'code': 'user',
|
||||
'name': '普通用户',
|
||||
'description': '新建用户默认。勾通用入口即可使用企业知识库。',
|
||||
'is_default': True,
|
||||
'is_system': True,
|
||||
'is_platform_admin': False,
|
||||
'sort_order': 10,
|
||||
'features': {},
|
||||
'agent_match': ('entrance',),
|
||||
},
|
||||
{
|
||||
'code': 'rd',
|
||||
'name': '研发应用',
|
||||
'description': '通用入口,以及研发侧应用(如专利)。本地尚未接入的应用,之后勾进本组即可。',
|
||||
'is_default': False,
|
||||
'is_system': False,
|
||||
'is_platform_admin': False,
|
||||
'sort_order': 20,
|
||||
'features': {},
|
||||
'agent_match': ('entrance', 'patent'),
|
||||
},
|
||||
{
|
||||
'code': 'hr',
|
||||
'name': '培训 HR',
|
||||
'description': '可进员工培训,并打开 HR 管理。',
|
||||
'is_default': False,
|
||||
'is_system': True,
|
||||
'is_platform_admin': False,
|
||||
'sort_order': 30,
|
||||
'features': {'training_hr_manage': True},
|
||||
'agent_match': ('entrance', 'training'),
|
||||
},
|
||||
{
|
||||
'code': 'shipping',
|
||||
'name': '货代专员',
|
||||
'description': '聊天与工作台共用货代应用入口。',
|
||||
'is_default': False,
|
||||
'is_system': False,
|
||||
'is_platform_admin': False,
|
||||
'sort_order': 40,
|
||||
'features': {'shipping_notice_force_create': True},
|
||||
'agent_match': ('entrance', 'shipping'),
|
||||
},
|
||||
{
|
||||
'code': 'admin',
|
||||
'name': '管理员',
|
||||
'description': '内置角色。应用入口隐式全开,可进入 /admin。',
|
||||
'is_default': False,
|
||||
'is_system': True,
|
||||
'is_platform_admin': True,
|
||||
'sort_order': 90,
|
||||
'features': {key: True for key in KNOWN_FEATURE_KEYS},
|
||||
'agent_match': (),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def agent_content_profile(agent: Any) -> str:
|
||||
"""读取 Agent.handler_config.content_profile。"""
|
||||
raw = getattr(agent, 'handler_config', None)
|
||||
if not isinstance(raw, dict):
|
||||
return ''
|
||||
return str(raw.get('content_profile') or '').strip()
|
||||
|
||||
|
||||
def agent_matches_kind(agent: Any, kind: str) -> bool:
|
||||
"""
|
||||
判断 Agent 是否属于种子包中的一类入口。
|
||||
|
||||
kind: entrance / training / shipping / patent / maintenance
|
||||
"""
|
||||
code = str(getattr(agent, 'agent_code', '') or '').strip()
|
||||
name = str(getattr(agent, 'name', '') or '')
|
||||
profile = agent_content_profile(agent)
|
||||
if kind == 'entrance':
|
||||
return profile == 'generic_entrance'
|
||||
if kind == 'training':
|
||||
return profile == 'training'
|
||||
if kind == 'shipping':
|
||||
return code == 'shipping_notice'
|
||||
if kind == 'patent':
|
||||
return '专利' in name
|
||||
if kind == 'maintenance':
|
||||
return '维保' in name or '维修' in name or code == 'maintenance'
|
||||
return False
|
||||
|
||||
|
||||
def feature_visible_for_agents(feature: dict[str, Any], agents: list[Any]) -> bool:
|
||||
"""已选应用是否展示该应用内能力。"""
|
||||
bind = str(feature.get('bind') or '')
|
||||
if bind == 'always':
|
||||
return True
|
||||
if bind.startswith('content_profile:'):
|
||||
want = bind.split(':', 1)[1]
|
||||
return any(agent_content_profile(agent) == want for agent in agents)
|
||||
if bind.startswith('agent_code:'):
|
||||
want = bind.split(':', 1)[1]
|
||||
return any(str(getattr(agent, 'agent_code', '') or '') == want for agent in agents)
|
||||
if bind.startswith('kind:'):
|
||||
want = bind.split(':', 1)[1]
|
||||
return any(agent_matches_kind(agent, want) for agent in agents)
|
||||
return False
|
||||
@@ -0,0 +1,641 @@
|
||||
"""
|
||||
services/permission_roles/service.py
|
||||
|
||||
用途:权限组 CRUD、成员预览/确认调整、把角色包同步到 users.role 与 user_agent_permissions。
|
||||
依赖:PermissionRole、User、Agent、catalog。
|
||||
逻辑:由 api/admin/permission_roles 调用;用户创建/改角色时 sync_user_grants_from_role。
|
||||
排程种子/告警用 first_platform_admin_user 按 is_platform_admin join,不写死 role='admin'。
|
||||
未种子角色表时保持旧的按人勾选,避免单测全量改夹具。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any, Iterable
|
||||
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.models.permission_role import PermissionRole
|
||||
from app.services.permission_roles.catalog import (
|
||||
FEATURE_CATALOG,
|
||||
KNOWN_FEATURE_KEYS,
|
||||
agent_matches_kind,
|
||||
feature_visible_for_agents,
|
||||
)
|
||||
|
||||
_ROLE_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,62}$')
|
||||
PLATFORM_ADMIN_CODE = 'admin'
|
||||
|
||||
|
||||
def roles_configured() -> bool:
|
||||
"""库中是否已有权限组;无则走历史按人授权。"""
|
||||
return db.session.query(PermissionRole.id).first() is not None
|
||||
|
||||
|
||||
def assert_direct_grants_allowed() -> None:
|
||||
"""权限组启用后禁止按人改应用授权,须改角色包或调整成员。"""
|
||||
if roles_configured():
|
||||
raise ValidationError(
|
||||
'Direct agent grants are disabled; assign a permission role instead',
|
||||
code='ROLE.DIRECT_GRANT_DISABLED',
|
||||
)
|
||||
|
||||
|
||||
def get_role_by_code(code: str | None) -> PermissionRole | None:
|
||||
"""按 code 取权限组;不存在返回 None。"""
|
||||
value = str(code or '').strip()
|
||||
if not value:
|
||||
return None
|
||||
return db.session.query(PermissionRole).filter(PermissionRole.code == value).one_or_none()
|
||||
|
||||
|
||||
def get_default_role() -> PermissionRole | None:
|
||||
"""新建用户预填的默认权限组。"""
|
||||
return (
|
||||
db.session.query(PermissionRole)
|
||||
.filter(PermissionRole.is_default.is_(True))
|
||||
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def default_role_code() -> str:
|
||||
"""默认角色 code,未配置时回退 user。"""
|
||||
role = get_default_role()
|
||||
return role.code if role else 'user'
|
||||
|
||||
|
||||
def list_role_name_map() -> dict[str, str]:
|
||||
"""code → 显示名,供用户列表带出。"""
|
||||
rows = db.session.query(PermissionRole).all()
|
||||
return {row.code: row.name for row in rows}
|
||||
|
||||
|
||||
def _orm_session(sess: Any | None):
|
||||
"""排程种子 after_commit 可能传入独立 Session,查询必须落在同一会话。"""
|
||||
return sess if sess is not None else db.session
|
||||
|
||||
|
||||
def _permission_roles_exist(sess: Any) -> bool:
|
||||
"""当前会话里是否已有权限组行。"""
|
||||
return sess.query(PermissionRole.id).first() is not None
|
||||
|
||||
|
||||
def platform_admin_users_query(sess: Any | None = None):
|
||||
"""
|
||||
启用中的平台管理员查询。
|
||||
|
||||
核心逻辑:已种子权限组时 join is_platform_admin;否则回退 users.role=admin。
|
||||
"""
|
||||
session = _orm_session(sess)
|
||||
query = session.query(User)
|
||||
if _permission_roles_exist(session):
|
||||
query = query.join(PermissionRole, PermissionRole.code == User.role).filter(
|
||||
PermissionRole.is_platform_admin.is_(True),
|
||||
)
|
||||
else:
|
||||
query = query.filter(User.role == PLATFORM_ADMIN_CODE)
|
||||
return query.filter(User.status == 'active').order_by(User.id.asc())
|
||||
|
||||
|
||||
def first_platform_admin_user(sess: Any | None = None) -> User | None:
|
||||
"""
|
||||
取 id 最小的启用中平台管理员,供排程种子写 owner。
|
||||
|
||||
Args:
|
||||
sess: 可选独立 Session;缺省用 Flask-SQLAlchemy 会话。
|
||||
|
||||
Returns:
|
||||
找到则返回 User,否则 None。
|
||||
"""
|
||||
return platform_admin_users_query(sess).first()
|
||||
|
||||
|
||||
def list_platform_admin_users(
|
||||
sess: Any | None = None,
|
||||
*,
|
||||
wecom_bound: bool = False,
|
||||
limit: int | None = None,
|
||||
) -> list[User]:
|
||||
"""
|
||||
列出启用中的平台管理员。
|
||||
|
||||
核心逻辑:告警接收人可再筛已绑企微,并限制条数。
|
||||
|
||||
Args:
|
||||
sess: 可选独立 Session。
|
||||
wecom_bound: True 时只要 wecom_userid 非空。
|
||||
limit: 可选上限。
|
||||
|
||||
Returns:
|
||||
按 id 升序的用户列表。
|
||||
"""
|
||||
query = platform_admin_users_query(sess)
|
||||
if wecom_bound:
|
||||
query = query.filter(User.wecom_userid.isnot(None))
|
||||
if limit is not None:
|
||||
query = query.limit(int(limit))
|
||||
return query.all()
|
||||
|
||||
|
||||
def first_schedule_owner_user(sess: Any | None = None) -> User | None:
|
||||
"""
|
||||
排程种子 owner:优先平台管理员,否则任意用户。
|
||||
|
||||
核心逻辑:没有管理员时仍要能种平台 Job,与历史「没 admin 就拿 id 最小用户」一致。
|
||||
"""
|
||||
owner = first_platform_admin_user(sess)
|
||||
if owner is not None:
|
||||
return owner
|
||||
return _orm_session(sess).query(User).order_by(User.id.asc()).first()
|
||||
|
||||
|
||||
def user_is_platform_admin(user: User | None, sess: Any | None = None) -> bool:
|
||||
"""
|
||||
判断用户是否属于 is_platform_admin 权限组。
|
||||
|
||||
核心逻辑:已种子时按 users.role join permission_roles;否则回退 role=admin。
|
||||
同一 User 实例在一次请求内缓存结果,避免货代工作台重复查询。
|
||||
|
||||
Args:
|
||||
user: 当前用户;None 视为否。
|
||||
sess: 可选独立 Session。
|
||||
|
||||
Returns:
|
||||
True 表示平台管理员。
|
||||
"""
|
||||
if user is None:
|
||||
return False
|
||||
session = _orm_session(sess)
|
||||
role_code = str(getattr(user, 'role', '') or '').strip()
|
||||
cached = getattr(user, '_is_platform_admin_cached', None)
|
||||
if isinstance(cached, tuple) and len(cached) == 2 and cached[0] == role_code:
|
||||
return bool(cached[1])
|
||||
if not role_code:
|
||||
user._is_platform_admin_cached = (role_code, False)
|
||||
return False
|
||||
if _permission_roles_exist(session):
|
||||
role = (
|
||||
session.query(PermissionRole)
|
||||
.filter(PermissionRole.code == role_code)
|
||||
.one_or_none()
|
||||
)
|
||||
result = bool(role and role.is_platform_admin)
|
||||
else:
|
||||
result = role_code == PLATFORM_ADMIN_CODE
|
||||
user._is_platform_admin_cached = (role_code, result)
|
||||
return result
|
||||
|
||||
|
||||
def platform_admin_role_codes(sess: Any | None = None) -> list[str]:
|
||||
"""当前所有平台管理组的 code;未种子时回退 ['admin']。"""
|
||||
session = _orm_session(sess)
|
||||
if not _permission_roles_exist(session):
|
||||
return [PLATFORM_ADMIN_CODE]
|
||||
rows = (
|
||||
session.query(PermissionRole.code)
|
||||
.filter(PermissionRole.is_platform_admin.is_(True))
|
||||
.all()
|
||||
)
|
||||
return [str(row[0]) for row in rows if row[0]]
|
||||
|
||||
|
||||
def _normalize_feature_map(raw: Any) -> dict[str, bool]:
|
||||
source = raw if isinstance(raw, dict) else {}
|
||||
return {key: bool(source.get(key)) for key in KNOWN_FEATURE_KEYS if key in source}
|
||||
|
||||
|
||||
def effective_feature_permissions(user: User) -> dict[str, bool] | None:
|
||||
"""
|
||||
若已配置权限组,返回该用户角色包的有效功能权限;否则 None 表示走 User 旧默认值。
|
||||
"""
|
||||
if not roles_configured():
|
||||
return None
|
||||
role = get_role_by_code(user.role)
|
||||
stored = _normalize_feature_map(role.feature_permissions if role else {})
|
||||
if role and role.is_platform_admin:
|
||||
result = {key: True for key in KNOWN_FEATURE_KEYS}
|
||||
result.update(stored)
|
||||
return result
|
||||
result = {key: False for key in KNOWN_FEATURE_KEYS}
|
||||
result.update(stored)
|
||||
return result
|
||||
|
||||
|
||||
def sync_user_grants_from_role(user: User) -> None:
|
||||
"""
|
||||
按用户当前 role 重写 Agent 授权与个人功能覆盖。
|
||||
|
||||
核心逻辑:管理员不写 user_agent_permissions(入口隐式全开);
|
||||
其他角色用权限组勾选的 Agent 全量替换;个人 feature_permissions 清空,改由角色包计算。
|
||||
未配置权限组时不改。
|
||||
"""
|
||||
if not roles_configured():
|
||||
return
|
||||
role = get_role_by_code(user.role)
|
||||
if role is None:
|
||||
fallback = get_default_role()
|
||||
if fallback is None:
|
||||
return
|
||||
user.role = fallback.code
|
||||
role = fallback
|
||||
user.feature_permissions = {}
|
||||
if role.is_platform_admin:
|
||||
return
|
||||
user.agents = list(role.agents)
|
||||
|
||||
|
||||
def _count_members(code: str) -> int:
|
||||
return db.session.query(User).filter(User.role == code).count()
|
||||
|
||||
|
||||
def _serialize_role(role: PermissionRole, *, with_agents: bool = True) -> dict[str, Any]:
|
||||
agent_ids = [agent.id for agent in role.agents] if with_agents else []
|
||||
return {
|
||||
'id': role.id,
|
||||
'code': role.code,
|
||||
'name': role.name,
|
||||
'description': role.description or '',
|
||||
'is_default': bool(role.is_default),
|
||||
'is_system': bool(role.is_system),
|
||||
'is_platform_admin': bool(role.is_platform_admin),
|
||||
'sort_order': role.sort_order,
|
||||
'member_count': _count_members(role.code),
|
||||
'agent_ids': agent_ids,
|
||||
'agent_names': [agent.name for agent in role.agents] if with_agents else [],
|
||||
'feature_permissions': _normalize_feature_map(role.feature_permissions),
|
||||
}
|
||||
|
||||
|
||||
def list_roles() -> list[dict[str, Any]]:
|
||||
"""权限组列表(含人数与已选应用)。"""
|
||||
rows = (
|
||||
db.session.query(PermissionRole)
|
||||
.options(joinedload(PermissionRole.agents))
|
||||
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [_serialize_role(row) for row in rows]
|
||||
|
||||
|
||||
def get_role_detail(code: str) -> dict[str, Any]:
|
||||
"""单个权限组详情。"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
raise NotFoundError('Permission role not found', code='ROLE.NOT_FOUND')
|
||||
return _serialize_role(role)
|
||||
|
||||
|
||||
def grantable_catalog() -> dict[str, Any]:
|
||||
"""
|
||||
角色编辑可选应用与能力。
|
||||
|
||||
Returns:
|
||||
agents: 启用中的全部 Agent(含 description / conversation_mode);features: 能力目录(含 bind / hint)。
|
||||
"""
|
||||
agents = (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
items = []
|
||||
for agent in agents:
|
||||
handler = agent.handler_config if isinstance(agent.handler_config, dict) else {}
|
||||
items.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': str(agent.description or '').strip(),
|
||||
'agent_code': agent.agent_code,
|
||||
'content_profile': str(handler.get('content_profile') or ''),
|
||||
'conversation_mode': agent.conversation_mode,
|
||||
})
|
||||
return {
|
||||
'agents': items,
|
||||
'features': [
|
||||
{
|
||||
'key': item['key'],
|
||||
'bind': item['bind'],
|
||||
'name': item['name'],
|
||||
'hint': str(item.get('hint') or ''),
|
||||
}
|
||||
for item in FEATURE_CATALOG
|
||||
],
|
||||
'default_role_code': default_role_code(),
|
||||
}
|
||||
|
||||
|
||||
def _unset_other_defaults(keep_id: int | None) -> None:
|
||||
query = db.session.query(PermissionRole).filter(PermissionRole.is_default.is_(True))
|
||||
if keep_id is not None:
|
||||
query = query.filter(PermissionRole.id != keep_id)
|
||||
for row in query.all():
|
||||
row.is_default = False
|
||||
|
||||
|
||||
def _load_agents(agent_ids: Iterable[Any]) -> list[Agent]:
|
||||
ids = []
|
||||
for raw in agent_ids or []:
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if value > 0:
|
||||
ids.append(value)
|
||||
if not ids:
|
||||
return []
|
||||
return db.session.query(Agent).filter(Agent.id.in_(ids)).all()
|
||||
|
||||
|
||||
def _apply_package(role: PermissionRole, data: dict[str, Any], *, allow_agents: bool) -> None:
|
||||
if 'name' in data:
|
||||
name = str(data.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValidationError('Role name is required', code='ROLE.NAME_REQUIRED')
|
||||
role.name = name
|
||||
if 'description' in data:
|
||||
role.description = str(data.get('description') or '').strip() or None
|
||||
if 'sort_order' in data:
|
||||
try:
|
||||
role.sort_order = int(data.get('sort_order') or 0)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('Invalid sort_order', code='ROLE.SORT_INVALID')
|
||||
if data.get('is_default'):
|
||||
_unset_other_defaults(role.id)
|
||||
role.is_default = True
|
||||
elif 'is_default' in data:
|
||||
if role.is_default and not data.get('is_default'):
|
||||
raise ValidationError('Keep at least one default role', code='ROLE.DEFAULT_REQUIRED')
|
||||
role.is_default = False
|
||||
if 'feature_permissions' in data:
|
||||
role.feature_permissions = _normalize_feature_map(data.get('feature_permissions'))
|
||||
if allow_agents and 'agent_ids' in data:
|
||||
role.agents = _load_agents(data.get('agent_ids') or [])
|
||||
role.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
def _enabled_feature_keys(raw: Any) -> set[str]:
|
||||
return {key for key, enabled in _normalize_feature_map(raw).items() if enabled}
|
||||
|
||||
|
||||
def _incoming_agent_ids(raw: Any) -> set[int]:
|
||||
ids: set[int] = set()
|
||||
for item in raw or []:
|
||||
try:
|
||||
value = int(item)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if value > 0:
|
||||
ids.add(value)
|
||||
return ids
|
||||
|
||||
|
||||
def _grants_changed(role: PermissionRole, data: dict[str, Any], *, allow_agents: bool) -> bool:
|
||||
"""应用勾选或已打开的能力是否相对当前角色包有变化。"""
|
||||
if allow_agents and 'agent_ids' in data:
|
||||
current = {agent.id for agent in role.agents}
|
||||
if _incoming_agent_ids(data.get('agent_ids')) != current:
|
||||
return True
|
||||
if 'feature_permissions' in data:
|
||||
if _enabled_feature_keys(data.get('feature_permissions')) != _enabled_feature_keys(role.feature_permissions):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def create_role(data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""新建权限组。"""
|
||||
code = str(data.get('code') or '').strip().lower()
|
||||
if not _ROLE_CODE_RE.match(code):
|
||||
raise ValidationError('Invalid role code', code='ROLE.CODE_INVALID')
|
||||
if code == PLATFORM_ADMIN_CODE:
|
||||
raise ValidationError('Cannot create another platform admin role', code='ROLE.CODE_RESERVED')
|
||||
if get_role_by_code(code):
|
||||
raise ConflictError('Role code already exists', code='ROLE.CODE_EXISTS')
|
||||
name = str(data.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValidationError('Role name is required', code='ROLE.NAME_REQUIRED')
|
||||
role = PermissionRole(
|
||||
code=code,
|
||||
name=name,
|
||||
description=str(data.get('description') or '').strip() or None,
|
||||
is_default=False,
|
||||
is_system=False,
|
||||
is_platform_admin=False,
|
||||
sort_order=int(data.get('sort_order') or 100),
|
||||
feature_permissions={},
|
||||
)
|
||||
db.session.add(role)
|
||||
db.session.flush()
|
||||
_apply_package(role, data, allow_agents=True)
|
||||
db.session.commit()
|
||||
return {'id': role.id, 'code': role.code}
|
||||
|
||||
|
||||
def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
保存权限组。仅当应用勾选或能力开关变化时,才同步该组用户的应用授权。
|
||||
|
||||
管理员不可改应用入口勾选。只改名称/说明不重写成员权限。
|
||||
"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
raise NotFoundError('Permission role not found', code='ROLE.NOT_FOUND')
|
||||
allow_agents = not role.is_platform_admin
|
||||
grants_changed = _grants_changed(role, data, allow_agents=allow_agents)
|
||||
_apply_package(role, data, allow_agents=allow_agents)
|
||||
users = db.session.query(User).filter(User.role == role.code).all() if grants_changed else []
|
||||
for user in users:
|
||||
sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'synced_users': len(users)}
|
||||
|
||||
|
||||
def delete_role(code: str) -> dict[str, Any]:
|
||||
"""删除非内置且无人使用的权限组。"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
raise NotFoundError('Permission role not found', code='ROLE.NOT_FOUND')
|
||||
if role.is_system or role.is_platform_admin:
|
||||
raise ForbiddenError('System role cannot be deleted', code='ROLE.SYSTEM_LOCKED')
|
||||
if _count_members(role.code):
|
||||
raise ConflictError('Role still has members', code='ROLE.HAS_MEMBERS')
|
||||
if role.is_default:
|
||||
raise ValidationError('Cannot delete the default role', code='ROLE.DEFAULT_REQUIRED')
|
||||
db.session.delete(role)
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def _person_payload(user: User, role_names: dict[str, str]) -> dict[str, Any]:
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'role_name': role_names.get(user.role) or user.role,
|
||||
'wecom_bound': bool(user.wecom_userid),
|
||||
}
|
||||
|
||||
|
||||
def list_picker_people() -> list[dict[str, Any]]:
|
||||
"""选人弹窗候选人:启用用户且排除平台管理员。"""
|
||||
role_names = list_role_name_map()
|
||||
query = db.session.query(User).filter(User.status == 'active')
|
||||
admin_codes = platform_admin_role_codes()
|
||||
if admin_codes:
|
||||
query = query.filter(User.role.notin_(admin_codes))
|
||||
users = query.order_by(User.id.asc()).all()
|
||||
return [_person_payload(user, role_names) for user in users]
|
||||
|
||||
|
||||
def _normalize_selected_ids(raw: Any) -> list[int]:
|
||||
seen: set[int] = set()
|
||||
result: list[int] = []
|
||||
for item in raw or []:
|
||||
try:
|
||||
value = int(item)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if value <= 0 or value in seen:
|
||||
continue
|
||||
seen.add(value)
|
||||
result.append(value)
|
||||
return result
|
||||
|
||||
|
||||
def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||
"""
|
||||
计算勾选草稿相对当前成员的增减,供确认框展示来源角色。
|
||||
"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
raise NotFoundError('Permission role not found', code='ROLE.NOT_FOUND')
|
||||
if role.is_platform_admin:
|
||||
raise ForbiddenError('Platform admin members cannot be changed here', code='ROLE.ADMIN_LOCKED')
|
||||
default_code = default_role_code()
|
||||
selected = set(_normalize_selected_ids(selected_ids))
|
||||
current_members = (
|
||||
db.session.query(User)
|
||||
.filter(User.role == role.code)
|
||||
.filter(User.status == 'active')
|
||||
.all()
|
||||
)
|
||||
current_ids = {user.id for user in current_members}
|
||||
added_ids = [item for item in selected if item not in current_ids]
|
||||
removed_ids = [item for item in current_ids if item not in selected]
|
||||
if role.code == default_code:
|
||||
removed_ids = []
|
||||
users_by_id = {
|
||||
user.id: user
|
||||
for user in db.session.query(User).filter(User.id.in_(added_ids + removed_ids)).all()
|
||||
} if added_ids or removed_ids else {}
|
||||
role_names = list_role_name_map()
|
||||
|
||||
def _rows(ids: list[int]) -> list[dict[str, Any]]:
|
||||
rows = []
|
||||
for user_id in ids:
|
||||
user = users_by_id.get(user_id)
|
||||
if not user or user_is_platform_admin(user):
|
||||
continue
|
||||
rows.append(_person_payload(user, role_names))
|
||||
return rows
|
||||
|
||||
added = _rows(added_ids)
|
||||
removed = _rows(removed_ids)
|
||||
stolen = [row for row in added if row['role'] not in {default_code, role.code}]
|
||||
return {
|
||||
'role_code': role.code,
|
||||
'role_name': role.name,
|
||||
'default_role_code': default_code,
|
||||
'added': added,
|
||||
'removed': removed,
|
||||
'stolen': stolen,
|
||||
'ignored_admin': 0,
|
||||
}
|
||||
|
||||
|
||||
def apply_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||
"""
|
||||
确认后写回成员:勾选的人改入本角色;取消勾选的人回到默认角色。
|
||||
排除管理员;默认角色忽略移出。
|
||||
"""
|
||||
preview = preview_role_members(code, selected_ids)
|
||||
role = get_role_by_code(code)
|
||||
default_code = preview['default_role_code']
|
||||
skipped_admin = 0
|
||||
for row in preview['added']:
|
||||
user = db.session.get(User, row['id'])
|
||||
if not user or user_is_platform_admin(user):
|
||||
skipped_admin += 1
|
||||
continue
|
||||
user.role = role.code
|
||||
sync_user_grants_from_role(user)
|
||||
for row in preview['removed']:
|
||||
user = db.session.get(User, row['id'])
|
||||
if not user or user_is_platform_admin(user):
|
||||
skipped_admin += 1
|
||||
continue
|
||||
user.role = default_code
|
||||
sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'ok',
|
||||
'added': len(preview['added']),
|
||||
'removed': len(preview['removed']),
|
||||
'skipped_admin': skipped_admin,
|
||||
}
|
||||
|
||||
|
||||
def assert_role_assignable(code: str | None, *, allow_admin: bool) -> str:
|
||||
"""
|
||||
校验将要写入 users.role 的 code。
|
||||
|
||||
Args:
|
||||
allow_admin: 用户编辑表单可为 True;选人弹窗必须 False。
|
||||
"""
|
||||
value = str(code or '').strip()
|
||||
if not value:
|
||||
raise ValidationError('Role is required', code='ROLE.REQUIRED')
|
||||
if not roles_configured():
|
||||
return value
|
||||
role = get_role_by_code(value)
|
||||
if not role:
|
||||
raise ValidationError('Unknown role', code='ROLE.NOT_FOUND')
|
||||
if role.is_platform_admin and not allow_admin:
|
||||
raise ForbiddenError('Platform admin cannot be assigned here', code='ROLE.ADMIN_LOCKED')
|
||||
return role.code
|
||||
|
||||
|
||||
def ensure_not_last_admin(user: User, new_role: str) -> None:
|
||||
"""禁止撤掉最后一名启用中的平台管理员。"""
|
||||
if not user_is_platform_admin(user):
|
||||
return
|
||||
incoming = get_role_by_code(new_role)
|
||||
if incoming and incoming.is_platform_admin:
|
||||
return
|
||||
if not roles_configured() and new_role == PLATFORM_ADMIN_CODE:
|
||||
return
|
||||
others = platform_admin_users_query().filter(User.id != user.id).first()
|
||||
if others is None:
|
||||
raise ValidationError('Cannot demote the last platform admin', code='ROLE.LAST_ADMIN')
|
||||
|
||||
|
||||
def visible_features_for_role(role: PermissionRole) -> list[str]:
|
||||
"""当前角色已选应用下应展示的能力键。"""
|
||||
keys = []
|
||||
for item in FEATURE_CATALOG:
|
||||
if feature_visible_for_agents(item, list(role.agents)):
|
||||
keys.append(item['key'])
|
||||
return keys
|
||||
|
||||
|
||||
def match_seed_agent_ids(kind: str) -> list[int]:
|
||||
"""迁移种子:按 catalog 规则找出启用 Agent id。"""
|
||||
agents = db.session.query(Agent).filter(Agent.is_active.is_(True)).all()
|
||||
return [agent.id for agent in agents if agent_matches_kind(agent, kind)]
|
||||
@@ -721,8 +721,6 @@ def can_force_create_shipping_duplicate(user: User | None) -> bool:
|
||||
"""判断用户是否可强制新建重复发货通知。"""
|
||||
if user is None:
|
||||
return False
|
||||
if str(getattr(user, 'role', '') or '') == 'admin':
|
||||
return True
|
||||
return bool(user.has_feature_permission('shipping_notice_force_create'))
|
||||
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ def _resolve_cancellation_operation_id(run: ShippingOrderProcessingRun, explicit
|
||||
|
||||
def _is_admin(actor: User) -> bool:
|
||||
"""判断操作者是否具备管理员取消权限。"""
|
||||
return str(getattr(actor, 'role', '') or '') == 'admin'
|
||||
return bool(actor.is_platform_admin())
|
||||
|
||||
|
||||
def _lock_run_for_actor(*, actor: User, run_no: str) -> ShippingOrderProcessingRun:
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
"""确保订单识别进度事件清理的每日默认排程存在。"""
|
||||
"""
|
||||
services/shipping_notice/order_extraction_progress_cleanup_schedule.py
|
||||
|
||||
用途:确保订单识别进度事件清理的每日默认排程存在。
|
||||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||
逻辑:无用户时跳过;owner 优先平台管理员。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
@@ -6,7 +12,8 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.models import ScheduleTask
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -24,7 +31,7 @@ def ensure_default_order_extraction_progress_cleanup_schedule(*, commit: bool =
|
||||
).first()
|
||||
if existing is not None:
|
||||
return existing
|
||||
owner = sess.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or sess.query(User).order_by(User.id.asc()).first()
|
||||
owner = first_schedule_owner_user(sess)
|
||||
if owner is None:
|
||||
_LOGGER.info('skip seed order-extraction progress cleanup schedule: no users yet')
|
||||
return None
|
||||
|
||||
@@ -154,7 +154,7 @@ def save_quality_label(*, batch_id: int, run_no: str, actor_id: int, payload: An
|
||||
if batch is None:
|
||||
raise NotFoundError('Quality batch not found')
|
||||
actor = db.session.get(User, actor_id)
|
||||
if actor is None or actor.role != 'admin':
|
||||
if actor is None or not actor.is_platform_admin():
|
||||
raise ValidationError('Quality reviewer must be an administrator')
|
||||
if (
|
||||
batch.status in {'approved', 'rejected'}
|
||||
@@ -215,7 +215,7 @@ def approve_quality_batch(*, batch_id: int, role: str, actor_id: int) -> Shippin
|
||||
if batch.status == 'rejected':
|
||||
raise ConflictError('Quality batch was rejected')
|
||||
actor = db.session.get(User, actor_id)
|
||||
if actor is None or actor.role != 'admin':
|
||||
if actor is None or not actor.is_platform_admin():
|
||||
raise ValidationError('Quality approver must be an administrator')
|
||||
if not quality_metrics(batch)['eligible']:
|
||||
raise ConflictError(
|
||||
|
||||
@@ -562,7 +562,7 @@ def _require_owner_agent(*, user: User, agent_id: int) -> Agent:
|
||||
'agent_id must reference an active shipping notice agent',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID',
|
||||
)
|
||||
if str(user.role or '').lower() != 'admin' and agent not in user.agents:
|
||||
if not user.is_platform_admin() and agent not in user.agents:
|
||||
raise ForbiddenError(
|
||||
'Permission denied for this agent',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_FORBIDDEN',
|
||||
|
||||
@@ -35,7 +35,7 @@ def is_shipping_admin(user: User) -> bool:
|
||||
Returns:
|
||||
True 表示管理员。
|
||||
"""
|
||||
return str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
return bool(user.is_platform_admin())
|
||||
|
||||
|
||||
def resolve_execution_owner_user_ids(execution: ShippingProcessExecution) -> set[int]:
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
|
||||
|
||||
def _is_admin(user: User) -> bool:
|
||||
"""判断用户是否为收料报表管理角色。"""
|
||||
return str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
return bool(user.is_platform_admin())
|
||||
|
||||
|
||||
def can_download_receipt_report_file(report_file: ShippingReceiptReportFile, user: User) -> bool:
|
||||
|
||||
@@ -20,6 +20,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import AppSetting, User
|
||||
from app.services.permission_roles.service import list_platform_admin_users
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
@@ -65,7 +66,7 @@ def _alert_fallback_admin_enabled() -> bool:
|
||||
def _alert_recipients() -> list[User]:
|
||||
"""
|
||||
解析告警接收人。
|
||||
核心逻辑:优先 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。
|
||||
核心逻辑:优先 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的平台管理员。
|
||||
"""
|
||||
raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES") or "").strip()
|
||||
names = [part.strip() for part in raw.split(",") if part.strip()] if raw else []
|
||||
@@ -82,13 +83,7 @@ def _alert_recipients() -> list[User]:
|
||||
names,
|
||||
)
|
||||
if _alert_fallback_admin_enabled():
|
||||
admins = (
|
||||
db.session.query(User)
|
||||
.filter(User.role == "admin", User.wecom_userid.isnot(None))
|
||||
.order_by(User.id.asc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
admins = list_platform_admin_users(wecom_bound=True, limit=20)
|
||||
if admins:
|
||||
logger.info(
|
||||
"[rpa-heartbeat-alert] using admin fallback recipients count=%d",
|
||||
@@ -106,7 +101,7 @@ def _log_recipient_gap_once() -> None:
|
||||
_RECIPIENT_GAP_LOGGED = True
|
||||
logger.warning(
|
||||
"[rpa-heartbeat-alert] no wecom recipients: set SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES "
|
||||
"or bind wecom_userid for at least one admin (FALLBACK_ADMIN=true)"
|
||||
"or bind wecom_userid for at least one platform admin (FALLBACK_ADMIN=true)"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/voucher_check/schedule_seed.py
|
||||
|
||||
用途:确保立账凭证检核(周二 06:00)与 PO 订单生成(周二 05:00)默认 ScheduleTask 存在。
|
||||
依赖:ScheduleTask/User、timezone_util、voucher_check.config。
|
||||
依赖:ScheduleTask/User、permission_roles.service.first_schedule_owner_user、timezone_util、voucher_check.config。
|
||||
逻辑:迁移种子 + create_app / User after_commit 幂等补建;检核排程剥离 schema 外的旧 job_params。
|
||||
"""
|
||||
|
||||
@@ -18,6 +18,7 @@ from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_PO_PRINT_JOB_PARAMS
|
||||
|
||||
@@ -107,14 +108,7 @@ def ensure_default_voucher_check_schedule(
|
||||
sess.commit()
|
||||
return existing
|
||||
|
||||
owner = (
|
||||
sess.query(User)
|
||||
.filter(User.role == "admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if owner is None:
|
||||
owner = sess.query(User).order_by(User.id.asc()).first()
|
||||
owner = _pick_schedule_owner(sess)
|
||||
if owner is None:
|
||||
_LOGGER.info("skip seed accounting-voucher-check schedule: no users yet")
|
||||
return None
|
||||
@@ -169,16 +163,8 @@ def ensure_default_voucher_check_schedule(
|
||||
|
||||
|
||||
def _pick_schedule_owner(sess: Any) -> Any | None:
|
||||
"""优先管理员,否则任意用户;尚无用户时返回 None。"""
|
||||
owner = (
|
||||
sess.query(User)
|
||||
.filter(User.role == "admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if owner is None:
|
||||
owner = sess.query(User).order_by(User.id.asc()).first()
|
||||
return owner
|
||||
"""优先平台管理员,否则任意用户;尚无用户时返回 None。"""
|
||||
return first_schedule_owner_user(sess)
|
||||
|
||||
|
||||
def ensure_default_voucher_po_print_schedule(
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
"""Seed configurable permission roles.
|
||||
|
||||
Revision ID: pr7b8c9d0e1f
|
||||
Revises: vc6a7b8c9d0e
|
||||
Create Date: 2026-09-17 13:30:00.000000
|
||||
|
||||
用途:新增 permission_roles / permission_role_agents;按现网 users.role 套标准包并重写授权。
|
||||
依赖:users、agents、user_agent_permissions。
|
||||
逻辑:user/hr/admin 映射内置组,另种子研发应用与货代专员;个人勾选的额外应用按确认策略丢弃。
|
||||
不再种子设备维保专员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import inspect
|
||||
|
||||
|
||||
revision = "pr7b8c9d0e1f"
|
||||
down_revision = "vc6a7b8c9d0e"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
KNOWN_FEATURES = (
|
||||
"training_hr_manage",
|
||||
"shipping_notice_force_create",
|
||||
"shipping_notice.audit_sensitive_read",
|
||||
"shipping_notice.xfa_split_rule_edit",
|
||||
"shipping_notice.xfa_split_rule_preview",
|
||||
"shipping_notice.xfa_split_rule_publish",
|
||||
"maintenance.ledger_write",
|
||||
)
|
||||
|
||||
|
||||
def _content_profile(handler_config) -> str:
|
||||
raw = handler_config
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except Exception:
|
||||
raw = {}
|
||||
if not isinstance(raw, dict):
|
||||
return ""
|
||||
return str(raw.get("content_profile") or "").strip()
|
||||
|
||||
|
||||
def _matches(kind: str, agent_code: str, name: str, profile: str) -> bool:
|
||||
code = str(agent_code or "").strip()
|
||||
label = str(name or "")
|
||||
if kind == "entrance":
|
||||
return profile == "generic_entrance"
|
||||
if kind == "training":
|
||||
return profile == "training"
|
||||
if kind == "shipping":
|
||||
return code == "shipping_notice"
|
||||
if kind == "patent":
|
||||
return "专利" in label
|
||||
if kind == "maintenance":
|
||||
return "维保" in label or "维修" in label or code == "maintenance"
|
||||
return False
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""建表、加宽 users.role、种子权限组并按角色重写 user_agent_permissions。"""
|
||||
bind = op.get_bind()
|
||||
inspector = inspect(bind)
|
||||
tables = inspector.get_table_names()
|
||||
|
||||
if "permission_roles" not in tables:
|
||||
op.create_table(
|
||||
"permission_roles",
|
||||
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column("code", sa.String(length=64), nullable=False),
|
||||
sa.Column("name", sa.String(length=100), nullable=False),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("is_default", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("is_system", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("is_platform_admin", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("feature_permissions", sa.JSON(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint("code", name="uq_permission_roles_code"),
|
||||
)
|
||||
op.create_index("ix_permission_roles_code", "permission_roles", ["code"])
|
||||
|
||||
if "permission_role_agents" not in tables:
|
||||
op.create_table(
|
||||
"permission_role_agents",
|
||||
sa.Column("role_id", sa.Integer(), sa.ForeignKey("permission_roles.id", ondelete="CASCADE"), primary_key=True),
|
||||
sa.Column("agent_id", sa.Integer(), sa.ForeignKey("agents.id", ondelete="CASCADE"), primary_key=True),
|
||||
)
|
||||
|
||||
user_columns = {col["name"]: col for col in inspector.get_columns("users")}
|
||||
role_col = user_columns.get("role")
|
||||
if role_col is not None:
|
||||
op.alter_column(
|
||||
"users",
|
||||
"role",
|
||||
existing_type=role_col["type"],
|
||||
type_=sa.String(length=64),
|
||||
existing_nullable=True,
|
||||
)
|
||||
|
||||
now = datetime.utcnow()
|
||||
roles = bind.execute(sa.text("SELECT code FROM permission_roles")).fetchall()
|
||||
existing = {row[0] for row in roles}
|
||||
|
||||
seeds = [
|
||||
("user", "普通用户", "新建用户默认。勾通用入口即可使用企业知识库。", True, True, False, 10, {}, ("entrance",)),
|
||||
("rd", "研发人员", "通用入口,以及研发侧应用(如专利)。", False, False, False, 20, {}, ("entrance", "patent")),
|
||||
("hr", "培训 HR", "可进员工培训,并打开 HR 管理。", False, True, False, 30, {"training_hr_manage": True}, ("entrance", "training")),
|
||||
("shipping", "货代专员", "聊天与工作台共用货代应用入口。", False, False, False, 40, {"shipping_notice_force_create": True}, ("entrance", "shipping")),
|
||||
("admin", "管理员", "内置角色。应用入口隐式全开,可进入 /admin。", False, True, True, 90, {key: True for key in KNOWN_FEATURES}, ()),
|
||||
]
|
||||
|
||||
insert_role = sa.text(
|
||||
"""
|
||||
INSERT INTO permission_roles
|
||||
(code, name, description, is_default, is_system, is_platform_admin, sort_order, feature_permissions, created_at, updated_at)
|
||||
VALUES
|
||||
(:code, :name, :description, :is_default, :is_system, :is_platform_admin, :sort_order, :feature_permissions, :created_at, :updated_at)
|
||||
"""
|
||||
).bindparams(sa.bindparam("feature_permissions", type_=sa.JSON()))
|
||||
for code, name, desc, is_default, is_system, is_admin, sort_order, features, _match in seeds:
|
||||
if code in existing:
|
||||
continue
|
||||
bind.execute(
|
||||
insert_role,
|
||||
{
|
||||
"code": code,
|
||||
"name": name,
|
||||
"description": desc,
|
||||
"is_default": is_default,
|
||||
"is_system": is_system,
|
||||
"is_platform_admin": is_admin,
|
||||
"sort_order": sort_order,
|
||||
"feature_permissions": features,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
},
|
||||
)
|
||||
|
||||
role_id_rows = bind.execute(sa.text("SELECT id, code FROM permission_roles")).fetchall()
|
||||
role_ids = {row[1]: row[0] for row in role_id_rows}
|
||||
|
||||
agents = bind.execute(
|
||||
sa.text("SELECT id, name, agent_code, handler_config, is_active FROM agents")
|
||||
).fetchall()
|
||||
active = [row for row in agents if bool(row[4])]
|
||||
|
||||
def ids_for(*kinds: str) -> list[int]:
|
||||
found: list[int] = []
|
||||
for row in active:
|
||||
profile = _content_profile(row[3])
|
||||
for kind in kinds:
|
||||
if _matches(kind, row[2], row[1], profile):
|
||||
found.append(int(row[0]))
|
||||
break
|
||||
return found
|
||||
|
||||
match_map = {
|
||||
"user": ("entrance",),
|
||||
"rd": ("entrance", "patent"),
|
||||
"hr": ("entrance", "training"),
|
||||
"shipping": ("entrance", "shipping"),
|
||||
"admin": (),
|
||||
}
|
||||
existing_links = {
|
||||
(int(row[0]), int(row[1]))
|
||||
for row in bind.execute(sa.text("SELECT role_id, agent_id FROM permission_role_agents")).fetchall()
|
||||
}
|
||||
insert_link = sa.text(
|
||||
"INSERT INTO permission_role_agents (role_id, agent_id) VALUES (:role_id, :agent_id)"
|
||||
)
|
||||
for code, kinds in match_map.items():
|
||||
role_id = role_ids.get(code)
|
||||
if not role_id:
|
||||
continue
|
||||
for agent_id in ids_for(*kinds):
|
||||
pair = (int(role_id), int(agent_id))
|
||||
if pair in existing_links:
|
||||
continue
|
||||
bind.execute(insert_link, {"role_id": role_id, "agent_id": agent_id})
|
||||
existing_links.add(pair)
|
||||
|
||||
# 未知 role(含已废弃的 maintenance_manager)收口到默认普通用户。
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE users
|
||||
SET role = 'user'
|
||||
WHERE role IS NULL OR role NOT IN ('user', 'hr', 'admin', 'rd', 'shipping')
|
||||
"""
|
||||
)
|
||||
)
|
||||
empty_json = sa.text("UPDATE users SET feature_permissions = :empty").bindparams(
|
||||
sa.bindparam("empty", type_=sa.JSON())
|
||||
)
|
||||
bind.execute(empty_json, {"empty": {}})
|
||||
|
||||
# 非管理员:用角色包全量替换个人 Agent 勾选。
|
||||
bind.execute(sa.text(
|
||||
"""
|
||||
DELETE FROM user_agent_permissions
|
||||
WHERE user_id IN (SELECT id FROM users WHERE role <> 'admin')
|
||||
"""
|
||||
))
|
||||
bind.execute(sa.text(
|
||||
"""
|
||||
INSERT INTO user_agent_permissions (user_id, agent_id)
|
||||
SELECT u.id, pra.agent_id
|
||||
FROM users u
|
||||
JOIN permission_roles pr ON pr.code = u.role
|
||||
JOIN permission_role_agents pra ON pra.role_id = pr.id
|
||||
WHERE u.role <> 'admin'
|
||||
"""
|
||||
))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除权限组表;不回写已丢弃的个人 Agent 勾选。"""
|
||||
op.drop_table("permission_role_agents")
|
||||
op.drop_index("ix_permission_roles_code", table_name="permission_roles")
|
||||
op.drop_table("permission_roles")
|
||||
op.alter_column(
|
||||
"users",
|
||||
"role",
|
||||
existing_type=sa.String(length=64),
|
||||
type_=sa.String(length=20),
|
||||
existing_nullable=True,
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""合并权限组种子与客户 ODM 两条 Alembic 头。
|
||||
|
||||
用途:``pr7b8c9d0e1f``(权限组种子)与 ``dd22ee33ff44``(ODM × 凭证通知配置 merge)
|
||||
并列成双 head,导致 ``flask db upgrade`` 无法解析默认 ``head``。
|
||||
依赖:``pr7b8c9d0e1f``(permission_roles 种子)、
|
||||
``dd22ee33ff44``(aa11bb22cc33 × vc6a7b8c9d0e 图合并)。
|
||||
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
|
||||
|
||||
Revision ID: pr8c9d0e1f20
|
||||
Revises: dd22ee33ff44, pr7b8c9d0e1f
|
||||
Create Date: 2026-09-18 00:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||
|
||||
|
||||
revision = "pr8c9d0e1f20"
|
||||
down_revision = ("dd22ee33ff44", "pr7b8c9d0e1f")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并权限组种子与 ODM merge 节点,不执行数据库结构变更。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
|
||||
pass
|
||||
@@ -0,0 +1,465 @@
|
||||
"""
|
||||
tests/test_permission_roles.py
|
||||
|
||||
用途:可配置权限组种子路径:角色包同步、成员确认、禁止按人授权、最后一名管理员、平台管理员查询。
|
||||
依赖:PermissionRole、User、Agent、permission_roles.service、user_service、permission_service。
|
||||
逻辑:未种子时旧测试仍走按人授权;本文件显式写入权限组后断言新路径。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ForbiddenError, ValidationError
|
||||
from app.models import Agent, PermissionRequest, User
|
||||
from app.models.permission_role import PermissionRole
|
||||
from app.services.admin import permission_service, user_service
|
||||
from app.services.permission_roles import service as role_service
|
||||
|
||||
|
||||
def _agent(name: str, *, profile: str = '', code: str = 'generic') -> Agent:
|
||||
return Agent(
|
||||
name=name,
|
||||
type='api',
|
||||
dify_app_id=f'app-{name}',
|
||||
dify_api_key=f'key-{name}',
|
||||
is_active=True,
|
||||
agent_code=code,
|
||||
handler_config={'content_profile': profile} if profile else {},
|
||||
)
|
||||
|
||||
|
||||
def _user(username: str, role: str = 'user', *, status: str = 'active') -> User:
|
||||
return User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role=role,
|
||||
status=status,
|
||||
real_name=username,
|
||||
employee_id=f'E-{username}',
|
||||
phone_number=f'138{abs(hash(username)) % 10_000_000:07d}',
|
||||
)
|
||||
|
||||
|
||||
def _seed_standard_roles(entrance: Agent, training: Agent | None = None) -> dict[str, PermissionRole]:
|
||||
"""写入默认普通用户 / 培训 HR / 管理员,供断言角色包路径。"""
|
||||
user_role = PermissionRole(
|
||||
code='user',
|
||||
name='普通用户',
|
||||
is_default=True,
|
||||
is_system=True,
|
||||
is_platform_admin=False,
|
||||
sort_order=10,
|
||||
feature_permissions={},
|
||||
)
|
||||
user_role.agents = [entrance]
|
||||
hr_role = PermissionRole(
|
||||
code='hr',
|
||||
name='培训 HR',
|
||||
is_default=False,
|
||||
is_system=True,
|
||||
is_platform_admin=False,
|
||||
sort_order=30,
|
||||
feature_permissions={'training_hr_manage': True},
|
||||
)
|
||||
hr_role.agents = [entrance] + ([training] if training else [])
|
||||
admin_role = PermissionRole(
|
||||
code='admin',
|
||||
name='管理员',
|
||||
is_default=False,
|
||||
is_system=True,
|
||||
is_platform_admin=True,
|
||||
sort_order=90,
|
||||
feature_permissions={'training_hr_manage': True},
|
||||
)
|
||||
db.session.add_all([user_role, hr_role, admin_role])
|
||||
db.session.flush()
|
||||
return {'user': user_role, 'hr': hr_role, 'admin': admin_role}
|
||||
|
||||
|
||||
def test_roles_configured_false_without_seed(app):
|
||||
with app.app_context():
|
||||
assert role_service.roles_configured() is False
|
||||
|
||||
|
||||
def test_sync_user_grants_from_role(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('entrance', profile='generic_entrance')
|
||||
extra = _agent('extra')
|
||||
db.session.add_all([entrance, extra])
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
user = _user('role-pkg-user')
|
||||
user.agents = [extra]
|
||||
user.feature_permissions = {'training_hr_manage': True}
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
# 断言:个人额外应用被角色包替换为通用入口;功能覆盖清空。
|
||||
assert [agent.id for agent in user.agents] == [entrance.id]
|
||||
assert user.feature_permissions == {}
|
||||
assert user.get_feature_permissions()['training_hr_manage'] is False
|
||||
|
||||
|
||||
def test_hr_role_enables_training_feature(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-hr', profile='generic_entrance')
|
||||
training = _agent('train-hr', profile='training')
|
||||
db.session.add_all([entrance, training])
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance, training)
|
||||
user = _user('hr-pkg-user', role='hr')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
perms = user.get_feature_permissions()
|
||||
assert perms['training_hr_manage'] is True
|
||||
assert {agent.id for agent in user.agents} == {entrance.id, training.id}
|
||||
|
||||
|
||||
def test_platform_admin_skips_agent_rows_and_grants_features(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-admin', profile='generic_entrance')
|
||||
db.session.add(entrance)
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
admin = _user('pkg-admin', role='admin')
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
role_service.sync_user_grants_from_role(admin)
|
||||
db.session.commit()
|
||||
db.session.refresh(admin)
|
||||
# 断言:管理员不写 user_agent_permissions,功能键全部为真。
|
||||
assert admin.agents == []
|
||||
assert admin.get_feature_permissions()['training_hr_manage'] is True
|
||||
assert admin.get_feature_permissions()['maintenance.ledger_write'] is True
|
||||
|
||||
|
||||
def test_direct_grants_disabled_when_roles_configured(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-direct', profile='generic_entrance')
|
||||
user = _user('direct-user')
|
||||
db.session.add_all([entrance, user])
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
permission_service.update_user_permissions(user.id, {'agent_ids': [entrance.id]})
|
||||
assert exc.value.code == 'ROLE.DIRECT_GRANT_DISABLED'
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
permission_service.batch_update_permissions(
|
||||
{'user_ids': [user.id], 'agent_ids': [entrance.id], 'action': 'add'},
|
||||
)
|
||||
assert exc.value.code == 'ROLE.DIRECT_GRANT_DISABLED'
|
||||
|
||||
|
||||
def test_approve_permission_request_disabled(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-req', profile='generic_entrance')
|
||||
user = _user('req-pkg-user')
|
||||
db.session.add_all([entrance, user])
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
req = PermissionRequest(user_id=user.id, agent_id=entrance.id, reason='need', status='pending')
|
||||
db.session.add(req)
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
permission_service.approve_permission_request(req.id)
|
||||
assert exc.value.code == 'ROLE.DIRECT_GRANT_DISABLED'
|
||||
|
||||
|
||||
def test_preview_and_apply_role_members(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-mem', profile='generic_entrance')
|
||||
training = _agent('train-mem', profile='training')
|
||||
db.session.add_all([entrance, training])
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance, training)
|
||||
staff = _user('mem-staff', role='user')
|
||||
other = _user('mem-other', role='user')
|
||||
admin = _user('mem-admin', role='admin')
|
||||
db.session.add_all([staff, other, admin])
|
||||
db.session.commit()
|
||||
|
||||
preview = role_service.preview_role_members('hr', [staff.id, admin.id])
|
||||
# 断言:管理员被忽略;从默认角色改入不算「抢走」。
|
||||
assert [row['id'] for row in preview['added']] == [staff.id]
|
||||
assert preview['stolen'] == []
|
||||
assert preview['removed'] == []
|
||||
|
||||
result = role_service.apply_role_members('hr', [staff.id, admin.id])
|
||||
assert result['added'] == 1
|
||||
db.session.refresh(staff)
|
||||
db.session.refresh(admin)
|
||||
assert staff.role == 'hr'
|
||||
assert {agent.id for agent in staff.agents} == {entrance.id, training.id}
|
||||
assert admin.role == 'admin'
|
||||
|
||||
steal_preview = role_service.preview_role_members('user', [other.id, staff.id])
|
||||
assert [row['id'] for row in steal_preview['stolen']] == [staff.id]
|
||||
|
||||
|
||||
def test_default_role_ignores_removal(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-def', profile='generic_entrance')
|
||||
db.session.add(entrance)
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
staff = _user('def-staff', role='user')
|
||||
db.session.add(staff)
|
||||
db.session.commit()
|
||||
preview = role_service.preview_role_members('user', [])
|
||||
assert preview['removed'] == []
|
||||
role_service.apply_role_members('user', [])
|
||||
db.session.refresh(staff)
|
||||
assert staff.role == 'user'
|
||||
|
||||
|
||||
def test_picker_excludes_platform_admin(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-pick', profile='generic_entrance')
|
||||
db.session.add(entrance)
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
staff = _user('pick-staff', role='user')
|
||||
admin = _user('pick-admin', role='admin')
|
||||
db.session.add_all([staff, admin])
|
||||
db.session.commit()
|
||||
people = role_service.list_picker_people()
|
||||
ids = {row['id'] for row in people}
|
||||
assert staff.id in ids
|
||||
assert admin.id not in ids
|
||||
|
||||
|
||||
def test_cannot_assign_admin_from_picker(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-lock', profile='generic_entrance')
|
||||
db.session.add(entrance)
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
db.session.commit()
|
||||
with pytest.raises(ForbiddenError) as exc:
|
||||
role_service.assert_role_assignable('admin', allow_admin=False)
|
||||
assert exc.value.code == 'ROLE.ADMIN_LOCKED'
|
||||
assert role_service.assert_role_assignable('admin', allow_admin=True) == 'admin'
|
||||
|
||||
|
||||
def test_last_admin_cannot_be_demoted(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-last', profile='generic_entrance')
|
||||
db.session.add(entrance)
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
admin = _user('last-admin', role='admin')
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
role_service.ensure_not_last_admin(admin, 'user')
|
||||
assert exc.value.code == 'ROLE.LAST_ADMIN'
|
||||
|
||||
|
||||
def test_create_user_follows_role_package(app, monkeypatch):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-create', profile='generic_entrance')
|
||||
extra = _agent('extra-create')
|
||||
db.session.add_all([entrance, extra])
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr('app.services.auth.casdoor_service.sync_create_user', lambda **kwargs: None)
|
||||
payload = user_service.create_user({
|
||||
'username': 'created-pkg',
|
||||
'password': 'Secret123!',
|
||||
'email': 'created-pkg@example.com',
|
||||
'real_name': '创建',
|
||||
'employee_id': 'E-created-pkg',
|
||||
'phone_number': '13900001111',
|
||||
'role': 'user',
|
||||
'agent_ids': [extra.id],
|
||||
})
|
||||
user = db.session.get(User, payload['id'])
|
||||
assert [agent.id for agent in user.agents] == [entrance.id]
|
||||
|
||||
|
||||
def test_update_role_syncs_existing_members(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-upd', profile='generic_entrance')
|
||||
training = _agent('train-upd', profile='training')
|
||||
db.session.add_all([entrance, training])
|
||||
db.session.flush()
|
||||
roles = _seed_standard_roles(entrance)
|
||||
staff = _user('upd-staff', role='user')
|
||||
db.session.add(staff)
|
||||
db.session.commit()
|
||||
role_service.sync_user_grants_from_role(staff)
|
||||
db.session.commit()
|
||||
|
||||
role_service.update_role('user', {'agent_ids': [entrance.id, training.id]})
|
||||
db.session.refresh(staff)
|
||||
assert {agent.id for agent in staff.agents} == {entrance.id, training.id}
|
||||
assert roles['user'].id
|
||||
|
||||
|
||||
def test_update_role_rename_skips_member_sync(app):
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-rename', profile='generic_entrance')
|
||||
extra = _agent('extra-rename')
|
||||
db.session.add_all([entrance, extra])
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
staff = _user('rename-staff', role='user')
|
||||
staff.agents = [extra]
|
||||
db.session.add(staff)
|
||||
db.session.commit()
|
||||
|
||||
result = role_service.update_role('user', {'name': '普通用户', 'agent_ids': [entrance.id]})
|
||||
# 断言:只改名称且勾选未变,不重写成员已有授权。
|
||||
assert result['synced_users'] == 0
|
||||
db.session.refresh(staff)
|
||||
assert [agent.id for agent in staff.agents] == [extra.id]
|
||||
role = role_service.get_role_by_code('user')
|
||||
assert role is not None
|
||||
assert role.name == '普通用户'
|
||||
|
||||
|
||||
def test_first_platform_admin_user_joins_flag_not_code(app):
|
||||
"""权限组 code 不叫 admin 时,排程 owner 仍按 is_platform_admin 查找。"""
|
||||
with app.app_context():
|
||||
ops_role = PermissionRole(
|
||||
code='platform_ops',
|
||||
name='平台运维',
|
||||
is_default=False,
|
||||
is_system=True,
|
||||
is_platform_admin=True,
|
||||
sort_order=90,
|
||||
feature_permissions={},
|
||||
)
|
||||
user_role = PermissionRole(
|
||||
code='user',
|
||||
name='普通用户',
|
||||
is_default=True,
|
||||
is_system=True,
|
||||
is_platform_admin=False,
|
||||
sort_order=10,
|
||||
feature_permissions={},
|
||||
)
|
||||
db.session.add_all([ops_role, user_role])
|
||||
staff = _user('plain-staff', role='user')
|
||||
named_admin = _user('ops-lead', role='platform_ops')
|
||||
legacy = _user('legacy-admin-name', role='admin')
|
||||
db.session.add_all([staff, named_admin, legacy])
|
||||
db.session.commit()
|
||||
found = role_service.first_platform_admin_user()
|
||||
assert found is not None
|
||||
assert found.username == 'ops-lead'
|
||||
|
||||
|
||||
def test_first_platform_admin_user_skips_inactive(app):
|
||||
"""停用的平台管理员不能当排程 owner。"""
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-inactive-admin', profile='generic_entrance')
|
||||
db.session.add(entrance)
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
inactive = _user('sleeping-admin', role='admin', status='disabled')
|
||||
active = _user('awake-admin', role='admin')
|
||||
db.session.add_all([inactive, active])
|
||||
db.session.commit()
|
||||
found = role_service.first_platform_admin_user()
|
||||
assert found is not None
|
||||
assert found.username == 'awake-admin'
|
||||
|
||||
|
||||
def test_first_platform_admin_user_fallback_without_roles(app):
|
||||
"""未种子权限组时回退 users.role=admin。"""
|
||||
with app.app_context():
|
||||
staff = _user('plain-no-roles', role='user')
|
||||
admin = _user('legacy-admin', role='admin')
|
||||
db.session.add_all([staff, admin])
|
||||
db.session.commit()
|
||||
found = role_service.first_platform_admin_user()
|
||||
assert found is not None
|
||||
assert found.username == 'legacy-admin'
|
||||
|
||||
|
||||
def test_list_platform_admin_users_wecom_bound(app):
|
||||
"""告警兜底只要已绑企微的启用平台管理员。"""
|
||||
with app.app_context():
|
||||
entrance = _agent('ent-wecom-admin', profile='generic_entrance')
|
||||
db.session.add(entrance)
|
||||
db.session.flush()
|
||||
_seed_standard_roles(entrance)
|
||||
bound = _user('bound-admin', role='admin')
|
||||
bound.wecom_userid = 'WX-BOUND'
|
||||
unbound = _user('unbound-admin', role='admin')
|
||||
db.session.add_all([bound, unbound])
|
||||
db.session.commit()
|
||||
rows = role_service.list_platform_admin_users(wecom_bound=True, limit=20)
|
||||
assert [row.username for row in rows] == ['bound-admin']
|
||||
|
||||
|
||||
def test_first_schedule_owner_falls_back_to_any_user(app):
|
||||
"""没有平台管理员时,排程种子仍可用任意用户当 owner。"""
|
||||
with app.app_context():
|
||||
staff = _user('only-user', role='user')
|
||||
db.session.add(staff)
|
||||
db.session.commit()
|
||||
found = role_service.first_schedule_owner_user()
|
||||
assert found is not None
|
||||
assert found.username == 'only-user'
|
||||
|
||||
|
||||
def test_user_is_platform_admin_joins_flag_not_code(app):
|
||||
"""code 不叫 admin 的平台管理组,用户仍是 is_platform_admin。"""
|
||||
with app.app_context():
|
||||
ops_role = PermissionRole(
|
||||
code='platform_ops',
|
||||
name='平台运维',
|
||||
is_default=False,
|
||||
is_system=True,
|
||||
is_platform_admin=True,
|
||||
sort_order=90,
|
||||
feature_permissions={},
|
||||
)
|
||||
user_role = PermissionRole(
|
||||
code='user',
|
||||
name='普通用户',
|
||||
is_default=True,
|
||||
is_system=True,
|
||||
is_platform_admin=False,
|
||||
sort_order=10,
|
||||
feature_permissions={},
|
||||
)
|
||||
db.session.add_all([ops_role, user_role])
|
||||
named = _user('ops-flag', role='platform_ops')
|
||||
legacy = _user('code-admin-only', role='admin')
|
||||
db.session.add_all([named, legacy])
|
||||
db.session.commit()
|
||||
# 断言:特权看权限组标记,不看 code 是否叫 admin。
|
||||
assert named.is_platform_admin() is True
|
||||
assert legacy.is_platform_admin() is False
|
||||
|
||||
|
||||
def test_unconfigured_feature_defaults_ignore_legacy_role_names(app):
|
||||
"""未种子权限组时,hr / maintenance_manager 不再自动带能力,须显式覆盖或等角色包。"""
|
||||
with app.app_context():
|
||||
hr = _user('legacy-hr-gate', role='hr')
|
||||
maint = _user('legacy-mm-gate', role='maintenance_manager')
|
||||
admin = _user('legacy-adm-gate', role='admin')
|
||||
db.session.add_all([hr, maint, admin])
|
||||
db.session.commit()
|
||||
assert hr.get_feature_permissions()['training_hr_manage'] is False
|
||||
assert maint.get_feature_permissions()['maintenance.ledger_write'] is False
|
||||
assert admin.get_feature_permissions()['training_hr_manage'] is True
|
||||
assert admin.get_feature_permissions()['maintenance.ledger_write'] is True
|
||||
hr.set_feature_permissions({'training_hr_manage': True})
|
||||
db.session.commit()
|
||||
db.session.refresh(hr)
|
||||
assert hr.get_feature_permissions()['training_hr_manage'] is True
|
||||
@@ -552,7 +552,12 @@ def test_training_user_progress_requires_auth_and_valid_payload(client, app):
|
||||
def test_training_admin_list_stats_and_export_share_one_fact_source(client, app):
|
||||
"""HR 管理列表、统计与导出应共用同一批 TrainingRecord,并支持部门/状态筛选。"""
|
||||
with app.app_context():
|
||||
hr_user = _create_user(username="training_hr", role="hr", department="人事部")
|
||||
hr_user = _create_user(
|
||||
username="training_hr",
|
||||
role="hr",
|
||||
department="人事部",
|
||||
feature_permissions={"training_hr_manage": True},
|
||||
)
|
||||
ordinary_user = _create_user(username="training_user_denied", role="user", department="生产一部")
|
||||
passed_user = _create_user(username="passed_learner", department="生产一部")
|
||||
failed_user = _create_user(username="failed_learner", department="生产一部")
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_notify_config.py
|
||||
|
||||
用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。
|
||||
依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。
|
||||
逻辑:GET/PUT 仅 admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型。
|
||||
逻辑:GET/PUT 仅 is_platform_admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# 智能HR请假管理需求
|
||||
|
||||
## 可配置权限组(2026-09)
|
||||
|
||||
- 每位用户只选一个权限组(角色包);角色 = 可用应用入口 + 应用内能力。部门只用于选人筛选,不自动授权。
|
||||
- 新建用户由管理员选角色,默认「普通用户」。新增应用时先勾到需要的角色,再按人数弹窗选人;全选只勾草稿,确定后必须确认增减(含来源角色)。
|
||||
- 管理员为锁定角色(`code=admin`):应用入口隐式全开,选人弹窗不能添加或移出;用户管理改到/改出管理员须额外确认,且不能撤掉最后一名启用中的管理员。
|
||||
- 平台管理员从 AI 工作台进入管理控制台:侧栏底部「返回聊天」上方展示入口,普通用户不显示;对话页齿轮入口保持不变。
|
||||
- 迁移按现网 `users.role` 枚举套标准包(普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员);不再种子设备维保专员,原 `maintenance_manager` 收口到普通用户。个人额外 Agent 勾选丢弃。原型见 [platform/role-permission-prototype.md](platform/role-permission-prototype.md)。
|
||||
|
||||
## 员工培训企微通知(2026-09)
|
||||
|
||||
- 员工在“员工培训”完成“出国规章培训”视频观看后,系统立即向该员工推送一条标题和正文均为“中国员工出差泰国的行为准则”的企业微信通知。
|
||||
|
||||
@@ -83,7 +83,7 @@ Chat 同一入口用 Tab 切换「检核任务」与「企微发送记录」。
|
||||
|
||||
### 3.6 通知配置(仅平台管理员)
|
||||
|
||||
Chat 第三 Tab「通知配置」按销售一期六类必检文件分行选人。配置写入 `voucher_check_notify_configs`,与 Profile 版本解耦,换人不必发版 `file_rules`。仅 `role=admin` 可见、可改;被授予 Agent 的普通用户看不到该 Tab。
|
||||
Chat 第三 Tab「通知配置」按销售一期六类必检文件分行选人。配置写入 `voucher_check_notify_configs`,与 Profile 版本解耦,换人不必发版 `file_rules`。仅 `is_platform_admin` 可见、可改;被授予 Agent 的普通用户看不到该 Tab。
|
||||
|
||||
| 项目 | 规则 |
|
||||
| -------- | ---- |
|
||||
|
||||
@@ -168,7 +168,7 @@ XFA:`can_auto_create=false` 时不得显示 automating;不放宽冻结门禁
|
||||
|
||||
## 5. profile_match 权限
|
||||
|
||||
- 判定:本轮暂 `user.role == 'admin'`(权限封装,避免散落前端)
|
||||
- 判定:本轮 `user.is_platform_admin()`(权限封装,避免散落前端)
|
||||
- 普通用户 Case API:四态 `matched|unmatched|ambiguous|unknown`,无候选分 / Profile ID / 原因链
|
||||
- 管理员:完整模板审计对象 + 用户态 `status` 映射
|
||||
- 禁止仅靠前端 `v-if` 隐藏敏感字段
|
||||
|
||||
@@ -2140,10 +2140,10 @@ test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是
|
||||
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS` | `90`(默认) | `90` |
|
||||
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED` | `false`(默认关闭企微心跳告警) | 同左;需要时改为 `true` |
|
||||
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` | 逗号分隔 HXOPS 用户名(**部署前建议显式填写**) | 同左 |
|
||||
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` |
|
||||
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的平台管理员) | 建议 `true` |
|
||||
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS` | `120`(企微发送中短锁,失败后可重试) | `120` |
|
||||
|
||||
**告警接收人部署检查**:`SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` 留空时,仅当存在 `role=admin` 且已绑定 `wecom_userid` 的用户才会真正收到企微通知;否则只写 warning。上线前请二选一:填写运维用户名,或确认至少一名 admin 已完成企微绑定。
|
||||
**告警接收人部署检查**:`SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` 留空时,仅当存在 `permission_roles.is_platform_admin` 且已绑定 `wecom_userid` 的启用用户才会真正收到企微通知;否则只写 warning。上线前请二选一:填写运维用户名,或确认至少一名平台管理员已完成企微绑定。
|
||||
|
||||
**多进程去重**:告警冷却状态以 `app_settings` 为权威源,Redis 仅作缓存同步;DB 不可读写时才回退 Redis/进程内内存 claim。
|
||||
|
||||
|
||||
+13
-3
@@ -1,5 +1,15 @@
|
||||
# 智能HR请假管理功能清单
|
||||
|
||||
## 可配置权限组(2026-09)
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 权限组表与种子 | 已实现 | `permission_roles` / `permission_role_agents`;标准包为普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员。不再种子设备维保专员。未种子时测试夹具仍走按人授权。 |
|
||||
| 角色包即授权 | 已实现 | 用户只选一个角色;保存角色立即同步该组成员应用入口;功能权限改由角色包计算。`is_platform_admin` 权限组隐式全开应用入口。 |
|
||||
| 管理端角色配置 | 已实现 | `/admin/permissions` 以角色列表为主:编辑时应用卡片内嵌功能权限短标签;点人数打开公共选人弹窗,确定后确认增减才写库。矩阵只读核对。 |
|
||||
| 用户只选角色 | 已实现 | 新建用户默认普通用户;改角色须确认;按人勾应用、应用页按人授权、权限申请通过加应用,在角色包启用后一律拒绝(`ROLE.DIRECT_GRANT_DISABLED`)。 |
|
||||
| 工作台进入管理控制台 | 已实现 | AI 工作台侧栏底部「返回聊天」上方,仅平台管理员(`is_platform_admin`)显示「管理控制台」并跳转 `/admin`;普通用户不渲染入口。 |
|
||||
|
||||
## 合同付款预警 Agent
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
@@ -11,7 +21,7 @@
|
||||
| 通用合同解析与待确认合同 | 已实现 | 不再校验 V4 或其他固定模板;只校验合同号、金额、交期、采购单号及四阶段付款比例完整、无重复、合计 100%。关键事实或比例校验失败合同归入 Chat「待确认」Tab,不得触发自动预警。 |
|
||||
| 扫描版合同 MinerU 解析 | 已实现 | OA PDF 附件优先经 MinerU 生成 Markdown 后再解析合同号、金额、交期与四阶段付款比例;服务未配置、失败或空结果时安全回退既有文字层/OCR,历史合同可用“批量重新解析存量合同”刷新。 |
|
||||
| 存量合同批量重解析 | 已实现 | 管理员可直接用已归档附件批量刷新历史解析结果,不拉取 OA、不覆盖 OA 字段,用于规则升级后的待确认合同恢复。 |
|
||||
| 合同付款 Agent 授权 | 已实现 | 入口为 Chat builtin Agent `contract_payment`:平台 admin 默认可访问,普通用户需在用户管理授予该 Agent。旧功能权限 `contract_payment.access` 由迁移写入 Agent 授权后删除。无授权直链提示并回应用管理,API 返回 403。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 |
|
||||
| 合同付款 Agent 授权 | 已实现 | 入口为 Chat builtin Agent `contract_payment`:平台 admin 默认可访问;权限组启用后把该 Agent 勾到角色包即可,不再按人授权。无授权直链提示并回应用管理,API 返回 403。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 |
|
||||
| OA 盖章合同优先 | 已实现 | 合同申请单存在“盖章完成合同上传”时固定优先下载和解析该附件;“合同附件”仅作为失败降级来源。 |
|
||||
|
||||
## 知识库同步状态校验
|
||||
@@ -41,8 +51,8 @@
|
||||
| 会话式维修记录查询 | 后端已实现 | 新增 `/api/maintenance/records` 查询接口,支持按设备编号、设备名称、维修状态筛选,供 Agent 会话查询和前端结果复用 |
|
||||
| 会话式设备台账卡片 | 已实现 | 明确设备编号/名称查询由 HXOPS 后端本地直答,返回设备台账信息卡片和最近维修记录;支持“这个设备/这台”等同会话追问复用上一轮设备,本地未命中时放行 Dify 处理复杂语义 |
|
||||
| Dify 设备维保查询 Tool | 已实现 | 新增 `/api/maintenance/tools/*` 只读 Tool API 与 `/api/maintenance/tools/openapi.json`,供 Dify 处理复杂问法时查询设备台账和维修记录 |
|
||||
| 维修记录管理 | 已实现 | `设备维保助手` 聊天输入栏底部仅对“管理员 / 维保管理员”显示“维修记录”按钮,右侧固定面板支持维修记录查询、新增、编辑、删除 |
|
||||
| 设备台账配置 | 已实现 | `设备维保助手` 聊天输入栏底部仅对“管理员 / 维保管理员”显示“台账配置”按钮,右侧固定面板包含“设备列表 / 设备配置”两个 Tab |
|
||||
| 维修记录管理 | 已实现 | `设备维保助手` 聊天输入栏底部仅对具备 `maintenance.ledger_write` 的用户显示“维修记录”按钮,右侧固定面板支持维修记录查询、新增、编辑、删除 |
|
||||
| 设备台账配置 | 已实现 | `设备维保助手` 聊天输入栏底部仅对具备 `maintenance.ledger_write` 的用户显示“台账配置”按钮,右侧固定面板包含“设备列表 / 设备配置”两个 Tab |
|
||||
| Excel 导入设备台账 | 已实现 | 支持下载设备台账模板并通过 Excel 批量导入,按设备编号新增或更新 |
|
||||
| 设备财务字段配置 | 已实现 | 设备台账支持原值、残值和账套字段;账套固定选项为和信、科技、电子、和宏智 |
|
||||
| 责任人字段 | 已实现 | 设备台账责任人字段使用 `responsible_user` / `responsibleUser` 用户名文本,不关联用户表 |
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# 角色权限配置原型
|
||||
|
||||
> **文档路径**:`docs/platform/role-permission-prototype.md`
|
||||
> **用途**:可配置角色(权限包)一期产品原型说明;交互稿见同目录 HTML。
|
||||
> **依赖**:管理控制台「应用权限」、`permission_roles`、`users.role`、`user_agent_permissions`。
|
||||
> **逻辑**:新建用户由管理员选角色(默认普通用户);已有用户可按角色点人数筛选勾选,确定前确认影响。一期已按此实现。可点击稿:[role-permission-prototype.html](role-permission-prototype.html)
|
||||
|
||||
---
|
||||
|
||||
## 怎么打开
|
||||
|
||||
用浏览器直接打开 `docs/platform/role-permission-prototype.html`(无需启动前后端)。左侧切换:
|
||||
|
||||
| 屏 | 要看什么 |
|
||||
| --- | --- |
|
||||
| **角色配置** | 权限包列表。点「编辑」给该角色勾应用;点蓝色**人数**给该角色加人 |
|
||||
| **编辑角色** | 列出全部可授权应用;保存前确认会立刻改变该角色下所有人的入口 |
|
||||
| **用户管理** | **新建用户必须选角色**,默认普通用户;编辑用户改角色也会先确认 |
|
||||
| **权限核对** | 现行矩阵的只读形态,格子禁用 |
|
||||
| **现行应用权限** | 对照说明:为什么不再按人打勾 |
|
||||
|
||||
建议演示:
|
||||
|
||||
1. **用户管理 → 新建用户**:角色预填「普通用户」,可改成培训 HR / 研发应用等,非默认角色会再确认。
|
||||
2. **新增应用后**:先编辑对应角色勾上该应用 → 再点该角色人数,按部门筛选勾选要进这个角色的人 → **确定后弹出确认**(写清从哪些角色改入)。全选只勾草稿,不要不核对就点确认调整。
|
||||
|
||||
---
|
||||
|
||||
## 一期约定(已画进原型)
|
||||
|
||||
1. **角色 = 权限包**:可用应用 + 应用内能力;管理员单独带「可进 /admin」。
|
||||
2. **用户只选一个角色**。新建时由管理员指定,默认普通用户;部门不会自动授权。
|
||||
3. **普通用户**默认只勾 **通用入口**(企业知识库是该聊天里的库切换,不单独占一列)。
|
||||
4. **研发应用** = 通用入口 + 研发侧应用(如专利);本地尚未接入的应用之后勾进本组即可。编码仍为 `rd`。
|
||||
5. 角色编辑列出**应用管理中全部启用应用**。有功能权限的应用在卡片内用短标签配置,不另开一排长框。新增应用:勾到需要的角色上,再按需把人改进该角色。
|
||||
6. **保存角色立即对已绑该角色的用户生效**,弹窗提示人数,须确认。
|
||||
7. **管理员内置**:应用入口隐式全开;人数不可点;选人列表排除管理员。改到/改出管理员须额外确认。
|
||||
8. **已有用户批量改角色**:点人数,左部门仅筛选。勾选后确定先出确认框(从来源角色、将失去原权限)。全选不是默认操作。
|
||||
9. **取消勾选后确认** = 回到默认普通用户。编辑「普通用户」时取消勾选忽略。
|
||||
|
||||
---
|
||||
|
||||
## 一期不做
|
||||
|
||||
- 一人多角色、按人额外加应用、在核对矩阵上打勾。
|
||||
- 部门自动映射角色(部门是组织,角色是权限包;入职/调岗由管理员选或改角色)。
|
||||
- 员工自助「申请某个应用」(若保留申请,应改为申请换角色)。
|
||||
+10
-2
@@ -1,5 +1,13 @@
|
||||
# Agent 应用注册补充(2026-07-28)
|
||||
|
||||
## 可配置权限组(2026-09)
|
||||
|
||||
- 表:`permission_roles`(code/name/feature_permissions/is_default/is_platform_admin)与 `permission_role_agents`。成员仍写在 `users.role`(加宽至 64)。运行时 Chat/工作台继续读 `user_agent_permissions` 与 `require_agent_permission`(`is_platform_admin` 旁路);非管理员的 Agent 行由角色包全量替换。排程种子 owner 与 RPA 心跳告警管理员兜底改为 join `is_platform_admin`(未种子权限组时回退 `users.role=admin`)。登录态下发 `is_platform_admin` / `role_name` / `feature_permissions`;业务门闩认标记与能力键。未种子时默认能力仅平台管理员全开,不再用 `hr` / `maintenance_manager` 角色名暗示权限(培训 FAQ 的 HR/员工身份、会话 guest、聊天 message.role、保留码 `admin` 除外)。
|
||||
- 种子:`user` 普通用户、`rd` 研发应用、`hr` 培训 HR、`shipping` 货代专员、`admin` 管理员。不再种子设备维保专员。
|
||||
- 管理 API:`/api/admin/permission-roles*`(列表、目录、CRUD、成员 preview/apply)。种子后禁止 `POST /users/:id/permissions`、`/permissions/batch`、`/agents/:id/permissions` 与权限申请批准加应用。
|
||||
- 前端:`/admin/permissions` 角色配置 + 只读矩阵;用户表单只选角色。能力键与 `User.get_feature_permissions` 对齐。详细约定见 [platform/role-permission-prototype.md](platform/role-permission-prototype.md)。
|
||||
- AI 工作台侧栏底部「返回聊天」上方,仅 `is_platform_admin` 渲染「管理控制台」入口(`openAdminPanel` → `/admin`);`/admin` 仍由路由守卫 `requiresAdmin` 拦截非平台管理员。
|
||||
|
||||
## 合同付款预警(2026-08)
|
||||
|
||||
- 使用 Flask + SQLAlchemy 合同付款域模型,OA 同步、每日预警扫描与周汇总均注册为平台排程任务;默认时区 `Asia/Shanghai`,周汇总 Cron 为 `0 18 * * 5`。合同付款 Job 运行超时由 `CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS`(默认 1800 秒)回收:未超过最大重试次数的任务重新排队,耗尽后标记失败,避免 Worker 异常退出导致任务永久停在 `running`。
|
||||
@@ -10,7 +18,7 @@
|
||||
- 普通 OA 同步仅补充本地空字段;管理员显式提交 `POST /api/contract-payment/sync` 的 `{ "force": true }` 时,才以 OA 本次非空字段覆盖合同主表。覆盖操作人、时间和 `before/after` 字段差异保存在既有 JSON 列 `source_payload_json.force_sync_audit`(最近 20 次),不新增数据库结构;附件下载及付款计划解析链路保持不变。
|
||||
- 同一同步 Job 支持 `{ "reparse_existing": true }` 存量恢复模式:不依赖 OA 增量通知,遍历已有合同的已归档附件并按盖章完成合同上传优先级重跑解析,刷新 `parse_result_json`、解析状态和节点;单次最多 1000 份,没有附件或文件资产的记录安全跳过。
|
||||
- OA 通知同步采用增量断点:`contract_payment_sync_states` 以 `state_key='oa-contract-archive'` 单行游标记录上次成功同步时间,下次用 `last_successful_sync_at - CONTRACT_PAYMENT_OA_SYNC_OVERLAP_SECONDS` 作为归档时间下限(overlap 兜住迟到/越序记录)。翻页使用 `CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE` / `..._PAGE_PARAM`;`CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES` 默认 `0`(翻到短页为止),仅约束增量窗口,首次全量忽略此上限。触顶且末页仍满页时标记截断,已入库记录保留但**不推进断点**。重复项由 `(event_type, source_event_id)` 幂等去重;仅当 OA 配置、列表接口可用且本轮未截断时才推进断点。增量窗口只拉"归档时间在窗口内"的合同,窗口外旧合同的字段修正由管理员显式触发:`{ force: true }` 同步绕过时间窗口全量重扫,`{ reparse_existing: true }` 存量重解析遍历全部已归档附件,都会覆盖窗口外记录。
|
||||
- Chat 主区嵌入台账 Tab(`agent_code=contract_payment`,builtin,不走 completions);`/api/contract-payment/*` 校验平台 admin 或 `user_agent_permissions` 中启用的该 Agent。无授权返回 403(`CONTRACT_PAYMENT.FORBIDDEN`)。`POST /sync`、`POST /alerts/run`、`POST /alerts/weekly-run` 额外要求 `role=admin`(`CONTRACT_PAYMENT.ADMIN_REQUIRED`),企业微信收件人与该访问权解耦。旧工作台 URL 由前端重定向到 `/chat/:agentId?view=`。
|
||||
- Chat 主区嵌入台账 Tab(`agent_code=contract_payment`,builtin,不走 completions);`/api/contract-payment/*` 校验平台管理员(`is_platform_admin`)或 `user_agent_permissions` 中启用的该 Agent。无授权返回 403(`CONTRACT_PAYMENT.FORBIDDEN`)。`POST /sync`、`POST /alerts/run`、`POST /alerts/weekly-run` 额外要求平台管理员(`CONTRACT_PAYMENT.ADMIN_REQUIRED`),企业微信收件人与该访问权解耦。旧工作台 URL 由前端重定向到 `/chat/:agentId?view=`。
|
||||
- 验收单归档不走合同申请单 HTTP 列表,而查 OA SQL Server(凭据复用 `OA_SQLSERVER_*`):`formtable_main_324.cgdh` 为采购单号,`requestId` 关联 `workflow_requestbase`,`currentnodetype='3'` 为已归档(0 创建 / 1 批准 / 2 提交 / 3 归档)。归档日取 `lastoperatedate`/`lastoperatetime`。事件幂等键 `oa-acceptance:{requestId}:c{contractId}`,按采购单号匹配台账;独立断点 `oa-acceptance-archive`。查询失败 fail-safe 跳过且不推进该断点。节点后于事件生成时,`_persist_payment_plan` 回放已有验收事件计算验收款/质保款日期。表名/字段可由 `CONTRACT_PAYMENT_OA_ACCEPTANCE_*` 覆盖。
|
||||
- 第二、三轮收件人查同一 OA SQL:`HrmResource.lastname` 唯一匹配台账申请人,取其 `departmentid`;`Matrixtable_3.bm` 关联部门,`zz` 为第二轮、`jfl` 为第三轮。该 ID 即 `HrmResource.id` 与企业微信 userid。优先按 `users.wecom_userid` 映射系统用户,未绑定再用主管 `lastname` 唯一匹配 `real_name`;查不到不向第一轮兜底。表名/字段可由 `CONTRACT_PAYMENT_OA_HRM_*`、`CONTRACT_PAYMENT_OA_MATRIX_*` 覆盖。
|
||||
|
||||
@@ -215,7 +223,7 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由
|
||||
### 2.x 立账凭证检核(accounting-voucher-check)
|
||||
|
||||
- 前端入口为 Chat builtin Agent `voucher_check`(`task_chat`,第一期不走 completions)。旧路由 `/workspace/accounting-voucher-check*` 重定向到 `/chat/:agentId?view=`;工作台侧栏不再展示该入口。
|
||||
- `/api/workspace/accounting-voucher-check/*` 查询校验平台 admin 或 `user_agent_permissions` 中启用的该 Agent。无授权返回 403(`VOUCHER_CHECK.FORBIDDEN`)。`POST /runs` 强制重检与 `GET/PUT /notify-config` 额外要求 `role=admin`(`VOUCHER_CHECK.ADMIN_REQUIRED`)。
|
||||
- `/api/workspace/accounting-voucher-check/*` 查询校验平台管理员(`is_platform_admin`)或 `user_agent_permissions` 中启用的该 Agent。无授权返回 403(`VOUCHER_CHECK.FORBIDDEN`)。`POST /runs` 强制重检与 `GET/PUT /notify-config` 额外要求平台管理员(`VOUCHER_CHECK.ADMIN_REQUIRED`)。
|
||||
- **目标架构**:通用检核引擎 + 业务方 Profile + 来源 Adapter。**每周二**处理上一个自然月;invoice 主体来自 HXJM `oma_file`(`oma10`/`oma02`,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13);引擎负责增量、归档、缺件双口径、Excel 与企微批次汇总。
|
||||
- **销售一期来源**:PO 订单由 HXOPS 按制式采购单生成 PDF 并上传到当月「PO订单」目录。发票在 HXJM,采购单在 **TGHX**(多角);关联已确认 `TRIM(oma99)=TRIM(pmm99)`,见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)。OA 销货放行单一期模拟页面、文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。
|
||||
- **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Attachment/Upload`、`Item/CreateFiles`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。类型目录上传与归档复制均为同名跳过。
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
/**
|
||||
* features/admin/api/admin.api.ts
|
||||
* 用途:管理后台用户、部门、Agent、权限、报表等 HTTP API。
|
||||
* 依赖:requestJson、getAuthHeaders、各管理域类型。
|
||||
* 依赖:requestJson、getAuthHeaders、各管理域类型(含 permissionRole.types)。
|
||||
* 逻辑:JSON 接口统一走 requestJson;业务域专属 API 位于各自 feature 目录。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import type { AdminUserRow } from '../types/admin.types';
|
||||
import type {
|
||||
PermissionRoleCatalog,
|
||||
PermissionRoleMembersPreview,
|
||||
PermissionRolePerson,
|
||||
PermissionRoleRow,
|
||||
} from '../types/permissionRole.types';
|
||||
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
|
||||
import type { PaginatedResult } from '@/shared/types/pagination.types';
|
||||
import type { AdminLinkedServiceRow } from '../types/linked-service.types';
|
||||
@@ -722,6 +728,54 @@ export const batchUpdateAdminPermissions = (payload: Record<string, unknown>) =>
|
||||
export const importAdminPermissions = (formData: FormData) =>
|
||||
requestJson('/api/admin/permissions/import', { method: 'POST', ...auth(), body: formData });
|
||||
|
||||
/** 列出全部权限组(含人数与已选应用)。 */
|
||||
export const listAdminPermissionRoles = () =>
|
||||
requestJson<PermissionRoleRow[]>('/api/admin/permission-roles', auth());
|
||||
|
||||
/** 角色编辑可选应用与应用内能力。 */
|
||||
export const getAdminPermissionRoleCatalog = () =>
|
||||
requestJson<PermissionRoleCatalog>('/api/admin/permission-roles/catalog', auth());
|
||||
|
||||
/** 选人弹窗候选人(排除管理员)。 */
|
||||
export const listAdminPermissionRolePickerUsers = () =>
|
||||
requestJson<PermissionRolePerson[]>('/api/admin/permission-roles/picker-users', auth());
|
||||
|
||||
/** 新建权限组。 */
|
||||
export const createAdminPermissionRole = (payload: Record<string, unknown>) =>
|
||||
requestJson<{ id: number; code: string }>('/api/admin/permission-roles', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
/** 保存权限包并同步该组用户授权。 */
|
||||
export const updateAdminPermissionRole = (code: string, payload: Record<string, unknown>) =>
|
||||
requestJson<{ status: string; synced_users: number }>(
|
||||
`/api/admin/permission-roles/${encodeURIComponent(code)}`,
|
||||
{ method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/** 删除空的非内置权限组。 */
|
||||
export const deleteAdminPermissionRole = (code: string) =>
|
||||
requestJson(`/api/admin/permission-roles/${encodeURIComponent(code)}`, {
|
||||
method: 'DELETE',
|
||||
...auth(),
|
||||
});
|
||||
|
||||
/** 确认前预览将改入/移出的人。 */
|
||||
export const previewAdminPermissionRoleMembers = (code: string, selectedIds: number[]) =>
|
||||
requestJson<PermissionRoleMembersPreview>(
|
||||
`/api/admin/permission-roles/${encodeURIComponent(code)}/members/preview`,
|
||||
{ method: 'POST', ...jsonAuth(), body: JSON.stringify({ selected_ids: selectedIds }) },
|
||||
);
|
||||
|
||||
/** 确认后写回成员。 */
|
||||
export const applyAdminPermissionRoleMembers = (code: string, selectedIds: number[]) =>
|
||||
requestJson<{ status: string; added: number; removed: number; skipped_admin: number }>(
|
||||
`/api/admin/permission-roles/${encodeURIComponent(code)}/members`,
|
||||
{ method: 'POST', ...jsonAuth(), body: JSON.stringify({ selected_ids: selectedIds }) },
|
||||
);
|
||||
|
||||
// Dashboard
|
||||
/** 仪表盘四张卡片:Agent 数、用户数、对话总数、平均评分 */
|
||||
export const getAdminDashboardSummary = () =>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* 用途:管理控制台的应用管理页,提供应用列表、创建/编辑弹窗、测试与授权入口。
|
||||
* 依赖:useAgentsAdmin 业务编排、AgentFormModal/AgentTestModal/AgentPermissionModal 弹窗。
|
||||
* 逻辑:页面加载后拉取应用/用户/排程数据;列表支持表头列宽拖拽并 localStorage 持久化。
|
||||
* 逻辑:页面加载后拉取应用/用户/排程数据;权限组启用后隐藏按人授权按钮。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, onMounted } from 'vue';
|
||||
@@ -43,6 +43,7 @@ const {
|
||||
showPermissionModal,
|
||||
permissionAgent,
|
||||
permissionUserIds,
|
||||
rolesConfigured,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
@@ -301,6 +302,7 @@ onMounted(() => {
|
||||
{{ t('admin.edit') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="!rolesConfigured"
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center justify-center p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-all"
|
||||
:title="t('admin.agent.manageAccess')"
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
*
|
||||
* Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。
|
||||
* 从原 AdminView.vue 的 agents 相关 script 抽取,供 AgentsPage 使用。
|
||||
* 权限组启用后拒绝打开按人授权弹窗,提示改到应用权限页的角色包。
|
||||
*/
|
||||
|
||||
import { ref, computed } from 'vue';
|
||||
@@ -18,6 +19,7 @@ import {
|
||||
listAdminIntentRoutes,
|
||||
listAdminAgents,
|
||||
listAdminUsers,
|
||||
listAdminPermissionRoles,
|
||||
saveAdminAgentPermissions,
|
||||
testAdminAgent,
|
||||
updateAdminAgent,
|
||||
@@ -235,6 +237,7 @@ export function useAgentsAdmin() {
|
||||
const intentRouteOptions = ref<IntentRouteOption[]>([]);
|
||||
const contentProfileOptions = ref<AdminContentProfileOption[]>([]);
|
||||
const users = ref<AdminUserRow[]>([]);
|
||||
const rolesConfigured = ref(false);
|
||||
const scheduleTasks = ref<ScheduleTask[]>([]);
|
||||
const trainingExamPdfGuides = ref<AgentGuideSummary[]>([]);
|
||||
const isLoading = ref(true);
|
||||
@@ -326,6 +329,16 @@ export function useAgentsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
const loadRolesConfigured = async (): Promise<void> => {
|
||||
try {
|
||||
const rows = await listAdminPermissionRoles();
|
||||
rolesConfigured.value = rows.length > 0;
|
||||
} catch (e) {
|
||||
console.error('Error loading permission roles:', e);
|
||||
rolesConfigured.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const loadScheduleTasks = async (): Promise<void> => {
|
||||
try {
|
||||
scheduleTasks.value = await listAdminSchedules();
|
||||
@@ -359,6 +372,7 @@ export function useAgentsAdmin() {
|
||||
loadContentProfileOptions(),
|
||||
loadAgents(),
|
||||
loadUsers(),
|
||||
loadRolesConfigured(),
|
||||
loadScheduleTasks(),
|
||||
]);
|
||||
isLoading.value = false;
|
||||
@@ -660,6 +674,10 @@ export function useAgentsAdmin() {
|
||||
};
|
||||
|
||||
const openPermissionModal = (agent: AgentRow): void => {
|
||||
if (rolesConfigured.value) {
|
||||
msg.warning(t('admin.permRoles.useRolePage'));
|
||||
return;
|
||||
}
|
||||
permissionAgent.value = agent;
|
||||
permissionUserIds.value = users.value
|
||||
.filter((u) => u.agent_ids.includes(agent.id))
|
||||
@@ -704,6 +722,7 @@ export function useAgentsAdmin() {
|
||||
intentRouteOptions,
|
||||
contentProfileOptions,
|
||||
users,
|
||||
rolesConfigured,
|
||||
scheduleTasks,
|
||||
trainingExamPdfGuides,
|
||||
activeUsers,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { onMounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ShieldCheck, Trash2 } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { adminRoleLabel } from '@/features/admin/utils/roleLabel';
|
||||
import { useApprovalsAdmin } from './composables/useApprovalsAdmin';
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -71,7 +72,7 @@ onMounted(() => {
|
||||
<span
|
||||
class="px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200"
|
||||
>
|
||||
{{ t('admin.role.' + user.role) }}
|
||||
{{ adminRoleLabel(t, user.role, user.role_name) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-8 py-5 text-right flex items-center justify-end gap-2">
|
||||
|
||||
@@ -1,34 +1,54 @@
|
||||
/**
|
||||
* features/admin/modules/permissions/PermissionsPage.vue
|
||||
* 用途:应用权限矩阵独立页面(用户 / 真实姓名 / 部门 + Agent 勾选)。
|
||||
* 依赖:usePermissionsAdmin、BatchPermissionModal、PaginationBar。
|
||||
* 逻辑:路由 /admin/permissions;左侧用户相关列 sticky,右侧为各应用权限列。
|
||||
* 用途:应用权限页。已种子权限组时以角色包为主、矩阵只读;否则保留历史按人勾选。
|
||||
* 依赖:usePermissionsAdmin、RoleEditModal、UserPickerDialog、PaginationBar、roleLabel。
|
||||
* 逻辑:路由 /admin/permissions;点人数打开选人弹窗,确定后必须确认增减才写库。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Download, FileText, Users } from 'lucide-vue-next';
|
||||
import { Download, FileText, Plus, Shield, Users } from 'lucide-vue-next';
|
||||
import BatchPermissionModal from '@/features/admin/modules/users/components/BatchPermissionModal.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import UserPickerDialog from '@/shared/components/UserPickerDialog.vue';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { adminRoleLabel, LEGACY_ROLE_OPTIONS } from '@/features/admin/utils/roleLabel';
|
||||
import RoleEditModal from './components/RoleEditModal.vue';
|
||||
import RoleMembersConfirmDialog from './components/RoleMembersConfirmDialog.vue';
|
||||
import { usePermissionsAdmin } from './composables/usePermissionsAdmin';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const {
|
||||
agents,
|
||||
permissionFilters,
|
||||
selectedUserIds,
|
||||
paginatedUsers,
|
||||
permissionPage,
|
||||
permissionPageSize,
|
||||
permissionPageSizeOptions,
|
||||
permissionTotalRows,
|
||||
permissionTotalPages,
|
||||
allUsersSelectedOnPage,
|
||||
isLoading,
|
||||
const {
|
||||
agents,
|
||||
roles,
|
||||
catalog,
|
||||
pickerUsers,
|
||||
permissionFilters,
|
||||
selectedUserIds,
|
||||
paginatedUsers,
|
||||
permissionPage,
|
||||
permissionPageSize,
|
||||
permissionPageSizeOptions,
|
||||
permissionTotalRows,
|
||||
permissionTotalPages,
|
||||
allUsersSelectedOnPage,
|
||||
isLoading,
|
||||
isSaving,
|
||||
activeTab,
|
||||
rolesConfigured,
|
||||
showBatchPermissionModal,
|
||||
batchPermissionForm,
|
||||
showRoleEditor,
|
||||
editingExisting,
|
||||
roleDraft,
|
||||
editingMemberCount,
|
||||
showRoleSaveConfirm,
|
||||
pickerRole,
|
||||
showPicker,
|
||||
pickerSelectedIds,
|
||||
membersPreview,
|
||||
showMembersConfirm,
|
||||
loadAll,
|
||||
toggleUserSelection,
|
||||
toggleAllUsers,
|
||||
@@ -36,8 +56,19 @@ const { t } = useI18n();
|
||||
closeBatchPermissionModal,
|
||||
submitBatchPermission,
|
||||
toggleUserAgentPermission,
|
||||
userHasAgent,
|
||||
exportPermissions,
|
||||
importPermissions,
|
||||
openCreateRole,
|
||||
openEditRole,
|
||||
closeRoleEditor,
|
||||
requestSaveRole,
|
||||
persistRole,
|
||||
removeRole,
|
||||
openMembersPicker,
|
||||
handlePickerConfirm,
|
||||
cancelMembersConfirm,
|
||||
applyMembers,
|
||||
} = usePermissionsAdmin();
|
||||
|
||||
onMounted(() => {
|
||||
@@ -55,11 +86,13 @@ onMounted(() => {
|
||||
<div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 class="section-title">{{ t('admin.perm.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.perm.subtitle') }}</p>
|
||||
<p class="section-desc mt-1">
|
||||
{{ rolesConfigured ? t('admin.permRoles.subtitle') : t('admin.perm.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<button
|
||||
v-if="selectedUserIds.length > 0"
|
||||
v-if="!rolesConfigured && selectedUserIds.length > 0"
|
||||
type="button"
|
||||
class="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-200 active:scale-95"
|
||||
@click="openBatchPermissionModal"
|
||||
@@ -68,6 +101,7 @@ onMounted(() => {
|
||||
<span class="font-medium">{{ t('admin.perm.batchAssign') }}</span>
|
||||
</button>
|
||||
<label
|
||||
v-if="!rolesConfigured"
|
||||
class="flex items-center gap-2 px-4 py-2 btn-secondary cursor-pointer text-sm font-medium transition-all shadow-sm"
|
||||
>
|
||||
<input type="file" accept=".csv" class="hidden" @change="importPermissions" />
|
||||
@@ -82,128 +116,239 @@ onMounted(() => {
|
||||
<Download class="w-4 h-4" />
|
||||
{{ t('admin.perm.exportCsv') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="rolesConfigured"
|
||||
type="button"
|
||||
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 text-sm font-medium"
|
||||
@click="openCreateRole"
|
||||
>
|
||||
<Plus class="w-4 h-4" />
|
||||
{{ t('admin.permRoles.create') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-filters--inline">
|
||||
<input
|
||||
v-model="permissionFilters.username"
|
||||
:placeholder="t('admin.perm.filterName')"
|
||||
class="admin-table-filter-input w-48"
|
||||
/>
|
||||
<input
|
||||
v-model="permissionFilters.department"
|
||||
:placeholder="t('admin.perm.filterDept')"
|
||||
class="admin-table-filter-input w-48"
|
||||
/>
|
||||
<select v-model="permissionFilters.role" class="admin-table-filter-input w-32">
|
||||
<option value="">{{ t('admin.perm.allRoles') }}</option>
|
||||
<option value="user">{{ t('admin.role.user') }}</option>
|
||||
<option value="hr">{{ t('admin.role.hr') }}</option>
|
||||
<option value="admin">{{ t('admin.role.admin') }}</option>
|
||||
</select>
|
||||
<div v-if="rolesConfigured" class="flex gap-1 border-b border-default">
|
||||
<button
|
||||
type="button"
|
||||
class="px-4 py-2 text-sm font-medium"
|
||||
:class="activeTab === 'roles' ? 'border-b-2 border-brand-600 text-brand-700' : 'text-muted'"
|
||||
@click="activeTab = 'roles'"
|
||||
>
|
||||
{{ t('admin.permRoles.tabs.roles') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="px-4 py-2 text-sm font-medium"
|
||||
:class="activeTab === 'matrix' ? 'border-b-2 border-brand-600 text-brand-700' : 'text-muted'"
|
||||
@click="activeTab = 'matrix'"
|
||||
>
|
||||
{{ t('admin.permRoles.tabs.matrix') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-section admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-4 py-4 w-12 text-center sticky left-0 admin-table-sticky-head z-20">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
|
||||
:checked="allUsersSelectedOnPage"
|
||||
@change="toggleAllUsers"
|
||||
/>
|
||||
</th>
|
||||
<th
|
||||
class="px-6 py-4 text-left text-sm sticky left-12 admin-table-sticky-head z-20 w-56"
|
||||
>
|
||||
{{ t('admin.perm.headers.user') }}
|
||||
</th>
|
||||
<th
|
||||
class="px-6 py-4 text-left text-sm sticky left-[17rem] admin-table-sticky-head z-20 w-36"
|
||||
>
|
||||
{{ t('admin.perm.headers.realName') }}
|
||||
</th>
|
||||
<th
|
||||
class="px-6 py-4 text-left text-sm sticky left-[26rem] admin-table-sticky-head z-20 w-40 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
|
||||
>
|
||||
{{ t('admin.perm.headers.dept') }}
|
||||
</th>
|
||||
<th
|
||||
v-for="agent in agents"
|
||||
:key="agent.id"
|
||||
class="px-4 py-4 text-center text-sm min-w-[100px]"
|
||||
>
|
||||
<div class="flex flex-col items-center gap-1">
|
||||
<span>{{ agent.name }}</span>
|
||||
<span class="text-[10px] text-muted font-normal border border-default px-1 rounded">
|
||||
{{ agent.type }}
|
||||
</span>
|
||||
</div>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="user in paginatedUsers" :key="user.id">
|
||||
<td class="px-4 py-4 text-center sticky left-0 admin-table-sticky-cell z-20">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
|
||||
:checked="selectedUserIds.includes(user.id)"
|
||||
@change="toggleUserSelection(user.id)"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-6 py-4 sticky left-12 admin-table-sticky-cell z-20">
|
||||
<div class="flex items-center gap-3">
|
||||
<div
|
||||
class="w-8 h-8 rounded-full bg-gradient-to-br from-brand-100 to-indigo-100 text-brand-600 flex items-center justify-center font-bold text-sm"
|
||||
>
|
||||
{{ user.username.charAt(0).toUpperCase() }}
|
||||
</div>
|
||||
<div class="font-medium text-primary text-sm truncate max-w-[120px]" :title="user.username">
|
||||
{{ user.username }}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 sticky left-[17rem] admin-table-sticky-cell z-20">
|
||||
<div class="text-sm text-primary truncate" :title="user.real_name || '-'">
|
||||
{{ user.real_name || '-' }}
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class="px-6 py-4 sticky left-[26rem] admin-table-sticky-cell z-20 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]"
|
||||
>
|
||||
<div class="text-sm text-muted truncate" :title="user.department">
|
||||
{{ user.department || '-' }}
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
v-for="agent in agents"
|
||||
:key="agent.id"
|
||||
class="px-4 py-4 text-center border-l border-dashed border-subtle"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="admin-checkbox-lg"
|
||||
:checked="user.agent_ids.includes(agent.id)"
|
||||
@change="toggleUserAgentPermission(user, agent.id)"
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-if="rolesConfigured && activeTab === 'roles'" class="space-y-4">
|
||||
<template v-if="rolesConfigured">
|
||||
<div class="admin-table-section admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-4 text-left text-sm">{{ t('admin.permRoles.headers.name') }}</th>
|
||||
<th class="px-6 py-4 text-left text-sm">{{ t('admin.permRoles.headers.description') }}</th>
|
||||
<th class="px-6 py-4 text-left text-sm">{{ t('admin.permRoles.headers.members') }}</th>
|
||||
<th class="px-6 py-4 text-left text-sm">{{ t('admin.permRoles.headers.apps') }}</th>
|
||||
<th class="px-6 py-4 text-right text-sm">{{ t('admin.user.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="role in roles" :key="role.code">
|
||||
<td class="px-6 py-4">
|
||||
<div class="font-medium text-primary">{{ role.name }}</div>
|
||||
<div class="mt-1 flex flex-wrap gap-1.5">
|
||||
<span
|
||||
v-if="role.is_default"
|
||||
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2 py-0.5 text-[11px] text-brand-700"
|
||||
>
|
||||
{{ t('admin.permRoles.badge.default') }}
|
||||
</span>
|
||||
<span
|
||||
v-if="role.is_platform_admin"
|
||||
class="inline-flex items-center gap-1 rounded-full border border-purple-100 bg-purple-50 px-2 py-0.5 text-[11px] text-purple-700"
|
||||
>
|
||||
<Shield class="w-3 h-3" />
|
||||
{{ t('admin.permRoles.badge.admin') }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted max-w-xs">{{ role.description || '-' }}</td>
|
||||
<td class="px-6 py-4">
|
||||
<button
|
||||
v-if="!role.is_platform_admin"
|
||||
type="button"
|
||||
class="text-brand-600 hover:text-brand-800 font-semibold"
|
||||
@click="openMembersPicker(role)"
|
||||
>
|
||||
{{ t('admin.permRoles.memberCount', { count: role.member_count }) }}
|
||||
</button>
|
||||
<span v-else class="text-sm text-muted">
|
||||
{{ t('admin.permRoles.memberCount', { count: role.member_count }) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted">
|
||||
{{
|
||||
role.is_platform_admin
|
||||
? t('admin.permRoles.allApps')
|
||||
: (role.agent_names || []).join('、') || '-'
|
||||
}}
|
||||
</td>
|
||||
<td class="px-6 py-4 text-right whitespace-nowrap">
|
||||
<button
|
||||
type="button"
|
||||
class="text-brand-600 hover:text-brand-900 font-medium text-xs px-3 py-1.5 rounded-lg hover:bg-brand-50"
|
||||
@click="openEditRole(role)"
|
||||
>
|
||||
{{ t('admin.edit') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="!role.is_system && !role.is_platform_admin"
|
||||
type="button"
|
||||
class="text-red-600 hover:text-red-800 font-medium text-xs px-3 py-1.5 rounded-lg hover:bg-red-50"
|
||||
@click="removeRole(role)"
|
||||
>
|
||||
{{ t('admin.delete') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<PaginationBar
|
||||
v-model:page="permissionPage"
|
||||
v-model:page-size="permissionPageSize"
|
||||
:total="permissionTotalRows"
|
||||
:pages="permissionTotalPages"
|
||||
:page-size-options="permissionPageSizeOptions"
|
||||
class="mt-5"
|
||||
/>
|
||||
<template v-if="!rolesConfigured || activeTab === 'matrix'">
|
||||
<p v-if="rolesConfigured" class="text-sm text-muted">{{ t('admin.permRoles.matrixHint') }}</p>
|
||||
<div class="admin-table-filters--inline">
|
||||
<input
|
||||
v-model="permissionFilters.username"
|
||||
:placeholder="t('admin.perm.filterName')"
|
||||
class="admin-table-filter-input w-48"
|
||||
/>
|
||||
<input
|
||||
v-model="permissionFilters.department"
|
||||
:placeholder="t('admin.perm.filterDept')"
|
||||
class="admin-table-filter-input w-48"
|
||||
/>
|
||||
<select v-model="permissionFilters.role" class="admin-table-filter-input w-40">
|
||||
<option value="">{{ t('admin.perm.allRoles') }}</option>
|
||||
<option v-for="role in roles" :key="role.code" :value="role.code">{{ role.name }}</option>
|
||||
<template v-if="!roles.length">
|
||||
<option
|
||||
v-for="option in LEGACY_ROLE_OPTIONS"
|
||||
:key="option.code"
|
||||
:value="option.code"
|
||||
>
|
||||
{{ t(option.i18nKey) }}
|
||||
</option>
|
||||
</template>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-section admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-if="!rolesConfigured" class="px-4 py-4 w-12 text-center sticky left-0 admin-table-sticky-head z-20">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
|
||||
:checked="allUsersSelectedOnPage"
|
||||
@change="toggleAllUsers"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-sm sticky left-0 admin-table-sticky-head z-20 w-56">
|
||||
{{ t('admin.perm.headers.user') }}
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-sm w-36">{{ t('admin.perm.headers.realName') }}</th>
|
||||
<th class="px-6 py-4 text-left text-sm w-40 border-r border-subtle">
|
||||
{{ t('admin.perm.headers.dept') }}
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-sm w-32">{{ t('admin.user.headers.role') }}</th>
|
||||
<th
|
||||
v-for="agent in agents"
|
||||
:key="agent.id"
|
||||
class="px-4 py-4 text-center text-sm min-w-[100px]"
|
||||
>
|
||||
<div class="flex flex-col items-center gap-1">
|
||||
<span>{{ agent.name }}</span>
|
||||
<span class="text-[10px] text-muted font-normal border border-default px-1 rounded">
|
||||
{{ agent.type }}
|
||||
</span>
|
||||
</div>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="user in paginatedUsers" :key="user.id">
|
||||
<td v-if="!rolesConfigured" class="px-4 py-4 text-center sticky left-0 admin-table-sticky-cell z-20">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
|
||||
:checked="selectedUserIds.includes(user.id)"
|
||||
@change="toggleUserSelection(user.id)"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-6 py-4 sticky left-0 admin-table-sticky-cell z-20">
|
||||
<div class="flex items-center gap-3">
|
||||
<div
|
||||
class="w-8 h-8 rounded-full bg-gradient-to-br from-brand-100 to-indigo-100 text-brand-600 flex items-center justify-center font-bold text-sm"
|
||||
>
|
||||
{{ user.username.charAt(0).toUpperCase() }}
|
||||
</div>
|
||||
<div class="font-medium text-primary text-sm truncate max-w-[120px]" :title="user.username">
|
||||
{{ user.username }}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<div class="text-sm text-primary truncate" :title="user.real_name || '-'">
|
||||
{{ user.real_name || '-' }}
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 border-r border-subtle">
|
||||
<div class="text-sm text-muted truncate" :title="user.department">
|
||||
{{ user.department || '-' }}
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-primary">
|
||||
{{ adminRoleLabel(t, user.role, user.role_name) }}
|
||||
</td>
|
||||
<td
|
||||
v-for="agent in agents"
|
||||
:key="agent.id"
|
||||
class="px-4 py-4 text-center border-l border-dashed border-subtle"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="admin-checkbox-lg"
|
||||
:checked="userHasAgent(user, agent.id)"
|
||||
:disabled="rolesConfigured"
|
||||
@change="toggleUserAgentPermission(user, agent.id)"
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<PaginationBar
|
||||
v-model:page="permissionPage"
|
||||
v-model:page-size="permissionPageSize"
|
||||
:total="permissionTotalRows"
|
||||
:pages="permissionTotalPages"
|
||||
:page-size-options="permissionPageSizeOptions"
|
||||
class="mt-5"
|
||||
/>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<BatchPermissionModal
|
||||
@@ -215,5 +360,44 @@ onMounted(() => {
|
||||
@close="closeBatchPermissionModal"
|
||||
@save="submitBatchPermission"
|
||||
/>
|
||||
|
||||
<RoleEditModal
|
||||
:visible="showRoleEditor"
|
||||
:draft="roleDraft"
|
||||
:catalog="catalog"
|
||||
:is-create="!editingExisting"
|
||||
:is-platform-admin="Boolean(roles.find((row) => row.code === roleDraft.code)?.is_platform_admin)"
|
||||
:is-saving="isSaving"
|
||||
@close="closeRoleEditor"
|
||||
@save="requestSaveRole"
|
||||
@update:draft="roleDraft = $event"
|
||||
/>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="showRoleSaveConfirm"
|
||||
:title="t('admin.permRoles.saveConfirm.title')"
|
||||
:message="t('admin.permRoles.saveConfirm.message', { count: editingMemberCount })"
|
||||
:confirm-text="t('admin.save')"
|
||||
confirm-tone="primary"
|
||||
:confirm-loading="isSaving"
|
||||
@confirm="persistRole"
|
||||
/>
|
||||
|
||||
<UserPickerDialog
|
||||
v-model="showPicker"
|
||||
:users="pickerUsers"
|
||||
:selected-ids="pickerSelectedIds"
|
||||
:title="t('admin.permRoles.picker.title', { name: pickerRole?.name || '' })"
|
||||
:subtitle="t('admin.permRoles.picker.subtitle')"
|
||||
@confirm="handlePickerConfirm"
|
||||
/>
|
||||
|
||||
<RoleMembersConfirmDialog
|
||||
:visible="showMembersConfirm"
|
||||
:preview="membersPreview"
|
||||
:is-saving="isSaving"
|
||||
@cancel="cancelMembersConfirm"
|
||||
@confirm="applyMembers"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,436 @@
|
||||
/**
|
||||
* features/admin/modules/permissions/components/RoleEditModal.vue
|
||||
* 用途:新建/编辑权限组:名称、应用入口,以及挂在各应用下的功能权限。
|
||||
* 依赖:permissionRole.types、rolePackage.utils、vue-i18n、lucide-vue-next。
|
||||
* 逻辑:PermissionsPage 打开;应用按对话形态分组;能力默认折叠,点右侧展开后再勾选。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ChevronDown, Search } from 'lucide-vue-next';
|
||||
import type {
|
||||
PermissionRoleCatalog,
|
||||
PermissionRoleCatalogAgent,
|
||||
PermissionRoleCatalogFeature,
|
||||
PermissionRoleDraft,
|
||||
} from '@/features/admin/types/permissionRole.types';
|
||||
import {
|
||||
featuresForAgent,
|
||||
isRoleFeatureVisible,
|
||||
permissionFeatureI18nKey,
|
||||
} from '../utils/rolePackage.utils';
|
||||
|
||||
const MODE_ORDER = ['chat', 'task_chat', 'embedded'] as const;
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
draft: PermissionRoleDraft;
|
||||
catalog: PermissionRoleCatalog;
|
||||
isCreate: boolean;
|
||||
isPlatformAdmin: boolean;
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
save: [];
|
||||
'update:draft': [PermissionRoleDraft];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const appQuery = ref('');
|
||||
const expandedAgentIds = ref<number[]>([]);
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(open) => {
|
||||
if (!open) return;
|
||||
expandedAgentIds.value = [];
|
||||
appQuery.value = '';
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 对话形态文案,与应用管理 `admin.agent.fields.conversationModes` 对齐。
|
||||
*/
|
||||
function conversationModeLabel(mode?: string): string {
|
||||
const code = String(mode || '').trim();
|
||||
if (!code) return '';
|
||||
const key = `admin.agent.fields.conversationModes.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 能力开关文案:优先 i18n,否则用目录 name。
|
||||
*/
|
||||
function featureLabel(feature: PermissionRoleCatalogFeature): string {
|
||||
const i18nKey = permissionFeatureI18nKey(feature.key);
|
||||
return te(i18nKey) ? t(i18nKey) : feature.name || feature.key;
|
||||
}
|
||||
|
||||
/**
|
||||
* 悬停说明:优先 i18n hint,否则用目录 hint。
|
||||
*/
|
||||
function featureHint(feature: PermissionRoleCatalogFeature): string {
|
||||
const i18nKey = `admin.permRoles.featureHints.${String(feature.key || '').replace(/\./g, '_')}`;
|
||||
if (te(i18nKey)) return t(i18nKey);
|
||||
return String(feature.hint || '');
|
||||
}
|
||||
|
||||
function agentSelected(agentId: number): boolean {
|
||||
return props.isPlatformAdmin || props.draft.agent_ids.includes(agentId);
|
||||
}
|
||||
|
||||
function agentFeatures(agent: PermissionRoleCatalogAgent): PermissionRoleCatalogFeature[] {
|
||||
return featuresForAgent(props.catalog.features, agent);
|
||||
}
|
||||
|
||||
function isExpanded(agentId: number): boolean {
|
||||
return expandedAgentIds.value.includes(agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 展开或收起某个应用的功能权限;与是否勾选应用入口无关。
|
||||
*/
|
||||
function toggleExpanded(agentId: number): void {
|
||||
expandedAgentIds.value = isExpanded(agentId)
|
||||
? expandedAgentIds.value.filter((id) => id !== agentId)
|
||||
: [...expandedAgentIds.value, agentId];
|
||||
}
|
||||
|
||||
const selectedCount = computed(() =>
|
||||
props.isPlatformAdmin ? props.catalog.agents.length : props.draft.agent_ids.length,
|
||||
);
|
||||
|
||||
/**
|
||||
* 按对话形态分组;筛选只匹配应用名。
|
||||
*/
|
||||
const groupedAgents = computed(() => {
|
||||
const query = appQuery.value.trim().toLowerCase();
|
||||
const buckets = new Map<string, PermissionRoleCatalogAgent[]>();
|
||||
for (const agent of props.catalog.agents) {
|
||||
if (query && !agent.name.toLowerCase().includes(query)) continue;
|
||||
const mode = String(agent.conversation_mode || 'chat').trim() || 'chat';
|
||||
const list = buckets.get(mode) || [];
|
||||
list.push(agent);
|
||||
buckets.set(mode, list);
|
||||
}
|
||||
const modes = [
|
||||
...MODE_ORDER.filter((mode) => buckets.has(mode)),
|
||||
...[...buckets.keys()].filter((mode) => !MODE_ORDER.includes(mode as (typeof MODE_ORDER)[number])),
|
||||
];
|
||||
return modes.map((mode) => ({
|
||||
mode,
|
||||
label: conversationModeLabel(mode),
|
||||
agents: buckets.get(mode) || [],
|
||||
}));
|
||||
});
|
||||
|
||||
function patch(partial: Partial<PermissionRoleDraft>): void {
|
||||
emit('update:draft', { ...props.draft, ...partial });
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消勾选应用时,清掉只属于该应用的功能权限。
|
||||
*/
|
||||
function toggleAgent(agentId: number): void {
|
||||
if (props.isPlatformAdmin) return;
|
||||
const has = props.draft.agent_ids.includes(agentId);
|
||||
const agent_ids = has
|
||||
? props.draft.agent_ids.filter((id) => id !== agentId)
|
||||
: [...props.draft.agent_ids, agentId];
|
||||
const remaining = props.catalog.agents.filter((agent) => agent_ids.includes(agent.id));
|
||||
const feature_permissions = { ...props.draft.feature_permissions };
|
||||
if (has) {
|
||||
const dropped = props.catalog.agents.find((agent) => agent.id === agentId);
|
||||
if (dropped) {
|
||||
for (const feature of agentFeatures(dropped)) {
|
||||
if (!isRoleFeatureVisible(feature, remaining)) feature_permissions[feature.key] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
patch({ agent_ids, feature_permissions });
|
||||
}
|
||||
|
||||
/**
|
||||
* 勾功能权限时,若应用尚未选中则一并勾上,避免出现有能力无入口。
|
||||
*/
|
||||
function toggleFeature(agent: PermissionRoleCatalogAgent, key: string, checked: boolean): void {
|
||||
const agent_ids =
|
||||
checked && !props.isPlatformAdmin && !props.draft.agent_ids.includes(agent.id)
|
||||
? [...props.draft.agent_ids, agent.id]
|
||||
: props.draft.agent_ids;
|
||||
patch({
|
||||
agent_ids,
|
||||
feature_permissions: {
|
||||
...props.draft.feature_permissions,
|
||||
[key]: checked,
|
||||
},
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in">
|
||||
<div class="admin-modal-panel max-w-3xl max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">
|
||||
{{ isCreate ? t('admin.permRoles.edit.createTitle') : t('admin.permRoles.edit.title') }}
|
||||
</h3>
|
||||
<p class="section-desc mt-1">{{ t('admin.permRoles.edit.subtitle') }}</p>
|
||||
</div>
|
||||
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-1.5">
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
|
||||
{{ t('admin.permRoles.edit.name') }}
|
||||
</label>
|
||||
<input
|
||||
:value="draft.name"
|
||||
type="text"
|
||||
class="w-full border-default rounded-xl px-4 py-3 text-sm"
|
||||
@input="patch({ name: ($event.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="isCreate" class="space-y-1.5">
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
|
||||
{{ t('admin.permRoles.edit.code') }}
|
||||
</label>
|
||||
<input
|
||||
:value="draft.code"
|
||||
type="text"
|
||||
class="w-full border-default rounded-xl px-4 py-3 text-sm"
|
||||
:placeholder="t('admin.permRoles.edit.codeHint')"
|
||||
@input="patch({ code: ($event.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
|
||||
{{ t('admin.permRoles.edit.description') }}
|
||||
</label>
|
||||
<textarea
|
||||
:value="draft.description"
|
||||
rows="2"
|
||||
class="w-full border-default rounded-xl px-4 py-3 text-sm"
|
||||
@input="patch({ description: ($event.target as HTMLTextAreaElement).value })"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<label class="flex items-center gap-2 text-sm text-primary">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="w-4 h-4 rounded text-brand-600"
|
||||
:checked="draft.is_default"
|
||||
:disabled="draft.is_default && !isCreate"
|
||||
@change="patch({ is_default: ($event.target as HTMLInputElement).checked })"
|
||||
/>
|
||||
{{ t('admin.permRoles.edit.isDefault') }}
|
||||
</label>
|
||||
|
||||
<div class="space-y-2">
|
||||
<div class="flex flex-wrap items-end justify-between gap-2">
|
||||
<div>
|
||||
<div class="text-xs font-semibold uppercase tracking-wider text-muted">
|
||||
{{ t('admin.permRoles.edit.apps') }}
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-muted">
|
||||
{{ isPlatformAdmin ? t('admin.permRoles.edit.adminAllApps') : t('admin.permRoles.edit.appsHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<span class="text-xs font-medium text-brand-700">
|
||||
{{ t('admin.permRoles.edit.selectedCount', { count: selectedCount }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="relative">
|
||||
<Search class="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" />
|
||||
<input
|
||||
v-model="appQuery"
|
||||
type="search"
|
||||
class="w-full rounded-xl border-default py-2 pl-9 pr-3 text-sm"
|
||||
:placeholder="t('admin.permRoles.edit.filterPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="role-app-list">
|
||||
<p v-if="!groupedAgents.length" class="px-4 py-8 text-center text-sm text-muted">
|
||||
{{ t('admin.permRoles.edit.noMatch') }}
|
||||
</p>
|
||||
<section v-for="group in groupedAgents" :key="group.mode" class="role-app-group">
|
||||
<h4 class="role-app-group-title">{{ group.label }}</h4>
|
||||
<div
|
||||
v-for="agent in group.agents"
|
||||
:key="agent.id"
|
||||
class="role-app-row"
|
||||
:class="agentSelected(agent.id) ? 'is-on' : ''"
|
||||
>
|
||||
<div class="flex items-center gap-2.5">
|
||||
<label
|
||||
class="flex min-w-0 flex-1 items-center gap-2.5"
|
||||
:class="isPlatformAdmin ? 'cursor-default' : 'cursor-pointer'"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="role-check appearance-none"
|
||||
:checked="agentSelected(agent.id)"
|
||||
:disabled="isPlatformAdmin"
|
||||
@change="toggleAgent(agent.id)"
|
||||
/>
|
||||
<span class="min-w-0 truncate text-sm font-medium text-primary">{{ agent.name }}</span>
|
||||
</label>
|
||||
<button
|
||||
v-if="agentFeatures(agent).length"
|
||||
type="button"
|
||||
class="role-expand"
|
||||
:aria-expanded="isExpanded(agent.id)"
|
||||
@click="toggleExpanded(agent.id)"
|
||||
>
|
||||
{{ t('admin.permRoles.edit.featureCount', { count: agentFeatures(agent).length }) }}
|
||||
<ChevronDown class="h-3.5 w-3.5 transition-transform" :class="isExpanded(agent.id) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="isExpanded(agent.id) && agentFeatures(agent).length" class="role-feat-row">
|
||||
<label
|
||||
v-for="feature in agentFeatures(agent)"
|
||||
:key="feature.key"
|
||||
class="role-feat"
|
||||
:class="draft.feature_permissions[feature.key] ? 'is-on' : ''"
|
||||
:title="featureHint(feature)"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="role-check role-check--sm appearance-none"
|
||||
:checked="Boolean(draft.feature_permissions[feature.key])"
|
||||
@change="toggleFeature(agent, feature.key, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span class="truncate">{{ featureLabel(feature) }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
||||
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
|
||||
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.role-app-list {
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 16px;
|
||||
background: var(--bg-surface);
|
||||
}
|
||||
.role-app-group + .role-app-group {
|
||||
border-top: 1px solid var(--border-subtle);
|
||||
}
|
||||
.role-app-group-title {
|
||||
padding: 10px 14px 4px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-muted);
|
||||
background: var(--bg-surface-soft);
|
||||
}
|
||||
.role-app-row {
|
||||
padding: 9px 14px;
|
||||
}
|
||||
.role-app-row + .role-app-row {
|
||||
border-top: 1px solid var(--border-subtle);
|
||||
}
|
||||
.role-app-row.is-on {
|
||||
background: color-mix(in srgb, var(--status-info-bg) 72%, var(--bg-surface));
|
||||
}
|
||||
.role-app-row:hover {
|
||||
background: var(--bg-surface-soft);
|
||||
}
|
||||
.role-app-row.is-on:hover {
|
||||
background: color-mix(in srgb, var(--status-info-bg) 88%, var(--bg-surface));
|
||||
}
|
||||
.role-feat-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin: 8px 0 2px 28px;
|
||||
}
|
||||
.role-check {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex: none;
|
||||
margin: 0;
|
||||
border: 1.5px solid #64748b;
|
||||
border-radius: 4px;
|
||||
background-color: #fff;
|
||||
background-image: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.role-check:hover:not(:disabled) {
|
||||
border-color: var(--status-info-fg);
|
||||
}
|
||||
.role-check:checked {
|
||||
background: var(--status-info-fg);
|
||||
border-color: var(--status-info-fg);
|
||||
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path fill='none' stroke='white' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round' d='M3.5 8.5l3 3 6-6'/></svg>");
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
background-size: 12px 12px;
|
||||
}
|
||||
.role-check:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.role-check--sm {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
.role-expand {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex: none;
|
||||
padding: 2px 6px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.role-expand:hover {
|
||||
background: var(--bg-surface-strong);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.role-feat {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
max-width: 100%;
|
||||
padding: 3px 8px 3px 6px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 999px;
|
||||
background: var(--bg-surface);
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
cursor: pointer;
|
||||
}
|
||||
.role-feat:hover {
|
||||
border-color: color-mix(in srgb, var(--status-info-fg) 35%, var(--border-default));
|
||||
color: var(--status-info-fg);
|
||||
}
|
||||
.role-feat.is-on {
|
||||
border-color: color-mix(in srgb, var(--status-info-fg) 40%, transparent);
|
||||
background: var(--status-info-bg);
|
||||
color: var(--status-info-fg);
|
||||
}
|
||||
</style>
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* features/admin/modules/permissions/components/RoleMembersConfirmDialog.vue
|
||||
* 用途:选人确定后展示将改入/移出的人及来源角色,确认才写库。
|
||||
* 依赖:permissionRole.types、vue-i18n。
|
||||
* 逻辑:PermissionsPage 在 UserPickerDialog 之后打开;取消不改变成员。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { PermissionRoleMembersPreview, PermissionRolePerson } from '@/features/admin/types/permissionRole.types';
|
||||
|
||||
defineProps<{
|
||||
visible: boolean;
|
||||
preview: PermissionRoleMembersPreview | null;
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
cancel: [];
|
||||
confirm: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
function personLine(person: PermissionRolePerson): string {
|
||||
const name = person.real_name || person.username;
|
||||
const from = person.role_name || person.role;
|
||||
return `${name} · ${from}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible && preview" class="admin-modal-overlay items-center">
|
||||
<div class="admin-modal-panel max-w-lg max-h-[90vh] animate-fade-in-up">
|
||||
<div class="px-8 py-6 border-b border-subtle">
|
||||
<h3 class="text-lg font-bold text-primary">{{ t('admin.permRoles.confirm.title') }}</h3>
|
||||
<p class="text-sm text-muted mt-1">
|
||||
{{ t('admin.permRoles.confirm.subtitle', { name: preview.role_name }) }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="p-8 space-y-4 overflow-y-auto">
|
||||
<div v-if="preview.added.length">
|
||||
<div class="text-xs font-semibold uppercase tracking-wider text-muted mb-2">
|
||||
{{ t('admin.permRoles.confirm.added', { count: preview.added.length }) }}
|
||||
</div>
|
||||
<ul class="space-y-1 text-sm text-primary">
|
||||
<li v-for="person in preview.added" :key="person.id">
|
||||
{{ personLine(person) }}
|
||||
<span
|
||||
v-if="preview.stolen.some((row) => row.id === person.id)"
|
||||
class="ml-1 text-amber-700"
|
||||
>
|
||||
{{ t('admin.permRoles.confirm.stolenHint') }}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div v-if="preview.removed.length">
|
||||
<div class="text-xs font-semibold uppercase tracking-wider text-muted mb-2">
|
||||
{{ t('admin.permRoles.confirm.removed', { count: preview.removed.length }) }}
|
||||
</div>
|
||||
<ul class="space-y-1 text-sm text-primary">
|
||||
<li v-for="person in preview.removed" :key="person.id">{{ personLine(person) }}</li>
|
||||
</ul>
|
||||
<p class="text-xs text-muted mt-2">
|
||||
{{ t('admin.permRoles.confirm.backToDefault') }}
|
||||
</p>
|
||||
</div>
|
||||
<p
|
||||
v-if="!preview.added.length && !preview.removed.length"
|
||||
class="text-sm text-muted"
|
||||
>
|
||||
{{ t('admin.permRoles.confirm.noChanges') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
|
||||
<button type="button" class="btn-ghost" @click="emit('cancel')">{{ t('admin.cancel') }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary disabled:opacity-50"
|
||||
:disabled="isSaving || (!preview.added.length && !preview.removed.length)"
|
||||
@click="emit('confirm')"
|
||||
>
|
||||
{{ isSaving ? t('admin.save') + '...' : t('admin.permRoles.confirm.apply') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+313
-2
@@ -1,15 +1,26 @@
|
||||
/**
|
||||
* features/admin/modules/permissions/composables/usePermissionsAdmin.ts
|
||||
* 用户权限矩阵:筛选、单格切换、批量分配、CSV 导入导出。
|
||||
* 用途:应用权限页:权限组 CRUD/选人确认,以及用户×应用核对矩阵。
|
||||
* 依赖:admin.api、UserPickerDialog 数据、rolePackage.utils、useMessage。
|
||||
* 逻辑:已种子权限组时矩阵只读、禁止按人打勾;未种子时保留历史批量勾选。
|
||||
* 保存角色仅在应用/能力勾选变化时弹出「重写入口」确认。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import * as XLSX from 'xlsx';
|
||||
import {
|
||||
applyAdminPermissionRoleMembers,
|
||||
batchUpdateAdminPermissions,
|
||||
createAdminPermissionRole,
|
||||
deleteAdminPermissionRole,
|
||||
getAdminPermissionRoleCatalog,
|
||||
importAdminPermissions,
|
||||
listAdminAgents,
|
||||
listAdminPermissionRolePickerUsers,
|
||||
listAdminPermissionRoles,
|
||||
listAdminUsers,
|
||||
previewAdminPermissionRoleMembers,
|
||||
updateAdminPermissionRole,
|
||||
updateAdminUserPermissions,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
@@ -19,6 +30,15 @@ import {
|
||||
type PermissionFilters,
|
||||
} from '@/features/admin/types/permission.types';
|
||||
import type { BatchPermissionForm } from '@/features/admin/types/user.types';
|
||||
import {
|
||||
createEmptyRoleDraft,
|
||||
type PermissionRoleCatalog,
|
||||
type PermissionRoleDraft,
|
||||
type PermissionRoleMembersPreview,
|
||||
type PermissionRolePerson,
|
||||
type PermissionRoleRow,
|
||||
} from '@/features/admin/types/permissionRole.types';
|
||||
import { pruneHiddenFeaturePermissions, roleGrantsUnchanged } from '../utils/rolePackage.utils';
|
||||
|
||||
export function usePermissionsAdmin() {
|
||||
const { t } = useI18n();
|
||||
@@ -26,6 +46,9 @@ export function usePermissionsAdmin() {
|
||||
|
||||
const users = ref<AdminUserRow[]>([]);
|
||||
const agents = ref<AdminAgentOption[]>([]);
|
||||
const roles = ref<PermissionRoleRow[]>([]);
|
||||
const catalog = ref<PermissionRoleCatalog>({ agents: [], features: [], default_role_code: 'user' });
|
||||
const pickerUsers = ref<PermissionRolePerson[]>([]);
|
||||
const permissionFilters = ref<PermissionFilters>(createEmptyPermissionFilters());
|
||||
const selectedUserIds = ref<number[]>([]);
|
||||
const isLoading = ref(true);
|
||||
@@ -33,10 +56,29 @@ export function usePermissionsAdmin() {
|
||||
const permissionPage = ref(1);
|
||||
const permissionPageSize = ref(10);
|
||||
const permissionPageSizeOptions = [10, 20, 50, 100];
|
||||
const activeTab = ref<'roles' | 'matrix'>('roles');
|
||||
|
||||
const showBatchPermissionModal = ref(false);
|
||||
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
|
||||
|
||||
const showRoleEditor = ref(false);
|
||||
const editingExisting = ref(false);
|
||||
const roleDraft = ref<PermissionRoleDraft>(createEmptyRoleDraft());
|
||||
const originalRoleGrants = ref<{ agent_ids: number[]; feature_permissions: Record<string, boolean> }>({
|
||||
agent_ids: [],
|
||||
feature_permissions: {},
|
||||
});
|
||||
const editingRoleCode = ref('');
|
||||
const showRoleSaveConfirm = ref(false);
|
||||
|
||||
const pickerRole = ref<PermissionRoleRow | null>(null);
|
||||
const showPicker = ref(false);
|
||||
const pickerSelectedIds = ref<number[]>([]);
|
||||
const membersPreview = ref<PermissionRoleMembersPreview | null>(null);
|
||||
const showMembersConfirm = ref(false);
|
||||
|
||||
const rolesConfigured = computed(() => roles.value.length > 0);
|
||||
|
||||
const activeUsers = computed(() => users.value.filter((u) => u.status !== 'pending'));
|
||||
|
||||
const filteredUsers = computed(() =>
|
||||
@@ -74,6 +116,11 @@ export function usePermissionsAdmin() {
|
||||
return ids.length > 0 && ids.every((id) => selectedUserIds.value.includes(id));
|
||||
});
|
||||
|
||||
const editingMemberCount = computed(() => {
|
||||
const current = roles.value.find((row) => row.code === editingRoleCode.value);
|
||||
return current?.member_count || 0;
|
||||
});
|
||||
|
||||
watch([permissionFilters, permissionPageSize], () => {
|
||||
permissionPage.value = 1;
|
||||
}, { deep: true });
|
||||
@@ -102,9 +149,40 @@ export function usePermissionsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
const loadRoles = async (): Promise<void> => {
|
||||
try {
|
||||
roles.value = await listAdminPermissionRoles();
|
||||
} catch (e) {
|
||||
console.error('Failed to load permission roles', e);
|
||||
roles.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const loadCatalog = async (): Promise<void> => {
|
||||
try {
|
||||
catalog.value = await getAdminPermissionRoleCatalog();
|
||||
} catch (e) {
|
||||
console.error('Failed to load permission role catalog', e);
|
||||
catalog.value = { agents: [], features: [], default_role_code: 'user' };
|
||||
}
|
||||
};
|
||||
|
||||
const loadPickerUsers = async (): Promise<void> => {
|
||||
try {
|
||||
pickerUsers.value = await listAdminPermissionRolePickerUsers();
|
||||
} catch (e) {
|
||||
console.error('Failed to load picker users', e);
|
||||
pickerUsers.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 并行拉取角色包、目录与核对矩阵数据。
|
||||
*/
|
||||
const loadAll = async (): Promise<void> => {
|
||||
isLoading.value = true;
|
||||
await Promise.all([loadUsers(), loadAgents()]);
|
||||
await Promise.all([loadUsers(), loadAgents(), loadRoles(), loadCatalog(), loadPickerUsers()]);
|
||||
activeTab.value = roles.value.length > 0 ? 'roles' : 'matrix';
|
||||
isLoading.value = false;
|
||||
};
|
||||
|
||||
@@ -128,6 +206,10 @@ export function usePermissionsAdmin() {
|
||||
};
|
||||
|
||||
const openBatchPermissionModal = (): void => {
|
||||
if (rolesConfigured.value) {
|
||||
msg.warning(t('admin.permRoles.directGrantDisabled'));
|
||||
return;
|
||||
}
|
||||
if (selectedUserIds.value.length === 0) return;
|
||||
batchPermissionForm.value = { agent_ids: [], action: 'add' };
|
||||
showBatchPermissionModal.value = true;
|
||||
@@ -161,7 +243,11 @@ export function usePermissionsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 核对矩阵单格切换;角色包启用后只读。
|
||||
*/
|
||||
const toggleUserAgentPermission = async (user: AdminUserRow, agentId: number): Promise<void> => {
|
||||
if (rolesConfigured.value) return;
|
||||
const hasPermission = user.agent_ids.includes(agentId);
|
||||
const newAgentIds = hasPermission
|
||||
? user.agent_ids.filter((id) => id !== agentId)
|
||||
@@ -179,11 +265,20 @@ export function usePermissionsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 矩阵格子是否勾选:管理员视为全部应用。
|
||||
*/
|
||||
const userHasAgent = (user: AdminUserRow, agentId: number): boolean => {
|
||||
if (user.is_platform_admin) return true;
|
||||
return user.agent_ids.includes(agentId);
|
||||
};
|
||||
|
||||
const exportPermissions = (): void => {
|
||||
const data = users.value.map((u) => ({
|
||||
Username: u.username,
|
||||
Email: u.email,
|
||||
Role: u.role,
|
||||
RoleName: u.role_name || '',
|
||||
Allowed_Agents: u.agent_ids.join('|'),
|
||||
}));
|
||||
const ws = XLSX.utils.json_to_sheet(data);
|
||||
@@ -193,6 +288,10 @@ export function usePermissionsAdmin() {
|
||||
};
|
||||
|
||||
const importPermissions = async (event: Event): Promise<void> => {
|
||||
if (rolesConfigured.value) {
|
||||
msg.warning(t('admin.permRoles.directGrantDisabled'));
|
||||
return;
|
||||
}
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
@@ -213,9 +312,198 @@ export function usePermissionsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开新建权限组表单。
|
||||
*/
|
||||
const openCreateRole = (): void => {
|
||||
editingExisting.value = false;
|
||||
editingRoleCode.value = '';
|
||||
roleDraft.value = createEmptyRoleDraft();
|
||||
originalRoleGrants.value = { agent_ids: [], feature_permissions: {} };
|
||||
showRoleEditor.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开编辑权限组表单。
|
||||
*/
|
||||
const openEditRole = (role: PermissionRoleRow): void => {
|
||||
editingExisting.value = true;
|
||||
editingRoleCode.value = role.code;
|
||||
roleDraft.value = {
|
||||
code: role.code,
|
||||
name: role.name,
|
||||
description: role.description || '',
|
||||
is_default: role.is_default,
|
||||
agent_ids: [...role.agent_ids],
|
||||
feature_permissions: { ...role.feature_permissions },
|
||||
};
|
||||
originalRoleGrants.value = {
|
||||
agent_ids: [...role.agent_ids],
|
||||
feature_permissions: { ...role.feature_permissions },
|
||||
};
|
||||
showRoleEditor.value = true;
|
||||
};
|
||||
|
||||
const closeRoleEditor = (): void => {
|
||||
showRoleEditor.value = false;
|
||||
showRoleSaveConfirm.value = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 组装当前草稿 payload;保存前裁掉当前不可见的能力(管理员按全部应用可见)。
|
||||
*/
|
||||
const buildRolePayload = (): Record<string, unknown> => {
|
||||
const editingAdmin = Boolean(
|
||||
roles.value.find((row) => row.code === roleDraft.value.code)?.is_platform_admin,
|
||||
);
|
||||
const selectedAgents = editingAdmin
|
||||
? catalog.value.agents
|
||||
: catalog.value.agents.filter((agent) => roleDraft.value.agent_ids.includes(agent.id));
|
||||
return {
|
||||
code: roleDraft.value.code.trim().toLowerCase(),
|
||||
name: roleDraft.value.name.trim(),
|
||||
description: roleDraft.value.description.trim(),
|
||||
is_default: roleDraft.value.is_default,
|
||||
agent_ids: roleDraft.value.agent_ids,
|
||||
feature_permissions: pruneHiddenFeaturePermissions(
|
||||
catalog.value.features,
|
||||
selectedAgents,
|
||||
roleDraft.value.feature_permissions,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 已有成员且应用/能力勾选变化时先确认;只改名称或说明直接保存。
|
||||
*/
|
||||
const requestSaveRole = (): void => {
|
||||
if (!roleDraft.value.name.trim()) {
|
||||
msg.warning(t('admin.permRoles.msg.nameRequired'));
|
||||
return;
|
||||
}
|
||||
if (!editingExisting.value && !/^[a-z][a-z0-9_]{1,62}$/.test(roleDraft.value.code.trim().toLowerCase())) {
|
||||
msg.warning(t('admin.permRoles.msg.codeInvalid'));
|
||||
return;
|
||||
}
|
||||
const payload = buildRolePayload();
|
||||
const grantsChanged = !roleGrantsUnchanged(originalRoleGrants.value, {
|
||||
agent_ids: (payload.agent_ids as number[]) || [],
|
||||
feature_permissions: (payload.feature_permissions as Record<string, boolean>) || {},
|
||||
});
|
||||
if (editingExisting.value && editingMemberCount.value > 0 && grantsChanged) {
|
||||
showRoleSaveConfirm.value = true;
|
||||
return;
|
||||
}
|
||||
void persistRole();
|
||||
};
|
||||
|
||||
const persistRole = async (): Promise<void> => {
|
||||
isSaving.value = true;
|
||||
try {
|
||||
const payload = buildRolePayload();
|
||||
if (editingExisting.value) {
|
||||
await updateAdminPermissionRole(editingRoleCode.value, payload);
|
||||
} else {
|
||||
await createAdminPermissionRole(payload);
|
||||
}
|
||||
showRoleSaveConfirm.value = false;
|
||||
showRoleEditor.value = false;
|
||||
await Promise.all([loadRoles(), loadUsers()]);
|
||||
msg.success(t('admin.permRoles.msg.saved'));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除无人使用的非内置权限组。
|
||||
*/
|
||||
const removeRole = async (role: PermissionRoleRow): Promise<void> => {
|
||||
if (role.is_system || role.is_platform_admin) {
|
||||
msg.warning(t('admin.permRoles.msg.systemLocked'));
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
await deleteAdminPermissionRole(role.code);
|
||||
await loadRoles();
|
||||
msg.success(t('admin.permRoles.msg.deleted'));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 点人数打开选人弹窗;管理员不可从这里改成员。
|
||||
*/
|
||||
const openMembersPicker = (role: PermissionRoleRow): void => {
|
||||
if (role.is_platform_admin) {
|
||||
msg.warning(t('admin.permRoles.msg.adminLocked'));
|
||||
return;
|
||||
}
|
||||
pickerRole.value = role;
|
||||
pickerSelectedIds.value = pickerUsers.value
|
||||
.filter((person) => person.role === role.code)
|
||||
.map((person) => person.id);
|
||||
showPicker.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 选人确定后先预览增减,不直接写库。
|
||||
*/
|
||||
const handlePickerConfirm = async (ids: number[]): Promise<void> => {
|
||||
showPicker.value = false;
|
||||
if (!pickerRole.value) return;
|
||||
isSaving.value = true;
|
||||
try {
|
||||
membersPreview.value = await previewAdminPermissionRoleMembers(pickerRole.value.code, ids);
|
||||
pickerSelectedIds.value = ids;
|
||||
showMembersConfirm.value = true;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const cancelMembersConfirm = (): void => {
|
||||
showMembersConfirm.value = false;
|
||||
membersPreview.value = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认预览后写回成员并刷新人数。
|
||||
*/
|
||||
const applyMembers = async (): Promise<void> => {
|
||||
if (!pickerRole.value) return;
|
||||
isSaving.value = true;
|
||||
try {
|
||||
await applyAdminPermissionRoleMembers(pickerRole.value.code, pickerSelectedIds.value);
|
||||
showMembersConfirm.value = false;
|
||||
membersPreview.value = null;
|
||||
await Promise.all([loadRoles(), loadUsers(), loadPickerUsers()]);
|
||||
msg.success(t('admin.permRoles.msg.membersUpdated'));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
users,
|
||||
agents,
|
||||
roles,
|
||||
catalog,
|
||||
pickerUsers,
|
||||
permissionFilters,
|
||||
selectedUserIds,
|
||||
filteredUsers,
|
||||
@@ -228,8 +516,20 @@ export function usePermissionsAdmin() {
|
||||
allUsersSelectedOnPage,
|
||||
isLoading,
|
||||
isSaving,
|
||||
activeTab,
|
||||
rolesConfigured,
|
||||
showBatchPermissionModal,
|
||||
batchPermissionForm,
|
||||
showRoleEditor,
|
||||
editingExisting,
|
||||
roleDraft,
|
||||
editingMemberCount,
|
||||
showRoleSaveConfirm,
|
||||
pickerRole,
|
||||
showPicker,
|
||||
pickerSelectedIds,
|
||||
membersPreview,
|
||||
showMembersConfirm,
|
||||
loadAll,
|
||||
toggleUserSelection,
|
||||
toggleAllUsers,
|
||||
@@ -237,7 +537,18 @@ export function usePermissionsAdmin() {
|
||||
closeBatchPermissionModal,
|
||||
submitBatchPermission,
|
||||
toggleUserAgentPermission,
|
||||
userHasAgent,
|
||||
exportPermissions,
|
||||
importPermissions,
|
||||
openCreateRole,
|
||||
openEditRole,
|
||||
closeRoleEditor,
|
||||
requestSaveRole,
|
||||
persistRole,
|
||||
removeRole,
|
||||
openMembersPicker,
|
||||
handlePickerConfirm,
|
||||
cancelMembersConfirm,
|
||||
applyMembers,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* features/admin/modules/permissions/utils/rolePackage.utils.test.ts
|
||||
* 用途:角色包能力可见性、按应用归组、隐藏键裁剪,以及名称改动不算改权限。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
featuresForAgent,
|
||||
isRoleFeatureVisible,
|
||||
permissionFeatureI18nKey,
|
||||
pruneHiddenFeaturePermissions,
|
||||
roleGrantsUnchanged,
|
||||
} from './rolePackage.utils';
|
||||
import type { PermissionRoleCatalogAgent, PermissionRoleCatalogFeature } from '@/features/admin/types/permissionRole.types';
|
||||
|
||||
const training: PermissionRoleCatalogFeature = {
|
||||
key: 'training_hr_manage',
|
||||
bind: 'content_profile:training',
|
||||
name: 'HR',
|
||||
};
|
||||
const shipping: PermissionRoleCatalogFeature = {
|
||||
key: 'shipping_notice.audit_sensitive_read',
|
||||
bind: 'agent_code:shipping_notice',
|
||||
name: 'audit',
|
||||
};
|
||||
const shippingCreate: PermissionRoleCatalogFeature = {
|
||||
key: 'shipping_notice_force_create',
|
||||
bind: 'agent_code:shipping_notice',
|
||||
name: 'force',
|
||||
};
|
||||
|
||||
const agents: PermissionRoleCatalogAgent[] = [
|
||||
{ id: 1, name: '入口', agent_code: 'generic', content_profile: 'generic_entrance' },
|
||||
{ id: 2, name: '培训', agent_code: 'training', content_profile: 'training' },
|
||||
{ id: 3, name: '货代', agent_code: 'shipping_notice', content_profile: '' },
|
||||
];
|
||||
|
||||
describe('rolePackage.utils', () => {
|
||||
it('shows training feature only when a training app is selected', () => {
|
||||
expect(isRoleFeatureVisible(training, agents)).toBe(true);
|
||||
expect(isRoleFeatureVisible(training, [agents[0]])).toBe(false);
|
||||
expect(isRoleFeatureVisible(shipping, agents)).toBe(true);
|
||||
expect(isRoleFeatureVisible(shipping, [agents[0]])).toBe(false);
|
||||
});
|
||||
|
||||
it('shows maintenance feature when a maintenance app is selected', () => {
|
||||
const maintenance: PermissionRoleCatalogFeature = {
|
||||
key: 'maintenance.ledger_write',
|
||||
bind: 'kind:maintenance',
|
||||
name: 'ledger',
|
||||
};
|
||||
const maintAgent: PermissionRoleCatalogAgent = {
|
||||
id: 4,
|
||||
name: '设备维保助手',
|
||||
agent_code: 'maintenance',
|
||||
content_profile: '',
|
||||
};
|
||||
expect(isRoleFeatureVisible(maintenance, [maintAgent])).toBe(true);
|
||||
expect(isRoleFeatureVisible(maintenance, [agents[0]])).toBe(false);
|
||||
expect(featuresForAgent([maintenance], maintAgent).map((item) => item.key)).toEqual([
|
||||
'maintenance.ledger_write',
|
||||
]);
|
||||
});
|
||||
|
||||
it('groups in-app features under the matching agent', () => {
|
||||
const catalog = [training, shipping, shippingCreate];
|
||||
expect(featuresForAgent(catalog, agents[0])).toEqual([]);
|
||||
expect(featuresForAgent(catalog, agents[1]).map((item) => item.key)).toEqual(['training_hr_manage']);
|
||||
expect(featuresForAgent(catalog, agents[2]).map((item) => item.key)).toEqual([
|
||||
'shipping_notice.audit_sensitive_read',
|
||||
'shipping_notice_force_create',
|
||||
]);
|
||||
});
|
||||
|
||||
it('maps dotted feature keys for i18n', () => {
|
||||
expect(permissionFeatureI18nKey('shipping_notice.audit_sensitive_read')).toBe(
|
||||
'admin.permRoles.features.shipping_notice_audit_sensitive_read',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops hidden feature ticks on save', () => {
|
||||
const pruned = pruneHiddenFeaturePermissions(
|
||||
[training, shipping],
|
||||
[agents[0]],
|
||||
{
|
||||
training_hr_manage: true,
|
||||
'shipping_notice.audit_sensitive_read': true,
|
||||
},
|
||||
);
|
||||
expect(pruned).toEqual({});
|
||||
});
|
||||
|
||||
it('treats a rename as unchanged grants', () => {
|
||||
expect(
|
||||
roleGrantsUnchanged(
|
||||
{ agent_ids: [1, 2], feature_permissions: { training_hr_manage: true } },
|
||||
{ agent_ids: [2, 1], feature_permissions: { training_hr_manage: true, 'shipping_notice.audit_sensitive_read': false } },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('detects app or feature ticks as grant changes', () => {
|
||||
expect(
|
||||
roleGrantsUnchanged(
|
||||
{ agent_ids: [1], feature_permissions: {} },
|
||||
{ agent_ids: [1, 2], feature_permissions: {} },
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
roleGrantsUnchanged(
|
||||
{ agent_ids: [1], feature_permissions: {} },
|
||||
{ agent_ids: [1], feature_permissions: { training_hr_manage: true } },
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* features/admin/modules/permissions/utils/rolePackage.utils.ts
|
||||
* 用途:角色编辑时按已选应用决定展示哪些应用内能力。
|
||||
* 依赖:permissionRole.types。
|
||||
* 逻辑:与后端 feature_visible_for_agents 对齐(always / content_profile: / agent_code: / kind:);按应用归组短标签;保存前剔除不可见键。
|
||||
*/
|
||||
import type {
|
||||
PermissionRoleCatalogAgent,
|
||||
PermissionRoleCatalogFeature,
|
||||
} from '@/features/admin/types/permissionRole.types';
|
||||
|
||||
/**
|
||||
* 判断应用是否属于种子包中的一类入口,与后端 agent_matches_kind 对齐。
|
||||
* @param agent - 目录中的应用
|
||||
* @param kind - entrance / training / shipping / patent / maintenance
|
||||
*/
|
||||
export function agentMatchesKind(
|
||||
agent: PermissionRoleCatalogAgent,
|
||||
kind: string,
|
||||
): boolean {
|
||||
const code = String(agent.agent_code || '').trim();
|
||||
const name = String(agent.name || '');
|
||||
const profile = String(agent.content_profile || '').trim();
|
||||
if (kind === 'entrance') return profile === 'generic_entrance';
|
||||
if (kind === 'training') return profile === 'training';
|
||||
if (kind === 'shipping') return code === 'shipping_notice';
|
||||
if (kind === 'patent') return name.includes('专利');
|
||||
if (kind === 'maintenance') {
|
||||
return name.includes('维保') || name.includes('维修') || code === 'maintenance';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 已选应用是否展示该能力开关。
|
||||
* @param feature - 目录项(bind=always / content_profile: / agent_code: / kind:)
|
||||
* @param agents - 当前勾选的应用
|
||||
*/
|
||||
export function isRoleFeatureVisible(
|
||||
feature: PermissionRoleCatalogFeature,
|
||||
agents: PermissionRoleCatalogAgent[],
|
||||
): boolean {
|
||||
const bind = String(feature.bind || '');
|
||||
if (bind === 'always') return true;
|
||||
if (bind.startsWith('content_profile:')) {
|
||||
const want = bind.slice('content_profile:'.length);
|
||||
return agents.some((agent) => agent.content_profile === want);
|
||||
}
|
||||
if (bind.startsWith('agent_code:')) {
|
||||
const want = bind.slice('agent_code:'.length);
|
||||
return agents.some((agent) => agent.agent_code === want);
|
||||
}
|
||||
if (bind.startsWith('kind:')) {
|
||||
const want = bind.slice('kind:'.length);
|
||||
return agents.some((agent) => agentMatchesKind(agent, want));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 某个应用自己挂着的功能权限(用于应用卡片内嵌标签)。
|
||||
*/
|
||||
export function featuresForAgent(
|
||||
features: PermissionRoleCatalogFeature[],
|
||||
agent: PermissionRoleCatalogAgent,
|
||||
): PermissionRoleCatalogFeature[] {
|
||||
return features.filter((feature) => isRoleFeatureVisible(feature, [agent]));
|
||||
}
|
||||
|
||||
/**
|
||||
* 能力键转 i18n 路径(点号换成下划线,避免 vue-i18n 当成嵌套路径)。
|
||||
*/
|
||||
export function permissionFeatureI18nKey(featureKey: string): string {
|
||||
return `admin.permRoles.features.${String(featureKey || '').replace(/\./g, '_')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存前只保留当前可见且勾选的能力。
|
||||
*/
|
||||
export function pruneHiddenFeaturePermissions(
|
||||
features: PermissionRoleCatalogFeature[],
|
||||
selectedAgents: PermissionRoleCatalogAgent[],
|
||||
current: Record<string, boolean>,
|
||||
): Record<string, boolean> {
|
||||
const next: Record<string, boolean> = {};
|
||||
for (const feature of features) {
|
||||
if (!isRoleFeatureVisible(feature, selectedAgents)) continue;
|
||||
next[feature.key] = Boolean(current[feature.key]);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开的能力键(值为 true),用于判断权限包是否真的变了。
|
||||
*/
|
||||
export function enabledFeatureKeys(map: Record<string, boolean> | null | undefined): string[] {
|
||||
return Object.keys(map || {})
|
||||
.filter((key) => Boolean(map?.[key]))
|
||||
.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两组应用 id 是否相同(忽略顺序与重复)。
|
||||
*/
|
||||
export function sameAgentIdSet(left: number[], right: number[]): boolean {
|
||||
const a = [...new Set(left.map(Number).filter((id) => Number.isInteger(id) && id > 0))].sort((x, y) => x - y);
|
||||
const b = [...new Set(right.map(Number).filter((id) => Number.isInteger(id) && id > 0))].sort((x, y) => x - y);
|
||||
return a.length === b.length && a.every((id, index) => id === b[index]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 名称/说明改动不算改权限;仅应用勾选或已打开的能力变化才算权限包变更。
|
||||
*/
|
||||
export function roleGrantsUnchanged(
|
||||
original: { agent_ids: number[]; feature_permissions: Record<string, boolean> },
|
||||
next: { agent_ids: number[]; feature_permissions: Record<string, boolean> },
|
||||
): boolean {
|
||||
if (!sameAgentIdSet(original.agent_ids, next.agent_ids)) return false;
|
||||
const before = enabledFeatureKeys(original.feature_permissions).join('|');
|
||||
const after = enabledFeatureKeys(next.feature_permissions).join('|');
|
||||
return before === after;
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/admin/modules/users/UsersPage.vue
|
||||
* 用途:用户管理独立页面(服务端筛选分页、用户/部门列排序、批量操作)。
|
||||
* 依赖:useUsersAdmin、SortableTableHeader、PaginationBar、用户相关 Modal。
|
||||
* 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取,表头排序复用 shared 组件。
|
||||
* 依赖:useUsersAdmin、SortableTableHeader、PaginationBar、用户相关 Modal、adminRoleLabel。
|
||||
* 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取;权限组启用后只选角色、关闭按人授权。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
@@ -11,6 +11,7 @@ import { Edit, Plus, Trash2, Users } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
|
||||
import { adminRoleLabel } from '@/features/admin/utils/roleLabel';
|
||||
import BatchEditUserModal from './components/BatchEditUserModal.vue';
|
||||
import BatchPermissionModal from './components/BatchPermissionModal.vue';
|
||||
import UserFormModal from './components/UserFormModal.vue';
|
||||
@@ -21,6 +22,8 @@ const { t } = useI18n();
|
||||
const {
|
||||
agents,
|
||||
departments,
|
||||
roles,
|
||||
rolesConfigured,
|
||||
isLoading,
|
||||
isListLoading,
|
||||
isSaving,
|
||||
@@ -44,6 +47,8 @@ const {
|
||||
batchPermissionForm,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
showRoleConfirm,
|
||||
roleConfirmMessage,
|
||||
loadAll,
|
||||
toggleSort,
|
||||
openCreateUserModal,
|
||||
@@ -59,6 +64,8 @@ const {
|
||||
submitBatchPermission,
|
||||
closeDeleteConfirm,
|
||||
confirmDelete,
|
||||
confirmRoleChange,
|
||||
closeRoleConfirm,
|
||||
} = useUsersAdmin();
|
||||
|
||||
onMounted(() => {
|
||||
@@ -108,7 +115,7 @@ onMounted(() => {
|
||||
<span>{{ t('admin.user.batchEdit') }} ({{ selectedUserIds.length }})</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="selectedUserIds.length > 0"
|
||||
v-if="selectedUserIds.length > 0 && !rolesConfigured"
|
||||
type="button"
|
||||
class="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition-all shadow-lg shadow-purple-200 active:scale-95 text-sm font-medium"
|
||||
@click="openBatchPermissionModal"
|
||||
@@ -209,21 +216,28 @@ onMounted(() => {
|
||||
<td class="px-6 py-4">
|
||||
<span
|
||||
class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
|
||||
:class="user.role === 'admin'
|
||||
:class="user.is_platform_admin
|
||||
? 'bg-purple-50 text-purple-700 border-purple-100'
|
||||
: user.role === 'hr'
|
||||
? 'bg-emerald-50 text-emerald-700 border-emerald-100'
|
||||
: 'bg-blue-50 text-blue-700 border-blue-100'"
|
||||
: 'bg-blue-50 text-blue-700 border-blue-100'"
|
||||
>
|
||||
{{ t('admin.role.' + user.role) }}
|
||||
{{ adminRoleLabel(t, user.role, user.role_name) }}
|
||||
</span>
|
||||
<div v-if="user.feature_permissions?.training_hr_manage" class="mt-2 flex flex-wrap gap-1.5">
|
||||
<div
|
||||
v-if="user.feature_permissions?.training_hr_manage || user.feature_permissions?.['maintenance.ledger_write']"
|
||||
class="mt-2 flex flex-wrap gap-1.5"
|
||||
>
|
||||
<span
|
||||
v-if="user.feature_permissions?.training_hr_manage"
|
||||
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
|
||||
>
|
||||
{{ t('admin.user.fields.trainingHrManage') }}
|
||||
</span>
|
||||
<span
|
||||
v-if="user.feature_permissions?.['maintenance.ledger_write']"
|
||||
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
|
||||
>
|
||||
{{ t('admin.permRoles.features.maintenance_ledger_write') }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-right">
|
||||
@@ -256,6 +270,8 @@ onMounted(() => {
|
||||
:form="editingUser"
|
||||
:agents="agents"
|
||||
:departments="departments"
|
||||
:roles="roles"
|
||||
:roles-configured="rolesConfigured"
|
||||
:is-saving="isSaving"
|
||||
@close="showUserModal = false"
|
||||
@save="saveUser"
|
||||
@@ -265,6 +281,8 @@ onMounted(() => {
|
||||
:visible="showBatchEditModal"
|
||||
:form="batchEditForm"
|
||||
:departments="departments"
|
||||
:roles="roles"
|
||||
:roles-configured="rolesConfigured"
|
||||
:selected-count="selectedUserIds.length"
|
||||
:is-saving="isSaving"
|
||||
@close="showBatchEditModal = false"
|
||||
@@ -287,5 +305,15 @@ onMounted(() => {
|
||||
@confirm="confirmDelete"
|
||||
@cancel="closeDeleteConfirm"
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
v-model="showRoleConfirm"
|
||||
:title="t('admin.permRoles.userRoleConfirmTitle')"
|
||||
:message="roleConfirmMessage"
|
||||
:confirm-text="t('admin.save')"
|
||||
confirm-tone="primary"
|
||||
:confirm-loading="isSaving"
|
||||
@confirm="confirmRoleChange"
|
||||
@cancel="closeRoleConfirm"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,16 +1,22 @@
|
||||
/**
|
||||
* features/admin/modules/users/components/BatchEditUserModal.vue
|
||||
* 批量编辑用户部门/角色/状态弹窗。
|
||||
* 用途:批量编辑用户部门/角色/状态弹窗。权限组启用后角色下拉读权限组列表。
|
||||
* 依赖:admin.types、permissionRole.types、user.types、roleLabel.LEGACY_ROLE_OPTIONS。
|
||||
* 逻辑:UsersPage 传入角色列表;未选字段表示保持不变。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
||||
import type { PermissionRoleRow } from '@/features/admin/types/permissionRole.types';
|
||||
import type { BatchEditForm } from '@/features/admin/types/user.types';
|
||||
import { LEGACY_ROLE_OPTIONS } from '@/features/admin/utils/roleLabel';
|
||||
|
||||
defineProps<{
|
||||
visible: boolean;
|
||||
form: BatchEditForm;
|
||||
departments: AdminDepartmentRow[];
|
||||
roles: PermissionRoleRow[];
|
||||
rolesConfigured: boolean;
|
||||
selectedCount: number;
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
@@ -36,12 +42,19 @@ const { t } = useI18n();
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.role') }}</label>
|
||||
<select v-model="form.role" class="input-field text-sm">
|
||||
<select v-if="rolesConfigured" v-model="form.role" class="input-field text-sm">
|
||||
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
|
||||
<option value="user">{{ t('admin.role.user') }}</option>
|
||||
<option value="hr">{{ t('admin.role.hr') }}</option>
|
||||
<option value="maintenance_manager">{{ t('admin.role.maintenanceManager') }}</option>
|
||||
<option value="admin">{{ t('admin.role.admin') }}</option>
|
||||
<option v-for="role in roles" :key="role.code" :value="role.code">{{ role.name }}</option>
|
||||
</select>
|
||||
<select v-else v-model="form.role" class="input-field text-sm">
|
||||
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
|
||||
<option
|
||||
v-for="option in LEGACY_ROLE_OPTIONS"
|
||||
:key="option.code"
|
||||
:value="option.code"
|
||||
>
|
||||
{{ t(option.i18nKey) }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
/**
|
||||
* features/admin/modules/users/components/UserFormModal.vue
|
||||
* 创建/编辑用户弹窗,含角色与培训 HR 功能权限勾选。
|
||||
* 用途:创建/编辑用户弹窗。权限组启用后只选角色,不再按人勾应用或功能权限。
|
||||
* 依赖:admin.types、user.types、permissionRole.types、roleLabel.LEGACY_ROLE_OPTIONS。
|
||||
* 逻辑:UsersPage 传入角色列表;未种子权限组时保留历史 Agent / 培训 HR 勾选,角色下拉用旧枚举。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { AdminAgentOption, AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
||||
import type { PermissionRoleRow } from '@/features/admin/types/permissionRole.types';
|
||||
import type { UserFormState } from '@/features/admin/types/user.types';
|
||||
import { LEGACY_ROLE_OPTIONS } from '@/features/admin/utils/roleLabel';
|
||||
|
||||
defineProps<{
|
||||
visible: boolean;
|
||||
form: UserFormState;
|
||||
agents: AdminAgentOption[];
|
||||
departments: AdminDepartmentRow[];
|
||||
roles: PermissionRoleRow[];
|
||||
rolesConfigured: boolean;
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
|
||||
@@ -49,7 +55,7 @@ const { t } = useI18n();
|
||||
</label>
|
||||
<input v-model="form.phone_number" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5 col-span-1 md:col-span-2">
|
||||
<div v-if="!rolesConfigured" class="space-y-1.5 col-span-1 md:col-span-2">
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.allowedAgents') }}</label>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-2">
|
||||
<label
|
||||
@@ -84,15 +90,24 @@ const { t } = useI18n();
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.role') }}</label>
|
||||
<select v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
|
||||
<option value="user">{{ t('admin.role.user') }}</option>
|
||||
<option value="hr">{{ t('admin.role.hr') }}</option>
|
||||
<option value="maintenance_manager">{{ t('admin.role.maintenanceManager') }}</option>
|
||||
<option value="admin">{{ t('admin.role.admin') }}</option>
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
|
||||
<span class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.role') }}
|
||||
</label>
|
||||
<select v-if="rolesConfigured" v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
|
||||
<option v-for="role in roles" :key="role.code" :value="role.code">{{ role.name }}</option>
|
||||
</select>
|
||||
<select v-else v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
|
||||
<option
|
||||
v-for="option in LEGACY_ROLE_OPTIONS"
|
||||
:key="option.code"
|
||||
:value="option.code"
|
||||
>
|
||||
{{ t(option.i18nKey) }}
|
||||
</option>
|
||||
</select>
|
||||
<p v-if="rolesConfigured" class="text-xs text-muted">{{ t('admin.permRoles.userFormHint') }}</p>
|
||||
</div>
|
||||
<div class="space-y-2 rounded-2xl border border-default bg-surface px-4 py-4">
|
||||
<div v-if="!rolesConfigured" class="space-y-2 rounded-2xl border border-default bg-surface px-4 py-4">
|
||||
<div class="text-xs font-semibold uppercase tracking-wider text-muted">{{ t('admin.user.fields.featurePermissions') }}</div>
|
||||
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
|
||||
<input
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* features/admin/modules/users/composables/useUsersAdmin.ts
|
||||
* 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、用户/部门列排序、批量操作)。
|
||||
* 依赖:admin.api、useMessage、useTableSort。
|
||||
* 依赖:admin.api、useMessage、useTableSort、permissionRole.types。
|
||||
* 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取,排序参数随请求下发。
|
||||
* 权限组启用后创建用户预填默认角色,改角色须确认;批量按人授权入口关闭。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -14,12 +15,14 @@ import {
|
||||
createAdminUser,
|
||||
listAdminAgents,
|
||||
listAdminDepartments,
|
||||
listAdminPermissionRoles,
|
||||
listAdminUsersPage,
|
||||
updateAdminUser,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useTableSort } from '@/shared/composables/useTableSort';
|
||||
import type { AdminAgentOption, AdminDepartmentRow, AdminUserRow } from '@/features/admin/types/admin.types';
|
||||
import type { PermissionRoleRow } from '@/features/admin/types/permissionRole.types';
|
||||
import {
|
||||
createEmptyUserFilters,
|
||||
createEmptyUserForm,
|
||||
@@ -42,6 +45,7 @@ export function useUsersAdmin() {
|
||||
const users = ref<AdminUserRow[]>([]);
|
||||
const agents = ref<AdminAgentOption[]>([]);
|
||||
const departments = ref<AdminDepartmentRow[]>([]);
|
||||
const roles = ref<PermissionRoleRow[]>([]);
|
||||
const isLoading = ref(true);
|
||||
const isListLoading = ref(false);
|
||||
const isSaving = ref(false);
|
||||
@@ -63,6 +67,11 @@ export function useUsersAdmin() {
|
||||
|
||||
const showUserModal = ref(false);
|
||||
const editingUser = ref<UserFormState>(createEmptyUserForm());
|
||||
const originalUserRole = ref('user');
|
||||
const showRoleConfirm = ref(false);
|
||||
const roleConfirmMessage = ref('');
|
||||
let pendingUserSave: (() => Promise<void>) | null = null;
|
||||
let pendingBatchSave: (() => Promise<void>) | null = null;
|
||||
|
||||
const showBatchEditModal = ref(false);
|
||||
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
|
||||
@@ -80,6 +89,17 @@ export function useUsersAdmin() {
|
||||
users.value.length > 0
|
||||
&& users.value.every((u) => selectedUserIds.value.includes(u.id)),
|
||||
);
|
||||
const rolesConfigured = computed(() => roles.value.length > 0);
|
||||
const defaultRoleCode = computed(() => roles.value.find((role) => role.is_default)?.code || 'user');
|
||||
|
||||
/**
|
||||
* 该 code 是否对应平台管理组;未种子时回退 admin。
|
||||
*/
|
||||
const isAdminRoleCode = (code: string): boolean => {
|
||||
const row = roles.value.find((role) => role.code === code);
|
||||
if (row) return Boolean(row.is_platform_admin);
|
||||
return code === 'admin';
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取当前页用户(服务端筛选 + 分页 + 排序)。
|
||||
@@ -144,9 +164,18 @@ export function useUsersAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
const loadRoles = async (): Promise<void> => {
|
||||
try {
|
||||
roles.value = await listAdminPermissionRoles();
|
||||
} catch (e) {
|
||||
console.error('Error loading permission roles:', e);
|
||||
roles.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const loadAll = async (): Promise<void> => {
|
||||
isLoading.value = true;
|
||||
await Promise.all([loadUsers(), loadAgents(), loadDepartments()]);
|
||||
await Promise.all([loadUsers(), loadAgents(), loadDepartments(), loadRoles()]);
|
||||
isLoading.value = false;
|
||||
};
|
||||
|
||||
@@ -188,11 +217,13 @@ export function useUsersAdmin() {
|
||||
};
|
||||
|
||||
const openCreateUserModal = (): void => {
|
||||
editingUser.value = createEmptyUserForm();
|
||||
editingUser.value = { ...createEmptyUserForm(), role: defaultRoleCode.value };
|
||||
originalUserRole.value = defaultRoleCode.value;
|
||||
showUserModal.value = true;
|
||||
};
|
||||
|
||||
const openEditUserModal = (user: AdminUserRow): void => {
|
||||
originalUserRole.value = user.role;
|
||||
editingUser.value = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
@@ -256,6 +287,26 @@ export function useUsersAdmin() {
|
||||
}
|
||||
}
|
||||
|
||||
const nextRole = editingUser.value.role;
|
||||
const roleChanged = isCreate
|
||||
? nextRole !== defaultRoleCode.value
|
||||
: nextRole !== originalUserRole.value;
|
||||
const touchesAdmin = isAdminRoleCode(nextRole) || isAdminRoleCode(originalUserRole.value);
|
||||
if (roleChanged) {
|
||||
roleConfirmMessage.value = touchesAdmin
|
||||
? t('admin.permRoles.userAdminConfirm')
|
||||
: t('admin.permRoles.userRoleConfirm', { role: nextRole });
|
||||
pendingUserSave = persistUser;
|
||||
showRoleConfirm.value = true;
|
||||
return;
|
||||
}
|
||||
await persistUser();
|
||||
};
|
||||
|
||||
/**
|
||||
* 真正提交创建/更新用户。
|
||||
*/
|
||||
const persistUser = async (): Promise<void> => {
|
||||
isSaving.value = true;
|
||||
try {
|
||||
if (editingUser.value.id) {
|
||||
@@ -294,6 +345,28 @@ export function useUsersAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认改角色(含管理员)后再提交。
|
||||
*/
|
||||
const confirmRoleChange = async (): Promise<void> => {
|
||||
const userSave = pendingUserSave;
|
||||
const batchSave = pendingBatchSave;
|
||||
pendingUserSave = null;
|
||||
pendingBatchSave = null;
|
||||
showRoleConfirm.value = false;
|
||||
if (userSave) {
|
||||
await userSave();
|
||||
return;
|
||||
}
|
||||
if (batchSave) await batchSave();
|
||||
};
|
||||
|
||||
const closeRoleConfirm = (): void => {
|
||||
pendingUserSave = null;
|
||||
pendingBatchSave = null;
|
||||
showRoleConfirm.value = false;
|
||||
};
|
||||
|
||||
const cleanRejectedUsers = async (): Promise<void> => {
|
||||
openDeleteConfirm(t('admin.user.confirmClean'), async () => {
|
||||
try {
|
||||
@@ -351,22 +424,38 @@ export function useUsersAdmin() {
|
||||
};
|
||||
|
||||
const openBatchPermissionModal = (): void => {
|
||||
if (rolesConfigured.value) {
|
||||
msg.warning(t('admin.permRoles.directGrantDisabled'));
|
||||
return;
|
||||
}
|
||||
if (selectedUserIds.value.length === 0) return;
|
||||
batchPermissionForm.value = { agent_ids: [], action: 'add' };
|
||||
showBatchPermissionModal.value = true;
|
||||
};
|
||||
|
||||
const submitBatchEdit = async (): Promise<void> => {
|
||||
const data: Record<string, string> = {};
|
||||
if (batchEditForm.value.department) data.department = batchEditForm.value.department;
|
||||
if (batchEditForm.value.role) data.role = batchEditForm.value.role;
|
||||
if (batchEditForm.value.status) data.status = batchEditForm.value.status;
|
||||
if (Object.keys(data).length === 0) {
|
||||
msg.warning(t('admin.msg.enterOneField'));
|
||||
return;
|
||||
}
|
||||
if (data.role) {
|
||||
roleConfirmMessage.value = isAdminRoleCode(data.role)
|
||||
? t('admin.permRoles.userAdminConfirm')
|
||||
: t('admin.permRoles.batchRoleConfirm');
|
||||
pendingBatchSave = () => persistBatchEdit(data);
|
||||
showRoleConfirm.value = true;
|
||||
return;
|
||||
}
|
||||
await persistBatchEdit(data);
|
||||
};
|
||||
|
||||
const persistBatchEdit = async (data: Record<string, string>): Promise<void> => {
|
||||
isSaving.value = true;
|
||||
try {
|
||||
const data: Record<string, string> = {};
|
||||
if (batchEditForm.value.department) data.department = batchEditForm.value.department;
|
||||
if (batchEditForm.value.role) data.role = batchEditForm.value.role;
|
||||
if (batchEditForm.value.status) data.status = batchEditForm.value.status;
|
||||
if (Object.keys(data).length === 0) {
|
||||
msg.warning(t('admin.msg.enterOneField'));
|
||||
return;
|
||||
}
|
||||
await batchUpdateAdminUsers(selectedUserIds.value, data);
|
||||
await loadUsers();
|
||||
showBatchEditModal.value = false;
|
||||
@@ -416,6 +505,8 @@ export function useUsersAdmin() {
|
||||
users,
|
||||
agents,
|
||||
departments,
|
||||
roles,
|
||||
rolesConfigured,
|
||||
isLoading,
|
||||
isListLoading,
|
||||
isSaving,
|
||||
@@ -438,6 +529,8 @@ export function useUsersAdmin() {
|
||||
batchPermissionForm,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
showRoleConfirm,
|
||||
roleConfirmMessage,
|
||||
loadAll,
|
||||
toggleSort,
|
||||
openCreateUserModal,
|
||||
@@ -453,5 +546,7 @@ export function useUsersAdmin() {
|
||||
submitBatchPermission,
|
||||
closeDeleteConfirm,
|
||||
confirmDelete,
|
||||
confirmRoleChange,
|
||||
closeRoleConfirm,
|
||||
};
|
||||
}
|
||||
@@ -58,6 +58,8 @@ export interface AdminUserRow {
|
||||
email: string;
|
||||
department?: string;
|
||||
role: string;
|
||||
role_name?: string;
|
||||
is_platform_admin?: boolean;
|
||||
status: string;
|
||||
real_name?: string;
|
||||
employee_id?: string;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* features/admin/types/permissionRole.types.ts
|
||||
* 用途:可配置权限组列表、目录、成员预览的前端类型。
|
||||
* 依赖:shared/types/userPicker.types。
|
||||
* 逻辑:PermissionsPage / UserFormModal / admin.api 共用;成员预览供确认框展示来源角色。
|
||||
*/
|
||||
import type { UserPickerPerson } from '@/shared/types/userPicker.types';
|
||||
|
||||
export interface PermissionRoleRow {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
description: string;
|
||||
is_default: boolean;
|
||||
is_system: boolean;
|
||||
is_platform_admin: boolean;
|
||||
sort_order: number;
|
||||
member_count: number;
|
||||
agent_ids: number[];
|
||||
agent_names: string[];
|
||||
feature_permissions: Record<string, boolean>;
|
||||
}
|
||||
|
||||
export interface PermissionRoleCatalogAgent {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string;
|
||||
agent_code: string;
|
||||
content_profile: string;
|
||||
conversation_mode?: string;
|
||||
}
|
||||
|
||||
export interface PermissionRoleCatalogFeature {
|
||||
key: string;
|
||||
bind: string;
|
||||
name: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export interface PermissionRoleCatalog {
|
||||
agents: PermissionRoleCatalogAgent[];
|
||||
features: PermissionRoleCatalogFeature[];
|
||||
default_role_code: string;
|
||||
}
|
||||
|
||||
export interface PermissionRolePerson extends UserPickerPerson {
|
||||
role: string;
|
||||
role_name: string;
|
||||
}
|
||||
|
||||
export interface PermissionRoleMembersPreview {
|
||||
role_code: string;
|
||||
role_name: string;
|
||||
default_role_code: string;
|
||||
added: PermissionRolePerson[];
|
||||
removed: PermissionRolePerson[];
|
||||
stolen: PermissionRolePerson[];
|
||||
ignored_admin: number;
|
||||
}
|
||||
|
||||
export interface PermissionRoleDraft {
|
||||
code: string;
|
||||
name: string;
|
||||
description: string;
|
||||
is_default: boolean;
|
||||
agent_ids: number[];
|
||||
feature_permissions: Record<string, boolean>;
|
||||
}
|
||||
|
||||
export const createEmptyRoleDraft = (): PermissionRoleDraft => ({
|
||||
code: '',
|
||||
name: '',
|
||||
description: '',
|
||||
is_default: false,
|
||||
agent_ids: [],
|
||||
feature_permissions: {},
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* features/admin/utils/roleLabel.ts
|
||||
* 用途:管理端角色展示名;优先后端 role_name,否则回退已知 code 的 i18n。
|
||||
* 依赖:vue-i18n t()。
|
||||
* 逻辑:UsersPage / PermissionsPage / ApprovalsPage 共用。未种子权限组时的下拉仅 user/hr/admin。
|
||||
*/
|
||||
export const LEGACY_ROLE_OPTIONS = [
|
||||
{ code: 'user', i18nKey: 'admin.role.user' },
|
||||
{ code: 'hr', i18nKey: 'admin.role.hr' },
|
||||
{ code: 'admin', i18nKey: 'admin.role.admin' },
|
||||
] as const;
|
||||
|
||||
const ROLE_I18N_KEYS: Record<string, string> = {
|
||||
user: 'admin.role.user',
|
||||
hr: 'admin.role.hr',
|
||||
admin: 'admin.role.admin',
|
||||
maintenance_manager: 'admin.role.maintenanceManager',
|
||||
rd: 'admin.role.rd',
|
||||
shipping: 'admin.role.shipping',
|
||||
guest: 'admin.role.guest',
|
||||
};
|
||||
|
||||
/**
|
||||
* 把 users.role code 转成界面文案。
|
||||
* @param t - vue-i18n t
|
||||
* @param role - 角色 code
|
||||
* @param roleName - 后端权限组显示名
|
||||
*/
|
||||
export function adminRoleLabel(
|
||||
t: (key: string) => string,
|
||||
role: string,
|
||||
roleName?: string | null,
|
||||
): string {
|
||||
const code = String(role || '').trim();
|
||||
const named = String(roleName || '').trim();
|
||||
if (named && named !== code) return named;
|
||||
const key = ROLE_I18N_KEYS[code];
|
||||
if (key) return t(key);
|
||||
return named || code || '-';
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
saveAuthUser,
|
||||
logoutAuth as logoutAuthStorage,
|
||||
refreshAccessToken as refreshAccessTokenStorage,
|
||||
isPlatformAdminUser,
|
||||
type AuthUser,
|
||||
type FeaturePermissions,
|
||||
} from '@/shared/utils/auth';
|
||||
@@ -29,22 +30,22 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
};
|
||||
|
||||
const isLoggedIn = computed(() => !!user.value && user.value.role !== 'guest');
|
||||
const isAdmin = computed(() => user.value?.role === 'admin');
|
||||
const isAdmin = computed(() => isPlatformAdminUser(user.value));
|
||||
const isGuest = computed(() => user.value?.role === 'guest');
|
||||
const token = computed(() => getAuthToken());
|
||||
|
||||
/**
|
||||
* 判断当前登录用户是否具备指定功能权限。
|
||||
* 核心逻辑:读取登录态 feature_permissions 的显式布尔值;键缺失时回退 false。
|
||||
* 核心逻辑:读登录态 feature_permissions 的显式布尔值;键缺失时平台管理员视为全开(兼容旧会话)。
|
||||
* @param permissionKey - 后端 User.get_feature_permissions 下发的键
|
||||
* @returns 显式为 true 时返回 true
|
||||
* @returns 显式为 true,或键缺失且当前是平台管理员时返回 true
|
||||
*/
|
||||
const hasFeaturePermission = (permissionKey: string): boolean => {
|
||||
const bag = user.value?.feature_permissions;
|
||||
if (bag && Object.prototype.hasOwnProperty.call(bag, permissionKey)) {
|
||||
return Boolean(bag[permissionKey]);
|
||||
}
|
||||
return false;
|
||||
return isPlatformAdminUser(user.value);
|
||||
};
|
||||
|
||||
const login = (nextUser: AuthUser, remember = false): void => {
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
} from 'lucide-vue-next';
|
||||
import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue';
|
||||
import { ExternalSystemLinks } from '@/features/sso';
|
||||
import { isPlatformAdminUser } from '@/shared/utils/auth';
|
||||
import AgentCategoryList from '@/shared/components/AgentCategoryList.vue';
|
||||
import { isHrFocusedAgent, type AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
|
||||
import type { AgentWithCategory } from '@/shared/utils/agent-category.utils';
|
||||
@@ -100,6 +101,8 @@ const onGoAdmin = () => {
|
||||
emit('go-admin');
|
||||
};
|
||||
|
||||
const canOpenAdmin = computed(() => isPlatformAdminUser(props.currentUser as { is_platform_admin?: boolean; role?: string } | null));
|
||||
|
||||
const agentAvatarLabel = computed(() => (isHrFocusedAgent(props.currentAgent) ? 'HR' : 'AI'));
|
||||
|
||||
const userInitial = (fallback: string) => {
|
||||
@@ -352,7 +355,7 @@ const orderExtractionAttentionClass = (item: DisplayHistoryItem) => {
|
||||
<Briefcase class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
v-if="currentUser?.role === 'admin'"
|
||||
v-if="canOpenAdmin"
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center transition-colors hover:text-secondary"
|
||||
:title="$t('admin.title')"
|
||||
|
||||
@@ -19,7 +19,7 @@ import { computed, defineAsyncComponent, provide, ref, watch } from 'vue';
|
||||
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { Maximize2, Minimize2, Loader2 } from 'lucide-vue-next';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
|
||||
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
||||
|
||||
@@ -164,7 +164,13 @@ const embeddedIframeSrc = computed(() => {
|
||||
|
||||
});
|
||||
|
||||
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(page.currentUser?.role || '')));
|
||||
const authStore = useAuthStore();
|
||||
|
||||
/**
|
||||
* 设备维保台账/维修写入口。
|
||||
* 核心逻辑:读登录态 maintenance.ledger_write,不再认 role 字符串。
|
||||
*/
|
||||
const canManageMaintenance = computed(() => authStore.hasFeaturePermission('maintenance.ledger_write'));
|
||||
|
||||
const hideWelcomePanel = computed(() => false);
|
||||
|
||||
|
||||
@@ -58,7 +58,11 @@ const records = computed(() => payload.value?.records || []);
|
||||
const queryMode = computed(() => payload.value?.queryMode === 'records' ? 'records' : 'device');
|
||||
const hasResult = computed(() => Boolean(device.value || records.value.length));
|
||||
const ledgerMatched = computed(() => payload.value?.summary?.ledgerMatched !== false);
|
||||
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(authStore.user?.role || '')));
|
||||
/**
|
||||
* 结果卡上的新增/编辑维修入口。
|
||||
* 核心逻辑:读登录态 maintenance.ledger_write,不再认 role 字符串。
|
||||
*/
|
||||
const canManageMaintenance = computed(() => authStore.hasFeaturePermission('maintenance.ledger_write'));
|
||||
const selectedRecord = ref<MaintenanceRecord | null>(null);
|
||||
|
||||
const deviceStatusLabel = (status?: string | null) => {
|
||||
|
||||
@@ -510,7 +510,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const canForceCreateShippingDuplicate = computed(() => {
|
||||
const user = useAuthStore().user;
|
||||
if (!user) return false;
|
||||
if (String(user.role || '') === 'admin') return true;
|
||||
return Boolean(user.feature_permissions?.shipping_notice_force_create);
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { getStoredAuthUser } from '@/shared/utils/auth';
|
||||
import { getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth';
|
||||
import type {
|
||||
KbDocumentItem,
|
||||
KbJob,
|
||||
@@ -30,9 +30,7 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
|
||||
const router = useRouter();
|
||||
const { t } = useI18n({ useScope: 'global' });
|
||||
|
||||
const isKbAdmin = computed(
|
||||
() => String(getStoredAuthUser()?.role || '').trim().toLowerCase() === 'admin',
|
||||
);
|
||||
const isKbAdmin = computed(() => isPlatformAdminUser(getStoredAuthUser()));
|
||||
|
||||
const isLoading = ref(true);
|
||||
const isDocumentsLoading = ref(false);
|
||||
|
||||
@@ -1,16 +1,31 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/user/views/UserProfilePage.vue
|
||||
* 閻劑鈧棑绱扮仦鏇犮仛閸滃瞼绱潏鎴濈秼閸撳秶鏁ら幋鐤カ閺傛瑣鈧浇顕㈢懛鈧?娑撳顣介崑蹇撱偨閿涘苯鑻熼幓鎰返娣囶喗鏁肩€靛棛鐖滈崗銉ュ經閵? * 娓氭繆绂嗛敍姝秙er-profile.context閵嗕勾ucide 閸ョ偓鐖i妴涔倁e i18n閵? * 闁槒绶敍姘矝閻?/workspace/profile 鐠侯垳鏁遍幍鑳祰閿涘奔绲炬い鐢告桨閸滃奔绗熼崝鈥崇秺鐏?user feature閵? */
|
||||
import { inject } from 'vue';
|
||||
* 用途:个人中心资料展示与编辑、语言/主题偏好、修改密码入口。
|
||||
* 依赖:workspace.context、lucide 图标、vue-i18n、isPlatformAdminUser。
|
||||
* 逻辑:与 /workspace/profile 共用 WORKSPACE_KEY 注入的资料状态,避免与工作台分叉。
|
||||
*/
|
||||
import { computed, inject } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
User, Mail, Building, CreditCard, Globe, Save, Palette,
|
||||
} from 'lucide-vue-next';
|
||||
import { WORKSPACE_KEY } from '@/features/workspace/composables/workspace.context';
|
||||
import { isPlatformAdminUser } from '@/shared/utils/auth';
|
||||
|
||||
// 个人资料与改密状态由工作台 useWorkspaceProfile 编排,经 WORKSPACE_KEY 注入。
|
||||
// 这里复用同一份 ws 上下文(含 profileUser/主题/移动端/登出能力),避免与工作台状态分叉。
|
||||
const userProfile = inject(WORKSPACE_KEY)!;
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 个人中心角色标签。
|
||||
* 核心逻辑:有权限组名称就展示名称;否则按 is_platform_admin 回退内置文案。
|
||||
*/
|
||||
const profileRoleLabel = computed(() => {
|
||||
const user = userProfile.profileUser || {};
|
||||
if (user.role_name) return user.role_name;
|
||||
return isPlatformAdminUser(user) ? t('profile.roleAdmin') : t('profile.roleUser');
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -39,8 +54,8 @@ const userProfile = inject(WORKSPACE_KEY)!;
|
||||
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.department || '-' }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.role') : (userProfile.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User')) }}</div>
|
||||
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User') }}</div>
|
||||
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.role') : profileRoleLabel }}</div>
|
||||
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ profileRoleLabel }}</div>
|
||||
</div>
|
||||
<div :class="userProfile.isMobile ? 'col-span-2' : 'sm:col-span-2'">
|
||||
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'break-all text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.email') : (userProfile.profileUser.email || '-') }}</div>
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* features/workspace/components/WorkspaceSidebar.spec.ts
|
||||
* 用途:验证工作台侧栏「管理控制台」仅对平台管理员露出。
|
||||
* 依赖:Vue Test Utils、vue-router、vue-i18n、workspace.context。
|
||||
* 逻辑:admin 渲染入口并调用 openAdminPanel;普通用户不渲染,避免误点后被守卫踢回。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createMemoryHistory, createRouter } from 'vue-router';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { WORKSPACE_PATHS } from '../constants/routes';
|
||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||
import WorkspaceSidebar from './WorkspaceSidebar.vue';
|
||||
|
||||
vi.mock('../composables/useShippingTodoBadge', () => ({
|
||||
useShippingTodoBadge: () => ({
|
||||
pendingBadge: { value: 0 },
|
||||
startShippingTodoBadgePolling: vi.fn(),
|
||||
stopShippingTodoBadgePolling: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/sso', () => ({
|
||||
ExternalSystemLinks: {
|
||||
name: 'ExternalSystemLinks',
|
||||
template: '<div data-testid="external-system-links" />',
|
||||
},
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
workspace: {
|
||||
brandTitle: 'AI工作台',
|
||||
collapseSidebar: '折叠',
|
||||
expandSidebar: '展开',
|
||||
nav: {
|
||||
profile: '个人中心',
|
||||
admin: '管理控制台',
|
||||
applications: '应用管理',
|
||||
scheduleRuns: '排程记录',
|
||||
receiptReports: '收料文件',
|
||||
shippingNotice: '货代发货',
|
||||
shippingCustomers: '客户主数据',
|
||||
shippingMyTasks: '我的待办',
|
||||
feedback: '意见反馈',
|
||||
updates: '最近更新',
|
||||
knowledgeBase: '知识库',
|
||||
backToChat: '返回聊天',
|
||||
logout: '退出登录',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* 挂载侧栏并注入可观察的工作台上下文。
|
||||
* 核心逻辑:用内存路由承接 RouterLink;按 is_platform_admin 切换 currentUser。
|
||||
*/
|
||||
async function mountSidebar(user: { role: string; is_platform_admin?: boolean }) {
|
||||
const openAdminPanel = vi.fn();
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: WORKSPACE_PATHS.applications, name: 'workspace-applications', component: { template: '<div />' } },
|
||||
{ path: WORKSPACE_PATHS.profile, name: 'workspace-profile', component: { template: '<div />' } },
|
||||
{ path: WORKSPACE_PATHS.scheduleRuns, name: 'workspace-schedule-runs', component: { template: '<div />' } },
|
||||
{ path: WORKSPACE_PATHS.receiptReports, name: 'workspace-receipt-reports', component: { template: '<div />' } },
|
||||
{ path: WORKSPACE_PATHS.feedback, name: 'workspace-feedback', component: { template: '<div />' } },
|
||||
{ path: WORKSPACE_PATHS.updates, name: 'workspace-updates', component: { template: '<div />' } },
|
||||
{ path: WORKSPACE_PATHS.shippingNoticeCustomers, name: 'workspace-shipping-customers', component: { template: '<div />' } },
|
||||
{ path: WORKSPACE_PATHS.shippingNoticeMyTasks, name: 'workspace-shipping-my-tasks', component: { template: '<div />' } },
|
||||
],
|
||||
});
|
||||
await router.push(WORKSPACE_PATHS.applications);
|
||||
await router.isReady();
|
||||
|
||||
const wrapper = mount(WorkspaceSidebar, {
|
||||
global: {
|
||||
plugins: [i18n, router],
|
||||
provide: {
|
||||
[WORKSPACE_KEY as symbol]: {
|
||||
currentUser: {
|
||||
username: 'admin',
|
||||
role: user.role,
|
||||
is_platform_admin: user.is_platform_admin,
|
||||
},
|
||||
router,
|
||||
openAdminPanel,
|
||||
navigateToKnowledgeBase: vi.fn(),
|
||||
navigateToGeneralChat: vi.fn(),
|
||||
handleLogout: vi.fn(),
|
||||
toggleSidebarCollapsed: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { wrapper, openAdminPanel };
|
||||
}
|
||||
|
||||
describe('WorkspaceSidebar admin console entry', () => {
|
||||
it('shows the admin console action for platform admins and opens /admin', async () => {
|
||||
const { wrapper, openAdminPanel } = await mountSidebar({
|
||||
role: 'platform_ops',
|
||||
is_platform_admin: true,
|
||||
});
|
||||
const button = wrapper.get('[data-testid="workspace-nav-admin"]');
|
||||
|
||||
// 平台管理员必须能在「返回聊天」上方看到入口。
|
||||
expect(button.text()).toContain('管理控制台');
|
||||
await button.trigger('click');
|
||||
expect(openAdminPanel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not render the admin console action for ordinary users', async () => {
|
||||
const { wrapper, openAdminPanel } = await mountSidebar({
|
||||
role: 'admin',
|
||||
is_platform_admin: false,
|
||||
});
|
||||
|
||||
// 无权限不渲染,避免点了被守卫踢回应用管理。
|
||||
expect(wrapper.find('[data-testid="workspace-nav-admin"]').exists()).toBe(false);
|
||||
expect(openAdminPanel).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/workspace/components/WorkspaceSidebar.vue
|
||||
* 工作台左侧导航:子路由链接、货代二级菜单、关联服务入口、返回聊天与退出登录。
|
||||
* 工作台左侧导航:子路由链接、货代二级菜单、关联服务入口、管理控制台、返回聊天与退出登录。
|
||||
* 依赖:WORKSPACE_PATHS、workspace.context、ExternalSystemLinks。
|
||||
* 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐。合同付款、立账凭证已迁入 Chat Agent,不再在此展示。
|
||||
* 矮屏时中间导航独立滚动,底部返回聊天/退出登录始终留在视口内。
|
||||
* 逻辑:底部关联服务复用 ws-nav-btn,与管理控制台/返回聊天/退出登录对齐。管理控制台仅平台管理员渲染。
|
||||
* 合同付款、立账凭证已迁入 Chat Agent,不再在此展示。矮屏时中间导航独立滚动,底部操作始终留在视口内。
|
||||
*/
|
||||
import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import {
|
||||
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen,
|
||||
ChevronDown, ChevronRight, ContactRound, Inbox, FileDown,
|
||||
ChevronDown, ChevronRight, ContactRound, Inbox, FileDown, Settings,
|
||||
} from 'lucide-vue-next';
|
||||
import { WORKSPACE_PATHS } from '../constants/routes';
|
||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||
import { isPlatformAdminUser } from '@/shared/utils/auth';
|
||||
import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
|
||||
import { ExternalSystemLinks } from '@/features/sso';
|
||||
|
||||
@@ -25,7 +26,7 @@ const ws = inject(WORKSPACE_KEY)! as any;
|
||||
const route = useRoute();
|
||||
const shippingRouteNames = ['workspace-shipping-customers', 'workspace-shipping-tasks', 'workspace-shipping-my-tasks'] as const;
|
||||
const shippingExpanded = ref(false);
|
||||
const isAdmin = computed(() => String(ws.currentUser?.role || '').trim().toLowerCase() === 'admin');
|
||||
const isAdmin = computed(() => isPlatformAdminUser(ws.currentUser));
|
||||
const { pendingBadge, startShippingTodoBadgePolling, stopShippingTodoBadgePolling } = useShippingTodoBadge();
|
||||
|
||||
const primaryLinkItems = [
|
||||
@@ -214,6 +215,18 @@ onBeforeUnmount(() => {
|
||||
:button-class="collapsed ? 'ws-nav-btn justify-center px-0' : 'ws-nav-btn'"
|
||||
icon-class="h-[18px] w-[18px] shrink-0"
|
||||
/>
|
||||
<button
|
||||
v-if="isAdmin"
|
||||
type="button"
|
||||
data-testid="workspace-nav-admin"
|
||||
class="ws-nav-btn"
|
||||
:class="collapsed ? 'justify-center px-0' : ''"
|
||||
:title="$t('workspace.nav.admin')"
|
||||
@click="ws.openAdminPanel"
|
||||
>
|
||||
<Settings class="h-[18px] w-[18px]" />
|
||||
<span v-if="!collapsed">{{ $t('workspace.nav.admin') }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="ws.navigateToGeneralChat"
|
||||
|
||||
@@ -113,12 +113,18 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
|
||||
id: data.user.id,
|
||||
username: data.user.username,
|
||||
role: data.user.role,
|
||||
role_name: data.user.role_name,
|
||||
is_platform_admin: data.user.is_platform_admin,
|
||||
default_agent_id: data.user.default_agent_id,
|
||||
feature_permissions: data.user.feature_permissions || {},
|
||||
};
|
||||
if (data.user?.feature_permissions && typeof data.user.feature_permissions === 'object') {
|
||||
// 首页刷新把服务端有效权限写回登录态,避免管理员刚授权后必须重新登录。
|
||||
patchStoredAuthUser({ feature_permissions: data.user.feature_permissions });
|
||||
if (data.user && typeof data.user === 'object') {
|
||||
patchStoredAuthUser({
|
||||
role: data.user.role,
|
||||
role_name: data.user.role_name,
|
||||
is_platform_admin: data.user.is_platform_admin,
|
||||
feature_permissions: data.user.feature_permissions || {},
|
||||
});
|
||||
useAuthStore().syncFromStorage();
|
||||
}
|
||||
agents.value = data.agents || [];
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/workspace/composables/useWorkspaceNavigation.ts
|
||||
* 用途:子路由导航、移动端 Tab、聊天跳转、企微 deeplink 与旧 view 参数兼容。
|
||||
* 用途:子路由导航、移动端 Tab、聊天/管理控制台跳转、企微 deeplink 与旧 view 参数兼容。
|
||||
* 依赖:vue-router、config、auth、requestJson、workspace routes/types。
|
||||
* 逻辑:由 useWorkspace 注入;知识库无权限时 toast t('workspace.kb.accessDenied')。
|
||||
* 逻辑:由 useWorkspace 注入;知识库无权限时 toast t('workspace.kb.accessDenied');管理控制台入口由侧栏按管理员角色渲染。
|
||||
*/
|
||||
import { computed, nextTick, ref, watch, type ComputedRef, type Ref } from 'vue';
|
||||
import { config } from '@/config';
|
||||
@@ -138,6 +138,11 @@ export function useWorkspaceNavigation(deps: WorkspaceDeps, options: NavigationO
|
||||
router.push(`/chat/${getLastChatAgentId(DEFAULT_POST_LOGIN_AGENT_ID)}`);
|
||||
};
|
||||
|
||||
/**
|
||||
* 从工作台进入管理控制台。
|
||||
* 核心逻辑:跳转 `/admin`;无管理员权限时由路由守卫静默回应用管理。
|
||||
* 触发时机:侧栏底部「管理控制台」入口(仅平台管理员渲染)。
|
||||
*/
|
||||
const openAdminPanel = () => {
|
||||
router.push('/admin');
|
||||
};
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* 逻辑:从本地登录态恢复 id/username/role/feature_permissions,供工作台侧栏判断专项权限。
|
||||
*/
|
||||
import { computed, type Ref } from 'vue';
|
||||
import { logoutAuth, getStoredAuthUser } from '@/shared/utils/auth';
|
||||
import { logoutAuth, getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth';
|
||||
import { KB_ACCESS_DENIED_MESSAGE } from '../types/workspace.types';
|
||||
import type { WorkspaceUser } from '../types/workspace.types';
|
||||
import type { WorkspaceDeps } from './workspace.deps';
|
||||
@@ -20,9 +20,7 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions
|
||||
const { currentUser } = options;
|
||||
|
||||
const isLoggedIn = computed(() => !!currentUser.value && currentUser.value.role !== 'guest');
|
||||
const hasKnowledgeBaseAccess = computed(
|
||||
() => String(currentUser.value?.role || '').trim().toLowerCase() === 'admin',
|
||||
);
|
||||
const hasKnowledgeBaseAccess = computed(() => isPlatformAdminUser(currentUser.value));
|
||||
|
||||
const loadAuthUser = () => {
|
||||
let stored = localStorage.getItem('hxops_user');
|
||||
@@ -55,6 +53,8 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions
|
||||
id: user.id || 0,
|
||||
username: user.username || '',
|
||||
role: user.role || 'user',
|
||||
role_name: user.role_name,
|
||||
is_platform_admin: user.is_platform_admin,
|
||||
feature_permissions: user.feature_permissions,
|
||||
};
|
||||
} catch {
|
||||
|
||||
@@ -2,14 +2,29 @@
|
||||
/**
|
||||
* features/workspace/pages/ProfilePage.vue
|
||||
* 个人中心:用户资料展示与编辑、语言/主题偏好、修改密码入口。
|
||||
* 依赖:workspace.context、lucide 图标、vue-i18n、isPlatformAdminUser。
|
||||
* 逻辑:角色展示优先用权限组名称;旧会话缺 role_name 时再回退管理员/用户文案。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { computed, inject } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
User, Mail, Building, CreditCard, Globe, Save, Palette,
|
||||
} from 'lucide-vue-next';
|
||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||
import { isPlatformAdminUser } from '@/shared/utils/auth';
|
||||
|
||||
const ws = inject(WORKSPACE_KEY)! as any;
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 个人中心角色标签。
|
||||
* 核心逻辑:有权限组名称就展示名称;否则按 is_platform_admin 回退内置文案。
|
||||
*/
|
||||
const profileRoleLabel = computed(() => {
|
||||
const user = ws.profileUser || {};
|
||||
if (user.role_name) return user.role_name;
|
||||
return isPlatformAdminUser(user) ? t('profile.roleAdmin') : t('profile.roleUser');
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -38,8 +53,8 @@ const ws = inject(WORKSPACE_KEY)! as any;
|
||||
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.department || '-' }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.role') : (ws.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User')) }}</div>
|
||||
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User') }}</div>
|
||||
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.role') : profileRoleLabel }}</div>
|
||||
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ profileRoleLabel }}</div>
|
||||
</div>
|
||||
<div :class="ws.isMobile ? 'col-span-2' : 'sm:col-span-2'">
|
||||
<div :class="ws.isMobile ? 'text-xs text-muted' : 'break-all text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.email') : (ws.profileUser.email || '-') }}</div>
|
||||
|
||||
@@ -13,13 +13,14 @@ import {
|
||||
resendReceiptReportFile, retryReceiptRpaUnit, type ReceiptReportFile, type ReceiptRpaUnit,
|
||||
} from '../api/receipt-report.api';
|
||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||
import { isPlatformAdminUser } from '@/shared/utils/auth';
|
||||
|
||||
const files = ref<ReceiptReportFile[]>([]);
|
||||
const failedUnits = ref<ReceiptRpaUnit[]>([]);
|
||||
const loading = ref(false);
|
||||
const { t } = useI18n();
|
||||
const ws = inject(WORKSPACE_KEY);
|
||||
const isAdmin = computed(() => String(ws?.currentUser?.role || '').trim().toLowerCase() === 'admin');
|
||||
const isAdmin = computed(() => isPlatformAdminUser(ws?.currentUser));
|
||||
|
||||
/** 读取当前用户的收料归档,不在前端补充或推断授权范围。 */
|
||||
async function loadFiles(): Promise<void> {
|
||||
|
||||
@@ -11,6 +11,8 @@ export interface WorkspaceUser {
|
||||
id: number;
|
||||
username: string;
|
||||
role: string;
|
||||
role_name?: string;
|
||||
is_platform_admin?: boolean;
|
||||
default_agent_id?: number | null;
|
||||
feature_permissions?: FeaturePermissions;
|
||||
}
|
||||
@@ -84,6 +86,8 @@ export interface WorkspaceProfileForm {
|
||||
phone_number: string;
|
||||
department: string;
|
||||
role: string;
|
||||
role_name?: string;
|
||||
is_platform_admin?: boolean;
|
||||
employee_id: string;
|
||||
language: string;
|
||||
theme_preference: ThemePreference;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 用途:立账凭证检核任务列表——按资料所属期间(年 + 月)查看批次统计,并展示最近一次检核。
|
||||
* 依赖:voucherCheck.api、vue-i18n、useMessage、DeleteConfirmDialog、PaginationBar、formatLocalDateTime、voucherCheck.display、auth。
|
||||
* Chat 嵌入时由 VoucherCheckChatPanel 传入 embedded / activeTab。
|
||||
* 逻辑:独立路由或 Chat 嵌入;进页默认上一个自然月;「最近一次检核」不跟筛选;强制重检仅 admin,进度在本卡轮询。
|
||||
* 逻辑:独立路由或 Chat 嵌入;进页默认上一个自然月;「最近一次检核」不跟筛选;强制重检仅 is_platform_admin,进度在本卡轮询。
|
||||
* 终态用矮指标格;排队/执行中才展开进度条与当前步骤。Chat 嵌入时隐藏页头与内层 Tab。
|
||||
*/
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
@@ -14,7 +14,7 @@ import { ChevronDown, Download, Loader2, RotateCcw, Search } from 'lucide-vue-ne
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getStoredAuthUser } from '@/shared/utils/auth';
|
||||
import { getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import { WORKSPACE_PATHS } from '../constants/routes';
|
||||
import {
|
||||
@@ -72,7 +72,7 @@ const latestRun = ref<VoucherCheckLatestRun | null>(null);
|
||||
const latestLoading = ref(false);
|
||||
let forcePollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const isAdmin = computed(() => String(getStoredAuthUser()?.role || '').trim().toLowerCase() === 'admin');
|
||||
const isAdmin = computed(() => isPlatformAdminUser(getStoredAuthUser()));
|
||||
const latestInProgress = computed(() => {
|
||||
const cardStatus = latestRun.value?.status;
|
||||
return cardStatus === 'queued' || cardStatus === 'running';
|
||||
|
||||
@@ -1920,6 +1920,97 @@
|
||||
"updateSuccess": "Permissions updated successfully"
|
||||
}
|
||||
},
|
||||
"permRoles": {
|
||||
"subtitle": "Grant apps and in-app features by permission group. Each user has one role.",
|
||||
"create": "New role",
|
||||
"tabs": {
|
||||
"roles": "Roles",
|
||||
"matrix": "Access matrix"
|
||||
},
|
||||
"headers": {
|
||||
"name": "Role",
|
||||
"description": "Description",
|
||||
"members": "Members",
|
||||
"apps": "Apps"
|
||||
},
|
||||
"memberCount": "{count} members",
|
||||
"allApps": "All apps (implicit)",
|
||||
"badge": {
|
||||
"default": "Default",
|
||||
"admin": "Admin"
|
||||
},
|
||||
"matrixHint": "The matrix is read-only. Change access by editing a role or its members.",
|
||||
"directGrantDisabled": "Per-user app ticks are disabled. Grant apps on a role, then adjust members.",
|
||||
"useRolePage": "Use App Permissions to grant apps on a role. Per-user assignment is disabled.",
|
||||
"userFormHint": "App access comes from this role. Department is only a filter.",
|
||||
"userRoleConfirmTitle": "Confirm role change",
|
||||
"userRoleConfirm": "Move this user to the selected role? Their apps will be rewritten immediately.",
|
||||
"userAdminConfirm": "Change admin membership? The people picker cannot add or remove admins; this form will rewrite access immediately.",
|
||||
"batchRoleConfirm": "Change roles for the selected users? Their apps will be rewritten from the new role.",
|
||||
"edit": {
|
||||
"title": "Edit role",
|
||||
"createTitle": "New role",
|
||||
"subtitle": "Saving applies immediately to everyone in this role.",
|
||||
"code": "Code",
|
||||
"codeHint": "Start with a lowercase letter; letters, digits and underscore only",
|
||||
"name": "Name",
|
||||
"description": "Description",
|
||||
"isDefault": "Default role for new users",
|
||||
"apps": "Apps",
|
||||
"appsHint": "Tick an app for access. Apps with features: open “N features” on the right, then tick them.",
|
||||
"adminAllApps": "Admins get every app implicitly; you can still tighten features below.",
|
||||
"features": "Feature permissions",
|
||||
"selectedCount": "{count} selected",
|
||||
"featureCount": "{count} features",
|
||||
"filterPlaceholder": "Filter apps",
|
||||
"noMatch": "No matching apps"
|
||||
},
|
||||
"confirm": {
|
||||
"title": "Confirm member changes",
|
||||
"subtitle": "The following people will be moved into “{name}”.",
|
||||
"added": "Add {count}",
|
||||
"removed": "Remove {count}",
|
||||
"stolenHint": "will lose their current role access",
|
||||
"backToDefault": "Unchecked people return to the default role.",
|
||||
"noChanges": "Selection matches current members. Nothing to confirm.",
|
||||
"apply": "Confirm"
|
||||
},
|
||||
"picker": {
|
||||
"title": "Choose members of “{name}”",
|
||||
"subtitle": "Departments only filter the list. Select all is a draft; you still confirm after OK."
|
||||
},
|
||||
"saveConfirm": {
|
||||
"title": "Save role",
|
||||
"message": "This role has {count} members. Saving will rewrite their app access immediately."
|
||||
},
|
||||
"msg": {
|
||||
"nameRequired": "Role name is required",
|
||||
"codeInvalid": "Code must start with a lowercase letter and use letters, digits or underscore",
|
||||
"saved": "Role saved",
|
||||
"deleted": "Role deleted",
|
||||
"systemLocked": "Built-in roles cannot be deleted",
|
||||
"adminLocked": "Change admins in user management with an extra confirmation",
|
||||
"membersUpdated": "Members updated"
|
||||
},
|
||||
"features": {
|
||||
"training_hr_manage": "HR management",
|
||||
"shipping_notice_force_create": "Force-create duplicate orders",
|
||||
"shipping_notice_audit_sensitive_read": "Read sensitive audit",
|
||||
"shipping_notice_xfa_split_rule_edit": "Edit XFA split rules",
|
||||
"shipping_notice_xfa_split_rule_preview": "Preview split",
|
||||
"shipping_notice_xfa_split_rule_publish": "Publish split rules",
|
||||
"maintenance_ledger_write": "Ledger and repair maintenance"
|
||||
},
|
||||
"featureHints": {
|
||||
"training_hr_manage": "View stats, filter records, and export Excel",
|
||||
"shipping_notice_force_create": "Skip duplicate blocking and create a new shipping notice",
|
||||
"shipping_notice_audit_sensitive_read": "View before / after / Diff text",
|
||||
"shipping_notice_xfa_split_rule_edit": "Maintain field split rules",
|
||||
"shipping_notice_xfa_split_rule_preview": "Preview split results",
|
||||
"shipping_notice_xfa_split_rule_publish": "Review and publish rules",
|
||||
"maintenance_ledger_write": "Maintain device ledger and repair records"
|
||||
}
|
||||
},
|
||||
"request": {
|
||||
"title": "Permission Requests",
|
||||
"subtitle": "Review user requests for agent access",
|
||||
@@ -2792,10 +2883,12 @@
|
||||
}
|
||||
},
|
||||
"role": {
|
||||
"user": "User",
|
||||
"hr": "HR",
|
||||
"maintenanceManager": "Maintenance Admin",
|
||||
"user": "Standard user",
|
||||
"hr": "Training HR",
|
||||
"maintenanceManager": "Maintenance specialist",
|
||||
"admin": "Admin",
|
||||
"rd": "R&D apps",
|
||||
"shipping": "Shipping specialist",
|
||||
"guest": "Guest"
|
||||
},
|
||||
"status": {
|
||||
|
||||
@@ -233,6 +233,19 @@
|
||||
"USER_EMPLOYEE_ID_EXISTS": "Employee ID already exists.",
|
||||
"USER_PHONE_EXISTS": "Phone number already exists.",
|
||||
"USER_UNIQUENESS_CONFLICT": "Data uniqueness conflict.",
|
||||
"ROLE.DIRECT_GRANT_DISABLED": "App access is granted by permission role; per-user ticks are disabled.",
|
||||
"ROLE.NOT_FOUND": "Permission role not found.",
|
||||
"ROLE.CODE_INVALID": "Invalid role code.",
|
||||
"ROLE.CODE_RESERVED": "Cannot create another admin role.",
|
||||
"ROLE.CODE_EXISTS": "Role code already exists.",
|
||||
"ROLE.NAME_REQUIRED": "Role name is required.",
|
||||
"ROLE.SORT_INVALID": "Invalid sort order.",
|
||||
"ROLE.DEFAULT_REQUIRED": "Keep at least one default role.",
|
||||
"ROLE.SYSTEM_LOCKED": "Built-in roles cannot be deleted.",
|
||||
"ROLE.HAS_MEMBERS": "Role still has members and cannot be deleted.",
|
||||
"ROLE.ADMIN_LOCKED": "Admin members cannot be changed here.",
|
||||
"ROLE.REQUIRED": "Please select a role.",
|
||||
"ROLE.LAST_ADMIN": "Cannot demote the last admin.",
|
||||
"SYSTEM_INTERNAL_ERROR": "Internal server error. Please try again later.",
|
||||
"AGENT_HANDLER_NOT_CONFIGURED": "Agent business handler is not configured. Please contact an administrator.",
|
||||
"AGENT_RUNTIME_CAPABILITY_NOT_DECLARED": "This application type does not declare the requested background business capability.",
|
||||
|
||||
@@ -1924,6 +1924,97 @@
|
||||
"updateSuccess": "อัปเดตสิทธิ์สำเร็จ"
|
||||
}
|
||||
},
|
||||
"permRoles": {
|
||||
"subtitle": "กำหนดแอปและความสามารถในแอปตามกลุ่มสิทธิ์ ผู้ใช้แต่ละคนมีได้บทบาทเดียว",
|
||||
"create": "สร้างกลุ่มสิทธิ์",
|
||||
"tabs": {
|
||||
"roles": "ตั้งค่าบทบาท",
|
||||
"matrix": "ตรวจสอบสิทธิ์"
|
||||
},
|
||||
"headers": {
|
||||
"name": "กลุ่มสิทธิ์",
|
||||
"description": "คำอธิบาย",
|
||||
"members": "สมาชิก",
|
||||
"apps": "แอป"
|
||||
},
|
||||
"memberCount": "{count} คน",
|
||||
"allApps": "แอปทั้งหมด (โดยปริยาย)",
|
||||
"badge": {
|
||||
"default": "ค่าเริ่มต้น",
|
||||
"admin": "ผู้ดูแลระบบ"
|
||||
},
|
||||
"matrixHint": "ตารางนี้เป็นแบบอ่านอย่างเดียว เปลี่ยนสิทธิ์โดยแก้ไขบทบาทหรือสมาชิก",
|
||||
"directGrantDisabled": "ปิดการติ๊กแอปรายคนแล้ว ให้ติ๊กแอปบนบทบาทแล้วปรับสมาชิก",
|
||||
"useRolePage": "ไปที่หน้าสิทธิ์แอปเพื่อให้สิทธิ์ตามบทบาท ไม่ต้องกำหนดรายคน",
|
||||
"userFormHint": "สิทธิ์แอปมาจากบทบาทนี้ แผนกใช้กรองรายชื่อเท่านั้น",
|
||||
"userRoleConfirmTitle": "ยืนยันการเปลี่ยนบทบาท",
|
||||
"userRoleConfirm": "ย้ายผู้ใช้นี้ไปยังกลุ่มสิทธิ์ที่เลือกหรือไม่ แอปที่ใช้ได้จะถูกเขียนใหม่ทันที",
|
||||
"userAdminConfirm": "ยืนยันการเปลี่ยนสถานะผู้ดูแลระบบ? หน้าต่างเลือกคนเพิ่มหรือนำผู้ดูแลออกไม่ได้ แบบฟอร์มนี้จะเขียนสิทธิ์ทันที",
|
||||
"batchRoleConfirm": "ยืนยันเปลี่ยนบทบาทเป็นชุดหรือไม่ แอปของผู้ใช้เหล่านี้จะถูกเขียนใหม่ตามกลุ่มใหม่",
|
||||
"edit": {
|
||||
"title": "แก้ไขกลุ่มสิทธิ์",
|
||||
"createTitle": "สร้างกลุ่มสิทธิ์",
|
||||
"subtitle": "เมื่อบันทึกจะมีผลกับสมาชิกทุกคนทันที",
|
||||
"code": "รหัส",
|
||||
"codeHint": "ขึ้นต้นด้วยตัวพิมพ์เล็ก ใช้ได้เฉพาะตัวอักษร ตัวเลข และขีดล่าง",
|
||||
"name": "ชื่อ",
|
||||
"description": "คำอธิบาย",
|
||||
"isDefault": "บทบาทเริ่มต้นสำหรับผู้ใช้ใหม่",
|
||||
"apps": "แอปที่ใช้ได้",
|
||||
"appsHint": "ติ๊กแอปเพื่อให้สิทธิ์เข้า แอปที่มีสิทธิ์ฟังก์ชันให้กด “N สิทธิ์” ด้านขวาก่อนแล้วค่อยติ๊ก",
|
||||
"adminAllApps": "ผู้ดูแลระบบเข้าแอปได้ทั้งหมดโดยปริยาย ยังจำกัดสิทธิ์ฟังก์ชันด้านล่างได้",
|
||||
"features": "สิทธิ์ฟังก์ชัน",
|
||||
"selectedCount": "เลือกแล้ว {count}",
|
||||
"featureCount": "{count} สิทธิ์",
|
||||
"filterPlaceholder": "กรองแอป",
|
||||
"noMatch": "ไม่พบแอปที่ตรงกัน"
|
||||
},
|
||||
"confirm": {
|
||||
"title": "ยืนยันการปรับสมาชิก",
|
||||
"subtitle": "จะย้ายรายชื่อต่อไปนี้เข้า “{name}”",
|
||||
"added": "เพิ่ม {count} คน",
|
||||
"removed": "นำออก {count} คน",
|
||||
"stolenHint": "จะเสียสิทธิ์ของบทบาทเดิม",
|
||||
"backToDefault": "คนที่เอาติ๊กออกจะกลับไปกลุ่มสิทธิ์เริ่มต้น",
|
||||
"noChanges": "รายการตรงกับสมาชิกปัจจุบัน ไม่มีการเปลี่ยนแปลง",
|
||||
"apply": "ยืนยัน"
|
||||
},
|
||||
"picker": {
|
||||
"title": "เลือกสมาชิก “{name}”",
|
||||
"subtitle": "แผนกด้านซ้ายใช้กรองเท่านั้น เลือกทั้งหมดเป็นแบบร่าง ยังต้องยืนยันหลังกดตกลง"
|
||||
},
|
||||
"saveConfirm": {
|
||||
"title": "บันทึกกลุ่มสิทธิ์",
|
||||
"message": "กลุ่มนี้มี {count} คน การบันทึกจะเขียนสิทธิ์แอปใหม่ทันที"
|
||||
},
|
||||
"msg": {
|
||||
"nameRequired": "กรุณากรอกชื่อกลุ่มสิทธิ์",
|
||||
"codeInvalid": "รหัสต้องขึ้นต้นด้วยตัวพิมพ์เล็ก และใช้ได้เฉพาะตัวอักษร ตัวเลข หรือขีดล่าง",
|
||||
"saved": "บันทึกกลุ่มสิทธิ์แล้ว",
|
||||
"deleted": "ลบกลุ่มสิทธิ์แล้ว",
|
||||
"systemLocked": "ไม่สามารถลบบทบาทในระบบได้",
|
||||
"adminLocked": "ปรับผู้ดูแลระบบในหน้าผู้ใช้พร้อมยืนยันเพิ่มเติม",
|
||||
"membersUpdated": "อัปเดตสมาชิกแล้ว"
|
||||
},
|
||||
"features": {
|
||||
"training_hr_manage": "การจัดการ HR",
|
||||
"shipping_notice_force_create": "บังคับสร้างเอกสารซ้ำ",
|
||||
"shipping_notice_audit_sensitive_read": "อ่านงานตรวจสอบที่ละเอียดอ่อน",
|
||||
"shipping_notice_xfa_split_rule_edit": "แก้ไขกฎแยก XFA",
|
||||
"shipping_notice_xfa_split_rule_preview": "ดูตัวอย่างการแยก",
|
||||
"shipping_notice_xfa_split_rule_publish": "เผยแพร่กฎแยก",
|
||||
"maintenance_ledger_write": "ดูแลบัญชีอุปกรณ์และงานซ่อม"
|
||||
},
|
||||
"featureHints": {
|
||||
"training_hr_manage": "ดูสถิติ กรองรายการ และส่งออก Excel",
|
||||
"shipping_notice_force_create": "ข้ามการกันเอกสารซ้ำ แล้วสร้างใบแจ้งส่งสินค้าใหม่",
|
||||
"shipping_notice_audit_sensitive_read": "ดูข้อความ before / after / Diff",
|
||||
"shipping_notice_xfa_split_rule_edit": "ดูแลกฎแยกฟิลด์",
|
||||
"shipping_notice_xfa_split_rule_preview": "ดูตัวอย่างผลการแยก",
|
||||
"shipping_notice_xfa_split_rule_publish": "ตรวจทานและเผยแพร่กฎ",
|
||||
"maintenance_ledger_write": "ดูแลบัญชีอุปกรณ์และบันทึกการซ่อม"
|
||||
}
|
||||
},
|
||||
"request": {
|
||||
"title": "คำขอสิทธิ์",
|
||||
"subtitle": "ตรวจสอบคำขอเข้าถึงตัวแทนของผู้ใช้",
|
||||
@@ -2662,9 +2753,11 @@
|
||||
},
|
||||
"role": {
|
||||
"user": "ผู้ใช้ทั่วไป",
|
||||
"hr": "HR",
|
||||
"maintenanceManager": "ผู้ดูแลซ่อมบำรุง",
|
||||
"hr": "HR อบรม",
|
||||
"maintenanceManager": "ผู้เชี่ยวชาญซ่อมบำรุง",
|
||||
"admin": "ผู้ดูแลระบบ",
|
||||
"rd": "แอปงานวิจัย",
|
||||
"shipping": "เจ้าหน้าที่ชิปปิ้ง",
|
||||
"guest": "ผู้เยี่ยมชม"
|
||||
},
|
||||
"status": {
|
||||
|
||||
@@ -233,6 +233,19 @@
|
||||
"USER_EMPLOYEE_ID_EXISTS": "รหัสพนักงานนี้มีอยู่แล้ว",
|
||||
"USER_PHONE_EXISTS": "หมายเลขโทรศัพท์นี้มีอยู่แล้ว",
|
||||
"USER_UNIQUENESS_CONFLICT": "ข้อมูลซ้ำกัน",
|
||||
"ROLE.DIRECT_GRANT_DISABLED": "สิทธิ์แอปกำหนดตามกลุ่มแล้ว ไม่สามารถติ๊กทีละคนได้",
|
||||
"ROLE.NOT_FOUND": "ไม่พบกลุ่มสิทธิ์",
|
||||
"ROLE.CODE_INVALID": "รหัสบทบาทไม่ถูกต้อง",
|
||||
"ROLE.CODE_RESERVED": "ไม่สามารถสร้างบทบาทผู้ดูแลระบบเพิ่มได้",
|
||||
"ROLE.CODE_EXISTS": "รหัสบทบาทนี้มีอยู่แล้ว",
|
||||
"ROLE.NAME_REQUIRED": "กรุณากรอกชื่อกลุ่มสิทธิ์",
|
||||
"ROLE.SORT_INVALID": "ลำดับไม่ถูกต้อง",
|
||||
"ROLE.DEFAULT_REQUIRED": "ต้องมีกลุ่มสิทธิ์เริ่มต้นอย่างน้อยหนึ่งกลุ่ม",
|
||||
"ROLE.SYSTEM_LOCKED": "ไม่สามารถลบบทบาทในระบบได้",
|
||||
"ROLE.HAS_MEMBERS": "กลุ่มสิทธิ์ยังมีสมาชิก ลบไม่ได้",
|
||||
"ROLE.ADMIN_LOCKED": "ไม่สามารถปรับผู้ดูแลระบบที่นี่",
|
||||
"ROLE.REQUIRED": "กรุณาเลือกกลุ่มสิทธิ์",
|
||||
"ROLE.LAST_ADMIN": "ไม่สามารถลดระดับผู้ดูแลระบบคนสุดท้ายได้",
|
||||
"SYSTEM_INTERNAL_ERROR": "เซิร์ฟเวอร์ขัดข้อง กรุณาลองใหม่ภายหลัง",
|
||||
"AGENT_HANDLER_NOT_CONFIGURED": "ยังไม่ได้กำหนด Agent handler กรุณาติดต่อผู้ดูแลระบบ",
|
||||
"AGENT_RUNTIME_CAPABILITY_NOT_DECLARED": "ประเภทแอปพลิเคชันนี้ไม่ได้ประกาศความสามารถทางธุรกิจเบื้องหลังที่ร้องขอ",
|
||||
|
||||
@@ -86,7 +86,7 @@
|
||||
"wecomEntryNotice": "เปิดมาจากข้อความ WeCom และเตรียมบริบทที่เกี่ยวข้องไว้ให้แล้ว",
|
||||
"nav": {
|
||||
"profile": "โปรไฟล์",
|
||||
"admin": "คอนโซลผู้ดูแล",
|
||||
"admin": "คอนโซลผู้ดูแลระบบ",
|
||||
"applications": "แอปพลิเคชัน",
|
||||
"knowledgeBase": "คลังความรู้",
|
||||
"scheduleRuns": "บันทึกตารางงาน",
|
||||
|
||||
@@ -2053,6 +2053,97 @@
|
||||
"updateSuccess": "权限更新成功"
|
||||
}
|
||||
},
|
||||
"permRoles": {
|
||||
"subtitle": "按权限组配置可用应用与应用内能力;每位用户只选一个角色。",
|
||||
"create": "新建权限组",
|
||||
"tabs": {
|
||||
"roles": "角色配置",
|
||||
"matrix": "权限核对"
|
||||
},
|
||||
"headers": {
|
||||
"name": "权限组",
|
||||
"description": "说明",
|
||||
"members": "人数",
|
||||
"apps": "应用"
|
||||
},
|
||||
"memberCount": "{count} 人",
|
||||
"allApps": "全部应用(隐式)",
|
||||
"badge": {
|
||||
"default": "默认",
|
||||
"admin": "管理员"
|
||||
},
|
||||
"matrixHint": "矩阵只读,用于核对;改权限请编辑角色或调整成员。",
|
||||
"directGrantDisabled": "已改为按权限组授权,请在角色配置里勾应用或调整成员。",
|
||||
"useRolePage": "请到「应用权限」按角色勾选应用,不再按人授权。",
|
||||
"userFormHint": "应用入口与应用内能力来自该角色,部门只用于筛选。",
|
||||
"userRoleConfirmTitle": "确认调整角色",
|
||||
"userRoleConfirm": "确认把该用户调整到所选权限组?其可用应用将立即按该组重写。",
|
||||
"userAdminConfirm": "确认调整管理员身份?选人弹窗不能添加或移出管理员,此处将立即改写其权限。",
|
||||
"batchRoleConfirm": "确认批量改角色?这些人的可用应用将立即按新权限组重写。",
|
||||
"edit": {
|
||||
"title": "编辑权限组",
|
||||
"createTitle": "新建权限组",
|
||||
"subtitle": "保存后立即对该组全部成员生效。",
|
||||
"code": "编码",
|
||||
"codeHint": "小写字母开头,仅字母数字下划线",
|
||||
"name": "名称",
|
||||
"description": "说明",
|
||||
"isDefault": "新建用户默认角色",
|
||||
"apps": "可用应用",
|
||||
"appsHint": "勾选应用即开通入口。有功能权限的应用点右侧「N 项能力」展开后再勾选。",
|
||||
"adminAllApps": "管理员应用入口隐式全开;仍可收紧下方功能权限。",
|
||||
"features": "功能权限",
|
||||
"selectedCount": "已选 {count}",
|
||||
"featureCount": "{count} 项能力",
|
||||
"filterPlaceholder": "筛选应用",
|
||||
"noMatch": "没有匹配的应用"
|
||||
},
|
||||
"confirm": {
|
||||
"title": "确认调整成员",
|
||||
"subtitle": "将把下列人员改入「{name}」。",
|
||||
"added": "改入 {count} 人",
|
||||
"removed": "移出 {count} 人",
|
||||
"stolenHint": "将失去原角色权限",
|
||||
"backToDefault": "取消勾选的人将回到默认权限组。",
|
||||
"noChanges": "勾选与当前成员相同,没有需要确认的变更。",
|
||||
"apply": "确认调整"
|
||||
},
|
||||
"picker": {
|
||||
"title": "选择「{name}」成员",
|
||||
"subtitle": "左侧部门只用于筛选。全选只勾草稿,确定后仍会弹出确认。"
|
||||
},
|
||||
"saveConfirm": {
|
||||
"title": "保存权限组",
|
||||
"message": "该组现有 {count} 人,保存后其应用入口将立即按新勾选重写。"
|
||||
},
|
||||
"msg": {
|
||||
"nameRequired": "请填写权限组名称",
|
||||
"codeInvalid": "编码须为小写字母开头的字母数字下划线",
|
||||
"saved": "权限组已保存",
|
||||
"deleted": "权限组已删除",
|
||||
"systemLocked": "内置权限组不能删除",
|
||||
"adminLocked": "管理员成员请在用户管理中单独调整并确认",
|
||||
"membersUpdated": "成员已更新"
|
||||
},
|
||||
"features": {
|
||||
"training_hr_manage": "HR 管理",
|
||||
"shipping_notice_force_create": "强制新建重复单据",
|
||||
"shipping_notice_audit_sensitive_read": "读取敏感审计",
|
||||
"shipping_notice_xfa_split_rule_edit": "编辑 XFA 拆分规则",
|
||||
"shipping_notice_xfa_split_rule_preview": "预览拆分",
|
||||
"shipping_notice_xfa_split_rule_publish": "发布拆分规则",
|
||||
"maintenance_ledger_write": "台账与维修维护"
|
||||
},
|
||||
"featureHints": {
|
||||
"training_hr_manage": "查看统计、筛选记录并导出 Excel",
|
||||
"shipping_notice_force_create": "跳过重复拦截,新建发货通知",
|
||||
"shipping_notice_audit_sensitive_read": "查看 before / after / Diff 正文",
|
||||
"shipping_notice_xfa_split_rule_edit": "维护字段拆分规则",
|
||||
"shipping_notice_xfa_split_rule_preview": "预览拆分结果",
|
||||
"shipping_notice_xfa_split_rule_publish": "审核并发布规则",
|
||||
"maintenance_ledger_write": "维护设备台账与维修记录"
|
||||
}
|
||||
},
|
||||
"request": {
|
||||
"title": "权限申请",
|
||||
"subtitle": "审核用户对应用的访问申请",
|
||||
@@ -2905,9 +2996,11 @@
|
||||
},
|
||||
"role": {
|
||||
"user": "普通用户",
|
||||
"hr": "HR",
|
||||
"maintenanceManager": "维保管理员",
|
||||
"hr": "培训 HR",
|
||||
"maintenanceManager": "设备维保专员",
|
||||
"admin": "管理员",
|
||||
"rd": "研发应用",
|
||||
"shipping": "货代专员",
|
||||
"guest": "访客"
|
||||
},
|
||||
"status": {
|
||||
|
||||
@@ -233,6 +233,19 @@
|
||||
"USER_EMPLOYEE_ID_EXISTS": "工号已存在。",
|
||||
"USER_PHONE_EXISTS": "手机号已存在。",
|
||||
"USER_UNIQUENESS_CONFLICT": "数据唯一性冲突。",
|
||||
"ROLE.DIRECT_GRANT_DISABLED": "已改为按权限组授权,不能再按人勾选应用。",
|
||||
"ROLE.NOT_FOUND": "权限组不存在。",
|
||||
"ROLE.CODE_INVALID": "权限组编码无效。",
|
||||
"ROLE.CODE_RESERVED": "不能再创建管理员角色。",
|
||||
"ROLE.CODE_EXISTS": "权限组编码已存在。",
|
||||
"ROLE.NAME_REQUIRED": "请填写权限组名称。",
|
||||
"ROLE.SORT_INVALID": "排序值无效。",
|
||||
"ROLE.DEFAULT_REQUIRED": "必须保留一个默认权限组。",
|
||||
"ROLE.SYSTEM_LOCKED": "内置权限组不能删除。",
|
||||
"ROLE.HAS_MEMBERS": "权限组仍有成员,不能删除。",
|
||||
"ROLE.ADMIN_LOCKED": "不能在此处调整管理员。",
|
||||
"ROLE.REQUIRED": "请选择权限组。",
|
||||
"ROLE.LAST_ADMIN": "不能撤掉最后一名管理员。",
|
||||
"SYSTEM_INTERNAL_ERROR": "服务器内部错误,请稍后重试。",
|
||||
"AGENT_HANDLER_NOT_CONFIGURED": "应用业务 Handler 未配置,请联系管理员。",
|
||||
"AGENT_RUNTIME_CAPABILITY_NOT_DECLARED": "当前应用类型未声明该后台业务能力。",
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
},
|
||||
"nav": {
|
||||
"profile": "个人中心",
|
||||
"admin": "管理后台",
|
||||
"admin": "管理控制台",
|
||||
"applications": "应用管理",
|
||||
"knowledgeBase": "知识库",
|
||||
"scheduleRuns": "排程记录",
|
||||
|
||||
@@ -1929,6 +1929,97 @@
|
||||
"updateSuccess": "權限更新成功"
|
||||
}
|
||||
},
|
||||
"permRoles": {
|
||||
"subtitle": "依權限組設定可用應用與應用內能力;每位使用者只選一個角色。",
|
||||
"create": "新增權限組",
|
||||
"tabs": {
|
||||
"roles": "角色設定",
|
||||
"matrix": "權限核對"
|
||||
},
|
||||
"headers": {
|
||||
"name": "權限組",
|
||||
"description": "說明",
|
||||
"members": "人數",
|
||||
"apps": "應用"
|
||||
},
|
||||
"memberCount": "{count} 人",
|
||||
"allApps": "全部應用(隱含)",
|
||||
"badge": {
|
||||
"default": "預設",
|
||||
"admin": "管理員"
|
||||
},
|
||||
"matrixHint": "矩陣唯讀,僅供核對;請編輯角色或調整成員來改權限。",
|
||||
"directGrantDisabled": "已改為依權限組授權,請在角色設定勾選應用或調整成員。",
|
||||
"useRolePage": "請到「應用權限」依角色勾選應用,不再依人授權。",
|
||||
"userFormHint": "應用入口與應用內能力來自此角色,部門只用於篩選。",
|
||||
"userRoleConfirmTitle": "確認調整角色",
|
||||
"userRoleConfirm": "確認將此使用者調整到所選權限組?其可用應用會立即依該組重寫。",
|
||||
"userAdminConfirm": "確認調整管理員身分?選人視窗不能新增或移出管理員,此處會立即改寫權限。",
|
||||
"batchRoleConfirm": "確認批次改角色?這些人的可用應用會立即依新權限組重寫。",
|
||||
"edit": {
|
||||
"title": "編輯權限組",
|
||||
"createTitle": "新增權限組",
|
||||
"subtitle": "儲存後立即對該組全部成員生效。",
|
||||
"code": "編碼",
|
||||
"codeHint": "小寫字母開頭,僅字母數字底線",
|
||||
"name": "名稱",
|
||||
"description": "說明",
|
||||
"isDefault": "新使用者預設角色",
|
||||
"apps": "可用應用",
|
||||
"appsHint": "勾選應用即開通入口。有功能權限的應用點右側「N 項能力」展開後再勾選。",
|
||||
"adminAllApps": "管理員應用入口隱含全開;仍可收緊下方功能權限。",
|
||||
"features": "功能權限",
|
||||
"selectedCount": "已選 {count}",
|
||||
"featureCount": "{count} 項能力",
|
||||
"filterPlaceholder": "篩選應用",
|
||||
"noMatch": "沒有符合的應用"
|
||||
},
|
||||
"confirm": {
|
||||
"title": "確認調整成員",
|
||||
"subtitle": "將把下列人員改入「{name}」。",
|
||||
"added": "改入 {count} 人",
|
||||
"removed": "移出 {count} 人",
|
||||
"stolenHint": "將失去原角色權限",
|
||||
"backToDefault": "取消勾選的人會回到預設權限組。",
|
||||
"noChanges": "勾選與目前成員相同,沒有需要確認的變更。",
|
||||
"apply": "確認調整"
|
||||
},
|
||||
"picker": {
|
||||
"title": "選擇「{name}」成員",
|
||||
"subtitle": "左側部門只用於篩選。全選只勾草稿,確定後仍會跳出確認。"
|
||||
},
|
||||
"saveConfirm": {
|
||||
"title": "儲存權限組",
|
||||
"message": "該組現有 {count} 人,儲存後其應用入口會立即依新勾選重寫。"
|
||||
},
|
||||
"msg": {
|
||||
"nameRequired": "請填寫權限組名稱",
|
||||
"codeInvalid": "編碼須為小寫字母開頭的字母數字底線",
|
||||
"saved": "權限組已儲存",
|
||||
"deleted": "權限組已刪除",
|
||||
"systemLocked": "內建權限組不能刪除",
|
||||
"adminLocked": "管理員成員請在使用者管理中單獨調整並確認",
|
||||
"membersUpdated": "成員已更新"
|
||||
},
|
||||
"features": {
|
||||
"training_hr_manage": "HR 管理",
|
||||
"shipping_notice_force_create": "強制新建重複單據",
|
||||
"shipping_notice_audit_sensitive_read": "讀取敏感稽核",
|
||||
"shipping_notice_xfa_split_rule_edit": "編輯 XFA 拆分規則",
|
||||
"shipping_notice_xfa_split_rule_preview": "預覽拆分",
|
||||
"shipping_notice_xfa_split_rule_publish": "發佈拆分規則",
|
||||
"maintenance_ledger_write": "台帳與維修維護"
|
||||
},
|
||||
"featureHints": {
|
||||
"training_hr_manage": "查看統計、篩選紀錄並匯出 Excel",
|
||||
"shipping_notice_force_create": "略過重複攔截,新建發貨通知",
|
||||
"shipping_notice_audit_sensitive_read": "查看 before / after / Diff 正文",
|
||||
"shipping_notice_xfa_split_rule_edit": "維護欄位拆分規則",
|
||||
"shipping_notice_xfa_split_rule_preview": "預覽拆分結果",
|
||||
"shipping_notice_xfa_split_rule_publish": "審核並發佈規則",
|
||||
"maintenance_ledger_write": "維護設備台帳與維修紀錄"
|
||||
}
|
||||
},
|
||||
"request": {
|
||||
"title": "權限申請",
|
||||
"subtitle": "審核用戶對應用的訪問申請",
|
||||
@@ -2667,9 +2758,11 @@
|
||||
},
|
||||
"role": {
|
||||
"user": "普通用戶",
|
||||
"hr": "HR",
|
||||
"maintenanceManager": "維保管理員",
|
||||
"hr": "培訓 HR",
|
||||
"maintenanceManager": "設備維保專員",
|
||||
"admin": "管理員",
|
||||
"rd": "研發應用",
|
||||
"shipping": "貨代專員",
|
||||
"guest": "訪客"
|
||||
},
|
||||
"status": {
|
||||
|
||||
@@ -233,6 +233,19 @@
|
||||
"USER_EMPLOYEE_ID_EXISTS": "工號已存在。",
|
||||
"USER_PHONE_EXISTS": "手機號已存在。",
|
||||
"USER_UNIQUENESS_CONFLICT": "數據唯一性衝突。",
|
||||
"ROLE.DIRECT_GRANT_DISABLED": "已改為依權限組授權,不能再依人勾選應用。",
|
||||
"ROLE.NOT_FOUND": "權限組不存在。",
|
||||
"ROLE.CODE_INVALID": "權限組編碼無效。",
|
||||
"ROLE.CODE_RESERVED": "不能再建立管理員角色。",
|
||||
"ROLE.CODE_EXISTS": "權限組編碼已存在。",
|
||||
"ROLE.NAME_REQUIRED": "請填寫權限組名稱。",
|
||||
"ROLE.SORT_INVALID": "排序值無效。",
|
||||
"ROLE.DEFAULT_REQUIRED": "必須保留一個預設權限組。",
|
||||
"ROLE.SYSTEM_LOCKED": "內建權限組不能刪除。",
|
||||
"ROLE.HAS_MEMBERS": "權限組仍有成員,不能刪除。",
|
||||
"ROLE.ADMIN_LOCKED": "不能在此處調整管理員。",
|
||||
"ROLE.REQUIRED": "請選擇權限組。",
|
||||
"ROLE.LAST_ADMIN": "不能撤掉最後一名管理員。",
|
||||
"SYSTEM_INTERNAL_ERROR": "伺服器內部錯誤,請稍後重試。",
|
||||
"AGENT_HANDLER_NOT_CONFIGURED": "應用業務 Handler 未配置,請聯絡管理員。",
|
||||
"AGENT_RUNTIME_CAPABILITY_NOT_DECLARED": "目前應用類型未宣告此後台業務能力。",
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
},
|
||||
"nav": {
|
||||
"profile": "個人中心",
|
||||
"admin": "管理後台",
|
||||
"admin": "管理控制台",
|
||||
"applications": "應用管理",
|
||||
"knowledgeBase": "知識庫",
|
||||
"scheduleRuns": "排程記錄",
|
||||
|
||||
@@ -15,6 +15,8 @@ export interface AuthUser {
|
||||
real_name?: string;
|
||||
employee_id?: string;
|
||||
role?: string;
|
||||
role_name?: string;
|
||||
is_platform_admin?: boolean;
|
||||
feature_permissions?: FeaturePermissions;
|
||||
token?: string;
|
||||
access_token?: string;
|
||||
@@ -23,6 +25,17 @@ export interface AuthUser {
|
||||
token_expires_at?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否平台管理员。优先读后端 is_platform_admin;旧登录态缺字段时回退 role=admin。
|
||||
*/
|
||||
export function isPlatformAdminUser(
|
||||
user?: { is_platform_admin?: boolean; role?: string } | null,
|
||||
): boolean {
|
||||
if (!user) return false;
|
||||
if (typeof user.is_platform_admin === 'boolean') return user.is_platform_admin;
|
||||
return String(user.role || '').trim().toLowerCase() === 'admin';
|
||||
}
|
||||
|
||||
interface StoredAuthPayload {
|
||||
user?: AuthUser;
|
||||
expiry?: number;
|
||||
|
||||
Reference in new issue
Block a user