Merge branch 'role' into dev
Co-authored-by: Cursor <cursoragent@cursor.com> # Conflicts: # backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py # backend/app/services/voucher_check/schedule_seed.py # docs/features/shipping-notice/technical.md # docs/tec.md # frontend/src/features/user/views/UserProfilePage.vue
This commit is contained in:
commit
bb7e0977b8
94 files changed
+4493
-388
No files matched your search
@@ -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]:
|
||||
"""
|
||||
解析告警接收人。
|
||||
核心逻辑:优先 FREIGHT_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。
|
||||
核心逻辑:优先 FREIGHT_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的平台管理员。
|
||||
"""
|
||||
raw = str(current_app.config.get("FREIGHT_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 FREIGHT_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)、销货放行单拉取(周二 05:30)默认 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,
|
||||
@@ -116,14 +117,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
|
||||
@@ -178,16 +172,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(
|
||||
|
||||
Reference in new issue
Block a user