Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb7e0977b8 | ||
|
|
a24bd94d43 |
No files matched your search
@@ -10,8 +10,6 @@ FLASK_ENV=development
|
||||
|
||||
# --- 2. 应用运行与进程 ---
|
||||
TASK_EXECUTION_MODE=sync
|
||||
# 集成连接器凭据密文的 Fernet 主密钥(凭据引用 db 模式落库用);仅由环境注入,轮换需同步重录凭据。
|
||||
INTEGRATION_CREDENTIAL_KEY=d8MCilouDvf6ubi-EWM2kZpiYCpH4kU7BSfOtBI0194=
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=10
|
||||
|
||||
|
||||
@@ -10,8 +10,6 @@ FLASK_ENV=production
|
||||
|
||||
# --- 2. 应用运行与进程 ---
|
||||
TASK_EXECUTION_MODE=rq
|
||||
# 集成连接器凭据密文的 Fernet 主密钥(凭据引用 db 模式落库用);仅由环境注入,轮换需同步重录凭据。
|
||||
INTEGRATION_CREDENTIAL_KEY=YJGD6nLfYUrbzhAlzBJ4xXvyoHw0dIOxDfRIA3xOXWA=
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
@@ -109,9 +107,6 @@ WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
# SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
|
||||
# SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
|
||||
# 进度细化灰度(阶段 5;生产默认开启,回滚时按需关闭,禁止删除审计事实)
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
@@ -139,9 +134,6 @@ SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
||||
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
||||
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
|
||||
+13
-2
@@ -229,13 +229,21 @@ EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# 在途仓自动调拨 Agent(来源并发 / 确认有效期 10 分钟 / 老化阈值);
|
||||
# 外部系统端点与凭据由集成连接器客户端实例管理,不在环境变量中配置。
|
||||
# 在途仓自动调拨 Agent(来源并发 / ERP 查询并发 / ERP 写并发恒 1 / 确认有效期 10 分钟 / 老化阈值)
|
||||
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=3
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=3
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=3
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=60
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=60
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=600
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
|
||||
# ERP SOAP 地址与凭据仅由环境/Secret 注入(WSDL 冻结前留空 = fail-closed,禁止写入本文件)
|
||||
# IN_TRANSIT_TRANSFER_ERP_ENDPOINT=
|
||||
# IN_TRANSIT_TRANSFER_ERP_USERNAME=
|
||||
# IN_TRANSIT_TRANSFER_ERP_PASSWORD=
|
||||
IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG=
|
||||
# 归档 bucket(MinIO;凭据复用 MINIO_*)
|
||||
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
|
||||
|
||||
@@ -280,6 +288,9 @@ SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS=120
|
||||
SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES=3
|
||||
SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=30
|
||||
SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800
|
||||
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
||||
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
# 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。
|
||||
# L7 验收完成前禁止开启通用解析与通用自动冻结。
|
||||
# 通用确定性解析:仅 no_special_profile_feature / 无漂移 no_match 可进入。
|
||||
|
||||
@@ -10,8 +10,6 @@ FLASK_ENV=test
|
||||
|
||||
# --- 2. 应用运行与进程 ---
|
||||
TASK_EXECUTION_MODE=rq
|
||||
# 集成连接器凭据密文的 Fernet 主密钥(凭据引用 db 模式落库用);仅由环境注入,轮换需同步重录凭据。
|
||||
INTEGRATION_CREDENTIAL_KEY=S6LTZXSdli532953J5G90rWxs35plKEph8ds6rh8AKQ=
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=6
|
||||
|
||||
|
||||
@@ -94,7 +94,6 @@ backend/data/kb/
|
||||
.pytest_cache/
|
||||
backend/data/fixed_assets/
|
||||
docs/FixedAssets_*.xlsx
|
||||
backend/data/freight_rpa/
|
||||
backend/data/shipping_notice/
|
||||
backend/data/logs/
|
||||
backend/data/logs/*.log
|
||||
|
||||
@@ -72,13 +72,6 @@ def create_app(config_name='default'):
|
||||
|
||||
register_blueprints(app)
|
||||
|
||||
# 能力声明是代码级契约:组合根在每次 create_app 时显式注册各域能力(幂等),
|
||||
# 保证管理端「能力清单」冷启动即可见,且测试 reset 注册表后建新 app 也能恢复。
|
||||
# 注意用 from-import:`import app.services...` 会把局部名 app 遮蔽成包模块。
|
||||
from app.services.in_transit_transfer import capabilities as _transfer_capabilities
|
||||
|
||||
_transfer_capabilities.register_transfer_capabilities()
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
# window between worker boot and the first ``before_request`` would still
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -22,11 +22,21 @@ def dashboard_summary():
|
||||
return jsonify(dashboard_service.compute_dashboard_summary())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard/badges', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_badges():
|
||||
"""
|
||||
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
|
||||
GET /api/admin/dashboard/badges
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_dashboard_badges())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_stats():
|
||||
"""
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary)。
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary 与 /dashboard/badges)。
|
||||
GET /api/admin/dashboard
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_legacy_dashboard_stats())
|
||||
@@ -28,13 +28,6 @@ def create_department():
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
||||
@require_admin
|
||||
def list_department_members(id: int):
|
||||
"""返回部门员工数量与名单。"""
|
||||
return jsonify(department_service.list_department_members(id))
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_department(id: int):
|
||||
|
||||
@@ -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')))
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/admin/permissions.py
|
||||
|
||||
用途:管理后台应用权限批量更新 API(薄路由层)。
|
||||
用途:管理后台权限批量更新与权限申请审批 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/permission_service。
|
||||
逻辑:/permissions/*、/users/<id>/permissions 路由。
|
||||
逻辑:/permissions/*、/permission-requests/*、/users/<id>/permissions 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -28,3 +28,22 @@ def update_user_permissions(id: int):
|
||||
return jsonify(permission_service.update_user_permissions(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_requests():
|
||||
"""列出全部权限申请。"""
|
||||
return jsonify(permission_service.list_permission_requests())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_request(id: int):
|
||||
"""批准权限申请。"""
|
||||
return jsonify(permission_service.approve_permission_request(id))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_request(id: int):
|
||||
"""拒绝权限申请。"""
|
||||
return jsonify(permission_service.reject_permission_request(id))
|
||||
@@ -19,7 +19,7 @@ def _query_params() -> dict[str, str]:
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""聊天使用分析报表(统计范围:start_date/end_date 自定义日期优先,否则 range=7d|30d|90d|180d|365d)。"""
|
||||
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
@@ -34,8 +34,6 @@ def usage_report():
|
||||
user_page=user_page,
|
||||
user_page_size=user_page_size,
|
||||
range_key=range_key,
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -45,7 +43,7 @@ def usage_report():
|
||||
def applications_report():
|
||||
"""
|
||||
应用运营报表:按应用聚合使用 / 权限 / 评分。
|
||||
Query: start_date, end_date(自定义日期优先), range, status, usage, q, sort, order, page, page_size。
|
||||
Query: range, status, usage, q, sort, order, page, page_size。
|
||||
"""
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
@@ -58,8 +56,6 @@ def applications_report():
|
||||
return jsonify(
|
||||
report_service.build_application_report(
|
||||
range_key=request.args.get('range'),
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
status=request.args.get('status'),
|
||||
usage=request.args.get('usage'),
|
||||
q=request.args.get('q'),
|
||||
@@ -71,22 +67,6 @@ def applications_report():
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/overview', methods=['GET'])
|
||||
@require_admin
|
||||
def ops_overview_report():
|
||||
"""
|
||||
运营总览报表:对话量 / 活跃用户 / 活跃应用 / 趋势环比 / Top 与低使用应用 / 未处理反馈。
|
||||
Query: start_date, end_date(自定义日期优先),否则 range(7d/30d/90d/180d/365d)。
|
||||
"""
|
||||
return jsonify(
|
||||
report_service.build_ops_overview_report(
|
||||
range_key=request.args.get('range'),
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_report():
|
||||
@@ -106,31 +86,3 @@ def list_general_feedbacks_report():
|
||||
def count_general_feedbacks_report():
|
||||
"""通用反馈计数。"""
|
||||
return jsonify(report_service.count_general_feedbacks_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/chat-log-tops', methods=['GET'])
|
||||
@require_admin
|
||||
def chat_log_tops():
|
||||
"""聊天日志 Top 提问/回答内容(直接按 ChatLog 明细统计,复用 FAQ 问句归一化)。"""
|
||||
return jsonify(report_service.build_chat_log_top_content(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback-summary', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_summary():
|
||||
"""用户反馈概览:待处理 / 本月已关闭 / 最多反馈应用(三张概览卡)。"""
|
||||
return jsonify(report_service.build_feedback_summary(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/issue-analysis', methods=['GET'])
|
||||
@require_admin
|
||||
def issue_analysis():
|
||||
"""问题分析:高频问题簇 KPI + 优先处理问题(复用聊天日志风险规则)。"""
|
||||
return jsonify(report_service.build_issue_analysis_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks/<int:feedback_id>/close', methods=['POST'])
|
||||
@require_admin
|
||||
def close_general_feedback(feedback_id: int):
|
||||
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
||||
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
||||
@@ -428,21 +428,6 @@ def get_shipping_inventory_configuration_catalog():
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/movement-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_movement_fields():
|
||||
"""标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。"""
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
return _ok([
|
||||
{
|
||||
'code': field.code, 'value_type': str(field.value_type),
|
||||
'required': bool(field.required), 'is_identity': bool(field.is_identity),
|
||||
}
|
||||
for field in MOVEMENT_FIELDS
|
||||
])
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_parsing_profiles():
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
"""
|
||||
backend/app/api/admin/users.py
|
||||
|
||||
鐢ㄩ€旓細绠$悊鍚庡彴鐢ㄦ埛 CRUD API锛堣杽璺敱灞傦級銆?
|
||||
渚濊禆锛歛dmin.blueprint銆乻ervices/admin/user_service銆乧ore.auth.jwt銆?
|
||||
閫昏緫锛?users* 璺敱銆?
|
||||
用途:管理后台用户 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/user_service、core.auth.jwt。
|
||||
逻辑:/users* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -20,7 +20,7 @@ def _query_params() -> dict[str, str]:
|
||||
@admin_bp.route('/users', methods=['GET'])
|
||||
@require_admin
|
||||
def list_users():
|
||||
"""Admin user operation."""
|
||||
"""列出管理端用户(支持分页与筛选)。"""
|
||||
result = user_service.list_users(_query_params())
|
||||
return jsonify(result)
|
||||
|
||||
@@ -28,7 +28,7 @@ def list_users():
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
"""Admin user operation."""
|
||||
"""创建用户并同步 Casdoor。"""
|
||||
data = request.get_json() or {}
|
||||
payload = user_service.create_user(data)
|
||||
return jsonify(payload), 201
|
||||
@@ -37,22 +37,30 @@ def create_user():
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id: int):
|
||||
"""Admin user operation."""
|
||||
"""更新用户资料;有 password 时同步 Casdoor 改密。"""
|
||||
data = request.get_json() or {}
|
||||
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():
|
||||
"""Admin user operation."""
|
||||
"""批量删除 status=rejected 的用户。"""
|
||||
return jsonify(user_service.cleanup_rejected_users())
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_users():
|
||||
"""Admin user operation."""
|
||||
"""批量删除用户(排除当前登录管理员)。"""
|
||||
data = request.get_json() or {}
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
@@ -62,7 +70,21 @@ def batch_delete_users():
|
||||
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_user(id: int):
|
||||
"""Admin user operation."""
|
||||
"""删除单个用户。"""
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.delete_user(id, current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_user(id: int):
|
||||
"""审批通过用户。"""
|
||||
return jsonify(user_service.approve_user(id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_user(id: int):
|
||||
"""拒绝用户注册。"""
|
||||
return jsonify(user_service.reject_user(id))
|
||||
@@ -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',
|
||||
|
||||
@@ -28,7 +28,7 @@ from app.services.in_transit_transfer.execution_service import (
|
||||
)
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
|
||||
from app.services.in_transit_transfer.retry_service import requery_items as retry_service_requery_items, retry_item
|
||||
from app.services.in_transit_transfer.retry_service import retry_item
|
||||
from app.services.in_transit_transfer.serializers import (
|
||||
serialize_item,
|
||||
serialize_source,
|
||||
@@ -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:
|
||||
@@ -72,11 +72,9 @@ def _ok(payload: Any, *, status: int = 200):
|
||||
@in_transit_transfer_bp.route("/prechecks", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def create_precheck_api():
|
||||
"""创建或复用一次调拨预检(只读,不写 外部系统)。
|
||||
"""创建或复用一次调拨预检(只读,不写 ERP)。
|
||||
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
|
||||
"receipt_date_from"/"receipt_date_to"(可选),
|
||||
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选)}。
|
||||
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -91,9 +89,6 @@ def create_precheck_api():
|
||||
source_codes=[str(item).strip() for item in source_codes],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
receipt_date_from=str(body.get("receipt_date_from")) if body.get("receipt_date_from") else None,
|
||||
receipt_date_to=str(body.get("receipt_date_to")) if body.get("receipt_date_to") else None,
|
||||
transfer_type=str(body.get("transfer_type")) if body.get("transfer_type") else None,
|
||||
)
|
||||
return _ok(serialize_summary(summary), status=201)
|
||||
|
||||
@@ -116,7 +111,7 @@ def execute_precheck_api(precheck_id: str):
|
||||
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
|
||||
|
||||
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
|
||||
响应:201 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果。
|
||||
响应:201 envelope,data 为 run_no / run 状态 / ERP 单号聚合结果。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
|
||||
@@ -135,88 +130,6 @@ def execute_precheck_api(precheck_id: str):
|
||||
}, status=201)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_no>/items/requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def requery_items_api(precheck_no: str):
|
||||
"""批量重查 外部系统 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body.get("invoice_nos"), list) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_service_requery_items(
|
||||
precheck_no=precheck_no, deps=deps, invoice_nos=invoice_nos,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/receipt-files", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def download_source_receipt_files_api():
|
||||
"""按选中来源打包下载各自最新归档收料文件(zip);记录访问审计。"""
|
||||
import io
|
||||
import zipfile
|
||||
from pathlib import Path as _Path
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
source_codes = body.get("source_codes")
|
||||
if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]:
|
||||
raise ValidationError("source_codes is required")
|
||||
|
||||
buffer = io.BytesIO()
|
||||
included: list[str] = []
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
for code in source_codes:
|
||||
code = str(code or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=code),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/预检取文件同口径,
|
||||
# 单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
if report is None:
|
||||
continue
|
||||
data = file_asset_storage.get_bytes(report.storage_key)
|
||||
safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name
|
||||
archive.writestr(f"{code}-{safe_name}", data)
|
||||
included.append(code)
|
||||
if not included:
|
||||
raise NotFoundError("no archived receipt files", code="SHIPPING.RECEIPT_FILE_NOT_FOUND")
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
|
||||
aggregate_type="in_transit_source",
|
||||
aggregate_id=",".join(included),
|
||||
actor_type="user",
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
actor_display=str(getattr(user, "name", "") or ""),
|
||||
request_id=getattr(g, "request_id", None),
|
||||
result="success",
|
||||
))
|
||||
db.session.commit()
|
||||
buffer.seek(0)
|
||||
return send_file(
|
||||
buffer,
|
||||
mimetype="application/zip",
|
||||
as_attachment=True,
|
||||
download_name=f"receipt-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip",
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_run_api(run_no: str):
|
||||
@@ -236,14 +149,14 @@ def cancel_run_api(run_no: str):
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/retry", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_item_api(item_id: int):
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 外部系统,创建新 Attempt)。
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 ERP,创建新 Attempt)。
|
||||
|
||||
请求体:{"kind": "external_recheck"}(可选,默认 external_recheck)。
|
||||
请求体:{"kind": "erp_recheck"}(可选,默认 erp_recheck)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
kind = body.get("kind") if isinstance(body, dict) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "external_recheck"))
|
||||
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "erp_recheck"))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/manual-close", methods=["POST"])
|
||||
@@ -344,10 +257,10 @@ def receipt_files_api(run_no: str):
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/external-inventory", methods=["GET"])
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/erp-inventory", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def erp_inventory_api(run_no: str):
|
||||
"""下载本次预检冻结的 外部系统 库存表(csv);记录访问审计。"""
|
||||
"""下载本次预检冻结的 ERP 库存表(csv);记录访问审计。"""
|
||||
import io
|
||||
|
||||
from app import db
|
||||
@@ -357,19 +270,19 @@ def erp_inventory_api(run_no: str):
|
||||
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,external_quantity,result,external_document_no"]
|
||||
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,erp_quantity,result,erp_document_no"]
|
||||
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all():
|
||||
lines.append(",".join([
|
||||
str(item.invoice_no), str(item.source_code), str(item.material_no),
|
||||
str(item.from_warehouse), str(item.to_warehouse),
|
||||
str(item.receipt_quantity), str(item.external_quantity or ""),
|
||||
str(item.result_code or item.status), str(item.external_document_no or ""),
|
||||
str(item.receipt_quantity), str(item.erp_quantity or ""),
|
||||
str(item.result_code or item.status), str(item.erp_document_no or ""),
|
||||
]))
|
||||
data = ("\n".join(lines) + "\n").encode("utf-8")
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_EXTERNAL_INVENTORY_DOWNLOADED",
|
||||
event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
@@ -384,7 +297,7 @@ def erp_inventory_api(run_no: str):
|
||||
io.BytesIO(data),
|
||||
mimetype="text/csv",
|
||||
as_attachment=True,
|
||||
download_name=f"external-inventory-{run_no}.csv",
|
||||
download_name=f"erp-inventory-{run_no}.csv",
|
||||
)
|
||||
|
||||
|
||||
@@ -402,9 +315,8 @@ def transfer_metrics_api():
|
||||
def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认预检)与状态标识;保留期已到或非当天
|
||||
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
|
||||
每来源附收料文件状态(ready/fetching/failed/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认预检)与状态标识。只读复用已启用库存来源。
|
||||
"""
|
||||
from app.models import ShippingInventorySource
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
@@ -1,30 +1,21 @@
|
||||
"""api/integration_connector.py
|
||||
|
||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
|
||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto。
|
||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。
|
||||
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
|
||||
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
|
||||
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
|
||||
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
|
||||
转移(绑定发布附加就绪门禁:接口须已发布且客户端启用);绑定创建/更新做客户端
|
||||
与接口成对校验(接口定义必须属于所选客户端实例,错配即 400)。
|
||||
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
|
||||
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
|
||||
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
|
||||
注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有
|
||||
/api/integration Dify 文件代理)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret, encrypt_secret
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import (
|
||||
IntegrationBinding,
|
||||
@@ -32,36 +23,14 @@ from app.models import (
|
||||
IntegrationCredentialReference,
|
||||
IntegrationInterfaceDefinition,
|
||||
)
|
||||
from app.services.integration_connector.capability import list_capabilities
|
||||
from app.services.integration_connector.credential_types import (
|
||||
build_secret_dict,
|
||||
get_credential_type,
|
||||
list_credential_types,
|
||||
visible_fields,
|
||||
)
|
||||
from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
from app.services.integration_connector.security import CREDENTIAL_KEY_CONFIG_NAME, _DB_SECRET_CODES
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
|
||||
integration_connector_bp = Blueprint('integration_connector', __name__)
|
||||
|
||||
VALID_CONNECTOR_TYPES = ('rest', 'soap')
|
||||
VALID_STATUSES = ('draft', 'published', 'retired')
|
||||
VALID_SECRET_PROVIDERS = ('db', 'env')
|
||||
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
|
||||
# 现语义等于断供且真实版本化轮换未实现(属 P2),故 PUT 只允许在 active/retired 间切换,
|
||||
# rotating 不再可进入;存量 rotating 数据保留只读展示,经 PUT 置 active 即恢复。
|
||||
VALID_CREDENTIAL_UI_STATUSES = ('active', 'retired')
|
||||
|
||||
# 配置实体生命周期转移表(接口定义与绑定共用):动作 → (源状态, 目标状态)。状态不再
|
||||
# 由 PUT 直接改写,只能经动作端点按此表转移(draft→published 发布;published→draft 撤回;
|
||||
# published→retired 退役;retired→draft 恢复为草稿,作为无版本化阶段的保险阀)。
|
||||
CONFIG_STATUS_TRANSITIONS = {
|
||||
'publish': ('draft', 'published'),
|
||||
'unpublish': ('published', 'draft'),
|
||||
'retire': ('published', 'retired'),
|
||||
'reopen': ('retired', 'draft'),
|
||||
}
|
||||
|
||||
|
||||
def _require(value, field: str) -> None:
|
||||
@@ -70,70 +39,6 @@ def _require(value, field: str) -> None:
|
||||
raise ValidationError(f'{field} is required', details={'field': field})
|
||||
|
||||
|
||||
def _require_client(code: str) -> IntegrationClientInstance:
|
||||
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise ValidationError(
|
||||
'client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND',
|
||||
details={'client_instance_code': code},
|
||||
)
|
||||
return client
|
||||
|
||||
|
||||
def _apply_status_transition(entity, action: str, *, kind: str) -> None:
|
||||
"""按转移表校验并落库状态;非法动作或源状态不符即 400。"""
|
||||
transition = CONFIG_STATUS_TRANSITIONS.get(action)
|
||||
if transition is None:
|
||||
raise ValidationError(
|
||||
'unknown lifecycle action', details={'allowed': sorted(CONFIG_STATUS_TRANSITIONS)})
|
||||
src, dst = transition
|
||||
if entity.status != src:
|
||||
raise ValidationError(
|
||||
f'{kind} status is {entity.status}, cannot {action}',
|
||||
code='INTEGRATION.ILLEGAL_STATUS_TRANSITION',
|
||||
details={'action': action, 'from': entity.status, 'to': dst},
|
||||
)
|
||||
entity.status = dst
|
||||
|
||||
|
||||
def _require_interface(code: str) -> IntegrationInterfaceDefinition:
|
||||
"""按编码取接口定义;不存在即 400(绑定成对校验以其所属客户端为准,而非依赖外键报 500)。"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise ValidationError(
|
||||
'interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND',
|
||||
details={'interface_definition_code': code},
|
||||
)
|
||||
return iface
|
||||
|
||||
|
||||
def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClientInstance, IntegrationInterfaceDefinition]:
|
||||
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
|
||||
|
||||
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
|
||||
400(fail-fast),不留给调用期 fail-closed。
|
||||
"""
|
||||
client = _require_client(str(client_code).strip())
|
||||
iface = _require_interface(str(interface_code).strip())
|
||||
if iface.client_instance_code != client.code:
|
||||
raise ValidationError(
|
||||
'interface definition does not belong to the selected client instance',
|
||||
code='INTEGRATION.BINDING_PAIR_MISMATCH',
|
||||
details={
|
||||
'client_instance_code': client.code,
|
||||
'interface_definition_code': iface.code,
|
||||
'interface_client_instance_code': iface.client_instance_code,
|
||||
},
|
||||
)
|
||||
return client, iface
|
||||
|
||||
|
||||
def _interface_transition(iface, action: str) -> None:
|
||||
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
|
||||
_apply_status_transition(iface, action, kind='interface')
|
||||
|
||||
|
||||
def _serialize_client(client) -> dict:
|
||||
return {
|
||||
'id': client.id, 'code': client.code, 'name': client.name,
|
||||
@@ -159,7 +64,7 @@ def _serialize_binding(binding) -> dict:
|
||||
return {
|
||||
'id': binding.id, 'capability': binding.capability,
|
||||
'context_selector_json': binding.context_selector_json or {},
|
||||
'param_mapping_json': binding.param_mapping_json or {},
|
||||
'context_source_code': binding.context_source_code,
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
'interface_definition_code': binding.interface_definition_code,
|
||||
'mapping_version': binding.mapping_version, 'priority': binding.priority,
|
||||
@@ -168,59 +73,15 @@ def _serialize_binding(binding) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _decrypted_secret(cred) -> dict:
|
||||
"""db 模式下解密凭据字典;密文缺失或主密钥异常时返回空 dict(fail-closed 不炸列表)。"""
|
||||
if cred.secret_provider != 'db' or not cred.secret_ciphertext:
|
||||
return {}
|
||||
try:
|
||||
raw = decrypt_secret(
|
||||
cred.secret_ciphertext,
|
||||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||||
codes=_DB_SECRET_CODES,
|
||||
)
|
||||
parsed = json.loads(raw)
|
||||
return parsed if isinstance(parsed, dict) else {}
|
||||
except AppError:
|
||||
return {}
|
||||
|
||||
|
||||
def _serialize_credential(cred) -> dict:
|
||||
secret_dict = _decrypted_secret(cred)
|
||||
return {
|
||||
'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref,
|
||||
'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type,
|
||||
# 非密字段按类型定义回显(如 username);密文字段与密文本身永不回显。
|
||||
'secret_fields': visible_fields(cred.credential_type, secret_dict),
|
||||
'has_secret': bool(cred.secret_ciphertext),
|
||||
'version': cred.version, 'status': cred.status,
|
||||
'updated_at': cred.updated_at.isoformat() if cred.updated_at else None,
|
||||
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _apply_db_secret(cred, body) -> None:
|
||||
"""db 模式:按凭据类型定义组装字段并加密落库;只改部分字段可沿用解密出的旧值。
|
||||
|
||||
类型必须在凭据类型注册表内(fail-closed);合并旧值后必填字段仍缺失即拒绝。
|
||||
"""
|
||||
ctype = str(body.get('credential_type') or cred.credential_type or 'password').strip()
|
||||
if get_credential_type(ctype) is None:
|
||||
raise ValidationError('unknown credential_type', details={'credential_type': ctype})
|
||||
cred.credential_type = ctype
|
||||
current = _decrypted_secret(cred) if cred.secret_ciphertext else {}
|
||||
values: dict = dict(current)
|
||||
for key in (field['key'] for field in get_credential_type(ctype)['fields']):
|
||||
incoming = body.get(key)
|
||||
if incoming is not None and str(incoming) != '':
|
||||
values[key] = str(incoming)
|
||||
merged = build_secret_dict(ctype, values)
|
||||
cred.secret_ciphertext = encrypt_secret(
|
||||
json.dumps(merged, ensure_ascii=False),
|
||||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||||
codes=_DB_SECRET_CODES,
|
||||
)
|
||||
|
||||
|
||||
def _result_to_dict(result: IntegrationCallResult) -> dict:
|
||||
return {
|
||||
'status': result.status,
|
||||
@@ -237,6 +98,7 @@ def _result_to_dict(result: IntegrationCallResult) -> dict:
|
||||
@integration_connector_bp.route('/capabilities', methods=['GET'])
|
||||
@require_admin
|
||||
def list_capabilities_endpoint():
|
||||
ensure_capabilities_loaded()
|
||||
data = [{
|
||||
'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency,
|
||||
'input_schema': spec.input_schema, 'output_schema': spec.output_schema,
|
||||
@@ -369,15 +231,15 @@ def create_interface_definition():
|
||||
code = str(body.get('code') or '').strip()
|
||||
_require(code, 'code')
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
# 连接器类型以所选客户端实例为单一事实源(服务端推导落库,忽略请求体传值,
|
||||
# 杜绝接口与客户端类型不一致);客户端不存在即 400,而非依赖外键报 500。
|
||||
client = _require_client(str(body['client_instance_code']).strip())
|
||||
connector_type = str(body.get('connector_type') or '')
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
status = str(body.get('status') or 'draft')
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code=code, name=str(body.get('name') or code).strip(),
|
||||
client_instance_code=client.code, connector_type=client.connector_type,
|
||||
client_instance_code=body['client_instance_code'], connector_type=connector_type,
|
||||
http_method=(str(body.get('http_method') or '').strip().upper() or None),
|
||||
request_path=(str(body.get('request_path') or '').strip() or None),
|
||||
request_spec_json=body.get('request_spec_json') or {},
|
||||
@@ -385,9 +247,7 @@ def create_interface_definition():
|
||||
response_mapping_json=body.get('response_mapping_json') or {},
|
||||
output_schema_json=body.get('output_schema_json') or {},
|
||||
version=int(body.get('version') or 1), status=status,
|
||||
# enabled 冻结:与 status 重复表达可用性且运行时不消费(假开关),请求体传值忽略;
|
||||
# 可用性只由 status 生命周期表达,列待 P2 版本化迁移时清理。
|
||||
enabled=True,
|
||||
enabled=bool(body.get('enabled', True)),
|
||||
)
|
||||
from app import db
|
||||
db.session.add(iface)
|
||||
@@ -398,11 +258,7 @@ def create_interface_definition():
|
||||
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_interface_definition(code):
|
||||
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema 与所属客户端)。
|
||||
|
||||
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
|
||||
连接器类型由所属客户端实例服务端推导,请求体传值被忽略。
|
||||
"""
|
||||
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||||
@@ -412,9 +268,12 @@ def update_interface_definition(code):
|
||||
iface.name = str(body['name']).strip()
|
||||
if body.get('client_instance_code') is not None:
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
client = _require_client(str(body['client_instance_code']).strip())
|
||||
iface.client_instance_code = client.code
|
||||
iface.connector_type = client.connector_type
|
||||
iface.client_instance_code = body['client_instance_code']
|
||||
if body.get('connector_type') is not None:
|
||||
connector_type = str(body['connector_type'])
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
iface.connector_type = connector_type
|
||||
if 'http_method' in body:
|
||||
iface.http_method = str(body.get('http_method') or '').strip().upper() or None
|
||||
if 'request_path' in body:
|
||||
@@ -424,52 +283,18 @@ def update_interface_definition(code):
|
||||
setattr(iface, json_field, body.get(json_field) or {})
|
||||
if body.get('version') is not None:
|
||||
iface.version = int(body.get('version') or 1)
|
||||
if body.get('status') is not None:
|
||||
status = str(body['status'])
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
iface.status = status
|
||||
if 'enabled' in body:
|
||||
iface.enabled = bool(body.get('enabled', True))
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_interface(iface))
|
||||
|
||||
|
||||
# ---- 接口定义生命周期(状态只经动作端点按转移表流转) ----
|
||||
|
||||
def _do_interface_lifecycle(code: str, action: str):
|
||||
"""动作端点共用体:取接口 → 按转移表转移 → 落库并回显。"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||||
_interface_transition(iface, action)
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_interface(iface))
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_interface_definition(code):
|
||||
"""发布接口定义(draft → published):发布后才会被绑定解析选中。"""
|
||||
return _do_interface_lifecycle(code, 'publish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/unpublish', methods=['POST'])
|
||||
@require_admin
|
||||
def unpublish_interface_definition(code):
|
||||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||||
return _do_interface_lifecycle(code, 'unpublish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_interface_definition(code):
|
||||
"""退役(published → retired):该接口引用的所有绑定同时失效。"""
|
||||
return _do_interface_lifecycle(code, 'retire')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/reopen', methods=['POST'])
|
||||
@require_admin
|
||||
def reopen_interface_definition(code):
|
||||
"""恢复为草稿(retired → draft):版本化发布上线前的保险阀,重新走发布流程。"""
|
||||
return _do_interface_lifecycle(code, 'reopen')
|
||||
|
||||
|
||||
# ---- Binding ----
|
||||
|
||||
@integration_connector_bp.route('/bindings', methods=['GET'])
|
||||
@@ -482,22 +307,23 @@ def list_bindings():
|
||||
@integration_connector_bp.route('/bindings', methods=['POST'])
|
||||
@require_admin
|
||||
def create_binding():
|
||||
"""创建绑定:成对校验客户端与接口后落库;新建固定落 draft,发布走 /publish 动作端点。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
_require(body.get('capability'), 'capability')
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
_require(body.get('interface_definition_code'), 'interface_definition_code')
|
||||
client, iface = _validate_binding_pair(body['client_instance_code'], body['interface_definition_code'])
|
||||
status = str(body.get('status') or 'draft')
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
binding = IntegrationBinding(
|
||||
capability=body['capability'],
|
||||
context_selector_json=body.get('context_selector_json') or {},
|
||||
param_mapping_json=body.get('param_mapping_json') or {},
|
||||
client_instance_code=client.code,
|
||||
interface_definition_code=iface.code,
|
||||
context_source_code=(str(body.get('context_source_code') or '').strip() or None),
|
||||
client_instance_code=body['client_instance_code'],
|
||||
interface_definition_code=body['interface_definition_code'],
|
||||
mapping_version=int(body.get('mapping_version') or 1),
|
||||
priority=int(body.get('priority') or 0),
|
||||
environment=str(body.get('environment') or 'prod').strip(),
|
||||
status='draft',
|
||||
status=status,
|
||||
)
|
||||
from app import db
|
||||
db.session.add(binding)
|
||||
@@ -508,11 +334,7 @@ def create_binding():
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_binding(binding_id):
|
||||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。
|
||||
|
||||
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
|
||||
客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。
|
||||
"""
|
||||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。"""
|
||||
from app import db
|
||||
binding = db.session.get(IntegrationBinding, binding_id)
|
||||
if binding is None:
|
||||
@@ -523,23 +345,14 @@ def update_binding(binding_id):
|
||||
binding.capability = body['capability']
|
||||
if 'context_selector_json' in body:
|
||||
binding.context_selector_json = body.get('context_selector_json') or {}
|
||||
if 'param_mapping_json' in body:
|
||||
binding.param_mapping_json = body.get('param_mapping_json') or {}
|
||||
new_client_code = body.get('client_instance_code')
|
||||
new_iface_code = body.get('interface_definition_code')
|
||||
if new_client_code is not None:
|
||||
_require(new_client_code, 'client_instance_code')
|
||||
if new_iface_code is not None:
|
||||
_require(new_iface_code, 'interface_definition_code')
|
||||
if new_client_code is not None or new_iface_code is not None:
|
||||
_validate_binding_pair(
|
||||
new_client_code if new_client_code is not None else binding.client_instance_code,
|
||||
new_iface_code if new_iface_code is not None else binding.interface_definition_code,
|
||||
)
|
||||
if new_client_code is not None:
|
||||
binding.client_instance_code = str(new_client_code).strip()
|
||||
if new_iface_code is not None:
|
||||
binding.interface_definition_code = str(new_iface_code).strip()
|
||||
if 'context_source_code' in body:
|
||||
binding.context_source_code = str(body.get('context_source_code') or '').strip() or None
|
||||
if body.get('client_instance_code') is not None:
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
binding.client_instance_code = body['client_instance_code']
|
||||
if body.get('interface_definition_code') is not None:
|
||||
_require(body.get('interface_definition_code'), 'interface_definition_code')
|
||||
binding.interface_definition_code = body['interface_definition_code']
|
||||
if body.get('mapping_version') is not None:
|
||||
binding.mapping_version = int(body.get('mapping_version') or 1)
|
||||
if body.get('priority') is not None:
|
||||
@@ -550,69 +363,16 @@ def update_binding(binding_id):
|
||||
binding.effective_from = body['effective_from'] or None
|
||||
if body.get('effective_to') is not None:
|
||||
binding.effective_to = body['effective_to'] or None
|
||||
if body.get('status') is not None:
|
||||
status = str(body['status'])
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
binding.status = status
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding))
|
||||
|
||||
|
||||
# ---- 绑定生命周期(状态只经动作端点按转移表流转) ----
|
||||
|
||||
def _do_binding_lifecycle(binding_id: int, action: str):
|
||||
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
|
||||
|
||||
发布(publish)附加就绪门禁:引用的接口定义须已发布、客户端实例须启用,
|
||||
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
|
||||
(与 binding.resolve_binding 的调用期门禁同一语义)。
|
||||
"""
|
||||
from app import db
|
||||
binding = db.session.get(IntegrationBinding, binding_id)
|
||||
if binding is None:
|
||||
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
|
||||
if action == 'publish':
|
||||
client = IntegrationClientInstance.query.filter_by(code=binding.client_instance_code).first()
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=binding.interface_definition_code).first()
|
||||
if client is None or iface is None or iface.status != 'published' or not client.enabled:
|
||||
raise ValidationError(
|
||||
'binding target not ready: interface must be published and client instance enabled',
|
||||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||
details={
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
'interface_definition_code': binding.interface_definition_code,
|
||||
},
|
||||
)
|
||||
_apply_status_transition(binding, action, kind='binding')
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding))
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_binding(binding_id):
|
||||
"""发布绑定(draft → published):发布后才会被绑定解析选中。"""
|
||||
return _do_binding_lifecycle(binding_id, 'publish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/unpublish', methods=['POST'])
|
||||
@require_admin
|
||||
def unpublish_binding(binding_id):
|
||||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||||
return _do_binding_lifecycle(binding_id, 'unpublish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_binding(binding_id):
|
||||
"""退役(published → retired):绑定退出自动调用。"""
|
||||
return _do_binding_lifecycle(binding_id, 'retire')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/reopen', methods=['POST'])
|
||||
@require_admin
|
||||
def reopen_binding(binding_id):
|
||||
"""恢复为草稿(retired → draft):重新走发布流程。"""
|
||||
return _do_binding_lifecycle(binding_id, 'reopen')
|
||||
|
||||
|
||||
# ---- 凭据引用 ----
|
||||
|
||||
@integration_connector_bp.route('/credential-references', methods=['GET'])
|
||||
@@ -625,87 +385,41 @@ def list_credential_references():
|
||||
@integration_connector_bp.route('/credential-references', methods=['POST'])
|
||||
@require_admin
|
||||
def create_credential_reference():
|
||||
"""创建凭据引用:db 模式(默认)按凭据类型加密字段落库;env 模式只存配置键名。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
_require(body.get('code'), 'code')
|
||||
# 缺省保持 env(兼容既有直连 API 调用);管理端 db 模式显式传 secret_provider='db'。
|
||||
provider = str(body.get('secret_provider') or 'env').strip()
|
||||
if provider not in VALID_SECRET_PROVIDERS:
|
||||
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
|
||||
code = str(body['code']).strip()
|
||||
if IntegrationCredentialReference.query.filter_by(code=code).first():
|
||||
raise ValidationError('credential reference code already exists', code='RESOURCE.CONFLICT')
|
||||
status = str(body.get('status') or 'active')
|
||||
if status not in ('active', 'rotating', 'retired'):
|
||||
raise ValidationError('invalid credential status', details={'allowed': ['active', 'rotating', 'retired']})
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
from app import db
|
||||
cred = IntegrationCredentialReference(
|
||||
code=code,
|
||||
secret_ref=str(body.get('secret_ref') or '').strip(),
|
||||
secret_provider=provider,
|
||||
code=str(body['code']).strip(),
|
||||
secret_ref=str(body['secret_ref']).strip(),
|
||||
secret_provider=str(body.get('secret_provider') or 'env').strip(),
|
||||
credential_type=str(body.get('credential_type') or 'password').strip(),
|
||||
version=int(body.get('version') or 1),
|
||||
status=status,
|
||||
status=str(body.get('status') or 'active'),
|
||||
)
|
||||
if provider == 'db':
|
||||
_apply_db_secret(cred, body)
|
||||
cred.secret_ref = f'db:{code}'
|
||||
else:
|
||||
_require(cred.secret_ref, 'secret_ref')
|
||||
from app import db
|
||||
db.session.add(cred)
|
||||
db.session.commit()
|
||||
# 永不回显真实凭据值;只回元数据与非密字段。
|
||||
# 永不回显真实凭据值;只回元数据。
|
||||
return ok(_serialize_credential(cred), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/credential-references/types', methods=['GET'])
|
||||
@require_admin
|
||||
def list_credential_type_specs():
|
||||
"""凭据类型注册表清单(类型 + 字段定义),供管理端动态渲染表单与占位符提示。"""
|
||||
return ok(list_credential_types())
|
||||
|
||||
|
||||
@integration_connector_bp.route('/credential-references/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_credential_reference(code):
|
||||
"""更新凭据引用(code 不变);db 模式可只改部分字段(其余沿用旧值),永不回显明文。"""
|
||||
"""更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。"""
|
||||
cred = IntegrationCredentialReference.query.filter_by(code=code).first()
|
||||
if cred is None:
|
||||
raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND')
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body.get('secret_ref') is not None:
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
cred.secret_ref = str(body['secret_ref']).strip()
|
||||
if body.get('secret_provider') is not None:
|
||||
provider = str(body['secret_provider']).strip()
|
||||
if provider not in VALID_SECRET_PROVIDERS:
|
||||
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
|
||||
cred.secret_provider = provider
|
||||
if provider == 'env':
|
||||
# 切回 env 模式时清掉遗留密文,避免失效凭据残留库中。
|
||||
cred.secret_ciphertext = None
|
||||
field_keys = tuple(
|
||||
field['key'] for field in (get_credential_type(
|
||||
str(body.get('credential_type') or cred.credential_type or 'password')) or {'fields': []}
|
||||
)['fields']
|
||||
)
|
||||
has_secret_input = any(body.get(key) is not None for key in field_keys)
|
||||
if cred.secret_provider == 'db':
|
||||
if has_secret_input or body.get('credential_type') is not None or not cred.secret_ciphertext:
|
||||
_apply_db_secret(cred, body)
|
||||
cred.secret_ref = f'db:{cred.code}'
|
||||
else:
|
||||
if body.get('secret_ref') is not None:
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
cred.secret_ref = str(body['secret_ref']).strip()
|
||||
if has_secret_input:
|
||||
raise ValidationError('credential fields only apply to db credentials')
|
||||
cred.secret_provider = str(body['secret_provider']).strip()
|
||||
if body.get('credential_type') is not None:
|
||||
cred.credential_type = str(body['credential_type']).strip()
|
||||
if body.get('status') is not None:
|
||||
# 状态改写冻结为两态开关:仅允许 active/retired(管理端行内开关即走此通道);
|
||||
# rotating 不可进入——其现语义等于断供(resolve_credential 只解析 active),
|
||||
# 真实版本化轮换属 P2;存量 rotating 数据经置 active 即恢复。
|
||||
status = str(body['status']).strip()
|
||||
if status not in VALID_CREDENTIAL_UI_STATUSES:
|
||||
raise ValidationError(
|
||||
'invalid credential status', details={'allowed': list(VALID_CREDENTIAL_UI_STATUSES)})
|
||||
cred.status = status
|
||||
cred.status = str(body['status']).strip()
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_credential(cred))
|
||||
@@ -716,11 +430,6 @@ def update_credential_reference(code):
|
||||
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
|
||||
@require_admin
|
||||
def test_connection(code):
|
||||
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
|
||||
|
||||
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds 独立列
|
||||
拼回 config_json 后再交给 transport,否则存独立列的地址会被误判为未冻结。
|
||||
"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found')
|
||||
@@ -730,20 +439,9 @@ def test_connection(code):
|
||||
raise ValidationError(
|
||||
'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN',
|
||||
)
|
||||
client_payload = {
|
||||
'config_json': merge_client_config({
|
||||
'config_json': client.config_json or {},
|
||||
'endpoint': client.endpoint,
|
||||
'timeout_seconds': client.timeout_seconds,
|
||||
}),
|
||||
'credential': {},
|
||||
}
|
||||
probe = getattr(transport, 'probe', None)
|
||||
if probe is not None:
|
||||
raw = probe(client=client_payload)
|
||||
ok_flag = bool(raw.get('ok'))
|
||||
else:
|
||||
# 测试替身等未实现 probe 的传输:回退 call(空 interface 规格)。
|
||||
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
|
||||
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
|
||||
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
|
||||
raw = transport.call(
|
||||
client={'config_json': client.config_json or {}, 'credential': {}},
|
||||
interface={'request_spec_json': {}},
|
||||
request={},
|
||||
)
|
||||
return ok({'ok': True, 'status': raw.get('status') or 'success', 'result': raw})
|
||||
@@ -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')
|
||||
|
||||
@@ -199,7 +199,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)
|
||||
@@ -224,7 +224,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))
|
||||
|
||||
|
||||
@@ -249,7 +249,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)
|
||||
@@ -276,7 +276,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,
|
||||
@@ -302,7 +302,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):
|
||||
@@ -345,7 +345,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')
|
||||
@@ -542,7 +542,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:
|
||||
@@ -562,7 +562,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
|
||||
|
||||
@@ -576,7 +576,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
|
||||
|
||||
@@ -601,7 +601,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
|
||||
@@ -633,7 +633,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,
|
||||
@@ -1604,7 +1604,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
|
||||
@@ -1639,7 +1639,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
|
||||
@@ -1676,7 +1676,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,
|
||||
@@ -1724,7 +1724,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,
|
||||
@@ -1762,7 +1762,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 = {}
|
||||
@@ -1821,7 +1821,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
|
||||
|
||||
@@ -1867,7 +1867,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
|
||||
|
||||
@@ -2135,7 +2135,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
|
||||
@@ -2176,7 +2176,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,
|
||||
@@ -2277,7 +2277,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,
|
||||
@@ -2690,7 +2690,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))
|
||||
@@ -2700,7 +2700,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')
|
||||
@@ -2725,7 +2725,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 {}
|
||||
|
||||
@@ -255,8 +255,6 @@ class Config:
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
# 集成连接器凭据密文的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。
|
||||
INTEGRATION_CREDENTIAL_KEY = os.getenv('INTEGRATION_CREDENTIAL_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
@@ -284,14 +282,27 @@ class Config:
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2'))
|
||||
# 在途仓自动调拨(独立业务模块)参数;外部系统端点/凭据由集成连接器客户端实例管理。
|
||||
# 在途仓自动调拨(独立业务模块)参数;ERP 凭据仅由环境/Secret 注入,未配置时 fail-closed。
|
||||
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY', '2'))
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY', '2'))
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY', '1'))
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS', '60') or '60'
|
||||
)
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS', '60') or '60'
|
||||
)
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600'
|
||||
)
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3')
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
|
||||
# ERP SOAP:WSDL/endpoint 冻结前保持空(SoapErpTransport fail-closed)。
|
||||
IN_TRANSIT_TRANSFER_ERP_ENDPOINT = os.getenv('IN_TRANSIT_TRANSFER_ERP_ENDPOINT', '').strip()
|
||||
IN_TRANSIT_TRANSFER_ERP_USERNAME = os.getenv('IN_TRANSIT_TRANSFER_ERP_USERNAME', '').strip()
|
||||
IN_TRANSIT_TRANSFER_ERP_PASSWORD = os.getenv('IN_TRANSIT_TRANSFER_ERP_PASSWORD', '').strip()
|
||||
IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG = os.getenv('IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG', '').strip()
|
||||
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip()
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
|
||||
@@ -487,7 +498,7 @@ class Config:
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_overseas_thailand_guidelines')
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
|
||||
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
|
||||
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
||||
@@ -648,9 +659,7 @@ class Config:
|
||||
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
# 订单抽取发送后选择计划预算:合格附件全量入选批次 1,有多少单解析多少单;
|
||||
# 唯一生效的选择预算是 MAX_TOTAL_BYTES(超限转 Review)。数量类字段仅作快照
|
||||
# 审计记录,不再截断;总量由 EML 层(每封 20)与单次上传 intake 数兜底。
|
||||
# 订单抽取发送后选择计划预算:首轮只挑最相关附件,后续批次按固定预算待扩展。
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS', '2')
|
||||
)
|
||||
@@ -661,7 +670,7 @@ class Config:
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE', '2')
|
||||
)
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', '20')
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', '6')
|
||||
)
|
||||
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED = os.getenv(
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
"""app/core/credential_crypto.py
|
||||
|
||||
用途:通用 Fernet 凭据加解密(主密钥只来自 Flask config 的环境注入键,绝不落库明文)。
|
||||
依赖:cryptography.fernet、Flask current_app、app.core.errors。
|
||||
逻辑:调用方通过 CredentialCryptoErrorCodes 提供各自的业务错误码;主密钥缺失/无效时
|
||||
fail-closed 拒绝加密,避免产生不可恢复密文。shipping_notice(RPA Profile)与
|
||||
integration_connector(凭据引用)共用本模块,仅密钥键名与错误码不同。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CredentialCryptoErrorCodes:
|
||||
"""加解密失败的错误码集合(按调用方业务域自定义)。"""
|
||||
|
||||
key_missing: str
|
||||
key_invalid: str
|
||||
secret_empty: str
|
||||
secret_missing: str
|
||||
secret_invalid: str
|
||||
|
||||
|
||||
def _fernet(key_config_name: str, codes: CredentialCryptoErrorCodes) -> Fernet:
|
||||
"""从 Flask config 读取主密钥并构造加密器;缺失/无效即 fail-closed。"""
|
||||
key = str(current_app.config.get(key_config_name) or '').strip()
|
||||
if not key:
|
||||
raise ServiceUnavailableError(
|
||||
f'{key_config_name} is not configured',
|
||||
code=codes.key_missing,
|
||||
)
|
||||
try:
|
||||
return Fernet(key.encode('ascii'))
|
||||
except (ValueError, UnicodeEncodeError) as exc:
|
||||
raise ServiceUnavailableError(
|
||||
f'{key_config_name} is invalid',
|
||||
code=codes.key_invalid,
|
||||
) from exc
|
||||
|
||||
|
||||
def encrypt_secret(value: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
|
||||
"""加密单个凭据字段以便持久化;调用方不得记录明文。"""
|
||||
plaintext = str(value or '')
|
||||
if not plaintext:
|
||||
raise ValidationError('credential must not be empty', code=codes.secret_empty)
|
||||
return _fernet(key_config_name, codes).encrypt(plaintext.encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_secret(ciphertext: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
|
||||
"""在受控运行时解密密文;仅供当次调用内存使用,禁止落日志/响应。"""
|
||||
value = str(ciphertext or '').strip()
|
||||
if not value:
|
||||
raise ValidationError('credential ciphertext is missing', code=codes.secret_missing)
|
||||
try:
|
||||
return _fernet(key_config_name, codes).decrypt(value.encode('ascii')).decode('utf-8')
|
||||
except (InvalidToken, UnicodeDecodeError) as exc:
|
||||
raise ValidationError('credential ciphertext is invalid', code=codes.secret_invalid) from exc
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -31,15 +31,14 @@ def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
|
||||
raise RuntimeError(f"missing_transfer_precheck: {precheck_no}")
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
scope = precheck.scope_json if isinstance(precheck.scope_json, dict) else {}
|
||||
source_codes = list(scope.get("source_codes") or [])
|
||||
source_codes = list(precheck.scope_json.get("source_codes") or []) if isinstance(
|
||||
precheck.scope_json, dict
|
||||
) else []
|
||||
result = run_precheck(
|
||||
source_codes=source_codes,
|
||||
business_date=precheck.business_date,
|
||||
deps=deps,
|
||||
run_no=precheck.run.run_no if precheck.run else "RUN-PENDING",
|
||||
# 类型范围随预检落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
|
||||
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
|
||||
)
|
||||
summary = result.summary
|
||||
precheck.status = summary.status
|
||||
@@ -51,6 +50,6 @@ def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
}
|
||||
precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity
|
||||
precheck.estimated_external_write_count = summary.estimated_external_write_count
|
||||
precheck.estimated_erp_write_count = summary.estimated_erp_write_count
|
||||
precheck.precheck_hash = summary.precheck_hash
|
||||
db.session.commit()
|
||||
@@ -724,18 +724,6 @@ def _handoff_continue_order_extraction(
|
||||
return True
|
||||
|
||||
|
||||
def _is_transient_lock_error(exc: BaseException) -> bool:
|
||||
"""
|
||||
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
|
||||
|
||||
【AI 触发时机】:订单抽取 Job 异常收口时决定是否标记可重试。此类错误重试即可恢复,
|
||||
按终态失败收口会触发 run failed 并要求人工重新识别(2026-09-22 生产事故两次)。
|
||||
SQLAlchemy 将 DBAPI 错误包装为 exc.orig;非 DBAPI 异常(无 pgcode)一律返回 False。
|
||||
"""
|
||||
orig = getattr(exc, 'orig', None)
|
||||
return getattr(orig, 'pgcode', None) in {'40P01', '55P03'}
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
||||
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
@@ -929,16 +917,15 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
persisted_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||
wave_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||
# 重试路径:已 candidate_ready 的 Unit 仍须独立触发下游(幂等)。
|
||||
# [交接不变量] defer_stp_enqueue:开工快照仍有待排版附件(本 Job 必交接)时
|
||||
# 推迟 STP 入队到 run 收口,确保 STP 只由最后一个抽取 Job 提交;否则本 Job
|
||||
# 提交的 STP Job 会与续抽 Job 并发执行,双方以相反顺序抢 run/intake 行锁
|
||||
# 形成结构性死锁(2026-09-22 SNER-20260922-6466EB53 生产事故)。
|
||||
# 推送失败必须冒泡(与下方新单元推送同一规则):此处是这些 Unit 候选与
|
||||
# 复核 Case 的唯一物化触发点,吞掉等于静默丢单。
|
||||
progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
|
||||
defer_stp_enqueue=bool(pending_layout_ids),
|
||||
)
|
||||
try:
|
||||
progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
|
||||
)
|
||||
except Exception:
|
||||
from flask import current_app
|
||||
current_app.logger.exception(
|
||||
'retry unit progress failed run=%s unit=%s', run.run_no, unit.id,
|
||||
)
|
||||
continue
|
||||
if unit.status == 'review_required':
|
||||
continue
|
||||
@@ -1208,11 +1195,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
continue
|
||||
# [交接不变量] 同 replay 路径:本 Job 仍会交接时推迟 STP 入队到 run 收口。
|
||||
try:
|
||||
unit_persist = progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=merged_unit_orders,
|
||||
defer_stp_enqueue=bool(pending_layout_ids),
|
||||
)
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
@@ -1432,14 +1417,6 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
# [STEP] 瞬时锁错(PostgreSQL 死锁 40P01 / 锁超时 55P03)不收口 run/unit 失败:
|
||||
# 失败标记会写 run=failed,重试 Job 将被"run status is not executable"门弹掉。
|
||||
# 直接可重试入队,由队列在 attempts 耗尽前自动重排;冲突窗口为秒级,重试即过
|
||||
# (2026-09-22 SNER-20260922-6466EB53 / 879785D1 生产事故)。attempts 耗尽后
|
||||
# 走下方常规失败收口,fail-closed 语义不变。
|
||||
if _is_transient_lock_error(exc):
|
||||
fail_job(job.id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
|
||||
return
|
||||
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
retryable = False
|
||||
if run is not None and run.status in {'queued', 'processing', 'failed'}:
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -130,8 +130,4 @@ class GeneralFeedback(Base):
|
||||
feedback_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source_page: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
# 处理状态:pending=待处理,closed=已关闭(数据分析卡片用;默认待处理)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending', nullable=False, index=True)
|
||||
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -41,11 +41,6 @@ TRANSFER_RUN_STATUSES = (
|
||||
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
|
||||
# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。
|
||||
TRANSFER_RUN_TYPES = (
|
||||
'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub',
|
||||
)
|
||||
TRANSFER_SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
@@ -54,7 +49,7 @@ TRANSFER_PRECHECK_STATUSES = (
|
||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'success', 'failed', 'cancelled', 'expired',
|
||||
)
|
||||
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'external_query', 'external_write')
|
||||
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'erp_query', 'erp_write')
|
||||
TRANSFER_ATTEMPT_STATUSES = (
|
||||
'queued', 'running', 'waiting_external', 'success', 'failed',
|
||||
'result_unknown', 'superseded',
|
||||
@@ -80,10 +75,6 @@ class TransferRun(Base):
|
||||
"trigger_type IN ('manual', 'schedule')",
|
||||
name='ck_transfer_runs_trigger_type',
|
||||
),
|
||||
CheckConstraint(
|
||||
f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})",
|
||||
name='ck_transfer_runs_transfer_type',
|
||||
),
|
||||
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
|
||||
Index('ix_transfer_runs_business_date', 'business_date'),
|
||||
)
|
||||
@@ -91,10 +82,6 @@ class TransferRun(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
|
||||
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定预检收料数据范围。
|
||||
transfer_type: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||||
)
|
||||
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
|
||||
@@ -180,7 +167,7 @@ class TransferPrecheck(Base):
|
||||
strategy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
estimated_external_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
estimated_erp_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
@@ -197,24 +184,18 @@ class TransferPrecheck(Base):
|
||||
|
||||
|
||||
class TransferInvoiceItem(Base):
|
||||
"""预检明细项;同一预检内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
|
||||
|
||||
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
||||
"""
|
||||
"""预检明细项;同一预检内 Invoice 唯一,保留原始行追溯。"""
|
||||
|
||||
__tablename__ = 'transfer_invoice_items'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
|
||||
name='uq_transfer_invoice_items_precheck_grain',
|
||||
),
|
||||
UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'),
|
||||
CheckConstraint(
|
||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})",
|
||||
name='ck_transfer_invoice_items_status',
|
||||
),
|
||||
Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'),
|
||||
Index('ix_transfer_invoice_items_run_id', 'run_id'),
|
||||
Index('ix_transfer_invoice_items_external_document_no', 'external_document_no'),
|
||||
Index('ix_transfer_invoice_items_erp_document_no', 'erp_document_no'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -222,10 +203,6 @@ class TransferInvoiceItem(Base):
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
||||
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
||||
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||
@@ -234,11 +211,11 @@ class TransferInvoiceItem(Base):
|
||||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
|
||||
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
erp_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
external_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 原始文件行追溯:Sheet + 行号 + 文件版本(决策 11)。
|
||||
raw_lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
|
||||
@@ -22,7 +22,6 @@ from sqlalchemy import (
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
@@ -42,7 +41,7 @@ CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql')
|
||||
|
||||
|
||||
class IntegrationCredentialReference(Base):
|
||||
"""凭据引用:真实凭据加密落库(db 模式)或引用环境注入键(env 模式),绝不落库明文。"""
|
||||
"""凭据引用:只存 secret_ref 键 + 元数据,真实凭据由 Secret 服务注入,绝不落库明文。"""
|
||||
|
||||
__tablename__ = 'integration_credential_references'
|
||||
__table_args__ = (
|
||||
@@ -56,9 +55,6 @@ class IntegrationCredentialReference(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
secret_ref: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
# db 模式:凭据 JSON(如 {"username","password"})的 Fernet 密文;主密钥由
|
||||
# INTEGRATION_CREDENTIAL_KEY 环境注入。env 模式为空。绝不回显、绝不写日志。
|
||||
secret_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env')
|
||||
credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password')
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
|
||||
@@ -163,12 +159,9 @@ class IntegrationBinding(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
capability: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
# 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。
|
||||
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
|
||||
# 域参数 → 接口参数的声明式映射(map_response 规范:{接口参数: {expr/template/transform/args}});
|
||||
# 空对象 = 域参数同名直通。结构属绑定(capability↔接口的翻译契约),不属接口定义。
|
||||
# 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。
|
||||
param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
|
||||
# 最常用的 context 匹配键独立列(JSON 保留作兜底)。
|
||||
context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
client_instance_code: Mapped[str] = mapped_column(
|
||||
ForeignKey('integration_client_instances.code'), nullable=False,
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
@@ -37,8 +37,7 @@ class ShippingCustomer(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
standard_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
|
||||
# 业务规则:客户简码允许重复(不同标准客户可共用同一简码,仅用作编号前缀),禁止再加唯一约束。
|
||||
short_code: Mapped[str] = mapped_column(String(6), nullable=False)
|
||||
short_code: Mapped[str] = mapped_column(String(6), nullable=False, unique=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
||||
merged_into_customer_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_customers.id'),
|
||||
|
||||
@@ -160,13 +160,9 @@ class ShippingInventorySourceParsingBindingAudit(Base):
|
||||
class ShippingInventoryParsingProfile(Base):
|
||||
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
|
||||
|
||||
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表",
|
||||
用途以 purpose 字段为准,勿按表名推断只服务库存。
|
||||
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
|
||||
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
|
||||
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
|
||||
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id /
|
||||
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_parsing_profiles'
|
||||
@@ -362,14 +358,7 @@ class ShippingInventoryRoutingRuleVersion(Base):
|
||||
|
||||
|
||||
class ShippingInventoryExternalMapping(Base):
|
||||
"""库存源到外部系统仓库的映射。
|
||||
|
||||
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
|
||||
「仓库」列(空值即「空库位」默认映射行,下方两个部分唯一索引保证同源最多
|
||||
一条启用的精确/默认映射);fixed 源仅一条启用映射直接取用。
|
||||
in_transit_warehouse_code(在途仓编码)是在途调拨拨出库位的来源
|
||||
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
|
||||
"""
|
||||
"""货代库存身份到外部系统仓库的单向映射;不承载调拨规则。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_external_mappings'
|
||||
__table_args__ = (
|
||||
@@ -398,8 +387,6 @@ class ShippingInventoryExternalMapping(Base):
|
||||
external_site_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
external_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
external_warehouse_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
# 在途仓编码:在途调拨拨出库位来源(DefaultRouteResolver);保存端必填。
|
||||
in_transit_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, server_default='', default='')
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
|
||||
@@ -52,10 +52,7 @@ class ShippingReceiptReportConfig(Base):
|
||||
|
||||
|
||||
class ShippingReceiptRpaUnitRun(Base):
|
||||
"""一次收料执行的站点或站点-Warehouse 不可重复执行单元。
|
||||
|
||||
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
|
||||
"""
|
||||
"""一次收料排程内的站点或站点-Warehouse 不可重复执行单元。"""
|
||||
|
||||
__tablename__ = 'shipping_receipt_rpa_unit_runs'
|
||||
__table_args__ = (
|
||||
@@ -69,7 +66,7 @@ class ShippingReceiptRpaUnitRun(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
|
||||
schedule_run_id: Mapped[int] = mapped_column(ForeignKey('schedule_runs.id'), nullable=False, index=True)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
||||
retry_of_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
|
||||
@@ -88,7 +85,7 @@ class ShippingReceiptRpaUnitRun(Base):
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
|
||||
schedule_run: Mapped['ScheduleRun'] = relationship(foreign_keys=[schedule_run_id])
|
||||
inventory_source: Mapped['ShippingInventorySource'] = relationship()
|
||||
retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id])
|
||||
files: Mapped[list['ShippingReceiptReportFile']] = relationship(
|
||||
|
||||
+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
|
||||
|
||||
@@ -15,13 +16,7 @@ import requests
|
||||
from app import db
|
||||
from app.core.config.settings import Config
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent, AgentDirectoryMember, ChatLog, ChatSession, ChatToolRun,
|
||||
ContractReview, FaqHotCandidate, Feedback, GeneralFeedback,
|
||||
PermissionRequest, QuickQuestion, ScheduleTask, User,
|
||||
UserDefaultAgent, UserFavoriteAgent, user_agent_permissions,
|
||||
)
|
||||
from sqlalchemy import delete, select, update
|
||||
from app.models import Agent, User
|
||||
from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members
|
||||
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
|
||||
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
|
||||
@@ -118,40 +113,11 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def delete_agent(agent_id: int) -> None:
|
||||
"""
|
||||
删除 Agent 及其数据库引用,避免 chat_logs 外键导致管理端删除失败。
|
||||
|
||||
[STEP 1] 清理权限、目录、收藏、默认入口及业务直接引用。
|
||||
[STEP 2] 先清理 chat_log 子表,再删除会话日志。
|
||||
[STEP 3] 最后删除 Agent,整段操作使用当前事务保证原子性。
|
||||
"""
|
||||
"""删除 Agent(不存在时静默成功)。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
return
|
||||
chat_log_ids = select(ChatLog.id).where(ChatLog.agent_id == agent_id)
|
||||
db.session.execute(delete(user_agent_permissions).where(user_agent_permissions.c.agent_id == agent_id))
|
||||
db.session.execute(delete(AgentDirectoryMember).where(
|
||||
(AgentDirectoryMember.directory_agent_id == agent_id)
|
||||
| (AgentDirectoryMember.member_agent_id == agent_id)
|
||||
))
|
||||
db.session.execute(delete(UserFavoriteAgent).where(UserFavoriteAgent.agent_id == agent_id))
|
||||
db.session.execute(delete(UserDefaultAgent).where(UserDefaultAgent.agent_id == agent_id))
|
||||
db.session.execute(update(User).where(User.default_agent_id == agent_id).values(default_agent_id=None))
|
||||
db.session.execute(update(ScheduleTask).where(ScheduleTask.dify_agent_id == agent_id).values(dify_agent_id=None))
|
||||
db.session.execute(delete(PermissionRequest).where(PermissionRequest.agent_id == agent_id))
|
||||
db.session.execute(delete(ContractReview).where(ContractReview.agent_id == agent_id))
|
||||
db.session.execute(delete(QuickQuestion).where(QuickQuestion.agent_id == agent_id))
|
||||
db.session.execute(delete(FaqHotCandidate).where(FaqHotCandidate.agent_id == agent_id))
|
||||
db.session.execute(delete(ChatSession).where(ChatSession.agent_id == agent_id))
|
||||
db.session.execute(delete(ChatToolRun).where(
|
||||
(ChatToolRun.agent_id == agent_id) | ChatToolRun.chat_log_id.in_(chat_log_ids)
|
||||
))
|
||||
db.session.execute(delete(Feedback).where(Feedback.chat_log_id.in_(chat_log_ids)))
|
||||
db.session.execute(delete(GeneralFeedback).where(GeneralFeedback.chat_log_id.in_(chat_log_ids)))
|
||||
db.session.execute(delete(ContractReview).where(ContractReview.chat_log_id.in_(chat_log_ids)))
|
||||
db.session.execute(delete(ChatLog).where(ChatLog.agent_id == agent_id))
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
if agent:
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_agent_connectivity(agent_id: int) -> dict[str, Any]:
|
||||
@@ -205,65 +171,68 @@ def _test_iframe_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
"""
|
||||
Test Dify endpoint reachability without executing the configured application flow.
|
||||
|
||||
The test calls Dify's read-only ``/v1/parameters`` endpoint so a business
|
||||
Chatflow/Workflow never receives synthetic text such as ``OK`` that could be
|
||||
passed into a database or other external tool.
|
||||
"""
|
||||
if not agent.dify_api_key:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing dify_api_key.',
|
||||
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u672a\u914d\u7f6e API Key\u3002',
|
||||
'analysis': '测试失败:未配置 API Key。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
|
||||
if not base_url:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing api_base_url.',
|
||||
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u672a\u914d\u7f6e API Base URL\u3002',
|
||||
'analysis': '测试失败:未配置 API Base URL。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
dify_app_type = str(agent.dify_app_type or 'chatflow').strip().lower()
|
||||
if dify_app_type not in ('chatflow', 'workflow'):
|
||||
dify_app_type = 'chatflow'
|
||||
|
||||
# [STEP 1] Read-only endpoint: never run a business Chatflow/Workflow in an admin connectivity test.
|
||||
request_url = DifyService._build_parameters_url(base_url)
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}'}
|
||||
if dify_app_type == 'workflow':
|
||||
request_url = DifyService._build_workflow_url(base_url)
|
||||
payload = {
|
||||
'inputs': {'query': '系统连通性测试,请简短回复OK。'},
|
||||
'response_mode': 'blocking',
|
||||
'user': 'admin_test',
|
||||
}
|
||||
else:
|
||||
request_url = DifyService._build_chat_messages_url(base_url)
|
||||
payload = {
|
||||
'inputs': {},
|
||||
'query': '系统连通性测试,请简短回复OK。',
|
||||
'response_mode': 'blocking',
|
||||
'user': 'admin_test',
|
||||
}
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'}
|
||||
try:
|
||||
response = requests.get(request_url, headers=headers, timeout=(5, 15))
|
||||
raw_text = (response.text or '')[:4000]
|
||||
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
|
||||
raw_text = (resp.text or '')[:4000]
|
||||
output_info = raw_text
|
||||
if response.ok:
|
||||
passed = False
|
||||
analysis = f'测试失败:HTTP {resp.status_code}。'
|
||||
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
|
||||
passed = True
|
||||
analysis = '\u6d4b\u8bd5\u901a\u8fc7\uff1aDify \u53c2\u6570\u63a5\u53e3\u53ef\u8bbf\u95ee\u4e14 API Key \u8ba4\u8bc1\u901a\u8fc7\u3002'
|
||||
try:
|
||||
body = response.json()
|
||||
if isinstance(body, dict):
|
||||
output_info = str(body)[:4000]
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
passed = False
|
||||
analysis = f'\u6d4b\u8bd5\u5931\u8d25\uff1aHTTP {response.status_code}\u3002'
|
||||
try:
|
||||
body = response.json()
|
||||
if isinstance(body, dict) and body.get('message'):
|
||||
output_info = str(body['message'])[:4000]
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if passed and not agent.is_active:
|
||||
analysis = '测试通过:Workflow 接口可访问且认证通过。'
|
||||
try:
|
||||
data = resp.json()
|
||||
if dify_app_type == 'workflow':
|
||||
passed, output_info, analysis = _parse_workflow_test_response(resp, data, output_info, analysis)
|
||||
else:
|
||||
passed, output_info, analysis = _parse_chatflow_test_response(resp, data, output_info, analysis, passed)
|
||||
except ValueError:
|
||||
if resp.ok and raw_text.strip():
|
||||
passed = True
|
||||
analysis = (
|
||||
'测试通过:Workflow 接口可访问并返回了文本内容。'
|
||||
if dify_app_type == 'workflow'
|
||||
else '测试通过:Chatflow 接口可访问并返回了文本内容。'
|
||||
)
|
||||
if passed and (not agent.is_active):
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return {
|
||||
@@ -272,7 +241,7 @@ def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
'request_url': request_url,
|
||||
'output_info': output_info,
|
||||
'analysis': analysis,
|
||||
'http_status': response.status_code,
|
||||
'http_status': resp.status_code,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
except requests.RequestException as exc:
|
||||
@@ -281,11 +250,12 @@ def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
'dify_app_type': dify_app_type,
|
||||
'request_url': request_url,
|
||||
'output_info': str(exc),
|
||||
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u8bf7\u6c42\u5f02\u5e38\uff08\u7f51\u7edc\u3001\u8d85\u65f6\u6216\u8ba4\u8bc1\u95ee\u9898\uff09\u3002',
|
||||
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
|
||||
def _parse_workflow_test_response(resp, data, output_info: str, analysis: str) -> tuple[bool, str, str]:
|
||||
passed = 200 <= resp.status_code < 300
|
||||
workflow_data = data.get('data') if isinstance(data, dict) else None
|
||||
@@ -322,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')
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, User
|
||||
from app.models import Agent, ChatLog, Feedback, PermissionRequest, User
|
||||
|
||||
|
||||
def compute_dashboard_summary() -> dict:
|
||||
@@ -32,12 +32,29 @@ def compute_dashboard_summary() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def compute_dashboard_badges() -> dict:
|
||||
"""
|
||||
聚合侧栏角标所需的待办数量。
|
||||
Returns:
|
||||
pending_approvals、pending_requests。
|
||||
"""
|
||||
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0
|
||||
pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0
|
||||
return {
|
||||
'pending_approvals': pending_approvals,
|
||||
'pending_requests': pending_requests,
|
||||
}
|
||||
|
||||
|
||||
def compute_legacy_dashboard_stats() -> dict:
|
||||
"""遗留 /dashboard 接口响应(summary + badges 字段名兼容早期前端)。"""
|
||||
summary = compute_dashboard_summary()
|
||||
badges = compute_dashboard_badges()
|
||||
return {
|
||||
'total_users': summary['user_count'],
|
||||
'active_agents': summary['agent_count'],
|
||||
'total_conversations': summary['total_conversations'],
|
||||
'avg_score': summary['avg_score'],
|
||||
'pending_approvals': badges['pending_approvals'],
|
||||
'pending_requests': badges['pending_requests'],
|
||||
}
|
||||
@@ -19,6 +19,7 @@ from app.models import (
|
||||
ChatLog,
|
||||
Department,
|
||||
Feedback,
|
||||
PermissionRequest,
|
||||
QuickQuestion,
|
||||
User,
|
||||
UserDefaultAgent,
|
||||
@@ -32,6 +33,7 @@ ADMIN_TABLE_MODEL_MAP = {
|
||||
'agents': Agent,
|
||||
'chat_logs': ChatLog,
|
||||
'feedbacks': Feedback,
|
||||
'permission_requests': PermissionRequest,
|
||||
'departments': Department,
|
||||
'quick_questions': QuickQuestion,
|
||||
'user_homepage_configs': UserHomepageConfig,
|
||||
@@ -50,35 +52,6 @@ def _serialize_model_row(item) -> dict:
|
||||
return row
|
||||
|
||||
|
||||
def _apply_generic_table_filters(query, model, query_params: dict[str, str]):
|
||||
"""通用表筛选:created_at 时间范围(created_from/created_to)+ 各列 ILIKE/等值过滤。"""
|
||||
reserved = {'created_from', 'created_to'}
|
||||
# 时间范围(支持有 created_at 列的通用表,如 feedbacks 回答评价)
|
||||
created_from = (query_params.get('created_from') or '').strip()
|
||||
created_to = (query_params.get('created_to') or '').strip()
|
||||
if created_from and hasattr(model, 'created_at'):
|
||||
dt = report_service._parse_datetime(created_from, end_of_day=False)
|
||||
if dt:
|
||||
query = query.filter(model.created_at >= dt)
|
||||
if created_to and hasattr(model, 'created_at'):
|
||||
dt = report_service._parse_datetime(created_to, end_of_day=True)
|
||||
if dt:
|
||||
query = query.filter(model.created_at <= dt)
|
||||
|
||||
for key, value in query_params.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if hasattr(model, key):
|
||||
col = getattr(model, key)
|
||||
col_type = getattr(col, 'type', None)
|
||||
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
|
||||
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
|
||||
query = query.filter(col == int(value))
|
||||
else:
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||||
"""
|
||||
返回管理报表表数据(最多 100 行)。
|
||||
@@ -89,20 +62,28 @@ def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||||
if not model:
|
||||
raise ValidationError('Invalid table')
|
||||
query = _apply_generic_table_filters(db.session.query(model), model, query_params)
|
||||
query = db.session.query(model)
|
||||
for key, value in query_params.items():
|
||||
if hasattr(model, key) and value:
|
||||
col = getattr(model, key)
|
||||
col_type = getattr(col, 'type', None)
|
||||
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
|
||||
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
|
||||
query = query.filter(col == int(value))
|
||||
else:
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
items = query.limit(100).all()
|
||||
return [_serialize_model_row(item) for item in items]
|
||||
|
||||
|
||||
def get_table_count(table: str, query_params: dict[str, str]) -> dict:
|
||||
"""返回表行数(应用当前筛选);chat_logs 使用报表筛选。"""
|
||||
"""返回表行数;chat_logs 使用报表筛选。"""
|
||||
if table == 'chat_logs':
|
||||
return report_service.count_chat_logs_report(query_params)
|
||||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||||
if not model:
|
||||
raise ValidationError('Invalid table')
|
||||
query = _apply_generic_table_filters(db.session.query(model), model, query_params)
|
||||
total = query.count()
|
||||
total = db.session.query(func.count(model.id)).scalar()
|
||||
return {'table': table, 'total': int(total or 0)}
|
||||
|
||||
|
||||
|
||||
@@ -9,11 +9,9 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Department, User
|
||||
from app.models import Department
|
||||
|
||||
|
||||
def serialize_department(dept: Department) -> dict:
|
||||
@@ -29,43 +27,8 @@ def serialize_department(dept: Department) -> dict:
|
||||
|
||||
def list_departments() -> list[dict]:
|
||||
"""返回全部部门(按 name 升序)。"""
|
||||
rows = (
|
||||
db.session.query(Department, func.count(User.id).label('member_count'))
|
||||
.outerjoin(User, User.department == Department.name)
|
||||
.group_by(Department.id)
|
||||
.order_by(Department.name.asc())
|
||||
.all()
|
||||
)
|
||||
return [{**serialize_department(dept), 'member_count': int(member_count or 0)} for dept, member_count in rows]
|
||||
|
||||
|
||||
def list_department_members(dept_id: int) -> dict:
|
||||
"""
|
||||
查询指定部门的员工名单。
|
||||
|
||||
[STEP 1] 通过部门主键读取部门名称。
|
||||
[STEP 2] 复用现有 users.department 文本关联查询成员。
|
||||
[STEP 3] 返回人数与脱敏后的管理端成员资料。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if not dept:
|
||||
raise NotFoundError('Not found')
|
||||
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all()
|
||||
return {
|
||||
'department': serialize_department(dept),
|
||||
'count': len(users),
|
||||
'members': [
|
||||
{
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'email': user.email,
|
||||
'status': user.status,
|
||||
}
|
||||
for user in users
|
||||
],
|
||||
}
|
||||
depts = db.session.query(Department).order_by(Department.name.asc()).all()
|
||||
return [serialize_department(d) for d in depts]
|
||||
|
||||
|
||||
def create_department(data: dict[str, Any]) -> dict:
|
||||
|
||||
@@ -1,22 +1,35 @@
|
||||
"""
|
||||
backend/app/services/admin/permission_service.py
|
||||
|
||||
用途:用户 Agent 权限批量/单用户更新业务逻辑。
|
||||
依赖:models、integrations.wecom.notify.send_wecom_event_message。
|
||||
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
|
||||
依赖:models、wecom_notify.send_wecom_event_message。
|
||||
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.models import Agent, PermissionRequest, User
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
|
||||
|
||||
|
||||
def serialize_permission_request(req: PermissionRequest) -> dict:
|
||||
"""PermissionRequest ORM → 管理端列表 JSON。"""
|
||||
return {
|
||||
'id': req.id,
|
||||
'user_id': req.user_id,
|
||||
'agent_id': req.agent_id,
|
||||
'reason': req.reason,
|
||||
'status': req.status,
|
||||
'created_at': req.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def _load_users_and_agents(user_ids: list[Any], agent_ids: list[Any]) -> tuple[list[User], list[Agent]]:
|
||||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
|
||||
@@ -55,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')
|
||||
@@ -82,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')
|
||||
@@ -95,3 +108,72 @@ 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: 申请不存在。
|
||||
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')
|
||||
|
||||
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'}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -153,7 +153,13 @@ 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
|
||||
# 客户简码允许重复(业务规则),导入预检不再因简码撞码产生 warning。
|
||||
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,
|
||||
})
|
||||
normalized_name = normalize_customer_name(name)
|
||||
similar = [
|
||||
item for item in db.session.query(ShippingCustomer).all()
|
||||
|
||||
@@ -320,12 +320,23 @@ 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。
|
||||
@@ -340,6 +351,7 @@ 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')
|
||||
@@ -430,6 +442,7 @@ 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'}:
|
||||
|
||||
@@ -255,43 +255,15 @@ 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,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
# 异动解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
|
||||
'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[dict[str, str], list[dict[str, Any]]]:
|
||||
@@ -356,7 +328,6 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
|
||||
config.config_version += 1
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
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)
|
||||
@@ -364,8 +335,7 @@ 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,
|
||||
'parsing_profile_id': config.parsing_profile_id},
|
||||
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
@@ -1177,7 +1147,6 @@ 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,
|
||||
}
|
||||
|
||||
@@ -1209,11 +1178,8 @@ 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
|
||||
# 货代仓库改为可选维度: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()
|
||||
# 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
|
||||
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')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -4,5 +4,5 @@
|
||||
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
|
||||
Phase 1 起扩展 file_preparation / precheck_service 等。
|
||||
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
|
||||
对外部系统(RPA/外部系统/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
|
||||
对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
|
||||
"""
|
||||
@@ -108,7 +108,7 @@ def archive_snapshot(
|
||||
"""归档一份对象并持久化索引 + 审计。
|
||||
|
||||
Args:
|
||||
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_id: 业务对象编号(precheck_no / run_no)。
|
||||
data: 待归档字节。
|
||||
original_filename: 原始文件名。
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
|
||||
供 in-transit-transfer platform job 调用。
|
||||
依赖:recovery_service、precheck_service、execution_service、notification。
|
||||
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 外部系统 结果。
|
||||
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -45,7 +45,7 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
|
||||
|
||||
cancelled = 0
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.external_document_no:
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no:
|
||||
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||
item.result_code = "cancelled"
|
||||
item.result_message = reason_value
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
"""services/in_transit_transfer/capabilities.py
|
||||
|
||||
用途:在途调拨域的能力声明——本域经集成连接器暴露的能力契约(入参/出参 Schema、
|
||||
幂等语义、读写标志),代码注册、禁止管理端动态定义。
|
||||
依赖:integration_connector.capability(机制层:CapabilitySpec/注册表)。
|
||||
逻辑:本模块属于领域包而非连接器框架——框架只提供注册/校验机制,域契约随域代码
|
||||
版本化;应用组合根(app/__init__.py)在每次 create_app 时调用
|
||||
register_transfer_capabilities()(幂等),保证管理端「能力清单」冷启动即可见,
|
||||
测试 reset 注册表后也能重建。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.capability import (
|
||||
CapabilitySpec,
|
||||
list_capabilities,
|
||||
register_capability,
|
||||
)
|
||||
|
||||
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
|
||||
# 查询契约:按组织批量查库存,目标为 (料号, 拨出库位, 拨出批号) 元组列表;
|
||||
# external_org 取自仓库映射(external_organization_code),由绑定参数映射翻译为接口的 organization。
|
||||
_QUERY_INPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["external_org", "targets"],
|
||||
"properties": {
|
||||
"external_org": {"type": "string"},
|
||||
"targets": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"required": ["material_no", "from_warehouse", "lot_no"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
_QUERY_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["rows"],
|
||||
"properties": {
|
||||
"rows": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"required": ["material_no", "from_warehouse", "lot_no", "quantity"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
"quantity": {"type": "number"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
_WRITE_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["status"],
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
|
||||
},
|
||||
"document_no": {"type": ["string", "null"]},
|
||||
"verified_posted": {"type": ["boolean", "null"]},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def register_transfer_capabilities() -> None:
|
||||
"""注册在途调拨域的三个能力(幂等:已注册的同名跳过)。
|
||||
|
||||
幂等是硬要求:组合根每次 create_app 都会调用;测试 reset 注册表后(模块缓存导致
|
||||
import 副作用不再执行)也依赖本函数重建,故不能依赖「只注册一次」。
|
||||
"""
|
||||
registered = {spec.name for spec in list_capabilities()}
|
||||
for spec in (
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.query_inventory",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_QUERY_OUTPUT_SCHEMA,
|
||||
idempotency="none",
|
||||
write=False,
|
||||
),
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.create_transfer",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=True,
|
||||
),
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.verify_duplicate",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=False,
|
||||
),
|
||||
):
|
||||
if spec.name not in registered:
|
||||
register_capability(spec)
|
||||
|
||||
|
||||
register_transfer_capabilities()
|
||||
@@ -1,283 +0,0 @@
|
||||
"""services/in_transit_transfer/capability_client.py
|
||||
|
||||
用途:在途调拨域的外部访问统一客户端——查询经 CapabilityGateway 按能力批量调用;
|
||||
写路径在外部契约冻结前 fail-closed(Phase 2 接线点);域异常与写结果分类集中于此。
|
||||
依赖:integration_connector.gateway / errors、app.core.errors。
|
||||
逻辑:查询按 (料号, 拨出库位, 拨出批号) 元组批量进行,组织键 external_org 取自
|
||||
仓库映射(external_organization_code);查询超时→ExternalQueryTimeoutError,
|
||||
网关失败→AppError;写 transport 未注入时 create_transfer/verify_duplicate
|
||||
抛 ExternalNotFrozenError,注入后超时分类为 technical_failed / result_unknown。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
|
||||
|
||||
EXTERNAL_NOT_FROZEN_CODE = "TRANSFER.EXTERNAL_NOT_FROZEN"
|
||||
EXTERNAL_QUERY_TIMEOUT_CODE = "TRANSFER.EXTERNAL_QUERY_TIMEOUT"
|
||||
EXTERNAL_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
|
||||
|
||||
|
||||
class ExternalNotFrozenError(AppError):
|
||||
"""外部系统契约(WSDL/endpoint)尚未冻结,禁止调用(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "external system contract not frozen"):
|
||||
super().__init__(code=EXTERNAL_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
|
||||
|
||||
|
||||
class ExternalQueryTimeoutError(AppError):
|
||||
"""外部系统查询超时(只读路径,允许上层重试)。"""
|
||||
|
||||
def __init__(self, message: str = "external query timeout"):
|
||||
super().__init__(code=EXTERNAL_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
class ExternalResultUnknownError(AppError):
|
||||
"""外部系统写结果无法确认(Phase 2 使用);禁止自动重试。"""
|
||||
|
||||
def __init__(self, message: str = "external result unknown", *, operation_id: str | None = None):
|
||||
details = {"operation_id": operation_id} if operation_id else {}
|
||||
super().__init__(code=EXTERNAL_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
|
||||
|
||||
|
||||
class ExternalWriteTimeoutError(TimeoutError):
|
||||
"""外部系统写超时;committed 表达是否可证明已落单。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
committed: bool | None,
|
||||
document_no: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.committed = committed
|
||||
self.document_no = document_no
|
||||
self.operation_id = operation_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferWriteResult:
|
||||
"""外部系统原子建单/审核/过账结果分类。"""
|
||||
|
||||
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
|
||||
document_no: str | None = None
|
||||
verified_posted: bool | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockTarget:
|
||||
"""库存查询目标元组:料号 + 拨出库位 + 拨出批号。"""
|
||||
|
||||
material_no: str
|
||||
from_warehouse: str
|
||||
lot_no: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockRow:
|
||||
"""外部系统返回的一行账面库存。"""
|
||||
|
||||
material_no: str
|
||||
from_warehouse: str
|
||||
lot_no: str
|
||||
quantity: Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockQueryResult:
|
||||
"""一次批量库存查询的结果;按元组精确匹配取数。"""
|
||||
|
||||
rows: tuple[StockRow, ...]
|
||||
|
||||
def lookup(self, *, material_no: str, from_warehouse: str, lot_no: str) -> Decimal | None:
|
||||
"""按三元组取库存数量;同键多行累加;未命中返回 None。"""
|
||||
total: Decimal | None = None
|
||||
for row in self.rows:
|
||||
if (row.material_no, row.from_warehouse, row.lot_no) == (material_no, from_warehouse, lot_no):
|
||||
total = row.quantity if total is None else total + row.quantity
|
||||
return total
|
||||
|
||||
|
||||
class CapabilityClient:
|
||||
"""域内外部访问统一客户端:查询经 CapabilityGateway,写路径 fail-closed。
|
||||
|
||||
Args:
|
||||
gateway: 可注入替身(测试);缺省 get_capability_gateway()。
|
||||
write_transport: 写路径传输替身(Phase 2 前恒 None → 写调用抛
|
||||
ExternalNotFrozenError;测试注入后走经典写分类:可证明未落单→
|
||||
technical_failed,否则 result_unknown)。
|
||||
"""
|
||||
|
||||
def __init__(self, gateway: Any | None = None, write_transport: Any | None = None) -> None:
|
||||
self._gateway_override = gateway
|
||||
self._write_transport = write_transport
|
||||
|
||||
def _gateway(self) -> Any:
|
||||
if self._gateway_override is not None:
|
||||
return self._gateway_override
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
|
||||
return get_capability_gateway()
|
||||
|
||||
def query_stock(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
external_org: str,
|
||||
targets: list[StockTarget],
|
||||
) -> StockQueryResult:
|
||||
"""按组织批量查询库存(一次调用覆盖全部目标元组)。
|
||||
|
||||
Raises:
|
||||
ExternalQueryTimeoutError: 查询超时(可重试)。
|
||||
AppError: 网关失败(绑定缺失/调用失败,fail-closed)。
|
||||
"""
|
||||
if not targets:
|
||||
return StockQueryResult(rows=())
|
||||
result = self._gateway().call(
|
||||
capability=QUERY_INVENTORY_CAPABILITY,
|
||||
context={},
|
||||
params={
|
||||
"external_org": external_org,
|
||||
"targets": [
|
||||
{
|
||||
"material_no": target.material_no,
|
||||
"from_warehouse": target.from_warehouse,
|
||||
"lot_no": target.lot_no,
|
||||
}
|
||||
for target in targets
|
||||
],
|
||||
},
|
||||
operation_id=operation_id,
|
||||
)
|
||||
if result.status == "timeout":
|
||||
raise ExternalQueryTimeoutError()
|
||||
if result.status != "success":
|
||||
raise AppError(
|
||||
code=result.error_code or "INTEGRATION.CALL_FAILED",
|
||||
message=result.error_message or "query_inventory failed",
|
||||
http_status=503,
|
||||
retryable=False,
|
||||
)
|
||||
rows = [
|
||||
StockRow(
|
||||
material_no=str(row.get("material_no") or ""),
|
||||
from_warehouse=str(row.get("from_warehouse") or ""),
|
||||
lot_no=str(row.get("lot_no") or ""),
|
||||
quantity=Decimal(str(row.get("quantity") or "0")),
|
||||
)
|
||||
for row in ((result.data or {}).get("rows") or [])
|
||||
]
|
||||
return StockQueryResult(rows=tuple(rows))
|
||||
|
||||
def create_transfer(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
external_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""外部系统原子建单/审核/过账并按结果分类。
|
||||
|
||||
Returns:
|
||||
TransferWriteResult:success / duplicate_success / duplicate_unverified /
|
||||
business_failed / technical_failed / result_unknown。
|
||||
Raises:
|
||||
ExternalNotFrozenError: 写契约未冻结(write_transport 未注入)。
|
||||
"""
|
||||
if self._write_transport is None:
|
||||
raise ExternalNotFrozenError("external create_transfer contract not frozen (endpoint missing)")
|
||||
try:
|
||||
response = self._write_transport.create_transfer(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, external_org=external_org,
|
||||
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
except ExternalWriteTimeoutError as exc:
|
||||
if exc.committed is False:
|
||||
# 可证明未落单 → 明确技术失败(不产生单据)。
|
||||
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_TIMEOUT_BEFORE_COMMIT")
|
||||
return TransferWriteResult(
|
||||
status="result_unknown", error_code="EXTERNAL_TIMEOUT_AFTER_COMMIT",
|
||||
document_no=exc.document_no,
|
||||
)
|
||||
except TimeoutError:
|
||||
# 无法区分是否落单 → result_unknown,禁止自动重试。
|
||||
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
|
||||
return _classify_write_response(response)
|
||||
|
||||
def verify_duplicate(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
external_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
|
||||
|
||||
Returns:
|
||||
duplicate_success(已过账,含原单号)或 duplicate_unverified。
|
||||
"""
|
||||
if self._write_transport is None:
|
||||
raise ExternalNotFrozenError("external verify_duplicate contract not frozen (endpoint missing)")
|
||||
try:
|
||||
response = self._write_transport.verify_duplicate(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, external_org=external_org,
|
||||
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
except (TimeoutError, ExternalWriteTimeoutError):
|
||||
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
|
||||
response = response if isinstance(response, dict) else {}
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if status == "duplicate_success" and posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
|
||||
|
||||
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
|
||||
"""按外部系统写响应原文分类业务结果。"""
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
if status == "success":
|
||||
return TransferWriteResult(status="success", document_no=document_no)
|
||||
if status == "duplicate_success":
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=False,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
if status == "business_failed":
|
||||
return TransferWriteResult(
|
||||
status="business_failed",
|
||||
error_code=str(response.get("code") or "EXTERNAL_BUSINESS_REJECT"),
|
||||
error_message=str(response.get("message") or ""),
|
||||
)
|
||||
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_UNKNOWN_RESPONSE")
|
||||
@@ -42,18 +42,16 @@ class TransferPrecheckAction:
|
||||
"""执行只读预检并输出 transfer-precheck 卡片。
|
||||
|
||||
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
|
||||
只读,不写 外部系统。
|
||||
只读,不写 ERP。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])]
|
||||
business_date = str(payload.get("business_date") or business_date_now())
|
||||
transfer_type = str(payload.get("transfer_type")) if payload.get("transfer_type") else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_precheck(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
detail = restore_precheck(summary.precheck_id)
|
||||
yield _message(
|
||||
@@ -73,7 +71,7 @@ class TransferExecuteAction:
|
||||
"""执行勾选范围并输出 transfer-result 卡片。
|
||||
|
||||
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
|
||||
后台确定性服务完成写前复查与 外部系统 原子写入。
|
||||
后台确定性服务完成写前复查与 ERP 原子写入。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
precheck_id = str(payload.get("precheck_id") or "").strip()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨并发参数与单写者约束。
|
||||
|
||||
用途:冻结来源并发(2)、外部系统 查询并发(2)与 外部系统 写并发(1)默认值;
|
||||
外部系统 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值;
|
||||
ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
依赖:无(纯常量)。
|
||||
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
|
||||
"""
|
||||
@@ -10,8 +10,8 @@ from __future__ import annotations
|
||||
|
||||
# 一期冻结并发参数(与规格 §10 一致)。
|
||||
SOURCE_CONCURRENCY = 3
|
||||
外部系统_QUERY_CONCURRENCY = 3
|
||||
外部系统_WRITE_CONCURRENCY = 3
|
||||
ERP_QUERY_CONCURRENCY = 3
|
||||
ERP_WRITE_CONCURRENCY = 3
|
||||
|
||||
|
||||
def assert_single_writer(run_count: int) -> None:
|
||||
@@ -22,4 +22,4 @@ def assert_single_writer(run_count: int) -> None:
|
||||
Raises:
|
||||
AssertionError: run_count > 1(一期硬约束)。
|
||||
"""
|
||||
assert run_count <= 1, "External write concurrency must stay 1 for the same precheck"
|
||||
assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck"
|
||||
@@ -1,10 +1,10 @@
|
||||
"""在途调拨 DTO 与稳定错误码契约。
|
||||
|
||||
用途:冻结前后端契约(预检摘要、明细项、外部系统 单据聚合结果)与一期错误码,
|
||||
用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码,
|
||||
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
|
||||
依赖:标准库 dataclasses / decimal。
|
||||
逻辑:DTO 全部 frozen;aggregate_external_documents 按 外部系统 单号聚合最终结果页
|
||||
(决策 20:外部系统 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
|
||||
逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页
|
||||
(决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +20,7 @@ TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
|
||||
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
|
||||
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND = "TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND"
|
||||
TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND"
|
||||
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
|
||||
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
|
||||
@@ -37,7 +37,7 @@ KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
|
||||
TRANSFER_FILE_SCHEMA_INVALID,
|
||||
TRANSFER_INVOICE_CONFLICT,
|
||||
TRANSFER_QUANTITY_MISMATCH,
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND,
|
||||
TRANSFER_ERP_INVENTORY_NOT_FOUND,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED,
|
||||
@@ -84,7 +84,7 @@ class RawLineRefDTO:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckInvoiceItemDTO:
|
||||
"""预检明细项(决策 6 十列 + 2026-09-21 增批号:拨出批号/拨入批号由 lot_no 转换派生,lot_no 存原值)。"""
|
||||
"""预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。"""
|
||||
|
||||
source_code: str
|
||||
material_no: str
|
||||
@@ -98,16 +98,13 @@ class PrecheckInvoiceItemDTO:
|
||||
result: str
|
||||
receipt_date: str | None = None
|
||||
reason: str = ""
|
||||
external_document_no: str | None = None
|
||||
erp_document_no: str | None = None
|
||||
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||
receipt_warehouse_code: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckSummaryDTO:
|
||||
"""预检摘要(含预计调拨数量、预计 外部系统 写入数与预检 Hash)。"""
|
||||
"""预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。"""
|
||||
|
||||
precheck_id: str
|
||||
status: str
|
||||
@@ -116,14 +113,14 @@ class PrecheckSummaryDTO:
|
||||
expires_at: str
|
||||
counts: PrecheckCountsDTO
|
||||
estimated_transfer_quantity: str
|
||||
estimated_external_write_count: int
|
||||
estimated_erp_write_count: int
|
||||
precheck_hash: str
|
||||
|
||||
|
||||
# ---- 结果页 DTO(决策 20)--------------------------------------------------
|
||||
@dataclass(frozen=True)
|
||||
class ExternalDocumentLineDTO:
|
||||
"""外部系统 单据内物料明细。"""
|
||||
class ErpDocumentLineDTO:
|
||||
"""ERP 单据内物料明细。"""
|
||||
|
||||
material_no: str
|
||||
material_name: str
|
||||
@@ -133,8 +130,8 @@ class ExternalDocumentLineDTO:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExternalDocumentDTO:
|
||||
"""按 外部系统 单号聚合的结果项。"""
|
||||
class ErpDocumentDTO:
|
||||
"""按 ERP 单号聚合的结果项。"""
|
||||
|
||||
document_no: str
|
||||
from_warehouse: str
|
||||
@@ -142,12 +139,12 @@ class ExternalDocumentDTO:
|
||||
material_count: int
|
||||
total_quantity: Decimal
|
||||
posting_status: str
|
||||
lines: tuple[ExternalDocumentLineDTO, ...] = field(default_factory=tuple)
|
||||
lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferExceptionDTO:
|
||||
"""未生成 外部系统 单据的异常项(单独展示)。"""
|
||||
"""未生成 ERP 单据的异常项(单独展示)。"""
|
||||
|
||||
source_code: str
|
||||
invoice_no: str
|
||||
@@ -158,31 +155,31 @@ class TransferExceptionDTO:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RunResultDTO:
|
||||
"""Run 最终结果投影:外部系统 单据聚合 + 未生成单据异常。"""
|
||||
"""Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。"""
|
||||
|
||||
run_no: str
|
||||
status: str
|
||||
external_documents: tuple[ExternalDocumentDTO, ...] = field(default_factory=tuple)
|
||||
erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple)
|
||||
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def aggregate_external_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
|
||||
"""按 外部系统 单号聚合成功项,产出结果页文档视图。
|
||||
def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]:
|
||||
"""按 ERP 单号聚合成功项,产出结果页文档视图。
|
||||
|
||||
Args:
|
||||
items: 预检明细项(含 external_document_no 与 result)。
|
||||
items: 预检明细项(含 erp_document_no 与 result)。
|
||||
Returns:
|
||||
按单号聚合的 ExternalDocumentDTO 元组(行按 Invoice 排序)。
|
||||
按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。
|
||||
"""
|
||||
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
|
||||
for item in items:
|
||||
if item.external_document_no and item.result in {"success", "duplicate_success"}:
|
||||
grouped.setdefault(item.external_document_no, []).append(item)
|
||||
documents: list[ExternalDocumentDTO] = []
|
||||
if item.erp_document_no and item.result in {"success", "duplicate_success"}:
|
||||
grouped.setdefault(item.erp_document_no, []).append(item)
|
||||
documents: list[ErpDocumentDTO] = []
|
||||
for document_no in sorted(grouped):
|
||||
rows = sorted(grouped[document_no], key=lambda row: row.invoice_no)
|
||||
lines = tuple(
|
||||
ExternalDocumentLineDTO(
|
||||
ErpDocumentLineDTO(
|
||||
material_no=row.material_no,
|
||||
material_name=row.material_name,
|
||||
specification=row.specification,
|
||||
@@ -191,7 +188,7 @@ def aggregate_external_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tup
|
||||
)
|
||||
for row in rows
|
||||
)
|
||||
documents.append(ExternalDocumentDTO(
|
||||
documents.append(ErpDocumentDTO(
|
||||
document_no=document_no,
|
||||
from_warehouse=rows[0].from_warehouse,
|
||||
to_warehouse=rows[0].to_warehouse,
|
||||
|
||||
@@ -20,30 +20,19 @@ MATURITY_NOT_MATURED = "not_matured"
|
||||
MATURITY_FUTURE = "future"
|
||||
|
||||
|
||||
def parse_date(value: date | datetime | str) -> date:
|
||||
"""将 date/datetime 或日期字符串归一化为 date。
|
||||
def parse_date(value: date | str) -> date:
|
||||
"""将 date 或 'YYYY-MM-DD' 字符串归一化为 date。
|
||||
|
||||
Args:
|
||||
value: date/datetime 对象,或日期字符串(允许携带时间部分,如
|
||||
Excel 日期单元格经字符串化的 '2026-08-26 17:38:38')。
|
||||
value: date 对象或 ISO 日期字符串。
|
||||
Returns:
|
||||
归一化后的 date。
|
||||
Raises:
|
||||
ValueError: 字符串不是可识别的日期/日期时间。
|
||||
ValueError: 字符串不是合法 ISO 日期。
|
||||
"""
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
text = str(value).strip()
|
||||
try:
|
||||
return date.fromisoformat(text)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return datetime.fromisoformat(text).date()
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Invalid date value: {value!r}") from exc
|
||||
return date.fromisoformat(str(value).strip())
|
||||
|
||||
|
||||
def business_date_now(moment: datetime | None = None) -> date:
|
||||
@@ -62,29 +51,6 @@ def business_date_now(moment: datetime | None = None) -> date:
|
||||
return moment.astimezone(SHANGHAI_TZ).date()
|
||||
|
||||
|
||||
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
|
||||
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
||||
|
||||
用途:判定"文件是否当天抓取"等新鲜度场景。数据库统一存 naive UTC 时间,
|
||||
直接取 .date() 与业务日期比较会漂移 8 小时,必须先换算窗口再比较。
|
||||
Args:
|
||||
now: 可选时刻;naive 按 UTC 兼容处理(与 business_date_now 口径一致)。
|
||||
Returns:
|
||||
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(SHANGHAI_TZ)
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=ZoneInfo("UTC"))
|
||||
sh_now = now.astimezone(SHANGHAI_TZ)
|
||||
start_utc = (
|
||||
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=SHANGHAI_TZ)
|
||||
.astimezone(ZoneInfo("UTC"))
|
||||
.replace(tzinfo=None)
|
||||
)
|
||||
return start_utc, start_utc + timedelta(hours=24)
|
||||
|
||||
|
||||
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
|
||||
"""按 D+1 规则判定收料日期成熟度。
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""在途调拨依赖装配(Dependencies)。
|
||||
|
||||
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
|
||||
依赖:movement_file_repository / capability_client / precheck_service / models。
|
||||
依赖:movement_file_repository / gateway_adapter / precheck_service / models。
|
||||
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
|
||||
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
|
||||
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed)。
|
||||
fail-closed 拒绝;ERP 访问走 CapabilityGateway(绑定缺失时 fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient
|
||||
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
|
||||
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteMapping,
|
||||
@@ -24,66 +24,35 @@ from app.services.in_transit_transfer.precheck_service import (
|
||||
|
||||
|
||||
class DefaultRouteResolver:
|
||||
"""默认路由解析:仓库映射的在途仓编码 + 外部系统仓库。
|
||||
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
|
||||
|
||||
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
|
||||
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
|
||||
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
|
||||
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
|
||||
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
|
||||
路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。
|
||||
"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(须启用)。
|
||||
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
|
||||
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
|
||||
Returns:
|
||||
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
|
||||
Raises:
|
||||
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
|
||||
"""
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
"""按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
mappings = ShippingInventoryExternalMapping.query.filter_by(
|
||||
mapping = ShippingInventoryExternalMapping.query.filter_by(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
).all()
|
||||
selected = None
|
||||
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
|
||||
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
|
||||
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
|
||||
key = str(warehouse_code or '').strip().upper()
|
||||
if key:
|
||||
selected = next(
|
||||
(m for m in mappings if str(m.freight_warehouse_id or '').strip().upper() == key), None,
|
||||
)
|
||||
if selected is None:
|
||||
selected = next((m for m in mappings if not str(m.freight_warehouse_id or '').strip()), None)
|
||||
else:
|
||||
selected = mappings[0] if mappings else None
|
||||
if selected is None or not selected.external_organization_code:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
from_warehouse = str(selected.in_transit_warehouse_code or '').strip()
|
||||
if not from_warehouse:
|
||||
# 拨出库位无来源(映射未维护在途仓编码)——fail-closed,不猜测。
|
||||
).first()
|
||||
if mapping is None or not mapping.external_organization_code:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
return RouteMapping(
|
||||
external_org=selected.external_organization_code,
|
||||
from_warehouse=from_warehouse,
|
||||
to_warehouse=selected.external_warehouse_code,
|
||||
erp_org=mapping.external_organization_code,
|
||||
from_warehouse=source.fixed_warehouse_id or "",
|
||||
to_warehouse=mapping.external_warehouse_code,
|
||||
)
|
||||
|
||||
|
||||
def _build_capability_client() -> CapabilityClient:
|
||||
"""装配调拨外部访问客户端:查询走 CapabilityGateway(绑定缺失时 fail-closed)。
|
||||
def _build_erp_adapter() -> CapabilityErpAdapter:
|
||||
"""装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。
|
||||
|
||||
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
|
||||
承担;create_transfer/verify_duplicate 在 WSDL 冻结前 fail-closed(Phase 2 接线)。
|
||||
承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。
|
||||
"""
|
||||
return CapabilityClient()
|
||||
return CapabilityErpAdapter()
|
||||
|
||||
|
||||
_override: TransferDeps | None = None
|
||||
@@ -96,14 +65,14 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
|
||||
|
||||
|
||||
def get_transfer_dependencies() -> TransferDeps:
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/外部系统 网关)。"""
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/ERP 网关)。"""
|
||||
if _override is not None:
|
||||
return _override
|
||||
return TransferDeps(
|
||||
file_repository=ShippingReceiptFileRepository(),
|
||||
rpa_trigger=_DefaultRpaTrigger(),
|
||||
route_resolver=DefaultRouteResolver(),
|
||||
capabilities=_build_capability_client(),
|
||||
erp=_build_erp_adapter(),
|
||||
)
|
||||
|
||||
|
||||
@@ -112,25 +81,11 @@ class _DefaultRpaTrigger:
|
||||
|
||||
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
|
||||
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
|
||||
另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时
|
||||
直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。
|
||||
"""
|
||||
|
||||
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
|
||||
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
|
||||
# 抓回的文件无法被 latest_ready_file 复用,预检会反复重抓。fail-closed 返回明确错误码。
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is not None:
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
if config is not None:
|
||||
profile = config.parsing_profile
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
|
||||
return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'}
|
||||
|
||||
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
|
||||
return {
|
||||
"ok": bool(outcome.get("ok")),
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
"""在途调拨 ERP 访问统一边界(Adapter)。
|
||||
|
||||
用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。
|
||||
Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer /
|
||||
verify_duplicate / 结果分类。
|
||||
依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。
|
||||
逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no /
|
||||
erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试;
|
||||
SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN"
|
||||
ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT"
|
||||
ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventoryQuery:
|
||||
"""ERP 账面库存查询结果。"""
|
||||
|
||||
found: bool
|
||||
quantity: Decimal | None = None
|
||||
document_no: str | None = None
|
||||
|
||||
|
||||
class ErpNotFrozenError(AppError):
|
||||
"""ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "ERP contract not frozen"):
|
||||
super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
|
||||
|
||||
|
||||
class ErpQueryTimeoutError(AppError):
|
||||
"""ERP 查询超时(只读路径,允许上层重试)。"""
|
||||
|
||||
def __init__(self, message: str = "ERP query timeout"):
|
||||
super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
class ErpResultUnknownError(AppError):
|
||||
"""ERP 写结果无法确认(Phase 2 使用);禁止自动重试。"""
|
||||
|
||||
def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None):
|
||||
details = {"operation_id": operation_id} if operation_id else {}
|
||||
super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
|
||||
|
||||
|
||||
class ErpWriteTimeoutError(TimeoutError):
|
||||
"""ERP 写超时;committed 表达是否可证明已落单。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
committed: bool | None,
|
||||
document_no: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.committed = committed
|
||||
self.document_no = document_no
|
||||
self.operation_id = operation_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferWriteResult:
|
||||
"""ERP 原子建单/审核/过账结果分类。"""
|
||||
|
||||
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
|
||||
document_no: str | None = None
|
||||
verified_posted: bool | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
class ErpTransport(Protocol):
|
||||
"""ERP 传输层协议(SOAP 或测试替身)。"""
|
||||
|
||||
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""按 Invoice 查询账面库存。"""
|
||||
|
||||
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""原子建单/审核/过账(Phase 2)。"""
|
||||
|
||||
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""核实重复 Invoice 原单是否已审核过账。"""
|
||||
|
||||
|
||||
class SoapErpTransport:
|
||||
"""真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。
|
||||
|
||||
Args:
|
||||
config: 来自 Flask config 或环境变量(endpoint/username/password 等)。
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict[str, Any] | None = None) -> None:
|
||||
self._config = config or {}
|
||||
|
||||
def _require_frozen(self, operation: str) -> None:
|
||||
"""WSDL/endpoint 未冻结前任何调用直接拒绝。"""
|
||||
if not str(self._config.get("endpoint") or "").strip():
|
||||
raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)")
|
||||
|
||||
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 查询账面库存(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("query_inventory")
|
||||
raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL")
|
||||
|
||||
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("create_transfer")
|
||||
raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL")
|
||||
|
||||
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("verify_duplicate")
|
||||
raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL")
|
||||
|
||||
|
||||
class ErpAdapter:
|
||||
"""ERP 唯一访问入口;组装统一请求并分类结果。"""
|
||||
|
||||
def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None:
|
||||
self._transport = transport
|
||||
self._default_org = default_org
|
||||
|
||||
def query_inventory(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> InventoryQuery:
|
||||
"""查询 ERP 账面库存并分类结果。
|
||||
|
||||
Args:
|
||||
operation_id / run_no / attempt_no / invoice_no / erp_org /
|
||||
from_warehouse / to_warehouse / quantity: 请求强制追踪字段。
|
||||
Returns:
|
||||
InventoryQuery。
|
||||
Raises:
|
||||
ErpQueryTimeoutError: 查询超时(可重试)。
|
||||
ErpNotFrozenError: ERP 契约未冻结。
|
||||
"""
|
||||
request = {
|
||||
"operation_id": operation_id,
|
||||
"run_no": run_no,
|
||||
"attempt_no": attempt_no,
|
||||
"invoice_no": invoice_no,
|
||||
"erp_org": erp_org or self._default_org,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
}
|
||||
try:
|
||||
response = self._transport.query_inventory(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except TimeoutError as exc:
|
||||
raise ErpQueryTimeoutError() from exc
|
||||
response = response if isinstance(response, dict) else {}
|
||||
if response.get("found"):
|
||||
return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0")))
|
||||
return InventoryQuery(found=False)
|
||||
|
||||
def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org,
|
||||
from_warehouse, to_warehouse, quantity) -> dict[str, Any]:
|
||||
"""组装携带全部强制追踪字段的 ERP 请求。"""
|
||||
return {
|
||||
"operation_id": operation_id,
|
||||
"run_no": run_no,
|
||||
"attempt_no": attempt_no,
|
||||
"invoice_no": invoice_no,
|
||||
"erp_org": erp_org or self._default_org,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
}
|
||||
|
||||
def create_transfer(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""ERP 原子建单/审核/过账并按结果分类。
|
||||
|
||||
Returns:
|
||||
TransferWriteResult:success / duplicate_success / duplicate_unverified /
|
||||
business_failed / technical_failed / result_unknown。
|
||||
Raises:
|
||||
ErpNotFrozenError: ERP 契约未冻结。
|
||||
"""
|
||||
request = self._build_request(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
|
||||
to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
try:
|
||||
response = self._transport.create_transfer(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except ErpWriteTimeoutError as exc:
|
||||
if exc.committed is False:
|
||||
# 可证明未落单 → 明确技术失败(不产生单据)。
|
||||
return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT")
|
||||
return TransferWriteResult(
|
||||
status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT",
|
||||
document_no=exc.document_no,
|
||||
)
|
||||
except TimeoutError:
|
||||
# 无法区分是否落单 → result_unknown,禁止自动重试。
|
||||
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
|
||||
return _classify_write_response(response)
|
||||
|
||||
def verify_duplicate(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
|
||||
|
||||
Returns:
|
||||
duplicate_success(已过账,含原单号)或 duplicate_unverified。
|
||||
"""
|
||||
request = self._build_request(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
|
||||
to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
try:
|
||||
response = self._transport.verify_duplicate(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except (TimeoutError, ErpWriteTimeoutError):
|
||||
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
|
||||
response = response if isinstance(response, dict) else {}
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if status == "duplicate_success" and posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
|
||||
|
||||
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
|
||||
"""按 ERP 写响应原文分类业务结果。"""
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
if status == "success":
|
||||
return TransferWriteResult(status="success", document_no=document_no)
|
||||
if status == "duplicate_success":
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=False,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
if status == "business_failed":
|
||||
return TransferWriteResult(
|
||||
status="business_failed",
|
||||
error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"),
|
||||
error_message=str(response.get("message") or ""),
|
||||
)
|
||||
return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE")
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨七 Sheet 异常 Excel 导出。
|
||||
|
||||
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/外部系统无库存/
|
||||
外部系统技术失败/外部系统结果未知/通知失败/原始文件追溯),供企微附件与下载。
|
||||
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/
|
||||
ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。
|
||||
依赖:openpyxl、models、execution_service。
|
||||
逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本;
|
||||
Secret 明文永不写入单元格(仅输出业务字段)。
|
||||
@@ -21,9 +21,9 @@ from app.core.errors import NotFoundError
|
||||
EXCEL_SHEET_NAMES = [
|
||||
"执行汇总",
|
||||
"数量不一致",
|
||||
"外部系统无库存",
|
||||
"外部系统技术失败",
|
||||
"外部系统结果未知",
|
||||
"ERP无库存",
|
||||
"ERP技术失败",
|
||||
"ERP结果未知",
|
||||
"通知失败",
|
||||
"原始文件追溯",
|
||||
]
|
||||
@@ -53,8 +53,8 @@ def build_exceptions_workbook(run_no: str) -> bytes:
|
||||
|
||||
_sheet_summary(workbook, run, items)
|
||||
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
|
||||
_sheet_blocked(workbook, items, "外部系统无库存", {"blocked_inventory_not_found"})
|
||||
_sheet_blocked(workbook, items, "外部系统技术失败", {"business_failed", "technical_failed", "item_execution_error"})
|
||||
_sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"})
|
||||
_sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"})
|
||||
_sheet_unknown(workbook, items)
|
||||
_sheet_notification(workbook, run)
|
||||
_sheet_raw_trace(workbook, items)
|
||||
@@ -71,30 +71,30 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
|
||||
sheet.append(["Run 状态", run.status])
|
||||
sheet.append(["通知状态", run.notification_status])
|
||||
sheet.append([])
|
||||
sheet.append(["Invoice", "来源", "料号", "预检结果", "外部系统 单号"])
|
||||
sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"])
|
||||
for item in items:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
item.result_code or item.status, item.external_document_no or "",
|
||||
item.result_code or item.status, item.erp_document_no or "",
|
||||
])
|
||||
|
||||
|
||||
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
|
||||
"""按阻断原因归类 Sheet。"""
|
||||
sheet = workbook.create_sheet(sheet_name)
|
||||
sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"])
|
||||
sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"])
|
||||
for item in items:
|
||||
if (item.result_code or "") in codes or item.status in codes:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
item.receipt_quantity, item.external_quantity or "",
|
||||
item.receipt_quantity, item.erp_quantity or "",
|
||||
item.result_message or item.result_code or item.status,
|
||||
])
|
||||
|
||||
|
||||
def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
|
||||
"""外部系统 结果未知 Sheet(只读提示,含 Operation 关联)。"""
|
||||
sheet = workbook.create_sheet("外部系统结果未知")
|
||||
"""ERP 结果未知 Sheet(只读提示,含 Operation 关联)。"""
|
||||
sheet = workbook.create_sheet("ERP结果未知")
|
||||
sheet.append(["Invoice", "来源", "料号", "说明"])
|
||||
sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""])
|
||||
for item in items:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨执行服务(确认门禁 + 写前复查 + 外部系统 原子写入 + 结果投影)。
|
||||
"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。
|
||||
|
||||
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
|
||||
逐项写前复查 外部系统 库存 → 原子建单/审核/过账 → 按 外部系统 单号投影最终结果。
|
||||
依赖:orchestrator、capability_client、quantity、contracts、audit、status、models。
|
||||
逻辑:未确认/过期/快照变化/选择含不可执行项 → 外部系统 写调用为 0;
|
||||
逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。
|
||||
依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。
|
||||
逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0;
|
||||
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
|
||||
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
|
||||
"""
|
||||
@@ -24,11 +24,11 @@ from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
ExternalDocumentDTO,
|
||||
ErpDocumentDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
RunResultDTO,
|
||||
TransferExceptionDTO,
|
||||
aggregate_external_documents,
|
||||
aggregate_erp_documents,
|
||||
)
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
@@ -36,7 +36,6 @@ from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteNotResolvedError,
|
||||
TransferDeps,
|
||||
)
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
|
||||
PRECHECK_EXPIRED_RESULT = "precheck_expired"
|
||||
@@ -73,7 +72,7 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"receipt_quantity": item.receipt_quantity,
|
||||
"external_quantity": item.external_quantity,
|
||||
"erp_quantity": item.erp_quantity,
|
||||
"result": _item_result_of(item),
|
||||
}
|
||||
for item in sorted(precheck.items, key=lambda row: row.id)
|
||||
@@ -89,11 +88,6 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
|
||||
},
|
||||
"items": items,
|
||||
}
|
||||
# [调拨类型] 创建时快照含 transfer_type(2026-09-22 起 scope_json 恒写入);
|
||||
# 存量预检 scope_json 无该字段时保持旧快照形状,避免复算 Hash 不一致误判过期。
|
||||
scope_transfer_type = str(precheck.scope_json.get("transfer_type") or "").strip()
|
||||
if scope_transfer_type:
|
||||
snapshot["transfer_type"] = scope_transfer_type
|
||||
return f"sha256:{canonical_hash(snapshot)}"
|
||||
|
||||
|
||||
@@ -121,7 +115,7 @@ def execute_precheck(
|
||||
Returns:
|
||||
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
|
||||
Raises:
|
||||
NotFoundError / ValidationError / AppError: 门禁失败(外部系统 写入为 0)。
|
||||
NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。
|
||||
ConflictError: 重复执行。
|
||||
"""
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(
|
||||
@@ -191,48 +185,42 @@ def execute_precheck(
|
||||
|
||||
|
||||
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
|
||||
"""写前复查 + 外部系统 原子写入单个 Invoice(创建新 Attempt)。"""
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
"""写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。"""
|
||||
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
|
||||
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
|
||||
return
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
# [STEP 1] 写前复查:重新查询外部系统库存并严格匹配冻结收料数量。
|
||||
# [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。
|
||||
try:
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=route.external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
)],
|
||||
)
|
||||
stock_qty = stock.lookup(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
|
||||
invoice_no=item.invoice_no, erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
)
|
||||
except RouteNotResolvedError:
|
||||
raise
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "external inventory changed since precheck")
|
||||
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck")
|
||||
return
|
||||
|
||||
# [STEP 2] 记录写 Attempt 并调用外部系统原子建单/审核/过账。
|
||||
# [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="external_write",
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="erp_write",
|
||||
status="running", operation_id=operation_id,
|
||||
request_snapshot_json={
|
||||
"run_no": run_no, "invoice_no": item.invoice_no, "external_org": route.external_org,
|
||||
"run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
result = deps.capabilities.create_transfer(
|
||||
result = deps.erp.create_transfer(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
|
||||
invoice_no=item.invoice_no, external_org=route.external_org,
|
||||
invoice_no=item.invoice_no, erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
)
|
||||
@@ -242,7 +230,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
|
||||
|
||||
|
||||
def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None:
|
||||
"""写前复查失败:fail-closed,不写 外部系统。"""
|
||||
"""写前复查失败:fail-closed,不写 ERP。"""
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = result
|
||||
item.result_message = message
|
||||
@@ -250,7 +238,7 @@ def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str)
|
||||
|
||||
|
||||
def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None:
|
||||
"""按 外部系统 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
|
||||
"""按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
|
||||
attempt.response_summary_json = {
|
||||
"status": result.status,
|
||||
"document_no": result.document_no,
|
||||
@@ -259,12 +247,12 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
|
||||
}
|
||||
if result.status == "success":
|
||||
item.status = status_machine.TransferStatus.SUCCESS.value
|
||||
item.external_document_no = result.document_no
|
||||
item.erp_document_no = result.document_no
|
||||
item.result_code = None
|
||||
attempt.status = "success"
|
||||
elif result.status == "duplicate_success":
|
||||
item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value
|
||||
item.external_document_no = result.document_no
|
||||
item.erp_document_no = result.document_no
|
||||
item.result_code = None
|
||||
attempt.status = "success"
|
||||
elif result.status == "result_unknown":
|
||||
@@ -282,7 +270,7 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
|
||||
|
||||
|
||||
def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None:
|
||||
"""为每次 外部系统 写入追加审计事件(脱敏快照 + Hash)。"""
|
||||
"""为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。"""
|
||||
event = build_transfer_audit_event(
|
||||
event_type="TRANSFER_ITEM_EXECUTED",
|
||||
aggregate_type="transfer_item",
|
||||
@@ -296,7 +284,7 @@ def _audit_item_write(item, run_no, request_id, operation_id, before_status) ->
|
||||
operation_id=operation_id,
|
||||
result="success" if item.status in {"success", "duplicate_success"} else "failure",
|
||||
before={"status": before_status},
|
||||
after={"status": item.status, "external_document_no": item.external_document_no},
|
||||
after={"status": item.status, "erp_document_no": item.erp_document_no},
|
||||
)
|
||||
db.session.add(event)
|
||||
|
||||
@@ -324,7 +312,7 @@ def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = N
|
||||
|
||||
|
||||
def get_run(run_no: str) -> dict[str, Any]:
|
||||
"""按 run_no 恢复 Run 最终结果(外部系统 单号聚合 + 未生成单据异常)。"""
|
||||
"""按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。"""
|
||||
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
@@ -349,13 +337,12 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=result,
|
||||
reason=item.result_message or "",
|
||||
external_document_no=item.external_document_no,
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
erp_document_no=item.erp_document_no,
|
||||
))
|
||||
if result not in {"success", "duplicate_success"}:
|
||||
exceptions.append(TransferExceptionDTO(
|
||||
@@ -363,12 +350,12 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
reason=result,
|
||||
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
|
||||
facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""),
|
||||
))
|
||||
return RunResultDTO(
|
||||
run_no=run.run_no,
|
||||
status=run.status,
|
||||
external_documents=aggregate_external_documents(item_dtos),
|
||||
erp_documents=aggregate_erp_documents(item_dtos),
|
||||
exceptions=tuple(exceptions),
|
||||
)
|
||||
|
||||
@@ -378,7 +365,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
|
||||
return {
|
||||
"run_no": result.run_no,
|
||||
"status": result.status,
|
||||
"external_documents": [
|
||||
"erp_documents": [
|
||||
{
|
||||
"document_no": document.document_no,
|
||||
"from_warehouse": document.from_warehouse,
|
||||
@@ -397,7 +384,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
|
||||
for line in document.lines
|
||||
],
|
||||
}
|
||||
for document in result.external_documents
|
||||
for document in result.erp_documents
|
||||
],
|
||||
"exceptions": [
|
||||
{
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from typing import Any, Iterable, Mapping
|
||||
|
||||
@@ -34,9 +34,6 @@ class ParsedReceiptRow:
|
||||
specification: str
|
||||
receipt_date: date
|
||||
receipt_quantity: Decimal
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
|
||||
warehouse_code: str = ""
|
||||
|
||||
|
||||
class ReceiptFileSchemaError(AppError):
|
||||
@@ -56,18 +53,6 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
|
||||
rows.append({"row_no": row_no, "reason": reason})
|
||||
|
||||
|
||||
def _is_unreceived_row(date_value: Any) -> bool:
|
||||
"""判断是否为"无收料事实的在途行":无异动日期即跳过。
|
||||
|
||||
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
|
||||
① 未收料在途 ASN(Date Received 空、Qty Received 0);
|
||||
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
|
||||
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与预检;
|
||||
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
|
||||
"""
|
||||
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
|
||||
|
||||
|
||||
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
|
||||
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
|
||||
|
||||
@@ -75,9 +60,8 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
|
||||
doc_no → invoice_no(幂等/汇总键)
|
||||
quantity → receipt_quantity(严格数量匹配)
|
||||
movement_date → receipt_date(成熟过滤)
|
||||
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
|
||||
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
|
||||
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
|
||||
lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
|
||||
Args:
|
||||
source_code: 任务来源实例(行内来源身份一致性校验)。
|
||||
@@ -136,7 +120,7 @@ def _parse_rows(
|
||||
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
|
||||
到原始行字段名的映射(如 {invoice_no: doc_no})。
|
||||
Returns:
|
||||
已校验的 ParsedReceiptRow 列表("无异动日期"的在途/执行中行已跳过)。
|
||||
已校验的 ParsedReceiptRow 列表。
|
||||
Raises:
|
||||
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
|
||||
"""
|
||||
@@ -153,7 +137,7 @@ def _parse_rows(
|
||||
invoice_no = str(row.get(invoice_key) or "").strip()
|
||||
material_no = str(row.get(material_key) or "").strip()
|
||||
sheet = str(row.get("sheet") or "").strip()
|
||||
receipt_date_value = row.get(date_key)
|
||||
receipt_date_raw = str(row.get(date_key) or "").strip()
|
||||
quantity_raw = row.get(quantity_key)
|
||||
|
||||
if not sheet or not row_no:
|
||||
@@ -169,12 +153,10 @@ def _parse_rows(
|
||||
if row_source and row_source.upper() != str(source_code).upper():
|
||||
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
|
||||
continue
|
||||
if _is_unreceived_row(receipt_date_value):
|
||||
continue
|
||||
try:
|
||||
receipt_date = parse_date(receipt_date_value)
|
||||
receipt_date = parse_date(receipt_date_raw)
|
||||
except ValueError:
|
||||
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_value!r}")
|
||||
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}")
|
||||
continue
|
||||
try:
|
||||
quantity = validate_receipt_quantity(quantity_raw)
|
||||
@@ -191,8 +173,6 @@ def _parse_rows(
|
||||
specification=str(row.get("specification") or "").strip(),
|
||||
receipt_date=receipt_date,
|
||||
receipt_quantity=quantity,
|
||||
lot_no=str(row.get("lot_no") or "").strip(),
|
||||
warehouse_code=str(row.get("warehouse_code") or "").strip(),
|
||||
))
|
||||
if errors:
|
||||
raise ReceiptFileSchemaError(rows=errors)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""services/in_transit_transfer/gateway_adapter.py
|
||||
|
||||
用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用
|
||||
(query_inventory 是首个配置绑定消费者)。
|
||||
依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。
|
||||
逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer /
|
||||
verify_duplicate 留待调拨执行阶段(Phase 2)接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery
|
||||
|
||||
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
|
||||
|
||||
|
||||
class CapabilityErpAdapter:
|
||||
"""把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。
|
||||
|
||||
Args:
|
||||
gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。
|
||||
"""
|
||||
|
||||
def __init__(self, gateway: Any | None = None) -> None:
|
||||
self._gateway = gateway
|
||||
|
||||
def _gateway_or_default(self):
|
||||
if self._gateway is not None:
|
||||
return self._gateway
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
|
||||
return get_capability_gateway()
|
||||
|
||||
def query_inventory(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> InventoryQuery:
|
||||
"""查询外部系统库存(经连接器框架)。
|
||||
|
||||
Args/Raises:
|
||||
与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError;
|
||||
写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={});
|
||||
来源专属绑定待 P2/P3。
|
||||
"""
|
||||
result = self._gateway_or_default().call(
|
||||
capability=QUERY_INVENTORY_CAPABILITY,
|
||||
context={},
|
||||
params={
|
||||
"invoice_no": invoice_no,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
},
|
||||
operation_id=operation_id,
|
||||
)
|
||||
if result.status == "timeout":
|
||||
raise ErpQueryTimeoutError()
|
||||
if result.status != "success":
|
||||
raise AppError(
|
||||
code=result.error_code or "INTEGRATION.CALL_FAILED",
|
||||
message=result.error_message or "query_inventory failed",
|
||||
http_status=503,
|
||||
retryable=False,
|
||||
)
|
||||
data = result.data or {}
|
||||
found = bool(data.get("found"))
|
||||
qty = data.get("quantity")
|
||||
return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨 Invoice 多行汇总。
|
||||
"""在途调拨 Invoice 多行汇总与冲突阻断。
|
||||
|
||||
用途:相同 Invoice+料号+收料日期 的多行只汇总收料数量,并永久保留原始
|
||||
Sheet/行号/文件版本;同 Invoice 跨料号或跨日期自然拆分为多张发票。
|
||||
用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本;
|
||||
同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。
|
||||
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
|
||||
逻辑:汇总键 (source_code, invoice_no, material_no, receipt_date)。
|
||||
逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,9 +30,6 @@ class AggregatedInvoice:
|
||||
receipt_date: date
|
||||
receipt_quantity: Decimal
|
||||
raw_lines: tuple[RawLineRefDTO, ...]
|
||||
lot_no: str = ""
|
||||
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
|
||||
warehouse_code: str = ""
|
||||
|
||||
|
||||
class InvoiceConflictError(AppError):
|
||||
@@ -48,25 +45,34 @@ class InvoiceConflictError(AppError):
|
||||
|
||||
|
||||
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
|
||||
"""按 Invoice+料号+收料日期 汇总收料数量并保留原始行证据。
|
||||
"""按 Invoice 汇总收料数量并保留原始行证据。
|
||||
|
||||
汇总键 (source_code, invoice_no, material_no, receipt_date):Invoice 语义为
|
||||
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨收料日期时
|
||||
自然拆分为多张发票(部分交付场景),不做整单阻断。
|
||||
Args:
|
||||
rows: 已校验的解析行。
|
||||
file_version: 当前文件版本(写入原始行追溯)。
|
||||
Returns:
|
||||
汇总后的 Invoice 列表(按汇总键排序)。
|
||||
汇总后的 Invoice 列表(按 Invoice 排序)。
|
||||
Raises:
|
||||
InvoiceConflictError: 同一 Invoice 多料号或多收料日期。
|
||||
"""
|
||||
grouped: dict[tuple[str, str, str, date], list[ParsedReceiptRow]] = {}
|
||||
grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {}
|
||||
for row in rows:
|
||||
grouped.setdefault(
|
||||
(row.source_code, row.invoice_no, row.material_no, row.receipt_date), [],
|
||||
).append(row)
|
||||
grouped.setdefault((row.source_code, row.invoice_no), []).append(row)
|
||||
|
||||
invoices: list[AggregatedInvoice] = []
|
||||
for (source_code, invoice_no, material_no, receipt_date), group in sorted(grouped.items()):
|
||||
for (source_code, invoice_no), group in sorted(grouped.items()):
|
||||
material_nos = {row.material_no for row in group}
|
||||
dates = {row.receipt_date for row in group}
|
||||
if len(material_nos) > 1:
|
||||
raise InvoiceConflictError(
|
||||
invoice_no=invoice_no,
|
||||
conflict=f"multiple_material_no: {sorted(material_nos)}",
|
||||
)
|
||||
if len(dates) > 1:
|
||||
raise InvoiceConflictError(
|
||||
invoice_no=invoice_no,
|
||||
conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}",
|
||||
)
|
||||
first = group[0]
|
||||
raw_lines = tuple(
|
||||
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
|
||||
@@ -75,13 +81,11 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
|
||||
invoices.append(AggregatedInvoice(
|
||||
source_code=source_code,
|
||||
invoice_no=invoice_no,
|
||||
material_no=material_no,
|
||||
material_no=first.material_no,
|
||||
material_name=first.material_name,
|
||||
specification=first.specification,
|
||||
receipt_date=receipt_date,
|
||||
receipt_date=first.receipt_date,
|
||||
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
|
||||
raw_lines=raw_lines,
|
||||
lot_no=first.lot_no,
|
||||
warehouse_code=first.warehouse_code,
|
||||
))
|
||||
return invoices
|
||||
@@ -41,8 +41,6 @@ class MovementField:
|
||||
|
||||
|
||||
# 定死的 10 个通用异动字段(领域契约,不配置化)。
|
||||
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
|
||||
# 批号(lot_no)为展示维度——预检列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
|
||||
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
|
||||
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
|
||||
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
|
||||
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
|
||||
movement_contract、receipt_file_gate(可用性门禁)、openpyxl。
|
||||
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
|
||||
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
|
||||
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
|
||||
校验由下游 file_parser 完成。
|
||||
movement_contract、openpyxl。
|
||||
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
|
||||
返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域字段 + 溯源字段
|
||||
(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整校验由下游
|
||||
file_parser 完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,7 +18,6 @@ from typing import Any, Mapping
|
||||
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
|
||||
|
||||
class ShippingReceiptFileRepository:
|
||||
@@ -28,14 +27,13 @@ class ShippingReceiptFileRepository:
|
||||
self._storage = file_asset_storage
|
||||
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
|
||||
"""返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。
|
||||
"""返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
|
||||
Returns:
|
||||
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
|
||||
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
|
||||
"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
|
||||
|
||||
@@ -54,8 +52,7 @@ class ShippingReceiptFileRepository:
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
@@ -117,11 +114,7 @@ def _extract_movement_rows(
|
||||
headers = [str(c or '').strip() for c in raw_rows[header_idx]]
|
||||
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
|
||||
|
||||
header_to_code: dict[str, list[str]] = {}
|
||||
for code, alias in field_mapping.items():
|
||||
# 一个表头别名可被多个领域字段共用(如 CRANE 单号/批号同源 ASN 列);
|
||||
# 反查必须是 一别名→多字段,不得互相覆盖。
|
||||
header_to_code.setdefault(str(alias).strip(), []).append(str(code).strip())
|
||||
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
|
||||
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
|
||||
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
|
||||
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
|
||||
@@ -133,16 +126,11 @@ def _extract_movement_rows(
|
||||
]
|
||||
|
||||
|
||||
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, list[str]]) -> dict[str, Any]:
|
||||
"""把一行原始单元格按表头别名映射为定死领域字段 dict。
|
||||
|
||||
header_to_code 为 一别名→多字段 列表:共用同一表头别名的字段
|
||||
(如 doc_no 与 lot_no 同源一列)各自都写入该单元格值,互不覆盖。
|
||||
"""
|
||||
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
|
||||
"""把一行原始单元格按表头别名映射为定死领域字段 dict。"""
|
||||
output: dict[str, Any] = {}
|
||||
for index, header in enumerate(headers):
|
||||
codes = header_to_code.get(header)
|
||||
if codes and index < len(row):
|
||||
for code in codes:
|
||||
output[code] = row[index]
|
||||
code = header_to_code.get(header)
|
||||
if code and index < len(row):
|
||||
output[code] = row[index]
|
||||
return output
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨企业微信汇总通知。
|
||||
|
||||
用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录
|
||||
notification_failed 且不改变 外部系统 业务结果(run.status 保持)。
|
||||
notification_failed 且不改变 ERP 业务结果(run.status 保持)。
|
||||
依赖:models、audit、typing.Protocol。
|
||||
逻辑:通知状态独立于 外部系统 状态;已成功投递幂等(每个 Run 一条)。
|
||||
逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -65,7 +65,7 @@ def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str
|
||||
if failed:
|
||||
run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED")
|
||||
run.notification_error_message = str(outcome.get("error_message") or "")
|
||||
# 关键:通知失败绝不修改 run.status(外部系统 业务结果保持)。
|
||||
# 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_NOTIFICATION",
|
||||
aggregate_type="transfer_run",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""在途调拨预检服务。
|
||||
|
||||
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → 外部系统 库存查询 →
|
||||
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 →
|
||||
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
|
||||
依赖:file_preparation / file_parser / invoice_aggregator / capability_client /
|
||||
依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter /
|
||||
date_policy / quantity / contracts / audit / models。
|
||||
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 外部系统;
|
||||
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP;
|
||||
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
|
||||
"""
|
||||
|
||||
@@ -29,13 +29,11 @@ from app.services.in_transit_transfer.contracts import (
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
MATURITY_ELIGIBLE,
|
||||
eligible_receipt_date_to,
|
||||
MATURITY_FUTURE,
|
||||
MATURITY_NOT_MATURED,
|
||||
maturity_status,
|
||||
parse_date,
|
||||
)
|
||||
from app.services.in_transit_transfer.capability_client import ExternalQueryTimeoutError, StockTarget
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
@@ -49,6 +47,7 @@ from app.services.in_transit_transfer.file_preparation import (
|
||||
ensure_receipt_file_ready,
|
||||
)
|
||||
from app.services.in_transit_transfer.invoice_aggregator import (
|
||||
InvoiceConflictError,
|
||||
aggregate_invoices,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
@@ -56,13 +55,6 @@ from app.services.in_transit_transfer.strategy import (
|
||||
TransferStrategyPolicy,
|
||||
default_strategy,
|
||||
)
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
TransferType,
|
||||
ensure_transfer_type_supported,
|
||||
filter_invoices_for_type,
|
||||
normalize_transfer_type,
|
||||
transfer_type_scope_note,
|
||||
)
|
||||
|
||||
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
|
||||
|
||||
@@ -72,15 +64,14 @@ RESULT_NOT_MATURED = "not_matured"
|
||||
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
|
||||
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
|
||||
RESULT_FUTURE_DATE = "blocked_future_date"
|
||||
RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
|
||||
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RouteMapping:
|
||||
"""来源路由:外部组织(external_org,取自仓库映射)/ 拨出仓(外部在途仓)/ 拨入仓(映射仓)。"""
|
||||
"""来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。"""
|
||||
|
||||
external_org: str
|
||||
erp_org: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
|
||||
@@ -100,8 +91,8 @@ class RouteNotResolvedError(AppError):
|
||||
class RouteResolver(Protocol):
|
||||
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
"""返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -133,7 +124,7 @@ class TransferDeps:
|
||||
file_repository: ReceiptFileRepository
|
||||
rpa_trigger: RpaTrigger
|
||||
route_resolver: RouteResolver
|
||||
capabilities: Any
|
||||
erp: Any
|
||||
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
|
||||
|
||||
|
||||
@@ -153,40 +144,22 @@ def run_precheck(
|
||||
deps: TransferDeps,
|
||||
active_source_job_key: str | None = None,
|
||||
run_no: str = "RUN-PENDING",
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> PrecheckRunResult:
|
||||
"""执行一次只读预检(不写 外部系统)。
|
||||
"""执行一次只读预检(不写 ERP)。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
|
||||
business_date: 业务日期 T(YYYY-MM-DD)。
|
||||
deps: 注入的文件仓库 / RPA / 路由 / 外部系统 依赖。
|
||||
deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。
|
||||
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
|
||||
run_no: Run 编号(创建 Run 前可为占位)。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
|
||||
transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。
|
||||
Returns:
|
||||
PrecheckRunResult(摘要 + 明细 + 来源进度)。
|
||||
Raises:
|
||||
ValidationError: source_codes 为空、日期范围非法或调拨类型非法/未支持。
|
||||
ValidationError: source_codes 为空。
|
||||
"""
|
||||
if not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
# [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。
|
||||
range_from = parse_date(receipt_date_from) if receipt_date_from else None
|
||||
range_to = parse_date(receipt_date_to) if receipt_date_to else None
|
||||
if range_from and range_to and range_from > range_to:
|
||||
raise ValidationError(
|
||||
"receipt date range is invalid", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
|
||||
)
|
||||
if range_to and range_to > eligible_receipt_date_to(business_date):
|
||||
raise ValidationError(
|
||||
"receipt date range end exceeds D+1 maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
|
||||
)
|
||||
validate_strategy = deps.strategy
|
||||
|
||||
sources: list[SourceProgressDTO] = []
|
||||
@@ -220,13 +193,6 @@ def run_precheck(
|
||||
# (doc_no/material_code/quantity/movement_date),按异动解析规则映射校验。
|
||||
parsed = parse_movement_rows(source_code=source_code, rows=ready_file.rows)
|
||||
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
|
||||
if range_from is not None:
|
||||
invoices = [invoice for invoice in invoices if invoice.receipt_date >= range_from]
|
||||
if range_to is not None:
|
||||
invoices = [invoice for invoice in invoices if invoice.receipt_date <= range_to]
|
||||
# [调拨类型] 类型决定收料数据范围(如类型1仅保留 INVOICE 前缀 HOM/HOX/WTP),
|
||||
# 范围外票与日期范围过滤同语义:静默排除、不入明细、不阻断来源。
|
||||
invoices = filter_invoices_for_type(invoices, resolved_transfer_type)
|
||||
source_items = _precheck_invoices(
|
||||
invoices=invoices,
|
||||
source_code=source_code,
|
||||
@@ -243,7 +209,7 @@ def run_precheck(
|
||||
file_version=ready_file.file_version,
|
||||
checksum=ready_file.checksum,
|
||||
))
|
||||
except ReceiptFileSchemaError as exc:
|
||||
except (ReceiptFileSchemaError, InvoiceConflictError) as exc:
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code=exc.code, error_message=exc.message,
|
||||
@@ -275,7 +241,6 @@ def run_precheck(
|
||||
snapshot = {
|
||||
"scope": sorted(set(source_codes)),
|
||||
"business_date": business_date,
|
||||
"transfer_type": resolved_transfer_type.value,
|
||||
"file_snapshot": file_snapshot,
|
||||
"counts": {
|
||||
"file_invoice_count": counts.file_invoice_count,
|
||||
@@ -291,7 +256,7 @@ def run_precheck(
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"receipt_quantity": str(item.to_quantity),
|
||||
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"result": item.result,
|
||||
}
|
||||
for item in items
|
||||
@@ -309,7 +274,7 @@ def run_precheck(
|
||||
expires_at="",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=str(estimated_quantity),
|
||||
estimated_external_write_count=counts.executable_count,
|
||||
estimated_erp_write_count=counts.executable_count,
|
||||
precheck_hash=precheck_hash,
|
||||
)
|
||||
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||
@@ -324,12 +289,8 @@ def _precheck_invoices(
|
||||
deps: TransferDeps,
|
||||
run_no: str,
|
||||
) -> list[PrecheckInvoiceItemDTO]:
|
||||
"""对单个来源的汇总 Invoice 预检(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
|
||||
"""对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。"""
|
||||
output: list[PrecheckInvoiceItemDTO] = []
|
||||
|
||||
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位,
|
||||
# 成熟项按 external_org(仓库映射的外部组织)分组,每组合并为一次批量查询。
|
||||
matured: list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]] = []
|
||||
for invoice in invoices:
|
||||
maturity = maturity_status(invoice.receipt_date, business_date)
|
||||
raw = tuple(
|
||||
@@ -341,11 +302,10 @@ def _precheck_invoices(
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse="", from_quantity=None,
|
||||
to_warehouse="", to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
@@ -353,98 +313,61 @@ def _precheck_invoices(
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse="", from_quantity=None,
|
||||
to_warehouse="", to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_FUTURE_DATE, reason="future receipt date",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=source_code, invoice_no=invoice.invoice_no,
|
||||
warehouse_code=invoice.warehouse_code or "",
|
||||
)
|
||||
matured.append((invoice, route, raw, receipt_date_iso))
|
||||
|
||||
groups: dict[str, list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]]] = {}
|
||||
for entry in matured:
|
||||
groups.setdefault(entry[1].external_org, []).append(entry)
|
||||
|
||||
# [STEP 2] 每个组织一次批量查询(targets = 料号+拨出库位+拨出批号 元组列表),
|
||||
# 组内逐票按三元组精确匹配库存数量;组级故障降级到组内全部票,不炸整来源。
|
||||
for external_org, entries in groups.items():
|
||||
targets = [
|
||||
StockTarget(material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no)
|
||||
for invoice, route, _, _ in entries
|
||||
]
|
||||
route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no)
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
try:
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=external_org, targets=targets,
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id,
|
||||
run_no=run_no,
|
||||
attempt_no=1,
|
||||
invoice_no=invoice.invoice_no,
|
||||
erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse,
|
||||
to_warehouse=route.to_warehouse,
|
||||
quantity=invoice.receipt_quantity,
|
||||
)
|
||||
except ExternalQueryTimeoutError:
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_EXTERNAL_QUERY_TIMEOUT, reason="external query timeout",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
|
||||
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
|
||||
# 组内逐票给 blocked_external_query_failed + 原因,预检列表保持可见可解释。
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_EXTERNAL_QUERY_FAILED, reason=f"external query failed: {detail}",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
stock_qty = stock.lookup(
|
||||
material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no,
|
||||
)
|
||||
if stock_qty is None:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
# 查无库存记录也是外部系统的真实答复:库存数按 0 展示(而非"-"),
|
||||
# 避免用户误以为查询失败;分类仍为 blocked_inventory_not_found。
|
||||
from_quantity=Decimal("0"), to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_INVENTORY_NOT_FOUND, reason="external inventory not found",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
match = classify_quantity_match(invoice.receipt_quantity, stock_qty)
|
||||
except ErpQueryTimeoutError:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=stock_qty, to_warehouse=route.to_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
if not query.found:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
match = classify_quantity_match(invoice.receipt_quantity, query.quantity)
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=query.quantity, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
|
||||
raw_lines=raw,
|
||||
))
|
||||
return output
|
||||
|
||||
|
||||
@@ -454,7 +377,7 @@ def _item_status(result: str) -> str:
|
||||
RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value,
|
||||
RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
}
|
||||
@@ -473,29 +396,20 @@ def create_precheck(
|
||||
business_date: str,
|
||||
deps: TransferDeps,
|
||||
active_source_job_key: str | None = None,
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> PrecheckSummaryDTO:
|
||||
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_precheck。
|
||||
receipt_date_from / receipt_date_to / transfer_type: 同 run_precheck。
|
||||
Returns:
|
||||
预检摘要(precheck_id 已回填)。
|
||||
"""
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
run_no = _generate_no("RUN", business_date)
|
||||
result = run_precheck(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
active_source_job_key=active_source_job_key,
|
||||
receipt_date_from=receipt_date_from,
|
||||
receipt_date_to=receipt_date_to,
|
||||
transfer_type=resolved_transfer_type,
|
||||
run_no=run_no,
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
@@ -506,7 +420,6 @@ def create_precheck(
|
||||
status="prechecking",
|
||||
source_codes_json=list(source_codes),
|
||||
counts_json=asdict(result.summary.counts),
|
||||
transfer_type=resolved_transfer_type.value,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
@@ -524,8 +437,6 @@ def create_precheck(
|
||||
run_id=run.id,
|
||||
source_code=job_source.source_code,
|
||||
status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending',
|
||||
error_code=job_source.error_code,
|
||||
error_message=job_source.error_message,
|
||||
)
|
||||
|
||||
precheck_no = _generate_no("TPC", business_date)
|
||||
@@ -534,13 +445,7 @@ def create_precheck(
|
||||
run_id=run.id,
|
||||
business_date=business_date,
|
||||
status=result.summary.status,
|
||||
scope_json={
|
||||
"source_codes": list(source_codes),
|
||||
"receipt_date_from": receipt_date_from,
|
||||
"receipt_date_to": receipt_date_to,
|
||||
"transfer_type": resolved_transfer_type.value,
|
||||
"transfer_type_scope": transfer_type_scope_note(resolved_transfer_type),
|
||||
},
|
||||
scope_json={"source_codes": list(source_codes)},
|
||||
file_snapshot_json={
|
||||
stage.source_code: {
|
||||
"file_no": stage.file_no,
|
||||
@@ -554,65 +459,34 @@ def create_precheck(
|
||||
strategy_version="v0",
|
||||
counts_json=asdict(result.summary.counts),
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
estimated_erp_write_count=result.summary.estimated_erp_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
|
||||
)
|
||||
db.session.add(precheck)
|
||||
db.session.flush()
|
||||
|
||||
# [幂等] 相同 (来源,单号,料号,收料日期) 的重复预检不得累加异常行:
|
||||
# 非终态行原地刷新并挂到最新预检;终态行(已执行/人工关闭等)保持既定事实不复活。
|
||||
_terminal_item_statuses = {
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
status_machine.TransferStatus.CANCELLED.value,
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
}
|
||||
for item in result.items:
|
||||
fields = {
|
||||
"precheck_id": precheck.id,
|
||||
"status": _item_status(item.result),
|
||||
"result_code": item.result if item.result != RESULT_EXECUTABLE else None,
|
||||
"result_message": item.reason or None,
|
||||
"from_warehouse": item.from_warehouse or "",
|
||||
"to_warehouse": item.to_warehouse or "",
|
||||
"receipt_quantity": str(item.to_quantity),
|
||||
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"lot_no": item.lot_no or "",
|
||||
"receipt_warehouse_code": item.receipt_warehouse_code or "",
|
||||
"raw_lines_json": [
|
||||
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
|
||||
for line in item.raw_lines
|
||||
],
|
||||
}
|
||||
# 禁 autoflush:避免本批 pending 插入在查询时提前落库(应随循环末统一 commit)。
|
||||
with db.session.no_autoflush:
|
||||
existing = (
|
||||
TransferInvoiceItem.query.filter_by(
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
receipt_date=item.receipt_date,
|
||||
)
|
||||
.order_by(TransferInvoiceItem.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
if existing.status not in _terminal_item_statuses:
|
||||
for attr, value in fields.items():
|
||||
setattr(existing, attr, value)
|
||||
continue
|
||||
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
|
||||
db.session.add(TransferInvoiceItem(
|
||||
precheck_id=precheck.id,
|
||||
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
receipt_date=item.receipt_date,
|
||||
**fields,
|
||||
from_warehouse=item.from_warehouse or "",
|
||||
to_warehouse=item.to_warehouse or "",
|
||||
receipt_quantity=str(item.to_quantity),
|
||||
erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
status=_item_status(item.result),
|
||||
result_code=item.result if item.result != RESULT_EXECUTABLE else None,
|
||||
result_message=item.reason or None,
|
||||
raw_lines_json=[
|
||||
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
|
||||
for line in item.raw_lines
|
||||
],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -624,7 +498,7 @@ def create_precheck(
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
counts=result.summary.counts,
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
estimated_erp_write_count=result.summary.estimated_erp_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
)
|
||||
return summary
|
||||
@@ -660,7 +534,7 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
|
||||
estimated_external_write_count=int(precheck.estimated_external_write_count or 0),
|
||||
estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0),
|
||||
precheck_hash=precheck.precheck_hash,
|
||||
)
|
||||
items = []
|
||||
@@ -671,19 +545,13 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
lot_no=item.lot_no or "",
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=item.result_code or (
|
||||
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
|
||||
),
|
||||
# 失败原因落库于 result_message(预检/重查降级均写);restore 不回读则
|
||||
# 前端刷新后原因恒为空,呈现「安静阻断」无法排查。
|
||||
reason=item.result_message or "",
|
||||
raw_lines=tuple(
|
||||
RawLineRefDTO(
|
||||
sheet=line.get("sheet", ""),
|
||||
@@ -700,8 +568,6 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
file_no=job.file_no,
|
||||
file_version=None,
|
||||
checksum=job.file_sha256,
|
||||
error_code=job.error_code,
|
||||
error_message=job.error_message,
|
||||
)
|
||||
for job in (precheck.run.source_jobs if precheck.run else [])
|
||||
] or [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨严格数量门禁。
|
||||
|
||||
用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
|
||||
用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则,
|
||||
禁止部分调拨、数量容差与隐式截断。
|
||||
依赖:标准库 decimal。
|
||||
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
|
||||
@@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool:
|
||||
return Decimal(str(left)) == Decimal(str(right))
|
||||
|
||||
|
||||
def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str:
|
||||
def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str:
|
||||
"""按严格相等规则分类数量匹配结果。
|
||||
|
||||
Args:
|
||||
receipt_quantity: 收料数量。
|
||||
external_quantity: 外部系统 账面库存;None 表示无库存。
|
||||
erp_quantity: ERP 账面库存;None 表示无库存。
|
||||
Returns:
|
||||
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
|
||||
"""
|
||||
if external_quantity is None:
|
||||
if erp_quantity is None:
|
||||
return MATCH_INVENTORY_NOT_FOUND
|
||||
if strict_quantities_equal(receipt_quantity, external_quantity):
|
||||
if strict_quantities_equal(receipt_quantity, erp_quantity):
|
||||
return MATCH_EXECUTABLE
|
||||
return MATCH_QUANTITY_MISMATCH
|
||||
@@ -1,69 +0,0 @@
|
||||
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
|
||||
|
||||
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
|
||||
供来源状态投影(source_file_status)、预检取文件(movement_file_repository)、
|
||||
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
|
||||
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
|
||||
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
|
||||
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
|
||||
两函数同核推导,规则文本只存在一处。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import ColumnElement, and_, not_, or_
|
||||
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
|
||||
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
|
||||
"""新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。"""
|
||||
window_start, window_end = business_date_utc_window(now)
|
||||
return and_(
|
||||
ShippingReceiptReportFile.created_at >= window_start,
|
||||
ShippingReceiptReportFile.created_at < window_end,
|
||||
or_(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_(None),
|
||||
ShippingReceiptReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「当前可用的收料归档文件」SQL 条件。
|
||||
|
||||
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
|
||||
+ 未过保留期(archive_expires_at 为空视为长期有效)。预检复用与下载
|
||||
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
_fresh_and_retention_valid(now),
|
||||
)
|
||||
|
||||
|
||||
def expired_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
|
||||
|
||||
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
|
||||
命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
not_(_fresh_and_retention_valid(now)),
|
||||
)
|
||||
@@ -96,7 +96,7 @@ def trigger_receipt_rpa(
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
|
||||
schedule_run_id=0, # 调拨触发无 ScheduleRun,沿用 0 占位约定
|
||||
inventory_source_id=unit_payload['inventory_source_id'],
|
||||
source_code=unit_payload['source_code'],
|
||||
connector_type=unit_payload['connector_type'],
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨每日历史恢复(自动复核待处理池)。
|
||||
|
||||
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新预检并创建新 Attempt;
|
||||
用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:models、retry_service._recheck_item、TransferDeps。
|
||||
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 外部系统)。
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。
|
||||
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP;
|
||||
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
|
||||
依赖:models、capability_client、quantity、status、audit、precheck_service.TransferDeps。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
|
||||
依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。
|
||||
逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
@@ -18,107 +17,55 @@ from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
RESULT_EXTERNAL_QUERY_FAILED,
|
||||
RESULT_EXECUTABLE,
|
||||
TransferDeps,
|
||||
)
|
||||
from app.services.in_transit_transfer.precheck_service import RESULT_EXECUTABLE, TransferDeps
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
|
||||
RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
|
||||
RETRY_KIND_ERP_RECHECK = "erp_recheck"
|
||||
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
|
||||
|
||||
# 可重查状态:可恢复阻断 + 可执行(已可执行的行也允许重查核对最新库存,
|
||||
# 避免预检后库存变化无法发现);终态(已执行/人工关闭等)仍不可重查。
|
||||
_RETRYABLE_STATUSES = {
|
||||
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
}
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
|
||||
"""对单个异常项重新查询 外部系统 并更新状态(创建新 Attempt)。
|
||||
"""对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。
|
||||
|
||||
Returns:
|
||||
重检后的 item 状态。
|
||||
"""
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id,
|
||||
run_no=item.run.run_no if item.run else "RUN-PENDING",
|
||||
attempt_no=item.attempt_no + 1,
|
||||
invoice_no=item.invoice_no,
|
||||
erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse,
|
||||
to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
)
|
||||
item.attempt_no += 1
|
||||
before_status = item.status
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="external_query",
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="erp_query",
|
||||
status="running", operation_id=operation_id,
|
||||
request_snapshot_json={
|
||||
"invoice_no": item.invoice_no, "external_org": route.external_org,
|
||||
"invoice_no": item.invoice_no, "erp_org": route.erp_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
# [降级] 与 precheck 逐票语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
|
||||
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
|
||||
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
|
||||
try:
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=route.external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
)],
|
||||
)
|
||||
stock_qty = stock.lookup(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
# 降级只落 DB(result_message/审计),若再无应用日志,控制台侧完全无痕可查。
|
||||
logger.warning(
|
||||
"transfer external recheck failed (degrade to blocked): invoice=%s item=%s attempt=%s error=%s",
|
||||
item.invoice_no, item.id, item.attempt_no, detail,
|
||||
)
|
||||
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = RESULT_EXTERNAL_QUERY_FAILED
|
||||
item.result_message = f"external query failed: {detail}"
|
||||
attempt.status = "failed"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ITEM_RECHECKED",
|
||||
aggregate_type="transfer_item",
|
||||
aggregate_id=str(item.id),
|
||||
run_no=item.run.run_no if item.run else None,
|
||||
invoice_no=item.invoice_no,
|
||||
item_id=str(item.id),
|
||||
attempt_no=item.attempt_no,
|
||||
actor_type="worker",
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
result="failure",
|
||||
before={"status": before_status},
|
||||
after={"status": item.status, "attempt_no": item.attempt_no, "error": detail},
|
||||
))
|
||||
db.session.flush()
|
||||
return item.status
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
|
||||
item.result_message = "external inventory not found" if stock_qty is None else "strict quantity mismatch"
|
||||
# 查无记录与数量不足都是外部系统的真实答复:库存数必须落库展示(查无记录按 0),
|
||||
# 不得显示"-"让用户误以为查询失败。
|
||||
item.external_quantity = str(stock_qty) if stock_qty is not None else "0"
|
||||
item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch"
|
||||
item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch"
|
||||
attempt.status = "failed"
|
||||
else:
|
||||
item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
item.external_quantity = str(stock_qty)
|
||||
item.erp_quantity = str(query.quantity)
|
||||
attempt.status = "success"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
@@ -140,14 +87,14 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
return item.status
|
||||
|
||||
|
||||
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTERNAL_RECHECK,
|
||||
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""人工重试异常项。
|
||||
|
||||
Args:
|
||||
item_id: TransferInvoiceItem.id。
|
||||
deps: 注入依赖。
|
||||
kind: external_recheck(默认);rpa_refetch 在 Run 创建后禁止。
|
||||
kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"item_id": ..., "status": ..., "attempt_no": ...}。
|
||||
@@ -158,65 +105,16 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTER
|
||||
kind_value = str(kind or "").strip()
|
||||
if kind_value == RETRY_KIND_RPA_REFETCH:
|
||||
raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED")
|
||||
if kind_value != RETRY_KIND_EXTERNAL_RECHECK:
|
||||
if kind_value != RETRY_KIND_ERP_RECHECK:
|
||||
raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID")
|
||||
item = db.session.get(TransferInvoiceItem, item_id)
|
||||
if item is None:
|
||||
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
|
||||
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
|
||||
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
|
||||
if item.status not in _RETRYABLE_STATUSES:
|
||||
if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}:
|
||||
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
|
||||
|
||||
status = _recheck_item(item, deps=deps, request_id=request_id)
|
||||
db.session.commit()
|
||||
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
|
||||
|
||||
|
||||
def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 外部系统 库存:对同一预检下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
|
||||
|
||||
Args:
|
||||
precheck_no: 预检编号(定位明细集合)。
|
||||
deps: 注入依赖(capabilities = 外部系统网关客户端)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该预检全部可重查行。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"precheck_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
单行失败(状态不允许/不存在)不影响其余行(来源级隔离同款语义)。
|
||||
"""
|
||||
from app.models import TransferPrecheck
|
||||
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=precheck_no).first()
|
||||
if precheck is None:
|
||||
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.precheck_id == precheck.id,
|
||||
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
|
||||
)
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
if wanted:
|
||||
query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted))
|
||||
items = query.order_by(TransferInvoiceItem.id).all()
|
||||
|
||||
results: list[dict] = []
|
||||
for item in items:
|
||||
try:
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": True, "status": item.status})
|
||||
except (ValidationError, NotFoundError) as exc:
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:任何单行异常不炸整批
|
||||
# 与 _recheck_item 降级同理:DB 只留单行结果,控制台必须同步留痕。
|
||||
logger.warning(
|
||||
"transfer requery row crashed (skipped): invoice=%s item=%s error=%s",
|
||||
item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__,
|
||||
)
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
return {"precheck_no": precheck_no, "total": len(items), "results": results}
|
||||
@@ -28,7 +28,7 @@ def serialize_summary(summary) -> dict[str, Any]:
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
},
|
||||
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
|
||||
"estimated_external_write_count": summary.estimated_external_write_count,
|
||||
"estimated_erp_write_count": summary.estimated_erp_write_count,
|
||||
"precheck_hash": summary.precheck_hash,
|
||||
}
|
||||
|
||||
@@ -41,7 +41,6 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
"material_name": item.material_name,
|
||||
"specification": item.specification,
|
||||
"invoice_no": item.invoice_no,
|
||||
"lot_no": item.lot_no,
|
||||
"receipt_date": item.receipt_date,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
|
||||
@@ -3,20 +3,14 @@
|
||||
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
|
||||
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
|
||||
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
|
||||
receipt_file_gate(可用/失效判定单一事实来源)。
|
||||
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
|
||||
见 receipt_file_gate)→ ready;有进行中单元 → fetching;
|
||||
最新单元为失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。
|
||||
逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching;
|
||||
最新单元为失败终态 → failed;否则 → none。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.in_transit_transfer.receipt_file_gate import (
|
||||
expired_receipt_file_condition,
|
||||
usable_receipt_file_condition,
|
||||
)
|
||||
|
||||
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
|
||||
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
@@ -25,19 +19,16 @@ FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
"""返回某来源的收料文件状态投影。
|
||||
|
||||
失效判定(不依赖保留期清理任务落位,与预检取文件/下载同口径,见
|
||||
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
|
||||
|
||||
Returns:
|
||||
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
|
||||
file_status ∈ {'ready', 'fetching', 'failed', 'expired', 'none'}。
|
||||
file_status ∈ {'ready', 'fetching', 'failed', 'none'}。
|
||||
"""
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
usable_receipt_file_condition(),
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
@@ -69,17 +60,4 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
|
||||
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
|
||||
expired_report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
expired_receipt_file_condition(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if expired_report is not None:
|
||||
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
@@ -4,7 +4,7 @@
|
||||
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
|
||||
依赖:models(TransferSourceJob)、status_machine。
|
||||
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
|
||||
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 外部系统/触发 RPA。
|
||||
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,22 +21,13 @@ SOURCE_JOB_STATUSES = (
|
||||
)
|
||||
|
||||
|
||||
def create_source_job(
|
||||
*,
|
||||
run_id: int,
|
||||
source_code: str,
|
||||
status: str = 'pending',
|
||||
error_code: str | None = None,
|
||||
error_message: str | None = None,
|
||||
) -> TransferSourceJob:
|
||||
def create_source_job(*, run_id: int, source_code: str, status: str = 'pending') -> TransferSourceJob:
|
||||
"""为一次 run 创建一条来源级 job;(run_id, source_code) 唯一由模型约束。
|
||||
|
||||
Args:
|
||||
run_id: 所属 TransferRun.id。
|
||||
source_code: 来源实例编码。
|
||||
status: 初始状态。
|
||||
error_code / error_message: 来源级失败事实(如解析失败 error_code),
|
||||
随创建落库,保证刷新/恢复后失败原因仍可见(不静默丢成全 0)。
|
||||
Returns:
|
||||
新建(或复用已存在同 run 同来源)的 TransferSourceJob。
|
||||
"""
|
||||
@@ -45,13 +36,7 @@ def create_source_job(
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
job = TransferSourceJob(
|
||||
run_id=run_id,
|
||||
source_code=source_code,
|
||||
status=status,
|
||||
error_code=error_code,
|
||||
error_message=error_message,
|
||||
)
|
||||
job = TransferSourceJob(run_id=run_id, source_code=source_code, status=status)
|
||||
db.session.add(job)
|
||||
db.session.flush()
|
||||
return job
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
|
||||
result_unknown / manually_closed / success / duplicate_success /
|
||||
not_matured / cancelled 为无出边终态;
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -39,7 +39,7 @@ class TransferStatus(StrEnum):
|
||||
|
||||
|
||||
class TransferRunStatus(StrEnum):
|
||||
"""Run 级生命周期;外部系统 结果与通知结果分离。"""
|
||||
"""Run 级生命周期;ERP 结果与通知结果分离。"""
|
||||
|
||||
QUEUED = "queued"
|
||||
PREPARING_FILES = "preparing_files"
|
||||
@@ -101,7 +101,7 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
|
||||
TransferStatus.PRECHECKING.value, # 仅 外部系统 重查/重新预检,创建新 Attempt
|
||||
TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
@@ -199,19 +199,19 @@ def assert_transition_allowed(
|
||||
|
||||
|
||||
def apply_notification_failure(run_status: str) -> str:
|
||||
"""通知失败不改变 外部系统 结果。
|
||||
"""通知失败不改变 ERP 结果。
|
||||
|
||||
Args:
|
||||
run_status: Run 的 外部系统 业务终态。
|
||||
run_status: Run 的 ERP 业务终态。
|
||||
Returns:
|
||||
原 run_status(保持不变)。
|
||||
Raises:
|
||||
TransferStateError: Run 尚未进入 外部系统 终态时不允许记录通知失败。
|
||||
TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。
|
||||
"""
|
||||
status = str(run_status or "").strip()
|
||||
if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}:
|
||||
raise TransferStateError(
|
||||
"notification failure only allowed after 外部系统 terminal status",
|
||||
"notification failure only allowed after ERP terminal status",
|
||||
current=status,
|
||||
)
|
||||
return status
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨策略硬门禁。
|
||||
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试,
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
|
||||
强制默认 10 分钟确认有效期。
|
||||
依赖:app.core.errors.AppError、standard decimal。
|
||||
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
|
||||
@@ -24,7 +24,7 @@ class TransferStrategyPolicy:
|
||||
|
||||
allow_partial: bool = False
|
||||
quantity_tolerance: Decimal = Decimal("0")
|
||||
allow_external_auto_retry: bool = False
|
||||
allow_erp_auto_retry: bool = False
|
||||
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
|
||||
|
||||
@@ -46,14 +46,14 @@ def validate_strategy(strategy: TransferStrategyPolicy) -> None:
|
||||
Args:
|
||||
strategy: 待校验策略。
|
||||
Raises:
|
||||
StrategyViolationError: 开启部分调拨、非零容差或 外部系统 自动重试。
|
||||
StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。
|
||||
"""
|
||||
if strategy.allow_partial:
|
||||
raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial")
|
||||
if strategy.quantity_tolerance != Decimal("0"):
|
||||
raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance")
|
||||
if strategy.allow_external_auto_retry:
|
||||
raise StrategyViolationError("External auto retry is forbidden in phase 1", reason="allow_external_auto_retry")
|
||||
if strategy.allow_erp_auto_retry:
|
||||
raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry")
|
||||
|
||||
|
||||
def default_strategy() -> TransferStrategyPolicy:
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
"""在途调拨类型契约。
|
||||
|
||||
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
|
||||
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝预检,规则先冻结)。
|
||||
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
|
||||
逻辑:类型决定预检纳入哪些收料票——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
的票(大小写不敏感,范围外票与收料日期范围过滤同语义,静默排除不入明细);
|
||||
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
|
||||
类型 3 规则待业务定义。调用方必须先 ensure_transfer_type_supported 再过滤。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import Iterable
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
|
||||
|
||||
# 类型不支持(占位类型被调用)时的稳定错误码。
|
||||
TRANSFER_TYPE_NOT_SUPPORTED = "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
|
||||
|
||||
|
||||
class TransferType(StrEnum):
|
||||
"""调拨业务类型(值与前端/i18n、transfer_runs.transfer_type 列一致)。"""
|
||||
|
||||
IN_TRANSIT_TO_HUB = "in_transit_to_hub" # 在途仓至HUB仓
|
||||
HUB_REPAIR_OUT = "hub_repair_out" # HUB仓维修出(占位)
|
||||
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
|
||||
|
||||
|
||||
# 一期已实现预检/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
|
||||
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
|
||||
|
||||
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES: tuple[str, ...] = ("HOM", "HOX", "WTP")
|
||||
|
||||
# 类型 2(HUB仓维修出)数据范围:ODM ID 精确值;待 movement 文件暴露 odm_id 后启用。
|
||||
HUB_REPAIR_OUT_ODM_ID = "HoxinRMA"
|
||||
|
||||
|
||||
def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
|
||||
"""规范化调拨类型入参;缺省/空值回落到类型 1(存量调用方语义不变)。
|
||||
|
||||
Args:
|
||||
value: 前端/API 传入的调拨类型值。
|
||||
Returns:
|
||||
TransferType 枚举。
|
||||
Raises:
|
||||
ValidationError: 非法类型值(不在枚举内)。
|
||||
"""
|
||||
raw = str(value.value if isinstance(value, TransferType) else (value or "")).strip()
|
||||
if not raw:
|
||||
return TransferType.IN_TRANSIT_TO_HUB
|
||||
try:
|
||||
return TransferType(raw)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
f"unknown transfer type: {raw}",
|
||||
code="TRANSFER.TRANSFER_TYPE_INVALID",
|
||||
details={"transfer_type": raw},
|
||||
) from exc
|
||||
|
||||
|
||||
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
|
||||
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入预检。
|
||||
|
||||
Args:
|
||||
transfer_type: 已规范化的调拨类型。
|
||||
Raises:
|
||||
ValidationError: 类型未实现(TRANSFER_TYPE_NOT_SUPPORTED)。
|
||||
"""
|
||||
if transfer_type not in SUPPORTED_TRANSFER_TYPES:
|
||||
raise ValidationError(
|
||||
f"transfer type not supported yet: {transfer_type.value}",
|
||||
code=TRANSFER_TYPE_NOT_SUPPORTED,
|
||||
details={"transfer_type": transfer_type.value},
|
||||
)
|
||||
|
||||
|
||||
def filter_invoices_for_type(
|
||||
invoices: Iterable[AggregatedInvoice],
|
||||
transfer_type: TransferType,
|
||||
) -> list[AggregatedInvoice]:
|
||||
"""按类型的收料数据范围过滤汇总票(返回保留项,保持原顺序)。
|
||||
|
||||
Args:
|
||||
invoices: 已汇总的收料票。
|
||||
transfer_type: 已规范化且已确认支持的调拨类型。
|
||||
Returns:
|
||||
类型范围内的票列表。
|
||||
"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
|
||||
return [
|
||||
invoice for invoice in invoices
|
||||
if str(invoice.invoice_no or "").strip().upper().startswith(prefixes)
|
||||
]
|
||||
# 类型 2/3 的过滤规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
|
||||
return list(invoices)
|
||||
|
||||
|
||||
def transfer_type_scope_note(transfer_type: TransferType) -> str:
|
||||
"""类型的范围规则说明(写入 TransferPrecheck.scope_json 供审计追溯)。"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
return f"invoice_prefix:{'+'.join(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES).lower()}"
|
||||
if transfer_type == TransferType.HUB_REPAIR_OUT:
|
||||
return f"odm_id:{HUB_REPAIR_OUT_ODM_ID}"
|
||||
return "pending_rule"
|
||||
@@ -4,21 +4,16 @@
|
||||
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。
|
||||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
|
||||
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
|
||||
且接口定义须为 published、客户端实例须 enabled(管理端「发布/退役」「启停」的总开关);
|
||||
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||||
from app.services.integration_connector.errors import BindingNotFoundError
|
||||
from app.services.integration_connector.transports.base import merge_client_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -37,9 +32,6 @@ class BindingSnapshot:
|
||||
request_spec: dict
|
||||
response_mapping: dict
|
||||
output_schema: dict
|
||||
# 域参数→接口参数映射(空 = 同名直通)与接口入参 Schema(映射结果校验)。
|
||||
param_mapping: dict
|
||||
input_schema: dict
|
||||
|
||||
|
||||
def _to_naive(dt: datetime | None) -> datetime | None:
|
||||
@@ -76,8 +68,7 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
Returns:
|
||||
BindingSnapshot。
|
||||
Raises:
|
||||
BindingNotFoundError: 无可用绑定(fail-closed);接口未发布或客户端已停用同样按
|
||||
无可用绑定处理(与列表「发布/退役」「启停」按钮语义闭环,且不向调用方泄露配置细节)。
|
||||
BindingNotFoundError: 无可用绑定(fail-closed)。
|
||||
"""
|
||||
base_now = now or datetime.utcnow()
|
||||
rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all()
|
||||
@@ -90,12 +81,6 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
continue
|
||||
candidates.append((row, selector))
|
||||
if not candidates:
|
||||
# fail-closed 必须可排障:区分「一条 published 都没有」与「有但路由选择器/生效窗口不命中」,
|
||||
# 否则调用方只看到 no binding for capability(2026-09 排障实测痛点)。
|
||||
logger.warning(
|
||||
"connector binding miss: capability=%s env=%s published_rows=%s context_keys=%s",
|
||||
capability, environment, len(rows), sorted((context or {}).keys()),
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True)
|
||||
row, selector = candidates[0]
|
||||
@@ -103,28 +88,15 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first()
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
|
||||
if client is None or iface is None:
|
||||
logger.warning(
|
||||
"connector binding target missing: capability=%s binding_id=%s client=%s iface=%s",
|
||||
capability, row.id, row.client_instance_code, row.interface_definition_code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
# fail-closed 门禁:接口未发布(draft/retired)或客户端已停用视同无可用绑定——
|
||||
# 管理端「发布/退役」「启停」按钮因此具备真实的调用期语义;错误类型与无命中一致。
|
||||
if iface.status != 'published' or not client.enabled:
|
||||
logger.warning(
|
||||
"connector binding gated: capability=%s binding_id=%s iface_status=%s client_enabled=%s",
|
||||
capability, row.id, iface.status, client.enabled,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费
|
||||
# (与 transports.base.merge_client_config 同一实现)。
|
||||
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。
|
||||
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
|
||||
config = merge_client_config({
|
||||
'config_json': client.config_json,
|
||||
'endpoint': client.endpoint,
|
||||
'timeout_seconds': client.timeout_seconds,
|
||||
})
|
||||
config = dict(client.config_json or {})
|
||||
if client.endpoint is not None:
|
||||
config['endpoint'] = client.endpoint
|
||||
if client.timeout_seconds is not None:
|
||||
config['timeout_seconds'] = client.timeout_seconds
|
||||
|
||||
request_spec = dict(iface.request_spec_json or {})
|
||||
if iface.http_method is not None:
|
||||
@@ -133,6 +105,8 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
request_spec['path'] = iface.request_path
|
||||
|
||||
selector = dict(row.context_selector_json or {})
|
||||
if row.context_source_code is not None and 'source_code' not in selector:
|
||||
selector['source_code'] = row.context_source_code
|
||||
|
||||
return BindingSnapshot(
|
||||
capability=row.capability,
|
||||
@@ -147,6 +121,4 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
request_spec=request_spec,
|
||||
response_mapping=iface.response_mapping_json or {},
|
||||
output_schema=iface.output_schema_json or {},
|
||||
param_mapping=row.param_mapping_json or {},
|
||||
input_schema=iface.input_schema_json or {},
|
||||
)
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。
|
||||
依赖:app.core.errors、errors.py;纯代码,不依赖 DB。
|
||||
逻辑:能力必须由代码注册,不能由管理端动态定义;各域契约声明在各域包的
|
||||
capabilities 模块(如 in_transit_transfer/capabilities.py),由应用组合根
|
||||
import 完成注册;领域只调用已注册能力,未注册 fail-closed。
|
||||
逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,6 +12,37 @@ from dataclasses import dataclass
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.integration_connector.errors import CapabilityNotFoundError
|
||||
|
||||
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
|
||||
_QUERY_INPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"],
|
||||
"properties": {
|
||||
"invoice_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"to_warehouse": {"type": "string"},
|
||||
"quantity": {"type": "number"},
|
||||
},
|
||||
}
|
||||
_QUERY_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"found": {"type": "boolean"},
|
||||
"quantity": {"type": ["number", "null"]},
|
||||
},
|
||||
}
|
||||
_WRITE_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["status"],
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
|
||||
},
|
||||
"document_no": {"type": ["string", "null"]},
|
||||
"verified_posted": {"type": ["boolean", "null"]},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilitySpec:
|
||||
@@ -27,6 +56,7 @@ class CapabilitySpec:
|
||||
|
||||
|
||||
_CAPABILITIES: dict[str, CapabilitySpec] = {}
|
||||
_LOADED = False
|
||||
|
||||
|
||||
def register_capability(spec: CapabilitySpec) -> CapabilitySpec:
|
||||
@@ -54,6 +84,42 @@ def list_capabilities() -> list[CapabilitySpec]:
|
||||
return sorted(_CAPABILITIES.values(), key=lambda s: s.name)
|
||||
|
||||
|
||||
def ensure_capabilities_loaded() -> None:
|
||||
"""惰性注册内置能力(幂等);由网关/API 在解析前调用。"""
|
||||
global _LOADED # noqa: PLW0603
|
||||
if _LOADED:
|
||||
return
|
||||
_LOADED = True
|
||||
_register_transfer_capabilities()
|
||||
|
||||
|
||||
def _register_transfer_capabilities() -> None:
|
||||
"""注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。"""
|
||||
register_capability(CapabilitySpec(
|
||||
name="in_transit_transfer.query_inventory",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_QUERY_OUTPUT_SCHEMA,
|
||||
idempotency="none",
|
||||
write=False,
|
||||
))
|
||||
register_capability(CapabilitySpec(
|
||||
name="in_transit_transfer.create_transfer",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=True,
|
||||
))
|
||||
register_capability(CapabilitySpec(
|
||||
name="in_transit_transfer.verify_duplicate",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=False,
|
||||
))
|
||||
|
||||
|
||||
def reset_capability_registry_for_tests() -> None:
|
||||
"""单测隔离:清空注册表(领域 capabilities 模块可重调其注册函数重建)。"""
|
||||
"""单测隔离:清空注册表并重置加载标记。"""
|
||||
global _LOADED # noqa: PLW0603
|
||||
_CAPABILITIES.clear()
|
||||
_LOADED = False
|
||||
@@ -1,79 +0,0 @@
|
||||
"""services/integration_connector/credential_types.py
|
||||
|
||||
用途:凭据形态注册表——每种凭据类型定义自己的字段清单(键名/是否密文/是否必填),
|
||||
是 UI 动态渲染与 API 组装/校验的唯一事实来源。
|
||||
依赖:app.core.errors;纯代码注册表,无 DB/IO。
|
||||
逻辑:类型由代码注册(与能力注册同哲学),管理端不可动态定义;字段键名即模板
|
||||
占位符 credential_<key> 的 <key>;新增形态 = 加一个注册条目 + 前端标签,零迁移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 凭据形态注册表:key 为稳定类型编码(credential_type 列值),fields 为字段清单。
|
||||
# secret=True 的字段加密落库且永不回显;required 在「合并旧值后」仍缺失即拒绝。
|
||||
CREDENTIAL_TYPE_SPECS: dict[str, dict[str, Any]] = {
|
||||
"password": {
|
||||
"fields": [
|
||||
{"key": "username", "secret": False, "required": True},
|
||||
{"key": "password", "secret": True, "required": True},
|
||||
],
|
||||
},
|
||||
"token": {
|
||||
"fields": [
|
||||
{"key": "token", "secret": True, "required": True},
|
||||
],
|
||||
},
|
||||
"api_key": {
|
||||
"fields": [
|
||||
{"key": "api_key", "secret": True, "required": True},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_credential_type(credential_type: str) -> dict[str, Any] | None:
|
||||
"""按类型编码查字段定义;未知类型返回 None(调用方 fail-closed)。"""
|
||||
return CREDENTIAL_TYPE_SPECS.get(str(credential_type or "").strip())
|
||||
|
||||
|
||||
def list_credential_types() -> list[dict[str, Any]]:
|
||||
"""返回全部已注册类型及其字段定义(供 GET /credential-references/types)。"""
|
||||
return [
|
||||
{"type": type_code, "fields": [dict(field) for field in spec["fields"]]}
|
||||
for type_code, spec in sorted(CREDENTIAL_TYPE_SPECS.items())
|
||||
]
|
||||
|
||||
|
||||
def build_secret_dict(credential_type: str, values: dict) -> dict[str, str]:
|
||||
"""按类型定义从「合并旧值后的提交值」组装凭据字典。
|
||||
|
||||
只保留类型定义内的键(未知键丢弃);必填字段缺失抛 ValidationError(fail-closed)。
|
||||
"""
|
||||
spec = get_credential_type(credential_type)
|
||||
if spec is None:
|
||||
raise ValidationError("unknown credential_type", details={"credential_type": credential_type})
|
||||
result: dict[str, str] = {}
|
||||
for field in spec["fields"]:
|
||||
value = values.get(field["key"])
|
||||
if value is not None and str(value) != "":
|
||||
result[field["key"]] = str(value)
|
||||
missing = [field["key"] for field in spec["fields"] if field["required"] and not result.get(field["key"])]
|
||||
if missing:
|
||||
raise ValidationError("required credential fields missing", details={"fields": missing})
|
||||
return result
|
||||
|
||||
|
||||
def visible_fields(credential_type: str, secret_dict: dict) -> dict[str, str]:
|
||||
"""按类型定义回显非密字段(secret=True 的字段永不回显)。"""
|
||||
spec = get_credential_type(credential_type)
|
||||
if spec is None:
|
||||
return {}
|
||||
return {
|
||||
field["key"]: str(secret_dict[field["key"]])
|
||||
for field in spec["fields"]
|
||||
if not field["secret"] and secret_dict.get(field["key"])
|
||||
}
|
||||
@@ -1,36 +1,26 @@
|
||||
"""services/integration_connector/engine.py
|
||||
|
||||
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→map-params→call→classify→audit。
|
||||
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。
|
||||
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
|
||||
逻辑:域入参先经能力 Schema 校验,再按绑定 param_mapping 翻译为接口参数(对照接口
|
||||
入参 Schema 校验);凭据按引用解析后以 credential_* 注入传输层;读能力返回
|
||||
带 status 的失败 dict 时原样分类,其余映射校验通过即 success;
|
||||
逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout;
|
||||
入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import replace
|
||||
|
||||
from app import db
|
||||
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
|
||||
from app.services.integration_connector.capability import CapabilitySpec, get_capability
|
||||
from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability
|
||||
from app.services.integration_connector.errors import CallFailedError, InputInvalidError
|
||||
from app.services.integration_connector.mapping import map_response, schema_errors
|
||||
from app.services.integration_connector.security import resolve_credential, sanitize
|
||||
from app.services.integration_connector.transports.base import (
|
||||
RESULT_FAILURE_STATUSES,
|
||||
IntegrationCallResult,
|
||||
Transport,
|
||||
classify_transport_response,
|
||||
)
|
||||
from app.services.integration_connector.security import sanitize
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
|
||||
from app.models import IntegrationCall
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def build_request(request_spec: dict, config: dict, params: dict) -> dict:
|
||||
"""按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。"""
|
||||
@@ -95,51 +85,34 @@ class CapabilityGateway:
|
||||
environment: str | None = None,
|
||||
transports: dict[str, Transport] | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
ensure_capabilities_loaded()
|
||||
spec = get_capability(capability)
|
||||
input_errors = schema_errors(params, spec.input_schema)
|
||||
if input_errors:
|
||||
# InputInvalidError 只带 message 不带明细,降级进 result_message 后只剩
|
||||
# "input invalid";不落日志则字段级原因(required missing/类型不符)永久丢失。
|
||||
logger.warning(
|
||||
"connector input invalid: capability=%s errors=%s",
|
||||
capability, input_errors,
|
||||
)
|
||||
raise InputInvalidError(details={'errors': input_errors})
|
||||
|
||||
env = environment or _environment()
|
||||
snapshot = resolve_binding(capability, context, env)
|
||||
# 域参数 → 接口参数翻译:绑定配置了 param_mapping 时按映射引擎执行,
|
||||
# 结果对照接口入参 Schema 校验;未配置时同名直通(能力入参原样下传)。
|
||||
params = map_response(snapshot.param_mapping, params, snapshot.input_schema) \
|
||||
if snapshot.param_mapping else params
|
||||
transport = (transports or self.transports).get(snapshot.connector_type)
|
||||
if transport is None:
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'})
|
||||
|
||||
# 凭据按引用解析(db 密文解密 / env 配置键读取),缺失即 fail-closed。
|
||||
credential = resolve_credential(snapshot.credential_ref_code) if snapshot.credential_ref_code else {}
|
||||
request = build_request(snapshot.request_spec, snapshot.config, params)
|
||||
trace_id = f'ic-{uuid.uuid4().hex}'
|
||||
start_ms = int(time.time() * 1000)
|
||||
try:
|
||||
raw = transport.call(
|
||||
client={'config_json': snapshot.config, 'credential': credential},
|
||||
client={'config_json': snapshot.config, 'credential': {}},
|
||||
interface={'request_spec_json': snapshot.request_spec},
|
||||
request=request,
|
||||
)
|
||||
except TimeoutError:
|
||||
result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
_record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id)
|
||||
return result
|
||||
|
||||
if spec.write:
|
||||
result = classify_transport_response(raw)
|
||||
elif isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
|
||||
# 传输层已判失败(HTTP 4xx/5xx、SOAP Fault、非 XML)→ 原样分类,不做输出映射。
|
||||
result = classify_transport_response(raw)
|
||||
else:
|
||||
result = IntegrationCallResult(status='success')
|
||||
if result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
|
||||
result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success')
|
||||
if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
|
||||
data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema)
|
||||
result = replace(result, data=data)
|
||||
result = replace(result, trace_id=trace_id)
|
||||
|
||||
@@ -2,14 +2,12 @@
|
||||
|
||||
用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。
|
||||
依赖:decimal、errors.py;纯函数,无 IO/网络/DB。
|
||||
逻辑:只允许点路径/数组下标提取与白名单转换函数(含 pick 键值取值、template 参数模板、
|
||||
each 列表逐元素子映射),禁止任意 Python/JS/SQL;缺字段且不可满足→MappingInvalidError;
|
||||
输出不合 Schema→MappingInvalidError(fail-closed)。
|
||||
逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL;
|
||||
缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import string
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
@@ -52,37 +50,25 @@ def _tokenize(path: str) -> list[str]:
|
||||
|
||||
|
||||
def extract_path(obj: Any, path: str) -> Any:
|
||||
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。
|
||||
|
||||
路径途经重复节点列表(名称段撞上列表)时逐元素收集剩余路径的命中:
|
||||
全部未命中视为 MISSING,部分命中收集为列表——同一配置在单/多记录
|
||||
(如多条件查询返回多个 RecordSet)之间不再随机失效。
|
||||
"""
|
||||
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。"""
|
||||
path = str(path or "")
|
||||
if len(path) > MAX_PATH_LENGTH:
|
||||
raise MappingInvalidError(details={"reason": "path_too_long"})
|
||||
tokens = _tokenize(path)
|
||||
if len(tokens) > MAX_DEPTH:
|
||||
raise MappingInvalidError(details={"reason": "path_too_deep"})
|
||||
return _walk(obj, tokens)
|
||||
|
||||
|
||||
def _walk(cur: Any, tokens: list[str]) -> Any:
|
||||
"""按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。"""
|
||||
if not tokens:
|
||||
return cur
|
||||
tok, rest = tokens[0], tokens[1:]
|
||||
if isinstance(cur, list) and tok.isdigit():
|
||||
idx = int(tok)
|
||||
if idx >= len(cur):
|
||||
cur = obj
|
||||
for tok in tokens:
|
||||
if isinstance(cur, list) and tok.isdigit():
|
||||
idx = int(tok)
|
||||
if idx >= len(cur):
|
||||
return MISSING
|
||||
cur = cur[idx]
|
||||
elif isinstance(cur, dict) and tok in cur:
|
||||
cur = cur[tok]
|
||||
else:
|
||||
return MISSING
|
||||
return _walk(cur[idx], rest)
|
||||
if isinstance(cur, dict) and tok in cur:
|
||||
return _walk(cur[tok], rest)
|
||||
if isinstance(cur, list):
|
||||
collected = [hit for item in cur if (hit := _walk(item, tokens)) is not MISSING]
|
||||
return collected if collected else MISSING
|
||||
return MISSING
|
||||
return cur
|
||||
|
||||
|
||||
# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ----
|
||||
@@ -133,81 +119,6 @@ def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any:
|
||||
return then if condition == "truthy" and bool(value) else else_
|
||||
|
||||
|
||||
def _pick(value: Any, key_field: str | None = None, key_value: Any = None,
|
||||
value_field: str | None = None, exists: bool = False, cast: str | None = None) -> Any:
|
||||
"""从「键值对记录列表」按 key_field==key_value 取值(行转列通用需求)。
|
||||
|
||||
Args:
|
||||
value: 目标列表(每项为 dict,如 XML 归一化后的 Field 列表)。
|
||||
key_field / key_value: 匹配键字段名与期望值(按字符串比较)。
|
||||
value_field: 命中后取的字段名;缺省返回整条记录。
|
||||
exists: True 时返回布尔(是否命中),不取值。
|
||||
cast: 可选 "decimal" 或 _cast 支持的标量类型。
|
||||
"""
|
||||
if value is MISSING:
|
||||
return MISSING
|
||||
if key_field is None or key_value is None:
|
||||
raise MappingInvalidError(details={"reason": "pick_requires_key_field_and_key_value"})
|
||||
if not isinstance(value, list):
|
||||
raise MappingInvalidError(details={"reason": "pick_target_not_list"})
|
||||
for item in value:
|
||||
if isinstance(item, dict) and str(item.get(key_field)) == str(key_value):
|
||||
if exists:
|
||||
return True
|
||||
found = item.get(value_field) if value_field is not None else item
|
||||
if cast == "decimal":
|
||||
return _decimal(found)
|
||||
return _cast(found, cast) if cast else found
|
||||
if exists:
|
||||
return False
|
||||
return MISSING
|
||||
|
||||
|
||||
def _each(value: Any, fields: dict | None = None) -> Any:
|
||||
"""对列表逐元素套用子映射,产出 dict 列表(多条外部记录→多行结果的通用需求)。
|
||||
|
||||
Args:
|
||||
value: 目标列表(每项为 dict,如归一化后的 Master 记录列表)。
|
||||
fields: 子映射 {输出字段: {expr/transform/args}},语义与 map_response 顶层一致:
|
||||
元素内缺字段按 MISSING 处理(跳过该键),转换函数复用 TRANSFORMS 白名单。
|
||||
"""
|
||||
if value is MISSING:
|
||||
# 目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 归一为空列表:
|
||||
# 空结果是合法答案(如库存查无此批号),交领域层归类为"未找到",
|
||||
# 不得因输出 Schema 校验 fail-closed 成映射错误。
|
||||
return []
|
||||
# XML 重复节点归一化后单条记录是 dict、多条是 list:单记录归一为单元素列表,
|
||||
# 否则同一配置在单/多记录间会随机 fail-closed。
|
||||
if isinstance(value, dict):
|
||||
value = [value]
|
||||
if not isinstance(value, list):
|
||||
raise MappingInvalidError(details={"reason": "each_target_not_list"})
|
||||
out: list[Any] = []
|
||||
for item in value:
|
||||
row: dict[str, Any] = {}
|
||||
for field, spec in (fields or {}).items():
|
||||
if not isinstance(spec, dict):
|
||||
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
|
||||
if "default" in spec:
|
||||
v: Any = spec["default"]
|
||||
else:
|
||||
expr = spec.get("expr")
|
||||
v = extract_path(item, expr) if expr is not None else MISSING
|
||||
transform = spec.get("transform")
|
||||
if transform:
|
||||
fn = TRANSFORMS.get(transform)
|
||||
if fn is None:
|
||||
raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"})
|
||||
v = fn(v, **(spec.get("args") or {}))
|
||||
if v is not MISSING:
|
||||
row[field] = v
|
||||
if row:
|
||||
# 全字段缺失的空行(如 Master 节点存在但无 Record 子节点)跳过,
|
||||
# 避免产出违反行 Schema 的 {} 行;部分缺失仍保留,由行 Schema fail-closed。
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
TRANSFORMS: dict[str, Any] = {
|
||||
"default": _default,
|
||||
"fallback": _fallback,
|
||||
@@ -216,64 +127,9 @@ TRANSFORMS: dict[str, Any] = {
|
||||
"enum-map": _enum_map,
|
||||
"list-map": _list_map,
|
||||
"if-else": _if_else,
|
||||
"pick": _pick,
|
||||
"each": _each,
|
||||
}
|
||||
|
||||
|
||||
# ---- 参数模板填充(spec 级 "template",对整个参数表渲染,多用于域参数→接口参数翻译)----
|
||||
|
||||
def _render_template_value(value: Any, args: dict) -> str:
|
||||
"""渲染单个占位符值:列表按 list_item_template 逐项渲染后用 separator 连接。
|
||||
|
||||
列表项为 dict 时,item_template 的占位符对 item 的键校验(缺失即
|
||||
template_item_field_missing,fail-closed)并按字段转义渲染,
|
||||
如 list_item_template = "(img01 = '{material_no}' AND img04 = '{lot_no}')"。
|
||||
"""
|
||||
item_template = str(args.get("list_item_template") or "{item}")
|
||||
separator = str(args.get("separator") if args.get("separator") is not None else ",")
|
||||
escape = args.get("escape")
|
||||
|
||||
def _escape(text: Any) -> str:
|
||||
text = str(text)
|
||||
if escape == "quote":
|
||||
text = text.replace("'", "''")
|
||||
return text
|
||||
|
||||
if isinstance(value, (list, tuple)):
|
||||
rendered: list[str] = []
|
||||
for item in value:
|
||||
if isinstance(item, dict):
|
||||
placeholders = {f for _, f, _, _ in string.Formatter().parse(item_template) if f}
|
||||
missing = sorted(p for p in placeholders if p not in item)
|
||||
if missing:
|
||||
raise MappingInvalidError(details={"reason": "template_item_field_missing", "field": missing[0]})
|
||||
rendered.append(item_template.format(**{k: _escape(v) for k, v in item.items()}))
|
||||
else:
|
||||
rendered.append(item_template.format(item=_escape(item)))
|
||||
return separator.join(rendered)
|
||||
return _escape(value)
|
||||
|
||||
|
||||
def fill_param_template(template: str, params: dict, args: dict | None = None) -> str:
|
||||
"""按 {param} 占位符对参数表渲染模板(str.format 语义,{{}} 转义字面大括号)。
|
||||
|
||||
缺占位符即抛 MappingInvalidError(fail-closed),绝不静默输出空串。
|
||||
"""
|
||||
template = str(template or "")
|
||||
args = args or {}
|
||||
placeholders = {fname for _, fname, _, _ in string.Formatter().parse(template) if fname}
|
||||
rendered: dict[str, str] = {}
|
||||
for name in placeholders:
|
||||
if name not in (params or {}):
|
||||
raise MappingInvalidError(details={"reason": "template_param_missing", "param": name})
|
||||
rendered[name] = _render_template_value(params[name], args)
|
||||
try:
|
||||
return template.format(**rendered)
|
||||
except (KeyError, IndexError, ValueError) as exc:
|
||||
raise MappingInvalidError(details={"reason": "template_invalid"}) from exc
|
||||
|
||||
|
||||
# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)----
|
||||
|
||||
def _matches_type(value: Any, type_spec: Any) -> bool:
|
||||
@@ -334,10 +190,7 @@ def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict:
|
||||
for field, spec in mapping.items():
|
||||
if not isinstance(spec, dict):
|
||||
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
|
||||
if "template" in spec:
|
||||
# 参数模板:对整个 raw(参数表)渲染,与单字段 expr 提取互补。
|
||||
value = fill_param_template(spec["template"], raw, spec.get("args") or {})
|
||||
elif "default" in spec:
|
||||
if "default" in spec:
|
||||
value = spec["default"]
|
||||
else:
|
||||
expr = spec.get("expr")
|
||||
|
||||
@@ -1,32 +1,18 @@
|
||||
"""services/integration_connector/security.py
|
||||
|
||||
用途:凭据引用解析(fail-closed)与敏感字段脱敏。
|
||||
依赖:IntegrationCredentialReference 模型、core.credential_crypto、current_app.config、errors.py。
|
||||
逻辑:db 模式解密 secret_ciphertext(主密钥 INTEGRATION_CREDENTIAL_KEY 环境注入);
|
||||
env 模式按 secret_ref 读当前环境配置,缺失即抛 CredentialUnresolvedError;
|
||||
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文/密文。
|
||||
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。
|
||||
逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError;
|
||||
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationCredentialReference
|
||||
from app.services.integration_connector.errors import CredentialUnresolvedError
|
||||
|
||||
# 连接器凭据密文的 Fernet 主密钥配置键与错误码。
|
||||
CREDENTIAL_KEY_CONFIG_NAME = 'INTEGRATION_CREDENTIAL_KEY'
|
||||
_DB_SECRET_CODES = CredentialCryptoErrorCodes(
|
||||
key_missing='INTEGRATION.CREDENTIAL_KEY_MISSING',
|
||||
key_invalid='INTEGRATION.CREDENTIAL_KEY_INVALID',
|
||||
secret_empty='INTEGRATION.CREDENTIAL_SECRET_EMPTY',
|
||||
secret_missing='INTEGRATION.CREDENTIAL_SECRET_MISSING',
|
||||
secret_invalid='INTEGRATION.CREDENTIAL_SECRET_INVALID',
|
||||
)
|
||||
|
||||
DEFAULT_SENSITIVE_KEYS = frozenset({
|
||||
'password', 'token', 'secret', 'authorization', 'cookie', 'access_key',
|
||||
'secret_key', 'credential', 'api_key', 'apikey', 'credentials',
|
||||
@@ -34,10 +20,10 @@ DEFAULT_SENSITIVE_KEYS = frozenset({
|
||||
|
||||
|
||||
def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
|
||||
"""按凭据引用解析真实凭据(db 解密 / env 配置键),fail-closed。
|
||||
"""按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。
|
||||
|
||||
Raises:
|
||||
CredentialUnresolvedError: 引用不存在、密文缺失、主密钥缺失/无效或 env 键缺失。
|
||||
CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
@@ -46,29 +32,13 @@ def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
|
||||
).first()
|
||||
if cred is None:
|
||||
raise CredentialUnresolvedError(ref=credential_ref_code)
|
||||
if cred.secret_provider == 'db':
|
||||
if not cred.secret_ciphertext:
|
||||
raise CredentialUnresolvedError(ref=credential_ref_code)
|
||||
try:
|
||||
value = decrypt_secret(
|
||||
cred.secret_ciphertext,
|
||||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||||
codes=_DB_SECRET_CODES,
|
||||
)
|
||||
except AppError as exc:
|
||||
raise CredentialUnresolvedError(message=str(exc.message)) from exc
|
||||
try:
|
||||
parsed = json.loads(value)
|
||||
except (ValueError, TypeError):
|
||||
parsed = None
|
||||
return dict(parsed) if isinstance(parsed, dict) else {'value': value}
|
||||
secret_ref = cred.secret_ref
|
||||
config_value = current_app.config.get(secret_ref) if has_app_ctx() else None
|
||||
if config_value is None or config_value == '':
|
||||
value = current_app.config.get(secret_ref) if has_app_ctx() else None
|
||||
if value is None or value == '':
|
||||
raise CredentialUnresolvedError(ref=secret_ref)
|
||||
if isinstance(config_value, dict):
|
||||
return dict(config_value)
|
||||
return {'value': config_value}
|
||||
if isinstance(value, dict):
|
||||
return dict(value)
|
||||
return {'value': value}
|
||||
|
||||
|
||||
def has_app_ctx() -> bool:
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
依赖:typing.Protocol、dataclass;无 Flask/DB。
|
||||
逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为
|
||||
IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。
|
||||
probe 为可选实现的连接测试探针(只证明网络可达,不做业务调用)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,9 +18,6 @@ RESULT_STATUSES = (
|
||||
'technical_failed', 'timeout', 'result_unknown',
|
||||
)
|
||||
|
||||
# 传输层直接判失败的子集(读能力返回带这些 status 的原始 dict 时不再做输出映射)。
|
||||
RESULT_FAILURE_STATUSES = ('business_failed', 'technical_failed')
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IntegrationCallResult:
|
||||
@@ -36,44 +32,13 @@ class IntegrationCallResult:
|
||||
|
||||
|
||||
class Transport(Protocol):
|
||||
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。
|
||||
|
||||
probe 为可选实现的连接测试探针:只证明网络/服务可达,不要求接口契约;
|
||||
Admin API 测试端点优先调 probe,未实现时回退 call(空 interface 规格)。
|
||||
"""
|
||||
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。"""
|
||||
|
||||
connector_type: str
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
...
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
...
|
||||
|
||||
|
||||
def merge_client_config(client: dict) -> dict:
|
||||
"""把客户端实例独立列(endpoint/timeout_seconds)拼回 config_json 的兼容层。
|
||||
|
||||
与 binding.resolve_binding 的列拼回逻辑同源(单一实现),供连接测试等
|
||||
不经绑定解析、直接消费客户端实例的调用方复用;返回副本,不改入参。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
if client.get('endpoint') is not None:
|
||||
config['endpoint'] = client['endpoint']
|
||||
if client.get('timeout_seconds') is not None:
|
||||
config['timeout_seconds'] = client['timeout_seconds']
|
||||
return config
|
||||
|
||||
|
||||
def mask_secrets(text: str, credential: dict | None) -> str:
|
||||
"""把凭据值从自由文本(错误回显/响应摘要)中替换为 ***,防外泄进审计与日志。"""
|
||||
result = str(text or '')
|
||||
for value in (credential or {}).values():
|
||||
secret = str(value or '')
|
||||
if secret:
|
||||
result = result.replace(secret, '***')
|
||||
return result
|
||||
|
||||
|
||||
def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
|
||||
"""按原始响应文本归一化结果分类(复用调拨六态分类语义)。
|
||||
@@ -102,7 +67,7 @@ def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
|
||||
error_message=str(raw.get('message') or ''),
|
||||
)
|
||||
if status == 'timeout':
|
||||
return IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN')
|
||||
return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN')
|
||||
if status == 'result_unknown':
|
||||
return IntegrationCallResult(status='result_unknown', error_code='EXTERNAL_RESULT_UNKNOWN', document_no=document_no)
|
||||
return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no)
|
||||
return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE')
|
||||
@@ -4,7 +4,6 @@
|
||||
依赖:requests(默认注入),可注入 http_request 供测试替身。
|
||||
逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为
|
||||
business_failed dict;非 JSON 响应映射为 technical_failed。
|
||||
probe 连接测试探针:GET endpoint,任意 HTTP 响应即算可达(连接异常才算不通)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,7 +13,6 @@ from typing import Any, Callable
|
||||
import requests
|
||||
|
||||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||||
from app.services.integration_connector.transports.base import mask_secrets
|
||||
|
||||
HttpRequest = Callable[..., Any]
|
||||
|
||||
@@ -52,8 +50,7 @@ class RestTransport:
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': f"HTTP_{int(response.status_code)}",
|
||||
# 错误回显可能包含请求内容(含凭据),先脱敏再截断。
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'message': str(getattr(response, 'text', ''))[:500],
|
||||
}
|
||||
try:
|
||||
return response.json()
|
||||
@@ -61,26 +58,5 @@ class RestTransport:
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'NON_JSON',
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'message': str(getattr(response, 'text', ''))[:500],
|
||||
}
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试探针:GET endpoint,任意 HTTP 响应(含 4xx/5xx)都证明网络可达。
|
||||
|
||||
与 call 的区别:不要求接口契约(method/path),不做业务语义解析;
|
||||
连接建立失败(DNS/超时/拒绝)才算不通。异常回显先脱敏再截断。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)')
|
||||
timeout = int(config.get('timeout_seconds') or 60)
|
||||
try:
|
||||
response = self._http_request('GET', endpoint, timeout=timeout)
|
||||
except Exception as exc:
|
||||
return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))}
|
||||
return {
|
||||
'ok': True,
|
||||
'code': f"HTTP_{int(getattr(response, 'status_code', 0))}",
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:200], client.get('credential'))[:200],
|
||||
}
|
||||
@@ -1,215 +1,29 @@
|
||||
"""services/integration_connector/transports/soap.py
|
||||
|
||||
用途:SOAP Transport——按接口消息配置(soap.body_template)生成报文并解析 XML 响应。
|
||||
依赖:requests(默认注入)、xml.etree.ElementTree、errors.py。
|
||||
逻辑:endpoint 或 body_template 缺失 → fail-closed(TransportNotFrozenError);
|
||||
模板占位符从请求参数 + 凭据(credential_* 保留前缀)填充,缺参即失败;
|
||||
响应按 localname 解析(不绑命名空间前缀),Body 首子节点为业务根,
|
||||
叶节点文本本身是合法 XML 时递归展开(内嵌转义报文的通用规则);
|
||||
标准 SOAP 1.1 Fault(faultcode/faultstring)→ business_failed(SOAP 1.2 的
|
||||
Code/Reason 结构暂只归 business_failed 不提取消息);HTTP ≥400 → business_failed;
|
||||
非 XML → technical_failed。
|
||||
probe 连接测试探针:GET WSDL 地址并校验返回 XML(definitions/Envelope 任一即通);
|
||||
裸服务端点自动补 ?wsdl(SOAP 端点对裸 GET 常返回 404/405/501)。
|
||||
用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。
|
||||
依赖:zeep(延时导入);errors.py。
|
||||
逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import string
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import Any, Callable
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
from app.services.integration_connector.errors import (
|
||||
InputInvalidError,
|
||||
TransportNotFrozenError,
|
||||
)
|
||||
from app.services.integration_connector.transports.base import mask_secrets
|
||||
|
||||
HttpRequest = Callable[..., Any]
|
||||
|
||||
# 内嵌转义 XML 的最大递归展开深度(防深嵌套/构造报文拖垮解析)。
|
||||
MAX_EMBED_DEPTH = 3
|
||||
|
||||
|
||||
def _localname(tag: Any) -> str:
|
||||
"""去掉命名空间 URI,只取元素/属性的本地名(厂商前缀差异不影响映射路径)。"""
|
||||
return tag.rsplit('}', 1)[-1] if isinstance(tag, str) else ''
|
||||
|
||||
|
||||
def fill_soap_template(template: str, params: dict, credential: dict) -> str:
|
||||
"""填充 SOAP 报文模板:{param} 来自请求参数,{credential_*} 来自凭据注入。
|
||||
|
||||
Args:
|
||||
template: 接口配置里的完整报文模板(str.format 语义,{{}} 为字面大括号)。
|
||||
params: 引擎映射后的接口参数。
|
||||
credential: resolve_credential 解析出的凭据字典,按 credential_ 前缀注入。
|
||||
Raises:
|
||||
InputInvalidError: 占位符无对应值(fail-closed,绝不静默出空串)。
|
||||
"""
|
||||
merged: dict[str, Any] = dict(params or {})
|
||||
# 凭据后注入并覆盖同名占位符:请求参数不得冒充/覆盖 credential_* 值。
|
||||
for key, value in (credential or {}).items():
|
||||
merged[f'credential_{key}'] = value
|
||||
missing = sorted({
|
||||
field for _, field, _, _ in string.Formatter().parse(template)
|
||||
if field and field not in merged
|
||||
})
|
||||
if missing:
|
||||
raise InputInvalidError(details={'reason': 'soap_template_param_missing', 'params': missing})
|
||||
for key, value in merged.items():
|
||||
# CDATA 内出现 ]]> 会截断报文;模板骨架自身的 CDATA 结束符不受影响,仅查替换值。
|
||||
if ']]>' in str(value):
|
||||
raise InputInvalidError(details={'reason': 'soap_cdata_terminator_in_params', 'param': key})
|
||||
try:
|
||||
return template.format(**merged)
|
||||
except (KeyError, IndexError, ValueError) as exc:
|
||||
# 覆盖裸 {} / 格式规格非法等 str.format 原生异常,统一 fail-closed 语义。
|
||||
raise InputInvalidError(details={'reason': 'soap_template_invalid'}) from exc
|
||||
|
||||
|
||||
def _element_to_value(elem: ET.Element, embed_depth: int) -> Any:
|
||||
"""把元素转为通用 dict:属性 → @key;重复同名子元素 → list;叶子文本为值。
|
||||
|
||||
叶子文本本身是合法 XML(网关型系统常见的转义内嵌报文)时递归解析并保留内层根标签。
|
||||
"""
|
||||
attrs = {f'@{_localname(key)}': value for key, value in elem.attrib.items()}
|
||||
children = list(elem)
|
||||
text = (elem.text or '').strip()
|
||||
if children:
|
||||
node: dict[str, Any] = dict(attrs)
|
||||
grouped: dict[str, list[Any]] = {}
|
||||
for child in children:
|
||||
name = _localname(child.tag)
|
||||
grouped.setdefault(name, []).append(_element_to_value(child, embed_depth))
|
||||
for name, items in grouped.items():
|
||||
node[name] = items[0] if len(items) == 1 else items
|
||||
if text:
|
||||
node['#text'] = text
|
||||
return node
|
||||
if text.startswith('<') and embed_depth > 0:
|
||||
try:
|
||||
inner = ET.fromstring(text)
|
||||
except ET.ParseError:
|
||||
inner = None
|
||||
if inner is not None:
|
||||
return {_localname(inner.tag): _element_to_value(inner, embed_depth - 1)}
|
||||
if not attrs:
|
||||
return text or None
|
||||
if text:
|
||||
return {**attrs, '#text': text}
|
||||
return attrs
|
||||
|
||||
|
||||
def _parse_soap_payload(text: str) -> dict[str, Any]:
|
||||
"""解析 SOAP 信封:取 Body 首子元素为业务根并转 dict;检测标准 Fault。"""
|
||||
root = ET.fromstring(text)
|
||||
body = None
|
||||
for node in root.iter():
|
||||
if _localname(node.tag) == 'Body':
|
||||
body = node
|
||||
break
|
||||
payload = list(body)[0] if body is not None and len(body) else root
|
||||
for node in payload.iter():
|
||||
if _localname(node.tag) == 'Fault':
|
||||
code = message = ''
|
||||
for child in node.iter():
|
||||
name = _localname(child.tag)
|
||||
if name == 'faultcode' and not code:
|
||||
code = (child.text or '').strip()
|
||||
if name == 'faultstring' and not message:
|
||||
message = (child.text or '').strip()
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': code or 'SOAP_FAULT',
|
||||
'message': message,
|
||||
}
|
||||
return {_localname(payload.tag): _element_to_value(payload, MAX_EMBED_DEPTH)}
|
||||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||||
|
||||
|
||||
class SoapTransport:
|
||||
"""SOAP 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
|
||||
"""SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。"""
|
||||
|
||||
connector_type = 'soap'
|
||||
|
||||
def __init__(self, http_request: HttpRequest | None = None):
|
||||
self._http_request = http_request or requests.request
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
# SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。
|
||||
# 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。
|
||||
wsdl = str(config.get('endpoint') or '').strip()
|
||||
if not wsdl:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
|
||||
|
||||
spec = interface.get('request_spec_json') or {}
|
||||
soap_spec = spec.get('soap') or {}
|
||||
template = str(soap_spec.get('body_template') or '').strip()
|
||||
if not template:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing soap.body_template)')
|
||||
|
||||
body = fill_soap_template(template, request.get('params') or {}, client.get('credential') or {})
|
||||
headers = {'Content-Type': 'text/xml; charset=utf-8'}
|
||||
action = str(soap_spec.get('action') or '').strip()
|
||||
# SOAPAction 头必须存在且按规范带引号(空契约即 '""'):不带引号或缺失
|
||||
# 会被鼎捷网关以 415 拒绝(2026-09-22 实测)。
|
||||
headers['SOAPAction'] = f'"{action}"'
|
||||
method = str(spec.get('method') or 'POST').upper()
|
||||
path = str(spec.get('path') or '').strip()
|
||||
url = endpoint.rstrip('/') + '/' + path.lstrip('/') if path else endpoint
|
||||
|
||||
response = self._http_request(
|
||||
method,
|
||||
url,
|
||||
data=body.encode('utf-8'),
|
||||
headers=headers,
|
||||
timeout=int(config.get('timeout_seconds') or 60),
|
||||
)
|
||||
if int(getattr(response, 'status_code', 0)) >= 400:
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': f"HTTP_{int(response.status_code)}",
|
||||
# 错误回显可能包含请求体(含凭据),先脱敏再截断。
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
}
|
||||
response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential'))
|
||||
try:
|
||||
return _parse_soap_payload(response_text)
|
||||
except ET.ParseError:
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'NON_XML',
|
||||
'message': response_text[:500],
|
||||
}
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试探针:GET WSDL 地址并校验返回 XML,只证明网络与服务可达。
|
||||
|
||||
与 call 的区别:不要求 soap.body_template 契约;根元素为 definitions
|
||||
(WSDL 地址约定)或 Envelope(直连服务端点约定)任一即算通过。
|
||||
裸服务端点对 GET 常返回 404/405/501(SOAP 只实现 POST),故未带 query
|
||||
时自动补 ?wsdl 取服务描述;已带 query(如 ?wsdl)则按原地址探测。
|
||||
连接失败 / HTTP ≥400 / 非 XML / 根元素不符 → ok=False;错误回显先脱敏。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
|
||||
timeout = int(config.get('timeout_seconds') or 60)
|
||||
probe_url = endpoint if '?' in endpoint else f'{endpoint}?wsdl'
|
||||
try:
|
||||
response = self._http_request('GET', probe_url, timeout=timeout)
|
||||
except Exception as exc:
|
||||
return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))}
|
||||
status = int(getattr(response, 'status_code', 0))
|
||||
text = mask_secrets(str(getattr(response, 'text', '') or '')[:500], client.get('credential'))
|
||||
if status >= 400:
|
||||
return {'ok': False, 'code': f'HTTP_{status}', 'message': text}
|
||||
try:
|
||||
root = ET.fromstring(str(getattr(response, 'text', '') or ''))
|
||||
except ET.ParseError:
|
||||
return {'ok': False, 'code': 'NON_XML', 'message': text}
|
||||
root_name = _localname(root.tag)
|
||||
if root_name not in ('definitions', 'Envelope'):
|
||||
return {'ok': False, 'code': 'NOT_WSDL', 'message': f'unexpected root <{root_name}>'}
|
||||
return {'ok': True, 'code': f'HTTP_{status}', 'message': f'wsdl root <{root_name}>'}
|
||||
# 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。
|
||||
raise NotImplementedError('SOAP implementation pending frozen WSDL')
|
||||
@@ -28,7 +28,6 @@ from app.services.lean_training_service import (
|
||||
_already_pushed_resource_ids,
|
||||
_config_video_resource_ids,
|
||||
_current_week_bounds,
|
||||
format_beijing_iso,
|
||||
target_user_ids_for_task,
|
||||
)
|
||||
from app.services.schedule.timezone_util import utc_now_naive
|
||||
@@ -133,8 +132,7 @@ def serialize_push_log(log: LeanTrainingVideoPushLog) -> dict[str, object]:
|
||||
"status": log.status,
|
||||
"error_message": log.error_message,
|
||||
"created_by_id": log.created_by_id,
|
||||
# 展示层转北京时间:管理端"推送记录"直接渲染该字段,UTC 直出会比实际早 8 小时
|
||||
"created_at": format_beijing_iso(log.created_at),
|
||||
"created_at": log.created_at.isoformat() if log.created_at else 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()
|
||||
|
||||
@@ -69,55 +69,6 @@ def _format_dashboard_datetime(value: str | None) -> str:
|
||||
return text[:16].replace("T", " ") if text else ""
|
||||
|
||||
|
||||
def format_beijing_iso(value: datetime | str | None) -> str | None:
|
||||
"""
|
||||
将存储的 UTC 时间转换为北京时间 ISO 字符串,供页面/Excel 展示。
|
||||
|
||||
用途:培训模块数据库统一存 UTC naive(观看/完成/截止时间),而业务要求所有对外展示为北京时间;
|
||||
此前序列化直接输出 UTC 导致页面显示比实际早 8 小时(如 18:47 显示 10:47)。
|
||||
Args:
|
||||
value: UTC naive datetime 或 ISO 字符串;naive 按 UTC 处理,带时区则先归一到绝对时间;
|
||||
字符串无法解析时原样返回,避免历史脏数据导致展示层报错。
|
||||
Returns:
|
||||
带 +08:00 偏移的 ISO 字符串(如 2026-09-22T18:47:00+08:00,前端 slice(0,16) 即得北京时间);入参为空返回 None。
|
||||
业务约束:仅用于序列化输出层,禁止将转换结果写回数据库——存储与服务端比较(超期判定等)仍一律 UTC。
|
||||
"""
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.strip())
|
||||
except ValueError:
|
||||
return value.strip()
|
||||
else:
|
||||
parsed = value
|
||||
if parsed.tzinfo is None:
|
||||
parsed = parsed.replace(tzinfo=timezone.utc)
|
||||
return parsed.astimezone(resolve_schedule_tzinfo("Asia/Shanghai")).isoformat()
|
||||
|
||||
|
||||
def parse_client_iso_to_utc_text(text: str) -> str:
|
||||
"""
|
||||
将客户端回显的观看时间 ISO 字符串归一为 UTC naive ISO 文本,供存储。
|
||||
|
||||
用途:save_completion 会合并客户端提交的 watched_at 兜底值(服务端记录缺失时入库);
|
||||
客户端时间格式随版本演进(UTC 带 Z / 北京时间带 +08:00),必须归一为 UTC,
|
||||
否则 watched_at_json 混入非 UTC 值会破坏"存储一律 UTC"的约定,后续服务端比较将出错。
|
||||
Args:
|
||||
text: 客户端提交的 ISO 时间字符串。
|
||||
Returns:
|
||||
UTC naive ISO 文本;无法解析时原样返回(与历史行为一致,不因脏数据阻塞提交)。
|
||||
"""
|
||||
try:
|
||||
parsed = datetime.fromisoformat(str(text))
|
||||
except ValueError:
|
||||
return str(text)
|
||||
if parsed.tzinfo is None:
|
||||
# naive 视为北京时间墙钟(新版客户端口径),入库前转 UTC
|
||||
parsed = parsed.replace(tzinfo=resolve_schedule_tzinfo("Asia/Shanghai"))
|
||||
return to_utc_naive(parsed).isoformat()
|
||||
|
||||
|
||||
def _dashboard_status_label(status: str | None) -> str:
|
||||
"""将看板状态转换为页面一致的中文文案。"""
|
||||
return {
|
||||
@@ -293,8 +244,7 @@ def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool =
|
||||
"week_key": task.week_key,
|
||||
"week_end": (week_start + timedelta(days=6)).isoformat() if week_start else None,
|
||||
"week_index": week_index_for_task(task),
|
||||
# 展示层转北京时间:管理端编辑器/看板头与学员端均直接渲染该字段,UTC 直出会比实际早 8 小时
|
||||
"due_at": format_beijing_iso(task.due_at),
|
||||
"due_at": task.due_at.isoformat(),
|
||||
"video_resource_ids": visible_ids,
|
||||
"target_roles": list(task.target_roles or []),
|
||||
"target_user_ids": list(task.target_user_ids or []),
|
||||
@@ -464,9 +414,8 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
|
||||
item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress")
|
||||
item["completion"] = {
|
||||
"summary_text": completion.summary_text,
|
||||
# 展示层转北京时间:学员端"已观看"直接渲染该字典值,存储仍为 UTC
|
||||
"watched_at": {key: format_beijing_iso(value) for key, value in (completion.watched_at_json or {}).items()},
|
||||
"completed_at": format_beijing_iso(completion.completed_at),
|
||||
"watched_at": dict(completion.watched_at_json or {}),
|
||||
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
|
||||
} if completion else None
|
||||
items.append(item)
|
||||
return items
|
||||
@@ -502,8 +451,7 @@ def mark_video_watched(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
# 观看草稿:保持 completed_at 为空,任务仍为进行中/已延期,直至感悟提交完成
|
||||
db.session.add(completion)
|
||||
db.session.commit()
|
||||
# 返回值供学员端即时回显"已观看时间",展示层转北京时间;数据库中保持 UTC
|
||||
return {"watched_at": {key: format_beijing_iso(value) for key, value in watched.items()}}
|
||||
return {"watched_at": watched}
|
||||
|
||||
|
||||
def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -517,8 +465,7 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
# 员工只能观看已推送的前缀视频,完成校验同样基于已推送范围而非全量选择列表
|
||||
required_ids = list(task.video_resource_ids or [])[: task.pushed_video_count]
|
||||
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
|
||||
# 兜底值入库前归一为 UTC:客户端可能提交北京时间(+08:00)或 UTC(Z)格式,存储一律 UTC
|
||||
watched = {str(key): parse_client_iso_to_utc_text(value) for key, value in (data.get("watched_at") or {}).items()}
|
||||
watched = {str(key): str(value) for key, value in (data.get("watched_at") or {}).items()}
|
||||
completion = db.session.execute(
|
||||
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
|
||||
).scalar_one_or_none() or LeanTrainingCompletion(weekly_task_id=task.id, user_id=user.id)
|
||||
@@ -554,7 +501,7 @@ def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompl
|
||||
# [RULE] 看板视频列只展示已推送前缀(video_resource_ids[:pushed_video_count]):未推送视频不属于本周期学习范围,避免名单出现从未布置过的视频
|
||||
visible_ids = task.video_resource_ids[: task.pushed_video_count]
|
||||
return [
|
||||
{"name": titles.get(resource_id, ""), "watched_at": format_beijing_iso(watched.get(str(resource_id)))}
|
||||
{"name": titles.get(resource_id, ""), "watched_at": watched.get(str(resource_id))}
|
||||
for resource_id in visible_ids
|
||||
]
|
||||
|
||||
@@ -575,7 +522,7 @@ def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingW
|
||||
"videos": _task_video_rows(task, completion),
|
||||
"summary_text": completion.summary_text,
|
||||
"status": status,
|
||||
"completed_at": format_beijing_iso(completion.completed_at),
|
||||
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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)]
|
||||
@@ -71,16 +71,8 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
|
||||
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count}
|
||||
db.session.commit()
|
||||
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+全部收料文件。
|
||||
try:
|
||||
task = run.task
|
||||
if task is not None and task.notify_enabled:
|
||||
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
|
||||
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
db.session.commit()
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-run] receipt RPA wecom notify failed: %s', wecom_exc)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_schedule_receipt_summary
|
||||
deliver_schedule_receipt_summary(run.id)
|
||||
return {'finalized': True, 'status': run.status}
|
||||
|
||||
|
||||
|
||||
Loaded 100 of 336 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user