Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	frontend/src/features/user/views/UserProfilePage.vue
This commit is contained in:
HTEWJ\26070045 committed 2026-09-23 14:34:20 +08:00
commit 5faf86b184
691 files changed
+55948 -17728

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ from app.services.admin.training_exam_pdf_service import parse_training_question
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
from app.services.agent_registry.catalog_loader import get_dify_required_providers
from app.services.agent_registry.serialization import serialize_agent_for_admin
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
def serialize_agent(agent: Agent) -> dict:
+1 -1
View File
@@ -14,7 +14,7 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import AgentGuide
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
GUIDE_USAGE_GENERAL = 'general'
@@ -1,8 +1,8 @@
"""
backend/app/services/admin/permission_service.py
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
依赖:models、wecom_notify.send_wecom_event_message。
用途:用户 Agent 权限批量/单用户更新业务逻辑。
依赖:models、integrations.wecom.notify.send_wecom_event_message。
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。
"""
from __future__ import annotations
@@ -12,7 +12,7 @@ from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, User
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
@@ -95,67 +95,3 @@ def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
user.agents = agents
db.session.commit()
return {'status': 'ok'}
def list_permission_requests() -> list[dict]:
"""返回全部权限申请(按 created_at 降序)。"""
reqs = (
db.session.query(PermissionRequest)
.order_by(PermissionRequest.created_at.desc())
.all()
)
return [serialize_permission_request(r) for r in reqs]
def approve_permission_request(request_id: int) -> dict:
"""
批准权限申请:更新状态并将 Agent 加入用户权限。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
req.status = 'approved'
req.reviewed_at = datetime.utcnow()
if user and agent and (agent not in user.agents):
user.agents.append(agent)
if user and user.wecom_userid:
send_wecom_event_message(
event_type='permission_request_approved',
user=user,
title='权限申请已通过',
content=f'你申请的应用权限已通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}
def reject_permission_request(request_id: int) -> dict:
"""
拒绝权限申请并通知用户(若已绑定企微)。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
req.status = 'rejected'
req.reviewed_at = datetime.utcnow()
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
if user and user.wecom_userid:
send_wecom_event_message(
event_type='permission_request_rejected',
user=user,
title='权限申请未通过',
content=f'你申请的应用权限未通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}
@@ -153,13 +153,7 @@ def _customer_row_validation(raw: dict[str, Any], *, default_source_system: str)
if status not in {'active', 'inactive'}:
errors.append({'code': 'SHIPPING.CUSTOMER_STATUS_INVALID', 'field': 'status'})
existing_ref = _existing_customer_by_ref(source_system, legacy_key) if legacy_key and source_system else None
code_owner = db.session.query(ShippingCustomer).filter_by(short_code=short_code).first() if short_code else None
if code_owner and (not existing_ref or code_owner.id != existing_ref.id):
warnings.append({
'code': 'SHIPPING.CUSTOMER_IMPORT_SHORT_CODE_CONFLICT',
'customer_id': code_owner.id,
'short_code': short_code,
})
# 客户简码允许重复(业务规则),导入预检不再因简码撞码产生 warning。
normalized_name = normalize_customer_name(name)
similar = [
item for item in db.session.query(ShippingCustomer).all()
@@ -37,6 +37,47 @@ from app.services.shipping_notice.customer_normalization import (
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
_ODM_ID_MAX_ITEMS = 100
_ODM_ID_MAX_LENGTH = 64
def _normalize_odm_ids(value: Any) -> list[str] | None:
"""
规范化客户 ODM ID 清单:逐项 trim、去空、去重(保持原顺序)。
Args:
value: 前端提交的清单(字符串列表);None 表示未提交,空列表表示清空。
Returns:
规范化后的清单;None 仅当输入为 None。
Raises:
ValidationError: 条目超长或清单超量。
"""
if value is None:
return None
if not isinstance(value, list):
raise ValidationError(
'ODM ID list must be an array of strings',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
normalized: list[str] = []
for item in value:
text = str(item or '').strip()
if not text:
continue
if len(text) > _ODM_ID_MAX_LENGTH:
raise ValidationError(
'ODM ID is too long',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
details={'odm_id': text},
)
if text not in normalized:
normalized.append(text)
if len(normalized) > _ODM_ID_MAX_ITEMS:
raise ValidationError(
'Too many ODM IDs',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
return normalized
def _record_lifecycle_event(
@@ -142,6 +183,7 @@ def serialize_customer(
'status': record.status,
'merged_into_customer_id': record.merged_into_customer_id,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
'created_by_id': record.created_by_id,
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
@@ -278,23 +320,12 @@ def get_customer(customer_id: int) -> dict[str, Any]:
return serialize_customer(record, include_identifiers=True)
def _assert_short_code_available(short_code: str, *, exclude_customer_id: int | None = None) -> None:
"""校验客户简码全局唯一。"""
query = db.session.query(ShippingCustomer.id).filter(ShippingCustomer.short_code == short_code)
if exclude_customer_id is not None:
query = query.filter(ShippingCustomer.id != exclude_customer_id)
if query.first():
raise ConflictError(
'Customer short code already exists',
code='SHIPPING.CUSTOMER_SHORT_CODE_EXISTS',
details={'short_code': short_code},
)
def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
创建标准客户。
客户简码允许重复(业务规则),仅做格式归一化,不做唯一性校验。
Args:
data: standard_name、short_code、status、remark。
actor_id: 当前管理员 ID。
@@ -309,7 +340,6 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
details={'field': 'standard_name'},
)
short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(short_code)
status = clean_text(data.get('status') or 'active').lower()
if status not in CUSTOMER_STATUSES - {'merged'}:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
@@ -318,6 +348,7 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
short_code=short_code,
status=status,
remark=clean_text(data.get('remark')) or None,
odm_ids=_normalize_odm_ids(data.get('odm_ids')) if 'odm_ids' in data else None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
@@ -385,11 +416,13 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
}
next_name = before['standard_name']
next_short_code = before['short_code']
next_status = before['status']
next_remark = before['remark']
next_odm_ids = before['odm_ids']
if 'standard_name' in data:
name = clean_text(data.get('standard_name'))
if not name:
@@ -397,18 +430,20 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
next_name = name
if 'short_code' in data:
next_short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(next_short_code, exclude_customer_id=customer_id)
if 'status' in data:
next_status = clean_text(data.get('status')).lower()
if next_status not in CUSTOMER_STATUSES - {'merged'}:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
if 'remark' in data:
next_remark = clean_text(data.get('remark')) or None
if 'odm_ids' in data:
next_odm_ids = _normalize_odm_ids(data.get('odm_ids'))
after = {
'standard_name': next_name,
'short_code': next_short_code,
'status': next_status,
'remark': next_remark,
'odm_ids': next_odm_ids,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
@@ -418,6 +453,7 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
record.short_code = next_short_code
record.status = next_status
record.remark = next_remark
record.odm_ids = next_odm_ids
record.updated_by_id = actor_id
_record_lifecycle_event(
record,
@@ -67,19 +67,6 @@ def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
return dict(value)
def _json_string_list(data: dict[str, Any], field: str) -> list[str]:
"""读取非空、去重的字符串列表,供 Source 别名等业务配置使用。"""
value = data.get(field, [])
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
raise ValidationError(f'{field} must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
result: list[str] = []
for item in value:
normalized = item.strip()
if normalized and normalized not in result:
result.append(normalized)
return result
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
value = data.get('login_config_json', {})
@@ -268,20 +255,47 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
profile = config.parsing_profile
return {
'id': config.id, 'inventory_source_id': config.inventory_source_id, 'enabled': bool(config.enabled),
'id': config.id, 'inventory_source_id': config.inventory_source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'warehouse_ids_json': config.warehouse_ids_json or [], 'config_version': config.config_version,
# 异动解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
'parsing_profile_id': config.parsing_profile_id,
'parsing_profile': ({
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status,
} if profile else None),
'config_version': config.config_version,
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
}
def _validate_movement_profile_binding(profile_id: Any) -> int | None:
"""校验收料配置绑定的异动解析规则:必须已发布且 purpose='movement';空值表示解绑。
Args:
profile_id: 请求中的 parsing_profile_id;None/空串表示解绑。
Returns:
规整后的规则 id 或 None。
Raises:
ValidationError: 规则不存在/未发布/用途不是 movement(fail-closed,防误绑库存规则)。
"""
if profile_id is None or str(profile_id).strip() == '':
return None
profile = db.session.get(ShippingInventoryParsingProfile, int(profile_id))
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
raise ValidationError(
'Receipt movement parsing profile must be published with purpose movement',
code='SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID',
)
return profile.id
def _validate_receipt_report_config(
source: ShippingInventorySource, data: dict[str, Any],
) -> tuple[bool, dict[str, str], list[dict[str, Any]], list[str]]:
"""规范收料配置,确保日期保持空值、DBS/Crane 路径与仓库拆分规则不混用。"""
enabled = _bool(data, 'enabled', True)
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
try:
parameters = _validate_query_parameters(data)
except ValidationError as exc:
@@ -289,19 +303,22 @@ def _validate_receipt_report_config(
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
raw_warehouses = _json_string_list(data, 'warehouse_ids_json')
raw_path = _json_object(data, 'report_path_json')
if source.connector_type == 'dbs':
try:
path = _validate_report_path('dbs', raw_path)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
if enabled and not raw_warehouses:
raise ValidationError('DBS receipt report requires warehouse_ids_json', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
return enabled, path, parameters, raw_warehouses
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
if len(warehouse_conditions) != 1 or not any(warehouse_values):
raise ValidationError(
'DBS receipt report requires exactly one Warehouse query condition with values',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return path, parameters
if source.connector_type == 'crane':
if raw_warehouses:
raise ValidationError('Crane receipt report does not support Warehouse split', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if parameters:
@@ -309,7 +326,7 @@ def _validate_receipt_report_config(
'Crane receipt report does not support query parameters',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return enabled, {'report_name': 'Inbound Details'}, [], []
return {'report_name': 'Inbound Details'}, []
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
@@ -327,7 +344,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
enabled, path, parameters, warehouses = _validate_receipt_report_config(source, data)
path, parameters = _validate_receipt_report_config(source, data)
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
before = _receipt_report_config_payload(config) if config else None
is_new = config is None
@@ -337,10 +354,9 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
db.session.add(config)
else:
config.config_version += 1
config.enabled = enabled
config.report_path_json = path
config.query_parameters_json = parameters
config.warehouse_ids_json = warehouses
config.parsing_profile_id = _validate_movement_profile_binding(data.get('parsing_profile_id'))
config.updated_by = actor_id
db.session.flush()
after = _receipt_report_config_payload(config)
@@ -348,7 +364,8 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config',
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
result='success', before=before, after=after,
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type},
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type,
'parsing_profile_id': config.parsing_profile_id},
)
db.session.commit()
return after
@@ -1160,6 +1177,7 @@ def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, An
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
'enabled': bool(mapping.enabled), 'version': mapping.version,
}
@@ -1191,8 +1209,11 @@ def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping
raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
record.inventory_source_id = source_id
# Freight warehouse is a business identity token; normalize it to match runtime inventory rows.
record.freight_warehouse_id = (_text(data, 'freight_warehouse_id') or '').upper() or None
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
record.external_organization_code = _text(data, 'external_organization_code')
record.external_site_code = _text(data, 'external_site_code')
@@ -20,7 +20,7 @@ from app.core.errors import NotFoundError, ValidationError
from app.models import AgentGuide, KbDocumentVersion
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
from app.services.kb.storage import resolve_storage_path
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
from edkb_system.contracts import Block, Context
from edkb_system.skills import loader_pdf, ocr
@@ -21,7 +21,7 @@ from app.core.config.env_persistence import persist_env_settings
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import Agent, LoginAudit, User, WecomNotifyAudit
from app.services.auth import wecom_auth_service
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa
def serialize_debug_match_user(user: User) -> dict: