diff --git a/.env.dev b/.env.dev
index 9ca67b66..2a0a1e9b 100644
--- a/.env.dev
+++ b/.env.dev
@@ -54,10 +54,13 @@ MINIO_SECURE=false
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
-# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
+# RoHS / 货代等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
+# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
+HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
-SHIPPING_NOTICE_TOOL_API_KEY=nsCL8xn3shu6u-5grXsd7jXlPzYcRrvLoaHnl9OMfE5nmuqNEsUah2n9uPGXEsy_
+
+SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
@@ -113,4 +116,4 @@ FREIGHT_RPA_MOCK=false
# FREIGHT_RPA_SAMPLE_INVENTORY=
# 设备维保助手后端工具调用密钥
-MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
\ No newline at end of file
+MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
diff --git a/.env.prod b/.env.prod
index b0bafa2d..4adaa83c 100644
--- a/.env.prod
+++ b/.env.prod
@@ -47,7 +47,9 @@ TASK_EXECUTION_MODE=rq
GUNICORN_WORKERS=20
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
+# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
+WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
# MinIO(知识库文档清洗图片托管,容器 minio-app)
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
@@ -58,11 +60,13 @@ MINIO_SECURE=false
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
-# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
+# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
+# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
+HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
-# SHIPPING_NOTICE_TOOL_API_KEY=nsCL8xn3shu6u-5grXsd7jXlPzYcRrvLoaHnl9OMfE5nmuqNEsUah2n9uPGXEsy_
+SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
@@ -73,6 +77,19 @@ FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
+# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
+SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
+SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
+# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
+SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
+SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
+SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
+
+# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
+FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
+FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
+FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
+FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# 设备维保助手后端工具调用密钥
diff --git a/.env.shared b/.env.shared
index aff394e0..46a40beb 100644
--- a/.env.shared
+++ b/.env.shared
@@ -80,8 +80,10 @@ WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=
# Common integration defaults
INTEGRATION_API_MODE=local
DIFY_API_BASE=https://api.dify.ai/v1
-# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow、OpenAPI、签名下载链接;无尾斜杠;各环境 .env.* 覆盖)
+# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
HXOPS_TOOLS_API_BASE=
+# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
+HXOPS_PUBLIC_BASE_URL=
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
diff --git a/.env.test b/.env.test
index 5f8b672d..ded487c5 100644
--- a/.env.test
+++ b/.env.test
@@ -47,7 +47,10 @@ TASK_EXECUTION_MODE=rq
GUNICORN_WORKERS=6
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
+# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
+WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
+HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
# MinIO(知识库文档清洗图片托管,容器 minio-app)
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
@@ -65,7 +68,7 @@ HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
-# SHIPPING_NOTICE_TOOL_API_KEY=
+SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
@@ -90,7 +93,7 @@ SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
-SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
+SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
@@ -102,10 +105,25 @@ FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
+# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
+SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
+SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
+# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
+# 两者皆无则告警只写日志、不会发企微
+SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
+SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
+# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
+SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
# 发货 Excel 模板(可选)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
+# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
+FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
+FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
+FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
+FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
+
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
diff --git a/.gitignore b/.gitignore
index 70ab0889..40af67ea 100644
--- a/.gitignore
+++ b/.gitignore
@@ -84,3 +84,5 @@ backend/data/kb/
.pytest_cache/
backend/data/fixed_assets/manifest.json
backend/data/shipping_notice/
+backend/data/logs/
+backend/data/logs/*.log
diff --git a/.vscode/settings.json b/.vscode/settings.json
index fb4db4d6..b1061986 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -1,7 +1,8 @@
{
- // 后端 Python 虚拟环境
+ // 后端 Python 虚拟环境(解释器路径供语言服务/调试使用)
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
- "python.terminal.activateEnvironment": true,
+ // 关闭 Python 扩展在新建终端时自动 activate,避免与下方 PowerShell (HXOPS) 的 cd 钩子重复激活
+ "python.terminal.activateEnvironment": false,
"python.venvPath": "${workspaceFolder}/backend",
"python.venvFolders": [".venv"],
"github.copilot.chat.commitMessageGeneration.instructions": [
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 9d7c511a..a2540bef 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -3,7 +3,8 @@ backend/app/__init__.py
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
-逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter。
+逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter;
+ 并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。
"""
import logging
import uuid
@@ -64,6 +65,16 @@ def create_app(config_name='default'):
ensure_intent_routes_loaded()
from app.services.schedule.scheduler_service import start_scheduler
start_scheduler(app)
+ # 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口
+ try:
+ from app.services.file_assets.cleanup_schedule import (
+ ensure_default_file_asset_cleanup_schedule,
+ register_file_asset_cleanup_schedule_hooks,
+ )
+ register_file_asset_cleanup_schedule_hooks()
+ ensure_default_file_asset_cleanup_schedule()
+ except Exception as exc: # pragma: no cover - 表未就绪时容忍
+ logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
FixedAssetsSnapshotService.start_worker(app)
diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py
index 808ca7b9..f85537bf 100644
--- a/backend/app/api/__init__.py
+++ b/backend/app/api/__init__.py
@@ -39,6 +39,7 @@ def register_blueprints(app: Flask) -> None:
workspace_shipping_notice_bp,
)
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
+ from app.api.files import files_bp
app.register_blueprint(chat_bp, url_prefix='/api/chat')
app.register_blueprint(admin_bp, url_prefix='/api/admin')
@@ -60,3 +61,4 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
+ app.register_blueprint(files_bp, url_prefix='/api/files')
diff --git a/backend/app/api/admin/reports.py b/backend/app/api/admin/reports.py
index 8aa10a5c..1109a51e 100644
--- a/backend/app/api/admin/reports.py
+++ b/backend/app/api/admin/reports.py
@@ -3,7 +3,7 @@ backend/app/api/admin/reports.py
用途:管理后台报表 API(薄路由层)。
依赖:admin.blueprint、services/admin/report_service。
-逻辑:/reports/* 路由。
+逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
"""
from flask import jsonify, request
@@ -38,6 +38,35 @@ def usage_report():
)
+@admin_bp.route('/reports/applications', methods=['GET'])
+@require_admin
+def applications_report():
+ """
+ 应用运营报表:按应用聚合使用 / 权限 / 评分。
+ Query: range, status, usage, q, sort, order, page, page_size。
+ """
+ try:
+ page = int(request.args.get('page', 1))
+ except (TypeError, ValueError):
+ page = 1
+ try:
+ page_size = int(request.args.get('page_size', 20))
+ except (TypeError, ValueError):
+ page_size = 20
+ return jsonify(
+ report_service.build_application_report(
+ range_key=request.args.get('range'),
+ status=request.args.get('status'),
+ usage=request.args.get('usage'),
+ q=request.args.get('q'),
+ sort=request.args.get('sort'),
+ order=request.args.get('order'),
+ page=page,
+ page_size=page_size,
+ )
+ )
+
+
@admin_bp.route('/reports/feedback', methods=['GET'])
@require_admin
def feedback_report():
diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py
index c94f421b..4b3fa999 100644
--- a/backend/app/api/chat.py
+++ b/backend/app/api/chat.py
@@ -8,6 +8,8 @@ backend/app/api/chat.py
import io
import ipaddress
import mimetypes
+import ntpath
+import posixpath
import tempfile
import os
import subprocess
@@ -226,26 +228,60 @@ def _update_chat_session(
return session
-def _normalize_windows_share_path(path_value: str) -> str:
- normalized = str(path_value or '').strip().strip('"').replace('/', '\\')
- if normalized.startswith('\\\\'):
- return '\\\\' + normalized[2:].rstrip('\\')
- return normalized.rstrip('\\')
+def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
+ """
+ 统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
+
+ Returns:
+ (path_kind, normalized_path)
+ - path_kind: 'windows' | 'posix' | ''
+ - normalized_path: 归一化后的绝对路径文本
+ """
+ raw_value = str(path_value or '').strip().strip('"')
+ if not raw_value:
+ return ('', '')
+ if raw_value.startswith('\\\\'):
+ normalized = raw_value.replace('/', '\\')
+ normalized = '\\\\' + normalized[2:].rstrip('\\')
+ return ('windows', normalized)
+ if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
+ normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
+ return ('windows', normalized)
+ if raw_value.startswith('/'):
+ normalized = posixpath.normpath(raw_value.replace('\\', '/'))
+ return ('posix', normalized.rstrip('/'))
+ return ('', '')
+
+def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
+ target_kind, normalized_target = _normalize_allowed_share_path(target_path)
+ root_kind, normalized_root = _normalize_allowed_share_path(root_path)
+ if not normalized_target or not normalized_root or target_kind != root_kind:
+ return False
+ if target_kind == 'windows':
+ target_lower = normalized_target.lower()
+ root_lower = normalized_root.lower()
+ return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
+ return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
def _is_allowed_share_path(target_url: str) -> bool:
- normalized_target = _normalize_windows_share_path(target_url)
- if not normalized_target.startswith('\\\\'):
+ target_kind, normalized_target = _normalize_allowed_share_path(target_url)
+ if not normalized_target:
return False
history_share_root = ''
+ history_local_root = ''
if has_request_context():
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
+ history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
if not history_share_root:
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
+ if not history_local_root:
+ history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
roots = [
- _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT),
- _normalize_windows_share_path(history_share_root),
+ PLM_PREVIEW_SHARE_ROOT,
+ history_share_root,
+ history_local_root,
]
- return any(root and normalized_target.lower().startswith(root.lower()) for root in roots)
+ return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
def _is_allowed_preview_url(target_url: str) -> bool:
"""
@@ -300,7 +336,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
import sqlalchemy as sa
from urllib.parse import parse_qs
if _is_allowed_share_path(file_url):
- normalized_path = _normalize_windows_share_path(file_url)
+ _path_kind, normalized_path = _normalize_allowed_share_path(file_url)
try:
if not os.path.isfile(normalized_path):
return (None, None, ('source file not found', 404))
@@ -1002,7 +1038,7 @@ def get_chat_messages():
continue
assistant_msg = {
'role': 'assistant',
- 'content': log.answer,
+ 'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
'chat_log_id': log.id,
'retriever_resources': log.retriever_resources or [],
'attribution_parts': log.attribution_parts or [],
@@ -1166,31 +1202,6 @@ def search_asset_history_files():
asset_name = (request.args.get('asset_name') or '').strip()
limit = request.args.get('limit', type=int) or 20
limit = max(1, min(limit, 50))
- # #region debug-point C:asset-history-api-entry
- import json as _debug_json
- import urllib.request as _debug_urllib_request
- try:
- _debug_payload = _debug_json.dumps({
- 'sessionId': 'asset-history-click',
- 'runId': 'pre-fix',
- 'hypothesisId': 'C',
- 'location': 'backend/chat.py:search_asset_history_files',
- 'msg': '[DEBUG] asset history api entry',
- 'data': {
- 'asset_id': asset_id,
- 'asset_name': asset_name,
- 'limit': limit,
- },
- }).encode('utf-8')
- _debug_urllib_request.urlopen(_debug_urllib_request.Request(
- 'http://127.0.0.1:7777/event',
- data=_debug_payload,
- headers={'Content-Type': 'application/json'},
- method='POST',
- ), timeout=2).read()
- except Exception:
- pass
- # #endregion
if not asset_id and not asset_name:
raise ValidationError('asset_id or asset_name is required')
@@ -1198,27 +1209,6 @@ def search_asset_history_files():
from app.services.fixed_asset_history import FixedAssetHistoryService
if not FixedAssetHistoryService.is_enabled():
- # #region debug-point C:asset-history-api-disabled
- try:
- _debug_payload = _debug_json.dumps({
- 'sessionId': 'asset-history-click',
- 'runId': 'pre-fix',
- 'hypothesisId': 'C',
- 'location': 'backend/chat.py:search_asset_history_files',
- 'msg': '[DEBUG] asset history api disabled',
- 'data': {
- 'share_root': str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or ''),
- },
- }).encode('utf-8')
- _debug_urllib_request.urlopen(_debug_urllib_request.Request(
- 'http://127.0.0.1:7777/event',
- data=_debug_payload,
- headers={'Content-Type': 'application/json'},
- method='POST',
- ), timeout=2).read()
- except Exception:
- pass
- # #endregion
raise ServiceUnavailableError('asset history share is not configured')
items = FixedAssetHistoryService.search_history_files(
@@ -1226,29 +1216,6 @@ def search_asset_history_files():
asset_name=asset_name,
limit=limit,
)
- # #region debug-point C:asset-history-api-success
- try:
- _debug_payload = _debug_json.dumps({
- 'sessionId': 'asset-history-click',
- 'runId': 'pre-fix',
- 'hypothesisId': 'C',
- 'location': 'backend/chat.py:search_asset_history_files',
- 'msg': '[DEBUG] asset history api success',
- 'data': {
- 'asset_id': asset_id,
- 'asset_name': asset_name,
- 'item_count': len(items),
- },
- }).encode('utf-8')
- _debug_urllib_request.urlopen(_debug_urllib_request.Request(
- 'http://127.0.0.1:7777/event',
- data=_debug_payload,
- headers={'Content-Type': 'application/json'},
- method='POST',
- ), timeout=2).read()
- except Exception:
- pass
- # #endregion
return jsonify({
'asset_id': asset_id,
'asset_name': asset_name,
diff --git a/backend/app/api/file_check_tools.py b/backend/app/api/file_check_tools.py
index 1de3a883..f14336d1 100644
--- a/backend/app/api/file_check_tools.py
+++ b/backend/app/api/file_check_tools.py
@@ -27,13 +27,19 @@ from app.core.errors import (
)
from app.models import ScheduleRun, ScheduleTask
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
-from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
+from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
from app.services.schedule import _build_srm_conn_str
from app.services.schedule.query_service import get_run, serialize_run
from app.services.schedule.srm_service import _fetch_records
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
+try:
+ import pyodbc # type: ignore
+except Exception: # pragma: no cover
+ pyodbc = None
+
+
file_check_bp = Blueprint("file_check_tools", __name__)
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
@@ -41,13 +47,13 @@ _RUN_START_LOCK = threading.Lock()
_TASK_LOCK_KEY_BASE = 8700000000
-def _tool_token_secret() -> str:
- return str(
- current_app.config.get("FILE_CHECK_TOOL_API_KEY")
- or current_app.config.get("INTEGRATION_API_KEY")
- or current_app.config.get("SECRET_KEY")
- or "default-secret"
- ).strip()
+def _download_token_secret() -> str:
+ """
+ Excel 下载 JWT 签名密钥。
+
+ 核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
+ """
+ return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
def _decode_download_token(token: str | None) -> dict | None:
@@ -57,7 +63,7 @@ def _decode_download_token(token: str | None) -> dict | None:
try:
import jwt
- payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
+ payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
return payload if isinstance(payload, dict) else None
except Exception as exc:
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
@@ -65,6 +71,20 @@ def _decode_download_token(token: str | None) -> dict | None:
def _require_tool_auth() -> None:
+ """
+ 校验 Tool API 访问权限。
+
+ 核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
+ """
+ # [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
+ if request.path.endswith("/excel"):
+ query_token = str(request.args.get("token") or "").strip()
+ if query_token:
+ if _decode_download_token(query_token):
+ return
+ raise UnauthorizedError("invalid_auth")
+
+ # [STEP 2] Dify / RPA 服务端调用
configured = str(
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
@@ -77,13 +97,11 @@ def _require_tool_auth() -> None:
)
bearer = str(request.headers.get("Authorization") or "").strip()
- token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
+ api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
- if configured in {token, integration_key}:
+ if configured in {api_token, integration_key}:
return
- if request.path.endswith("/excel") and _decode_download_token(request.args.get("token")):
- return
- if not token and not integration_key:
+ if not api_token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
@@ -104,6 +122,8 @@ def _tool_error_code(exc: AppError) -> str:
"dify_retrieve_failed",
}:
return message
+ if exc.code == "data_source_unavailable":
+ return "data_source_unavailable"
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
@@ -128,7 +148,8 @@ def _handle_tool_app_error(exc: AppError):
def _public_base_url() -> str:
- return resolve_HXOPS_TOOLS_API_BASE()
+ """用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
+ return resolve_hxops_user_facing_base_url()
def _acquire_task_start_lock(task_id: int) -> None:
@@ -148,7 +169,7 @@ def _build_excel_download_url(run: ScheduleRun) -> str:
"run_id": run.id,
"exp": int(time.time()) + 600,
}
- token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
+ token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
@@ -309,12 +330,30 @@ def _build_no_data_response(task: ScheduleTask) -> dict:
}
+def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
+ """
+ 将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
+
+ 核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
+ """
+ current_app.logger.warning(
+ "[file-check-tool] precheck data source unavailable task_id=%s error=%s",
+ task.id,
+ exc,
+ exc_info=True,
+ )
+ raise ServiceUnavailableError(
+ "检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
+ code="data_source_unavailable",
+ ) from exc
+
+
def _precheck_no_data(task: ScheduleTask) -> dict | None:
"""
启动前预检当前任务是否存在待检资料。
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
- 避免创建空批次并向 ChatLog 回写 run_id。
+ 避免创建空批次并向 ChatLog 回写 run_id。数据源连接失败时抛 503 data_source_unavailable。
"""
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
return None
@@ -323,12 +362,19 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
if not cfg or not str(cfg.fetch_sql or "").strip():
return None
- if cfg.data_source and not cfg.data_source.is_empty():
- conn_str = cfg.data_source.build_connection_string()
- else:
- conn_str = _build_srm_conn_str()
+ try:
+ if cfg.data_source and not cfg.data_source.is_empty():
+ conn_str = cfg.data_source.build_connection_string()
+ else:
+ conn_str = _build_srm_conn_str()
+ rows = _fetch_records(conn_str, cfg.fetch_sql)
+ except RuntimeError as exc:
+ _raise_data_source_unavailable(task, exc)
+ except Exception as exc:
+ if pyodbc is not None and isinstance(exc, pyodbc.Error):
+ _raise_data_source_unavailable(task, exc)
+ raise
- rows = _fetch_records(conn_str, cfg.fetch_sql)
if rows:
return None
return _build_no_data_response(task)
diff --git a/backend/app/api/files/__init__.py b/backend/app/api/files/__init__.py
new file mode 100644
index 00000000..6f83cae9
--- /dev/null
+++ b/backend/app/api/files/__init__.py
@@ -0,0 +1,11 @@
+"""
+backend/app/api/files/__init__.py
+
+用途:平台级文件资产 API 包入口。
+依赖:files.assets。
+逻辑:register_blueprints 挂载 /api/files。
+"""
+
+from app.api.files.assets import files_bp
+
+__all__ = ['files_bp']
diff --git a/backend/app/api/files/assets.py b/backend/app/api/files/assets.py
new file mode 100644
index 00000000..9c6243a5
--- /dev/null
+++ b/backend/app/api/files/assets.py
@@ -0,0 +1,80 @@
+"""
+backend/app/api/files/assets.py
+
+用途:通用文件资产上传、查询、删除与受控下载 API。
+依赖:file_assets.service、app.core.auth.jwt、app.core.response。
+逻辑:薄路由鉴权与参数校验;storage_key 不向前端返回。
+"""
+
+from __future__ import annotations
+
+import io
+
+from flask import Blueprint, g, request, send_file
+
+from app.core.auth.jwt import get_current_user
+from app.core.errors import UnauthorizedError
+from app.core.response import ok
+from app.services.file_assets.service import (
+ delete_temporary_asset,
+ get_asset_for_user,
+ read_asset_bytes,
+ serialize_asset_public,
+ upload_file_asset,
+)
+
+files_bp = Blueprint('files', __name__)
+
+
+def _require_user():
+ user = get_current_user()
+ if not user:
+ raise UnauthorizedError()
+ return user
+
+
+@files_bp.route('/assets', methods=['POST'])
+def upload_asset():
+ """上传文件并创建 FileAsset。"""
+ user = _require_user()
+ upload = request.files.get('file')
+ if not upload:
+ from app.core.errors import ValidationError
+
+ raise ValidationError('file is required')
+ if not upload.filename:
+ from app.core.errors import ValidationError
+
+ raise ValidationError('file is required')
+ data = upload_file_asset(user_id=user.id, upload=upload)
+ return ok(data, request_id=getattr(g, 'request_id', None), status=201)
+
+
+@files_bp.route('/assets/', methods=['GET'])
+def get_asset(asset_no: str):
+ """查询当前用户的文件资产元数据。"""
+ user = _require_user()
+ asset = get_asset_for_user(asset_no, user.id)
+ return ok(serialize_asset_public(asset), request_id=getattr(g, 'request_id', None))
+
+
+@files_bp.route('/assets/', methods=['DELETE'])
+def delete_asset(asset_no: str):
+ """逻辑删除未引用的临时资产。"""
+ user = _require_user()
+ delete_temporary_asset(asset_no=asset_no, user_id=user.id)
+ return ok({'deleted': True}, request_id=getattr(g, 'request_id', None))
+
+
+@files_bp.route('/assets//download', methods=['GET'])
+def download_asset(asset_no: str):
+ """鉴权后流式下载文件内容。"""
+ user = _require_user()
+ asset = get_asset_for_user(asset_no, user.id)
+ data = read_asset_bytes(asset)
+ return send_file(
+ io.BytesIO(data),
+ mimetype=asset.mime_type or 'application/octet-stream',
+ as_attachment=True,
+ download_name=asset.original_filename,
+ )
diff --git a/backend/app/api/schedule/__init__.py b/backend/app/api/schedule/__init__.py
index 034a6942..c731c734 100644
--- a/backend/app/api/schedule/__init__.py
+++ b/backend/app/api/schedule/__init__.py
@@ -12,5 +12,6 @@ import app.api.schedule.config # noqa: F401
import app.api.schedule.tasks # noqa: F401
import app.api.schedule.runs # noqa: F401
import app.api.schedule.platform_tasks # noqa: F401
+import app.api.schedule.rpa_workers # noqa: F401
__all__ = ['schedule_admin_bp']
diff --git a/backend/app/api/schedule/rpa_workers.py b/backend/app/api/schedule/rpa_workers.py
new file mode 100644
index 00000000..4616e456
--- /dev/null
+++ b/backend/app/api/schedule/rpa_workers.py
@@ -0,0 +1,24 @@
+"""
+backend/app/api/schedule/rpa_workers.py
+
+用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
+依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
+逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
+"""
+
+from __future__ import annotations
+
+from app.api.schedule.blueprint import schedule_admin_bp
+from app.core.decorators import require_admin
+from app.core.response import ok
+from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status
+
+
+@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
+@require_admin
+def get_rpa_workers_status():
+ """
+ 返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
+ 核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
+ """
+ return ok(serialize_rpa_worker_status())
diff --git a/backend/app/api/schedule/runs.py b/backend/app/api/schedule/runs.py
index 7fee8f9f..f35875cf 100644
--- a/backend/app/api/schedule/runs.py
+++ b/backend/app/api/schedule/runs.py
@@ -21,6 +21,7 @@ from app.core.errors import ConflictError, NotFoundError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.query_service import get_run, list_runs, serialize_run
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
+from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
@@ -139,3 +140,19 @@ def get_schedule_run_excel(run_id: int):
download_name=run.excel_file_name or 'result.xlsx',
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
+
+
+@schedule_admin_bp.route('/schedule-runs//inventory-raw-zip', methods=['GET'])
+@require_admin
+def get_schedule_run_inventory_raw_zip(run_id: int):
+ """下载库存 RPA 排程 run 的原始库存 Excel 打包(ZIP + manifest)。"""
+ run = get_run(run_id)
+ if not run:
+ raise NotFoundError('Not found')
+ zip_path, file_name = resolve_inventory_raw_zip_download(run)
+ return send_file(
+ zip_path,
+ as_attachment=True,
+ download_name=file_name,
+ mimetype='application/zip',
+ )
diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py
index 797d7b33..368380f0 100644
--- a/backend/app/api/shipping_notice_tools.py
+++ b/backend/app/api/shipping_notice_tools.py
@@ -34,6 +34,7 @@ from app.services.shipping_notice.query_service import (
task_export_error_message,
)
from app.services.shipping_notice.tool_common import switch_batch_focus
+from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__)
@@ -81,7 +82,10 @@ def _tool_error_code(exc: AppError) -> str:
@shipping_notice_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
- return (jsonify({'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}), exc.http_status)
+ body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
+ if exc.details:
+ body['details'] = exc.details
+ return jsonify(body), exc.http_status
@shipping_notice_bp.before_request
def _verify_tool_access():
@@ -148,7 +152,7 @@ def tool_create_batch():
batch = get_batch_by_no(batch_no)
if batch:
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
- batch = shipping_tools.create_batch(payload)
+ batch, _created = shipping_tools.create_batch(payload)
db.session.commit()
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
@@ -258,6 +262,16 @@ def tool_submit_decision():
"""
return jsonify(shipping_tools.submit_decision(_payload()))
+
+@shipping_notice_bp.route('/tools/confirm_inventory_source', methods=['POST'])
+def tool_confirm_inventory_source():
+ """
+ 确认库存查询来源(仅提交 source_code)。
+ 【AI 触发时机】:用户在库存源人工检查点选择正式库存源后调用。
+ """
+ return jsonify(shipping_tools.confirm_inventory_source(_payload()))
+
+
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
def tool_generate_shipment_excel():
"""
@@ -323,6 +337,22 @@ def tool_switch_focus_task():
db.session.commit()
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
+@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
+def rpa_worker_heartbeat():
+ """
+ RPA Worker 心跳上报。
+ 核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
+ """
+ payload = _payload()
+ try:
+ worker = record_rpa_worker_heartbeat(payload)
+ except ValueError as exc:
+ raise ValidationError(str(exc))
+ except ServiceUnavailableError:
+ raise
+ return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
+
+
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
def rpa_inventory_ready():
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
@@ -333,6 +363,17 @@ def rpa_inventory_batch_ready():
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
+@shipping_notice_bp.route('/tasks//repair-inventory-attachment', methods=['POST'])
+def repair_task_inventory_attachment(task_no: str):
+ """
+ 从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
+ 核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
+ """
+ payload = _payload()
+ payload.setdefault("task_no", task_no)
+ payload.setdefault("task_id", task_no)
+ return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
+
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py
index 62271c1e..500de75c 100644
--- a/backend/app/api/workspace/shipping_notice.py
+++ b/backend/app/api/workspace/shipping_notice.py
@@ -101,8 +101,17 @@ def workspace_create_shipping_batch_from_notices():
create_shipping_batch_from_notice_items,
intake_notice_uploads_for_batch,
)
+ from app.services.shipping_notice.batch_create_idempotency import (
+ normalize_create_idempotency_key,
+ warn_missing_create_idempotency_key,
+ )
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
conversation_id = str(request.form.get('conversation_id') or '').strip()
+ idempotency_key = normalize_create_idempotency_key(
+ request.headers.get('Idempotency-Key') or request.form.get('idempotency_key')
+ )
+ if not idempotency_key:
+ warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_notices')
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
try:
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
@@ -114,6 +123,7 @@ def workspace_create_shipping_batch_from_notices():
conversation_id=conversation_id or None,
notice_items=notice_items,
file_summary=file_summary,
+ create_idempotency_key=idempotency_key,
)
return _ok(created)
@@ -362,7 +372,11 @@ def workspace_confirm_shipping_inventory_source(task_no: str):
if not source_code:
raise ValidationError('source_code is required')
from app.services.shipping_notice import tools as shipping_tools
- return jsonify(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code}))
+ return jsonify(shipping_tools.confirm_inventory_source({
+ 'task_id': task.task_no,
+ 'source_code': source_code,
+ '_trusted_user_id': user.id,
+ }))
@workspace_shipping_notice_bp.route('/shipping-tasks//apply-inventory-mapping', methods=['POST'])
def workspace_apply_inventory_mapping(task_no: str):
@@ -575,6 +589,147 @@ def workspace_shipping_task_export(task_no: str):
path, download_name = resolved
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
+
+@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
+def workspace_list_shipping_notice_intakes():
+ """列出当前会话下未消费的活跃接入记录。"""
+ user = _require_user()
+ conversation_id = str(request.args.get('conversation_id') or '').strip() or None
+ status = str(request.args.get('status') or '').strip().lower()
+ from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation
+
+ if status and status != 'active':
+ return _ok({'items': []})
+ items = list_active_intakes_for_conversation(user_id=user.id, conversation_id=conversation_id)
+ return _ok({'items': items})
+
+
+@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
+def workspace_create_shipping_notice_intake():
+ """基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
+ user = _require_user()
+ body = request.get_json(silent=True) or {}
+ asset_no = str(body.get('asset_no') or '').strip()
+ if not asset_no:
+ raise ValidationError('asset_no is required')
+ conversation_id = str(body.get('conversation_id') or '').strip() or None
+ from app.services.shipping_notice.intake_service import create_shipping_notice_intake
+
+ data = create_shipping_notice_intake(
+ user_id=user.id,
+ asset_no=asset_no,
+ conversation_id=conversation_id,
+ )
+ return ok(data, request_id=getattr(g, 'request_id', None), status=202)
+
+
+@workspace_shipping_notice_bp.route('/shipping-notice/intakes/', methods=['GET'])
+def workspace_get_shipping_notice_intake(intake_no: str):
+ """查询单个接入记录。"""
+ user = _require_user()
+ from app.services.shipping_notice.intake_service import get_intake_detail
+
+ return _ok(get_intake_detail(user_id=user.id, intake_no=intake_no))
+
+
+@workspace_shipping_notice_bp.route('/shipping-notice/intakes/status', methods=['POST'])
+def workspace_shipping_notice_intake_statuses():
+ """批量查询接入状态。"""
+ user = _require_user()
+ body = request.get_json(silent=True) or {}
+ intake_nos = body.get('intake_nos')
+ if not isinstance(intake_nos, list):
+ raise ValidationError('intake_nos is required')
+ from app.services.shipping_notice.intake_service import get_intake_statuses
+
+ return _ok({'items': get_intake_statuses(user_id=user.id, intake_nos=intake_nos)})
+
+
+@workspace_shipping_notice_bp.route('/shipping-notice/intakes//retry', methods=['POST'])
+def workspace_retry_shipping_notice_intake(intake_no: str):
+ """重试失败的预解析。"""
+ user = _require_user()
+ from app.services.shipping_notice.intake_service import retry_intake_parse
+
+ return _ok(retry_intake_parse(user_id=user.id, intake_no=intake_no))
+
+
+@workspace_shipping_notice_bp.route('/shipping-notice/intakes/', methods=['DELETE'])
+def workspace_cancel_shipping_notice_intake(intake_no: str):
+ """取消未消费接入记录。"""
+ user = _require_user()
+ from app.services.shipping_notice.intake_service import cancel_intake
+
+ cancel_intake(user_id=user.id, intake_no=intake_no)
+ return _ok({'cancelled': True})
+
+
+@workspace_shipping_notice_bp.route(
+ '/shipping-notice/intakes//duplicate-resolution',
+ methods=['POST'],
+)
+def workspace_resolve_shipping_notice_duplicate(intake_no: str):
+ """保存发货通知重复检测决策。"""
+ user = _require_user()
+ body = request.get_json(silent=True) or {}
+ action = str(body.get('action') or '').strip()
+ target_task_no = str(body.get('target_task_no') or '').strip() or None
+ reason = str(body.get('reason') or '').strip() or None
+ from app.services.shipping_notice.intake_service import resolve_intake_duplicate
+
+ return _ok(
+ resolve_intake_duplicate(
+ user_id=user.id,
+ intake_no=intake_no,
+ action=action,
+ target_task_no=target_task_no,
+ reason=reason,
+ actor=user,
+ )
+ )
+
+
+@workspace_shipping_notice_bp.route(
+ '/shipping-notice/intakes//duplicate-refresh',
+ methods=['POST'],
+)
+def workspace_refresh_shipping_notice_duplicate(intake_no: str):
+ """重新执行重复检测。"""
+ user = _require_user()
+ from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
+
+ return _ok(refresh_intake_duplicate_detection(user_id=user.id, intake_no=intake_no))
+
+
+@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
+def workspace_create_shipping_batch_from_intakes():
+ """从已解析接入记录确认建批。"""
+ user = _require_user()
+ body = request.get_json(silent=True) or {}
+ intake_nos = body.get('intake_nos')
+ if not isinstance(intake_nos, list) or not intake_nos:
+ raise ValidationError('intake_nos is required')
+ conversation_id = str(body.get('conversation_id') or '').strip() or None
+ from app.services.shipping_notice.batch_create_idempotency import (
+ normalize_create_idempotency_key,
+ warn_missing_create_idempotency_key,
+ )
+ from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
+
+ idempotency_key = normalize_create_idempotency_key(
+ request.headers.get('Idempotency-Key') or body.get('idempotency_key')
+ )
+ if not idempotency_key:
+ warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes')
+ result = create_shipping_batch_from_intakes(
+ user_id=user.id,
+ conversation_id=conversation_id,
+ intake_nos=[str(item) for item in intake_nos],
+ create_idempotency_key=idempotency_key,
+ )
+ return _ok(result)
+
+
@workspace_shipping_notice_bp.route('/shipping-batches//retry-pending', methods=['POST'])
def workspace_retry_shipping_batch_pending(batch_no: str):
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py
index fd948a06..65d966c9 100644
--- a/backend/app/core/config/settings.py
+++ b/backend/app/core/config/settings.py
@@ -119,9 +119,12 @@ class Config:
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
- # HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
+ # HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
+ # HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠,应为域名)
+ HXOPS_PUBLIC_BASE_URL = os.getenv('HXOPS_PUBLIC_BASE_URL')
+
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
@@ -158,6 +161,41 @@ class Config:
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
)
+ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
+ os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
+ )
+ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = (
+ os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
+ )
+ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
+ os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
+ in {'1', 'true', 'yes', 'on'}
+ if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
+ else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
+ )
+ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
+ os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
+ )
+ SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip()
+ SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = (
+ os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
+ or '.hxops_rpa_shared_mount'
+ )
+ SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
+ os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'true').lower() == 'true'
+ )
+ SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
+ os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
+ )
+ SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv(
+ 'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', ''
+ ).strip()
+ SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
+ os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
+ )
+ SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
+ os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
+ )
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
@@ -206,6 +244,9 @@ class Config:
FREIGHT_RPA_BROWSER_PROFILE_DIR = _data_path(
"FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile"
)
+ FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _data_path(
+ "FREIGHT_RPA_INVENTORY_ARCHIVE_DIR", "shipping_notice", "freight_rpa", "inventory_archives"
+ )
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
)
@@ -302,6 +343,7 @@ class Config:
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip()
+ FIXED_ASSET_HISTORY_LOCAL_ROOT = os.getenv('FIXED_ASSET_HISTORY_LOCAL_ROOT', '').strip()
FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip()
FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '')
FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20')
@@ -326,6 +368,31 @@ class Config:
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
+ MINIO_FILE_ASSETS_BUCKET = os.getenv('MINIO_FILE_ASSETS_BUCKET', 'hxops-file-assets')
+ FILE_ASSET_MAX_SIZE_MB = int(os.getenv('FILE_ASSET_MAX_SIZE_MB', '30'))
+ FILE_ASSET_TEMP_TTL_HOURS = int(os.getenv('FILE_ASSET_TEMP_TTL_HOURS', '72'))
+ FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS = int(os.getenv('FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS', '300'))
+ SHIPPING_NOTICE_INTAKE_TTL_HOURS = int(os.getenv('SHIPPING_NOTICE_INTAKE_TTL_HOURS', '72'))
+ SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', '3'))
+ SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
+ os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
+ )
+ SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
+ # EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本)
+ # parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
+ # parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
+ SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20'))
+ SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int(
+ os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024))
+ )
+ SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES = int(
+ os.getenv('SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES', str(50 * 1024 * 1024))
+ )
+ SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH = int(os.getenv('SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH', '3'))
+ # EML 全部附件 extracted_text 写入 structured_result_json 的合计字符上限
+ SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS = int(
+ os.getenv('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS', str(500_000))
+ )
class DevelopmentConfig(Config):
@@ -346,6 +413,9 @@ class TestingConfig(Config):
SCHEDULE_WORKER_ENABLED = False
FIXED_ASSETS_SYNC_ENABLED = False
FIXED_ASSETS_EXPORT_TO_DOCS = False
+ ENV_NAME = 'dev'
+ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
+ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
config = {
diff --git a/backend/app/core/errors.py b/backend/app/core/errors.py
index af5b7492..b4c38d2c 100644
--- a/backend/app/core/errors.py
+++ b/backend/app/core/errors.py
@@ -22,9 +22,15 @@ class AppError(Exception):
class ValidationError(AppError):
- def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None):
+ def __init__(
+ self,
+ message: str = "Invalid request parameters",
+ *,
+ code: str = "VALIDATION.INVALID_PARAM",
+ details: dict[str, Any] | None = None,
+ ):
super().__init__(
- code="VALIDATION.INVALID_PARAM",
+ code=code,
message=message,
http_status=400,
details=details or {},
@@ -38,13 +44,23 @@ class UnauthorizedError(AppError):
class ForbiddenError(AppError):
- def __init__(self, message: str = "Forbidden"):
- super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False)
+ def __init__(
+ self,
+ message: str = "Forbidden",
+ *,
+ code: str = "AUTH.FORBIDDEN",
+ ):
+ super().__init__(code=code, message=message, http_status=403, retryable=False)
class NotFoundError(AppError):
- def __init__(self, message: str = "Resource not found"):
- super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False)
+ def __init__(
+ self,
+ message: str = "Resource not found",
+ *,
+ code: str = "RESOURCE.NOT_FOUND",
+ ):
+ super().__init__(code=code, message=message, http_status=404, retryable=False)
class ConflictError(AppError):
@@ -65,8 +81,14 @@ class ConflictError(AppError):
class ServiceUnavailableError(AppError):
- def __init__(self, message: str = "Service unavailable", *, code: str = "SYSTEM.SERVICE_UNAVAILABLE"):
- super().__init__(code=code, message=message, http_status=503, retryable=True)
+ def __init__(
+ self,
+ message: str = "Service unavailable",
+ *,
+ code: str = "SYSTEM.SERVICE_UNAVAILABLE",
+ details: dict[str, Any] | None = None,
+ ):
+ super().__init__(code=code, message=message, http_status=503, details=details or {}, retryable=True)
class AgentHandlerNotConfiguredError(AppError):
diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py
index ce31fd52..897e77b5 100644
--- a/backend/app/jobs/handlers/__init__.py
+++ b/backend/app/jobs/handlers/__init__.py
@@ -5,4 +5,4 @@ backend/app/jobs/handlers/__init__.py
逻辑:Wave 2 起在 worker 启动前 import 本包。
"""
-from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_run, wecom_directory_sync # noqa: F401
+from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, wecom_directory_sync # noqa: F401
diff --git a/backend/app/jobs/handlers/shipping_notice_parse.py b/backend/app/jobs/handlers/shipping_notice_parse.py
new file mode 100644
index 00000000..5993b517
--- /dev/null
+++ b/backend/app/jobs/handlers/shipping_notice_parse.py
@@ -0,0 +1,276 @@
+"""
+backend/app/jobs/handlers/shipping_notice_parse.py
+
+用途:发货通知接入记录异步预解析 handler。
+依赖:jobs.context、jobs.registry、intake_parse_workflow、queue.fail/finish。
+逻辑:领取时写入 parse_lease="{job_id}:{attempts}";写回/失败清理均校验 lease;
+ Job 收口一律 finish_job/fail_job(owned_attempt=...) 条件 UPDATE,
+ 禁止依赖 Session 身份映射判断执行权。
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import and_, or_, update
+
+from app import db
+from app.core.errors import AppError, NotFoundError
+from app.jobs.context import JobContext
+from app.jobs.queue import fail_job, finish_job
+from app.jobs.registry import register_handler
+from app.jobs.types import JobType
+from app.models import FileAsset, Job, ShippingNoticeIntake
+from app.services.shipping_notice.intake_parse_workflow import (
+ fail_intake_with_stage2_cleanup,
+ run_intake_parse,
+)
+
+# 真终态:无论 Job 身份都不再领取
+_TERMINAL_SKIP_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'})
+# 正常可领取进入 parsing
+_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parse_failed'})
+
+
+def _load_asset(asset_id: int) -> FileAsset:
+ """
+ 加载父级 FileAsset;软删或不存在则抛 NotFoundError。
+
+ Args:
+ asset_id: FileAsset 主键。
+
+ Returns:
+ 可用的 FileAsset。
+
+ Raises:
+ NotFoundError: 资产不存在或已软删。
+ """
+ asset = db.session.get(FileAsset, asset_id)
+ if not asset or asset.deleted_at is not None:
+ raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
+ return asset
+
+
+def _build_parse_lease(*, job_id: int | None, owned_attempt: int | None) -> str:
+ """
+ 构造本轮解析执行代次 token。
+
+ 核心逻辑:有 Job 时使用 "{job_id}:{attempts}",与 claim_next_job 递增的 attempts 对齐;
+ 无 Job(单测直调)时使用随机 UUID。
+ """
+ if job_id is not None and owned_attempt is not None:
+ return f'{int(job_id)}:{int(owned_attempt)}'
+ return uuid.uuid4().hex
+
+
+def _claim_intake_for_parsing(
+ intake_no: str,
+ *,
+ job_id: int | None,
+ owned_attempt: int | None,
+) -> tuple[ShippingNoticeIntake, str] | None:
+ """
+ 原子领取 Intake 并轮转 parse_lease。
+
+ 核心逻辑:仅 created/queued/parse_failed,或 parsing 且 parse_job_id 精确等于当前 Job
+ (回收漏同步时由新 attempts 轮转 lease,旧 lease 立即失效)。
+
+ Returns:
+ (Intake, lease) 或 None。
+ """
+ now = datetime.utcnow()
+ lease = _build_parse_lease(job_id=job_id, owned_attempt=owned_attempt)
+ claim_predicate = ShippingNoticeIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
+ if job_id is not None:
+ claim_predicate = or_(
+ claim_predicate,
+ and_(
+ ShippingNoticeIntake.parse_status == 'parsing',
+ ShippingNoticeIntake.parse_job_id == int(job_id),
+ ),
+ )
+ values: dict = {
+ 'parse_status': 'parsing',
+ 'parse_lease': lease,
+ 'updated_at': now,
+ }
+ if job_id is not None:
+ values['parse_job_id'] = int(job_id)
+ stmt = (
+ update(ShippingNoticeIntake)
+ .where(
+ ShippingNoticeIntake.intake_no == intake_no,
+ claim_predicate,
+ )
+ .values(**values)
+ )
+ result = db.session.execute(stmt)
+ if int(result.rowcount or 0) != 1:
+ db.session.rollback()
+ return None
+ db.session.commit()
+ intake = (
+ db.session.query(ShippingNoticeIntake)
+ .filter_by(intake_no=intake_no)
+ .first()
+ )
+ if intake is None:
+ return None
+ return intake, lease
+
+
+def _is_retryable_exc(exc: BaseException) -> bool:
+ """业务 NotFound / AppError.retryable=False 视为不可再排队。"""
+ if isinstance(exc, NotFoundError):
+ return False
+ if isinstance(exc, AppError):
+ return bool(getattr(exc, 'retryable', False))
+ return True
+
+
+@register_handler(JobType.SHIPPING_NOTICE_PARSE)
+def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
+ """
+ 消费发货通知预解析任务。
+
+ Args:
+ ctx: Worker 上下文。
+ payload: 须含 job_id 或 intake_no。
+ """
+ raw_job_id = payload.get('job_id')
+ job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
+ job_id = int(job.id) if job is not None else None
+ # claim_next_job 已递增 attempts;该值即本轮执行代次(收口必须带入条件 UPDATE)
+ owned_attempt = int(job.attempts or 0) if job is not None else None
+ intake_no = str(
+ (job.payload_json or {}).get('intake_no') if job else payload.get('intake_no') or ''
+ ).strip().upper()
+ if not intake_no:
+ if job_id is not None:
+ fail_job(
+ job_id,
+ error='missing intake_no',
+ retryable=False,
+ owned_attempt=owned_attempt,
+ )
+ return
+
+ intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
+ if not intake:
+ if job_id is not None:
+ fail_job(
+ job_id,
+ error=f'intake not found: {intake_no}',
+ retryable=False,
+ owned_attempt=owned_attempt,
+ )
+ return
+
+ # [STEP 1] 真终态跳过
+ if intake.parse_status in _TERMINAL_SKIP_STATUSES:
+ if job_id is not None:
+ finish_job(
+ job_id,
+ result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True},
+ owned_attempt=owned_attempt,
+ )
+ return
+
+ # [STEP 1b] parsing 但非本 Job:另一 worker 持有 → 跳过
+ if (
+ intake.parse_status == 'parsing'
+ and job_id is not None
+ and (
+ intake.parse_job_id is None
+ or int(intake.parse_job_id) != int(job_id)
+ )
+ ):
+ finish_job(
+ job_id,
+ result={'status': 'parsing', 'intake_no': intake_no, 'skipped': True},
+ owned_attempt=owned_attempt,
+ )
+ return
+
+ # [STEP 2] 原子领取并轮转 lease
+ claimed = _claim_intake_for_parsing(
+ intake_no, job_id=job_id, owned_attempt=owned_attempt
+ )
+ if claimed is None:
+ current = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
+ if job_id is not None:
+ finish_job(
+ job_id,
+ result={
+ 'status': str(getattr(current, 'parse_status', None) or 'unknown'),
+ 'intake_no': intake_no,
+ 'skipped': True,
+ },
+ owned_attempt=owned_attempt,
+ )
+ return
+
+ intake, parse_lease = claimed
+ intake_id = int(intake.id)
+ preserved_parser = str(intake.parser_version or 'v6')
+ preserved_text = intake.extracted_text
+ preserved_structured = (
+ dict(intake.structured_result_json)
+ if isinstance(intake.structured_result_json, dict)
+ else {}
+ )
+ preserved_warnings = list(intake.parse_warnings_json or [])
+
+ try:
+ asset = _load_asset(intake.asset_id)
+ result = run_intake_parse(intake, asset, parse_lease=parse_lease)
+ if job_id is None:
+ return
+ status = str(result.get('status') or '')
+ if status in {'parsed', 'skipped'}:
+ finish_job(
+ job_id,
+ result=result,
+ message=(
+ '发货通知预解析完成'
+ if status == 'parsed'
+ else '接入已取消、过期或执行代次失效,跳过'
+ ),
+ owned_attempt=owned_attempt,
+ )
+ else:
+ fail_job(
+ job_id,
+ error=str(result.get('error_message') or 'parse failed'),
+ retryable=False,
+ owned_attempt=owned_attempt,
+ )
+ except Exception as exc:
+ db.session.rollback()
+ error_code = getattr(exc, 'code', None) or 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
+ fail_result = fail_intake_with_stage2_cleanup(
+ intake_id=intake_id,
+ intake_no=intake_no,
+ parser_version=preserved_parser,
+ error_code=str(error_code),
+ error_message=str(exc)[:1000],
+ extracted_text=preserved_text,
+ structured_result_json=preserved_structured,
+ parse_warnings_json=preserved_warnings,
+ allowed_statuses=frozenset({'parsing', 'queued', 'created'}),
+ required_lease=parse_lease,
+ )
+ # 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回)
+ if str(fail_result.get('reason') or '') == 'stale_parse_lease':
+ return
+ retryable = _is_retryable_exc(exc)
+ if job_id is not None:
+ fail_job(
+ job_id,
+ error=str(exc),
+ retryable=retryable,
+ owned_attempt=owned_attempt,
+ )
+ if retryable:
+ raise
diff --git a/backend/app/jobs/queue.py b/backend/app/jobs/queue.py
index e14b7e1a..3db86f52 100644
--- a/backend/app/jobs/queue.py
+++ b/backend/app/jobs/queue.py
@@ -2,17 +2,25 @@
backend/app/jobs/queue.py
用途:通用后台任务入队、领取与完成状态管理,并保留旧 KB 入队兼容入口。
-依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层。
-逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环。
+依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层;
+ shipping_notice Intake 仅在预解析 Job 被 queued 同伴取代时同事务重指 parse_job_id。
+逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环;
+ recover 使用 FOR UPDATE SKIP LOCKED + 条件 UPDATE;finish/fail 以 status/attempts 条件 UPDATE;
+ enqueue 仅在 SAVEPOINT 内 add+flush,唯一冲突回落已有 Job;
+ running→queued 若撞 shipping_notice_parse queued 唯一索引则标 cancelled;
+ 替代 Job 须 FOR UPDATE;仅 queued 或已真正持有 Intake lease 的 running 可 supersede。
"""
from __future__ import annotations
import socket
from datetime import datetime, timedelta
+from collections.abc import Callable, Sequence
from typing import Any
from flask import current_app
-from sqlalchemy.exc import OperationalError
+from sqlalchemy import update
+from sqlalchemy.exc import IntegrityError, OperationalError
+from sqlalchemy.orm import Session
from app import db
from app.core.errors import ValidationError
@@ -20,7 +28,43 @@ from app.jobs.types import JobType
from app.models import Job
ACTIVE_STATUSES = ("queued", "running")
+QUEUED_ONLY_STATUSES = ("queued",)
TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled")
+# 与 models.Job.uq_jobs_shipping_parse_queued_ref 对齐
+_PARSE_QUEUED_UNIQUE_TYPE = JobType.SHIPPING_NOTICE_PARSE.value
+
+
+def _orm_session() -> Session:
+ """
+ 取得底层 Session。
+
+ scoped_session 代理不转发 in_transaction/get_transaction,须解包后使用。
+ """
+ return db.session()
+
+
+def _ensure_outer_dbapi_transaction(session: Session) -> None:
+ """
+ 确保 begin_nested() 不会成为数据库最外层事务。
+
+ 核心逻辑:SQLite 在尚未 BEGIN 时执行 SAVEPOINT,随后 RELEASE 等价于 COMMIT,
+ 会破坏 commit=False / 外层 rollback。先 materialize 连接事务;SQLite 必要时
+ 显式 DBAPI BEGIN(已在事务中则忽略)。
+ """
+ if not session.in_transaction():
+ session.begin()
+ bind = session.connection()
+ if str(bind.dialect.name or "") != "sqlite":
+ return
+ dbapi_conn = bind.connection.dbapi_connection
+ in_txn = getattr(dbapi_conn, "in_transaction", None)
+ if callable(in_txn) and in_txn():
+ return
+ try:
+ dbapi_conn.execute("BEGIN")
+ except Exception:
+ # 已在事务中:sqlite 会报错,可安全忽略
+ pass
def _normalize_job_type(job_type: JobType | str) -> str:
@@ -28,6 +72,242 @@ def _normalize_job_type(job_type: JobType | str) -> str:
return str(getattr(job_type, "value", job_type) or "").strip()
+def _subject_to_parse_queued_unique(job_type: str | None) -> bool:
+ """是否受 shipping_notice_parse queued 部分唯一索引约束。"""
+ return str(job_type or "").strip() == _PARSE_QUEUED_UNIQUE_TYPE
+
+
+def _lock_other_active_parse_job(
+ *,
+ domain: str,
+ job_type: str,
+ business_ref: str | None,
+ exclude_id: int,
+) -> Job | None:
+ """
+ FOR UPDATE 锁定同业务锚点下优先级最高的 queued/running 预解析 Job。
+
+ 核心逻辑:queued 受部分唯一索引保护且天然可安全替代,因此必须优先于
+ running;仅无 queued 时才按最小 id 选择 running,并交由
+ `_is_safe_supersede_target` 校验精确 Intake lease。持锁期间 Worker 的
+ claim(SKIP LOCKED)会跳过最终候选。
+
+ Args:
+ domain / job_type / business_ref: 与待降级 Job 相同的锚点。
+ exclude_id: 排除自身主键。
+
+ Returns:
+ 锁定的最高优先级同伴;没有则 None。
+ """
+ ref = str(business_ref or "").strip() or None
+ if not ref:
+ return None
+ return (
+ db.session.query(Job)
+ .filter(
+ Job.domain == str(domain),
+ Job.job_type == str(job_type),
+ Job.business_ref == ref,
+ Job.status.in_(("queued", "running")),
+ Job.id != int(exclude_id),
+ )
+ .order_by((Job.status == "queued").desc(), Job.id.asc())
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+
+
+def _parse_lease_for_job(job: Job) -> str:
+ """构造 `{job_id}:{attempts}` 执行代次 lease。"""
+ return f"{int(job.id)}:{int(job.attempts or 0)}"
+
+
+def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
+ """
+ 判定锁定的同伴是否可安全取代旧 running Job。
+
+ 核心逻辑:
+ - queued:可 supersede(旧取消,Intake 回到排队挂 keep);
+ - running:仅当 Intake 已明确持有该 Job 的精确 parse_job_id + parse_lease
+ (Worker 已真正 claim Intake)。否则可能 Worker 已按旧 id 决定 skip+finish,
+ 若此时伪造 lease 会导致 Intake 永久 parsing。
+
+ Returns:
+ True 表示可取消旧 Job 并重指;False 表示应让旧 Job 正常 requeue。
+ """
+ db.session.refresh(sibling)
+ status = str(sibling.status or "")
+ if status == "queued":
+ return True
+ if status != "running":
+ return False
+
+ from app.models import ShippingNoticeIntake
+
+ intake_no = str(
+ (cancelled_job.payload_json or {}).get("intake_no")
+ or cancelled_job.business_ref
+ or sibling.business_ref
+ or ""
+ ).strip().upper()
+ if not intake_no:
+ return False
+ locked = (
+ db.session.query(ShippingNoticeIntake)
+ .filter(ShippingNoticeIntake.intake_no == intake_no)
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+ if locked is None:
+ return False
+ expected_lease = _parse_lease_for_job(sibling)
+ return (
+ str(locked.parse_status or "") == "parsing"
+ and locked.parse_job_id is not None
+ and int(locked.parse_job_id) == int(sibling.id)
+ and str(locked.parse_lease or "") == expected_lease
+ )
+
+
+def _resolve_safe_supersede_sibling(
+ *,
+ domain: str,
+ job_type: str,
+ business_ref: str | None,
+ exclude_id: int,
+ cancelled_job: Job,
+) -> Job | None:
+ """
+ 锁定同伴并过滤为可安全 supersede 的目标;不安全则视为无替代者。
+ """
+ sibling = _lock_other_active_parse_job(
+ domain=domain,
+ job_type=job_type,
+ business_ref=business_ref,
+ exclude_id=exclude_id,
+ )
+ if sibling is None:
+ return None
+ if not _is_safe_supersede_target(sibling, cancelled_job=cancelled_job):
+ return None
+ return sibling
+
+
+def _retarget_intake_parse_job_after_supersede(
+ *,
+ cancelled_job: Job,
+ keep_job: Job,
+) -> None:
+ """
+ 旧 running 预解析 Job 被安全同伴取代时,同事务重指 Intake.parse_job_id。
+
+ 核心逻辑:FOR UPDATE Intake 后复检 keep_job.status——
+ keep 仍为 queued:parsing→queued 并清 parse_lease;
+ keep 已 running:仅在 Intake 已持有其精确 lease 时保留状态,绝不伪造 lease
+ (否则会踩到已决定 skip+finish 的 Worker,造成永久 parsing)。
+ """
+ if not _subject_to_parse_queued_unique(str(cancelled_job.job_type or "")):
+ return
+ from app.models import ShippingNoticeIntake
+
+ intake_no = str(
+ (cancelled_job.payload_json or {}).get("intake_no")
+ or cancelled_job.business_ref
+ or ""
+ ).strip().upper()
+ if not intake_no:
+ return
+
+ # 锁内复检同伴状态(调用方应已 FOR UPDATE keep_job)
+ db.session.refresh(keep_job)
+ keep_status = str(keep_job.status or "")
+ if keep_status not in {"queued", "running"}:
+ return
+
+ locked = (
+ db.session.query(ShippingNoticeIntake)
+ .filter(ShippingNoticeIntake.intake_no == intake_no)
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+ if locked is None:
+ return
+ current_job_id = int(locked.parse_job_id) if locked.parse_job_id is not None else None
+ cancelled_id = int(cancelled_job.id)
+ keep_id = int(keep_job.id)
+ # 已指向第三方 Job:不抢占
+ if current_job_id is not None and current_job_id not in {cancelled_id, keep_id}:
+ return
+ now = datetime.utcnow()
+ current_lease = str(locked.parse_lease or "") or None
+ status_now = str(locked.parse_status or "")
+
+ if keep_status == "queued":
+ if current_job_id in {cancelled_id, None}:
+ locked.parse_job_id = keep_id
+ # 仅当仍挂旧 Job/旧代次时才打回 queued,避免清掉 keep 新 Worker 的 lease
+ if status_now == "parsing" and (
+ current_job_id == cancelled_id
+ or current_lease is None
+ or str(current_lease).startswith(f"{cancelled_id}:")
+ ):
+ locked.parse_status = "queued"
+ locked.parse_lease = None
+ locked.updated_at = now
+ return
+
+ # keep 已 running:只保留已真正接管的状态,禁止伪造 lease 转移
+ keep_lease = _parse_lease_for_job(keep_job)
+ if (
+ status_now == "parsing"
+ and current_job_id == keep_id
+ and current_lease == keep_lease
+ ):
+ locked.updated_at = now
+ return
+ # 未真正接管:调用方本不应 supersede;此处 no-op 防误伤
+ return
+
+
+def _cancel_running_job_superseded(
+ *,
+ job_id: int,
+ now: datetime,
+ message: str,
+ owned_attempt: int | None = None,
+ snap_attempts: int | None = None,
+) -> int:
+ """
+ 将仍为 running 的 Job 标为 cancelled(已被新 queued 取代)。
+
+ Returns:
+ 条件 UPDATE 影响行数。
+ """
+ where = [Job.id == int(job_id), Job.status == "running"]
+ if owned_attempt is not None:
+ where.append(Job.attempts == int(owned_attempt))
+ elif snap_attempts is not None:
+ where.append(Job.attempts == int(snap_attempts))
+ stmt = (
+ update(Job)
+ .where(*where)
+ .values(
+ status="cancelled",
+ progress=100,
+ message=str(message or "已被新的 queued Job 取代")[:500],
+ locked_by=None,
+ locked_at=None,
+ started_at=None,
+ finished_at=now,
+ updated_at=now,
+ )
+ )
+ return int(db.session.execute(stmt).rowcount or 0)
+
+
def _worker_id() -> str:
"""生成当前 worker 标识,用于锁记录和排障。"""
try:
@@ -103,12 +383,19 @@ def enqueue(
max_attempts: int = 3,
message: str | None = None,
dedupe_active: bool = True,
+ dedupe_statuses: Sequence[str] | None = None,
+ commit: bool = True,
correlation_id: str | None = None,
scheduled_at: Any = None,
) -> int:
"""
将任务写入通用 jobs 队列并返回 job id。
+ 核心逻辑:先按 domain/type/business_ref + dedupe_statuses 查复用;
+ 无则 SAVEPOINT 插入。撞上 shipping_notice_parse 的 queued 部分唯一索引时
+ IntegrityError 回读已有 Job(并发双插幂等)。commit=False 时不开自动提交,
+ 由调用方与业务行同事务提交。
+
Args:
job_type: 任务类型。
payload: JSON payload。
@@ -118,7 +405,10 @@ def enqueue(
priority: 优先级,数值越大越先执行。
max_attempts: 最大尝试次数。
message: 初始状态说明。
- dedupe_active: 是否复用 active 状态的同业务任务。
+ dedupe_active: 是否复用同业务键下指定状态中的任务。
+ dedupe_statuses: 去重匹配的 Job.status 集合;默认 queued+running。
+ 重试场景应传仅 queued,避免复用即将结束的 running Job。
+ commit: False 时仅 flush,由调用方与业务行同一事务提交。
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
"""
@@ -139,20 +429,26 @@ def enqueue(
if not isinstance(payload, dict):
raise ValueError("payload must be a dict")
- if dedupe_active and normalized_ref:
- existing = (
+ statuses = tuple(dedupe_statuses) if dedupe_statuses is not None else ACTIVE_STATUSES
+
+ def _find_active_dedupe_job() -> Job | None:
+ if not (dedupe_active and normalized_ref and statuses):
+ return None
+ return (
db.session.query(Job)
.filter(
Job.domain == normalized_domain,
Job.job_type == normalized_type,
Job.business_ref == normalized_ref,
- Job.status.in_(ACTIVE_STATUSES),
+ Job.status.in_(statuses),
)
.order_by(Job.created_at.desc(), Job.id.desc())
.first()
)
- if existing:
- return int(existing.id)
+
+ existing = _find_active_dedupe_job()
+ if existing is not None:
+ return int(existing.id)
now = datetime.utcnow()
queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now
@@ -171,50 +467,207 @@ def enqueue(
created_at=queue_at,
updated_at=now,
)
- db.session.add(job)
- db.session.commit()
+ # [STEP] SAVEPOINT 边界:仅在 begin_nested 内 add+flush。
+ # begin_nested 会先 autoflush pending;若 Job 提前进入 Session,冲突会落在 SAVEPOINT 之外,
+ # 毒化外层事务并在异常分支触发 PendingRollbackError。
+ session = _orm_session()
+ _ensure_outer_dbapi_transaction(session)
+ try:
+ with session.begin_nested():
+ session.add(job)
+ session.flush()
+ except IntegrityError:
+ # SAVEPOINT 已回滚;确保失败对象不残留为 pending
+ try:
+ session.expunge(job)
+ except Exception:
+ pass
+ # 即使 dedupe_active=False,唯一冲突仍须回落已有 queued(索引层幂等)
+ raced = _find_active_dedupe_job()
+ if raced is None and normalized_ref:
+ raced = (
+ db.session.query(Job)
+ .filter(
+ Job.domain == normalized_domain,
+ Job.job_type == normalized_type,
+ Job.business_ref == normalized_ref,
+ Job.status == "queued",
+ )
+ .order_by(Job.id.asc())
+ .first()
+ )
+ if raced is not None:
+ return int(raced.id)
+ raise
+ if commit:
+ session.commit()
return int(job.id)
-def recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int:
- """回收指定业务域内超时 running 的通用任务。"""
+def _job_id(job: Job | int) -> int:
+ """统一解析 Job 主键。"""
+ return int(job if isinstance(job, int) else job.id)
+
+
+def recover_stale_jobs(
+ *,
+ domain: str,
+ timeout_seconds: float,
+ job_type: str | JobType | None = None,
+ on_recovered: Callable[[Job], None] | None = None,
+) -> int:
+ """
+ 回收指定业务域内超时 running 的通用任务。
+
+ 核心逻辑:FOR UPDATE SKIP LOCKED 领取待回收行,再以
+ status=running AND attempts=快照 条件 UPDATE;同事务回调 on_recovered。
+ 多 Worker 并发回收时不会双写同一 Job,也不会把已被新 Worker 领取的代次打回 queued。
+ 若已存在同锚点 queued 同伴(parse 唯一索引),旧 Job 标 cancelled 并重指 Intake,
+ 每条更新包在 SAVEPOINT 内,避免单行 IntegrityError 毒化整批回收。
+
+ Args:
+ on_recovered: 每条 Job 条件更新成功后、统一 commit 前的回调。
+ """
cutoff = datetime.utcnow() - timedelta(seconds=float(timeout_seconds))
- query = (
- db.session.query(Job)
- .filter(
- Job.domain == domain,
- Job.status == "running",
- Job.started_at.isnot(None),
- Job.started_at < cutoff,
- )
+ query = db.session.query(Job).filter(
+ Job.domain == domain,
+ Job.status == "running",
+ Job.started_at.isnot(None),
+ Job.started_at < cutoff,
)
normalized_type = _normalize_job_type(job_type) if job_type else ""
if normalized_type:
query = query.filter(Job.job_type == normalized_type)
- stale_jobs = query.order_by(Job.started_at.asc(), Job.id.asc()).all()
+
+ try:
+ stale_jobs = (
+ query.order_by(Job.started_at.asc(), Job.id.asc())
+ .with_for_update(skip_locked=True)
+ .all()
+ )
+ except OperationalError:
+ db.session.rollback()
+ raise
+
if not stale_jobs:
+ db.session.rollback()
return 0
+ session = _orm_session()
+ _ensure_outer_dbapi_transaction(session)
now = datetime.utcnow()
+ recovered = 0
for job in stale_jobs:
- if int(job.attempts or 0) < int(job.max_attempts or 1):
- job.status = "queued"
- job.message = "任务执行超时,已回收等待重试"
- job.locked_by = None
- job.locked_at = None
- job.started_at = None
- job.updated_at = now
+ # 锁内复检:可能已被他事务终态化(本连接持锁期间一般仍为 running)
+ if str(job.status or "") != "running":
continue
- job.status = "failed"
- job.error_message = f"任务执行超时(超过 {int(timeout_seconds)}s)"
- job.message = job.error_message
- job.progress = 100
- job.locked_by = None
- job.locked_at = None
- job.finished_at = now
- job.updated_at = now
+ if job.started_at is None or job.started_at >= cutoff:
+ continue
+ snap_attempts = int(job.attempts or 0)
+ max_attempts = int(job.max_attempts or 1)
+ job_id = int(job.id)
+ sibling: Job | None = None
+ rowcount = 0
+
+ if snap_attempts < max_attempts:
+ if _subject_to_parse_queued_unique(str(job.job_type or "")):
+ try:
+ sibling = _resolve_safe_supersede_sibling(
+ domain=str(job.domain),
+ job_type=str(job.job_type),
+ business_ref=job.business_ref,
+ exclude_id=job_id,
+ cancelled_job=job,
+ )
+ except OperationalError:
+ # 死锁会使整个事务失败;回滚后由下一轮回收重试
+ db.session.rollback()
+ return 0
+ # [STEP] SAVEPOINT:queued 唯一冲突不得毁掉整批外层事务
+ try:
+ with session.begin_nested():
+ if sibling is not None:
+ rowcount = _cancel_running_job_superseded(
+ job_id=job_id,
+ now=now,
+ message="超时回收:已存在安全替代解析 Job,旧 Job 已取消",
+ snap_attempts=snap_attempts,
+ )
+ else:
+ result = db.session.execute(
+ update(Job)
+ .where(
+ Job.id == job_id,
+ Job.status == "running",
+ Job.attempts == snap_attempts,
+ )
+ .values(
+ status="queued",
+ message="任务执行超时,已回收等待重试",
+ locked_by=None,
+ locked_at=None,
+ started_at=None,
+ updated_at=now,
+ )
+ )
+ rowcount = int(result.rowcount or 0)
+ except IntegrityError:
+ try:
+ sibling = _resolve_safe_supersede_sibling(
+ domain=str(job.domain),
+ job_type=str(job.job_type),
+ business_ref=job.business_ref,
+ exclude_id=job_id,
+ cancelled_job=job,
+ )
+ except OperationalError:
+ db.session.rollback()
+ return 0
+ if sibling is None:
+ continue
+ with session.begin_nested():
+ rowcount = _cancel_running_job_superseded(
+ job_id=job_id,
+ now=now,
+ message="超时回收:queued 唯一冲突,旧 Job 已取消",
+ snap_attempts=snap_attempts,
+ )
+ else:
+ timeout_msg = f"任务执行超时(超过 {int(timeout_seconds)}s)"
+ result = db.session.execute(
+ update(Job)
+ .where(
+ Job.id == job_id,
+ Job.status == "running",
+ Job.attempts == snap_attempts,
+ )
+ .values(
+ status="failed",
+ error_message=timeout_msg,
+ message=timeout_msg,
+ progress=100,
+ locked_by=None,
+ locked_at=None,
+ finished_at=now,
+ updated_at=now,
+ )
+ )
+ rowcount = int(result.rowcount or 0)
+
+ if rowcount != 1:
+ continue
+ db.session.expire(job)
+ db.session.refresh(job)
+ if str(job.status or "") == "cancelled" and sibling is not None:
+ _retarget_intake_parse_job_after_supersede(
+ cancelled_job=job,
+ keep_job=sibling,
+ )
+ if on_recovered is not None:
+ on_recovered(job)
+ recovered += 1
db.session.commit()
- return len(stale_jobs)
+ return recovered
def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
@@ -243,7 +696,8 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None,
return None
job.status = "running"
- job.started_at = job.started_at or now
+ # 每次领取刷新 started_at,避免 fail_job requeue 残留旧时间导致立刻被超时回收
+ job.started_at = now
job.locked_at = now
job.locked_by = worker_id or _worker_id()
job.attempts = int(job.attempts or 0) + 1
@@ -254,35 +708,235 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None,
return job
-def finish_job(job: Job, *, result: dict[str, Any] | None = None, message: str | None = None) -> None:
- """标记任务成功完成。"""
- now = datetime.utcnow()
- job.status = "success"
- job.progress = 100
- job.result_json = result or {}
- job.message = message or "任务处理完成"
- job.error_message = None
- job.locked_by = None
- job.locked_at = None
- job.finished_at = now
- job.updated_at = now
- db.session.commit()
+def _sync_parse_intake_after_job_mutation(job_id: int) -> None:
+ """
+ shipping_notice_parse Job 状态变更后同步 Intake(同事务、commit 前)。
+
+ 核心逻辑:委托 sync_intake_after_parse_job_recovery,覆盖 requeue→queued、
+ failed→parse_failed、cancelled→安全重指/终态清理,避免 Intake 永久 parsing。
+ """
+ job = db.session.get(Job, int(job_id))
+ if job is None or not _subject_to_parse_queued_unique(str(job.job_type or "")):
+ return
+ db.session.expire(job)
+ db.session.refresh(job)
+ from app.services.shipping_notice.intake_parse_workflow import (
+ sync_intake_after_parse_job_recovery,
+ )
+
+ sync_intake_after_parse_job_recovery(job)
-def fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None:
- """标记任务失败;retryable 且未达上限时重新排队。"""
+def finish_job(
+ job: Job | int,
+ *,
+ result: dict[str, Any] | None = None,
+ message: str | None = None,
+ owned_attempt: int | None = None,
+) -> bool:
+ """
+ 条件收口为 success:仅当 Job 仍为 running(且可选 attempts 匹配)时生效。
+
+ Returns:
+ 是否实际更新到一行(False 表示代次失效或已非 running,调用方应视为 no-op)。
+ """
now = datetime.utcnow()
- can_retry = retryable and int(job.attempts or 0) < int(job.max_attempts or 1)
- job.status = "queued" if can_retry else "failed"
- job.progress = 0 if can_retry else 100
- job.result_json = result or {}
- job.error_message = str(error or "job failed")[:1000]
- job.message = "任务失败,等待重试" if can_retry else job.error_message
- job.locked_by = None
- job.locked_at = None
- job.finished_at = None if can_retry else now
- job.updated_at = now
+ job_id = _job_id(job)
+ where = [Job.id == job_id, Job.status == "running"]
+ if owned_attempt is not None:
+ where.append(Job.attempts == int(owned_attempt))
+ stmt = (
+ update(Job)
+ .where(*where)
+ .values(
+ status="success",
+ progress=100,
+ result_json=result or {},
+ message=message or "任务处理完成",
+ error_message=None,
+ locked_by=None,
+ locked_at=None,
+ finished_at=now,
+ updated_at=now,
+ )
+ )
+ rowcount = int(db.session.execute(stmt).rowcount or 0)
db.session.commit()
+ cached = db.session.get(Job, job_id)
+ if cached is not None:
+ db.session.expire(cached)
+ return rowcount == 1
+
+
+def fail_job(
+ job: Job | int,
+ *,
+ error: str,
+ result: dict[str, Any] | None = None,
+ retryable: bool = False,
+ owned_attempt: int | None = None,
+) -> bool:
+ """
+ 条件收口失败:仅 running(且可选 attempts 匹配)时改 queued/failed/cancelled。
+
+ 核心逻辑:retryable 且 attempts 未耗尽时,优先安全 supersede,否则 requeue
+ (清空 started_at)并同步 Intake;唯一冲突窗口消失时保持 running 返回 False,
+ 禁止误标 failed。attempts 耗尽则 failed 并同步 Intake 离开 parsing。
+
+ Returns:
+ 是否实际更新到一行。
+ """
+ now = datetime.utcnow()
+ job_id = _job_id(job)
+ error_text = str(error or "job failed")[:1000]
+ payload = result or {}
+ base_where = [Job.id == job_id, Job.status == "running"]
+ if owned_attempt is not None:
+ base_where.append(Job.attempts == int(owned_attempt))
+
+ session = _orm_session()
+ _ensure_outer_dbapi_transaction(session)
+
+ def _expire_cached() -> None:
+ cached = db.session.get(Job, job_id)
+ if cached is not None:
+ db.session.expire(cached)
+
+ if retryable:
+ # 先锁住自身 running 行,再锁同伴,缩短无锁窗口且便于复检 attempts
+ job_row = (
+ db.session.query(Job)
+ .filter(Job.id == job_id, Job.status == "running")
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+ sibling: Job | None = None
+ if job_row is not None and _subject_to_parse_queued_unique(str(job_row.job_type or "")):
+ try:
+ sibling = _resolve_safe_supersede_sibling(
+ domain=str(job_row.domain),
+ job_type=str(job_row.job_type),
+ business_ref=job_row.business_ref,
+ exclude_id=job_id,
+ cancelled_job=job_row,
+ )
+ except OperationalError:
+ db.session.rollback()
+ return False
+
+ attempts_ok = (
+ job_row is not None
+ and int(job_row.attempts or 0) < int(job_row.max_attempts or 1)
+ )
+ if sibling is not None and attempts_ok:
+ # 仅安全替代者:取消旧 Job(running 且已真正接管 Intake,或仍为 queued)
+ rowcount = _cancel_running_job_superseded(
+ job_id=job_id,
+ now=now,
+ message="失败重试:已存在安全替代解析 Job,旧 Job 已取消",
+ owned_attempt=owned_attempt,
+ )
+ if rowcount == 1:
+ cancelled = db.session.get(Job, job_id)
+ if cancelled is not None:
+ _retarget_intake_parse_job_after_supersede(
+ cancelled_job=cancelled,
+ keep_job=sibling,
+ )
+ _sync_parse_intake_after_job_mutation(job_id)
+ db.session.commit()
+ _expire_cached()
+ return True
+ elif sibling is None and attempts_ok:
+ # 无安全替代(含:同伴 running 但尚未 claim Intake)→ 正常 requeue
+ requeue_stmt = (
+ update(Job)
+ .where(*base_where, Job.attempts < Job.max_attempts)
+ .values(
+ status="queued",
+ progress=0,
+ result_json=payload,
+ error_message=error_text,
+ message="任务失败,等待重试",
+ locked_by=None,
+ locked_at=None,
+ started_at=None,
+ finished_at=None,
+ updated_at=now,
+ )
+ )
+ try:
+ with session.begin_nested():
+ rowcount = int(db.session.execute(requeue_stmt).rowcount or 0)
+ except IntegrityError:
+ try:
+ sibling = (
+ _resolve_safe_supersede_sibling(
+ domain=str(job_row.domain),
+ job_type=str(job_row.job_type),
+ business_ref=job_row.business_ref,
+ exclude_id=job_id,
+ cancelled_job=job_row,
+ )
+ if job_row is not None
+ else None
+ )
+ except OperationalError:
+ db.session.rollback()
+ return False
+ if sibling is None:
+ # 唯一冲突窗口已消失:保持 running,勿强行 failed 造成永久 parsing
+ db.session.rollback()
+ return False
+ with session.begin_nested():
+ rowcount = _cancel_running_job_superseded(
+ job_id=job_id,
+ now=now,
+ message="失败重试:queued 唯一冲突,旧 Job 已取消",
+ owned_attempt=owned_attempt,
+ )
+ if rowcount == 1:
+ cancelled = db.session.get(Job, job_id)
+ if cancelled is not None:
+ _retarget_intake_parse_job_after_supersede(
+ cancelled_job=cancelled,
+ keep_job=sibling,
+ )
+ _sync_parse_intake_after_job_mutation(job_id)
+ db.session.commit()
+ _expire_cached()
+ return True
+ else:
+ if rowcount == 1:
+ _sync_parse_intake_after_job_mutation(job_id)
+ db.session.commit()
+ _expire_cached()
+ return True
+
+ # 终态 failed:同步 Intake 离开 parsing,避免永久卡住
+ fail_stmt = (
+ update(Job)
+ .where(*base_where)
+ .values(
+ status="failed",
+ progress=100,
+ result_json=payload,
+ error_message=error_text,
+ message=error_text,
+ locked_by=None,
+ locked_at=None,
+ started_at=None,
+ finished_at=now,
+ updated_at=now,
+ )
+ )
+ rowcount = int(db.session.execute(fail_stmt).rowcount or 0)
+ if rowcount == 1:
+ _sync_parse_intake_after_job_mutation(job_id)
+ db.session.commit()
+ _expire_cached()
+ return rowcount == 1
def process_next_job(
@@ -293,7 +947,12 @@ def process_next_job(
timeout_config_key: str | None = None,
default_timeout_seconds: float = 300,
) -> tuple[bool, str]:
- """领取并分发一条通用任务。"""
+ """
+ 领取并分发一条通用任务。
+
+ 核心逻辑:超时回收必须与本次允许领取的 job_types 同范围,避免同 domain
+ 下其他类型被错误阈值或缺少业务回调的入口提前回收;未指定类型时才回收整个 domain。
+ """
import app.jobs.handlers # noqa: F401
from app.jobs.registry import get_handler
@@ -302,29 +961,54 @@ def process_next_job(
if timeout_config_key
else default_timeout_seconds
)
- recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
+ normalized_types = list(
+ dict.fromkeys(
+ _normalize_job_type(item)
+ for item in (job_types or [])
+ if _normalize_job_type(item)
+ )
+ )
+ if normalized_types:
+ for normalized_type in normalized_types:
+ on_recovered = None
+ if normalized_type == JobType.SHIPPING_NOTICE_PARSE.value:
+ from app.services.shipping_notice.intake_parse_workflow import (
+ sync_intake_after_parse_job_recovery,
+ )
+
+ on_recovered = sync_intake_after_parse_job_recovery
+ recover_stale_jobs(
+ domain=domain,
+ timeout_seconds=timeout_seconds,
+ job_type=normalized_type,
+ on_recovered=on_recovered,
+ )
+ else:
+ recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
job = claim_next_job(domain=domain, job_types=job_types)
if not job:
return False, "no_job"
job_id = int(job.id)
+ owned_attempt = int(job.attempts or 0)
job_type_value = str(job.job_type or "").strip()
payload = dict(job.payload_json or {})
payload.setdefault("job_id", job_id)
handler = get_handler(JobType(job_type_value))
if handler is None:
- fail_job(job, error=f"no handler registered for {job.job_type}")
+ fail_job(
+ job_id,
+ error=f"no handler registered for {job.job_type}",
+ owned_attempt=owned_attempt,
+ )
return True, "missing_handler"
try:
handler(ctx, payload)
- refreshed = db.session.get(Job, job_id)
- if refreshed and refreshed.status == "running":
- finish_job(refreshed, message="任务处理完成")
+ # 条件收口:Handler 已 finish/fail 或代次失效时 rowcount=0,不覆盖
+ finish_job(job_id, message="任务处理完成", owned_attempt=owned_attempt)
return True, job_type_value
except Exception as exc:
db.session.rollback()
- refreshed = db.session.get(Job, job_id)
- if refreshed:
- fail_job(refreshed, error=str(exc), retryable=True)
+ fail_job(job_id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
raise
diff --git a/backend/app/jobs/runner.py b/backend/app/jobs/runner.py
index 00f45aec..5cf994fb 100644
--- a/backend/app/jobs/runner.py
+++ b/backend/app/jobs/runner.py
@@ -43,13 +43,23 @@ def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None)
continue
handler = get_handler(job['job_type'])
+ owned_attempt = job.get('attempts')
+ owned_attempt_int = int(owned_attempt) if owned_attempt is not None else None
if not handler:
ctx.logger.error('No handler for job_type=%s job_id=%s', job.get('job_type'), job.get('id'))
- store.mark_failed(job['id'], message=f'no handler for {job.get("job_type")}')
+ store.mark_failed(
+ job['id'],
+ message=f'no handler for {job.get("job_type")}',
+ owned_attempt=owned_attempt_int,
+ )
continue
try:
handler(ctx, job.get('payload') or {})
except Exception as exc:
ctx.logger.exception('Handler failed job_id=%s', job.get('id'))
- store.mark_failed(job['id'], message=str(exc))
+ store.mark_failed(
+ job['id'],
+ message=str(exc),
+ owned_attempt=owned_attempt_int,
+ )
diff --git a/backend/app/jobs/store.py b/backend/app/jobs/store.py
index bbeeb2fb..5fb59e58 100644
--- a/backend/app/jobs/store.py
+++ b/backend/app/jobs/store.py
@@ -10,7 +10,23 @@ from __future__ import annotations
from typing import Any
from app.jobs.types import QUEUE_KB_JOB_TYPES, JobType, handler_type_for_kb_job
-from app.models import KbJob
+from app.models import Job, KbJob
+
+
+def _normalize_generic_job(job: Job) -> dict[str, Any]:
+ """将通用 Job ORM 实例转为 runner/handler 使用的归一化任务 dict。"""
+ job_type_value = str(job.job_type or '').strip()
+ return {
+ 'id': job.id,
+ 'job_type': JobType(job_type_value),
+ 'raw_job_type': job_type_value,
+ # 领取时代次,供异常收口条件 UPDATE(勿信 Session 缓存)
+ 'attempts': int(job.attempts or 0),
+ 'payload': {
+ 'job_id': job.id,
+ **(job.payload_json or {}),
+ },
+ }
def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
@@ -59,7 +75,7 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
recover_stale_running_jobs()
- if 'shipping_notice_run' in allowed_types:
+ if 'shipping_notice_run' in allowed_types or 'shipping_notice_parse' in allowed_types:
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
recover_stale_shipping_notice_jobs()
@@ -77,30 +93,44 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
job = claim_next_shipping_notice_job()
if job:
- return _normalize_kb_job(job)
+ return _normalize_generic_job(job)
return None
-def mark_failed(job_id: int, *, message: str) -> None:
+def mark_failed(job_id: int, *, message: str, owned_attempt: int | None = None) -> None:
"""
- handler 未捕获异常时,将 KbJob 标记为 failed。
+ handler 未捕获异常时,将任务标记为 failed(KbJob 或通用 Job)。
+
Args:
- job_id: KbJob 主键。
+ job_id: 任务主键。
message: 失败原因(截断至 1000 字符)。
+ owned_attempt: 领取时的 Job.attempts;通用 Job 用条件 UPDATE,避免覆盖新代次。
"""
from datetime import datetime
from app import db
+ from app.jobs.queue import fail_job
- job = db.session.get(KbJob, job_id)
- if not job or job.status != 'running':
+ # 通用 Job 表命中则条件收口(rowcount=0 即代次/状态已变,安全 no-op)
+ generic = db.session.query(Job.id).filter(Job.id == int(job_id)).first()
+ if generic is not None:
+ fail_job(
+ int(job_id),
+ error=message[:1000],
+ retryable=True,
+ owned_attempt=owned_attempt,
+ )
+ return
+
+ kb_job = db.session.get(KbJob, job_id)
+ if not kb_job or kb_job.status != 'running':
return
now = datetime.utcnow()
- job.status = 'failed'
- job.error_message = message[:1000]
- job.message = message[:500]
- job.finished_at = now
- job.progress = 100
+ kb_job.status = 'failed'
+ kb_job.error_message = message[:1000]
+ kb_job.message = message[:500]
+ kb_job.finished_at = now
+ kb_job.progress = 100
db.session.commit()
diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py
index 8206168b..34646c06 100644
--- a/backend/app/jobs/types.py
+++ b/backend/app/jobs/types.py
@@ -15,6 +15,7 @@ class JobType(StrEnum):
KB_CLEAN = 'kb_clean'
KB_DIFY_SYNC = 'kb_dify_sync'
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
+ SHIPPING_NOTICE_PARSE = 'shipping_notice_parse'
SCHEDULE_RUN = 'schedule_run'
FILE_CHECK_RUN = 'file_check_run'
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
@@ -48,7 +49,7 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
- 'shipping': frozenset({'shipping_notice_run'}),
+ 'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse'}),
}
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index e09f6cd2..cbf17dc3 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -16,10 +16,14 @@ from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGro
from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord
from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
from app.models.settings import AppSetting
+from app.models.file_asset import FileAsset
from app.models.shipping import (
ShippingBatch,
ShippingInventoryFile,
ShippingInventoryMapping,
+ ShippingNoticeCandidate,
+ ShippingNoticeDocument,
+ ShippingNoticeIntake,
ShippingTask,
ShippingTaskEvent,
ShippingTaskInventoryLink,
@@ -66,6 +70,10 @@ __all__ = [
'ShippingInventoryFile',
'ShippingTaskInventoryLink',
'ShippingInventoryMapping',
+ 'ShippingNoticeIntake',
+ 'ShippingNoticeDocument',
+ 'ShippingNoticeCandidate',
+ 'FileAsset',
'AgentGuide',
'AgentDirectoryMember',
'TrainingRecord',
diff --git a/backend/app/models/file_asset.py b/backend/app/models/file_asset.py
new file mode 100644
index 00000000..2b2e1058
--- /dev/null
+++ b/backend/app/models/file_asset.py
@@ -0,0 +1,70 @@
+"""
+backend/app/models/file_asset.py
+
+用途:平台级通用文件资产模型,承载私有 MinIO 存储元数据与生命周期。
+依赖:models.base.Base。
+逻辑:由 file_assets.service 创建与更新;ShippingNoticeIntake 经 asset_id 引用上传根资产;
+ EML 解析后的订单附件以 parent_asset_id 挂为 derived 子资产(阶段二);
+ 派生资产对 (parent_asset_id, content_hash) 使用未删除行的部分唯一索引。
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Optional
+
+from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint, text
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.models.base import Base
+
+
+class FileAsset(Base):
+ """通用文件资产(私有对象存储 + 审计元数据)。"""
+
+ __tablename__ = 'file_assets'
+ __table_args__ = (
+ UniqueConstraint('asset_no', name='uq_file_assets_asset_no'),
+ Index('ix_file_assets_owner_content_hash', 'owner_user_id', 'content_hash'),
+ Index('ix_file_assets_lifecycle_expires', 'lifecycle_status', 'expires_at'),
+ Index('ix_file_assets_owner_created', 'owner_user_id', 'created_at'),
+ # 仅约束未删除派生资产,避免 soft-delete 永久阻塞同哈希重资产化
+ Index(
+ 'uq_file_assets_parent_content_hash_alive',
+ 'parent_asset_id',
+ 'content_hash',
+ unique=True,
+ postgresql_where=text('deleted_at IS NULL AND parent_asset_id IS NOT NULL'),
+ sqlite_where=text('deleted_at IS NULL AND parent_asset_id IS NOT NULL'),
+ ),
+ Index('ix_file_assets_parent_attachment_key', 'parent_asset_id', 'source_attachment_key'),
+ )
+
+ id: Mapped[int] = mapped_column(primary_key=True)
+ asset_no: Mapped[str] = mapped_column(String(64), nullable=False)
+ owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False)
+ tenant_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ # 派生资产:EML 根资产 → 附件 PDF 等子资产
+ parent_asset_id: Mapped[Optional[int]] = mapped_column(
+ ForeignKey('file_assets.id'),
+ index=True,
+ nullable=True,
+ )
+ asset_role: Mapped[str] = mapped_column(String(32), default='upload', nullable=False)
+ # 派生资产首次落库时的 attachment_key;后续复用同哈希时不覆盖(当前来源见 Document.attachment_key)
+ source_attachment_key: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
+ storage_provider: Mapped[str] = mapped_column(String(32), default='minio', nullable=False)
+ storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
+ storage_key: Mapped[str] = mapped_column(String(512), nullable=False)
+ content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
+ file_size: Mapped[int] = mapped_column(Integer, nullable=False)
+ mime_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
+ extension: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ upload_status: Mapped[str] = mapped_column(String(32), default='uploading', nullable=False)
+ lifecycle_status: Mapped[str] = mapped_column(String(32), default='temporary', nullable=False)
+ reference_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
+ expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+ deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
+ updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
diff --git a/backend/app/models/job.py b/backend/app/models/job.py
index 27d80986..f1a978c1 100644
--- a/backend/app/models/job.py
+++ b/backend/app/models/job.py
@@ -11,7 +11,7 @@ from __future__ import annotations
from datetime import datetime
from typing import Optional
-from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text
+from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
@@ -29,6 +29,25 @@ class Job(Base):
Index('ix_jobs_type_status_created', 'job_type', 'status', 'created_at'),
Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'),
Index('ix_jobs_locked_at', 'locked_at'),
+ # 仅预解析 Job:同业务锚点同时只允许一条 queued
+ # (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限)
+ Index(
+ 'uq_jobs_shipping_parse_queued_ref',
+ 'domain',
+ 'job_type',
+ 'business_ref',
+ unique=True,
+ postgresql_where=text(
+ "job_type = 'shipping_notice_parse' "
+ "AND status = 'queued' "
+ "AND business_ref IS NOT NULL"
+ ),
+ sqlite_where=text(
+ "job_type = 'shipping_notice_parse' "
+ "AND status = 'queued' "
+ "AND business_ref IS NOT NULL"
+ ),
+ ),
)
id: Mapped[int] = mapped_column(primary_key=True)
diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py
index 45b6104a..a72d169c 100644
--- a/backend/app/models/shipping.py
+++ b/backend/app/models/shipping.py
@@ -1,8 +1,13 @@
"""
backend/app/models/shipping.py
-用途:货代发货通知批次、任务、事件、库存文件与库存映射模型。
+用途:货代发货通知批次、任务、事件、库存文件、接入记录、文档/候选与库存映射模型。
依赖:models.base.Base。
+逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等;
+ Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
+ Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
+ Document/Candidate 承载阶段二「一邮件多订单」识别;ShippingTask.source_candidate_id 预留给建单;
+ ShippingTask.supersedes_task_id 唯一约束保证修订链线性。
"""
from __future__ import annotations
@@ -10,7 +15,20 @@ from __future__ import annotations
from datetime import datetime
from typing import List, Optional
-from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
+from sqlalchemy import (
+ Boolean,
+ DateTime,
+ Float,
+ ForeignKey,
+ ForeignKeyConstraint,
+ Index,
+ Integer,
+ JSON,
+ String,
+ Text,
+ UniqueConstraint,
+ text,
+)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
@@ -23,6 +41,11 @@ class ShippingBatch(Base):
__table_args__ = (
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
Index('ix_shipping_batches_conversation', 'conversation_id'),
+ UniqueConstraint(
+ 'user_id',
+ 'create_idempotency_key',
+ name='uq_shipping_batches_user_create_idempotency',
+ ),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -39,6 +62,7 @@ class ShippingBatch(Base):
nullable=True,
)
file_count: Mapped[int] = mapped_column(Integer, default=1)
+ create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
@@ -59,6 +83,16 @@ class ShippingTask(Base):
Index('ix_shipping_tasks_conversation', 'conversation_id'),
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
Index('ix_shipping_tasks_upload_status', 'upload_status'),
+ Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'),
+ Index('ix_shipping_tasks_inventory_site_id', 'inventory_site_id'),
+ Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'),
+ Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
+ Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
+ Index('ix_shipping_tasks_user_source_content_hash', 'user_id', 'source_content_hash'),
+ Index('ix_shipping_tasks_user_business_fingerprint', 'user_id', 'business_fingerprint'),
+ # 线性版本链:同一父任务至多一个后继(NULL 不冲突)
+ UniqueConstraint('supersedes_task_id', name='uq_shipping_tasks_supersedes_task_id'),
+ Index('ix_shipping_tasks_duplicate_source_task_id', 'duplicate_source_task_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -69,6 +103,36 @@ class ShippingTask(Base):
source_type: Mapped[str] = mapped_column(String(32), default='manual')
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True)
+ source_intake_id: Mapped[Optional[int]] = mapped_column(
+ ForeignKey('shipping_notice_intakes.id'),
+ index=True,
+ nullable=True,
+ )
+ # 阶段二:由 Candidate 正式建单时回填;与 Candidate.consumed_task_id 对向引用,用 use_alter
+ source_candidate_id: Mapped[Optional[int]] = mapped_column(
+ ForeignKey(
+ 'shipping_notice_candidates.id',
+ name='fk_shipping_tasks_source_candidate_id',
+ use_alter=True,
+ ),
+ index=True,
+ nullable=True,
+ )
+ business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
+ supersedes_task_id: Mapped[Optional[int]] = mapped_column(
+ ForeignKey('shipping_tasks.id'),
+ nullable=True,
+ )
+ duplicate_source_task_id: Mapped[Optional[int]] = mapped_column(
+ ForeignKey('shipping_tasks.id'),
+ nullable=True,
+ )
+ duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ duplicate_resolution_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
@@ -76,6 +140,21 @@ class ShippingTask(Base):
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
+ destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
+ inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ inventory_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ inventory_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ inventory_source_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
+ inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+ inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
@@ -150,6 +229,28 @@ class ShippingInventoryFile(Base):
'snapshot_status',
'exported_at',
),
+ Index(
+ 'ix_shipping_inventory_files_source_site_wh',
+ 'source_code',
+ 'site_id',
+ 'warehouse_id',
+ ),
+ Index(
+ 'uq_shipping_inventory_files_rpa_identity_ready',
+ 'rpa_run_no',
+ 'source_code',
+ 'site_id',
+ 'warehouse_id',
+ unique=True,
+ postgresql_where=text(
+ "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
+ "AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
+ ),
+ sqlite_where=text(
+ "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
+ "AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
+ ),
+ ),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -167,6 +268,9 @@ class ShippingInventoryFile(Base):
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
+ source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
@@ -193,6 +297,12 @@ class ShippingTaskInventoryLink(Base):
__table_args__ = (
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'),
+ Index(
+ 'ix_shipping_task_inventory_links_task_source',
+ 'task_id',
+ 'matched_source_code',
+ 'matched_site_id',
+ ),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -203,6 +313,10 @@ class ShippingTaskInventoryLink(Base):
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
link_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ matched_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ matched_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
audit_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
@@ -216,6 +330,179 @@ class ShippingTaskInventoryLink(Base):
)
+class ShippingNoticeIntake(Base):
+ """发货通知预解析接入记录(上传成功至正式建单前的异步解析阶段)。"""
+
+ __tablename__ = 'shipping_notice_intakes'
+ __table_args__ = (
+ UniqueConstraint('intake_no', name='uq_shipping_notice_intakes_intake_no'),
+ UniqueConstraint(
+ 'asset_id',
+ 'purpose',
+ 'parser_version',
+ name='uq_shipping_notice_intakes_asset_purpose_parser',
+ ),
+ Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
+ Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'),
+ Index('ix_shipping_notice_intakes_expires', 'expires_at'),
+ Index('ix_shipping_notice_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'),
+ Index('ix_shipping_notice_intakes_duplicate_status_created', 'duplicate_status', 'created_at'),
+ Index('ix_shipping_notice_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'),
+ Index('ix_shipping_notice_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'),
+ )
+
+ id: Mapped[int] = mapped_column(primary_key=True)
+ intake_no: Mapped[str] = mapped_column(String(64), nullable=False)
+ asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=False)
+ user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False)
+ conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
+ purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False)
+ parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True)
+ extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
+ parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
+ parser_version: Mapped[str] = mapped_column(String(32), nullable=False)
+ parse_job_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
+ # 解析执行代次:格式 "{job_id}:{job.attempts}";超时回收清空后旧 Worker 写回被拒绝
+ parse_lease: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ duplicate_status: Mapped[str] = mapped_column(
+ String(32),
+ default='unchecked',
+ server_default=text("'unchecked'"),
+ nullable=False,
+ )
+ duplicate_matches_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
+ duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+ duplicate_resolution: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
+ duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+ consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+ consumed_batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True)
+ consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
+ create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
+ expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
+ updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
+class ShippingNoticeDocument(Base):
+ """
+ 发货通知文档单元:邮件正文或单个附件(阶段二)。
+
+ 核心逻辑:Intake 解析后按 attachment_key 幂等 upsert;附件型 Document 可挂 derived FileAsset。
+ """
+
+ __tablename__ = 'shipping_notice_documents'
+ __table_args__ = (
+ UniqueConstraint(
+ 'intake_id',
+ 'attachment_key',
+ name='uq_shipping_notice_documents_intake_attachment_key',
+ ),
+ # 支撑 Candidate (primary_document_id, intake_id) 复合外键
+ UniqueConstraint('id', 'intake_id', name='uq_shipping_notice_documents_id_intake'),
+ Index('ix_shipping_notice_documents_intake_id', 'intake_id'),
+ Index('ix_shipping_notice_documents_asset_id', 'asset_id'),
+ Index('ix_shipping_notice_documents_content_hash', 'content_hash'),
+ Index('ix_shipping_notice_documents_parse_status', 'parse_status'),
+ )
+
+ id: Mapped[int] = mapped_column(primary_key=True)
+ intake_id: Mapped[int] = mapped_column(
+ ForeignKey('shipping_notice_intakes.id'),
+ nullable=False,
+ )
+ asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
+ document_type: Mapped[str] = mapped_column(String(32), nullable=False)
+ attachment_key: Mapped[str] = mapped_column(String(64), nullable=False)
+ filename: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
+ content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ classification: Mapped[str] = mapped_column(String(32), default='unknown', nullable=False)
+ parse_status: Mapped[str] = mapped_column(String(32), default='pending', nullable=False)
+ extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
+ updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
+class ShippingNoticeCandidate(Base):
+ """
+ 订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
+
+ 核心逻辑:通常 1 Document → 1 Candidate;重复检测与决策落在 Candidate 级,互不影响。
+ """
+
+ __tablename__ = 'shipping_notice_candidates'
+ __table_args__ = (
+ UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'),
+ UniqueConstraint(
+ 'intake_id',
+ 'primary_document_id',
+ name='uq_shipping_notice_candidates_intake_primary_document',
+ ),
+ # 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接
+ ForeignKeyConstraint(
+ ['primary_document_id', 'intake_id'],
+ ['shipping_notice_documents.id', 'shipping_notice_documents.intake_id'],
+ name='fk_shipping_notice_candidates_document_intake',
+ ),
+ Index('ix_shipping_notice_candidates_intake_id', 'intake_id'),
+ Index('ix_shipping_notice_candidates_primary_document_id', 'primary_document_id'),
+ Index('ix_shipping_notice_candidates_po_number', 'po_number'),
+ Index(
+ 'ix_shipping_notice_candidates_user_fingerprint',
+ 'business_fingerprint',
+ ),
+ Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'),
+ )
+
+ id: Mapped[int] = mapped_column(primary_key=True)
+ candidate_no: Mapped[str] = mapped_column(String(64), nullable=False)
+ intake_id: Mapped[int] = mapped_column(
+ ForeignKey('shipping_notice_intakes.id'),
+ nullable=False,
+ )
+ primary_document_id: Mapped[int] = mapped_column(Integer, nullable=False)
+ po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
+ structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
+ confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
+ validation_status: Mapped[str] = mapped_column(
+ String(32),
+ default='pending',
+ server_default=text("'pending'"),
+ nullable=False,
+ )
+ conflicts_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
+ selected: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), nullable=False)
+ business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ duplicate_status: Mapped[str] = mapped_column(
+ String(32),
+ default='unchecked',
+ server_default=text("'unchecked'"),
+ nullable=False,
+ )
+ duplicate_matches_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
+ duplicate_resolution: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+ duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+ consumed_task_id: Mapped[Optional[int]] = mapped_column(
+ ForeignKey('shipping_tasks.id'),
+ nullable=True,
+ )
+ created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
+ updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
class ShippingInventoryMapping(Base):
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
diff --git a/backend/app/models/user.py b/backend/app/models/user.py
index 6c85ffd9..d6c24216 100644
--- a/backend/app/models/user.py
+++ b/backend/app/models/user.py
@@ -89,6 +89,8 @@ class User(Base):
"""返回当前角色自带的功能权限默认值。"""
return {
'training_hr_manage': self.role in {'admin', 'hr'},
+ # 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予
+ 'shipping_notice_force_create': self.role == 'admin',
}
def get_feature_permissions(self) -> dict[str, bool]:
diff --git a/backend/app/services/admin/database_admin_service.py b/backend/app/services/admin/database_admin_service.py
index 5c037e42..7c61c3dd 100644
--- a/backend/app/services/admin/database_admin_service.py
+++ b/backend/app/services/admin/database_admin_service.py
@@ -3,7 +3,7 @@ backend/app/services/admin/database_admin_service.py
用途:管理后台通用数据表浏览与 chat_logs 批量删除。
依赖:models、report_service(chat_logs 报表复用)。
-逻辑:由 api/admin/database.py 调用。
+逻辑:由 api/admin/database.py 调用;整型筛选字段对纯数字条件使用等值匹配。
"""
from __future__ import annotations
@@ -66,7 +66,12 @@ def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
for key, value in query_params.items():
if hasattr(model, key) and value:
col = getattr(model, key)
- query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
+ 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]
diff --git a/backend/app/services/admin/report_service.py b/backend/app/services/admin/report_service.py
index 4a1de7ea..67d4083e 100644
--- a/backend/app/services/admin/report_service.py
+++ b/backend/app/services/admin/report_service.py
@@ -1,8 +1,8 @@
"""
backend/app/services/admin/report_service.py
-用途:管理后台报表(使用分析、反馈、聊天日志)数据聚合。
-依赖:models、SQLAlchemy func。
+用途:管理后台报表(使用分析、应用运营、反馈、聊天日志)数据聚合。
+依赖:models、SQLAlchemy func、user_agent_permissions。
逻辑:由 api/admin/reports.py、database_admin_service 调用。
"""
from __future__ import annotations
@@ -11,12 +11,29 @@ import math
from datetime import datetime, timedelta
from typing import Any
-from sqlalchemy import desc, func
+from sqlalchemy import asc, desc, func, or_
from app import db
-from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
+from app.models import Agent, ChatLog, Feedback, GeneralFeedback, PermissionRequest, User
+from app.models.base import user_agent_permissions
USAGE_BY_USER_TOP_LIMIT = 50
+APPLICATION_REPORT_PAGE_SIZE_MAX = 100
+APPLICATION_REPORT_SORT_KEYS = frozenset({
+ 'name',
+ 'chat_count',
+ 'unique_users',
+ 'last_active_at',
+ 'authorized_users',
+ 'pending_requests',
+ 'avg_score',
+ 'tokens_used',
+})
+DEFAULT_APPLICATION_SORT = 'chat_count'
+# 运营提醒:启用应用在范围内对话次数 ≤ 该阈值视为低使用(含零使用)
+USAGE_LOW_AGENT_MAX_CHATS = 2
+# 运营提醒:低使用应用最多返回条数
+USAGE_LOW_AGENT_LIST_LIMIT = 5
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
USAGE_RANGE_DAYS = {
@@ -52,10 +69,16 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
"""
聊天使用分析报表(按应用 / 按用户),限定时间范围内的 ChatLog。
+ 核心逻辑:按 Agent / User 聚合 ChatLog 次数;按用户统计同时返回 username 与 real_name;
+ 另对启用 Agent 左连接对话量,产出含零使用的低使用应用列表(与应用运营口径对齐)。
+
Args:
user_page: 按用户统计分页页码。
user_page_size: 每页条数(上限 USAGE_BY_USER_TOP_LIMIT)。
range_key: 时间范围 key,见 USAGE_RANGE_DAYS。
+
+ Returns:
+ 含 total / by_user / by_agent / by_day / low_agents 及用户分页字段的字典。
"""
normalized_range, since = resolve_usage_range_start(range_key)
base_filter = ChatLog.created_at >= since
@@ -69,13 +92,42 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
.order_by(desc(func.count(ChatLog.id)), Agent.name)
.all()
)
+ # [STEP 1] 按日期聚合趋势,供管理端判断近几天是否出现使用高峰或低谷。
+ by_day = (
+ db.session.query(func.date(ChatLog.created_at), func.count(ChatLog.id))
+ .filter(base_filter)
+ .group_by(func.date(ChatLog.created_at))
+ .order_by(asc(func.date(ChatLog.created_at)))
+ .all()
+ )
+ # [STEP 2] 低使用应用:以启用 Agent 为主表左连接范围内对话量,含零使用(by_agent 只有有对话的应用)
+ agent_chat_counts = (
+ db.session.query(
+ ChatLog.agent_id.label('agent_id'),
+ func.count(ChatLog.id).label('chat_count'),
+ )
+ .filter(base_filter)
+ .group_by(ChatLog.agent_id)
+ .subquery()
+ )
+ chat_count_col = func.coalesce(agent_chat_counts.c.chat_count, 0)
+ low_agents = (
+ db.session.query(Agent.name, chat_count_col.label('count'))
+ .outerjoin(agent_chat_counts, agent_chat_counts.c.agent_id == Agent.id)
+ .filter(Agent.is_active.is_(True))
+ .filter(chat_count_col <= USAGE_LOW_AGENT_MAX_CHATS)
+ .order_by(asc(chat_count_col), Agent.name)
+ .limit(USAGE_LOW_AGENT_LIST_LIMIT)
+ .all()
+ )
user_page = max(1, user_page)
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
+ # [STEP 3] 按用户聚合对话量,一并选出真实姓名供管理端展示
by_user_top = (
- db.session.query(User.username, func.count(ChatLog.id))
+ db.session.query(User.username, User.real_name, func.count(ChatLog.id))
.join(ChatLog)
.filter(base_filter)
- .group_by(User.username)
+ .group_by(User.username, User.real_name)
.order_by(desc(func.count(ChatLog.id)), User.username)
.limit(USAGE_BY_USER_TOP_LIMIT)
.all()
@@ -88,8 +140,15 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
return {
'total': total,
'range': normalized_range,
- 'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
+ 'by_user': [
+ {'username': u, 'real_name': rn or '', 'count': c}
+ for u, rn, c in by_user_page
+ ],
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
+ 'by_day': [{'date': str(day), 'count': c} for day, c in by_day],
+ 'low_agents': [{'agent': a, 'count': int(c)} for a, c in low_agents],
+ 'low_agent_max_chats': USAGE_LOW_AGENT_MAX_CHATS,
+ 'low_agent_list_limit': USAGE_LOW_AGENT_LIST_LIMIT,
'user_total': user_total,
'user_page': user_page,
'user_page_size': user_page_size,
@@ -110,6 +169,214 @@ def build_feedback_report() -> dict:
}
+def build_application_report(
+ *,
+ range_key: str | None = None,
+ status: str | None = None,
+ usage: str | None = None,
+ q: str | None = None,
+ sort: str | None = None,
+ order: str | None = None,
+ page: int = 1,
+ page_size: int = 20,
+) -> dict:
+ """
+ 应用运营报表:以 Agent 为主表,聚合时间范围内的使用 / 权限 / 评分指标。
+
+ 核心逻辑:ChatLog 聚合对话与用户;user_agent_permissions 统计授权人数;
+ PermissionRequest 统计待审;Feedback JOIN ChatLog 统计均分。不含 API Key 等配置敏感字段。
+
+ Args:
+ range_key: 时间范围 key(7d/30d/90d/180d/365d),非法值回退近一月。
+ status: all | active | inactive,按 is_active 过滤。
+ usage: all | used | unused,按时间范围内是否有对话过滤。
+ q: 应用名称模糊搜索。
+ sort: 排序字段,见 APPLICATION_REPORT_SORT_KEYS。
+ order: asc | desc,默认 desc。
+ page: 页码(从 1 起)。
+ page_size: 每页条数,上限 APPLICATION_REPORT_PAGE_SIZE_MAX。
+
+ Returns:
+ 含 summary / items / 分页字段的字典。
+ """
+ normalized_range, since = resolve_usage_range_start(range_key)
+ status_key = (status or 'all').strip().lower()
+ if status_key not in {'all', 'active', 'inactive'}:
+ status_key = 'all'
+ usage_key = (usage or 'all').strip().lower()
+ if usage_key not in {'all', 'used', 'unused'}:
+ usage_key = 'all'
+ sort_key = (sort or DEFAULT_APPLICATION_SORT).strip().lower()
+ if sort_key not in APPLICATION_REPORT_SORT_KEYS:
+ sort_key = DEFAULT_APPLICATION_SORT
+ order_key = (order or 'desc').strip().lower()
+ if order_key not in {'asc', 'desc'}:
+ order_key = 'desc'
+ page = max(1, int(page or 1))
+ page_size = max(1, min(int(page_size or 20), APPLICATION_REPORT_PAGE_SIZE_MAX))
+ keyword = (q or '').strip()
+
+ # [STEP 1] 子查询:时间范围内对话 / 授权 / 待审 / 评分
+ chat_stats = (
+ db.session.query(
+ ChatLog.agent_id.label('agent_id'),
+ func.count(ChatLog.id).label('chat_count'),
+ func.count(func.distinct(ChatLog.user_id)).label('unique_users'),
+ func.max(ChatLog.created_at).label('last_active_at'),
+ func.coalesce(func.sum(ChatLog.tokens_used), 0).label('tokens_used'),
+ func.avg(ChatLog.latency).label('avg_latency_ms'),
+ )
+ .filter(ChatLog.created_at >= since)
+ .group_by(ChatLog.agent_id)
+ .subquery()
+ )
+ auth_stats = (
+ db.session.query(
+ user_agent_permissions.c.agent_id.label('agent_id'),
+ func.count(user_agent_permissions.c.user_id).label('authorized_users'),
+ )
+ .group_by(user_agent_permissions.c.agent_id)
+ .subquery()
+ )
+ pending_stats = (
+ db.session.query(
+ PermissionRequest.agent_id.label('agent_id'),
+ func.count(PermissionRequest.id).label('pending_requests'),
+ )
+ .filter(PermissionRequest.status == 'pending')
+ .group_by(PermissionRequest.agent_id)
+ .subquery()
+ )
+ feedback_stats = (
+ db.session.query(
+ ChatLog.agent_id.label('agent_id'),
+ func.avg(Feedback.score).label('avg_score'),
+ func.count(Feedback.id).label('feedback_count'),
+ )
+ .join(Feedback, Feedback.chat_log_id == ChatLog.id)
+ .filter(ChatLog.created_at >= since)
+ .group_by(ChatLog.agent_id)
+ .subquery()
+ )
+
+ chat_count_col = func.coalesce(chat_stats.c.chat_count, 0)
+ unique_users_col = func.coalesce(chat_stats.c.unique_users, 0)
+ authorized_col = func.coalesce(auth_stats.c.authorized_users, 0)
+ pending_col = func.coalesce(pending_stats.c.pending_requests, 0)
+ tokens_col = func.coalesce(chat_stats.c.tokens_used, 0)
+
+ # [STEP 2] Agent 左连接各聚合,应用筛选
+ query = (
+ db.session.query(
+ Agent.id,
+ Agent.name,
+ Agent.is_active,
+ Agent.category,
+ chat_count_col.label('chat_count'),
+ unique_users_col.label('unique_users'),
+ chat_stats.c.last_active_at,
+ authorized_col.label('authorized_users'),
+ pending_col.label('pending_requests'),
+ feedback_stats.c.avg_score,
+ func.coalesce(feedback_stats.c.feedback_count, 0).label('feedback_count'),
+ tokens_col.label('tokens_used'),
+ chat_stats.c.avg_latency_ms,
+ )
+ .outerjoin(chat_stats, chat_stats.c.agent_id == Agent.id)
+ .outerjoin(auth_stats, auth_stats.c.agent_id == Agent.id)
+ .outerjoin(pending_stats, pending_stats.c.agent_id == Agent.id)
+ .outerjoin(feedback_stats, feedback_stats.c.agent_id == Agent.id)
+ )
+ if status_key == 'active':
+ query = query.filter(Agent.is_active.is_(True))
+ elif status_key == 'inactive':
+ query = query.filter(Agent.is_active.is_(False))
+ if usage_key == 'used':
+ query = query.filter(chat_count_col > 0)
+ elif usage_key == 'unused':
+ query = query.filter(or_(chat_stats.c.chat_count.is_(None), chat_stats.c.chat_count == 0))
+ if keyword:
+ query = query.filter(Agent.name.ilike(f'%{keyword}%'))
+
+ # [STEP 3] 一次拉取筛选结果,内存排序分页(应用数量通常较小;兼容 SQLite 测试)
+ filtered_rows = list(query.all())
+ agent_total = len(filtered_rows)
+ active_agents = sum(1 for row in filtered_rows if row.is_active)
+ used_agents = sum(1 for row in filtered_rows if int(row.chat_count or 0) > 0)
+ unused_agents = agent_total - used_agents
+ pending_permission_total = sum(int(row.pending_requests or 0) for row in filtered_rows)
+
+ def _row_sort_key(row: Any) -> tuple:
+ """
+ 构造排序键:(是否空值, 业务值, 名称, id)。
+ 空值(无最近活跃 / 无评分)始终排在末尾。
+ """
+ if sort_key == 'name':
+ return (0, (row.name or '').lower(), row.name or '', row.id)
+ if sort_key in {'chat_count', 'unique_users', 'authorized_users', 'pending_requests', 'tokens_used'}:
+ return (0, int(getattr(row, sort_key) or 0), row.name or '', row.id)
+ raw = getattr(row, sort_key, None)
+ if raw is None:
+ return (1, None, row.name or '', row.id)
+ if sort_key == 'avg_score':
+ return (0, float(raw), row.name or '', row.id)
+ return (0, raw, row.name or '', row.id)
+
+ reverse = order_key == 'desc'
+ non_null = [r for r in filtered_rows if _row_sort_key(r)[0] == 0]
+ nulls = [r for r in filtered_rows if _row_sort_key(r)[0] == 1]
+ non_null.sort(key=_row_sort_key, reverse=reverse)
+ nulls.sort(key=lambda r: (r.name or '', r.id))
+ filtered_rows = non_null + nulls
+
+ pages = max(1, math.ceil(agent_total / page_size)) if agent_total else 1
+ page = min(page, pages)
+ offset = (page - 1) * page_size
+ page_rows = filtered_rows[offset:offset + page_size]
+
+ items = []
+ for row in page_rows:
+ avg_score = float(row.avg_score) if row.avg_score is not None else None
+ avg_latency = float(row.avg_latency_ms) if row.avg_latency_ms is not None else None
+ last_active = row.last_active_at.isoformat() if row.last_active_at else None
+ items.append({
+ 'agent_id': row.id,
+ 'name': row.name,
+ 'is_active': bool(row.is_active),
+ 'category': row.category or '',
+ 'chat_count': int(row.chat_count or 0),
+ 'unique_users': int(row.unique_users or 0),
+ 'last_active_at': last_active,
+ 'authorized_users': int(row.authorized_users or 0),
+ 'pending_requests': int(row.pending_requests or 0),
+ 'avg_score': round(avg_score, 2) if avg_score is not None else None,
+ 'feedback_count': int(row.feedback_count or 0),
+ 'tokens_used': int(row.tokens_used or 0),
+ 'avg_latency_ms': round(avg_latency, 1) if avg_latency is not None else None,
+ })
+
+ return {
+ 'range': normalized_range,
+ 'status': status_key,
+ 'usage': usage_key,
+ 'q': keyword,
+ 'sort': sort_key,
+ 'order': order_key,
+ 'summary': {
+ 'agent_total': agent_total,
+ 'active_agents': active_agents,
+ 'used_agents': used_agents,
+ 'unused_agents': unused_agents,
+ 'pending_permission_total': pending_permission_total,
+ },
+ 'items': items,
+ 'total': agent_total,
+ 'page': page,
+ 'page_size': page_size,
+ 'pages': pages,
+ }
+
+
def _apply_general_feedback_filters(query, query_params: dict[str, str]):
reserved = {'limit', 'offset', 'page', 'page_size'}
for key, value in query_params.items():
@@ -208,6 +475,8 @@ def apply_chat_logs_report_filters(query, query_params: dict[str, str]):
continue
if key == 'agent_name':
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
+ elif key == 'agent_id' and value.isdigit():
+ query = query.filter(ChatLog.agent_id == int(value))
elif key == 'username':
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
elif key == 'real_name':
diff --git a/backend/app/services/agent_directory.py b/backend/app/services/agent_directory.py
index 9484067e..4701101b 100644
--- a/backend/app/services/agent_directory.py
+++ b/backend/app/services/agent_directory.py
@@ -86,9 +86,23 @@ def list_directory_member_agents(agent_id: int, *, active_only: bool = False) ->
return query.all()
-def serialize_directory_member(agent: Agent) -> dict[str, Any]:
- """Serialize one member Agent for Admin and Dify runtime metadata."""
- return {
+def serialize_directory_member(
+ agent: Agent,
+ *,
+ active_only: bool = False,
+ max_depth: int = 0,
+ visited_ids: set[int] | None = None,
+) -> dict[str, Any]:
+ """
+ Serialize one member Agent for Admin, user navigation, and Dify metadata.
+
+ Args:
+ active_only: True 时只展开启用中的子应用。
+ max_depth: 允许向下展开的聚合层级,避免用户列表中聚合子应用丢失展开能力。
+ visited_ids: 已访问 Agent ID,用于防止循环配置导致递归。
+ """
+ is_aggregate = bool(getattr(agent, 'is_aggregate', False))
+ payload = {
'id': agent.id,
'name': agent.name,
'description': agent.description,
@@ -97,12 +111,41 @@ def serialize_directory_member(agent: Agent) -> dict[str, Any]:
'dify_app_id': agent.dify_app_id,
'category': agent.category,
'sub_category': agent.sub_category,
+ 'sort_order': int(getattr(agent, 'sort_order', 0) or 0),
+ 'is_aggregate': is_aggregate,
}
+ if is_aggregate and max_depth > 0:
+ next_visited = set(visited_ids or set())
+ if agent.id not in next_visited:
+ next_visited.add(agent.id)
+ payload['directory_members'] = serialize_directory_members(
+ agent.id,
+ active_only=active_only,
+ max_depth=max_depth - 1,
+ visited_ids=next_visited,
+ )
+ return payload
-def serialize_directory_members(agent_id: int, *, active_only: bool = False) -> list[dict[str, Any]]:
+def serialize_directory_members(
+ agent_id: int,
+ *,
+ active_only: bool = False,
+ max_depth: int = 0,
+ visited_ids: set[int] | None = None,
+) -> list[dict[str, Any]]:
"""Serialize configured member Agents for a directory Agent."""
+ visited = set(visited_ids or set())
+ if agent_id in visited:
+ return []
+ visited.add(agent_id)
return [
- serialize_directory_member(agent)
+ serialize_directory_member(
+ agent,
+ active_only=active_only,
+ max_depth=max_depth,
+ visited_ids=visited,
+ )
for agent in list_directory_member_agents(agent_id, active_only=active_only)
+ if agent.id not in visited
]
diff --git a/backend/app/services/chat/turn_runtime.py b/backend/app/services/chat/turn_runtime.py
index 25bfd431..93775416 100644
--- a/backend/app/services/chat/turn_runtime.py
+++ b/backend/app/services/chat/turn_runtime.py
@@ -2,8 +2,9 @@
backend/app/services/chat/turn_runtime.py
用途:平台统一 Chat Turn 执行器,编排 SSE 生命周期、session、ChatLog 与 action 路由。
-依赖:action_registry、turn_events、session_service、log_service、turn_context、action_schema。
+依赖:action_registry、turn_events、session_service、log_service、turn_context、action_schema、db。
逻辑:api/chat/turns/stream 调用 ChatTurnRuntime.stream();业务 handler 只 yield TurnEvent。
+ 失败路径先 db.session.rollback(),再 touch_chat_session,避免 handler 脏写被一并提交。
"""
from __future__ import annotations
@@ -14,6 +15,7 @@ from typing import Any, Iterator
from flask import current_app
+from app import db
from app.core.errors import AppError, ValidationError
from app.services.chat.action_registry import ensure_handlers_loaded, resolve_action_handler
from app.services.chat.action_schema import TurnEvent, TurnInput, parse_turn_refs_from_context
@@ -183,6 +185,8 @@ class ChatTurnRuntime:
getattr(exc, "code", None),
exc.message,
)
+ # 业务失败后先 rollback,避免 handler 预占/脏写被 touch_chat_session 一并提交
+ db.session.rollback()
touch_chat_session(user_id, agent_id, session.session_id, status="error")
yield emit_run_failed(
run_id=run_id,
@@ -193,6 +197,7 @@ class ChatTurnRuntime:
)
except Exception as exc:
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
+ db.session.rollback()
touch_chat_session(user_id, agent_id, session.session_id, status="error")
yield emit_run_failed(
run_id=run_id,
diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py
index 4625eae2..5f1787e3 100644
--- a/backend/app/services/dify.py
+++ b/backend/app/services/dify.py
@@ -134,6 +134,98 @@ class DifyService:
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
+ @staticmethod
+ def _merge_stream_answer_text(
+ streamed_text: str,
+ terminal_answer: str | None,
+ *,
+ replace_answer: bool = False,
+ ) -> str:
+ """
+ 合并流式增量文本与终态 answer,避免 Dify 结束事件重复携带整段正文导致落库翻倍。
+ 核心逻辑:与前端 useChat.ts 终态事件去重策略保持一致。
+
+ Args:
+ streamed_text: message 事件累积的增量文本。
+ terminal_answer: message_end / workflow_finished 携带的 answer。
+ replace_answer: 为 True 时仅使用终态 answer。
+
+ Returns:
+ 去重后的最终正文。
+ """
+ current_content = str(streamed_text or '')
+ terminal = str(terminal_answer or '')
+
+ if replace_answer and terminal.strip():
+ return terminal.strip()
+ if not terminal:
+ return current_content.strip()
+ if not current_content.strip():
+ return terminal.strip()
+
+ current_stripped = current_content.strip()
+ terminal_stripped = terminal.strip()
+ if (
+ terminal_stripped
+ and current_stripped
+ and len(terminal_stripped) >= len(current_stripped)
+ and current_stripped in terminal_stripped
+ ):
+ return terminal_stripped
+ if terminal_stripped and current_stripped and terminal_stripped in current_stripped:
+ return current_stripped
+ return (current_content + terminal).strip()
+
+ @staticmethod
+ def _build_final_answer_text(
+ *,
+ streamed_parts: list[str],
+ data: dict,
+ event_name: str,
+ ) -> str:
+ """
+ 根据流式片段与终态事件组装最终落库 answer。
+ 核心逻辑:先走 _merge_stream_answer_text 去重;workflow_finished 无 answer 时回退 outputs。
+ """
+ streamed_text = ''.join(streamed_parts)
+ terminal = str(data.get('answer') or '') if data.get('answer') else ''
+ answer_text = DifyService._merge_stream_answer_text(
+ streamed_text,
+ terminal or None,
+ replace_answer=bool(data.get('replace_answer')),
+ )
+
+ if not answer_text and event_name == 'workflow_finished':
+ wf_data = data.get('data') or {}
+ outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
+ if isinstance(outputs, dict):
+ for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
+ value = outputs.get(key)
+ if isinstance(value, str) and value.strip():
+ answer_text = value.strip()
+ break
+ if not answer_text:
+ for value in outputs.values():
+ if isinstance(value, str) and value.strip():
+ answer_text = value.strip()
+ break
+ return answer_text
+
+ @staticmethod
+ def _dedupe_exact_doubled_text(text: str) -> str:
+ """
+ 修复历史落库时将同一段正文原样拼接两次的记录。
+ 核心逻辑:仅当整段文本可被均分为两段完全相同子串时才裁剪。
+ """
+ normalized = str(text or '')
+ stripped = normalized.strip()
+ if len(stripped) < 2:
+ return normalized
+ half = len(stripped) // 2
+ if len(stripped) % 2 == 0 and stripped[:half] == stripped[half:]:
+ return stripped[:half]
+ return normalized
+
@staticmethod
def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None:
if not isinstance(data, dict):
@@ -896,25 +988,11 @@ class DifyService:
return result
def build_final_answer_text(data: dict, event_name: str) -> str:
- answer_text = ''.join(full_answer).strip()
- if data.get('answer'):
- answer_text = (answer_text + str(data.get('answer') or '')).strip()
-
- if not answer_text and event_name == 'workflow_finished':
- wf_data = data.get('data') or {}
- outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
- if isinstance(outputs, dict):
- for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
- value = outputs.get(key)
- if isinstance(value, str) and value.strip():
- answer_text = value.strip()
- break
- if not answer_text:
- for value in outputs.values():
- if isinstance(value, str) and value.strip():
- answer_text = value.strip()
- break
- return answer_text
+ return DifyService._build_final_answer_text(
+ streamed_parts=full_answer,
+ data=data,
+ event_name=event_name,
+ )
max_retries = 3
diff --git a/backend/app/services/file_assets/__init__.py b/backend/app/services/file_assets/__init__.py
new file mode 100644
index 00000000..79b03358
--- /dev/null
+++ b/backend/app/services/file_assets/__init__.py
@@ -0,0 +1,7 @@
+"""
+backend/app/services/file_assets/__init__.py
+
+用途:平台级文件资产服务包入口。
+依赖:file_assets.service、file_assets.storage、file_assets.cleanup。
+逻辑:API 与 shipping intake 经 service 层读写 FileAsset 与私有 MinIO 对象。
+"""
diff --git a/backend/app/services/file_assets/cleanup.py b/backend/app/services/file_assets/cleanup.py
new file mode 100644
index 00000000..a0214427
--- /dev/null
+++ b/backend/app/services/file_assets/cleanup.py
@@ -0,0 +1,83 @@
+"""
+backend/app/services/file_assets/cleanup.py
+
+用途:过期未引用 FileAsset 与关联 intake 的清理编排。
+依赖:file_assets.storage、models.FileAsset/ShippingNoticeIntake。
+逻辑:由排程或 file_asset_cleanup Job 调用;先标记 expired → 删 MinIO → 成功后 mark deleted;
+ MinIO 删除失败不伪装成功,保留记录供下次重试。
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime
+
+from sqlalchemy import or_
+
+from app import db
+from app.models import FileAsset, ShippingNoticeIntake
+from app.services.file_assets.storage import file_asset_storage
+
+_LOGGER = logging.getLogger(__name__)
+
+
+def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
+ """
+ 清理过期或已标记 expired 但尚未物理删除的临时资产。
+ Returns:
+ 统计字典:scanned/expired/deleted/errors。
+ """
+ now = datetime.utcnow()
+ assets = (
+ db.session.query(FileAsset)
+ .filter(
+ FileAsset.reference_count == 0,
+ FileAsset.deleted_at.is_(None),
+ or_(
+ (
+ (FileAsset.lifecycle_status == 'temporary')
+ & (FileAsset.expires_at.isnot(None))
+ & (FileAsset.expires_at < now)
+ ),
+ FileAsset.lifecycle_status == 'expired',
+ ),
+ )
+ .order_by(FileAsset.expires_at.asc().nullsfirst(), FileAsset.id.asc())
+ .limit(max(int(limit or 100), 1))
+ .all()
+ )
+ stats = {'scanned': len(assets), 'expired': 0, 'deleted': 0, 'errors': 0}
+ for asset in assets:
+ consumed = (
+ db.session.query(ShippingNoticeIntake.id)
+ .filter(
+ ShippingNoticeIntake.asset_id == asset.id,
+ ShippingNoticeIntake.parse_status == 'consumed',
+ )
+ .first()
+ )
+ if consumed:
+ continue
+ stats['expired'] += 1
+ asset.lifecycle_status = 'expired'
+ (
+ db.session.query(ShippingNoticeIntake)
+ .filter(
+ ShippingNoticeIntake.asset_id == asset.id,
+ ShippingNoticeIntake.consumed_at.is_(None),
+ ShippingNoticeIntake.parse_status.notin_(('consumed', 'cancelled')),
+ )
+ .update({'parse_status': 'expired', 'updated_at': now}, synchronize_session=False)
+ )
+ try:
+ file_asset_storage.delete_object(asset.storage_key)
+ asset.upload_status = 'deleted'
+ asset.deleted_at = now
+ asset.updated_at = now
+ stats['deleted'] += 1
+ except Exception:
+ stats['errors'] += 1
+ asset.updated_at = now
+ _LOGGER.exception('failed to delete minio object for asset %s', asset.asset_no)
+ db.session.commit()
+ return stats
diff --git a/backend/app/services/file_assets/cleanup_schedule.py b/backend/app/services/file_assets/cleanup_schedule.py
new file mode 100644
index 00000000..19d9bafa
--- /dev/null
+++ b/backend/app/services/file_assets/cleanup_schedule.py
@@ -0,0 +1,157 @@
+"""
+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 事件。
+逻辑:create_app 启动时 ensure 一次;User after_commit 用独立 Session 即时补建(原 session 已 committed 不可再发 SQL)。
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime
+from typing import Any
+
+from sqlalchemy import event
+from sqlalchemy.orm import Session
+
+from app import db
+from app.models import ScheduleTask, User
+from app.services.schedule.timezone_util import compute_next_run_at
+
+_LOGGER = logging.getLogger(__name__)
+
+DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO = "SCH-FILE-ASSET-CLEANUP"
+DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH = "file-asset-cleanup"
+DEFAULT_FILE_ASSET_CLEANUP_CRON = "0 * * * *"
+DEFAULT_FILE_ASSET_CLEANUP_NAME = "临时文件资产 TTL 清理"
+
+_HOOKS_REGISTERED = False
+_SESSION_INFO_KEY = "_seed_file_asset_cleanup"
+
+
+def ensure_default_file_asset_cleanup_schedule(
+ *,
+ commit: bool = True,
+ session: Any | None = None,
+) -> ScheduleTask | None:
+ """
+ 幂等确保默认 TTL 清理排程存在。
+
+ 核心逻辑:若已有同 schedule_no 或同 platform_api_path 的排程则跳过;
+ 否则在存在至少一个用户时创建启用态排程(next_run_at 走 Cron 语义)。
+
+ Args:
+ commit: 是否立即提交。
+ session: 可选独立 Session(User after_commit 钩子须传入,避免 committed 态 Session 发 SQL)。
+
+ Returns:
+ 新建或已存在的 ScheduleTask;尚无用户时返回 None。
+ """
+ sess = session if session is not None else db.session
+ existing = (
+ sess.query(ScheduleTask)
+ .filter(
+ (ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
+ | (ScheduleTask.platform_api_path == DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH)
+ )
+ .first()
+ )
+ 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()
+ if owner is None:
+ _LOGGER.info("skip seed file-asset-cleanup schedule: no users yet")
+ return None
+
+ now = datetime.utcnow()
+ next_run = compute_next_run_at(
+ DEFAULT_FILE_ASSET_CLEANUP_CRON,
+ timezone_name="Asia/Shanghai",
+ ) or now
+
+ task = ScheduleTask(
+ schedule_no=DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO,
+ name=DEFAULT_FILE_ASSET_CLEANUP_NAME,
+ schedule_type="platform_job",
+ owner_user_id=int(owner.id),
+ cron_expr=DEFAULT_FILE_ASSET_CLEANUP_CRON,
+ schedule_timezone="Asia/Shanghai",
+ wait_seconds=0,
+ platform_api_path=DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH,
+ job_params=None,
+ kb_sync_enabled=False,
+ notify_user_ids_json=[],
+ notify_enabled=False,
+ enabled=True,
+ next_run_at=next_run,
+ created_by=int(owner.id),
+ updated_by=int(owner.id),
+ created_at=now,
+ updated_at=now,
+ )
+ sess.add(task)
+ if commit:
+ try:
+ sess.commit()
+ except Exception:
+ sess.rollback()
+ existing = (
+ sess.query(ScheduleTask)
+ .filter(
+ (ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
+ | (ScheduleTask.platform_api_path == DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH)
+ )
+ .first()
+ )
+ if existing is not None:
+ return existing
+ raise
+ else:
+ sess.flush()
+ _LOGGER.info(
+ "seeded default file-asset-cleanup schedule_no=%s owner_user_id=%s",
+ task.schedule_no,
+ owner.id,
+ )
+ return task
+
+
+def register_file_asset_cleanup_schedule_hooks() -> None:
+ """
+ 注册 Session 钩子:User 插入并 commit 后立即尝试补建默认清理排程。
+
+ 核心逻辑:after_flush 标记;after_commit 用独立 Session 调用 ensure
+ (原 session 处于 committed 态不能再发 SQL)。
+ """
+ global _HOOKS_REGISTERED
+ if _HOOKS_REGISTERED:
+ return
+
+ @event.listens_for(Session, "after_flush")
+ def _mark_user_insert(session: Session, _context) -> None: # type: ignore[no-untyped-def]
+ if any(isinstance(obj, User) for obj in session.new):
+ session.info[_SESSION_INFO_KEY] = True
+
+ @event.listens_for(Session, "after_commit")
+ def _seed_after_user_commit(session: Session) -> None:
+ if not session.info.pop(_SESSION_INFO_KEY, False):
+ return
+ bind = session.get_bind()
+ if bind is None:
+ return
+ try:
+ with Session(bind) as seed_session:
+ ensure_default_file_asset_cleanup_schedule(commit=True, session=seed_session)
+ except Exception as exc: # pragma: no cover - 防御不阻断建用户
+ _LOGGER.warning("ensure file-asset-cleanup after user create failed: %s", exc)
+
+ _HOOKS_REGISTERED = True
diff --git a/backend/app/services/file_assets/service.py b/backend/app/services/file_assets/service.py
new file mode 100644
index 00000000..1de7c862
--- /dev/null
+++ b/backend/app/services/file_assets/service.py
@@ -0,0 +1,633 @@
+"""
+backend/app/services/file_assets/service.py
+
+用途:FileAsset 业务编排(校验、哈希、落库、鉴权、生命周期)。
+依赖:file_assets.storage、models.FileAsset、Flask current_app。
+逻辑:由 /api/files 与 shipping intake 调用;storage_key 不向前端返回;
+ create_derived_file_asset_from_bytes 供 EML 附件子资产幂等落库(阶段二);
+ mark/release 以 SQL 原子 UPDATE 按关联边增减 reference_count;补偿失败写 orphan_cleanup 行。
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import mimetypes
+import os
+import re
+import uuid
+from datetime import datetime, timedelta
+from typing import Any
+
+from flask import current_app
+from sqlalchemy import case, update
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.orm import Session
+from werkzeug.datastructures import FileStorage
+from werkzeug.utils import secure_filename
+
+from app import db
+from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
+from app.core.response import utc_iso
+from app.models import FileAsset
+from app.services.file_assets.storage import file_asset_storage
+
+_LOGGER = logging.getLogger(__name__)
+
+
+def _keep_first_source_attachment_key(
+ asset: FileAsset,
+ *,
+ source_attachment_key: str | None,
+) -> bool:
+ """
+ 仅在资产尚无来源键时写入首次 source_attachment_key,复用/复活不覆盖。
+
+ Returns:
+ 是否实际写入了字段。
+ """
+ incoming = str(source_attachment_key or '').strip()
+ if not incoming or str(asset.source_attachment_key or '').strip():
+ return False
+ asset.source_attachment_key = incoming[:64]
+ return True
+
+_ALLOWED_EXTENSIONS = {
+ 'pdf', 'doc', 'docx', 'txt', 'md', 'log', 'html', 'htm', 'eml',
+ 'csv', 'png', 'jpg', 'jpeg', 'webp',
+}
+
+
+def _max_file_size_bytes() -> int:
+ mb = int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30)
+ return max(mb, 1) * 1024 * 1024
+
+
+def _temp_ttl_hours() -> int:
+ return max(int(current_app.config.get('FILE_ASSET_TEMP_TTL_HOURS', 72) or 72), 1)
+
+
+def generate_asset_no() -> str:
+ """生成 FA-YYYYMMDD-XXXXXXXX 格式资产编号。"""
+ return f"FA-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
+
+
+def _normalize_extension(filename: str) -> str:
+ ext = os.path.splitext(str(filename or '').strip())[1].lower().lstrip('.')
+ return ext
+
+
+def _build_storage_key(*, user_id: int, asset_no: str, filename: str) -> str:
+ now = datetime.utcnow()
+ safe_name = secure_filename(filename) or 'file'
+ safe_name = re.sub(r'[^\w\-.]+', '_', safe_name)[:120] or 'file'
+ return f"temporary/{user_id}/{now:%Y}/{now:%m}/{asset_no}/{safe_name}"
+
+
+def _build_derived_storage_key(
+ *,
+ user_id: int,
+ parent_asset_no: str,
+ asset_no: str,
+ filename: str,
+) -> str:
+ """派生附件存储路径:挂在父资产编号下,便于审计与清理。"""
+ now = datetime.utcnow()
+ safe_name = secure_filename(filename) or 'file'
+ safe_name = re.sub(r'[^\w\-.]+', '_', safe_name)[:120] or 'file'
+ parent = re.sub(r'[^\w\-]+', '_', str(parent_asset_no or 'parent'))[:64] or 'parent'
+ return f"derived/{user_id}/{now:%Y}/{now:%m}/{parent}/{asset_no}/{safe_name}"
+
+
+def _serialize_asset(asset: FileAsset) -> dict[str, Any]:
+ return {
+ 'asset_no': asset.asset_no,
+ 'original_filename': asset.original_filename,
+ 'file_size': asset.file_size,
+ 'mime_type': asset.mime_type,
+ 'content_hash': asset.content_hash,
+ 'upload_status': asset.upload_status,
+ 'lifecycle_status': asset.lifecycle_status,
+ 'parent_asset_id': asset.parent_asset_id,
+ 'asset_role': asset.asset_role,
+ 'source_attachment_key': asset.source_attachment_key,
+ 'expires_at': utc_iso(asset.expires_at),
+ 'created_at': utc_iso(asset.created_at),
+ }
+
+
+def get_asset_for_user(asset_no: str, user_id: int) -> FileAsset:
+ """
+ 按编号查询当前用户拥有的资产。
+ Raises:
+ NotFoundError: 不存在或已逻辑删除。
+ ForbiddenError: 非所有者。
+ """
+ normalized = str(asset_no or '').strip().upper()
+ asset = (
+ db.session.query(FileAsset)
+ .filter(FileAsset.asset_no == normalized, FileAsset.deleted_at.is_(None))
+ .first()
+ )
+ if not asset:
+ raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
+ if int(asset.owner_user_id) != int(user_id):
+ raise ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问该文件资产')
+ return asset
+
+
+def upload_file_asset(*, user_id: int, upload: FileStorage) -> dict[str, Any]:
+ """
+ 上传文件并创建 FileAsset 记录。
+ 核心逻辑:校验类型与大小 → SHA-256 → 写 MinIO → 落库 ready/temporary。
+ """
+ filename = str(upload.filename or '').strip() or 'file'
+ ext = _normalize_extension(filename)
+ if ext not in _ALLOWED_EXTENSIONS:
+ raise ValidationError(
+ code='FILE_ASSET.INVALID_TYPE',
+ message=f'不支持的文件类型: .{ext or "unknown"}',
+ )
+
+ data = upload.read()
+ if not data:
+ raise ValidationError(code='FILE_ASSET.UPLOAD_FAILED', message='文件内容为空')
+ if len(data) > _max_file_size_bytes():
+ raise ValidationError(code='FILE_ASSET.SIZE_EXCEEDED', message='文件大小超过限制')
+
+ content_hash = hashlib.sha256(data).hexdigest()
+ asset_no = generate_asset_no()
+ storage_key = _build_storage_key(user_id=user_id, asset_no=asset_no, filename=filename)
+ mime_type = upload.mimetype or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
+ expires_at = datetime.utcnow() + timedelta(hours=_temp_ttl_hours())
+
+ asset = FileAsset(
+ asset_no=asset_no,
+ owner_user_id=int(user_id),
+ original_filename=filename,
+ parent_asset_id=None,
+ asset_role='upload',
+ source_attachment_key=None,
+ storage_provider='minio',
+ storage_bucket=file_asset_storage.bucket_name,
+ storage_key=storage_key,
+ content_hash=content_hash,
+ file_size=len(data),
+ mime_type=mime_type,
+ extension=ext or None,
+ upload_status='uploading',
+ lifecycle_status='temporary',
+ reference_count=0,
+ expires_at=expires_at,
+ )
+ db.session.add(asset)
+ db.session.flush()
+
+ try:
+ file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type=mime_type)
+ asset.upload_status = 'ready'
+ except Exception:
+ asset.upload_status = 'failed'
+ db.session.commit()
+ raise
+
+ db.session.commit()
+ return _serialize_asset(asset)
+
+
+def _find_derived_by_parent_hash(
+ *,
+ parent_id: int,
+ content_hash: str,
+ include_deleted: bool = False,
+) -> FileAsset | None:
+ """按父资产 + content_hash 查找派生资产(默认可复用活记录)。"""
+ query = db.session.query(FileAsset).filter(
+ FileAsset.parent_asset_id == int(parent_id),
+ FileAsset.content_hash == content_hash,
+ )
+ if not include_deleted:
+ query = query.filter(FileAsset.deleted_at.is_(None))
+ return query.order_by(FileAsset.id.asc()).first()
+
+
+def _revive_soft_deleted_derived_asset(
+ asset: FileAsset,
+ *,
+ data: bytes,
+ filename: str,
+ mime_type: str | None,
+ source_attachment_key: str | None,
+ uploaded_storage_keys: list[str] | None,
+) -> FileAsset:
+ """
+ 恢复被 soft-delete 的派生资产并重新上传对象。
+
+ 核心逻辑:清理 deleted_at 后复用原 storage_key;失败时保持 expired 供清理。
+ """
+ resolved_mime = (
+ str(mime_type or asset.mime_type or '').strip()
+ or mimetypes.guess_type(filename)[0]
+ or 'application/octet-stream'
+ )
+ asset.deleted_at = None
+ asset.upload_status = 'uploading'
+ asset.lifecycle_status = 'temporary'
+ asset.reference_count = 0
+ asset.expires_at = datetime.utcnow() + timedelta(hours=_temp_ttl_hours())
+ asset.original_filename = str(filename or asset.original_filename or 'attachment.bin')[:255]
+ asset.mime_type = resolved_mime[:128]
+ # 复活时仅补写空的首次来源键,不覆盖历史审计值
+ _keep_first_source_attachment_key(asset, source_attachment_key=source_attachment_key)
+ asset.updated_at = datetime.utcnow()
+ db.session.flush()
+ try:
+ file_asset_storage.upload_bytes(
+ storage_key=asset.storage_key,
+ data=data,
+ content_type=resolved_mime,
+ )
+ asset.upload_status = 'ready'
+ if uploaded_storage_keys is not None:
+ uploaded_storage_keys.append(asset.storage_key)
+ except Exception:
+ asset.upload_status = 'failed'
+ asset.lifecycle_status = 'expired'
+ asset.updated_at = datetime.utcnow()
+ raise
+ return asset
+
+
+def create_derived_file_asset_from_bytes(
+ *,
+ user_id: int,
+ parent: FileAsset,
+ data: bytes,
+ filename: str,
+ mime_type: str | None = None,
+ source_attachment_key: str | None = None,
+ asset_role: str = 'derived_attachment',
+ uploaded_storage_keys: list[str] | None = None,
+) -> tuple[FileAsset, bool]:
+ """
+ 从可信内部字节创建(或复用)派生 FileAsset。
+
+ 核心逻辑:按 parent_asset_id + content_hash 幂等;DB 唯一约束兜底并发;
+ IntegrityError 时 SAVEPOINT 回滚后回查已有行;新建成功后记录 storage_key 供事务失败补偿。
+ source_attachment_key 语义为「首次来源键」:已有值时复用不覆盖。
+
+ Args:
+ user_id: 所有者,须与 parent.owner_user_id 一致。
+ parent: EML 等根资产。
+ data: 附件原始字节(不可为空)。
+ filename: 原始文件名。
+ mime_type: MIME;缺省按文件名猜测。
+ source_attachment_key: 首次资产化时的 att-key(审计);后续复用不改。
+ asset_role: 默认 derived_attachment。
+ uploaded_storage_keys: 若提供,本函数成功上传的新对象 key 会 append,供调用方失败补偿。
+
+ Returns:
+ (已 ready 的 FileAsset, created_new);flush,不 commit。
+
+ Raises:
+ ForbiddenError: 非父资产所有者。
+ ValidationError: 空内容或超大。
+ """
+ if int(parent.owner_user_id) != int(user_id):
+ raise ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权在该父资产下创建派生文件')
+ if not data:
+ raise ValidationError(code='FILE_ASSET.UPLOAD_FAILED', message='派生文件内容为空')
+ if len(data) > _max_file_size_bytes():
+ raise ValidationError(code='FILE_ASSET.SIZE_EXCEEDED', message='派生文件大小超过限制')
+
+ content_hash = hashlib.sha256(data).hexdigest().lower()
+ existing = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash)
+ if existing is not None:
+ if _keep_first_source_attachment_key(existing, source_attachment_key=source_attachment_key):
+ existing.updated_at = datetime.utcnow()
+ if str(existing.upload_status or '') == 'ready':
+ return existing, False
+ try:
+ file_asset_storage.upload_bytes(
+ storage_key=existing.storage_key,
+ data=data,
+ content_type=existing.mime_type or 'application/octet-stream',
+ )
+ existing.upload_status = 'ready'
+ existing.updated_at = datetime.utcnow()
+ if uploaded_storage_keys is not None:
+ uploaded_storage_keys.append(existing.storage_key)
+ except Exception:
+ existing.upload_status = 'failed'
+ existing.updated_at = datetime.utcnow()
+ raise
+ return existing, False
+
+ # 软删除记录挡住同哈希时优先复活,避免孤儿行永久占位
+ soft_deleted = _find_derived_by_parent_hash(
+ parent_id=int(parent.id),
+ content_hash=content_hash,
+ include_deleted=True,
+ )
+ if soft_deleted is not None and soft_deleted.deleted_at is not None:
+ revived = _revive_soft_deleted_derived_asset(
+ soft_deleted,
+ data=data,
+ filename=str(filename or soft_deleted.original_filename or 'attachment.bin'),
+ mime_type=mime_type,
+ source_attachment_key=source_attachment_key,
+ uploaded_storage_keys=uploaded_storage_keys,
+ )
+ return revived, False
+
+ safe_filename = str(filename or '').strip() or 'attachment.bin'
+ ext = _normalize_extension(safe_filename)
+ if not ext:
+ ext = 'bin'
+ if not os.path.splitext(safe_filename)[1]:
+ safe_filename = f'{safe_filename}.bin'
+
+ asset_no = generate_asset_no()
+ storage_key = _build_derived_storage_key(
+ user_id=int(user_id),
+ parent_asset_no=str(parent.asset_no or ''),
+ asset_no=asset_no,
+ filename=safe_filename,
+ )
+ resolved_mime = (
+ str(mime_type or '').strip()
+ or mimetypes.guess_type(safe_filename)[0]
+ or 'application/octet-stream'
+ )
+ expires_at = datetime.utcnow() + timedelta(hours=_temp_ttl_hours())
+
+ asset = FileAsset(
+ asset_no=asset_no,
+ owner_user_id=int(user_id),
+ parent_asset_id=int(parent.id),
+ asset_role=str(asset_role or 'derived_attachment')[:32],
+ source_attachment_key=(str(source_attachment_key)[:64] if source_attachment_key else None),
+ original_filename=safe_filename[:255],
+ storage_provider='minio',
+ storage_bucket=file_asset_storage.bucket_name,
+ storage_key=storage_key,
+ content_hash=content_hash,
+ file_size=len(data),
+ mime_type=resolved_mime[:128],
+ extension=ext[:32] if ext else None,
+ upload_status='uploading',
+ lifecycle_status='temporary',
+ reference_count=0,
+ expires_at=expires_at,
+ )
+
+ # [STEP] SAVEPOINT:唯一约束冲突时只回滚本插入,保留外层 Document 事务
+ try:
+ with db.session.begin_nested():
+ db.session.add(asset)
+ db.session.flush()
+ except IntegrityError:
+ raced = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash)
+ if raced is not None:
+ if _keep_first_source_attachment_key(raced, source_attachment_key=source_attachment_key):
+ raced.updated_at = datetime.utcnow()
+ return raced, False
+ # 冲突落在软删除行(旧全量唯一约束环境)时尝试复活
+ raced_deleted = _find_derived_by_parent_hash(
+ parent_id=int(parent.id),
+ content_hash=content_hash,
+ include_deleted=True,
+ )
+ if raced_deleted is None:
+ raise
+ revived = _revive_soft_deleted_derived_asset(
+ raced_deleted,
+ data=data,
+ filename=safe_filename,
+ mime_type=mime_type,
+ source_attachment_key=source_attachment_key,
+ uploaded_storage_keys=uploaded_storage_keys,
+ )
+ return revived, False
+
+ try:
+ file_asset_storage.upload_bytes(
+ storage_key=storage_key,
+ data=data,
+ content_type=resolved_mime,
+ )
+ asset.upload_status = 'ready'
+ if uploaded_storage_keys is not None:
+ uploaded_storage_keys.append(storage_key)
+ except Exception:
+ asset.upload_status = 'failed'
+ raise
+
+ return asset, True
+
+
+def mark_asset_referenced(asset: FileAsset) -> None:
+ """
+ 建立一次业务引用:原子 +1,并置 lifecycle=referenced。
+
+ 核心逻辑:数据库层 `reference_count = reference_count + 1`,避免并发读改写丢失。
+ """
+ now = datetime.utcnow()
+ db.session.execute(
+ update(FileAsset)
+ .where(FileAsset.id == int(asset.id))
+ .values(
+ reference_count=FileAsset.reference_count + 1,
+ lifecycle_status='referenced',
+ expires_at=None,
+ updated_at=now,
+ )
+ )
+ db.session.refresh(asset)
+
+
+def release_asset_reference(asset: FileAsset) -> None:
+ """
+ 原子减少业务引用;派生资产归零后恢复 temporary + TTL,供清理任务回收。
+
+ 核心逻辑:单条 UPDATE 内用旧值计算新计数与 lifecycle,避免并发少计/多计。
+ """
+ now = datetime.utcnow()
+ expires = now + timedelta(hours=_temp_ttl_hours())
+ # 不用 GREATEST:SQLite 测试库无该函数;CASE 在 PG/SQLite 均可原子计算新计数
+ new_count = case(
+ (FileAsset.reference_count > 0, FileAsset.reference_count - 1),
+ else_=0,
+ )
+ db.session.execute(
+ update(FileAsset)
+ .where(FileAsset.id == int(asset.id))
+ .values(
+ reference_count=new_count,
+ lifecycle_status=case(
+ (
+ (FileAsset.reference_count <= 1)
+ & (FileAsset.asset_role == 'derived_attachment'),
+ 'temporary',
+ ),
+ (
+ FileAsset.reference_count > 1,
+ 'referenced',
+ ),
+ else_=FileAsset.lifecycle_status,
+ ),
+ expires_at=case(
+ (
+ (FileAsset.reference_count <= 1)
+ & (FileAsset.asset_role == 'derived_attachment'),
+ expires,
+ ),
+ (
+ FileAsset.reference_count > 1,
+ None,
+ ),
+ else_=FileAsset.expires_at,
+ ),
+ updated_at=now,
+ )
+ )
+ db.session.refresh(asset)
+
+
+def _persist_orphan_storage_key_for_cleanup(
+ *,
+ storage_key: str,
+ owner_user_id: int | None,
+ storage_bucket: str | None,
+) -> None:
+ """
+ 补偿删除失败时写入可被 cleanup 回收的孤儿资产行。
+
+ 核心逻辑:使用独立 Session,避免污染调用方 Session;标记 expired + orphan_cleanup。
+ """
+ now = datetime.utcnow()
+ owner = int(owner_user_id or 0)
+ if owner <= 0:
+ # 无可用所有者时仍记录日志即可,不强写无主行
+ _LOGGER.error(
+ 'orphan minio key has no owner_user_id; cannot persist cleanup row key=%s',
+ storage_key,
+ )
+ return
+ bind = db.session.get_bind()
+ if bind is None:
+ _LOGGER.error('orphan persist skipped: no DB bind for key=%s', storage_key)
+ return
+ row = FileAsset(
+ asset_no=generate_asset_no(),
+ owner_user_id=owner,
+ parent_asset_id=None,
+ asset_role='orphan_cleanup',
+ source_attachment_key=None,
+ original_filename='orphan.bin',
+ storage_provider='minio',
+ storage_bucket=str(storage_bucket or file_asset_storage.bucket_name)[:128],
+ storage_key=storage_key[:512],
+ content_hash=hashlib.sha256(storage_key.encode('utf-8')).hexdigest(),
+ file_size=0,
+ mime_type='application/octet-stream',
+ extension='bin',
+ upload_status='ready',
+ lifecycle_status='expired',
+ reference_count=0,
+ expires_at=now,
+ deleted_at=None,
+ )
+ with Session(bind=bind) as orphan_session:
+ orphan_session.add(row)
+ orphan_session.commit()
+
+
+def compensate_uploaded_storage_keys(
+ storage_keys: list[str] | None,
+ *,
+ owner_user_id: int | None = None,
+ storage_bucket: str | None = None,
+) -> None:
+ """
+ 事务失败后尽力删除本轮新上传的 MinIO 对象。
+
+ 核心逻辑:删除失败则 error 日志 + 独立 Session 写入 orphan_cleanup;
+ 台账写入失败会 rollback 调用方 Session,避免 PendingRollbackError。
+
+ Args:
+ storage_keys: create_derived 写入的 storage_key 列表。
+ owner_user_id: 孤儿行归属用户;缺省时仅打日志。
+ storage_bucket: MinIO bucket;缺省用配置桶。
+ """
+ for key in storage_keys or []:
+ normalized = str(key or '').strip()
+ if not normalized:
+ continue
+ try:
+ file_asset_storage.delete_object(normalized)
+ except Exception:
+ _LOGGER.exception('failed to compensate-delete minio object key=%s', normalized)
+ try:
+ _persist_orphan_storage_key_for_cleanup(
+ storage_key=normalized,
+ owner_user_id=owner_user_id,
+ storage_bucket=storage_bucket,
+ )
+ except Exception:
+ _LOGGER.exception(
+ 'failed to persist orphan cleanup row for minio key=%s',
+ normalized,
+ )
+ try:
+ db.session.rollback()
+ except Exception:
+ _LOGGER.exception(
+ 'failed to rollback session after orphan persist error key=%s',
+ normalized,
+ )
+
+
+
+def delete_temporary_asset(*, asset_no: str, user_id: int) -> None:
+ """
+ 删除未引用的临时资产:先标记 expired,再删 MinIO;成功后标记 deleted。
+ Raises:
+ ConflictError: 已被业务引用。
+ ServiceUnavailableError: MinIO 删除失败(保留 expired 供清理重试)。
+ """
+ asset = get_asset_for_user(asset_no, user_id)
+ if str(asset.lifecycle_status or '') == 'referenced' or int(asset.reference_count or 0) > 0:
+ raise ConflictError(code='FILE_ASSET.ALREADY_REFERENCED', message='文件已被业务引用,无法删除')
+ if str(asset.upload_status or '') == 'deleted' and asset.deleted_at is not None:
+ return
+
+ now = datetime.utcnow()
+ asset.lifecycle_status = 'expired'
+ asset.updated_at = now
+ db.session.flush()
+
+ try:
+ file_asset_storage.delete_object(asset.storage_key)
+ except Exception:
+ db.session.commit()
+ raise
+
+ asset.upload_status = 'deleted'
+ asset.deleted_at = now
+ asset.updated_at = now
+ db.session.commit()
+
+
+def read_asset_bytes(asset: FileAsset) -> bytes:
+ """读取资产对象字节,校验未过期/未删除。"""
+ if asset.deleted_at is not None:
+ raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
+ if asset.expires_at and asset.expires_at < datetime.utcnow() and asset.lifecycle_status == 'temporary':
+ raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期')
+ return file_asset_storage.get_bytes(asset.storage_key)
+
+
+def serialize_asset_public(asset: FileAsset) -> dict[str, Any]:
+ """对外序列化资产(不含 storage_key)。"""
+ return _serialize_asset(asset)
diff --git a/backend/app/services/file_assets/storage.py b/backend/app/services/file_assets/storage.py
new file mode 100644
index 00000000..3788aa1c
--- /dev/null
+++ b/backend/app/services/file_assets/storage.py
@@ -0,0 +1,132 @@
+"""
+backend/app/services/file_assets/storage.py
+
+用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
+依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
+逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。
+"""
+
+from __future__ import annotations
+
+import io
+import logging
+from datetime import timedelta
+from typing import BinaryIO
+
+from minio import Minio
+from minio.error import S3Error
+
+from app.core.config.settings import ACTIVE_ENV_NAME, config
+from app.core.errors import ServiceUnavailableError
+
+_LOGGER = logging.getLogger(__name__)
+_cfg = config[ACTIVE_ENV_NAME]
+
+
+class FileAssetStorage:
+ """私有业务文件 MinIO 存储客户端。"""
+
+ def __init__(self) -> None:
+ self.client = Minio(
+ _cfg.MINIO_ENDPOINT,
+ access_key=_cfg.MINIO_ACCESS_KEY,
+ secret_key=_cfg.MINIO_SECRET_KEY,
+ secure=_cfg.MINIO_SECURE,
+ )
+ self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
+
+ def _ensure_bucket_exists(self) -> None:
+ """确保私有 bucket 存在,不设置 public-read policy。"""
+ try:
+ if not self.client.bucket_exists(self.bucket_name):
+ self.client.make_bucket(self.bucket_name)
+ except Exception as exc:
+ _LOGGER.exception('MinIO file assets bucket unavailable')
+ raise ServiceUnavailableError(
+ code='FILE_ASSET.UPLOAD_FAILED',
+ message='文件存储服务暂不可用,请稍后重试',
+ ) from exc
+
+ def upload_bytes(
+ self,
+ *,
+ storage_key: str,
+ data: bytes,
+ content_type: str,
+ ) -> None:
+ """
+ 上传字节流到私有 bucket。
+ Raises:
+ ServiceUnavailableError: MinIO 不可用或上传失败。
+ """
+ self._ensure_bucket_exists()
+ stream: BinaryIO = io.BytesIO(data)
+ try:
+ self.client.put_object(
+ bucket_name=self.bucket_name,
+ object_name=storage_key,
+ data=stream,
+ length=len(data),
+ content_type=content_type or 'application/octet-stream',
+ )
+ except Exception as exc:
+ _LOGGER.exception('MinIO upload failed key=%s', storage_key)
+ raise ServiceUnavailableError(
+ code='FILE_ASSET.UPLOAD_FAILED',
+ message='文件上传失败,请稍后重试',
+ ) from exc
+
+ def get_bytes(self, storage_key: str) -> bytes:
+ """
+ 读取对象字节内容。
+ Raises:
+ ServiceUnavailableError: 读取失败(含网络异常与 S3Error)。
+ """
+ try:
+ response = self.client.get_object(self.bucket_name, storage_key)
+ try:
+ return response.read()
+ finally:
+ response.close()
+ response.release_conn()
+ except Exception as exc:
+ _LOGGER.exception('MinIO read failed key=%s', storage_key)
+ raise ServiceUnavailableError(
+ code='FILE_ASSET.UPLOAD_FAILED',
+ message='文件存储服务暂不可用,请稍后重试',
+ ) from exc
+
+ def delete_object(self, storage_key: str) -> None:
+ """
+ 删除 MinIO 对象;失败时抛出可重试 503,供清理任务重试。
+ Raises:
+ ServiceUnavailableError: 删除失败。
+ """
+ try:
+ self.client.remove_object(self.bucket_name, storage_key)
+ except Exception as exc:
+ _LOGGER.exception('MinIO delete failed key=%s', storage_key)
+ raise ServiceUnavailableError(
+ code='FILE_ASSET.UPLOAD_FAILED',
+ message='文件对象删除失败,请稍后重试',
+ ) from exc
+
+ def object_exists(self, storage_key: str) -> bool:
+ """判断对象是否存在。"""
+ try:
+ self.client.stat_object(self.bucket_name, storage_key)
+ return True
+ except S3Error:
+ return False
+
+ def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str:
+ """生成短期受控下载 URL。"""
+ self._ensure_bucket_exists()
+ return self.client.presigned_get_object(
+ self.bucket_name,
+ storage_key,
+ expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
+ )
+
+
+file_asset_storage = FileAssetStorage()
diff --git a/backend/app/services/file_check_tools/openapi_base.json b/backend/app/services/file_check_tools/openapi_base.json
index 8bba81df..4222cc60 100644
--- a/backend/app/services/file_check_tools/openapi_base.json
+++ b/backend/app/services/file_check_tools/openapi_base.json
@@ -108,6 +108,9 @@
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
+ },
+ "503": {
+ "$ref": "#/components/responses/DataSourceUnavailable"
}
}
}
@@ -533,7 +536,8 @@
"properties": {
"task_id": {
"type": "integer",
- "example": 12
+ "example": 12,
+ "description": "检核任务 ID(ScheduleTask.id);绑定 解析运行态上下文.task_id_int(Number),勿绑意图识别.task_id"
},
"trigger_source": {
"type": "string",
@@ -561,7 +565,7 @@
"required": [
"task_id"
],
- "description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
+ "description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
},
"RunCheckSuccessResponse": {
"type": "object",
@@ -887,6 +891,21 @@
}
}
}
+ },
+ "DataSourceUnavailable": {
+ "description": "检核数据源不可用(ODBC/SQL Server 连接失败或 SRM 环境变量未配置)",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ },
+ "example": {
+ "ok": false,
+ "error_code": "data_source_unavailable",
+ "message": "检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动"
+ }
+ }
+ }
}
}
}
diff --git a/backend/app/services/fixed_asset_history.py b/backend/app/services/fixed_asset_history.py
index ef10e3b4..7a5d3a6f 100644
--- a/backend/app/services/fixed_asset_history.py
+++ b/backend/app/services/fixed_asset_history.py
@@ -3,7 +3,9 @@ backend/app/services/fixed_asset_history.py
用途:为固资管理提供“资产履历”共享盘检索能力,按资产编号/资产名称匹配履历文件。
依赖:app.core.config.settings.Config、chat.py 里的预览代理会复用这里返回的共享盘文件路径。
-逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索共享盘 -> 前端拿到候选履历文件后继续走既有预览弹窗。
+逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索履历目录 -> 前端拿到候选履历文件后继续走既有预览弹窗;
+ 支持 Windows 直接访问 UNC 共享盘,也支持 Linux 通过本地挂载目录访问同一批履历文件;
+ 编号命中优先;共享盘按设备名归档时,允许用资产名称匹配文件夹/文件名作为回退。
"""
from __future__ import annotations
@@ -17,6 +19,7 @@ from dataclasses import dataclass
from flask import current_app, has_app_context
from app.core.config.settings import Config
+from app.core.errors import ServiceUnavailableError
_CONNECT_LOCK = threading.Lock()
@@ -75,12 +78,64 @@ class FixedAssetHistoryService:
@classmethod
def is_enabled(cls) -> bool:
- return bool(cls.get_share_root())
+ return bool(cls.get_local_root() or cls.get_share_root())
@classmethod
def get_share_root(cls) -> str:
return cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_ROOT').strip()
+ @classmethod
+ def get_local_root(cls) -> str:
+ return cls._get_runtime_setting('FIXED_ASSET_HISTORY_LOCAL_ROOT').strip()
+
+ @classmethod
+ def get_access_root(cls) -> str:
+ """
+ 返回当前环境实际用于检索/预览履历文件的可访问根目录。
+
+ AI 触发时机:
+ - Windows 本地开发环境通常直接访问 UNC 共享盘;
+ - Linux 测试/生产环境通常通过宿主机或容器挂载目录访问共享盘;
+ - 因此优先读取 `FIXED_ASSET_HISTORY_LOCAL_ROOT`,未配置时再回退到原共享盘根目录。
+ """
+ return cls.get_local_root() or cls.get_share_root()
+
+ @classmethod
+ def _resolve_share_root(cls) -> str:
+ """
+ 解析并校验资产履历共享盘根目录。
+
+ AI 触发时机:当用户点击资产编号查询履历时,必须先确认后端能访问配置的共享盘;
+ 若测试/生产环境未挂载成功,不应误报成“未找到履历文件”,而应返回更准确的环境异常提示。
+ """
+ root = cls.get_access_root()
+ if not root:
+ raise ServiceUnavailableError('asset history share is not configured')
+ if not os.path.exists(root):
+ cls._ensure_share_connected(root)
+ if not os.path.exists(root):
+ raise ServiceUnavailableError('asset history share is unreachable')
+ if not os.path.isdir(root):
+ raise ServiceUnavailableError('asset history share is invalid')
+ return root
+
+ @classmethod
+ def _build_asset_id_variants(cls, asset_id: str) -> tuple[str, ...]:
+ """
+ 生成资产编号匹配变体。
+
+ AI 触发时机:测试/生产环境的共享盘文件名可能出现“带前缀 A”与“不带前缀”两种写法;
+ 这里统一构造多个匹配 key,避免因为命名差一个前缀就查不到履历。
+ """
+ normalized = cls._normalize_keyword(asset_id)
+ if not normalized:
+ return tuple()
+ variants = [normalized]
+ stripped = re.sub(r'^[a-z]+', '', normalized)
+ if stripped and stripped not in variants:
+ variants.append(stripped)
+ return tuple(variants)
+
@classmethod
def search_history_files(
cls,
@@ -97,17 +152,12 @@ class FixedAssetHistoryService:
[STEP 3] 再用资产名称命中同名文件夹/文件,补足部分历史文件只按设备名称归档的情况。
"""
asset_id_value = cls._normalize_keyword(asset_id)
+ asset_id_variants = cls._build_asset_id_variants(asset_id)
asset_name_value = cls._normalize_keyword(asset_name)
- if not asset_id_value and not asset_name_value:
+ if not asset_id_variants and not asset_name_value:
return []
- root = cls.get_share_root()
- if not root:
- return []
- if not os.path.exists(root):
- cls._ensure_share_connected(root)
- if not os.path.isdir(root):
- return []
+ root = cls._resolve_share_root()
max_results = max(
1,
@@ -115,13 +165,13 @@ class FixedAssetHistoryService:
)
candidates: dict[str, AssetHistoryCandidate] = {}
- if asset_id_value:
+ if asset_id_variants:
for current_root, _dirs, files in os.walk(root):
for filename in files:
candidate = cls._build_candidate(
root=root,
file_path=os.path.join(current_root, filename),
- asset_id=asset_id_value,
+ asset_id_variants=asset_id_variants,
asset_name=asset_name_value,
match_reason="asset_id",
)
@@ -135,7 +185,7 @@ class FixedAssetHistoryService:
candidate = cls._build_candidate(
root=root,
file_path=os.path.join(current_root, filename),
- asset_id=asset_id_value,
+ asset_id_variants=asset_id_variants,
asset_name=asset_name_value,
match_reason="asset_name_folder",
)
@@ -143,18 +193,18 @@ class FixedAssetHistoryService:
cls._merge_candidate(candidates, candidate)
if asset_name_value:
- for entry in os.scandir(root):
- if not entry.is_file():
- continue
- candidate = cls._build_candidate(
- root=root,
- file_path=entry.path,
- asset_id=asset_id_value,
- asset_name=asset_name_value,
- match_reason="asset_name_file",
- )
- if candidate:
- cls._merge_candidate(candidates, candidate)
+ # 全树按资产名称匹配文件名(共享盘常见「设备名+履历.xls」,不一定含资产编号)
+ for current_root, _dirs, files in os.walk(root):
+ for filename in files:
+ candidate = cls._build_candidate(
+ root=root,
+ file_path=os.path.join(current_root, filename),
+ asset_id_variants=asset_id_variants,
+ asset_name=asset_name_value,
+ match_reason="asset_name_file",
+ )
+ if candidate:
+ cls._merge_candidate(candidates, candidate)
ordered = sorted(
candidates.values(),
@@ -191,10 +241,18 @@ class FixedAssetHistoryService:
*,
root: str,
file_path: str,
- asset_id: str,
+ asset_id_variants: tuple[str, ...],
asset_name: str,
match_reason: str,
) -> AssetHistoryCandidate | None:
+ """
+ 将单个文件构造成履历候选;按匹配原因施加不同门槛。
+
+ 核心逻辑:
+ - asset_id:文件名/相对路径必须包含资产编号(或去字母前缀变体);
+ - asset_name_folder / asset_name_file:共享盘大量按设备名归档,不强制编号出现在文件名;
+ 名称文件夹命中后,目录内履历文件均可作为候选。
+ """
if not os.path.isfile(file_path):
return None
ext = os.path.splitext(file_path)[1].strip().lower()
@@ -210,15 +268,23 @@ class FixedAssetHistoryService:
if not searchable_text:
return None
- if asset_id and asset_id not in searchable_text:
- return None
- if asset_name and asset_name not in searchable_text and match_reason != "asset_id":
+ # [STEP] 按匹配原因分流门槛,避免“有资产编号就永远要求文件名含编号”导致设备名归档全部 miss
+ if match_reason == "asset_id":
+ if not asset_id_variants or not any(variant in searchable_text for variant in asset_id_variants):
+ return None
+ elif match_reason == "asset_name_file":
+ if not asset_name or asset_name not in searchable_text:
+ return None
+ elif match_reason == "asset_name_folder":
+ # 文件夹已按资产名称命中;文件本身可不含编号/全名
+ pass
+ else:
return None
score = cls._score_candidate(
searchable_text=searchable_text,
filename=cls._normalize_keyword(filename),
- asset_id=asset_id,
+ asset_id_variants=asset_id_variants,
asset_name=asset_name,
match_reason=match_reason,
)
@@ -243,21 +309,33 @@ class FixedAssetHistoryService:
*,
searchable_text: str,
filename: str,
- asset_id: str,
+ asset_id_variants: tuple[str, ...],
asset_name: str,
match_reason: str,
) -> int:
+ """
+ 为履历候选打分;编号命中优先于名称命中。
+
+ 核心逻辑:编号精确/模糊命中给高分;名称命中与「履历」关键字加分;
+ 纯名称归档场景(无编号)至少要靠名称或文件夹命中拿到正分,否则会被过滤。
+ """
score = 0
- if asset_id:
- if asset_id in filename:
- score += 120
- elif asset_id in searchable_text:
- score += 80
+ if asset_id_variants:
+ for index, asset_id in enumerate(asset_id_variants):
+ exact_bonus = 120 if index == 0 else 100
+ fuzzy_bonus = 80 if index == 0 else 60
+ if asset_id in filename:
+ score = max(score, exact_bonus)
+ elif asset_id in searchable_text:
+ score = max(score, fuzzy_bonus)
if asset_name:
if asset_name in filename:
score += 60
elif asset_name in searchable_text:
score += 40
+ elif match_reason == "asset_name_folder":
+ # 文件夹已按名称命中,目录内文件给基础分,避免 score=0 被丢弃
+ score += 30
if "履历" in filename:
score += 20
if match_reason == "asset_name_folder":
@@ -277,7 +355,10 @@ class FixedAssetHistoryService:
尝试用配置的账号密码建立共享盘会话。
账号密码只从环境变量读取,避免把敏感信息写进仓库。
+ Linux 测试/生产环境应优先通过挂载目录访问共享盘,此处仅作为 Windows UNC 共享盘的兜底建连。
"""
+ if os.name != 'nt':
+ return
username = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_USERNAME').strip()
password = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_PASSWORD')
if not username or not password:
diff --git a/backend/app/services/hxops_tool_api.py b/backend/app/services/hxops_tool_api.py
index 5616617c..c228f9b6 100644
--- a/backend/app/services/hxops_tool_api.py
+++ b/backend/app/services/hxops_tool_api.py
@@ -1,23 +1,42 @@
"""
backend/app/services/hxops_tool_api.py
-文件用途:解析 HXOPS 对外 Tool API 基地址(Dify Chatflow / OpenAPI / 签名下载链接)。
+
+用途:解析 HXOPS 两类对外基地址——Dify Tool API(服务端)与用户浏览器访问(下载链等)。
+依赖:Flask current_app / request。
+逻辑:Dify/RPA 调 Tool API 走 resolve_HXOPS_TOOLS_API_BASE;用户可见下载链走 resolve_hxops_user_facing_base_url。
"""
from __future__ import annotations
from flask import current_app, has_request_context, request
-def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
- """返回无尾斜杠的 hxops 对外根地址,如 http://192.168.100.192:8891。"""
- cfg = config
- if cfg is None and current_app:
- cfg = current_app.config
- cfg = cfg or {}
+def _resolve_config(config: dict | None = None) -> dict:
+ """读取 Flask config 或空 dict。"""
+ if config is not None:
+ return config
+ if current_app:
+ return current_app.config
+ return {}
- for key in ("HXOPS_TOOLS_API_BASE", "HXOPS_TOOLS_API_BASE", "PUBLIC_BASE_URL"):
- configured = str(cfg.get(key) or "").strip().rstrip("/")
- if configured:
- return configured
+
+def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
+ """
+ 返回 Dify / RPA 等服务端调用 Tool API 时使用的根地址(无尾斜杠)。
+
+ 核心逻辑:仅读 HXOPS_TOOLS_API_BASE(常为内网 IP),与浏览器下载链、PUBLIC_BASE_URL 分离。
+
+ Args:
+ config: 可选配置字典;缺省时读 current_app.config。
+ request_host: 可选请求 host_url;缺省且在请求上下文中时取 request.host_url。
+
+ Returns:
+ 无尾斜杠的根地址,如 http://192.168.100.192:8890。
+ """
+ cfg = _resolve_config(config)
+
+ configured = str(cfg.get("HXOPS_TOOLS_API_BASE") or "").strip().rstrip("/")
+ if configured:
+ return configured
host = request_host
if host is None and has_request_context():
@@ -25,3 +44,26 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
return host or ""
+def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
+ """
+ 返回浏览器侧可访问的根地址,用于 Excel 签名下载等用户可见链接。
+
+ 核心逻辑:仅读 HXOPS_PUBLIC_BASE_URL / WECOM_PUBLIC_BASE_URL,不复用 Tool API 内网地址或通知地址。
+
+ Args:
+ config: 可选配置字典;缺省时读 current_app.config。
+
+ Returns:
+ 无尾斜杠的根地址,如 https://ai.example.com。
+ """
+ cfg = _resolve_config(config)
+
+ for key in ("HXOPS_PUBLIC_BASE_URL", "WECOM_PUBLIC_BASE_URL"):
+ configured = str(cfg.get(key) or "").strip().rstrip("/")
+ if configured:
+ return configured
+
+ if has_request_context():
+ return request.host_url.rstrip("/")
+
+ return resolve_HXOPS_TOOLS_API_BASE(config=cfg)
diff --git a/backend/app/services/oa_sqlserver.py b/backend/app/services/oa_sqlserver.py
index 6ce3d61a..8fb349a4 100644
--- a/backend/app/services/oa_sqlserver.py
+++ b/backend/app/services/oa_sqlserver.py
@@ -1,8 +1,49 @@
+"""
+backend/app/services/oa_sqlserver.py
+
+用途:封装 OA SQL Server 的员工检索与组织信息查询能力,供请假代理人/申请人选择等场景复用。
+依赖:pyodbc、OA ecology 数据库视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
+逻辑:通过只读 SQL 查询返回 OA 用户与组织字段;对于 OA 中夹带的多语言包装串,统一在服务层清洗成可直接展示的中文文本。
+"""
+
import os
+import re
+
import pyodbc
from flask import current_app
+_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
+ r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
+)
+
class OASQLServerService:
+ @staticmethod
+ def _normalize_oa_text(value) -> str:
+ """
+ 清洗 OA 多语言包装字段。
+
+ AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
+ `~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
+ 可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
+
+ Args:
+ value: 来自 OA SQL Server 的原始字段值。
+
+ Returns:
+ 优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
+ """
+ text = str(value or "").strip()
+ if not text:
+ return ""
+ matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
+ if not matched:
+ return text
+ simplified, english, traditional = (
+ segment.strip().strip("`").strip()
+ for segment in matched.groups()
+ )
+ return simplified or english or traditional or text
+
@staticmethod
def _pick_driver():
drivers = pyodbc.drivers()
@@ -96,13 +137,13 @@ class OASQLServerService:
items.append({
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
- "name": str(row.lastname) if row.lastname is not None else "",
- "jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
+ "name": cls._normalize_oa_text(row.lastname),
+ "jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
- "departmentName": str(row.departmentname).strip() if row.departmentname else "",
- "subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
- "jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
+ "departmentName": cls._normalize_oa_text(row.departmentname),
+ "subcompanyName": cls._normalize_oa_text(row.subcompanyname),
+ "jobtitleName": cls._normalize_oa_text(row.jobtitlename),
})
return {
@@ -145,13 +186,13 @@ class OASQLServerService:
return {
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
- "name": str(row.lastname) if row.lastname is not None else "",
- "jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
+ "name": cls._normalize_oa_text(row.lastname),
+ "jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
- "departmentName": str(row.departmentname).strip() if row.departmentname else "",
- "subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
- "jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
+ "departmentName": cls._normalize_oa_text(row.departmentname),
+ "subcompanyName": cls._normalize_oa_text(row.subcompanyname),
+ "jobtitleName": cls._normalize_oa_text(row.jobtitlename),
}
finally:
try:
@@ -171,7 +212,7 @@ class OASQLServerService:
[department_id.strip()],
)
row = cursor.fetchone()
- return str(row.departmentname).strip() if row and row.departmentname else ""
+ return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
finally:
try:
cursor.close()
@@ -190,7 +231,7 @@ class OASQLServerService:
[subcompany_id.strip()],
)
row = cursor.fetchone()
- return str(row.subcompanyname).strip() if row and row.subcompanyname else ""
+ return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
finally:
try:
cursor.close()
@@ -209,7 +250,7 @@ class OASQLServerService:
[jobtitle_id.strip()],
)
row = cursor.fetchone()
- return str(row.jobtitlename).strip() if row and row.jobtitlename else ""
+ return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
finally:
try:
cursor.close()
diff --git a/backend/app/services/schedule/file_asset_cleanup_job.py b/backend/app/services/schedule/file_asset_cleanup_job.py
new file mode 100644
index 00000000..2f7192cc
--- /dev/null
+++ b/backend/app/services/schedule/file_asset_cleanup_job.py
@@ -0,0 +1,26 @@
+"""
+backend/app/services/schedule/file_asset_cleanup_job.py
+
+用途:排程平台 Job —— 清理过期未引用的临时文件资产。
+依赖:file_assets.cleanup。
+逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用。
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from app.services.file_assets.cleanup import cleanup_expired_temporary_assets
+
+
+def run_file_asset_cleanup_schedule(task: Any, run: Any) -> dict[str, Any]:
+ """
+ 执行临时文件资产 TTL 清理。
+ Args:
+ task: ScheduleTask。
+ run: ScheduleRun。
+ Returns:
+ 清理统计。
+ """
+ _ = task, run
+ return cleanup_expired_temporary_assets(limit=200)
diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py
index 36b519bb..0757a47b 100644
--- a/backend/app/services/schedule/job_registry.py
+++ b/backend/app/services/schedule/job_registry.py
@@ -129,6 +129,7 @@ def run_platform_job(
def _register_builtin_platform_jobs() -> None:
"""模块加载时注册内置平台 Job(含参数契约)。"""
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
+ from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
@@ -191,6 +192,14 @@ def _register_builtin_platform_jobs() -> None:
description="同步 PLM 固资快照至本地 manifest。",
category="assets",
))
+ register_platform_job(PlatformJobDefinition(
+ key="file-asset-cleanup",
+ label="临时文件资产清理",
+ label_key="admin.schedule.form.platformJobFileAssetCleanup",
+ handler=run_file_asset_cleanup_schedule,
+ description="按 TTL 清理未建单、未引用的临时 FileAsset 与关联 intake,并删除私有 MinIO 对象。",
+ category="files",
+ ))
_register_builtin_platform_jobs()
diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py
index 607e3cc4..c7dba7d4 100644
--- a/backend/app/services/schedule/query_service.py
+++ b/backend/app/services/schedule/query_service.py
@@ -9,6 +9,7 @@ from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
+from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
@@ -59,6 +60,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
def serialize_run(run: ScheduleRun) -> dict:
+ summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
return {
'id': run.id,
'run_no': run.run_no,
@@ -82,6 +84,7 @@ def serialize_run(run: ScheduleRun) -> dict:
'error_message': run.error_message,
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
+ 'inventory_raw_zip_available': inventory_raw_zip_available_from_summary(summary),
'kb_sync_status': run.kb_sync_status,
'kb_group_id': run.kb_group_id,
'kb_document_id': run.kb_document_id,
diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py
index 7cfac3c3..a665a8a1 100644
--- a/backend/app/services/schedule/scheduler_service.py
+++ b/backend/app/services/schedule/scheduler_service.py
@@ -76,6 +76,51 @@ _WECOM_STATUS_LABEL = {
_WECOM_EVENT_TYPE = 'schedule_completed'
+def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) -> dict[str, Any]:
+ """
+ 构造排程企微 textcard 跳转 query 参数。
+
+ 核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 与 download 意图,
+ 由前端在登录后自动触发一次下载,失败时保留手动下载入口。
+ """
+ from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
+
+ summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
+ params: dict[str, Any] = {
+ 'task_id': task.id,
+ 'run_id': run.id,
+ }
+ if inventory_raw_zip_available_from_summary(summary):
+ params['raw_zip'] = '1'
+ params['download'] = 'inventory_raw_zip'
+ return params
+
+
+def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
+ """
+ 组装排程完成企微 textcard 正文。
+
+ 核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
+ 有原始库存归档时提示点击卡片进入 HXOPS 并在登录后自动下载(URL 仅放 jump_url,不写进正文)。
+ """
+ status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
+ skipped_count = int(run.skipped_count or 0)
+ description = (
+ f'执行单号: {run.run_no}\n'
+ f'状态: {status_label}\n'
+ f'总数: {run.total_count} 成功: {run.success_count} '
+ f'跳过: {skipped_count} 失败: {run.failed_count}'
+ )
+ summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
+ if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
+ description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
+ from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
+
+ if inventory_raw_zip_available_from_summary(summary):
+ description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
+ return description
+
+
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
from app.services.wecom_notify import (
upload_wecom_temp_media,
@@ -104,16 +149,8 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
run.wecom_notify_error = 'no wecom_userid bound users in notify list'
return
- status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
title = f'排程执行结果: {task.name}'
- description = (
- f'执行单号: {run.run_no}\n'
- f'状态: {status_label}\n'
- f'总数: {run.total_count} 成功: {run.success_count} 失败: {run.failed_count}'
- )
- summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
- if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
- description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
+ jump_params = _build_schedule_run_wecom_jump_params(task, run)
media_id = None
if run.excel_file_data and run.excel_file_name:
@@ -125,12 +162,26 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
run.run_no, exc,
)
+ raw_zip_media_id = None
+ raw_zip_file_name = None
+ try:
+ from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
+
+ raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run)
+ raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name)
+ except Exception as exc:
+ current_app.logger.info(
+ '[wecom-schedule] raw inventory zip media skipped for run %s: %s',
+ run.run_no, exc,
+ )
+
textcard_ok_count = 0
errors = []
for u in wecom_users:
trace_id = uuid.uuid4().hex
- jump_url = _build_jump_url('/workspace', trace_id, {'tab': 'schedule-runs'})
+ jump_url = _build_jump_url('/admin/schedules', trace_id, jump_params)
+ description = _build_schedule_run_wecom_description(run)
try:
audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id)
@@ -163,6 +214,22 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
except Exception as exc:
errors.append(f'{u.real_name or u.username}: file exception={exc}')
+ if raw_zip_media_id:
+ try:
+ raw_zip_audit = _create_audit(
+ f'{_WECOM_EVENT_TYPE}_inventory_raw_zip', u,
+ title, f'[原始库存包] {raw_zip_file_name}', uuid.uuid4().hex,
+ )
+ raw_zip_data = send_wecom_file_message(u.wecom_userid, raw_zip_media_id)
+ if raw_zip_data.get('errcode') == 0:
+ raw_zip_audit.status = 'sent'
+ else:
+ raw_zip_audit.error_code = str(raw_zip_data.get('errcode'))
+ raw_zip_audit.error_message = str(raw_zip_data.get('errmsg', 'unknown'))[:255]
+ errors.append(f'{u.real_name or u.username}: raw zip errcode={raw_zip_data.get("errcode")}')
+ except Exception as exc:
+ errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
+
if textcard_ok_count > 0:
run.wecom_notified = True
run.wecom_notified_at = datetime.utcnow()
@@ -605,8 +672,33 @@ def start_scheduler(app):
recovered_awaiting,
)
+ from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
+ recover_pending_rpa_callback_cleanup_jobs,
+ )
+
+ cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
+ if cleanup_count:
+ current_app.logger.info(
+ "[schedule-worker] processed %d RPA callback cleanup job(s) on startup",
+ cleanup_count,
+ )
+ if cleanup_warnings:
+ current_app.logger.warning(
+ "[schedule-worker] RPA callback cleanup warnings: %s",
+ "; ".join(cleanup_warnings[:5]),
+ )
+
+ from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
+ maybe_alert_rpa_worker_status(force=True)
+
while True:
try:
+ from app.services.shipping_notice.rpa_worker_heartbeat_alert import (
+ maybe_alert_rpa_worker_status,
+ )
+
+ maybe_alert_rpa_worker_status()
+
now = utc_now_naive()
due_tasks = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
diff --git a/backend/app/services/schedule/shipping_inventory_rpa_archive.py b/backend/app/services/schedule/shipping_inventory_rpa_archive.py
new file mode 100644
index 00000000..7d2a3b72
--- /dev/null
+++ b/backend/app/services/schedule/shipping_inventory_rpa_archive.py
@@ -0,0 +1,269 @@
+"""
+backend/app/services/schedule/shipping_inventory_rpa_archive.py
+
+用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)。
+依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
+逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
+ query_service 只读 summary;api/schedule/runs 按 raw_inventory_zip_path send_file。
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import zipfile
+from pathlib import Path
+from typing import Any
+
+from flask import current_app
+
+from app import db
+from app.core.errors import NotFoundError
+from app.models import ScheduleRun, ShippingInventoryFile
+from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
+
+_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
+
+_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
+ "raw_inventory_zip_available": False,
+ "raw_inventory_zip_path": None,
+ "raw_inventory_file_count": 0,
+ "raw_inventory_file_nos": [],
+ "raw_inventory_zip_size": 0,
+}
+
+
+def get_inventory_archive_dir() -> str:
+ """返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
+ archive_dir = Path(
+ current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
+ if current_app
+ else ""
+ )
+ if not str(archive_dir):
+ from app.core.config.settings import Config
+
+ archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
+ archive_dir.mkdir(parents=True, exist_ok=True)
+ return str(archive_dir)
+
+
+def inventory_raw_zip_download_name(run_no: str) -> str:
+ """浏览器下载时使用的 ZIP 文件名。"""
+ return f"inventory-rpa-raw-{run_no}.zip"
+
+
+def _inventory_raw_zip_archive_path(run_no: str) -> Path:
+ """磁盘归档路径:/.zip。"""
+ return Path(get_inventory_archive_dir()) / f"{run_no}.zip"
+
+
+def _api_response_created(run: ScheduleRun) -> list[dict[str, Any]]:
+ """从 run.api_response_json 提取 created 列表。"""
+ api_resp = run.api_response_json if isinstance(run.api_response_json, dict) else {}
+ created = api_resp.get("created")
+ if not isinstance(created, list):
+ return []
+ return [item for item in created if isinstance(item, dict)]
+
+
+def _normalize_created_items(created: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
+ """过滤并规范化 created 列表。"""
+ if not isinstance(created, list):
+ return []
+ return [item for item in created if isinstance(item, dict)]
+
+
+def _iter_packable_inventory_files(
+ run: ScheduleRun,
+ *,
+ created: list[dict[str, Any]] | None = None,
+):
+ """
+ 遍历可实际打包的库存快照。
+
+ 核心逻辑:需存在 ShippingInventoryFile 且 storage_path 指向可读文件。
+
+ Yields:
+ tuple[dict, ShippingInventoryFile, Path]: created 项、快照记录、可读路径。
+ """
+ if not is_shipping_inventory_rpa_task(getattr(run, "task", None)):
+ return
+
+ items = _normalize_created_items(created) if created is not None else _api_response_created(run)
+ for item in items:
+ inventory_file_no = str(item.get("inventory_file_no") or "").strip()
+ if not inventory_file_no:
+ continue
+
+ inv_file = (
+ db.session.query(ShippingInventoryFile)
+ .filter(ShippingInventoryFile.inventory_file_no == inventory_file_no)
+ .first()
+ )
+ if not inv_file:
+ continue
+
+ storage_path = Path(str(inv_file.storage_path or "").strip())
+ if not storage_path.is_file():
+ continue
+
+ yield item, inv_file, storage_path
+
+
+def inventory_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
+ """
+ 从 response_summary_json 读取原始库存 ZIP 是否可下载。
+
+ 核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。
+ """
+ if not isinstance(summary, dict):
+ return False
+ return bool(summary.get("raw_inventory_zip_available"))
+
+
+def persist_inventory_rpa_raw_zip_archive(
+ run: ScheduleRun,
+ *,
+ created: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ """
+ finalize 阶段预生成原始库存 ZIP 归档并返回 summary 字段。
+
+ 核心逻辑:收集可读快照 → 写入 /.zip(含 manifest.json);
+ 无可用文件时返回 raw_inventory_zip_available=false。
+
+ Args:
+ run: 库存 RPA ScheduleRun。
+ created: 可选回调 created 列表;finalize 时传入避免依赖尚未落库的 api_response_json。
+
+ Returns:
+ dict: raw_inventory_zip_available / raw_inventory_zip_path / raw_inventory_file_count /
+ raw_inventory_file_nos / raw_inventory_zip_size。
+ """
+ packable_files = list(_iter_packable_inventory_files(run, created=created))
+ if not packable_files:
+ return dict(_EMPTY_ARCHIVE_SUMMARY)
+
+ archive_path = _inventory_raw_zip_archive_path(run.run_no)
+ files_manifest: list[dict[str, str]] = []
+
+ with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
+ for zip_index, (item, inv_file, storage_path) in enumerate(packable_files, start=1):
+ inventory_file_no = str(item.get("inventory_file_no") or "").strip()
+ source_code = str(item.get("source_code") or inv_file.source_code or "").strip()
+ warehouse_id = str(item.get("warehouse_id") or inv_file.warehouse_id or "").strip()
+ entry_name = _build_zip_entry_name(
+ index=zip_index,
+ source_code=source_code,
+ warehouse_id=warehouse_id,
+ inventory_file_no=inventory_file_no,
+ original_suffix=storage_path.suffix or ".xlsx",
+ )
+ archive.write(storage_path, arcname=entry_name)
+ files_manifest.append({
+ "inventory_file_no": inventory_file_no,
+ "source_code": source_code,
+ "warehouse_id": warehouse_id,
+ "file_name": entry_name,
+ "original_file_name": inv_file.source_file_name or storage_path.name,
+ })
+
+ manifest = {
+ "run_no": run.run_no,
+ "total_count": int(run.total_count or 0),
+ "success_count": int(run.success_count or 0),
+ "skipped_count": int(run.skipped_count or 0),
+ "failed_count": int(run.failed_count or 0),
+ "files": files_manifest,
+ }
+ archive.writestr(
+ "manifest.json",
+ json.dumps(manifest, ensure_ascii=False, indent=2),
+ )
+
+ return {
+ "raw_inventory_zip_available": True,
+ "raw_inventory_zip_path": str(archive_path.resolve()),
+ "raw_inventory_file_count": len(files_manifest),
+ "raw_inventory_file_nos": [item["inventory_file_no"] for item in files_manifest],
+ "raw_inventory_zip_size": int(archive_path.stat().st_size),
+ }
+
+
+def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
+ """
+ 校验归档 ZIP 路径是否安全可下载。
+
+ 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
+ """
+ resolved = zip_path.resolve()
+ if resolved.suffix.lower() != ".zip":
+ return False
+ if not resolved.is_file():
+ return False
+
+ archive_dir = Path(get_inventory_archive_dir()).resolve()
+ try:
+ resolved.relative_to(archive_dir)
+ except ValueError:
+ return False
+ return True
+
+
+def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
+ """
+ 解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
+
+ 核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
+ 且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
+
+ Returns:
+ tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
+
+ Raises:
+ NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。
+ """
+ summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
+ if not inventory_raw_zip_available_from_summary(summary):
+ raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
+
+ zip_path_raw = str(summary.get("raw_inventory_zip_path") or "").strip()
+ if not zip_path_raw:
+ raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
+
+ zip_path = Path(zip_path_raw)
+ if not _is_allowed_inventory_archive_path(zip_path):
+ raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
+
+ return zip_path.resolve(), inventory_raw_zip_download_name(run.run_no)
+
+
+def _sanitize_zip_segment(value: str) -> str:
+ """ZIP 内文件名片段安全化,避免路径穿越与非法字符。"""
+ cleaned = re.sub(r"[^\w\-.]+", "_", str(value or "").strip())
+ return cleaned or "unknown"
+
+
+def _build_zip_entry_name(
+ *,
+ index: int,
+ source_code: str,
+ warehouse_id: str,
+ inventory_file_no: str,
+ original_suffix: str,
+) -> str:
+ """生成 ZIP 内单文件条目名(不含目录)。"""
+ base = "_".join(
+ filter(
+ None,
+ [
+ f"{index:03d}",
+ _sanitize_zip_segment(source_code),
+ _sanitize_zip_segment(warehouse_id),
+ _sanitize_zip_segment(inventory_file_no),
+ ],
+ )
+ )
+ suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}"
+ return f"{base}{suffix}"
diff --git a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py b/backend/app/services/schedule/shipping_inventory_rpa_finalize.py
index afa6e189..11975d55 100644
--- a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py
+++ b/backend/app/services/schedule/shipping_inventory_rpa_finalize.py
@@ -33,6 +33,7 @@ _INVENTORY_RPA_HEADER_ORDER = [
"display_name",
"inventory_file_no",
"export_status",
+ "skip_reason",
"error_message",
]
_INVENTORY_RPA_HEADER_LABELS = {
@@ -42,6 +43,7 @@ _INVENTORY_RPA_HEADER_LABELS = {
"display_name": "名称",
"inventory_file_no": "库存快照号",
"export_status": "导出状态",
+ "skip_reason": "跳过原因",
"error_message": "错误原因",
}
@@ -96,16 +98,17 @@ def should_defer_schedule_run_finalization(task: ScheduleTask, step_logs: list |
return is_shipping_inventory_rpa_task(task) and is_awaiting_rpa_callback(step_logs)
-def _compute_run_status(*, total_count: int, success_count: int, failed_count: int) -> str:
+def _compute_run_status(*, total_count: int, success_count: int, failed_count: int, skipped_count: int = 0) -> str:
"""
根据成功/失败数计算排程终态。
- 核心逻辑:须 success_count == total_count 且无失败才算 success;全失败 failed;否则 partial_failed。
+ 核心逻辑:success 与 skipped 都是 RPA 已处理完成;只有 failed 代表系统/导出失败。
"""
if total_count <= 0:
return "failed"
- if success_count >= total_count and failed_count == 0:
+ completed_count = success_count + skipped_count
+ if failed_count == 0 and completed_count >= total_count:
return "success"
- if success_count == 0:
+ if completed_count == 0:
return "failed"
return "partial_failed"
@@ -115,6 +118,7 @@ def _build_finalize_details(
*,
created: list[dict[str, Any]],
failed: list[dict[str, Any]],
+ skipped: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
"""
合并 trigger 阶段 pending 明细与 RPA 回调结果,供 Excel 导出。
@@ -146,8 +150,27 @@ def _build_finalize_details(
"display_name": base.get("display_name"),
"inventory_file_no": item.get("inventory_file_no"),
"export_status": "success",
+ "skip_reason": "",
"error_message": "",
})
+ for item in skipped or []:
+ if not isinstance(item, dict):
+ continue
+ code = str(item.get("source_code") or "").strip()
+ wh = str(item.get("warehouse_id") or "").strip()
+ key = _source_identity_key(code, wh)
+ handled_keys.add(key)
+ base = pending_by_key.get(key, {})
+ details.append({
+ "source_code": code or item.get("source_code"),
+ "site_id": item.get("site_id") or base.get("site_id"),
+ "warehouse_id": wh or base.get("warehouse_id"),
+ "display_name": base.get("display_name"),
+ "inventory_file_no": "",
+ "export_status": "skipped",
+ "skip_reason": str(item.get("skip_reason") or "skipped")[:200],
+ "error_message": str(item.get("message") or item.get("error_message") or "")[:500],
+ })
for item in failed:
if not isinstance(item, dict):
continue
@@ -163,6 +186,7 @@ def _build_finalize_details(
"display_name": base.get("display_name"),
"inventory_file_no": "",
"export_status": "failed",
+ "skip_reason": "",
"error_message": str(item.get("error") or item.get("error_message") or "export failed")[:500],
})
for key, base in pending_by_key.items():
@@ -175,6 +199,7 @@ def _build_finalize_details(
"display_name": base.get("display_name"),
"inventory_file_no": "",
"export_status": "failed",
+ "skip_reason": "",
"error_message": "RPA callback missing",
})
return details
@@ -349,6 +374,7 @@ def finalize_shipping_inventory_schedule_run(
*,
created: list[dict[str, Any]],
failed: list[dict[str, Any]],
+ skipped: list[dict[str, Any]] | None = None,
payload: dict[str, Any] | None = None,
) -> FinalizeScheduleRunResult:
"""
@@ -380,7 +406,13 @@ def finalize_shipping_inventory_schedule_run(
return {"ok": False, "error": "schedule run is not awaiting RPA callback", "schedule_finalize_status": "skipped"}
try:
- return _finalize_shipping_inventory_schedule_run_impl(run, created=created, failed=failed, payload=payload)
+ return _finalize_shipping_inventory_schedule_run_impl(
+ run,
+ created=created,
+ skipped=skipped or [],
+ failed=failed,
+ payload=payload,
+ )
except Exception as exc:
db.session.rollback()
db.session.refresh(run)
@@ -405,6 +437,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
run: ScheduleRun,
*,
created: list[dict[str, Any]],
+ skipped: list[dict[str, Any]],
failed: list[dict[str, Any]],
payload: dict[str, Any] | None,
) -> FinalizeScheduleRunResult:
@@ -415,14 +448,16 @@ def _finalize_shipping_inventory_schedule_run_impl(
raise RuntimeError("schedule task not found")
pending_details = summary.get("pending_details") if isinstance(summary.get("pending_details"), list) else []
- details = _build_finalize_details(pending_details, created=created, failed=failed)
+ details = _build_finalize_details(pending_details, created=created, skipped=skipped, failed=failed)
success_count = sum(1 for item in details if item.get("export_status") == "success")
+ skipped_count = sum(1 for item in details if item.get("export_status") == "skipped")
failed_count = sum(1 for item in details if item.get("export_status") == "failed")
total_count = max(int(run.total_count or 0), len(pending_details), len(details))
status = _compute_run_status(
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
+ skipped_count=skipped_count,
)
finished_at = datetime.utcnow()
@@ -448,6 +483,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
"status": status,
"total_count": total_count,
"success_count": success_count,
+ "skipped_count": skipped_count,
"failed_count": failed_count,
"duration_ms": duration_ms,
},
@@ -470,6 +506,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
"status": "success" if status == "success" else "failed" if status == "failed" else "partial_failed",
"detail": {
"created_count": success_count,
+ "skipped_count": skipped_count,
"failed_count": failed_count,
"rpa_mode": (payload or {}).get("rpa_mode"),
"run_no": (payload or {}).get("run_no"),
@@ -482,16 +519,43 @@ def _finalize_shipping_inventory_schedule_run_impl(
run.status = status
run.total_count = total_count
run.success_count = success_count
+ run.skipped_count = skipped_count
run.failed_count = failed_count
run.step_logs = step_logs
run.api_response_json = {
"run_no": (payload or {}).get("run_no"),
"rpa_mode": (payload or {}).get("rpa_mode"),
"created": created,
+ "skipped": skipped,
"failed": failed,
}
+
+ archive_summary: dict[str, Any] = {
+ "raw_inventory_zip_available": False,
+ "raw_inventory_zip_path": None,
+ "raw_inventory_file_count": 0,
+ "raw_inventory_file_nos": [],
+ "raw_inventory_zip_size": 0,
+ }
+ try:
+ from app.services.schedule.shipping_inventory_rpa_archive import persist_inventory_rpa_raw_zip_archive
+
+ archive_summary = persist_inventory_rpa_raw_zip_archive(run, created=created)
+ except Exception as archive_exc:
+ if current_app:
+ current_app.logger.error(
+ "[schedule-run] inventory RPA raw zip archive failed run_no=%s: %s",
+ run.run_no,
+ archive_exc,
+ exc_info=True,
+ )
+
run.response_summary_json = {
"awaiting_rpa": False,
+ "total_count": total_count,
+ "success_count": success_count,
+ "skipped_count": skipped_count,
+ "failed_count": failed_count,
"errors": errors[:20],
"schedule_type": task.schedule_type,
"platform_api_path": task.platform_api_path,
@@ -501,9 +565,11 @@ def _finalize_shipping_inventory_schedule_run_impl(
"excel_failed": not excel_export_ok,
"rpa_finalize": {
"created_count": success_count,
+ "skipped_count": skipped_count,
"failed_count": failed_count,
"excel_failed": not excel_export_ok,
},
+ **archive_summary,
}
run.error_message = "; ".join(errors[:3]) if errors else None
run.excel_file_data = file_data
@@ -541,10 +607,11 @@ def _finalize_shipping_inventory_schedule_run_impl(
if current_app:
current_app.logger.info(
- "[schedule-run] run_no=%s finalized after RPA callback status=%s success=%d failed=%d",
+ "[schedule-run] run_no=%s finalized after RPA callback status=%s success=%d skipped=%d failed=%d",
run.run_no,
status,
success_count,
+ skipped_count,
failed_count,
)
return {
@@ -552,5 +619,6 @@ def _finalize_shipping_inventory_schedule_run_impl(
"schedule_finalize_status": "ok",
"run_status": status,
"success_count": success_count,
+ "skipped_count": skipped_count,
"failed_count": failed_count,
}
diff --git a/backend/app/services/schedule/shipping_inventory_rpa_job.py b/backend/app/services/schedule/shipping_inventory_rpa_job.py
index 8482a9a9..162dc34f 100644
--- a/backend/app/services/schedule/shipping_inventory_rpa_job.py
+++ b/backend/app/services/schedule/shipping_inventory_rpa_job.py
@@ -14,10 +14,12 @@ from datetime import datetime
from typing import Any
from app import db
+from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
+from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -137,19 +139,34 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
return 0, 0, 0, 1, [], [message], step_logs
run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
- trigger_path = write_inventory_export_batch_trigger(
- run_no,
- sources,
- payload={
- "trigger_type": "scheduled",
- "schedule_run_id": run.id,
- "schedule_task_id": task.id,
- },
- )
+ try:
+ trigger_path = write_inventory_export_batch_trigger(
+ run_no,
+ sources,
+ payload={
+ "trigger_type": "scheduled",
+ "schedule_run_id": run.id,
+ "schedule_task_id": task.id,
+ },
+ )
+ except ServiceUnavailableError as exc:
+ message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
+ detail_message = str((exc.details or {}).get("detail_message") or message)
+ step_logs.append({
+ "step": "shipping_inventory_rpa",
+ "status": "failed",
+ "detail": {
+ "message": message,
+ "detail_message": detail_message,
+ "error_code": exc.code,
+ "reasons": (exc.details or {}).get("reasons") or [],
+ },
+ })
+ return len(sources), 0, len(sources), 0, [], [detail_message], step_logs
if not trigger_path:
message = "inventory RPA trigger dir not configured"
step_logs.append({"step": "shipping_inventory_rpa", "status": "failed", "detail": {"message": message}})
- return len(sources), 0, 0, len(sources), [], [message], step_logs
+ return len(sources), 0, len(sources), 0, [], [message], step_logs
run.api_request_json = {
"run_no": run_no,
diff --git a/backend/app/services/shipping_notice/attachment_integrity.py b/backend/app/services/shipping_notice/attachment_integrity.py
new file mode 100644
index 00000000..fc014d61
--- /dev/null
+++ b/backend/app/services/shipping_notice/attachment_integrity.py
@@ -0,0 +1,82 @@
+"""
+services/shipping_notice/attachment_integrity.py
+
+用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。
+依赖:仅标准库(与 structured_result_json / parse_summary 形状对齐)。
+逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用;
+ BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致
+ (由 tests 校验两端前缀集合)。
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+# 顶层 / 附件行 warnings 前缀:出现任一即视为不完整(与前端门禁契约对齐)
+BLOCKING_WARNING_PREFIXES: tuple[str, ...] = (
+ 'eml_nesting_depth_exceeded:',
+ 'eml_attachment_limit_exceeded:',
+ 'eml_total_attachment_size_exceeded:',
+ 'eml_nested_message_unreadable',
+ 'eml_attachment_text_budget_exhausted:',
+ 'eml_attachment_text_truncated:',
+ 'notice_text_truncated:',
+)
+
+_INCOMPLETE_ATTACHMENT_STATUSES = frozenset({'failed', 'empty', 'skipped'})
+
+
+def is_blocking_warning(text: str) -> bool:
+ """
+ 判定单条 warning 是否为完整性阻断项。
+
+ Args:
+ text: warning 原文。
+
+ Returns:
+ True 表示该警告会使 Intake 被视为附件解析不完整。
+ """
+ normalized = str(text or '')
+ return any(normalized.startswith(prefix) for prefix in BLOCKING_WARNING_PREFIXES)
+
+
+def is_attachment_parse_incomplete(structured: dict[str, Any] | None) -> bool:
+ """
+ 判定 structured_result_json / parse_summary 是否存在未完整解析的附件。
+
+ 核心逻辑:阻断警告(深度/数量/总大小/不可读嵌套/文本预算或截断)、
+ attachment_count > 已登记数、或任一行 parse_status 为 failed/empty/skipped
+ 均视为不完整;duplicate 仅去重提示,不阻断。
+
+ Args:
+ structured: Intake 的 structured_result_json 或 API 下发的 parse_summary。
+
+ Returns:
+ True 表示不可用该 Intake 直接建批,应拒绝或允许重试解析。
+ """
+ if not isinstance(structured, dict):
+ return False
+
+ warnings = structured.get('warnings') or []
+ for item in warnings:
+ if is_blocking_warning(str(item or '')):
+ return True
+
+ rows = structured.get('attachments') or []
+ if not isinstance(rows, list):
+ rows = []
+ total = int(structured.get('attachment_count') or 0)
+ if total > len(rows):
+ return True
+
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ status = str(row.get('parse_status') or '').strip().lower()
+ if status in _INCOMPLETE_ATTACHMENT_STATUSES:
+ return True
+ for item in row.get('warnings') or []:
+ if is_blocking_warning(str(item or '')):
+ return True
+
+ return False
diff --git a/backend/app/services/shipping_notice/batch_create_idempotency.py b/backend/app/services/shipping_notice/batch_create_idempotency.py
new file mode 100644
index 00000000..f3057bdd
--- /dev/null
+++ b/backend/app/services/shipping_notice/batch_create_idempotency.py
@@ -0,0 +1,310 @@
+"""
+services/shipping_notice/batch_create_idempotency.py
+
+用途:发货通知建单幂等键标准化、批次回查与跨请求文件内容重复校验。
+依赖:models.ShippingBatch/ShippingTask、query_service、tool_response 序列化。
+逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingTask.idempotency_key(货代上传幂等)语义分离。
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+import zlib
+from typing import Any, Iterable
+
+from sqlalchemy import text
+from sqlalchemy.exc import IntegrityError
+
+from app import db
+from app.core.errors import AppError, ConflictError
+from app.models import ShippingBatch, ShippingTask
+from app.services.shipping_notice.query_service import (
+ get_focus_task_for_batch,
+ list_sorted_batch_tasks,
+ serialize_batch_for_tool,
+ serialize_task_summary,
+)
+
+logger = logging.getLogger(__name__)
+
+_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128
+_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$")
+
+_TERMINAL_TASK_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
+
+
+def normalize_create_idempotency_key(raw: str | None) -> str | None:
+ """
+ 标准化建单幂等键:去首尾空格、校验长度与安全字符集。
+
+ Args:
+ raw: HTTP Header / payload 中的原始幂等键。
+
+ Returns:
+ 标准化后的幂等键;空值返回 None。
+
+ Raises:
+ ValidationError: 键非空但格式或长度不合法(SHIPPING.IDEMPOTENCY_KEY_INVALID)。
+ """
+ value = str(raw or "").strip()
+ if not value:
+ return None
+ if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN:
+ raise AppError(
+ code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
+ message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符",
+ http_status=400,
+ )
+ if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value):
+ raise AppError(
+ code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
+ message="幂等键仅允许字母、数字及 . _ : - 字符",
+ http_status=400,
+ )
+ return value
+
+
+def warn_missing_create_idempotency_key(*, source: str) -> None:
+ """兼容期记录缺少建单幂等键的告警,不阻断旧客户端。"""
+ logger.warning(
+ "shipping batch create without create_idempotency_key source=%s",
+ source,
+ )
+
+
+def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]]) -> str:
+ """
+ 根据 notice_items 的 source_content_hash 计算稳定文件集合指纹。
+
+ 核心逻辑:排序后拼接哈希再 SHA-256,与批次 process_summary_json.create_content_fingerprint 对齐。
+ """
+ hashes = sorted(
+ {
+ str(item.get("source_content_hash") or "").strip().lower()
+ for item in notice_items
+ if isinstance(item, dict) and str(item.get("source_content_hash") or "").strip()
+ }
+ )
+ if not hashes:
+ return ""
+ return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
+
+
+def batch_stored_content_fingerprint(batch: ShippingBatch) -> str | None:
+ """
+ 读取批次已持久化的文件集合指纹;历史批次无字段时从任务 source_content_hash 推导。
+ """
+ summary = batch.process_summary_json if isinstance(batch.process_summary_json, dict) else {}
+ stored = str(summary.get("create_content_fingerprint") or "").strip().lower()
+ if stored:
+ return stored
+ tasks = list_sorted_batch_tasks(batch)
+ hashes = sorted(
+ {
+ str(task.source_content_hash or "").strip().lower()
+ for task in tasks
+ if str(task.source_content_hash or "").strip()
+ }
+ )
+ if not hashes:
+ return None
+ return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
+
+
+def assert_idempotent_batch_content_matches(
+ batch: ShippingBatch,
+ notice_items: list[dict[str, Any]],
+) -> None:
+ """
+ 校验幂等键命中时,本次文件集合与已有批次一致。
+
+ Raises:
+ ConflictError: 文件集合不一致(SHIPPING.BATCH_IDEMPOTENCY_CONFLICT)。
+ """
+ stored_fp = batch_stored_content_fingerprint(batch)
+ request_fp = compute_notice_items_content_fingerprint(notice_items)
+ if not stored_fp or not request_fp:
+ return
+ if stored_fp == request_fp:
+ return
+ raise ConflictError(
+ "建单幂等键对应的文件集合与本次上传不一致,请更换幂等键后重试",
+ code="SHIPPING.BATCH_IDEMPOTENCY_CONFLICT",
+ details={
+ "batch_no": batch.batch_no,
+ "stored_content_fingerprint": stored_fp,
+ "request_content_fingerprint": request_fp,
+ },
+ )
+
+
+def _advisory_lock_key(*parts: str) -> int:
+ raw = "|".join(parts)
+ return zlib.crc32(raw.encode("utf-8")) & 0x7FFFFFFF
+
+
+def acquire_notice_create_locks(user_id: int, content_hashes: Iterable[str]) -> None:
+ """
+ 在建单事务内获取 PostgreSQL 事务级 advisory lock,串行化同用户建单与活跃文件去重。
+
+ 核心逻辑:SQLite 等测试库跳过;生产 PostgreSQL 对 user 级与每个 content_hash 加锁。
+ """
+ bind = db.session.get_bind()
+ if bind.dialect.name != "postgresql":
+ return
+ lock_keys = {_advisory_lock_key(str(user_id), "shipping-notice-create")}
+ for content_hash in content_hashes:
+ normalized = str(content_hash or "").strip().lower()
+ if normalized:
+ lock_keys.add(_advisory_lock_key(str(user_id), "shipping-notice-hash", normalized))
+ for lock_key in sorted(lock_keys):
+ db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
+
+
+def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> ShippingBatch | None:
+ """
+ 按用户与建单幂等键查找已有批次。
+
+ Args:
+ user_id: 当前用户 ID。
+ create_idempotency_key: 已标准化的建单幂等键。
+
+ Returns:
+ 匹配的 ShippingBatch 或 None。
+ """
+ key = str(create_idempotency_key or "").strip()
+ if not key:
+ return None
+ return (
+ ShippingBatch.query.filter_by(user_id=user_id, create_idempotency_key=key).first()
+ )
+
+
+def build_existing_batch_tool_response(batch: ShippingBatch, *, user_id: int) -> dict[str, Any]:
+ """
+ 将已有批次序列化为 create_batch_tasks 兼容的 Tool 响应结构。
+
+ 核心逻辑:不创建新任务、不启动编排器;供幂等重放与唯一约束竞争回查共用。
+ """
+ tasks = list_sorted_batch_tasks(batch)
+ focus_task = get_focus_task_for_batch(batch.batch_no, user_id)
+ created_tasks = [
+ {
+ "task_id": task.task_no,
+ "batch_index": task.batch_index,
+ "parse_status": "deferred",
+ }
+ for task in tasks
+ ]
+ data: dict[str, Any] = {
+ "batch": serialize_batch_for_tool(batch),
+ "tasks": created_tasks,
+ "orchestrator_started": False,
+ }
+ if focus_task:
+ data["focus_task"] = serialize_task_summary(focus_task)
+ return {
+ "status": "ok",
+ "batch_no": batch.batch_no,
+ "message": f"已恢复此前创建的批次 {batch.batch_no}",
+ "data": data,
+ "idempotent_replay": True,
+ }
+
+
+def assert_no_exact_duplicate_notices(
+ user_id: int,
+ notice_items: list[dict[str, Any]],
+ *,
+ exclude_batch_id: int | None = None,
+) -> None:
+ """
+ 校验跨请求是否存在相同文件内容且仍在进行中的任务。
+
+ 核心逻辑:须在 acquire_notice_create_locks 之后调用,避免不同幂等键并发重复建单。
+ 合法的 duplicate_resolution_type=revision|force_create 跳过哈希阻断(业务 Gate 已授权)。
+
+ Raises:
+ ConflictError: SHIPPING.NOTICE_EXACT_DUPLICATE,details 含已有 task_no。
+ """
+ hashes: list[tuple[str, str]] = []
+ for item in notice_items:
+ if not isinstance(item, dict):
+ continue
+ resolution_type = str(item.get("duplicate_resolution_type") or "").strip().lower()
+ # 修订/强制新建:已由 intake Gate 校验决策与权限,允许同 content_hash 再建
+ if resolution_type in {"revision", "force_create"}:
+ continue
+ content_hash = str(item.get("source_content_hash") or "").strip().lower()
+ if not content_hash:
+ continue
+ filename = str(item.get("source_file_name") or "").strip() or "notice"
+ hashes.append((content_hash, filename))
+ if not hashes:
+ return
+
+ for content_hash, _filename in hashes:
+ query = ShippingTask.query.filter(
+ ShippingTask.user_id == user_id,
+ ShippingTask.source_content_hash == content_hash,
+ ShippingTask.process_status.notin_(list(_TERMINAL_TASK_STATUSES)),
+ )
+ if exclude_batch_id is not None:
+ query = query.filter(
+ (ShippingTask.batch_id.is_(None)) | (ShippingTask.batch_id != exclude_batch_id)
+ )
+ existing = query.order_by(ShippingTask.id.desc()).first()
+ if existing:
+ raise ConflictError(
+ f"该文件已存在于进行中的任务 {existing.task_no}",
+ code="SHIPPING.NOTICE_EXACT_DUPLICATE",
+ details={
+ "task_no": existing.task_no,
+ "source_content_hash": content_hash,
+ },
+ )
+
+
+def dedupe_notice_items_by_content_hash(notice_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """请求内按 source_content_hash 二次去重,防止绕过 intake 时重复建任务。"""
+ seen: set[str] = set()
+ unique: list[dict[str, Any]] = []
+ for item in notice_items:
+ if not isinstance(item, dict):
+ continue
+ content_hash = str(item.get("source_content_hash") or "").strip().lower()
+ if content_hash:
+ if content_hash in seen:
+ continue
+ seen.add(content_hash)
+ unique.append(item)
+ return unique
+
+
+def handle_batch_create_integrity_error(
+ *,
+ user_id: int,
+ create_idempotency_key: str | None,
+ exc: IntegrityError,
+) -> dict[str, Any] | None:
+ """
+ 捕获批次建单唯一约束竞争,回滚后回查已有批次。
+
+ Returns:
+ 幂等重放响应;无法回查时返回 None,由上层继续抛出原异常。
+ """
+ db.session.rollback()
+ key = str(create_idempotency_key or "").strip()
+ if not key:
+ return None
+ batch = find_batch_by_create_idempotency(user_id, key)
+ if not batch:
+ return None
+ logger.info(
+ "shipping batch create idempotency race resolved batch_no=%s user_id=%s",
+ batch.batch_no,
+ user_id,
+ )
+ return build_existing_batch_tool_response(batch, user_id=user_id)
diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py
new file mode 100644
index 00000000..eea76dd5
--- /dev/null
+++ b/backend/app/services/shipping_notice/batch_from_intakes.py
@@ -0,0 +1,740 @@
+"""
+backend/app/services/shipping_notice/batch_from_intakes.py
+
+用途:从已解析 ShippingNoticeIntake 确认建批的共享编排。
+依赖:batch_from_notices、intake_service、intake_parse_workflow、batch_create_idempotency、
+ attachment_integrity。
+逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块。
+ 幂等以 intake.create_idempotency_key 为准(覆盖混合批次 / 纯 open_existing);
+ 批次 create_idempotency_key + process_summary.request_intake_nos 为兼容回退。
+ 建批传 defer_commit,与 consumed 关联 / 摘要 / 审计同事务提交后再启动编排器。
+ 按 content_hash 去重后 FOR UPDATE 预占 consumed;建批失败须 rollback 预占。
+ parsed 仍须通过附件完整性门禁(与前端 incomplete 规则一致),防止直调 API 绕过。
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.orm.attributes import flag_modified
+
+from app import db
+from app.core.errors import ConflictError, ValidationError
+from app.models import FileAsset, ShippingBatch, ShippingNoticeIntake, ShippingTask
+from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
+from app.services.shipping_notice.batch_create_idempotency import (
+ build_existing_batch_tool_response,
+ find_batch_by_create_idempotency,
+ normalize_create_idempotency_key,
+)
+from app.services.shipping_notice.batch_from_notices import create_shipping_batch_from_notice_items
+from app.services.shipping_notice.duplicate_detection import detect_duplicates_for_intake
+from app.services.shipping_notice.intake_parse_workflow import intake_to_notice_item
+from app.services.shipping_notice.intake_service import mark_intakes_consumed
+from app.services.shipping_notice.tool_common import log_task_event
+
+
+def _batch_intake_nos(batch_id: int) -> set[str]:
+ """
+ 读取批次关联的全部 intake_no 集合。
+
+ 核心逻辑:以 consumed_batch_id 为准(含 content_hash 去重后的附属 intake)。
+ 注意:open_existing 会挂到旧任务批次,不可单独用于混合请求的全量比对。
+ """
+ rows = (
+ db.session.query(ShippingNoticeIntake.intake_no)
+ .filter(ShippingNoticeIntake.consumed_batch_id == int(batch_id))
+ .all()
+ )
+ return {str(row[0]).strip().upper() for row in rows if row and row[0]}
+
+
+def _stamp_intakes_create_idempotency(
+ intakes: list[ShippingNoticeIntake],
+ create_idempotency_key: str | None,
+) -> None:
+ """
+ 将建单幂等键写回本请求涉及的全部 intake。
+
+ 核心逻辑:混合批次里 open_existing 不会挂入新建批次,须靠 intake 键闭环重放。
+ """
+ key = normalize_create_idempotency_key(create_idempotency_key)
+ if not key:
+ return
+ now = datetime.utcnow()
+ for intake in intakes:
+ intake.create_idempotency_key = key
+ intake.updated_at = now
+
+
+def _opened_existing_payload(intake: ShippingNoticeIntake) -> dict[str, Any]:
+ """从已消费 intake 组装 open_existing 投影。"""
+ task_no = None
+ if intake.consumed_task_id:
+ task = db.session.get(ShippingTask, int(intake.consumed_task_id))
+ if task is not None:
+ task_no = task.task_no
+ if not task_no:
+ task_no = str(intake.duplicate_target_task_no or '').strip().upper() or None
+ return {
+ 'intake_no': intake.intake_no,
+ 'task_no': task_no,
+ 'batch_no': None,
+ }
+
+
+def _is_open_existing_intake(intake: ShippingNoticeIntake) -> bool:
+ """判断 intake 是否为打开已有任务决策。"""
+ return str(intake.duplicate_resolution or '').strip().lower() == 'open_existing'
+
+
+def _resolve_create_batch_for_replay(
+ *,
+ user_id: int,
+ create_intakes: list[ShippingNoticeIntake],
+ create_idempotency_key: str | None,
+) -> ShippingBatch:
+ """
+ 为含建单意图的 intake 解析所属新批次(含断点恢复)。
+
+ 核心逻辑:优先 consumed_batch_id → 批次幂等键 → 任务 source_intake_id 反查;
+ 找到后回填缺失的 consumed_*,避免半成品重放成「未创建新批次」。
+ """
+ batch: ShippingBatch | None = None
+ for intake in create_intakes:
+ if intake.consumed_batch_id is None:
+ continue
+ candidate = db.session.get(ShippingBatch, int(intake.consumed_batch_id))
+ if candidate is not None and int(candidate.user_id or 0) == int(user_id):
+ batch = candidate
+ break
+
+ key = normalize_create_idempotency_key(create_idempotency_key)
+ if batch is None and key:
+ batch = find_batch_by_create_idempotency(user_id, key)
+
+ if batch is None:
+ intake_ids = [int(item.id) for item in create_intakes]
+ task = (
+ db.session.query(ShippingTask)
+ .filter(
+ ShippingTask.user_id == int(user_id),
+ ShippingTask.source_intake_id.in_(intake_ids),
+ )
+ .order_by(ShippingTask.id.desc())
+ .first()
+ )
+ if task is not None and task.batch_id is not None:
+ batch = db.session.get(ShippingBatch, int(task.batch_id))
+
+ if batch is None or int(batch.user_id or 0) != int(user_id):
+ raise ConflictError(
+ '建单结果未完整关联,请使用相同幂等键重试',
+ code='SHIPPING.BATCH_CREATE_INCOMPLETE',
+ details={
+ 'intake_nos': [item.intake_no for item in create_intakes],
+ 'create_idempotency_key': key,
+ },
+ )
+
+ tasks = (
+ db.session.query(ShippingTask)
+ .filter(ShippingTask.batch_id == int(batch.id))
+ .order_by(ShippingTask.batch_index.asc(), ShippingTask.id.asc())
+ .all()
+ )
+ task_by_intake_id = {
+ int(task.source_intake_id): task
+ for task in tasks
+ if task.source_intake_id is not None
+ }
+ now = datetime.utcnow()
+ dirty = False
+ for intake in create_intakes:
+ task = task_by_intake_id.get(int(intake.id))
+ if task is None:
+ continue
+ if intake.consumed_batch_id != int(batch.id) or intake.consumed_task_id != int(task.id):
+ intake.consumed_batch_id = int(batch.id)
+ intake.consumed_task_id = int(task.id)
+ intake.updated_at = now
+ dirty = True
+ if intake.parse_status != 'consumed' or intake.consumed_at is None:
+ intake.parse_status = 'consumed'
+ intake.consumed_at = intake.consumed_at or now
+ intake.updated_at = now
+ dirty = True
+ if dirty:
+ db.session.commit()
+ return batch
+
+
+def _build_replay_from_intakes(
+ *,
+ user_id: int,
+ intakes: list[ShippingNoticeIntake],
+ create_idempotency_key: str | None = None,
+) -> dict[str, Any]:
+ """
+ 依据已打幂等键的 intake 重建确认响应。
+
+ 核心逻辑:区分 open_existing 与新建批次;建单断点时通过批次/任务反查并回填关联。
+ """
+ opened: list[dict[str, Any]] = []
+ create_intakes: list[ShippingNoticeIntake] = []
+ for intake in intakes:
+ if _is_open_existing_intake(intake):
+ opened.append(_opened_existing_payload(intake))
+ else:
+ create_intakes.append(intake)
+
+ if create_intakes:
+ batch = _resolve_create_batch_for_replay(
+ user_id=user_id,
+ create_intakes=create_intakes,
+ create_idempotency_key=create_idempotency_key
+ or next(
+ (str(item.create_idempotency_key or '') for item in intakes if item.create_idempotency_key),
+ None,
+ ),
+ )
+ result = build_existing_batch_tool_response(batch, user_id=user_id)
+ result['idempotent_replay'] = True
+ if opened:
+ result['opened_existing'] = opened
+ return result
+
+ focus_task_no = opened[0].get('task_no') if opened else None
+ return {
+ 'status': 'ok',
+ 'batch_no': None,
+ 'idempotent_replay': True,
+ 'opened_existing': opened,
+ 'message': '已打开已有任务,未创建新批次',
+ 'data': {
+ 'opened_existing': opened,
+ 'focus_task': {'task_no': focus_task_no} if focus_task_no else None,
+ },
+ }
+
+
+def _try_idempotent_replay(
+ *,
+ user_id: int,
+ create_idempotency_key: str | None,
+ intake_nos: list[str],
+) -> dict[str, Any] | None:
+ """
+ 按 create_idempotency_key 重放确认建单结果。
+
+ 核心逻辑:
+ 1. 优先查 intake.create_idempotency_key(混合 / 纯 open_existing);
+ 2. 回退查 ShippingBatch + process_summary.request_intake_nos(兼容旧数据)。
+ """
+ key = normalize_create_idempotency_key(create_idempotency_key)
+ if not key:
+ return None
+ expected = {str(no).strip().upper() for no in intake_nos}
+
+ stamped = (
+ db.session.query(ShippingNoticeIntake)
+ .filter(
+ ShippingNoticeIntake.user_id == int(user_id),
+ ShippingNoticeIntake.create_idempotency_key == key,
+ )
+ .all()
+ )
+ if stamped:
+ actual = {str(item.intake_no).strip().upper() for item in stamped}
+ if actual != expected:
+ raise ConflictError(
+ '建单幂等键对应接入集合不一致',
+ code='SHIPPING.BATCH_IDEMPOTENCY_CONFLICT',
+ details={
+ 'expected': sorted(expected),
+ 'actual': sorted(actual),
+ 'source': 'intake_create_idempotency_key',
+ },
+ )
+ return _build_replay_from_intakes(
+ user_id=user_id,
+ intakes=stamped,
+ create_idempotency_key=key,
+ )
+
+ existing = find_batch_by_create_idempotency(user_id, key)
+ if existing is None:
+ return None
+ summary = existing.process_summary_json if isinstance(existing.process_summary_json, dict) else {}
+ stored = summary.get('request_intake_nos')
+ if isinstance(stored, list) and stored:
+ actual = {str(item or '').strip().upper() for item in stored if str(item or '').strip()}
+ else:
+ # 历史纯建批路径:仅有新建批次上的 intake
+ actual = _batch_intake_nos(int(existing.id))
+ if actual != expected:
+ raise ConflictError(
+ '建单幂等键对应批次的接入集合不一致',
+ code='SHIPPING.BATCH_IDEMPOTENCY_CONFLICT',
+ details={
+ 'batch_no': existing.batch_no,
+ 'expected': sorted(expected),
+ 'actual': sorted(actual),
+ 'source': 'batch_fallback',
+ },
+ )
+ result = build_existing_batch_tool_response(existing, user_id=user_id)
+ result['idempotent_replay'] = True
+ return result
+
+
+def _partition_intakes_by_content_hash(
+ ordered: list[tuple[ShippingNoticeIntake, FileAsset]],
+) -> tuple[list[tuple[ShippingNoticeIntake, FileAsset]], dict[str, list[ShippingNoticeIntake]]]:
+ """按 FileAsset.content_hash 去重,保留首次出现的 intake 用于建单。"""
+ seen: set[str] = set()
+ primary: list[tuple[ShippingNoticeIntake, FileAsset]] = []
+ duplicates_by_hash: dict[str, list[ShippingNoticeIntake]] = {}
+ for intake, asset in ordered:
+ content_hash = str(asset.content_hash or '').strip()
+ if not content_hash:
+ primary.append((intake, asset))
+ continue
+ if content_hash in seen:
+ duplicates_by_hash.setdefault(content_hash, []).append(intake)
+ continue
+ seen.add(content_hash)
+ primary.append((intake, asset))
+ return primary, duplicates_by_hash
+
+
+def _assert_duplicate_gate(
+ *,
+ user_id: int,
+ intake: ShippingNoticeIntake,
+ asset: FileAsset,
+) -> dict[str, Any]:
+ """
+ 建单前事务内重跑重复检测并校验用户决策。
+
+ Returns:
+ 最新 duplicate 结果。
+ Raises:
+ ConflictError: 需决策或目标漂移等。
+ """
+ structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
+ business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else None
+ fresh = detect_duplicates_for_intake(
+ intake=intake,
+ asset=asset,
+ business_summary=business_summary,
+ )
+ # 写入最新 matches(不清空已有 resolution,供比对)
+ intake.business_fingerprint = fresh.get('fingerprint')
+ intake.fingerprint_version = fresh.get('fingerprint_version')
+ intake.fingerprint_strength = fresh.get('fingerprint_strength')
+ intake.duplicate_status = str(fresh.get('status') or 'none')
+ intake.duplicate_matches_json = list(fresh.get('matches') or [])
+ intake.duplicate_checked_at = datetime.utcnow()
+
+ blocking = bool(fresh.get('blocking'))
+ resolution = str(intake.duplicate_resolution or '').strip().lower()
+ if blocking and not resolution:
+ raise ConflictError(
+ '检测到重复发货通知,请先选择处理方式',
+ code='SHIPPING_NOTICE.DUPLICATE_RESOLUTION_REQUIRED',
+ details={'intake_no': intake.intake_no, 'duplicate': fresh},
+ )
+ if not blocking:
+ return fresh
+
+ target_no = str(intake.duplicate_target_task_no or '').strip().upper()
+ matches = list(fresh.get('matches') or [])
+ if resolution in {'open_existing', 'create_revision', 'force_create'}:
+ if not target_no or not any(str(m.get('task_no') or '').upper() == target_no for m in matches):
+ raise ConflictError(
+ '目标任务状态已变化,请重新确认',
+ code='SHIPPING_NOTICE.DUPLICATE_TARGET_CHANGED',
+ details={'intake_no': intake.intake_no},
+ )
+ target = (
+ db.session.query(ShippingTask)
+ .filter(ShippingTask.task_no == target_no, ShippingTask.user_id == int(user_id))
+ .first()
+ )
+ if not target:
+ raise ConflictError(
+ '重复目标任务不存在',
+ code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND',
+ )
+ match_row = next((m for m in matches if str(m.get('task_no') or '').upper() == target_no), None)
+ if match_row and str(match_row.get('process_status') or '') != str(target.process_status or ''):
+ raise ConflictError(
+ '目标任务状态已变化,请重新确认',
+ code='SHIPPING_NOTICE.DUPLICATE_TARGET_CHANGED',
+ )
+ if resolution == 'create_revision' and not target:
+ raise ConflictError(
+ '修订目标无效',
+ code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
+ )
+ # 建单时再次校验强制新建权限与原因,防决策后权限被撤或伪造 resolution
+ if resolution == 'force_create':
+ from app.models import User
+ from app.core.errors import ForbiddenError, ValidationError
+ from app.services.shipping_notice.intake_service import can_force_create_shipping_duplicate
+
+ user = db.session.get(User, int(user_id))
+ if not can_force_create_shipping_duplicate(user):
+ raise ForbiddenError(
+ code='SHIPPING_NOTICE.DUPLICATE_OVERRIDE_FORBIDDEN',
+ message='无权强制新建重复发货通知',
+ )
+ if not str(intake.duplicate_resolution_reason or '').strip():
+ raise ValidationError(
+ code='SHIPPING_NOTICE.DUPLICATE_REASON_REQUIRED',
+ message='强制新建必须填写原因',
+ )
+ return fresh
+
+
+def _attach_request_intake_summary(
+ batch: ShippingBatch,
+ *,
+ request_intake_nos: list[str],
+ open_existing_intake_nos: list[str],
+) -> None:
+ """把本请求完整 intake 集合写入批次摘要,供无 intake 键时的回退重放。"""
+ summary = dict(batch.process_summary_json) if isinstance(batch.process_summary_json, dict) else {}
+ summary['request_intake_nos'] = list(request_intake_nos)
+ summary['open_existing_intake_nos'] = list(open_existing_intake_nos)
+ batch.process_summary_json = summary
+ flag_modified(batch, 'process_summary_json')
+
+
+def create_shipping_batch_from_intakes(
+ *,
+ user_id: int,
+ conversation_id: str | None,
+ intake_nos: list[str],
+ create_idempotency_key: str | None = None,
+) -> dict[str, Any]:
+ """
+ 根据已解析且未消费的 intake 列表创建批次。
+
+ 核心逻辑:
+ 1. 幂等回放(intake 键优先);
+ 2. FOR UPDATE 锁定;若已全部消费则再试重放,否则报已消费;
+ 3. 事务内重跑业务去重并校验决策;
+ 4. open_existing 仅关联已有任务;其余走建批(含 revision/force 元数据);
+ 5. 全部 intake 打 create_idempotency_key,content_hash 去重预占后建批。
+ """
+ normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()]
+ if not normalized:
+ raise ValidationError('intake_nos is required')
+
+ # [STEP 1] 幂等重放优先
+ replay = _try_idempotent_replay(
+ user_id=user_id,
+ create_idempotency_key=create_idempotency_key,
+ intake_nos=normalized,
+ )
+ if replay is not None:
+ return replay
+
+ # [STEP 2] 锁定并校验
+ stmt = (
+ select(ShippingNoticeIntake, FileAsset)
+ .join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
+ .where(
+ ShippingNoticeIntake.user_id == int(user_id),
+ ShippingNoticeIntake.intake_no.in_(normalized),
+ )
+ .with_for_update()
+ )
+ rows = list(db.session.execute(stmt).all())
+ row_by_no = {intake.intake_no: (intake, asset) for intake, asset in rows}
+ if len(row_by_no) != len(set(normalized)):
+ raise ValidationError(
+ '部分接入记录不存在或无权访问',
+ code='SHIPPING_NOTICE.INTAKE_NOT_FOUND',
+ )
+
+ replay = _try_idempotent_replay(
+ user_id=user_id,
+ create_idempotency_key=create_idempotency_key,
+ intake_nos=normalized,
+ )
+ if replay is not None:
+ return replay
+
+ ordered_pairs: list[tuple[ShippingNoticeIntake, FileAsset]] = []
+ now = datetime.utcnow()
+ consumed_pairs: list[ShippingNoticeIntake] = []
+ for intake_no in normalized:
+ intake, asset = row_by_no[intake_no]
+ if intake.consumed_at is not None or intake.parse_status == 'consumed':
+ consumed_pairs.append(intake)
+ continue
+ if intake.parse_status != 'parsed':
+ raise ConflictError(
+ f'接入记录 {intake.intake_no} 尚未解析完成',
+ code=(
+ 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING'
+ if intake.parse_status in {'created', 'queued', 'parsing'}
+ else 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
+ ),
+ )
+ # [STEP] 附件完整性:failed/empty/skipped、超限警告、文本预算耗尽等均不可建批
+ structured = (
+ intake.structured_result_json
+ if isinstance(intake.structured_result_json, dict)
+ else None
+ )
+ if is_attachment_parse_incomplete(structured):
+ raise ConflictError(
+ f'接入记录 {intake.intake_no} 附件解析不完整,请重试解析或移除后重新上传',
+ code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
+ )
+ if intake.expires_at and intake.expires_at < now:
+ raise ConflictError(
+ '接入记录已过期',
+ code='SHIPPING_NOTICE.INTAKE_EXPIRED',
+ )
+ ordered_pairs.append((intake, asset))
+
+ if consumed_pairs:
+ if len(consumed_pairs) == len(normalized):
+ # 并发首成功后重试:依赖 intake 幂等键重放,避免「已消费」误伤
+ replay = _try_idempotent_replay(
+ user_id=user_id,
+ create_idempotency_key=create_idempotency_key,
+ intake_nos=normalized,
+ )
+ if replay is not None:
+ return replay
+ raise ConflictError(
+ f'接入记录 {consumed_pairs[0].intake_no} 已被消费',
+ code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED',
+ )
+
+ # [STEP 3] 事务内业务去重 Gate
+ open_existing_pairs: list[tuple[ShippingNoticeIntake, FileAsset, ShippingTask]] = []
+ create_pairs: list[tuple[ShippingNoticeIntake, FileAsset]] = []
+ for intake, asset in ordered_pairs:
+ _assert_duplicate_gate(user_id=user_id, intake=intake, asset=asset)
+ resolution = str(intake.duplicate_resolution or '').strip().lower()
+ if resolution == 'open_existing':
+ target = (
+ db.session.query(ShippingTask)
+ .filter(
+ ShippingTask.task_no == str(intake.duplicate_target_task_no or '').strip().upper(),
+ ShippingTask.user_id == int(user_id),
+ )
+ .first()
+ )
+ if not target:
+ raise ConflictError(
+ '重复目标任务不存在',
+ code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND',
+ )
+ open_existing_pairs.append((intake, asset, target))
+ else:
+ create_pairs.append((intake, asset))
+
+ all_request_intakes = [intake for intake, _ in ordered_pairs]
+ _stamp_intakes_create_idempotency(all_request_intakes, create_idempotency_key)
+
+ # [STEP 4] open_existing:关联并 consumed,不新建
+ opened: list[dict[str, Any]] = []
+ for intake, asset, target in open_existing_pairs:
+ mark_intakes_consumed(
+ intakes=[intake],
+ batch_id=target.batch_id,
+ task_ids_by_intake={int(intake.id): int(target.id)},
+ )
+ intake.duplicate_resolution = 'open_existing'
+ log_task_event(
+ target,
+ 'duplicate_opened_existing',
+ {
+ 'intake_no': intake.intake_no,
+ 'matched_task_no': target.task_no,
+ 'match_type': intake.duplicate_status,
+ 'fingerprint_version': intake.fingerprint_version,
+ 'resolution': 'open_existing',
+ 'operator_user_id': int(user_id),
+ },
+ )
+ opened.append({'intake_no': intake.intake_no, 'task_no': target.task_no, 'batch_no': None})
+
+ if not create_pairs:
+ db.session.commit()
+ focus = open_existing_pairs[0][2] if open_existing_pairs else None
+ return {
+ 'status': 'ok',
+ 'batch_no': None,
+ 'idempotent_replay': False,
+ 'opened_existing': opened,
+ 'message': '已打开已有任务,未创建新批次',
+ 'data': {
+ 'opened_existing': opened,
+ 'focus_task': {'task_no': focus.task_no} if focus else None,
+ },
+ }
+
+ # [STEP 5] content_hash 去重后建批
+ primary_pairs, duplicates_by_hash = _partition_intakes_by_content_hash(create_pairs)
+ primary_intakes = [intake for intake, _ in primary_pairs]
+ notice_items = [intake_to_notice_item(intake, asset) for intake, asset in primary_pairs]
+
+ mark_intakes_consumed(intakes=primary_intakes, batch_id=None)
+ db.session.flush()
+
+ try:
+ result = create_shipping_batch_from_notice_items(
+ user_id=user_id,
+ conversation_id=conversation_id,
+ notice_items=notice_items,
+ create_idempotency_key=create_idempotency_key,
+ defer_commit=True,
+ start_orchestrator=False,
+ )
+ except Exception:
+ db.session.rollback()
+ raise
+
+ if bool(result.get('idempotent_replay')):
+ db.session.rollback()
+ # 下层批次回放成功后,本地预占已回滚;再以 intake 键或批次回放统一出口
+ replay = _try_idempotent_replay(
+ user_id=user_id,
+ create_idempotency_key=create_idempotency_key,
+ intake_nos=normalized,
+ )
+ if replay is not None:
+ if opened:
+ replay['opened_existing'] = opened
+ return replay
+ if opened:
+ result['opened_existing'] = opened
+ return result
+
+ data = result.get('data') if isinstance(result.get('data'), dict) else {}
+ batch = data.get('batch') if isinstance(data.get('batch'), dict) else {}
+ batch_no = str(result.get('batch_no') or batch.get('batch_no') or '').strip()
+ if not batch_no:
+ if opened:
+ result['opened_existing'] = opened
+ return result
+
+ from app.services.shipping_notice.query_service import get_batch_for_user
+
+ batch_obj = get_batch_for_user(batch_no, user_id)
+ if not batch_obj:
+ return result
+
+ _attach_request_intake_summary(
+ batch_obj,
+ request_intake_nos=normalized,
+ open_existing_intake_nos=[item['intake_no'] for item in opened],
+ )
+
+ tasks = (
+ db.session.query(ShippingTask)
+ .filter(ShippingTask.batch_id == batch_obj.id)
+ .order_by(ShippingTask.batch_index.asc(), ShippingTask.id.asc())
+ .all()
+ )
+ task_by_intake_id = {
+ int(task.source_intake_id): task
+ for task in tasks
+ if task.source_intake_id is not None
+ }
+ hash_to_task_id: dict[str, int] = {}
+ for intake, asset in primary_pairs:
+ task = task_by_intake_id.get(int(intake.id))
+ if task is None:
+ continue
+ intake.consumed_batch_id = int(batch_obj.id)
+ intake.consumed_task_id = int(task.id)
+ intake.updated_at = datetime.utcnow()
+ content_hash = str(asset.content_hash or '').strip()
+ if content_hash:
+ hash_to_task_id[content_hash] = int(task.id)
+ # 审计:修订 / 强制新建
+ resolution_type = str(task.duplicate_resolution_type or 'normal')
+ if resolution_type == 'revision' and task.supersedes_task_id:
+ prev = db.session.get(ShippingTask, int(task.supersedes_task_id))
+ if prev:
+ log_task_event(
+ task,
+ 'duplicate_revision_created',
+ {
+ 'intake_no': intake.intake_no,
+ 'matched_task_no': prev.task_no,
+ 'fingerprint_version': task.fingerprint_version,
+ 'resolution': 'create_revision',
+ 'document_version': task.document_version,
+ 'operator_user_id': int(user_id),
+ },
+ )
+ log_task_event(
+ prev,
+ 'task_superseded',
+ {
+ 'new_task_no': task.task_no,
+ 'document_version': task.document_version,
+ 'operator_user_id': int(user_id),
+ },
+ )
+ elif resolution_type == 'force_create':
+ log_task_event(
+ task,
+ 'duplicate_force_created',
+ {
+ 'intake_no': intake.intake_no,
+ 'matched_task_no': intake.duplicate_target_task_no,
+ 'reason': task.duplicate_override_reason,
+ 'fingerprint_version': task.fingerprint_version,
+ 'resolution': 'force_create',
+ 'operator_user_id': int(user_id),
+ },
+ )
+
+ duplicate_intakes: list[ShippingNoticeIntake] = []
+ for content_hash, dups in duplicates_by_hash.items():
+ task_id = hash_to_task_id.get(content_hash)
+ if task_id is None:
+ continue
+ for dup in dups:
+ duplicate_intakes.append(dup)
+ dup.consumed_batch_id = int(batch_obj.id)
+ dup.consumed_task_id = int(task_id)
+ if duplicate_intakes:
+ _stamp_intakes_create_idempotency(duplicate_intakes, create_idempotency_key)
+ mark_intakes_consumed(
+ intakes=duplicate_intakes,
+ batch_id=int(batch_obj.id),
+ task_ids_by_intake={int(i.id): int(i.consumed_task_id) for i in duplicate_intakes if i.consumed_task_id},
+ )
+
+ # 与批次创建 / intake 关联 / 审计同事务提交,消除提交断点
+ db.session.commit()
+
+ from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
+
+ orchestrator_started = start_batch_orchestrator(batch_no)
+ if isinstance(data, dict):
+ data['orchestrator_started'] = orchestrator_started
+ if orchestrator_started:
+ base_message = str(result.get('message') or '').strip()
+ result['message'] = (
+ f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。'
+ )
+
+ if opened:
+ result['opened_existing'] = opened
+ return result
diff --git a/backend/app/services/shipping_notice/batch_from_notices.py b/backend/app/services/shipping_notice/batch_from_notices.py
index e22dfa73..13a211ac 100644
--- a/backend/app/services/shipping_notice/batch_from_notices.py
+++ b/backend/app/services/shipping_notice/batch_from_notices.py
@@ -2,7 +2,7 @@
services/shipping_notice/batch_from_notices.py
用途:从发货通知附件创建批次的共享编排(workspace API 与 Chat Turn handler 共用)。
-依赖:shipping_tools、notice_upload、batch_orchestrator、query_service。
+依赖:shipping_tools、notice_upload、batch_orchestrator、batch_create_idempotency、query_service。
逻辑:workspace/shipping_notice 与 chat_action_handlers 均调用本模块,避免建批逻辑双份维护。
"""
@@ -10,7 +10,18 @@ from __future__ import annotations
from typing import Any
+from sqlalchemy.exc import IntegrityError
+
from app.services.shipping_notice import tools as shipping_tools
+from app.services.shipping_notice.batch_create_idempotency import (
+ assert_idempotent_batch_content_matches,
+ build_existing_batch_tool_response,
+ dedupe_notice_items_by_content_hash,
+ find_batch_by_create_idempotency,
+ handle_batch_create_integrity_error,
+ normalize_create_idempotency_key,
+ warn_missing_create_idempotency_key,
+)
from app.services.shipping_notice.notice_upload import build_notice_file_summary
from app.services.shipping_notice.query_service import get_focus_task_for_batch, serialize_task_summary
@@ -21,22 +32,36 @@ def create_shipping_batch_from_notice_items(
conversation_id: str | None,
notice_items: list[dict[str, Any]],
file_summary: dict[str, Any] | None = None,
+ create_idempotency_key: str | None = None,
+ defer_commit: bool = False,
+ start_orchestrator: bool | None = None,
) -> dict[str, Any]:
"""
根据已抽取的发货通知条目创建批次并可选启动编排器。
+ 核心逻辑:优先按建单幂等键回查已有批次;新建时写入 create_idempotency_key 并捕获唯一约束竞争。
+ intake 路径应传 defer_commit=True,避免批次先提交导致上层 ingested 关联/审计断点。
+
Args:
user_id: 当前用户 ID。
conversation_id: 可选 Agent 会话 ID。
notice_items: notice_upload 产出的 notice item 列表。
file_summary: 可选文件预检摘要,写入响应供前端展示。
+ create_idempotency_key: 建单幂等键(与 ShippingTask.idempotency_key 货代上传幂等分离)。
+ defer_commit: True 时下层仅 flush,由调用方最终 commit。
+ start_orchestrator: 是否启动编排器;默认与 defer_commit 相反(延后提交时不启动)。
Returns:
- 与 workspace create-from-notices 一致的结果字典。
+ 与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。
Raises:
ValidationError: notice_items 为空。
"""
+ normalized_key = normalize_create_idempotency_key(create_idempotency_key)
+ if not normalized_key:
+ warn_missing_create_idempotency_key(source="create_shipping_batch_from_notice_items")
+
+ notice_items = dedupe_notice_items_by_content_hash(notice_items)
if not notice_items:
from app.core.errors import ValidationError
@@ -45,22 +70,46 @@ def create_shipping_batch_from_notice_items(
details={"file_summary": file_summary or {}},
)
+ if normalized_key:
+ existing_batch = find_batch_by_create_idempotency(user_id, normalized_key)
+ if existing_batch:
+ assert_idempotent_batch_content_matches(existing_batch, notice_items)
+ created = build_existing_batch_tool_response(existing_batch, user_id=user_id)
+ if file_summary:
+ created["file_summary"] = file_summary
+ return created
+
payload = {
"user_id": user_id,
"conversation_id": conversation_id or None,
"file_count": len(notice_items),
"notice_items": notice_items,
"defer_parse": True,
+ "create_idempotency_key": normalized_key,
+ "defer_commit": bool(defer_commit),
}
- created = shipping_tools.create_batch_tasks(payload)
+ try:
+ created = shipping_tools.create_batch_tasks(payload)
+ except IntegrityError as exc:
+ replay = handle_batch_create_integrity_error(
+ user_id=user_id,
+ create_idempotency_key=normalized_key,
+ exc=exc,
+ )
+ if replay is None:
+ raise
+ created = replay
+
if not isinstance(created, dict):
return {"status": "failed", "message": "create batch failed"}
+ idempotent_replay = bool(created.get("idempotent_replay"))
data = created.get("data") if isinstance(created.get("data"), dict) else {}
batch_data = data.get("batch") if isinstance(data.get("batch"), dict) else {}
batch_no = str(created.get("batch_no") or batch_data.get("batch_no") or "").strip()
+ should_start = start_orchestrator if start_orchestrator is not None else (not defer_commit)
orchestrator_started = False
- if batch_no:
+ if batch_no and not idempotent_replay and should_start:
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
orchestrator_started = start_batch_orchestrator(batch_no)
@@ -72,6 +121,8 @@ def create_shipping_batch_from_notice_items(
base_message = str(created.get("message") or "").strip()
if orchestrator_started:
created["message"] = f"{base_message},后台已开始逐票处理。" if base_message else "后台已开始逐票处理。"
+ if idempotent_replay:
+ created["idempotent_replay"] = True
if file_summary:
created["file_summary"] = file_summary
return created
@@ -85,8 +136,12 @@ def format_batch_created_assistant_message(
"""
格式化建批成功后写入 Chat Turn assistant 气泡的文案。
- 核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构。
+ 核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构;幂等重放时提示已恢复批次。
"""
+ if bool(result.get("idempotent_replay")):
+ batch_no = str(result.get("batch_no") or "").strip()
+ return f"已恢复此前创建的批次。\n批次编号:{batch_no}" if batch_no else "已恢复此前创建的批次。"
+
data = result.get("data") if isinstance(result.get("data"), dict) else {}
batch = data.get("batch") if isinstance(data.get("batch"), dict) else {}
tasks = data.get("tasks") if isinstance(data.get("tasks"), list) else []
@@ -132,11 +187,12 @@ def intake_notice_uploads_for_batch(
"""
from app.services.shipping_notice.notice_upload import intake_temp_notice_uploads
- accepted, rejected = intake_temp_notice_uploads(request_id, uploads)
+ accepted, rejected, duplicate_files = intake_temp_notice_uploads(request_id, uploads)
file_summary = build_notice_file_summary(
total_files=len(uploads),
accepted=accepted,
rejected=rejected,
+ duplicate_files=duplicate_files,
)
notice_items = [item.to_notice_item() for item in accepted]
return notice_items, file_summary
diff --git a/backend/app/services/shipping_notice/business_fingerprint.py b/backend/app/services/shipping_notice/business_fingerprint.py
new file mode 100644
index 00000000..dddf3a1b
--- /dev/null
+++ b/backend/app/services/shipping_notice/business_fingerprint.py
@@ -0,0 +1,173 @@
+"""
+backend/app/services/shipping_notice/business_fingerprint.py
+
+用途:基于业务摘要生成稳定业务指纹与强度判定(货代域,不含文件哈希)。
+依赖:po_number / reservation_id 标准化函数。
+逻辑:intake_parse_workflow / Candidate 级 duplicate_detection / 建单门闩共用;算法版本 shipping-v1。
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from decimal import Decimal, InvalidOperation
+from typing import Any
+
+from app.services.shipping_notice.po_number import normalize_po_number
+from app.services.shipping_notice.reservation_id import normalize_reservation_id
+
+FINGERPRINT_VERSION = 'shipping-v1'
+
+
+def _norm_text(value: Any) -> str:
+ return str(value or '').strip().upper()
+
+
+def _norm_qty(value: Any) -> str:
+ if value is None or value == '':
+ return ''
+ try:
+ return format(Decimal(str(value)).quantize(Decimal('0.0001')), 'f')
+ except (InvalidOperation, ValueError, TypeError):
+ return _norm_text(value)
+
+
+def _line_digest(lines: list[dict[str, Any]]) -> str:
+ parts: list[str] = []
+ for line in lines:
+ if not isinstance(line, dict):
+ continue
+ sku = _norm_text(line.get('sku'))
+ rid = normalize_reservation_id(str(line.get('reservation_id') or '')) or ''
+ qty = _norm_qty(line.get('qty'))
+ if not sku and not rid and not qty:
+ continue
+ parts.append(f'{sku}|{rid}|{qty}')
+ parts.sort()
+ return '\n'.join(parts)
+
+
+def _customer_identity(summary: dict[str, Any]) -> tuple[str, str]:
+ """
+ 解析客户身份键。
+
+ 核心逻辑:优先 customer_code;启发式预解析常只有 customer_name,须回退到名称,
+ 否则强业务单号(PO/Reservation)也无法生成 usable 指纹。
+ Returns:
+ (identity_value, identity_field) 如 ('ACME', 'customer_name');无则 ('', '')。
+ """
+ code = _norm_text(summary.get('customer_code'))
+ if code:
+ return code, 'customer_code'
+ name = _norm_text(summary.get('customer_name'))
+ if name:
+ return name, 'customer_name'
+ return '', ''
+
+
+def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[str, Any]:
+ """
+ 由业务摘要生成指纹、强度与组成依据。
+
+ 核心逻辑(shipping-v1):
+ - strong:客户身份(code 或 name)+ (PO 或 reservation 集合)
+ 或:PO + reservation 集合(稳定业务编号,无需客户码)
+ - medium:客户身份 + 目的地 + required_date + 行 digest
+ - weak:ship_to 或 仅行 digest(SKU+qty)
+ - unavailable:不足以可靠去重
+
+ Args:
+ business_summary: intake_business_parser 产出。
+
+ Returns:
+ {fingerprint, version, strength, components}
+ """
+ summary = business_summary if isinstance(business_summary, dict) else {}
+ customer_id, customer_field = _customer_identity(summary)
+ po_number = normalize_po_number(str(summary.get('po_number') or '')) or ''
+ reservation_ids = sorted(
+ {
+ normalize_reservation_id(str(item)) or ''
+ for item in (summary.get('reservation_ids') or [])
+ if str(item or '').strip()
+ }
+ - {''}
+ )
+ dest = summary.get('destination') if isinstance(summary.get('destination'), dict) else {}
+ destination_key = '|'.join(
+ [
+ _norm_text(dest.get('code')),
+ _norm_text(dest.get('city')),
+ _norm_text(dest.get('country')),
+ ]
+ ).strip('|')
+ required_date = _norm_text(summary.get('required_date'))
+ ship_to = _norm_text(summary.get('ship_to'))
+ lines = summary.get('lines') if isinstance(summary.get('lines'), list) else []
+ line_digest = _line_digest([item for item in lines if isinstance(item, dict)])
+
+ strength = 'unavailable'
+ components: dict[str, Any] = {}
+
+ # [STEP 1] 强指纹:客户身份 + 稳定单号;或仅 PO+Reservation(编号本身足够强)
+ if customer_id and (po_number or reservation_ids):
+ strength = 'strong'
+ components = {
+ customer_field: customer_id,
+ 'po_number': po_number or None,
+ 'reservation_ids': reservation_ids,
+ }
+ elif po_number and reservation_ids:
+ strength = 'strong'
+ components = {
+ 'po_number': po_number,
+ 'reservation_ids': reservation_ids,
+ }
+ elif customer_id and destination_key and required_date and line_digest:
+ strength = 'medium'
+ components = {
+ customer_field: customer_id,
+ 'destination': destination_key,
+ 'required_date': required_date,
+ 'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16],
+ }
+ elif ship_to and line_digest:
+ strength = 'weak'
+ components = {
+ 'ship_to': ship_to,
+ 'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16],
+ }
+ elif line_digest and (reservation_ids or po_number or customer_id):
+ # 有行 digest 且至少一项单头标识:弱指纹,可标记 possible
+ strength = 'weak'
+ components = {
+ 'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16],
+ }
+ if customer_id:
+ components[customer_field] = customer_id
+ if po_number:
+ components['po_number'] = po_number
+ if reservation_ids:
+ components['reservation_ids'] = reservation_ids
+ else:
+ return {
+ 'fingerprint': None,
+ 'version': FINGERPRINT_VERSION,
+ 'strength': 'unavailable',
+ 'components': {},
+ }
+
+ payload = {
+ 'version': FINGERPRINT_VERSION,
+ 'strength': strength,
+ 'components': components,
+ }
+ digest = hashlib.sha256(
+ json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
+ ).hexdigest()
+ return {
+ 'fingerprint': digest,
+ 'version': FINGERPRINT_VERSION,
+ 'strength': strength,
+ 'components': components,
+ }
diff --git a/backend/app/services/shipping_notice/chat_action_handlers.py b/backend/app/services/shipping_notice/chat_action_handlers.py
index 39223e4f..80ced5b1 100644
--- a/backend/app/services/shipping_notice/chat_action_handlers.py
+++ b/backend/app/services/shipping_notice/chat_action_handlers.py
@@ -113,6 +113,7 @@ class ShippingCreateBatchFromNoticesAction:
raise ValidationError("notice_items is required")
file_summary = payload.get("file_summary") if isinstance(payload.get("file_summary"), dict) else None
conversation_id = _payload_str(payload, "conversation_id", "conversationId") or None
+ idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_notices", "label": "处理发货通知..."})
@@ -126,6 +127,7 @@ class ShippingCreateBatchFromNoticesAction:
conversation_id=conversation_id,
notice_items=notice_items,
file_summary=file_summary,
+ create_idempotency_key=idempotency_key,
)
batch_no = str(result.get("batch_no") or "").strip()
if batch_no:
@@ -141,11 +143,89 @@ class ShippingCreateBatchFromNoticesAction:
"batch_no": batch_no,
"task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
"orchestrator_started": bool(data.get("orchestrator_started")),
+ "idempotent_replay": bool(result.get("idempotent_replay")),
}
yield from _stream_text_events(content, message_type="text", payload=message_payload)
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_notices"})
+class ShippingCreateBatchFromIntakesAction:
+ """基于已解析接入记录确认建批(第二阶段主路径)。"""
+
+ action_type = "shipping.create_batch_from_intakes"
+
+ def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
+ user_id = ctx.user_id
+ if user_id is None:
+ raise ValidationError("user context is required")
+ payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
+ intake_nos = payload.get("intake_nos")
+ if not isinstance(intake_nos, list) or not intake_nos:
+ raise ValidationError("intake_nos is required")
+ # 空白新会话 payload 常无 conversation_id;回退到 Chat Turn 刚创建的本地 session_id
+ conversation_id = (
+ _payload_str(payload, "conversation_id", "conversationId")
+ or str(getattr(ctx, "session_id", "") or "").strip()
+ or None
+ )
+ idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
+
+ yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_intakes", "label": "确认建单..."})
+
+ from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
+ from app.services.shipping_notice.batch_from_notices import format_batch_created_assistant_message
+
+ result = create_shipping_batch_from_intakes(
+ user_id=user_id,
+ conversation_id=conversation_id,
+ intake_nos=[str(item) for item in intake_nos],
+ create_idempotency_key=idempotency_key,
+ )
+ opened = result.get("opened_existing") if isinstance(result.get("opened_existing"), list) else []
+ if opened and not str(result.get("batch_no") or "").strip():
+ data = result.get("data") if isinstance(result.get("data"), dict) else {}
+ focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
+ task_no = str(focus_task.get("task_no") or opened[0].get("task_no") or "").strip()
+ if task_no:
+ task = get_task_by_ref(task_no)
+ if task is not None:
+ yield _shipping_ui_state_event(task)
+ content = str(result.get("message") or "已打开已有任务,未创建新批次")
+ yield from _stream_text_events(
+ content,
+ message_type="text",
+ payload={
+ "opened_existing": True,
+ "task_no": task_no,
+ "intake_nos": [str(item.get("intake_no") or "") for item in opened],
+ },
+ )
+ yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"})
+ return
+
+ batch_no = str(result.get("batch_no") or "").strip()
+ if batch_no:
+ batch_event = _shipping_batch_ui_state_event(batch_no, user_id)
+ if batch_event is not None:
+ yield batch_event
+
+ file_count = len(intake_nos)
+ content = format_batch_created_assistant_message(result, file_count=file_count)
+ data = result.get("data") if isinstance(result.get("data"), dict) else {}
+ focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
+ message_payload = {
+ "batch_no": batch_no,
+ "task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
+ "orchestrator_started": bool(data.get("orchestrator_started")),
+ "idempotent_replay": bool(result.get("idempotent_replay")),
+ "document_version": focus_task.get("document_version"),
+ "duplicate_resolution_type": focus_task.get("duplicate_resolution_type"),
+ "supersedes_task_no": focus_task.get("supersedes_task_no"),
+ }
+ yield from _stream_text_events(content, message_type="text", payload=message_payload)
+ yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"})
+
+
class ShippingSubmitDecisionAction:
"""提交人工决策:confirm / reject / rematch / retry_rpa 等。"""
@@ -264,6 +344,7 @@ class ShippingConfirmInventorySourceAction:
"task_id": task.task_no,
"source_code": source_code,
"event_source": "chat_turn",
+ "_trusted_user_id": ctx.user_id,
})
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "confirm_inventory_source failed")
@@ -303,6 +384,7 @@ class ShippingMarkManualUploadedAction:
_HANDLERS = (
ShippingCreateBatchFromNoticesAction(),
+ ShippingCreateBatchFromIntakesAction(),
ShippingSubmitDecisionAction(),
ShippingGenerateExcelAction(),
ShippingRetryUploadAction(),
diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py
index 95ec5c8d..fb6efc8e 100644
--- a/backend/app/services/shipping_notice/decision_workflow.py
+++ b/backend/app/services/shipping_notice/decision_workflow.py
@@ -12,8 +12,10 @@ from typing import Any
from app import db
from app.services.shipping_notice.constants import (
+ CP_INVENTORY_SOURCE_REVIEW,
CP_MAP_INFER,
CP_PARSE_OK,
+ PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
PH_RPA_PENDING,
PH_SHORTAGE,
@@ -36,9 +38,17 @@ from app.services.shipping_notice.inventory_file_store import (
from app.services.shipping_notice.inventory_upload import (
has_uploaded_task_inventory,
read_task_inventory_schema_preview,
+ resolve_task_inventory_upload_path,
task_inventory_upload_path,
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory
+from app.services.shipping_notice.inventory_source_gate import (
+ is_inventory_source_stable,
+ adjudicate_and_apply_inventory_source,
+ ensure_inventory_source_review_state,
+ task_needs_parse_review,
+ transition_task_to_inventory_source_review,
+)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
@@ -160,6 +170,25 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
and not match_completed(task)
)
):
+ is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF
+ # 已在库存源确认节点时禁止用 confirm 跳过;低置信度解析复核可先 confirm,确认后再进库存源。
+ if (
+ not is_low_confidence_parse_confirm
+ and (
+ task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
+ or not is_inventory_source_stable(task)
+ )
+ ):
+ ui = resolve_task_ui_state(task)
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message="库存源尚未确定,请先完成库存源确认。",
+ data=serialize_task_for_tool(task),
+ human_options=ui.human_options,
+ checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
+ stop_agent_turn=True,
+ )
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
task.match_status = None
task.shortage_json = None
@@ -172,6 +201,24 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
comment=comment,
)
db.session.commit()
+ if not is_inventory_source_stable(task):
+ adjudication = ensure_inventory_source_review_state(task)
+ db.session.commit()
+ return tool_response(
+ status="ok",
+ task=task,
+ message="解析内容已确认,请继续选择正式库存源。",
+ data={
+ **serialize_task_for_tool(task),
+ "inventory_source_candidates": adjudication.candidates,
+ "inventory_source_status": adjudication.status,
+ "inventory_source_reason": adjudication.reason,
+ "destination_candidates": adjudication.destination_candidates,
+ },
+ checkpoint=CP_INVENTORY_SOURCE_REVIEW,
+ human_options=resolve_task_ui_state(task).human_options,
+ stop_agent_turn=True,
+ )
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
@@ -408,8 +455,8 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.CORRECT_MAPPING)
log_task_event(task, "inventory_mapping_correction_requested", {"comment": comment})
db.session.commit()
- upload_path = task_inventory_upload_path(task.task_no)
- if upload_path.is_file():
+ upload_path = resolve_task_inventory_upload_path(task.task_no)
+ if upload_path is not None:
try:
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
@@ -444,12 +491,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY_DEMOTE)
else:
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY)
- upload_path = task_inventory_upload_path(task.task_no)
- if upload_path.is_file():
- try:
- upload_path.unlink()
- except OSError:
- pass
+ for suffix in (".xlsx", ".csv"):
+ upload_path = task_inventory_upload_path(task.task_no, suffix=suffix)
+ if upload_path.is_file():
+ try:
+ upload_path.unlink()
+ except OSError:
+ pass
log_task_event(task, "inventory_reparse_requested", {"comment": comment})
db.session.commit()
return tool_response(
diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py
new file mode 100644
index 00000000..9404f175
--- /dev/null
+++ b/backend/app/services/shipping_notice/document_candidate_persist.py
@@ -0,0 +1,645 @@
+"""
+backend/app/services/shipping_notice/document_candidate_persist.py
+
+用途:阶段二——EML 附件派生 FileAsset、ShippingNoticeDocument / Candidate 幂等落库。
+依赖:file_assets.service、intake_business_parser、business_fingerprint、duplicate_detection、eml_parse。
+逻辑:由 intake_parse_workflow.run_intake_parse 在文本落库成功后调用;重试按
+ (parent, content_hash)、(intake, attachment_key)、(intake, primary_document_id) 复用,不重复创建。
+ Document↔派生资产的引用计数仅在 asset_id 变更时 +1/-1;
+ Candidate 重复检测可由调用方延后到 SAVEPOINT(run_duplicate_detection=False);
+ cancel / 阶段二失败可整单释放并清理 structured 投影字段。
+"""
+
+from __future__ import annotations
+
+import hashlib
+import uuid
+from datetime import datetime
+from typing import Any
+
+from app import db
+from app.models import (
+ FileAsset,
+ ShippingNoticeCandidate,
+ ShippingNoticeDocument,
+ ShippingNoticeIntake,
+)
+from app.services.file_assets.service import (
+ create_derived_file_asset_from_bytes,
+ mark_asset_referenced,
+ release_asset_reference,
+)
+from app.services.shipping_notice.business_fingerprint import build_business_fingerprint
+from app.services.shipping_notice.eml_parse import pop_attachment_payload, strip_attachment_payloads
+from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary
+from app.services.shipping_notice.notice_upload import NoticeIntakeResult
+
+BODY_ATTACHMENT_KEY = 'body'
+
+
+def generate_candidate_no() -> str:
+ """生成 SNC-YYYYMMDD-XXXXXXXX 格式候选编号。"""
+ return f"SNC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
+
+
+def _guess_source_type_for_doc(*, filename: str | None, mime_type: str | None, document_type: str) -> str:
+ if document_type == 'email_body':
+ return 'email'
+ name = str(filename or '').lower()
+ mime = str(mime_type or '').lower()
+ if name.endswith('.pdf') or 'pdf' in mime:
+ return 'pdf'
+ if name.endswith('.docx') or 'wordprocessingml' in mime:
+ return 'docx'
+ if name.endswith('.eml') or mime in {'message/rfc822', 'application/eml'}:
+ return 'email'
+ return 'manual'
+
+
+def _has_order_signal(business_summary: dict[str, Any] | None) -> bool:
+ """是否具备真实业务标识(PO / Reservation / 行项目),禁止用文件名或哈希伪造。"""
+ summary = business_summary if isinstance(business_summary, dict) else {}
+ return bool(
+ str(summary.get('po_number') or '').strip()
+ or (summary.get('reservation_ids') or [])
+ or (summary.get('lines') or [])
+ )
+
+
+def _classify_document(
+ *,
+ document_type: str,
+ filename: str | None,
+ mime_type: str | None,
+ parse_status: str,
+ business_summary: dict[str, Any] | None,
+) -> str:
+ """
+ 文档分类:order_notice / email_context / supporting / unknown。
+
+ 核心逻辑:仅当业务摘要含真实 PO/Reservation/行项目时标 order_notice;
+ 邮件正文始终为 email_context(上下文/索引,不生成 Candidate);
+ 无信号的 parsed PDF/文本归 supporting,保留 Document 但不造假候选。
+ """
+ has_order_signal = _has_order_signal(business_summary)
+ status = str(parse_status or '').strip().lower()
+ name = str(filename or '').lower()
+ mime = str(mime_type or '').lower()
+ is_orderish_file = (
+ name.endswith(('.pdf', '.docx', '.doc', '.txt', '.csv'))
+ or 'pdf' in mime
+ or 'wordprocessingml' in mime
+ or mime.startswith('text/')
+ )
+
+ if document_type == 'email_body':
+ return 'email_context'
+ if status == 'parsed' and has_order_signal:
+ return 'order_notice'
+ if status == 'parsed' and is_orderish_file:
+ return 'supporting'
+ if status in {'failed', 'empty', 'skipped', 'duplicate'}:
+ return 'supporting' if is_orderish_file else 'unknown'
+ return 'unknown'
+
+
+def _should_create_candidate(*, document_type: str, classification: str, parse_status: str) -> bool:
+ """正文永不生成 Candidate;仅 order_notice + parsed 的附件/单文件可生成。"""
+ if str(document_type or '') == 'email_body':
+ return False
+ return classification == 'order_notice' and str(parse_status or '').lower() == 'parsed'
+
+
+def _release_document_asset(asset_id: int | None) -> None:
+ """Document 不再引用时释放派生资产引用计数。"""
+ if not asset_id:
+ return
+ asset = db.session.get(FileAsset, int(asset_id))
+ if asset is None:
+ return
+ if str(asset.asset_role or '') != 'derived_attachment':
+ return
+ release_asset_reference(asset)
+
+
+def _should_persist_attachment_asset(item: dict[str, Any], payload: bytes) -> bool:
+ """有效订单附件:有二进制且非重复/纯超限 skip 时可落派生资产。"""
+ if not payload:
+ return False
+ status = str(item.get('parse_status') or '').lower()
+ if status == 'duplicate':
+ return False
+ if status == 'skipped':
+ # 过大/总量超限仍可不落库;其它 skipped(如超深)有 raw 时尽量保留供下载重试
+ warnings = [str(w) for w in (item.get('warnings') or [])]
+ if any('too_large' in w or 'total_attachment_size_exceeded' in w for w in warnings):
+ return False
+ return True
+
+
+def _upsert_document(
+ *,
+ intake: ShippingNoticeIntake,
+ attachment_key: str,
+ document_type: str,
+ filename: str | None,
+ content_hash: str | None,
+ parse_status: str,
+ extracted_text: str | None,
+ warnings: list[str],
+ asset_id: int | None,
+ classification: str,
+) -> ShippingNoticeDocument:
+ row = (
+ db.session.query(ShippingNoticeDocument)
+ .filter(
+ ShippingNoticeDocument.intake_id == int(intake.id),
+ ShippingNoticeDocument.attachment_key == attachment_key,
+ )
+ .first()
+ )
+ if row is None:
+ row = ShippingNoticeDocument(
+ intake_id=int(intake.id),
+ attachment_key=attachment_key,
+ document_type=document_type,
+ )
+ db.session.add(row)
+ previous_asset_id = int(row.asset_id) if row.asset_id else None
+ row.document_type = document_type
+ row.filename = (filename or None)
+ row.content_hash = (content_hash or None)
+ row.parse_status = parse_status
+ row.extracted_text = extracted_text
+ row.parse_warnings_json = list(warnings or [])
+ row.asset_id = asset_id
+ row.classification = classification
+ row.updated_at = datetime.utcnow()
+ db.session.flush()
+ # 按 Document→Asset 关联边增减引用,避免「已 referenced」跳过 +1 导致漏计多文档共用
+ new_asset_id = int(asset_id) if asset_id else None
+ if previous_asset_id and previous_asset_id != new_asset_id:
+ _release_document_asset(previous_asset_id)
+ if new_asset_id and previous_asset_id != new_asset_id:
+ new_asset = db.session.get(FileAsset, new_asset_id)
+ if new_asset is not None and str(new_asset.asset_role or '') == 'derived_attachment':
+ mark_asset_referenced(new_asset)
+ return row
+
+
+def _upsert_candidate(
+ *,
+ intake: ShippingNoticeIntake,
+ document: ShippingNoticeDocument,
+ business_summary: dict[str, Any],
+ fingerprint: dict[str, Any],
+ duplicate_result: dict[str, Any],
+) -> ShippingNoticeCandidate:
+ row = (
+ db.session.query(ShippingNoticeCandidate)
+ .filter(
+ ShippingNoticeCandidate.intake_id == int(intake.id),
+ ShippingNoticeCandidate.primary_document_id == int(document.id),
+ )
+ .first()
+ )
+ if row is None:
+ row = ShippingNoticeCandidate(
+ candidate_no=generate_candidate_no(),
+ intake_id=int(intake.id),
+ primary_document_id=int(document.id),
+ selected=True,
+ validation_status='pending',
+ )
+ db.session.add(row)
+ row.po_number = str(business_summary.get('po_number') or '').strip() or None
+ row.structured_result_json = {
+ 'business_summary': business_summary,
+ 'fingerprint_components': fingerprint.get('components') or {},
+ }
+ row.confidence = (
+ float(business_summary['confidence'])
+ if business_summary.get('confidence') is not None
+ else None
+ )
+ row.business_fingerprint = fingerprint.get('fingerprint')
+ row.fingerprint_version = fingerprint.get('version')
+ row.fingerprint_strength = fingerprint.get('strength')
+ row.duplicate_status = str(duplicate_result.get('status') or 'none')
+ row.duplicate_matches_json = list(duplicate_result.get('matches') or [])
+ row.duplicate_checked_at = datetime.utcnow()
+ # 重解析后清空旧决策,避免陈旧 resolution
+ row.duplicate_resolution = None
+ row.duplicate_resolution_reason = None
+ row.duplicate_target_task_no = None
+ row.updated_at = datetime.utcnow()
+ db.session.flush()
+ return row
+
+
+def _serialize_document_brief(doc: ShippingNoticeDocument, *, include_text: bool) -> dict[str, Any]:
+ asset = db.session.get(FileAsset, int(doc.asset_id)) if doc.asset_id else None
+ payload: dict[str, Any] = {
+ 'id': doc.id,
+ 'document_type': doc.document_type,
+ 'attachment_key': doc.attachment_key,
+ 'filename': doc.filename,
+ 'content_hash': doc.content_hash,
+ 'classification': doc.classification,
+ 'parse_status': doc.parse_status,
+ 'asset_no': asset.asset_no if asset else None,
+ 'asset_id': doc.asset_id,
+ 'warnings': list(doc.parse_warnings_json or []),
+ }
+ if include_text:
+ payload['extracted_text'] = doc.extracted_text
+ else:
+ payload['text_length'] = len(str(doc.extracted_text or ''))
+ return payload
+
+
+def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
+ matches = list(cand.duplicate_matches_json or [])
+ status = str(cand.duplicate_status or 'unchecked')
+ blocking = status in {
+ 'exact_file',
+ 'same_active_task',
+ 'same_completed_task',
+ 'possible_duplicate',
+ }
+ strength = str(cand.fingerprint_strength or 'unavailable')
+ if strength == 'unavailable' and status == 'none':
+ blocking = False
+ summary = None
+ if isinstance(cand.structured_result_json, dict):
+ summary = cand.structured_result_json.get('business_summary')
+ return {
+ 'candidate_no': cand.candidate_no,
+ 'primary_document_id': cand.primary_document_id,
+ 'po_number': cand.po_number,
+ 'confidence': cand.confidence,
+ 'validation_status': cand.validation_status,
+ 'selected': bool(cand.selected),
+ 'business_fingerprint': cand.business_fingerprint,
+ 'fingerprint_strength': cand.fingerprint_strength,
+ 'fingerprint_version': cand.fingerprint_version,
+ 'duplicate': {
+ 'status': status,
+ 'blocking': blocking,
+ 'matches': matches,
+ },
+ 'duplicate_resolution': cand.duplicate_resolution,
+ 'business_summary': summary,
+ 'consumed_task_id': cand.consumed_task_id,
+ }
+
+
+def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list[dict[str, Any]]:
+ """列出 Intake 下 Document 摘要。"""
+ rows = (
+ db.session.query(ShippingNoticeDocument)
+ .filter(ShippingNoticeDocument.intake_id == int(intake_id))
+ .order_by(ShippingNoticeDocument.id.asc())
+ .all()
+ )
+ return [_serialize_document_brief(row, include_text=include_text) for row in rows]
+
+
+def list_intake_candidates(intake_id: int) -> list[dict[str, Any]]:
+ """列出 Intake 下 Candidate 摘要。"""
+ rows = (
+ db.session.query(ShippingNoticeCandidate)
+ .filter(ShippingNoticeCandidate.intake_id == int(intake_id))
+ .order_by(ShippingNoticeCandidate.id.asc())
+ .all()
+ )
+ return [_serialize_candidate_brief(row) for row in rows]
+
+
+_UNCHECKED_DUP: dict[str, Any] = {
+ 'status': 'unchecked',
+ 'blocking': False,
+ 'matches': [],
+ 'fingerprint': None,
+ 'fingerprint_version': None,
+ 'fingerprint_strength': None,
+ 'components': {},
+ 'allowed_actions': [],
+}
+
+
+def persist_documents_and_candidates(
+ *,
+ intake: ShippingNoticeIntake,
+ parent_asset: FileAsset,
+ result: NoticeIntakeResult,
+ uploaded_storage_keys: list[str] | None = None,
+ run_duplicate_detection: bool = True,
+) -> dict[str, Any]:
+ """
+ 从一次解析结果落派生资产 + Document + Candidate(仅 flush,由调用方统一 commit)。
+
+ 核心逻辑:
+ 1. 正文 Document(email_context,永不生成 Candidate);
+ 2. 附件 → 幂等派生 FileAsset → Document;仅真实订单信号生成 Candidate;
+ 3. 清理本轮无效 Document 与失效 Candidate;释放孤立派生资产引用;
+ 4. 剥离 `_payload_bytes`。
+ run_duplicate_detection=False 时 Candidate 仅落基础行(duplicate=unchecked),
+ 供调用方在 SAVEPOINT 内再跑重复检测,避免检测 DB 异常连带回滚阶段二。
+
+ Returns:
+ {document_count, candidate_count, linked_asset_count, created_asset_count, documents, candidates}
+ """
+ from app.services.shipping_notice.duplicate_detection import detect_duplicates_for_candidate
+
+ meta = result.meta if isinstance(result.meta, dict) else {}
+ email_meta = meta.get('email') if isinstance(meta.get('email'), dict) else {}
+ body_text = str(email_meta.get('body_text') or '')
+ is_eml = str(meta.get('file_type') or '').lower() == 'eml' or bool(email_meta)
+
+ active_keys: set[str] = set()
+ linked_asset_count = 0
+ created_asset_count = 0
+ documents: list[ShippingNoticeDocument] = []
+ candidates: list[ShippingNoticeCandidate] = []
+ active_candidate_doc_ids: set[int] = set()
+
+ # [STEP 1] 正文 Document:仅邮件级上下文,不生成 Candidate
+ if is_eml:
+ body_summary = parse_intake_business_summary(
+ extracted_text=body_text,
+ source_type='email',
+ )
+ body_class = _classify_document(
+ document_type='email_body',
+ filename=parent_asset.original_filename,
+ mime_type=parent_asset.mime_type,
+ parse_status='parsed' if body_text.strip() else 'empty',
+ business_summary=body_summary,
+ )
+ body_hash = hashlib.sha256(body_text.encode('utf-8')).hexdigest().lower() if body_text else None
+ body_doc = _upsert_document(
+ intake=intake,
+ attachment_key=BODY_ATTACHMENT_KEY,
+ document_type='email_body',
+ filename=parent_asset.original_filename,
+ content_hash=body_hash or str(parent_asset.content_hash or '') or None,
+ parse_status='parsed' if body_text.strip() else 'empty',
+ extracted_text=body_text or None,
+ warnings=[],
+ asset_id=None,
+ classification=body_class,
+ )
+ active_keys.add(BODY_ATTACHMENT_KEY)
+ documents.append(body_doc)
+
+ # [STEP 2] 附件派生资产 + Document + Candidate(需真实业务信号)
+ raw_attachments = list(meta.get('attachments') or [])
+ for item in raw_attachments:
+ if not isinstance(item, dict):
+ continue
+ key = str(item.get('attachment_key') or '').strip()
+ if not key:
+ continue
+ payload = pop_attachment_payload(item)
+ asset_id: int | None = None
+ if _should_persist_attachment_asset(item, payload):
+ child, created_new = create_derived_file_asset_from_bytes(
+ user_id=int(intake.user_id),
+ parent=parent_asset,
+ data=payload,
+ filename=str(item.get('filename') or f'{key}.bin'),
+ mime_type=str(item.get('mime_type') or '') or None,
+ source_attachment_key=key,
+ uploaded_storage_keys=uploaded_storage_keys,
+ )
+ asset_id = int(child.id)
+ linked_asset_count += 1
+ if created_new:
+ created_asset_count += 1
+ item['asset_no'] = child.asset_no
+ item['asset_id'] = child.id
+
+ att_text = str(item.get('extracted_text') or '')
+ att_status = str(item.get('parse_status') or 'empty')
+ att_summary = parse_intake_business_summary(
+ extracted_text=att_text,
+ source_type=_guess_source_type_for_doc(
+ filename=str(item.get('filename') or ''),
+ mime_type=str(item.get('mime_type') or ''),
+ document_type='attachment',
+ ),
+ )
+ classification = _classify_document(
+ document_type='attachment',
+ filename=str(item.get('filename') or ''),
+ mime_type=str(item.get('mime_type') or ''),
+ parse_status=att_status,
+ business_summary=att_summary,
+ )
+
+ doc = _upsert_document(
+ intake=intake,
+ attachment_key=key,
+ document_type='attachment',
+ filename=str(item.get('filename') or '') or None,
+ content_hash=str(item.get('content_hash') or '') or None,
+ parse_status=att_status,
+ extracted_text=att_text or None,
+ warnings=[str(w) for w in (item.get('warnings') or [])],
+ asset_id=asset_id,
+ classification=classification,
+ )
+ item['document_id'] = doc.id
+ active_keys.add(key)
+ documents.append(doc)
+
+ if _should_create_candidate(
+ document_type='attachment',
+ classification=classification,
+ parse_status=att_status,
+ ):
+ fp = build_business_fingerprint(att_summary)
+ if run_duplicate_detection:
+ child_asset = db.session.get(FileAsset, int(asset_id)) if asset_id else parent_asset
+ dup = detect_duplicates_for_candidate(
+ intake=intake,
+ asset=child_asset or parent_asset,
+ document=doc,
+ business_summary=att_summary,
+ fingerprint_result=fp,
+ )
+ else:
+ dup = dict(_UNCHECKED_DUP)
+ cand = _upsert_candidate(
+ intake=intake,
+ document=doc,
+ business_summary=att_summary,
+ fingerprint=fp,
+ duplicate_result=dup,
+ )
+ candidates.append(cand)
+ active_candidate_doc_ids.add(int(doc.id))
+
+ # [STEP 3] 非 EML 单文件:有真实订单信号才生成 Candidate
+ if not is_eml:
+ file_summary = parse_intake_business_summary(
+ extracted_text=str(result.text or ''),
+ source_type=str(result.source_type or 'manual'),
+ )
+ file_class = _classify_document(
+ document_type='attachment',
+ filename=result.filename,
+ mime_type=result.source_file_type,
+ parse_status='parsed',
+ business_summary=file_summary,
+ )
+ file_doc = _upsert_document(
+ intake=intake,
+ attachment_key='file',
+ document_type='attachment',
+ filename=result.filename,
+ content_hash=str(result.content_hash or parent_asset.content_hash or '') or None,
+ parse_status='parsed',
+ extracted_text=str(result.text or '') or None,
+ warnings=list(result.warnings or []),
+ asset_id=int(parent_asset.id),
+ classification=file_class,
+ )
+ active_keys.add('file')
+ documents.append(file_doc)
+ if _should_create_candidate(
+ document_type='attachment',
+ classification=file_class,
+ parse_status='parsed',
+ ):
+ fp = build_business_fingerprint(file_summary)
+ if run_duplicate_detection:
+ dup = detect_duplicates_for_candidate(
+ intake=intake,
+ asset=parent_asset,
+ document=file_doc,
+ business_summary=file_summary,
+ fingerprint_result=fp,
+ )
+ else:
+ dup = dict(_UNCHECKED_DUP)
+ cand = _upsert_candidate(
+ intake=intake,
+ document=file_doc,
+ business_summary=file_summary,
+ fingerprint=fp,
+ duplicate_result=dup,
+ )
+ candidates.append(cand)
+ active_candidate_doc_ids.add(int(file_doc.id))
+
+ # [STEP 4] 清理消失的 Document,并释放其派生资产
+ stale_docs = (
+ db.session.query(ShippingNoticeDocument)
+ .filter(
+ ShippingNoticeDocument.intake_id == int(intake.id),
+ ShippingNoticeDocument.attachment_key.notin_(tuple(active_keys) or ('__none__',)),
+ )
+ .all()
+ )
+ stale_ids = {int(d.id) for d in stale_docs}
+ if stale_ids:
+ db.session.query(ShippingNoticeCandidate).filter(
+ ShippingNoticeCandidate.intake_id == int(intake.id),
+ ShippingNoticeCandidate.primary_document_id.in_(tuple(stale_ids)),
+ ).delete(synchronize_session=False)
+ for doc in stale_docs:
+ _release_document_asset(int(doc.asset_id) if doc.asset_id else None)
+ db.session.delete(doc)
+
+ # [STEP 5] 清理本轮不再具备候选资格的旧 Candidate(Document 仍在但 classification 变了)
+ stale_cand_q = db.session.query(ShippingNoticeCandidate).filter(
+ ShippingNoticeCandidate.intake_id == int(intake.id),
+ )
+ if active_candidate_doc_ids:
+ stale_cand_q = stale_cand_q.filter(
+ ShippingNoticeCandidate.primary_document_id.notin_(tuple(active_candidate_doc_ids)),
+ )
+ stale_cand_q.delete(synchronize_session=False)
+
+ # [STEP 6] 剥离 payload,防止后续 structured_result 泄漏
+ strip_attachment_payloads(meta)
+
+ db.session.flush()
+ return {
+ 'document_count': len(documents),
+ 'candidate_count': len(candidates),
+ 'linked_asset_count': linked_asset_count,
+ 'created_asset_count': created_asset_count,
+ 'documents': [_serialize_document_brief(d, include_text=False) for d in documents],
+ 'candidates': [_serialize_candidate_brief(c) for c in candidates],
+ }
+
+
+def clear_intake_stage2_structured_projection(intake: ShippingNoticeIntake) -> None:
+ """
+ 清理 structured_result_json 中的阶段二投影(document/candidate 计数与附件资产标识)。
+
+ 核心逻辑:取消或阶段二失败后,避免摘要仍指向已删除的 Document/Asset。
+ """
+ structured = (
+ dict(intake.structured_result_json)
+ if isinstance(intake.structured_result_json, dict)
+ else {}
+ )
+ structured.pop('document_count', None)
+ structured.pop('candidate_count', None)
+ attachments = structured.get('attachments')
+ if isinstance(attachments, list):
+ cleaned: list[dict[str, Any]] = []
+ for item in attachments:
+ if not isinstance(item, dict):
+ continue
+ row = dict(item)
+ row.pop('asset_no', None)
+ row.pop('asset_id', None)
+ row.pop('document_id', None)
+ cleaned.append(row)
+ structured['attachments'] = cleaned
+ intake.structured_result_json = structured
+ intake.updated_at = datetime.utcnow()
+
+
+def release_unconsumed_intake_stage2(*, intake: ShippingNoticeIntake) -> dict[str, int]:
+ """
+ 删除未消费 Intake 的 Document/Candidate,并释放派生资产引用。
+
+ 核心逻辑:用于 cancel / 阶段二重试失败清理;已 consumed 的 Intake 不得调用。
+ Candidate 先删(FK 指向 Document),再逐项 release 派生资产后删 Document。
+
+ Args:
+ intake: 目标接入记录(须已锁定或处于独占写路径)。
+
+ Returns:
+ 删除的 candidate/document 数量及释放的 asset 次数。
+ """
+ candidates = (
+ db.session.query(ShippingNoticeCandidate)
+ .filter(ShippingNoticeCandidate.intake_id == int(intake.id))
+ .all()
+ )
+ documents = (
+ db.session.query(ShippingNoticeDocument)
+ .filter(ShippingNoticeDocument.intake_id == int(intake.id))
+ .all()
+ )
+ for cand in candidates:
+ db.session.delete(cand)
+ released_assets = 0
+ for doc in documents:
+ if doc.asset_id:
+ _release_document_asset(int(doc.asset_id))
+ released_assets += 1
+ db.session.delete(doc)
+ db.session.flush()
+ return {
+ 'deleted_candidates': len(candidates),
+ 'deleted_documents': len(documents),
+ 'released_assets': released_assets,
+ }
diff --git a/backend/app/services/shipping_notice/duplicate_detection.py b/backend/app/services/shipping_notice/duplicate_detection.py
new file mode 100644
index 00000000..4e1bdb71
--- /dev/null
+++ b/backend/app/services/shipping_notice/duplicate_detection.py
@@ -0,0 +1,609 @@
+"""
+backend/app/services/shipping_notice/duplicate_detection.py
+
+用途:发货通知业务重复检测(文件哈希 + 业务指纹),产出统一 duplicate 结果。
+依赖:models.ShippingTask/FileAsset/Document/Candidate、business_fingerprint、core.response.utc_iso。
+逻辑:Intake 级与 Candidate 级共用匹配规则;候选 A 重复只写回 A,不连带阻断同信其它候选;
+ 刷新入口按 Candidate 重检再聚合到 Intake;检测异常可 clear 为 unchecked;
+ 范围限定当前 user_id,不跨用户泄露。
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+from app import db
+from app.core.response import utc_iso
+from app.models import (
+ FileAsset,
+ ShippingNoticeCandidate,
+ ShippingNoticeDocument,
+ ShippingNoticeIntake,
+ ShippingTask,
+)
+from app.services.shipping_notice.business_fingerprint import FINGERPRINT_VERSION, build_business_fingerprint
+
+# 与 state_machine 主路径对齐的活跃/完成/关闭态(禁止 needs_review/matching/export_ready 等非主状态)
+_ACTIVE_PROCESS_STATUSES = frozenset(
+ {
+ 'created',
+ 'parsed',
+ 'pending_review',
+ 'inventory_ready',
+ 'waiting_inventory',
+ 'matched',
+ 'waiting_upload',
+ 'upload_failed',
+ }
+)
+_COMPLETED_PROCESS_STATUSES = frozenset({'uploaded', 'completed'})
+_CLOSED_PROCESS_STATUSES = frozenset({'closed', 'rejected'})
+_IRREVERSIBLE_PROCESS_STATUSES = frozenset({'uploaded', 'completed', 'closed', 'rejected'})
+
+
+def classify_task_lifecycle(process_status: str | None) -> str:
+ """将 process_status 归类为 active / completed / closed / unknown。"""
+ status = str(process_status or '').strip().lower()
+ if status in _ACTIVE_PROCESS_STATUSES:
+ return 'active'
+ if status in _COMPLETED_PROCESS_STATUSES:
+ return 'completed'
+ if status in _CLOSED_PROCESS_STATUSES:
+ return 'closed'
+ return 'unknown'
+
+
+def is_irreversible_task(task: ShippingTask) -> bool:
+ """已 uploaded 或终态任务不可原地覆盖源文件。"""
+ status = str(task.process_status or '').strip().lower()
+ if status in _IRREVERSIBLE_PROCESS_STATUSES:
+ return True
+ upload_status = str(task.upload_status or '').strip().lower()
+ return upload_status in {'uploaded', 'succeeded', 'success'}
+
+
+def _match_payload(task: ShippingTask, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]:
+ return {
+ 'task_no': task.task_no,
+ 'process_status': task.process_status,
+ 'document_version': int(task.document_version or 1),
+ 'match_type': match_type,
+ 'matched_fields': list(matched_fields),
+ 'lifecycle': classify_task_lifecycle(task.process_status),
+ 'created_at': utc_iso(task.created_at),
+ }
+
+
+def _allowed_actions_for(
+ *,
+ status: str,
+ fingerprint_strength: str,
+ matches: list[dict[str, Any]],
+) -> list[str]:
+ if status in {'none', 'unchecked'} or not matches:
+ return []
+ actions = ['open_existing']
+ primary = matches[0]
+ lifecycle = str(primary.get('lifecycle') or '')
+ if lifecycle in {'active', 'completed', 'closed'}:
+ actions.append('create_revision')
+ if fingerprint_strength in {'strong', 'medium', 'weak', 'unavailable'}:
+ actions.append('force_create')
+ return actions
+
+
+def detect_duplicates_for_intake(
+ *,
+ intake: ShippingNoticeIntake,
+ asset: FileAsset | None = None,
+ business_summary: dict[str, Any] | None = None,
+ fingerprint_result: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """
+ 对已解析 intake 执行重复检测。
+
+ 核心逻辑:
+ 1. 同用户同 content_hash 且已有未关闭任务 → exact_file;
+ 2. 同业务指纹任务 → same_active_task / same_completed_task;
+ 3. 弱指纹仅可能标记 possible_duplicate;
+ 4. strength=unavailable 不阻断。
+
+ Returns:
+ {status, blocking, fingerprint_strength, fingerprint, fingerprint_version, matches, allowed_actions, components}
+ """
+ summary = business_summary if isinstance(business_summary, dict) else (
+ intake.structured_result_json.get('business_summary')
+ if isinstance(intake.structured_result_json, dict)
+ else None
+ )
+ fp = fingerprint_result or build_business_fingerprint(summary if isinstance(summary, dict) else {})
+ strength = str(fp.get('strength') or 'unavailable')
+ fingerprint = fp.get('fingerprint')
+ version = str(fp.get('version') or FINGERPRINT_VERSION)
+ components = fp.get('components') if isinstance(fp.get('components'), dict) else {}
+
+ if asset is None:
+ asset = db.session.get(FileAsset, int(intake.asset_id))
+
+ matches: list[dict[str, Any]] = []
+ status = 'none'
+
+ # [STEP 1] 精确文件哈希
+ content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower()
+ if content_hash:
+ hash_tasks = (
+ db.session.query(ShippingTask)
+ .filter(
+ ShippingTask.user_id == int(intake.user_id),
+ ShippingTask.source_content_hash == content_hash,
+ ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
+ )
+ .order_by(ShippingTask.id.desc())
+ .limit(10)
+ .all()
+ )
+ for task in hash_tasks:
+ matches.append(
+ _match_payload(
+ task,
+ match_type='exact_file',
+ matched_fields=['source_content_hash'],
+ )
+ )
+ if matches:
+ status = 'exact_file'
+
+ # [STEP 2] 业务指纹
+ if fingerprint and strength in {'strong', 'medium'}:
+ fp_tasks = (
+ db.session.query(ShippingTask)
+ .filter(
+ ShippingTask.user_id == int(intake.user_id),
+ ShippingTask.business_fingerprint == fingerprint,
+ ShippingTask.fingerprint_version == version,
+ )
+ .order_by(ShippingTask.id.desc())
+ .limit(20)
+ .all()
+ )
+ matched_fields = list(components.keys())
+ for task in fp_tasks:
+ # 跳过已被当前 exact_file 命中过的同一 task
+ if any(m.get('task_no') == task.task_no for m in matches):
+ continue
+ matches.append(
+ _match_payload(
+ task,
+ match_type='business_fingerprint',
+ matched_fields=matched_fields,
+ )
+ )
+ if matches and status == 'none':
+ primary_life = classify_task_lifecycle(matches[0].get('process_status'))
+ if primary_life == 'active':
+ status = 'same_active_task'
+ elif primary_life == 'completed':
+ status = 'same_completed_task'
+ else:
+ status = 'possible_duplicate'
+ elif matches and status == 'exact_file':
+ # 同文件命中优先;保留 status=exact_file
+ pass
+ elif fingerprint and strength == 'weak' and status == 'none':
+ # 弱指纹:仅标记疑似,不按 active 强阻断
+ fp_tasks = (
+ db.session.query(ShippingTask)
+ .filter(
+ ShippingTask.user_id == int(intake.user_id),
+ ShippingTask.business_fingerprint == fingerprint,
+ ShippingTask.fingerprint_version == version,
+ ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
+ )
+ .order_by(ShippingTask.id.desc())
+ .limit(5)
+ .all()
+ )
+ for task in fp_tasks:
+ matches.append(
+ _match_payload(
+ task,
+ match_type='weak_fingerprint',
+ matched_fields=list(components.keys()),
+ )
+ )
+ if matches:
+ status = 'possible_duplicate'
+
+ blocking = status in {
+ 'exact_file',
+ 'same_active_task',
+ 'same_completed_task',
+ 'possible_duplicate', # 疑似重复须用户确认,不可静默建单
+ }
+ if strength == 'unavailable' and status == 'none':
+ blocking = False
+
+ return {
+ 'status': status,
+ 'blocking': blocking,
+ 'fingerprint_strength': strength,
+ 'fingerprint': fingerprint,
+ 'fingerprint_version': version,
+ 'components': components,
+ 'matches': matches,
+ 'allowed_actions': _allowed_actions_for(
+ status=status,
+ fingerprint_strength=strength,
+ matches=matches,
+ ),
+ 'checked_at': utc_iso(datetime.utcnow()),
+ }
+
+
+def apply_duplicate_result_to_intake(
+ intake: ShippingNoticeIntake,
+ result: dict[str, Any],
+) -> None:
+ """将检测结果写回 intake ORM 字段(不 commit)。"""
+ intake.business_fingerprint = result.get('fingerprint')
+ intake.fingerprint_version = result.get('fingerprint_version')
+ intake.fingerprint_strength = result.get('fingerprint_strength')
+ intake.duplicate_status = str(result.get('status') or 'none')
+ intake.duplicate_matches_json = list(result.get('matches') or [])
+ intake.duplicate_checked_at = datetime.utcnow()
+ # 重新检测后清空旧决策,避免陈旧 resolution
+ intake.duplicate_resolution = None
+ intake.duplicate_resolution_reason = None
+ intake.duplicate_target_task_no = None
+ intake.duplicate_resolved_by_id = None
+ intake.duplicate_resolved_at = None
+ intake.updated_at = datetime.utcnow()
+
+
+def clear_duplicate_state_to_unchecked(*, intake: ShippingNoticeIntake) -> None:
+ """
+ 将 Intake 与其 Candidate 的重复结果/决策统一清空为 unchecked。
+
+ 核心逻辑:重复检测 SAVEPOINT 回滚后调用,避免 partial 写回与陈旧 resolution 并存。
+ """
+ now = datetime.utcnow()
+ intake.duplicate_status = 'unchecked'
+ intake.duplicate_matches_json = []
+ intake.business_fingerprint = None
+ intake.fingerprint_version = None
+ intake.fingerprint_strength = None
+ intake.duplicate_checked_at = now
+ intake.duplicate_resolution = None
+ intake.duplicate_resolution_reason = None
+ intake.duplicate_target_task_no = None
+ intake.duplicate_resolved_by_id = None
+ intake.duplicate_resolved_at = None
+ intake.updated_at = now
+ candidates = (
+ db.session.query(ShippingNoticeCandidate)
+ .filter(ShippingNoticeCandidate.intake_id == int(intake.id))
+ .all()
+ )
+ for candidate in candidates:
+ candidate.duplicate_status = 'unchecked'
+ candidate.duplicate_matches_json = []
+ candidate.duplicate_checked_at = now
+ candidate.duplicate_resolution = None
+ candidate.duplicate_resolution_reason = None
+ candidate.duplicate_target_task_no = None
+ candidate.updated_at = now
+
+
+def apply_duplicate_result_to_candidate(
+ candidate: ShippingNoticeCandidate,
+ result: dict[str, Any],
+ *,
+ clear_resolution: bool = True,
+) -> None:
+ """
+ 将检测结果写回 Candidate ORM 字段(不 commit)。
+
+ 核心逻辑:刷新/重解析后同步 duplicate_* 与指纹概要;默认清空旧决策。
+ """
+ candidate.duplicate_status = str(result.get('status') or 'none')
+ candidate.duplicate_matches_json = list(result.get('matches') or [])
+ candidate.duplicate_checked_at = datetime.utcnow()
+ if result.get('fingerprint') is not None:
+ candidate.business_fingerprint = result.get('fingerprint')
+ if result.get('fingerprint_version') is not None:
+ candidate.fingerprint_version = result.get('fingerprint_version')
+ if result.get('fingerprint_strength') is not None:
+ candidate.fingerprint_strength = result.get('fingerprint_strength')
+ if clear_resolution:
+ candidate.duplicate_resolution = None
+ candidate.duplicate_resolution_reason = None
+ candidate.duplicate_target_task_no = None
+ candidate.updated_at = datetime.utcnow()
+
+
+def refresh_candidates_and_aggregate_intake(
+ *,
+ intake: ShippingNoticeIntake,
+ parent_asset: FileAsset | None = None,
+) -> dict[str, Any]:
+ """
+ 逐 Candidate 重跑重复检测,写回各候选后聚合 Intake 概览。
+
+ 核心逻辑:有 Candidate 时必须走候选级路径,避免仅刷新 Intake 造成数据分裂;
+ 无候选时回退扁平 Intake 级检测。
+ 调用方须已对 Intake FOR UPDATE,并确认仍为 parsed 且未消费。
+
+ Returns:
+ 聚合后的 duplicate 结果(已 apply 到 Intake;Candidate 已写回)。
+ """
+ candidates = (
+ db.session.query(ShippingNoticeCandidate)
+ .filter(ShippingNoticeCandidate.intake_id == int(intake.id))
+ .order_by(ShippingNoticeCandidate.id.asc())
+ .all()
+ )
+ if not candidates:
+ summary = (
+ intake.structured_result_json.get('business_summary')
+ if isinstance(intake.structured_result_json, dict)
+ else None
+ )
+ summary = summary if isinstance(summary, dict) else {}
+ fingerprint = build_business_fingerprint(summary)
+ result = detect_duplicates_for_intake(
+ intake=intake,
+ asset=parent_asset,
+ business_summary=summary,
+ fingerprint_result=fingerprint,
+ )
+ apply_duplicate_result_to_intake(intake, result)
+ return result
+
+ candidate_results: list[dict[str, Any]] = []
+ for candidate in candidates:
+ document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id))
+ structured = (
+ candidate.structured_result_json
+ if isinstance(candidate.structured_result_json, dict)
+ else {}
+ )
+ summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
+ fingerprint = build_business_fingerprint(summary)
+ child_asset = None
+ if document is not None and document.asset_id:
+ child_asset = db.session.get(FileAsset, int(document.asset_id))
+ dup = detect_duplicates_for_candidate(
+ intake=intake,
+ asset=child_asset or parent_asset,
+ document=document,
+ business_summary=summary,
+ fingerprint_result=fingerprint,
+ )
+ apply_duplicate_result_to_candidate(candidate, dup)
+ candidate_results.append(dup)
+
+ aggregated = aggregate_intake_duplicate_from_candidates(intake, candidate_results)
+ # 概览指纹不足时用扁平摘要补强列表展示
+ structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
+ flat_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
+ if flat_summary and not aggregated.get('fingerprint'):
+ flat_fp = build_business_fingerprint(flat_summary)
+ if flat_fp.get('fingerprint'):
+ aggregated = {
+ **aggregated,
+ 'fingerprint': flat_fp.get('fingerprint'),
+ 'fingerprint_version': flat_fp.get('version'),
+ 'fingerprint_strength': flat_fp.get('strength'),
+ 'components': flat_fp.get('components') or {},
+ }
+ apply_duplicate_result_to_intake(intake, aggregated)
+ return aggregated
+
+
+def detect_duplicates_for_candidate(
+ *,
+ intake: ShippingNoticeIntake,
+ asset: FileAsset | None = None,
+ document: ShippingNoticeDocument | None = None,
+ business_summary: dict[str, Any] | None = None,
+ fingerprint_result: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """
+ 对单个订单候选执行重复检测(不写 Intake,不影响同信其它候选)。
+
+ 核心逻辑:与 detect_duplicates_for_intake 同源规则,但 exact_file 优先用
+ Document/派生资产 content_hash(单 PDF),避免整封 EML 哈希误伤其它订单。
+
+ Returns:
+ 与 intake 检测相同结构的结果字典。
+ """
+ summary = business_summary if isinstance(business_summary, dict) else {}
+ fp = fingerprint_result or build_business_fingerprint(summary)
+ strength = str(fp.get('strength') or 'unavailable')
+ fingerprint = fp.get('fingerprint')
+ version = str(fp.get('version') or FINGERPRINT_VERSION)
+ components = fp.get('components') if isinstance(fp.get('components'), dict) else {}
+
+ content_hash = ''
+ if document is not None and str(document.content_hash or '').strip():
+ content_hash = str(document.content_hash).strip().lower()
+ if not content_hash and asset is not None:
+ content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower()
+
+ matches: list[dict[str, Any]] = []
+ status = 'none'
+
+ # [STEP 1] 精确文件哈希(附件级)
+ if content_hash:
+ hash_tasks = (
+ db.session.query(ShippingTask)
+ .filter(
+ ShippingTask.user_id == int(intake.user_id),
+ ShippingTask.source_content_hash == content_hash,
+ ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
+ )
+ .order_by(ShippingTask.id.desc())
+ .limit(10)
+ .all()
+ )
+ for task in hash_tasks:
+ matches.append(
+ _match_payload(
+ task,
+ match_type='exact_file',
+ matched_fields=['source_content_hash'],
+ )
+ )
+ if matches:
+ status = 'exact_file'
+
+ # [STEP 2] 业务指纹
+ if fingerprint and strength in {'strong', 'medium'}:
+ fp_tasks = (
+ db.session.query(ShippingTask)
+ .filter(
+ ShippingTask.user_id == int(intake.user_id),
+ ShippingTask.business_fingerprint == fingerprint,
+ ShippingTask.fingerprint_version == version,
+ )
+ .order_by(ShippingTask.id.desc())
+ .limit(20)
+ .all()
+ )
+ matched_fields = list(components.keys())
+ for task in fp_tasks:
+ if any(m.get('task_no') == task.task_no for m in matches):
+ continue
+ matches.append(
+ _match_payload(
+ task,
+ match_type='business_fingerprint',
+ matched_fields=matched_fields,
+ )
+ )
+ if matches and status == 'none':
+ primary_life = classify_task_lifecycle(matches[0].get('process_status'))
+ if primary_life == 'active':
+ status = 'same_active_task'
+ elif primary_life == 'completed':
+ status = 'same_completed_task'
+ else:
+ status = 'possible_duplicate'
+ elif fingerprint and strength == 'weak' and status == 'none':
+ fp_tasks = (
+ db.session.query(ShippingTask)
+ .filter(
+ ShippingTask.user_id == int(intake.user_id),
+ ShippingTask.business_fingerprint == fingerprint,
+ ShippingTask.fingerprint_version == version,
+ ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
+ )
+ .order_by(ShippingTask.id.desc())
+ .limit(5)
+ .all()
+ )
+ for task in fp_tasks:
+ matches.append(
+ _match_payload(
+ task,
+ match_type='weak_fingerprint',
+ matched_fields=list(components.keys()),
+ )
+ )
+ if matches:
+ status = 'possible_duplicate'
+
+ blocking = status in {
+ 'exact_file',
+ 'same_active_task',
+ 'same_completed_task',
+ 'possible_duplicate',
+ }
+ if strength == 'unavailable' and status == 'none':
+ blocking = False
+
+ return {
+ 'status': status,
+ 'blocking': blocking,
+ 'fingerprint_strength': strength,
+ 'fingerprint': fingerprint,
+ 'fingerprint_version': version,
+ 'components': components,
+ 'matches': matches,
+ 'allowed_actions': _allowed_actions_for(
+ status=status,
+ fingerprint_strength=strength,
+ matches=matches,
+ ),
+ 'checked_at': utc_iso(datetime.utcnow()),
+ }
+
+
+def aggregate_intake_duplicate_from_candidates(
+ intake: ShippingNoticeIntake,
+ candidate_results: list[dict[str, Any]],
+) -> dict[str, Any]:
+ """
+ 将多个 Candidate 检测结果汇总到 Intake(仅概览,不抹平单候选独立性)。
+
+ 核心逻辑:全部 none → none;部分阻断 → partial_duplicate;全部同态则透传该状态。
+ """
+ if not candidate_results:
+ return {
+ 'status': 'none',
+ 'blocking': False,
+ 'fingerprint_strength': 'unavailable',
+ 'fingerprint': None,
+ 'fingerprint_version': FINGERPRINT_VERSION,
+ 'components': {},
+ 'matches': [],
+ 'allowed_actions': [],
+ 'checked_at': utc_iso(datetime.utcnow()),
+ }
+
+ statuses = [str(item.get('status') or 'none') for item in candidate_results]
+ blocking_items = [item for item in candidate_results if item.get('blocking')]
+ unique_blocking = {str(item.get('status') or 'none') for item in blocking_items}
+
+ if not blocking_items:
+ status = 'none'
+ blocking = False
+ elif len(unique_blocking) == 1 and len(blocking_items) == len(candidate_results):
+ status = next(iter(unique_blocking))
+ blocking = True
+ else:
+ status = 'partial_duplicate'
+ blocking = True
+
+ # 概览指纹:取首个强/中指纹候选;否则首个候选
+ primary = next(
+ (
+ item
+ for item in candidate_results
+ if str(item.get('fingerprint_strength') or '') in {'strong', 'medium'}
+ ),
+ candidate_results[0],
+ )
+ matches: list[dict[str, Any]] = []
+ for item in blocking_items:
+ for match in item.get('matches') or []:
+ if isinstance(match, dict) and match not in matches:
+ matches.append(match)
+
+ return {
+ 'status': status,
+ 'blocking': blocking,
+ 'fingerprint_strength': primary.get('fingerprint_strength'),
+ 'fingerprint': primary.get('fingerprint'),
+ 'fingerprint_version': primary.get('fingerprint_version') or FINGERPRINT_VERSION,
+ 'components': primary.get('components') or {},
+ 'matches': matches,
+ 'allowed_actions': _allowed_actions_for(
+ status=status,
+ fingerprint_strength=str(primary.get('fingerprint_strength') or 'unavailable'),
+ matches=matches,
+ ),
+ 'checked_at': utc_iso(datetime.utcnow()),
+ 'candidate_statuses': statuses,
+ }
diff --git a/backend/app/services/shipping_notice/eml_parse.py b/backend/app/services/shipping_notice/eml_parse.py
new file mode 100644
index 00000000..25d5bb2d
--- /dev/null
+++ b/backend/app/services/shipping_notice/eml_parse.py
@@ -0,0 +1,1195 @@
+"""
+services/shipping_notice/eml_parse.py
+
+用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、真实附件及各自文本)。
+依赖:标准库 email/html;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。
+逻辑:由 notice_upload.extract_notice_text 在 file_type=eml 时调用;忽略内嵌图片/签名图;
+ 嵌套 message/rfc822 与附件型 multipart(disposition/filename)登记为独立附件;
+ 外层 body 不穿透 rfc822 / 附件型 multipart,避免订单文本误入正文或重复;
+ 单附件失败不影响其余附件;总大小:顶层容器计费,展开子内容不计费;
+ 附件摘要内存字段 `_payload_bytes` 供阶段二派生 FileAsset,写库/API 前须剥离。
+"""
+
+from __future__ import annotations
+
+import hashlib
+import html as html_lib
+import re
+import tempfile
+from dataclasses import dataclass, field
+from email import policy
+from email.message import Message
+from email.parser import BytesParser
+from email.utils import parsedate_to_datetime
+from pathlib import Path
+from typing import Any, Callable
+
+# 签名/Logo 文件名启发式(仅对 image/* 生效)
+_SIGNATURE_LOGO_NAME_RE = re.compile(
+ r"(?:^|[_.\-])(logo|signature|sig|banner|icon|spacer|pixel|footer|header)(?:[_.\-]|$)",
+ re.IGNORECASE,
+)
+
+
+@dataclass
+class EmlLimits:
+ """EML 解析安全上限。"""
+
+ max_attachments: int = 20
+ max_attachment_bytes: int = 20 * 1024 * 1024
+ max_total_attachment_bytes: int = 50 * 1024 * 1024
+ max_nesting_depth: int = 3
+
+
+def load_eml_limits() -> EmlLimits:
+ """
+ 从 Flask 配置读取 EML 安全上限;无应用上下文时回退默认值。
+
+ Returns:
+ EmlLimits: 附件数量/大小/总大小/嵌套深度上限。
+ """
+ defaults = EmlLimits()
+ try:
+ from flask import current_app
+
+ cfg = current_app.config
+ except RuntimeError:
+ return defaults
+
+ def _int(key: str, fallback: int) -> int:
+ raw = cfg.get(key)
+ try:
+ value = int(raw) if raw is not None and str(raw).strip() != "" else fallback
+ except (TypeError, ValueError):
+ return fallback
+ return value if value > 0 else fallback
+
+ return EmlLimits(
+ max_attachments=_int("SHIPPING_NOTICE_EML_MAX_ATTACHMENTS", defaults.max_attachments),
+ max_attachment_bytes=_int(
+ "SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES", defaults.max_attachment_bytes
+ ),
+ max_total_attachment_bytes=_int(
+ "SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES",
+ defaults.max_total_attachment_bytes,
+ ),
+ max_nesting_depth=_int("SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH", defaults.max_nesting_depth),
+ )
+
+
+def _header_str(msg: Message, name: str) -> str:
+ """读取并规范化邮件头为单行字符串。"""
+ raw = msg.get(name)
+ if raw is None:
+ return ""
+ return " ".join(str(raw).split())
+
+
+def _decode_part_text(part: Message | None, data: bytes) -> str:
+ """
+ 按 MIME 声明的 charset 优先解码文本字节。
+
+ 核心逻辑:先试 part.get_content_charset(),再回退 utf-8/GB/latin-1,避免欧洲邮件乱码。
+ """
+ if not data:
+ return ""
+ candidates: list[str] = []
+ charset = ""
+ if part is not None:
+ try:
+ charset = str(part.get_content_charset() or "").strip()
+ except Exception:
+ charset = ""
+ if charset:
+ candidates.append(charset)
+ candidates.extend(("utf-8", "utf-8-sig", "gb18030", "gbk", "latin-1", "cp1252"))
+ seen: set[str] = set()
+ for enc in candidates:
+ key = enc.lower().replace("_", "-")
+ if key in seen:
+ continue
+ seen.add(key)
+ try:
+ return data.decode(enc)
+ except Exception:
+ continue
+ return data.decode("utf-8", errors="replace")
+
+
+def _html_to_text(raw_html: str) -> str:
+ """
+ 简易 HTML 转文本:去脚本样式、保留表格行列边界、解码实体;不执行脚本。
+
+ 核心逻辑:→换行、|→制表符;压缩空格时不得吞掉制表符。
+ """
+ s = re.sub(r"(?is)<(script|style).*?>.*?\1>", "", raw_html or "")
+ s = re.sub(r"(?is)
", "\n", s)
+ s = re.sub(r"(?is)
", "\n", s)
+ s = re.sub(r"(?is)", "\n", s)
+ s = re.sub(r"(?is)", "\n", s)
+ s = re.sub(r"(?is)(td|th)\s*>", "\t", s)
+ s = re.sub(r"(?is)<[^>]+>", " ", s)
+ s = html_lib.unescape(s)
+ # 只压缩空格,保留 \t 作为列分隔
+ s = re.sub(r" +", " ", s)
+ s = re.sub(r" *\t *", "\t", s)
+ s = re.sub(r"\n\s*\n+", "\n\n", s)
+ return s.strip()
+
+
+def _normalize_message_id(value: str) -> str:
+ text = str(value or "").strip()
+ if not text:
+ return ""
+ return text
+
+
+def _format_date(msg: Message) -> str:
+ raw = _header_str(msg, "Date")
+ if not raw:
+ return ""
+ try:
+ dt = parsedate_to_datetime(raw)
+ if dt is not None:
+ return dt.isoformat()
+ except Exception:
+ pass
+ return raw
+
+
+def _looks_like_signature_or_logo(filename: str) -> bool:
+ name = Path(str(filename or "")).name
+ return bool(_SIGNATURE_LOGO_NAME_RE.search(name))
+
+
+def _part_filename(part: Message, fallback: str = "attachment.bin") -> str:
+ name = str(part.get_filename() or "").strip()
+ if name:
+ return name
+ ctype = str(part.get_content_type() or "application/octet-stream")
+ subtype = ctype.split("/", 1)[-1] if "/" in ctype else "bin"
+ return f"{fallback}.{subtype}"
+
+
+def _is_body_text_part(part: Message) -> bool:
+ """
+ 判定是否为邮件正文部件。
+
+ 核心逻辑:text/plain|html 且非 attachment;带 filename/name 的文本部件视为附件而非正文。
+ """
+ ctype = str(part.get_content_type() or "")
+ if ctype not in {"text/plain", "text/html"}:
+ return False
+ if part.get_content_disposition() == "attachment":
+ return False
+ if str(part.get_filename() or "").strip():
+ return False
+ return True
+
+
+def _is_inline_or_embedded_resource(part: Message) -> bool:
+ """
+ 判定应忽略的内嵌资源 / 签名图 / Logo。
+
+ 核心逻辑:仅跳过图片类 inline/CID/签名文件名;inline PDF 等可下载内容仍视为真实附件。
+ """
+ ctype = str(part.get_content_type() or "").lower()
+ disp = part.get_content_disposition()
+ content_id = str(part.get("Content-ID") or "").strip()
+ filename = str(part.get_filename() or "").strip()
+
+ if not ctype.startswith("image/"):
+ return False
+ if disp == "attachment":
+ return False
+ if disp == "inline" or content_id:
+ return True
+ if filename and _looks_like_signature_or_logo(filename):
+ return True
+ return False
+
+
+def _is_real_attachment(part: Message) -> bool:
+ """判定是否为真实附件(排除 multipart、正文、内嵌图片、嵌套 rfc822 容器)。"""
+ if part.is_multipart():
+ return False
+ ctype = str(part.get_content_type() or "").lower()
+ if ctype == "message/rfc822":
+ return False
+ if _is_body_text_part(part):
+ return False
+ if _is_inline_or_embedded_resource(part):
+ return False
+ disp = part.get_content_disposition()
+ if disp == "attachment":
+ return True
+ if part.get_filename():
+ return True
+ # inline 的非图片可下载内容(如 PDF)按真实附件处理
+ if disp == "inline" and not ctype.startswith("image/"):
+ return True
+ if not ctype.startswith("text/") and ctype not in {"message/delivery-status", "text/calendar"}:
+ if disp is None and ctype.startswith("application/"):
+ return True
+ return False
+
+
+def _read_part_payload(part: Message) -> bytes:
+ """读取 MIME 部件解码后的原始字节;失败返回空。"""
+ try:
+ payload = part.get_payload(decode=True)
+ except Exception:
+ return b""
+ if isinstance(payload, bytes):
+ return payload
+ if isinstance(payload, str):
+ return payload.encode("utf-8", errors="ignore")
+ return b""
+
+
+def _part_as_text(part: Message) -> str:
+ """将文本部件按 charset 解码并在需要时做 HTML 清洗。"""
+ raw = _read_part_payload(part)
+ text = _decode_part_text(part, raw)
+ if str(part.get_content_type() or "") == "text/html":
+ return _html_to_text(text)
+ return text.strip()
+
+
+def _is_attached_multipart(part: Message) -> bool:
+ """
+ 判定 multipart 是否应视为「文件附件容器」(而非可选正文结构)。
+
+ 核心逻辑:Content-Disposition=attachment 或带 filename/name 的 multipart/*
+ (如 bundle.mime)须登记为独立附件,禁止当外层正文树展开。
+ """
+ if not isinstance(part, Message) or not part.is_multipart():
+ return False
+ ctype = str(part.get_content_type() or "").lower()
+ if ctype == "message/rfc822":
+ return False
+ if part.get_content_disposition() == "attachment":
+ return True
+ if str(part.get_filename() or "").strip():
+ return True
+ try:
+ name_param = str(part.get_param("name") or "").strip()
+ except Exception:
+ name_param = ""
+ return bool(name_param)
+
+
+def _iter_local_body_candidates(msg: Message, *, root: bool = True):
+ """
+ 遍历可作为「当前容器正文」的 text 部件。
+
+ 核心逻辑:不穿透 message/rfc822 与附件型 multipart(二者由独立附件登记),
+ 避免外层 body_text 吞掉附件内订单文本。
+ """
+ ctype = str(msg.get_content_type() or "").lower()
+ if ctype == "message/rfc822":
+ return
+ if msg.is_multipart():
+ # 根若本身是附件型 multipart,正文候选应为空(由附件路径提取)
+ if not root and _is_attached_multipart(msg):
+ return
+ if root and _is_attached_multipart(msg):
+ return
+ parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
+ for part in parts:
+ if not isinstance(part, Message):
+ continue
+ if _is_attached_multipart(part):
+ continue
+ yield from _iter_local_body_candidates(part, root=False)
+ return
+ # 根级单部件邮件放宽到 text/*;multipart 内仅认真正无 filename 的正文部件
+ if root:
+ if _is_body_text_part(msg) or ctype in {"text/plain", "text/html"}:
+ yield msg
+ elif _is_body_text_part(msg):
+ yield msg
+
+
+def _extract_body_text(msg: Message) -> str:
+ """
+ 提取清洗后的邮件正文(仅当前消息容器,不穿透 rfc822 / 附件型 multipart)。
+
+ 核心逻辑:优先 text/plain,其次 text/html;带 filename 的部件不算正文;
+ 转发/附件容器内订单文本只出现在独立附件行,供扁平正文单次拼接。
+ """
+ plain = ""
+ html = ""
+ for part in _iter_local_body_candidates(msg):
+ ctype = str(part.get_content_type() or "")
+ text = _part_as_text(part)
+ if ctype == "text/plain" and not plain:
+ plain = text
+ elif ctype == "text/html" and not html:
+ html = text
+ return plain or html
+
+
+def _is_collectible_text_leaf(msg: Message) -> bool:
+ """判定部件是否可作为附件容器内的可落库文本叶子(非 filename 附件)。"""
+ ctype = str(msg.get_content_type() or "").lower()
+ if ctype not in {"text/plain", "text/html"}:
+ return False
+ if not _is_body_text_part(msg) and str(msg.get_filename() or "").strip():
+ return False
+ if not _is_body_text_part(msg) and msg.get_content_disposition() == "attachment":
+ return False
+ return True
+
+
+def _extract_alternative_part_text(alt: Message) -> str:
+ """
+ 从 multipart/alternative 选取单一表达:plain 优先于 html。
+
+ 核心逻辑:根节点即使带 disposition=attachment 也须进入子树;
+ 仅跳过嵌套 rfc822 / 再套一层附件型 multipart;子树内 plain 优先。
+ """
+ plain = ""
+ html = ""
+
+ def _walk(msg: Message, *, is_root: bool) -> None:
+ nonlocal plain, html
+ ctype = str(msg.get_content_type() or "").lower()
+ if ctype == "message/rfc822":
+ return
+ # 根 alternative 本身常为附件型 multipart,不得在此处直接 return
+ if not is_root and _is_attached_multipart(msg):
+ return
+ if msg.is_multipart():
+ parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
+ for part in parts:
+ if isinstance(part, Message):
+ _walk(part, is_root=False)
+ return
+ if not _is_collectible_text_leaf(msg):
+ return
+ text = _part_as_text(msg).strip()
+ if not text:
+ return
+ if ctype == "text/plain" and not plain:
+ plain = text
+ elif ctype == "text/html" and not html:
+ html = text
+
+ _walk(alt, is_root=True)
+ return plain or html
+
+
+def _extract_text_inside_attached_multipart(root: Message) -> str:
+ """
+ 从附件型 multipart 内部抽取可落库文本。
+
+ 核心逻辑:
+ - multipart/mixed(及非 alternative 容器):独立 text/plain 与 text/html 段全部拼接保留;
+ - multipart/alternative(含根即为附件型 alternative):plain 优先取一份等价表达;
+ - 不穿透嵌套 rfc822 / 再套附件型 multipart(留给 _walk_message 按 depth 展开)。
+ """
+ chunks: list[str] = []
+
+ def _walk(msg: Message, *, is_root: bool) -> None:
+ ctype = str(msg.get_content_type() or "").lower()
+ if ctype == "message/rfc822":
+ return
+ if not is_root and _is_attached_multipart(msg):
+ return
+ if msg.is_multipart():
+ if ctype == "multipart/alternative":
+ text = _extract_alternative_part_text(msg).strip()
+ if text:
+ chunks.append(text)
+ return
+ parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
+ for part in parts:
+ if isinstance(part, Message):
+ _walk(part, is_root=False)
+ return
+ if not _is_collectible_text_leaf(msg):
+ return
+ text = _part_as_text(msg).strip()
+ if text:
+ chunks.append(text)
+
+ _walk(root, is_root=True)
+ return "\n\n".join(chunks)
+
+
+def _register_skipped_attached_multipart(
+ state: _ParseState,
+ part: Message,
+ *,
+ reason: str,
+) -> None:
+ """超深/超限的附件型 multipart 登记为 skipped,供完整性门禁感知。"""
+ state.discovered_attachment_count += 1
+ if reason.startswith("eml_total_attachment_size_exceeded"):
+ if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
+ state.warnings.append(reason)
+ elif reason.startswith("eml_nesting_depth_exceeded"):
+ if not any(str(w).startswith("eml_nesting_depth_exceeded") for w in state.warnings):
+ state.warnings.append(reason)
+ elif reason not in state.warnings:
+ state.warnings.append(reason)
+ if len(state.attachments) >= state.limits.max_attachments:
+ _note_attachment_limit_exceeded(state)
+ return
+ filename = _part_filename(part, fallback="bundle")
+ try:
+ raw = part.as_bytes()
+ except Exception:
+ raw = b""
+ key = _next_attachment_key(state)
+ state.attachments.append(
+ {
+ "attachment_key": key,
+ "filename": filename,
+ "mime_type": str(part.get_content_type() or "multipart/mixed"),
+ "size": len(raw or b""),
+ "content_hash": hashlib.sha256(raw).hexdigest().lower() if raw else "",
+ "parse_status": "skipped",
+ "extracted_text": "",
+ "warnings": [reason],
+ }
+ )
+
+
+def _register_and_expand_attached_multipart(
+ state: _ParseState,
+ part: Message,
+ *,
+ depth: int,
+ count_toward_total: bool,
+) -> None:
+ """
+ 将 disposition=attachment / 带文件名的 multipart/* 登记为独立附件并展开内层。
+
+ 核心逻辑:容器计费后子内容 count_toward_total=False;容器 extracted_text 拼接内层
+ 全部正文段;再以 depth+1 walk 子树(嵌套容器计入深度上限)。
+
+ Args:
+ depth: 当前容器所在深度;展开子内容使用 depth+1。
+ """
+ state.discovered_attachment_count += 1
+ if len(state.attachments) >= state.limits.max_attachments:
+ _note_attachment_limit_exceeded(state)
+ return
+
+ try:
+ raw = part.as_bytes()
+ except Exception:
+ raw = b""
+ size = len(raw or b"")
+ filename = _part_filename(part, fallback="bundle")
+ content_hash = hashlib.sha256(raw or b"").hexdigest().lower() if raw else ""
+ key = _next_attachment_key(state)
+ item: dict[str, Any] = {
+ "attachment_key": key,
+ "filename": filename,
+ "mime_type": str(part.get_content_type() or "multipart/mixed"),
+ "size": size,
+ "content_hash": content_hash,
+ "parse_status": "skipped",
+ "extracted_text": "",
+ "warnings": [],
+ "_payload_bytes": raw or b"",
+ }
+
+ if size > state.limits.max_attachment_bytes:
+ item["parse_status"] = "skipped"
+ item["warnings"].append(f"eml_attachment_too_large:{size}")
+ state.warnings.append(f"eml_attachment_too_large:{filename}:{size}")
+ state.attachments.append(item)
+ return
+ if count_toward_total:
+ if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes:
+ item["parse_status"] = "skipped"
+ item["warnings"].append("eml_total_attachment_size_exceeded")
+ if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
+ state.warnings.append(
+ f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}"
+ )
+ state.attachments.append(item)
+ return
+ state.total_attachment_bytes += size
+
+ if content_hash and content_hash in state.seen_hashes:
+ item["parse_status"] = "duplicate"
+ item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}")
+ state.warnings.append(f"eml_attachment_duplicate:{filename}")
+ state.attachments.append(item)
+ return
+ if content_hash:
+ state.seen_hashes[content_hash] = key
+
+ text = _extract_text_inside_attached_multipart(part).strip()
+ state.attachments.append(item)
+ before_child_count = len(state.attachments)
+ # [STEP] 子内容深度 +1,与 rfc822 / 嵌套 .eml 对齐
+ _walk_message(part, state, depth=depth + 1, count_toward_total=False)
+ if text:
+ item["parse_status"] = "parsed"
+ item["extracted_text"] = text
+ elif len(state.attachments) > before_child_count:
+ # 仅含二进制子附件:容器本身无正文,仍视为成功登记
+ item["parse_status"] = "parsed"
+ item["extracted_text"] = ""
+ else:
+ item["parse_status"] = "empty"
+ item["warnings"].append("eml_attachment_empty_text")
+
+
+def _unwrap_rfc822(part: Message) -> Message | None:
+ """从 message/rfc822 部件取出内嵌 Message。"""
+ payload = part.get_payload()
+ if isinstance(payload, list) and payload:
+ inner = payload[0]
+ if isinstance(inner, Message):
+ return inner
+ if isinstance(payload, Message):
+ return payload
+ raw = _read_part_payload(part)
+ if not raw:
+ if isinstance(payload, str) and payload.strip():
+ raw = payload.encode("utf-8", errors="ignore")
+ elif isinstance(payload, bytes):
+ raw = payload
+ if not raw:
+ return None
+ try:
+ return BytesParser(policy=policy.default).parsebytes(raw)
+ except Exception:
+ return None
+
+
+def _rfc822_container_bytes(part: Message, nested: Message | None = None) -> bytes:
+ """
+ 估算 message/rfc822 容器输入字节。
+
+ 核心逻辑:优先 decode 后的 part payload;若为空(内层以 Message 对象挂载),
+ 则用 nested.as_bytes(),以便对原生转发邮件执行单附件/总量上限。
+ """
+ raw = _read_part_payload(part)
+ if raw:
+ return raw
+ target = nested
+ if target is None:
+ target = _unwrap_rfc822(part)
+ if target is None:
+ return b""
+ try:
+ return target.as_bytes()
+ except Exception:
+ return b""
+
+
+def _guess_suffix(filename: str, mime_type: str) -> str:
+ suffix = Path(filename).suffix.lower()
+ if suffix:
+ return suffix
+ mime = (mime_type or "").lower()
+ mapping = {
+ "application/pdf": ".pdf",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
+ "text/csv": ".csv",
+ "text/plain": ".txt",
+ "text/html": ".html",
+ "message/rfc822": ".eml",
+ "image/png": ".png",
+ "image/jpeg": ".jpg",
+ "image/webp": ".webp",
+ }
+ return mapping.get(mime, ".bin")
+
+
+ExtractTextFn = Callable[[Path], tuple[str, dict[str, Any]]]
+
+
+@dataclass
+class _ParseState:
+ limits: EmlLimits
+ extract_text: ExtractTextFn
+ warnings: list[str] = field(default_factory=list)
+ attachments: list[dict[str, Any]] = field(default_factory=list)
+ nested_bodies: list[str] = field(default_factory=list) # 兼容保留;v3 起 rfc822 改走 attachments,不再写入
+ seen_hashes: dict[str, str] = field(default_factory=dict)
+ total_attachment_bytes: int = 0
+ attachment_seq: int = 0
+ skipped_inline: int = 0
+ # 发现的真实附件总数(含因上限未登记的),用于 attachment_count
+ discovered_attachment_count: int = 0
+
+
+def _next_attachment_key(state: _ParseState) -> str:
+ state.attachment_seq += 1
+ return f"att-{state.attachment_seq:03d}"
+
+
+def _is_eml_payload(*, filename: str, mime_type: str) -> bool:
+ """判定附件是否为可递归的 .eml / rfc822 载荷。"""
+ suffix = Path(filename or "").suffix.lower()
+ mime = (mime_type or "").lower()
+ return suffix == ".eml" or mime in {"message/rfc822", "application/eml"}
+
+
+def _expand_eml_file_attachment(
+ *,
+ state: _ParseState,
+ payload: bytes,
+ depth: int,
+) -> tuple[str, str, list[str]]:
+ """
+ 在共享 _ParseState 下展开 .eml 文件附件。
+
+ 核心逻辑:深度 +1 后复用同一 attachments/限额/哈希,避免重新 parse_eml_bytes(depth=0)
+ 绕过嵌套与附件总数限制;容器项自身只保留内层主题+正文。
+ 容器字节已在登记时计入 total_attachment_bytes,子内容 count_toward_total=False
+ 避免与容器双重计费,同时封死「多个近似空壳大 EML」绕过总量上限。
+
+ Returns:
+ (parse_status, extracted_text, warnings)
+ """
+ next_depth = depth + 1
+ if next_depth > state.limits.max_nesting_depth:
+ warn = f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}"
+ if warn not in state.warnings:
+ state.warnings.append(warn)
+ return "skipped", "", [warn]
+ try:
+ nested = BytesParser(policy=policy.default).parsebytes(payload or b"")
+ except Exception as exc:
+ return "failed", "", [f"eml_attachment_extract_failed:{exc}"]
+
+ subject = _header_str(nested, "Subject")
+ body = _extract_body_text(nested)
+ chunks: list[str] = []
+ if subject:
+ chunks.append(f"Subject: {subject}")
+ if body:
+ chunks.append(body)
+ # 子附件计入同一 state;大小已由容器计费,不再对子 payload 累加总字节
+ _walk_message(nested, state, depth=next_depth, count_toward_total=False)
+ text = "\n\n".join(chunks).strip()
+ if not text:
+ return "empty", "", ["eml_attachment_empty_text"]
+ return "parsed", text, []
+
+
+def _extract_attachment_text(
+ *,
+ state: _ParseState,
+ filename: str,
+ mime_type: str,
+ payload: bytes,
+ depth: int,
+) -> tuple[str, str, list[str]]:
+ """
+ 抽取单个附件文本。
+
+ 核心逻辑:.eml 走共享状态展开;其他类型写临时文件调用 extract_text(PDF/DOCX 等)。
+
+ Returns:
+ (parse_status, extracted_text, warnings)
+ """
+ if _is_eml_payload(filename=filename, mime_type=mime_type):
+ return _expand_eml_file_attachment(state=state, payload=payload or b"", depth=depth)
+
+ suffix = _guess_suffix(filename, mime_type)
+ tmp_path: Path | None = None
+ try:
+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
+ tmp.write(payload)
+ tmp_path = Path(tmp.name)
+ text, meta = state.extract_text(tmp_path)
+ warn = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
+ if not str(text or "").strip():
+ return "empty", "", warn or ["eml_attachment_empty_text"]
+ return "parsed", str(text).strip(), warn
+ except Exception as exc:
+ return "failed", "", [f"eml_attachment_extract_failed:{exc}"]
+ finally:
+ if tmp_path is not None:
+ try:
+ tmp_path.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def _note_attachment_limit_exceeded(state: _ParseState) -> None:
+ """刷新「附件数量超限」警告,带上当前 discovered 总数。"""
+ prefix = "eml_attachment_limit_exceeded:"
+ state.warnings = [w for w in state.warnings if not str(w).startswith(prefix)]
+ state.warnings.append(
+ f"{prefix}{state.limits.max_attachments}:discovered={state.discovered_attachment_count}"
+ )
+
+
+def _append_attachment(
+ state: _ParseState,
+ *,
+ filename: str,
+ mime_type: str,
+ payload: bytes,
+ depth: int,
+ count_toward_total: bool = True,
+) -> None:
+ """
+ 在安全上限内登记并抽取单个真实附件。
+
+ Args:
+ count_toward_total: True 时把本附件 payload 计入总大小配额。
+ 由 .eml 容器展开出的子附件传 False(容器已计费,避免双重计费)。
+ """
+ state.discovered_attachment_count += 1
+
+ # [STEP 1] 数量上限:仍计入 discovered,但不登记抽正文
+ if len(state.attachments) >= state.limits.max_attachments:
+ _note_attachment_limit_exceeded(state)
+ return
+
+ size = len(payload or b"")
+ content_hash = hashlib.sha256(payload or b"").hexdigest().lower()
+ key = _next_attachment_key(state)
+ item: dict[str, Any] = {
+ "attachment_key": key,
+ "filename": filename,
+ "mime_type": mime_type or "application/octet-stream",
+ "size": size,
+ "content_hash": content_hash,
+ "parse_status": "skipped",
+ "extracted_text": "",
+ "warnings": [],
+ # 仅内存保留供阶段二派生资产;写 structured_result / 对外 API 前必须剥离
+ "_payload_bytes": payload or b"",
+ }
+
+ # [STEP 2] 单附件 / 总大小上限
+ # 计费规则:顶层真实附件(含 .eml 容器)计入总量;从已计费 .eml 展开的子内容不计。
+ if size > state.limits.max_attachment_bytes:
+ item["parse_status"] = "skipped"
+ item["warnings"].append(f"eml_attachment_too_large:{size}")
+ state.warnings.append(f"eml_attachment_too_large:{filename}:{size}")
+ state.attachments.append(item)
+ return
+ if count_toward_total:
+ if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes:
+ item["parse_status"] = "skipped"
+ item["warnings"].append("eml_total_attachment_size_exceeded")
+ if not any(
+ str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings
+ ):
+ state.warnings.append(
+ f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}"
+ )
+ state.attachments.append(item)
+ return
+ state.total_attachment_bytes += size
+
+ # [STEP 3] 同信内内容哈希去重(含嵌套 .eml 展开后的子附件)
+ if content_hash in state.seen_hashes:
+ item["parse_status"] = "duplicate"
+ item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}")
+ state.warnings.append(f"eml_attachment_duplicate:{filename}")
+ state.attachments.append(item)
+ return
+ state.seen_hashes[content_hash] = key
+
+ # [STEP 4] 先占位登记,再抽取/展开,确保 .eml 递归子附件计入同一数量上限
+ state.attachments.append(item)
+ status, text, warn = _extract_attachment_text(
+ state=state,
+ filename=filename,
+ mime_type=mime_type,
+ payload=payload or b"",
+ depth=depth,
+ )
+ item["parse_status"] = status
+ item["extracted_text"] = text
+ item["warnings"].extend(warn)
+ if status == "failed":
+ state.warnings.append(f"eml_attachment_extract_failed:{filename}")
+
+
+def _register_and_expand_rfc822(
+ state: _ParseState,
+ part: Message,
+ nested: Message,
+ *,
+ depth: int,
+) -> None:
+ """
+ 将原生 message/rfc822 登记为独立附件,并展开内层正文附件。
+
+ 核心逻辑:与 .eml 文件附件对齐——容器行保存主题+正文;子附件 count_toward_total=False;
+ 不写入 nested_bodies,避免与 attachment.extracted_text / 扁平正文双重拼接。
+
+ Args:
+ state: 共享解析状态(容器字节须已由调用方计费或无需计费)。
+ part: 外层 message/rfc822 MIME 部件。
+ nested: 已 unwrap 的内层 Message。
+ depth: 当前外层深度;内层 walk 使用 depth+1。
+ """
+ state.discovered_attachment_count += 1
+ if len(state.attachments) >= state.limits.max_attachments:
+ _note_attachment_limit_exceeded(state)
+ return
+
+ raw = _rfc822_container_bytes(part, nested)
+ filename = str(part.get_filename() or "").strip() or "forwarded-message.eml"
+ content_hash = hashlib.sha256(raw).hexdigest().lower() if raw else ""
+ key = _next_attachment_key(state)
+ item: dict[str, Any] = {
+ "attachment_key": key,
+ "filename": filename,
+ "mime_type": "message/rfc822",
+ "size": len(raw),
+ "content_hash": content_hash,
+ "parse_status": "empty",
+ "extracted_text": "",
+ "warnings": [],
+ "_payload_bytes": raw or b"",
+ }
+
+ if content_hash and content_hash in state.seen_hashes:
+ item["parse_status"] = "duplicate"
+ item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}")
+ state.warnings.append(f"eml_attachment_duplicate:{filename}")
+ state.attachments.append(item)
+ return
+ if content_hash:
+ state.seen_hashes[content_hash] = key
+
+ subject = _header_str(nested, "Subject")
+ body = _extract_body_text(nested)
+ chunks: list[str] = []
+ if subject:
+ chunks.append(f"Subject: {subject}")
+ if body:
+ chunks.append(body)
+ text = "\n\n".join(chunks).strip()
+ state.attachments.append(item)
+ # [STEP] 先占位再展开,使内层子附件与容器共享数量上限
+ _walk_message(nested, state, depth=depth + 1, count_toward_total=False)
+ if text:
+ item["parse_status"] = "parsed"
+ item["extracted_text"] = text
+ else:
+ item["parse_status"] = "empty"
+ item["warnings"].append("eml_attachment_empty_text")
+
+
+def _register_skipped_nested_rfc822(state: _ParseState, part: Message, *, reason: str) -> None:
+ """
+ 超深/不可读/超限的 message/rfc822 登记为 skipped 附件行,供前端徽标感知「不完整」。
+
+ Args:
+ state: 共享解析状态。
+ part: 被跳过的 rfc822 部件。
+ reason: 警告码(如 eml_nesting_depth_exceeded:N / eml_attachment_too_large:N)。
+ """
+ state.discovered_attachment_count += 1
+ # [STEP] 总量超限只保留一条顶层 warning;其它 reason 按原文去重
+ if reason.startswith("eml_total_attachment_size_exceeded"):
+ if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
+ state.warnings.append(reason)
+ elif reason not in state.warnings:
+ state.warnings.append(reason)
+ if len(state.attachments) >= state.limits.max_attachments:
+ _note_attachment_limit_exceeded(state)
+ return
+ filename = str(part.get_filename() or "").strip() or "forwarded-message.eml"
+ raw = _rfc822_container_bytes(part)
+ key = _next_attachment_key(state)
+ state.attachments.append(
+ {
+ "attachment_key": key,
+ "filename": filename,
+ "mime_type": "message/rfc822",
+ "size": len(raw),
+ "content_hash": hashlib.sha256(raw).hexdigest().lower() if raw else "",
+ "parse_status": "skipped",
+ "extracted_text": "",
+ "warnings": [reason],
+ }
+ )
+
+
+def _maybe_charge_rfc822_container(
+ state: _ParseState,
+ part: Message,
+ nested: Message,
+ *,
+ count_toward_total: bool,
+) -> bool:
+ """
+ 对原生 message/rfc822 转发容器执行单附件/总量上限并计费。
+
+ 核心逻辑:与 .eml 文件附件一致——容器字节计入配额后,内层展开 count_toward_total=False。
+
+ Returns:
+ True 表示可通过并已计费(或无需计费);False 表示已登记 skipped,调用方勿再展开。
+ """
+ if not count_toward_total:
+ return True
+ raw = _rfc822_container_bytes(part, nested)
+ size = len(raw)
+ filename = str(part.get_filename() or "").strip() or "forwarded-message.eml"
+ if size > state.limits.max_attachment_bytes:
+ reason = f"eml_attachment_too_large:{size}"
+ state.warnings.append(f"eml_attachment_too_large:{filename}:{size}")
+ _register_skipped_nested_rfc822(state, part, reason=reason)
+ return False
+ if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes:
+ reason = f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}"
+ _register_skipped_nested_rfc822(state, part, reason=reason)
+ return False
+ state.total_attachment_bytes += size
+ return True
+
+
+def _walk_message(
+ msg: Message,
+ state: _ParseState,
+ *,
+ depth: int,
+ count_toward_total: bool = True,
+) -> None:
+ """
+ 递归遍历 MIME 树:收集真实附件,展开 message/rfc822(含内层正文),跳过内嵌图片。
+
+ Args:
+ msg: 当前邮件 Message。
+ state: 共享解析状态。
+ depth: 当前嵌套深度(顶层为 0)。
+ count_toward_total: 本层登记的附件是否计入总大小配额。
+ """
+ if depth > state.limits.max_nesting_depth:
+ state.warnings.append(f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}")
+ return
+
+ if not msg.is_multipart():
+ if _is_real_attachment(msg):
+ _append_attachment(
+ state,
+ filename=_part_filename(msg),
+ mime_type=str(msg.get_content_type() or "application/octet-stream"),
+ payload=_read_part_payload(msg),
+ depth=depth,
+ count_toward_total=count_toward_total,
+ )
+ return
+
+ parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
+ for part in parts:
+ if not isinstance(part, Message):
+ continue
+ ctype = str(part.get_content_type() or "").lower()
+
+ if ctype == "message/rfc822":
+ if depth + 1 > state.limits.max_nesting_depth:
+ _register_skipped_nested_rfc822(
+ state,
+ part,
+ reason=f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}",
+ )
+ continue
+ nested = _unwrap_rfc822(part)
+ if nested is None:
+ _register_skipped_nested_rfc822(
+ state,
+ part,
+ reason="eml_nested_message_unreadable",
+ )
+ continue
+ # [STEP] 原生转发容器须计费,防止绕过单附件/总量上限
+ if not _maybe_charge_rfc822_container(
+ state,
+ part,
+ nested,
+ count_toward_total=count_toward_total,
+ ):
+ continue
+ # 成功路径登记为独立附件(与 .eml 文件附件一致),再展开内层
+ _register_and_expand_rfc822(state, part, nested, depth=depth)
+ continue
+
+ if part.is_multipart():
+ # 附件型 multipart(filename / disposition=attachment)须独立登记,禁止当正文树展开
+ if _is_attached_multipart(part):
+ next_depth = depth + 1
+ if next_depth > state.limits.max_nesting_depth:
+ _register_skipped_attached_multipart(
+ state,
+ part,
+ reason=f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}",
+ )
+ continue
+ _register_and_expand_attached_multipart(
+ state,
+ part,
+ depth=depth,
+ count_toward_total=count_toward_total,
+ )
+ continue
+ _walk_message(
+ part,
+ state,
+ depth=depth,
+ count_toward_total=count_toward_total,
+ )
+ continue
+
+ if _is_inline_or_embedded_resource(part):
+ state.skipped_inline += 1
+ continue
+
+ if _is_body_text_part(part):
+ continue
+
+ if _is_real_attachment(part):
+ _append_attachment(
+ state,
+ filename=_part_filename(part),
+ mime_type=str(part.get_content_type() or "application/octet-stream"),
+ payload=_read_part_payload(part),
+ depth=depth,
+ count_toward_total=count_toward_total,
+ )
+
+
+def _compose_flat_text(
+ *,
+ subject: str,
+ body_text: str,
+ attachments: list[dict[str, Any]],
+) -> str:
+ """将主题、正文(含转发段)与各附件文本拼成下游订单解析用的扁平正文。"""
+ parts: list[str] = []
+ if subject:
+ parts.append(f"Subject: {subject}")
+ if body_text:
+ parts.append(body_text)
+ for item in attachments:
+ if item.get("parse_status") != "parsed":
+ continue
+ text = str(item.get("extracted_text") or "").strip()
+ if not text:
+ continue
+ name = str(item.get("filename") or item.get("attachment_key") or "attachment")
+ parts.append(f"--- attachment: {name} ---\n{text}")
+ return "\n\n".join(parts)
+
+
+def parse_eml_bytes(
+ data: bytes,
+ *,
+ extract_text: ExtractTextFn,
+ limits: EmlLimits | None = None,
+ depth: int = 0,
+ retain_payloads: bool = False,
+) -> tuple[str, dict[str, Any]]:
+ """
+ 结构化解析 EML 字节流。
+
+ 核心逻辑:提取邮件头与清洗正文 → 区分真实附件与内嵌图片 → 对附件调用 extract_text;
+ 嵌套 rfc822 登记为独立附件并展开内层;不执行宏、脚本或嵌入对象。
+
+ Args:
+ data: .eml 原始字节。
+ extract_text: 叶附件文本抽取函数,签名与 extract_notice_text 一致。
+ limits: 安全上限;为空时从配置/默认加载。
+ depth: 当前嵌套深度(供嵌套 .eml 附件复用)。
+ retain_payloads: True 时在 attachments[*]._payload_bytes 保留二进制供派生资产;
+ 默认 False,返回前剥离,避免测试/JSON 路径泄漏。
+
+ Returns:
+ tuple[str, dict]: (扁平拼接文本, meta含 email/attachments/attachment_count/warnings)。
+ """
+ limits = limits or load_eml_limits()
+ if depth > limits.max_nesting_depth:
+ return "", {
+ "file_type": "eml",
+ "warnings": [f"eml_nesting_depth_exceeded:{limits.max_nesting_depth}"],
+ "email": {},
+ "attachments": [],
+ "attachment_count": 0,
+ "attachment_registered_count": 0,
+ }
+
+ msg = BytesParser(policy=policy.default).parsebytes(data or b"")
+ subject = _header_str(msg, "Subject")
+ from_addr = _header_str(msg, "From")
+ to_addr = _header_str(msg, "To")
+ date_val = _format_date(msg)
+ message_id = _normalize_message_id(_header_str(msg, "Message-ID") or _header_str(msg, "Message-Id"))
+ body_text = _extract_body_text(msg)
+
+ state = _ParseState(limits=limits, extract_text=extract_text)
+ _walk_message(msg, state, depth=depth)
+
+ if state.skipped_inline:
+ state.warnings.append(f"eml_inline_resources_skipped:{state.skipped_inline}")
+
+ body_segments = [body_text, *state.nested_bodies]
+ combined_body = "\n\n".join(segment for segment in body_segments if segment)
+
+ email_meta = {
+ "message_id": message_id,
+ "subject": subject,
+ "from": from_addr,
+ "to": to_addr,
+ "date": date_val,
+ "body_text": combined_body,
+ }
+ flat = _compose_flat_text(
+ subject=subject,
+ body_text=combined_body,
+ attachments=state.attachments,
+ )
+ meta: dict[str, Any] = {
+ "file_type": "eml",
+ "warnings": list(state.warnings),
+ "email": email_meta,
+ "attachments": list(state.attachments),
+ # attachment_count = 发现的真实附件总数(含因上限未登记的)
+ "attachment_count": int(state.discovered_attachment_count),
+ "attachment_registered_count": len(state.attachments),
+ }
+ # 注意:attachments[*]._payload_bytes 仅供同进程持久化派生资产,不得序列化进 DB/API
+ if not retain_payloads:
+ strip_attachment_payloads(meta)
+ return flat, meta
+
+
+def pop_attachment_payload(item: dict[str, Any]) -> bytes:
+ """
+ 取出并移除附件上的内存 payload。
+
+ Args:
+ item: parse_eml_bytes 产出的单条 attachment 摘要。
+
+ Returns:
+ 原始字节;无则 b""。
+ """
+ if not isinstance(item, dict):
+ return b""
+ raw = item.pop("_payload_bytes", None)
+ return raw if isinstance(raw, (bytes, bytearray)) else b""
+
+
+def strip_attachment_payloads(meta: dict[str, Any] | None) -> dict[str, Any]:
+ """
+ 就地剥除 meta.attachments 中的 `_payload_bytes`,防止二进制泄漏到摘要/API。
+
+ Returns:
+ 同一 meta 引用(或空 dict)。
+ """
+ if not isinstance(meta, dict):
+ return {}
+ for item in meta.get("attachments") or []:
+ if isinstance(item, dict):
+ item.pop("_payload_bytes", None)
+ return meta
diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py
index c701e5de..57ea6cc6 100644
--- a/backend/app/services/shipping_notice/fulfillment_workflow.py
+++ b/backend/app/services/shipping_notice/fulfillment_workflow.py
@@ -39,6 +39,7 @@ from app.services.shipping_notice.rpa_attempts import (
max_rpa_upload_attempts,
upload_rpa_attempts,
)
+from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress
from app.services.shipping_notice.tool_response import tool_response
@@ -270,6 +271,16 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
+ if not is_inventory_source_stable(task):
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message="库存源尚未确定,无法执行库存匹配。",
+ data=serialize_task_for_tool(task),
+ checkpoint="inventory_source_review",
+ stop_agent_turn=True,
+ )
+
# [STEP 3] 执行匹配并按结果分流。
# fulfillable 时继续走自动串联;shortage/异常时停在人审确认,避免误生成 Excel 或误上传。
def _on_match_progress(processed: int, total: int) -> None:
@@ -363,6 +374,15 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
+ if not is_inventory_source_stable(task):
+ return tool_response(
+ status="failed",
+ task=task,
+ message="库存源尚未确定,无法生成发货 Excel。",
+ data=serialize_task_for_tool(task),
+ forbidden_next_tools=["upload_to_freight"],
+ )
+
# [STEP 1] 若任务已有可下载的导出文件,则直接返回成功,保证重复点击“生成 Excel”幂等。
# 这里不重复生成文件,避免任务已进入 waiting_upload 后再次点击却被旧门禁误判为“未完成匹配”。
if task.export_file_path and not task_export_error_message(task):
@@ -440,6 +460,14 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
+ if not is_inventory_source_stable(task):
+ return tool_response(
+ status="failed",
+ task=task,
+ message="库存源尚未确定,无法上传货代系统。",
+ data=serialize_task_for_tool(task),
+ )
+
# [STEP 1] 先确保上传所需的 Excel 已经存在。
# 调用方可能直接请求 upload,此时需要自动补齐 generate_excel 前置步骤。
if not task.export_file_path:
diff --git a/backend/app/services/shipping_notice/i18n.py b/backend/app/services/shipping_notice/i18n.py
index 9c2e0f6d..f46b9763 100644
--- a/backend/app/services/shipping_notice/i18n.py
+++ b/backend/app/services/shipping_notice/i18n.py
@@ -105,7 +105,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.mapping_header_mismatch": "列映射与 Excel 表头不匹配。(表头在第 {row} 行){errors} 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。",
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
"workflow.inventory.file_missing": "未收到 file 字段",
- "workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .xls / .csv 库存文件",
+ "workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .csv 库存文件",
"workflow.inventory.uploading": "正在上传并解析库存文件",
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
@@ -240,7 +240,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.mapping_header_mismatch": "The column mapping does not match the Excel headers. (The header row is row {row}) {errors} Please call apply_inventory_mapping again using schema_preview.headers.",
"workflow.inventory.parse_failed_detail": "Failed to parse inventory: {error}",
"workflow.inventory.file_missing": "The file field was not received.",
- "workflow.inventory.file_type_unsupported": "Only .xlsx / .xls / .csv inventory files are supported.",
+ "workflow.inventory.file_type_unsupported": "Only .xlsx / .csv inventory files are supported.",
"workflow.inventory.uploading": "Uploading and parsing the inventory file.",
"workflow.inventory.uploading_detail": "Processing inventory file {filename}",
"workflow.inventory.save_failed": "Failed to save inventory file: {error}",
@@ -375,7 +375,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.mapping_header_mismatch": "การจับคู่คอลัมน์ไม่ตรงกับหัวตาราง Excel (หัวตารางอยู่ที่แถว {row}) {errors} โปรดเรียก apply_inventory_mapping ใหม่โดยอ้างอิง schema_preview.headers",
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
"workflow.inventory.file_missing": "ไม่ได้รับฟิลด์ file",
- "workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .xls / .csv",
+ "workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .csv",
"workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
diff --git a/backend/app/services/shipping_notice/intake_business_parser.py b/backend/app/services/shipping_notice/intake_business_parser.py
new file mode 100644
index 00000000..0f521e0f
--- /dev/null
+++ b/backend/app/services/shipping_notice/intake_business_parser.py
@@ -0,0 +1,76 @@
+"""
+backend/app/services/shipping_notice/intake_business_parser.py
+
+用途:从发货通知抽取文本产出稳定业务摘要(预解析阶段,不创建 ShippingTask)。
+依赖:extract.extract_notice_fields、notice_lines。
+逻辑:由 intake_parse_workflow 在文本抽取成功后调用;与正式 parse_notice 共用字段口径。
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from app.services.shipping_notice.extract import extract_notice_fields
+
+
+def parse_intake_business_summary(
+ *,
+ extracted_text: str,
+ source_type: str = 'manual',
+) -> dict[str, Any]:
+ """
+ 将预解析文本转为可序列化业务摘要。
+
+ 核心逻辑:调用 extract_notice_fields(无 Dify structured,走启发式兜底),
+ 提取单头/行项目/置信度;不写库。
+
+ Args:
+ extracted_text: 文本抽取结果。
+ source_type: 来源类型(pdf/email/manual 等)。
+
+ Returns:
+ 含 customer/po/reservation/lines/confidence/parse_source 的摘要字典。
+ """
+ parsed, confidence, warnings = extract_notice_fields(
+ raw_text=str(extracted_text or ''),
+ source_type=str(source_type or 'manual'),
+ structured=None,
+ )
+ lines = parsed.get('lines') if isinstance(parsed.get('lines'), list) else []
+ reservation_ids: list[str] = []
+ for line in lines:
+ if not isinstance(line, dict):
+ continue
+ rid = str(line.get('reservation_id') or '').strip()
+ if rid and rid not in reservation_ids:
+ reservation_ids.append(rid)
+ doc_rid = str(parsed.get('reservation_id') or '').strip()
+ if doc_rid and doc_rid not in reservation_ids:
+ reservation_ids.insert(0, doc_rid)
+
+ return {
+ 'customer_name': str(parsed.get('customer_name') or '').strip() or None,
+ 'customer_code': str(parsed.get('customer_code') or '').strip() or None,
+ 'po_number': str(parsed.get('po_number') or '').strip() or None,
+ 'reservation_ids': reservation_ids,
+ 'ship_to': str(parsed.get('ship_to') or '').strip() or None,
+ 'destination': {
+ 'code': str(parsed.get('destination_code') or '').strip() or None,
+ 'city': str(parsed.get('destination_city') or '').strip() or None,
+ 'country': str(parsed.get('destination_country') or '').strip() or None,
+ },
+ 'required_date': str(parsed.get('required_date') or '').strip() or None,
+ 'lines': [
+ {
+ 'sku': str(line.get('sku') or '').strip() or None,
+ 'reservation_id': str(line.get('reservation_id') or '').strip() or None,
+ 'qty': line.get('qty'),
+ 'uom': str(line.get('uom') or '').strip() or None,
+ }
+ for line in lines
+ if isinstance(line, dict)
+ ],
+ 'confidence': float(confidence or 0.0),
+ 'parse_source': str(parsed.get('parse_source') or 'heuristic'),
+ 'warnings': list(warnings),
+ }
diff --git a/backend/app/services/shipping_notice/intake_parse_workflow.py b/backend/app/services/shipping_notice/intake_parse_workflow.py
new file mode 100644
index 00000000..db227784
--- /dev/null
+++ b/backend/app/services/shipping_notice/intake_parse_workflow.py
@@ -0,0 +1,823 @@
+"""
+backend/app/services/shipping_notice/intake_parse_workflow.py
+
+用途:发货通知接入记录的文本抽取与预解析编排;intake 转 notice_item(含修订行锁)。
+依赖:notice_upload、file_assets.service、document_candidate_persist、duplicate_detection、models。
+逻辑:由 shipping_notice_parse Job handler 调用;EML 结构化 meta(email/attachments)写入
+ structured_result_json;解析成功后先落 Document/Candidate 基础行,再在 SAVEPOINT 内
+ 做 Candidate/Intake 重复检测;失败清理 clear_duplicate_state_to_unchecked;
+ 超时 Job 回收经 sync_intake_after_parse_job_recovery 同步 Intake 并清空 parse_lease;
+ 写回须匹配 parse_lease,拒绝过期 Worker。
+"""
+
+from __future__ import annotations
+
+import tempfile
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+from flask import current_app
+
+from app import db
+from app.core.errors import ConflictError
+from app.models import FileAsset, ShippingNoticeIntake, ShippingTask
+from app.services.file_assets.service import read_asset_bytes
+from app.services.shipping_notice.notice_upload import (
+ NoticeIntakeResult,
+ extract_notice_text,
+ guess_source_type,
+ max_notice_chars,
+ truncate_notice_text,
+)
+
+
+def _parser_version() -> str:
+ return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v6') or 'v6').strip()
+
+
+def _truncate_meta_text(text: str, *, limit: int | None = None) -> tuple[str, bool]:
+ """
+ 截断写入 structured_result_json 的长文本字段。
+
+ Returns:
+ (截断后文本, 是否发生截断)
+ """
+ if limit is not None:
+ cap = int(limit)
+ else:
+ try:
+ cap = max_notice_chars()
+ except RuntimeError:
+ cap = 200000
+ if cap <= 0:
+ return str(text or ''), False
+ value = str(text or '')
+ if len(value) <= cap:
+ return value, False
+ return value[:cap], True
+
+
+def _eml_stored_attachment_chars_budget() -> int:
+ """EML 全部附件落库文本合计上限;无应用上下文时回退 500000。"""
+ try:
+ raw = current_app.config.get('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS')
+ value = int(raw) if raw is not None and str(raw).strip() != '' else 500_000
+ except (RuntimeError, TypeError, ValueError):
+ return 500_000
+ return value if value > 0 else 500_000
+
+
+def _attachment_summaries_for_structured(meta: dict[str, Any]) -> tuple[list[dict[str, Any]], list[str]]:
+ """
+ 从 EML 抽取 meta 生成可写入 structured_result_json 的附件摘要。
+
+ 核心逻辑:单附件按 NOTICE_TEXT_MAX_CHARS 截断;全部附件再共享
+ SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS 总预算。
+
+ Returns:
+ (附件摘要列表, 汇总级 warnings)
+ """
+ rows: list[dict[str, Any]] = []
+ extra_warnings: list[str] = []
+ try:
+ per_limit = max_notice_chars()
+ except RuntimeError:
+ per_limit = 200000
+ budget = _eml_stored_attachment_chars_budget()
+ remaining = budget
+ for item in meta.get('attachments') or []:
+ if not isinstance(item, dict):
+ continue
+ original = str(item.get('extracted_text') or '')
+ text, truncated = _truncate_meta_text(original, limit=per_limit)
+ warn = list(item.get('warnings') or [])
+ if truncated:
+ warn = [*warn, f'eml_attachment_text_truncated:{per_limit}']
+ if remaining <= 0:
+ if text:
+ text = ''
+ warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}']
+ elif len(text) > remaining:
+ text = text[:remaining]
+ warn = [*warn, f'eml_attachment_text_budget_exhausted:{budget}']
+ remaining = 0
+ else:
+ remaining -= len(text)
+ row: dict[str, Any] = {
+ 'attachment_key': item.get('attachment_key'),
+ 'filename': item.get('filename'),
+ 'mime_type': item.get('mime_type'),
+ 'size': item.get('size'),
+ 'content_hash': item.get('content_hash'),
+ 'parse_status': item.get('parse_status'),
+ 'extracted_text': text,
+ 'text_length': len(original),
+ 'stored_text_length': len(text),
+ 'warnings': warn,
+ }
+ if item.get('asset_no'):
+ row['asset_no'] = item.get('asset_no')
+ if item.get('asset_id') is not None:
+ row['asset_id'] = item.get('asset_id')
+ if item.get('document_id') is not None:
+ row['document_id'] = item.get('document_id')
+ rows.append(row)
+ if any(
+ any(str(w).startswith('eml_attachment_text_budget_exhausted:') for w in (row.get('warnings') or []))
+ for row in rows
+ ):
+ extra_warnings.append(f'eml_attachment_text_budget_exhausted:{budget}')
+ return rows, extra_warnings
+
+
+def intake_result_to_structured_summary(
+ result: NoticeIntakeResult,
+ *,
+ business_summary: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """
+ 生成前端可展示的预解析摘要(技术摘要 + 可选业务摘要)。
+
+ 核心逻辑:普通文件仅写文件级统计;EML 额外写入 email 元数据、attachment_count 与附件摘要
+ (含各附件独立 extracted_text);email.body_text 按 notice 文本上限截断;
+ 截断警告统一为 `eml_*_truncated:{limit}`(N=上限字符数)。
+ """
+ line_count = 0
+ for line in str(result.text or '').splitlines():
+ if line.strip():
+ line_count += 1
+ payload: dict[str, Any] = {
+ 'filename': result.filename,
+ 'source_type': result.source_type,
+ 'text_length': len(result.text or ''),
+ 'line_count': line_count,
+ 'warnings': list(result.warnings),
+ 'parser_version': _parser_version(),
+ }
+ meta = result.meta if isinstance(result.meta, dict) else {}
+ email_meta = meta.get('email')
+ if isinstance(email_meta, dict) and email_meta:
+ original_body = str(email_meta.get('body_text') or '')
+ try:
+ body_limit = max_notice_chars()
+ except RuntimeError:
+ body_limit = 200000
+ body_text, body_truncated = _truncate_meta_text(original_body, limit=body_limit)
+ payload['email'] = {
+ 'message_id': email_meta.get('message_id') or '',
+ 'subject': email_meta.get('subject') or '',
+ 'from': email_meta.get('from') or '',
+ 'to': email_meta.get('to') or '',
+ 'date': email_meta.get('date') or '',
+ 'body_text': body_text,
+ 'body_text_length': len(original_body),
+ 'stored_body_text_length': len(body_text),
+ }
+ if body_truncated:
+ payload['warnings'] = [
+ *payload['warnings'],
+ f'eml_body_text_truncated:{body_limit}',
+ ]
+ if 'attachment_count' in meta:
+ payload['attachment_count'] = int(meta.get('attachment_count') or 0)
+ if 'attachment_registered_count' in meta:
+ payload['attachment_registered_count'] = int(meta.get('attachment_registered_count') or 0)
+ attachments, attach_extra_warnings = _attachment_summaries_for_structured(meta)
+ if attach_extra_warnings:
+ payload['warnings'] = [*payload['warnings'], *attach_extra_warnings]
+ if attachments:
+ payload['attachments'] = attachments
+ if isinstance(business_summary, dict):
+ payload['business_summary'] = business_summary
+ payload['confidence'] = business_summary.get('confidence')
+ payload['parse_source'] = business_summary.get('parse_source')
+ return payload
+
+
+def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult:
+ """
+ 从 FileAsset 下载并抽取发货通知文本。
+ 核心逻辑:写入临时文件后复用 extract_notice_text,避免长期落盘到 notice_uploads。
+ """
+ raw = read_asset_bytes(asset)
+ filename = str(asset.original_filename or 'notice')
+ source_type = guess_source_type(filename)
+ suffix = Path(filename).suffix or '.bin'
+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
+ tmp.write(raw)
+ tmp_path = Path(tmp.name)
+ try:
+ # EML 须保留附件二进制,供阶段二幂等创建派生 FileAsset
+ text, meta = extract_notice_text(tmp_path, retain_payloads=True)
+ warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
+ except Exception as exc:
+ return NoticeIntakeResult(
+ filename=filename,
+ source_type=source_type,
+ source_file_type=asset.mime_type,
+ text='',
+ warnings=[f'notice_extract_failed:{exc}'],
+ meta={},
+ content_hash=str(asset.content_hash or ''),
+ file_size=int(asset.file_size or 0),
+ status='extract_failed',
+ saved_path=None,
+ )
+ finally:
+ try:
+ tmp_path.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+ if not str(text or '').strip():
+ return NoticeIntakeResult(
+ filename=filename,
+ source_type=source_type,
+ source_file_type=asset.mime_type,
+ text='',
+ warnings=warnings,
+ meta=meta if isinstance(meta, dict) else {},
+ content_hash=str(asset.content_hash or ''),
+ file_size=int(asset.file_size or 0),
+ status='empty_text',
+ saved_path=None,
+ )
+
+ text, warnings = truncate_notice_text(text, warnings)
+ return NoticeIntakeResult(
+ filename=filename,
+ source_type=source_type,
+ source_file_type=asset.mime_type,
+ text=text,
+ warnings=warnings,
+ meta=meta if isinstance(meta, dict) else {},
+ content_hash=str(asset.content_hash or ''),
+ file_size=int(asset.file_size or 0),
+ status='accepted',
+ saved_path=None,
+ )
+
+
+_ABORT_WRITE_STATUSES = frozenset({'cancelled', 'expired', 'consumed'})
+# 与 cancel 同序写路径:解析写回 / 失败清理允许的状态
+_WRITABLE_PARSE_STATUSES = frozenset({'parsing', 'queued', 'created'})
+
+
+def _db_parse_status(intake_id: int) -> str | None:
+ """
+ 绕过 Session 身份映射强制读库中的 parse_status。
+
+ 核心逻辑:expire 本地缓存后 refresh,避免抽取耗时窗口内他事务 cancel 后仍读到 parsing。
+ """
+ obj = db.session.get(ShippingNoticeIntake, int(intake_id))
+ if obj is None:
+ return None
+ db.session.expire(obj)
+ db.session.refresh(obj)
+ return str(obj.parse_status or '')
+
+
+def _lock_intake_row(intake_id: int) -> ShippingNoticeIntake | None:
+ """
+ FOR UPDATE 锁定 Intake 行(与 cancel / refresh / retry 同序之首)。
+
+ 核心逻辑:先 expire 本地缓存并以 populate_existing 重读,避免抽取窗口内他事务
+ 已 cancel 而身份映射仍返回 parsing。
+ """
+ cached = db.session.get(ShippingNoticeIntake, int(intake_id))
+ if cached is not None:
+ db.session.expire(cached)
+ return (
+ db.session.query(ShippingNoticeIntake)
+ .filter(ShippingNoticeIntake.id == int(intake_id))
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+
+
+def _strip_stage2_keys_from_summary(summary: dict[str, Any]) -> dict[str, Any]:
+ """从 structured_result 摘要中剥离阶段二投影字段。"""
+ summary.pop('document_count', None)
+ summary.pop('candidate_count', None)
+ attachments = summary.get('attachments')
+ if isinstance(attachments, list):
+ for item in attachments:
+ if isinstance(item, dict):
+ item.pop('asset_no', None)
+ item.pop('asset_id', None)
+ item.pop('document_id', None)
+ return summary
+
+
+def _parse_lease_matches(
+ locked: ShippingNoticeIntake,
+ *,
+ required_lease: str | None,
+) -> bool:
+ """
+ 校验写回是否仍持有当前执行代次。
+
+ 核心逻辑:双方均为空(直连单测未发 lease)放行;否则必须精确相等。
+ 超时回收会清空 parse_lease,旧 Worker 持旧 lease 写回将被拒绝。
+ """
+ current = str(getattr(locked, 'parse_lease', None) or '').strip() or None
+ expected = str(required_lease or '').strip() or None
+ if expected is None and current is None:
+ return True
+ return expected is not None and current == expected
+
+
+def _fail_intake_with_stage2_cleanup(
+ *,
+ intake_id: int,
+ intake_no: str,
+ parser_version: str,
+ error_code: str,
+ error_message: str,
+ extracted_text: str | None,
+ structured_result_json: dict[str, Any] | None,
+ parse_warnings_json: list[str] | None,
+ allowed_statuses: frozenset[str] | None = None,
+ commit: bool = True,
+ locked_intake: ShippingNoticeIntake | None = None,
+ required_lease: str | None = None,
+) -> dict[str, Any]:
+ """
+ 持 Intake 锁清理阶段二并写 parse_failed。
+
+ 核心逻辑:与 cancel 同序(先 Intake 再 Document/资产);释放阶段二后完整清空
+ Intake 重复字段(matches/指纹/决策)。structured_result_json / parse_warnings_json
+ 为 None 时保留锁内现有值并仅剥离阶段二投影。commit=False 供 Job 回收同事务调用。
+ required_lease 不匹配时跳过(旧 Worker),避免覆盖新执行。
+ """
+ from app.services.shipping_notice.document_candidate_persist import (
+ release_unconsumed_intake_stage2,
+ )
+ from app.services.shipping_notice.duplicate_detection import (
+ clear_duplicate_state_to_unchecked,
+ )
+
+ allowed = allowed_statuses or _WRITABLE_PARSE_STATUSES
+ locked = locked_intake if locked_intake is not None else _lock_intake_row(intake_id)
+ if locked is None:
+ return {'status': 'skipped', 'intake_no': intake_no, 'parse_status': None}
+ status_now = str(locked.parse_status or '')
+ if status_now in _ABORT_WRITE_STATUSES or status_now not in allowed:
+ if commit:
+ db.session.rollback()
+ return {'status': 'skipped', 'intake_no': intake_no, 'parse_status': status_now}
+ if not _parse_lease_matches(locked, required_lease=required_lease):
+ if commit:
+ db.session.rollback()
+ return {
+ 'status': 'skipped',
+ 'intake_no': intake_no,
+ 'parse_status': status_now,
+ 'reason': 'stale_parse_lease',
+ }
+
+ release_unconsumed_intake_stage2(intake=locked)
+ clear_duplicate_state_to_unchecked(intake=locked)
+ base_summary = (
+ dict(structured_result_json)
+ if isinstance(structured_result_json, dict)
+ else dict(locked.structured_result_json or {})
+ )
+ summary = _strip_stage2_keys_from_summary(base_summary)
+ locked.parser_version = parser_version or locked.parser_version
+ locked.parse_status = 'parse_failed'
+ locked.parse_lease = None
+ locked.error_code = error_code
+ locked.error_message = str(error_message or '')[:1000]
+ # extracted_text=None 表示清空(抽取失败);Handler 路径应传入上一轮值以保留
+ locked.extracted_text = extracted_text
+ locked.structured_result_json = summary
+ if parse_warnings_json is not None:
+ locked.parse_warnings_json = list(parse_warnings_json)
+ locked.updated_at = datetime.utcnow()
+ if commit:
+ db.session.commit()
+ return {
+ 'status': 'parse_failed',
+ 'intake_no': intake_no,
+ 'error_message': locked.error_message,
+ }
+
+
+def fail_intake_with_stage2_cleanup(**kwargs: Any) -> dict[str, Any]:
+ """
+ 公开入口:领取后 Handler/回收路径写 parse_failed 并清理阶段二。
+
+ 核心逻辑:委托 _fail_intake_with_stage2_cleanup,保证资产缺失与超时失败同口径。
+ """
+ return _fail_intake_with_stage2_cleanup(**kwargs)
+
+
+def sync_intake_after_parse_job_recovery(job: Any) -> None:
+ """
+ 预解析 Job 超时回收后同步 Intake(须在 recover_stale_jobs 同事务、commit 前调用)。
+
+ 核心逻辑:仅当 parse_job_id 仍指向本 Job时处理;通常要求 Intake=parsing,
+ 但 Job→queued 还允许本轮 Handler 已先提交的 parse_failed,并恢复为 queued;
+ Job→queued 清空 parse_lease/错误(使旧 Worker 写回失效);
+ Job→cancelled 则 FOR UPDATE 锁定替代 Job 后按 queued/running 安全重指;
+ Job→failed 则持锁阶段二清理并 parse_failed。
+ """
+ from app.models import Job as JobModel
+
+ if not isinstance(job, JobModel):
+ return
+ if str(job.job_type or '') != 'shipping_notice_parse':
+ return
+ intake_no = str(
+ (job.payload_json or {}).get('intake_no') or job.business_ref or ''
+ ).strip().upper()
+ if not intake_no:
+ return
+
+ locked = (
+ db.session.query(ShippingNoticeIntake)
+ .filter(ShippingNoticeIntake.intake_no == intake_no)
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+ if locked is None:
+ return
+ if locked.parse_job_id is None or int(locked.parse_job_id) != int(job.id):
+ return
+
+ now = datetime.utcnow()
+ job_status = str(job.status or '')
+ intake_status = str(locked.parse_status or '')
+ if job_status == 'queued':
+ if intake_status not in {'parsing', 'parse_failed'}:
+ return
+ # Handler 可能已先提交 parse_failed;Job 自动重试时恢复为 queued 同一语义
+ locked.parse_status = 'queued'
+ locked.parse_lease = None
+ locked.error_code = None
+ locked.error_message = None
+ locked.updated_at = now
+ return
+ if intake_status != 'parsing':
+ return
+ if job_status == 'cancelled':
+ # 安全替代者重指;若无替代且仍挂本 Job,终态清理以免永久 parsing
+ from app.jobs.queue import (
+ _resolve_safe_supersede_sibling,
+ _retarget_intake_parse_job_after_supersede,
+ )
+
+ sibling = _resolve_safe_supersede_sibling(
+ domain=str(job.domain or ''),
+ job_type='shipping_notice_parse',
+ business_ref=job.business_ref,
+ exclude_id=int(job.id),
+ cancelled_job=job,
+ )
+ if sibling is not None:
+ _retarget_intake_parse_job_after_supersede(
+ cancelled_job=job,
+ keep_job=sibling,
+ )
+ return
+ current_lease = str(locked.parse_lease or '') or None
+ _fail_intake_with_stage2_cleanup(
+ intake_id=int(locked.id),
+ intake_no=intake_no,
+ parser_version=str(locked.parser_version or _parser_version()),
+ error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
+ error_message=str(job.message or job.error_message or '预解析 Job 已取消')[:1000],
+ extracted_text=locked.extracted_text,
+ structured_result_json=None,
+ parse_warnings_json=None,
+ allowed_statuses=frozenset({'parsing'}),
+ commit=False,
+ locked_intake=locked,
+ required_lease=current_lease,
+ )
+ return
+ if job_status == 'failed':
+ # 超时/终态失败清理:不校验 lease(当前仍是持锁的活跃解析代次)
+ current_lease = str(locked.parse_lease or '') or None
+ error_code = (
+ 'SHIPPING_NOTICE.INTAKE_PARSE_TIMEOUT'
+ if '超时' in str(job.error_message or job.message or '')
+ else 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
+ )
+ _fail_intake_with_stage2_cleanup(
+ intake_id=int(locked.id),
+ intake_no=intake_no,
+ parser_version=str(locked.parser_version or _parser_version()),
+ error_code=error_code,
+ error_message=str(job.error_message or '预解析任务失败')[:1000],
+ extracted_text=locked.extracted_text,
+ structured_result_json=None,
+ parse_warnings_json=None,
+ allowed_statuses=frozenset({'parsing'}),
+ commit=False,
+ locked_intake=locked,
+ required_lease=current_lease,
+ )
+
+
+def _run_business_dedup_after_parse(
+ intake: ShippingNoticeIntake,
+ asset: FileAsset,
+ *,
+ extracted_text: str,
+ source_type: str,
+ candidate_dup_results: list[dict[str, Any]] | None = None,
+ commit: bool = True,
+) -> dict[str, Any]:
+ """
+ 解析成功后:候选级汇总 / 扁平文本回退 → 指纹 → 写回 intake。
+
+ 核心逻辑:若已有 Candidate 检测结果则聚合为 Intake 概览(partial_duplicate 表示部分阻断);
+ 否则回退到扁平文本 Intake 级检测。commit=False 时由调用方在同一 Intake 锁事务中提交。
+
+ Returns:
+ duplicate 检测结果字典。
+ """
+ from app.services.shipping_notice.business_fingerprint import build_business_fingerprint
+ from app.services.shipping_notice.duplicate_detection import (
+ aggregate_intake_duplicate_from_candidates,
+ apply_duplicate_result_to_intake,
+ detect_duplicates_for_intake,
+ )
+ from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary
+
+ business_summary = parse_intake_business_summary(
+ extracted_text=extracted_text,
+ source_type=source_type,
+ )
+ if candidate_dup_results:
+ dup = aggregate_intake_duplicate_from_candidates(intake, candidate_dup_results)
+ # 概览指纹仍保留扁平摘要强度供列表展示
+ flat_fp = build_business_fingerprint(business_summary)
+ if not dup.get('fingerprint') and flat_fp.get('fingerprint'):
+ dup = {
+ **dup,
+ 'fingerprint': flat_fp.get('fingerprint'),
+ 'fingerprint_version': flat_fp.get('version'),
+ 'fingerprint_strength': flat_fp.get('strength'),
+ 'components': flat_fp.get('components') or {},
+ }
+ else:
+ fingerprint = build_business_fingerprint(business_summary)
+ dup = detect_duplicates_for_intake(
+ intake=intake,
+ asset=asset,
+ business_summary=business_summary,
+ fingerprint_result=fingerprint,
+ )
+ # 合并业务摘要进 structured_result_json
+ structured = dict(intake.structured_result_json or {})
+ structured['business_summary'] = business_summary
+ structured['confidence'] = business_summary.get('confidence')
+ structured['parse_source'] = business_summary.get('parse_source')
+ intake.structured_result_json = structured
+ apply_duplicate_result_to_intake(intake, dup)
+ if commit:
+ db.session.commit()
+ return dup
+
+
+def run_intake_parse(
+ intake: ShippingNoticeIntake,
+ asset: FileAsset,
+ *,
+ parse_lease: str | None = None,
+) -> dict[str, Any]:
+ """
+ 执行单条接入记录的预解析并更新 ORM 状态。
+
+ 核心逻辑:抽取文本(无锁)→ FOR UPDATE Intake → 校验 parse_lease →
+ 同事务落阶段二基础行 + parsed;重复检测在 SAVEPOINT;失败出口持锁清理。
+ parse_lease 不匹配(超时后被新 Worker 接替)则 skipped,防止旧结果覆盖。
+
+ Returns:
+ 解析结果摘要字典;若期间被取消/过期/租约失效则 status=skipped。
+ """
+ from app.services.file_assets.service import compensate_uploaded_storage_keys
+ from app.services.shipping_notice.document_candidate_persist import (
+ persist_documents_and_candidates,
+ )
+ from app.services.shipping_notice.eml_parse import strip_attachment_payloads
+
+ result = extract_notice_from_asset(asset)
+ intake_id = int(intake.id)
+ intake_no = intake.intake_no
+ parser_version = _parser_version()
+ warnings = list(result.warnings)
+ owner_user_id = int(getattr(asset, 'owner_user_id', None) or getattr(intake, 'user_id', 0) or 0)
+ storage_bucket = str(getattr(asset, 'storage_bucket', '') or '') or None
+
+ if result.status in {'extract_failed', 'empty_text'}:
+ strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {})
+ summary = intake_result_to_structured_summary(result)
+ error_message = (
+ '; '.join(warnings)[:1000] or '文本抽取失败'
+ if result.status == 'extract_failed'
+ else '未提取到有效文本'
+ )
+ return _fail_intake_with_stage2_cleanup(
+ intake_id=intake_id,
+ intake_no=intake_no,
+ parser_version=parser_version,
+ error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
+ error_message=error_message,
+ extracted_text=None,
+ structured_result_json=summary,
+ parse_warnings_json=warnings,
+ required_lease=parse_lease,
+ )
+
+ # [STEP 1] 与 cancel 同序:先锁 Intake,确认仍可写且 lease 仍有效
+ locked = _lock_intake_row(intake_id)
+ if locked is None:
+ strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {})
+ return {'status': 'skipped', 'intake_no': intake_no, 'parse_status': None}
+ status_now = str(locked.parse_status or '')
+ if status_now in _ABORT_WRITE_STATUSES or status_now not in _WRITABLE_PARSE_STATUSES:
+ db.session.rollback()
+ strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {})
+ return {
+ 'status': 'skipped',
+ 'intake_no': intake_no,
+ 'parse_status': status_now,
+ }
+ if not _parse_lease_matches(locked, required_lease=parse_lease):
+ db.session.rollback()
+ strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {})
+ return {
+ 'status': 'skipped',
+ 'intake_no': intake_no,
+ 'parse_status': status_now,
+ 'reason': 'stale_parse_lease',
+ }
+
+ persist_info: dict[str, Any] = {}
+ uploaded_storage_keys: list[str] = []
+ try:
+ # [STEP 2] 阶段二基础落库(重复检测延后到 SAVEPOINT,避免检测异常回滚 Document/资产)
+ persist_info = persist_documents_and_candidates(
+ intake=locked,
+ parent_asset=asset,
+ result=result,
+ uploaded_storage_keys=uploaded_storage_keys,
+ run_duplicate_detection=False,
+ )
+
+ tech_summary = intake_result_to_structured_summary(result)
+ tech_summary['document_count'] = persist_info.get('document_count')
+ tech_summary['candidate_count'] = persist_info.get('candidate_count')
+ locked.parser_version = parser_version
+ locked.parse_status = 'parsed'
+ locked.parse_lease = None
+ locked.error_code = None
+ locked.error_message = None
+ locked.extracted_text = result.text
+ locked.structured_result_json = tech_summary
+ locked.parse_warnings_json = warnings
+ locked.updated_at = datetime.utcnow()
+
+ # SAVEPOINT:写业务摘要 + Candidate/Intake 重复检测;失败降级 unchecked
+ from app.services.shipping_notice.duplicate_detection import (
+ clear_duplicate_state_to_unchecked,
+ refresh_candidates_and_aggregate_intake,
+ )
+ from app.services.shipping_notice.intake_business_parser import (
+ parse_intake_business_summary,
+ )
+
+ try:
+ with db.session.begin_nested():
+ business_summary = parse_intake_business_summary(
+ extracted_text=str(result.text or ''),
+ source_type=str(result.source_type or 'manual'),
+ )
+ structured = dict(locked.structured_result_json or {})
+ structured['business_summary'] = business_summary
+ structured['confidence'] = business_summary.get('confidence')
+ structured['parse_source'] = business_summary.get('parse_source')
+ locked.structured_result_json = structured
+ dup = refresh_candidates_and_aggregate_intake(
+ intake=locked,
+ parent_asset=asset,
+ )
+ except Exception:
+ clear_duplicate_state_to_unchecked(intake=locked)
+ dup = {
+ 'status': 'unchecked',
+ 'fingerprint_strength': None,
+ }
+
+ strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {})
+ db.session.commit()
+ return {
+ 'status': 'parsed',
+ 'intake_no': intake_no,
+ 'duplicate_status': dup.get('status'),
+ 'fingerprint_strength': dup.get('fingerprint_strength'),
+ 'document_count': persist_info.get('document_count'),
+ 'candidate_count': persist_info.get('candidate_count'),
+ }
+ except Exception as exc:
+ db.session.rollback()
+ compensate_uploaded_storage_keys(
+ uploaded_storage_keys,
+ owner_user_id=owner_user_id,
+ storage_bucket=storage_bucket,
+ )
+ strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {})
+ fail_summary = intake_result_to_structured_summary(result)
+ fail_warnings = [
+ *warnings,
+ f'document_candidate_persist_failed:{type(exc).__name__}:{str(exc)[:200]}',
+ ]
+ fail_summary['warnings'] = list(fail_summary.get('warnings') or []) + [
+ f'document_candidate_persist_failed:{type(exc).__name__}',
+ ]
+ return _fail_intake_with_stage2_cleanup(
+ intake_id=intake_id,
+ intake_no=intake_no,
+ parser_version=parser_version,
+ error_code='SHIPPING_NOTICE.INTAKE_STAGE2_PERSIST_FAILED',
+ error_message=(
+ f'附件资产化或候选识别失败: {type(exc).__name__}: {str(exc)[:400]}'
+ ),
+ extracted_text=result.text,
+ structured_result_json=fail_summary,
+ parse_warnings_json=fail_warnings,
+ required_lease=parse_lease,
+ )
+
+
+def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]:
+ """
+ 将已解析 intake 转为兼容 create_batch 的 notice_item(含业务指纹与重复决策元数据)。
+
+ 核心逻辑:create_revision 时对目标任务 FOR UPDATE,并拒绝已有后继,防止并发打出两个 v2。
+ """
+ item = {
+ 'source_type': guess_source_type(asset.original_filename),
+ 'source_file_name': asset.original_filename,
+ 'source_file_type': asset.mime_type,
+ 'source_content_hash': asset.content_hash,
+ 'file_size': asset.file_size,
+ 'raw_text': intake.extracted_text or '',
+ 'warnings': list(intake.parse_warnings_json or []),
+ 'source_asset_id': asset.id,
+ 'source_intake_id': intake.id,
+ 'business_fingerprint': intake.business_fingerprint,
+ 'fingerprint_version': intake.fingerprint_version,
+ 'document_version': 1,
+ 'duplicate_resolution_type': 'normal',
+ 'supersedes_task_id': None,
+ 'duplicate_source_task_id': None,
+ 'duplicate_override_reason': None,
+ }
+ resolution = str(intake.duplicate_resolution or '').strip().lower()
+ target_no = str(intake.duplicate_target_task_no or '').strip().upper()
+ if resolution == 'create_revision' and target_no:
+ target = (
+ db.session.query(ShippingTask)
+ .filter(ShippingTask.task_no == target_no)
+ .with_for_update()
+ .first()
+ )
+ if not target:
+ raise ConflictError(
+ '修订目标任务不存在',
+ code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
+ details={'target_task_no': target_no},
+ )
+ existing_successor = (
+ db.session.query(ShippingTask.id)
+ .filter(ShippingTask.supersedes_task_id == int(target.id))
+ .first()
+ )
+ if existing_successor is not None:
+ raise ConflictError(
+ '目标任务已有修订版本,请打开已有修订或重新检测',
+ code='SHIPPING_NOTICE.REVISION_CONFLICT',
+ details={'target_task_no': target.task_no, 'document_version': int(target.document_version or 1)},
+ )
+ item['supersedes_task_id'] = int(target.id)
+ item['document_version'] = int(target.document_version or 1) + 1
+ item['duplicate_resolution_type'] = 'revision'
+ elif resolution == 'force_create' and target_no:
+ target = (
+ db.session.query(ShippingTask)
+ .filter(ShippingTask.task_no == target_no)
+ .first()
+ )
+ if target:
+ item['duplicate_source_task_id'] = int(target.id)
+ item['duplicate_override_reason'] = intake.duplicate_resolution_reason
+ item['duplicate_resolution_type'] = 'force_create'
+ return item
diff --git a/backend/app/services/shipping_notice/intake_service.py b/backend/app/services/shipping_notice/intake_service.py
new file mode 100644
index 00000000..c63a1cd3
--- /dev/null
+++ b/backend/app/services/shipping_notice/intake_service.py
@@ -0,0 +1,695 @@
+"""
+backend/app/services/shipping_notice/intake_service.py
+
+用途:发货通知接入记录(ShippingNoticeIntake)业务编排(含重复决策投影与权限)。
+依赖:file_assets.service、intake_parse_workflow、jobs.queue、models、duplicate_detection、
+ attachment_integrity。
+逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行;
+ 创建 Intake:SAVEPOINT 插入 + IntegrityError 回落,mutate/enqueue 前 FOR UPDATE;
+ cancelled/expired 拒绝复活;重投仅复用 queued Job(与 retry 同口径);
+ 状态轮询用瘦身 parse_summary。
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timedelta
+from typing import Any
+
+from flask import current_app
+from sqlalchemy.exc import IntegrityError
+
+from app import db
+from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
+from app.core.response import utc_iso
+from app.jobs.queue import QUEUED_ONLY_STATUSES, enqueue
+from app.jobs.types import JobType
+from app.models import FileAsset, ShippingNoticeIntake, ShippingTask, User
+from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
+from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
+
+from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ACTIVE_INTAKE_STATUSES = frozenset(
+ {
+ 'created',
+ 'queued',
+ 'parsing',
+ 'parsed',
+ 'parse_failed',
+ 'consumed',
+ 'cancelled',
+ 'expired',
+ }
+)
+
+_DUPLICATE_RESOLUTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
+
+
+def _parser_version() -> str:
+ return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v6') or 'v6').strip()
+
+
+def _intake_ttl_hours() -> int:
+ return max(int(current_app.config.get('SHIPPING_NOTICE_INTAKE_TTL_HOURS', 72) or 72), 1)
+
+
+def generate_intake_no() -> str:
+ """生成 SNI-YYYYMMDD-XXXXXXXX 格式接入编号。"""
+ return f"SNI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
+
+
+def _duplicate_payload_from_intake(intake: ShippingNoticeIntake) -> dict[str, Any]:
+ """
+ 从 intake 投影 duplicate 载荷(供轮询/卡片展示)。
+
+ 核心逻辑:blocking 与 duplicate_detection 对齐——exact/same_* / possible 均须用户确认,
+ 避免疑似重复在前端被静默放行。
+ """
+ matches = list(intake.duplicate_matches_json or [])
+ status = str(intake.duplicate_status or 'unchecked')
+ strength = str(intake.fingerprint_strength or 'unavailable')
+ blocking = status in {
+ 'exact_file',
+ 'same_active_task',
+ 'same_completed_task',
+ 'possible_duplicate',
+ 'partial_duplicate',
+ }
+ if strength == 'unavailable' and status == 'none':
+ blocking = False
+ allowed: list[str] = []
+ if blocking:
+ allowed = ['open_existing', 'create_revision', 'force_create']
+ return {
+ 'status': status,
+ 'blocking': blocking,
+ 'fingerprint_strength': strength,
+ 'matches': matches,
+ 'allowed_actions': allowed,
+ }
+
+
+def _lean_parse_summary(structured: dict[str, Any] | None) -> dict[str, Any]:
+ """
+ 构造轮询/列表用的轻量 parse_summary:去掉附件全文与大正文,仅保留摘要字段。
+
+ 核心逻辑:状态接口高频轮询不得携带 MB 级 extracted_text;详情接口再返回全文。
+ """
+ if not isinstance(structured, dict):
+ return {}
+ out = dict(structured)
+ email = out.get('email')
+ if isinstance(email, dict):
+ lean_email = {
+ 'message_id': email.get('message_id') or '',
+ 'subject': email.get('subject') or '',
+ 'from': email.get('from') or '',
+ 'to': email.get('to') or '',
+ 'date': email.get('date') or '',
+ 'body_text_length': int(
+ email.get('body_text_length')
+ if email.get('body_text_length') is not None
+ else len(str(email.get('body_text') or ''))
+ ),
+ 'stored_body_text_length': int(
+ email.get('stored_body_text_length')
+ if email.get('stored_body_text_length') is not None
+ else len(str(email.get('body_text') or ''))
+ ),
+ }
+ out['email'] = lean_email
+ attachments = out.get('attachments')
+ if isinstance(attachments, list):
+ lean_rows: list[dict[str, Any]] = []
+ for item in attachments:
+ if not isinstance(item, dict):
+ continue
+ row = {
+ 'attachment_key': item.get('attachment_key'),
+ 'filename': item.get('filename'),
+ 'mime_type': item.get('mime_type'),
+ 'size': item.get('size'),
+ 'content_hash': item.get('content_hash'),
+ 'parse_status': item.get('parse_status'),
+ 'text_length': item.get('text_length'),
+ 'stored_text_length': item.get('stored_text_length'),
+ 'warnings': list(item.get('warnings') or []),
+ }
+ if item.get('asset_no'):
+ row['asset_no'] = item.get('asset_no')
+ if item.get('document_id') is not None:
+ row['document_id'] = item.get('document_id')
+ lean_rows.append(row)
+ out['attachments'] = lean_rows
+ return out
+
+
+def serialize_intake(
+ intake: ShippingNoticeIntake,
+ *,
+ asset: FileAsset | None = None,
+ include_parse_texts: bool = False,
+) -> dict[str, Any]:
+ """
+ 对外序列化接入记录(含业务摘要、Document/Candidate 与重复检测)。
+
+ Args:
+ include_parse_texts: True 时返回 structured 中的附件全文/正文(详情接口),
+ 并附带 documents 全文;False 时返回瘦身 parse_summary 与精简 documents/candidates。
+ """
+ from app.services.shipping_notice.document_candidate_persist import (
+ list_intake_candidates,
+ list_intake_documents,
+ )
+
+ structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
+ business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else None
+ resolution = None
+ if intake.duplicate_resolution:
+ resolution = {
+ 'action': intake.duplicate_resolution,
+ 'reason': intake.duplicate_resolution_reason,
+ 'resolved_by_id': intake.duplicate_resolved_by_id,
+ 'resolved_at': utc_iso(intake.duplicate_resolved_at),
+ 'target_task_no': intake.duplicate_target_task_no,
+ }
+ parse_summary = structured if include_parse_texts else _lean_parse_summary(structured)
+ documents = list_intake_documents(int(intake.id), include_text=include_parse_texts)
+ candidates = list_intake_candidates(int(intake.id))
+ payload: dict[str, Any] = {
+ 'intake_no': intake.intake_no,
+ 'asset_no': asset.asset_no if asset else None,
+ 'conversation_id': intake.conversation_id,
+ 'parse_status': intake.parse_status,
+ 'parser_version': intake.parser_version,
+ 'parse_summary': parse_summary,
+ 'business_summary': business_summary,
+ 'business_fingerprint': intake.business_fingerprint,
+ 'fingerprint_strength': intake.fingerprint_strength,
+ 'fingerprint_version': intake.fingerprint_version,
+ 'duplicate': _duplicate_payload_from_intake(intake),
+ 'duplicate_resolution': resolution,
+ 'documents': documents,
+ 'candidates': candidates,
+ 'document_count': len(documents),
+ 'candidate_count': len(candidates),
+ 'warnings': list(intake.parse_warnings_json or []),
+ 'error_code': intake.error_code,
+ 'error_message': intake.error_message,
+ 'expires_at': utc_iso(intake.expires_at),
+ 'consumed_at': utc_iso(intake.consumed_at),
+ 'created_at': utc_iso(intake.created_at),
+ 'updated_at': utc_iso(intake.updated_at),
+ }
+ if asset:
+ payload['original_filename'] = asset.original_filename
+ payload['file_size'] = asset.file_size
+ payload['content_hash'] = asset.content_hash
+ return payload
+
+
+def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake:
+ """按编号查询当前用户的接入记录。"""
+ normalized = str(intake_no or '').strip().upper()
+ intake = (
+ db.session.query(ShippingNoticeIntake)
+ .filter(ShippingNoticeIntake.intake_no == normalized)
+ .first()
+ )
+ if not intake or int(intake.user_id) != int(user_id):
+ raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在')
+ return intake
+
+
+def get_intake_detail(*, user_id: int, intake_no: str) -> dict[str, Any]:
+ """查询单个接入记录详情(含资产摘要与附件全文)。"""
+ intake = get_intake_for_user(intake_no, user_id)
+ asset = db.session.get(FileAsset, intake.asset_id)
+ if not asset:
+ raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
+ return serialize_intake(intake, asset=asset, include_parse_texts=True)
+
+
+def _load_asset_for_intake(intake: ShippingNoticeIntake) -> FileAsset:
+ asset = db.session.get(FileAsset, intake.asset_id)
+ if not asset or asset.deleted_at is not None:
+ raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
+ return asset
+
+
+def _lock_intake_for_asset_purpose_parser(
+ *,
+ asset_id: int,
+ purpose: str,
+ parser_version: str,
+) -> ShippingNoticeIntake | None:
+ """
+ FOR UPDATE 锁定同一资产目的+解析器版本下的 Intake(创建/重投入口串行化)。
+
+ Returns:
+ 锁定的 Intake;不存在则 None。
+ """
+ return (
+ db.session.query(ShippingNoticeIntake)
+ .filter(
+ ShippingNoticeIntake.asset_id == int(asset_id),
+ ShippingNoticeIntake.purpose == purpose,
+ ShippingNoticeIntake.parser_version == parser_version,
+ )
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+
+
+def create_shipping_notice_intake(
+ *,
+ user_id: int,
+ asset_no: str,
+ conversation_id: str | None = None,
+) -> dict[str, Any]:
+ """
+ 基于已上传 FileAsset 创建接入记录并投递解析 Job。
+
+ 核心逻辑:
+ 1. 校验资产 ready;
+ 2. FOR UPDATE 查同 (asset, purpose, parser_version);无则 SAVEPOINT 插入,
+ IntegrityError 后回落再锁已有行(并发首次创建幂等);
+ 3. parsed/consumed/queued/parsing 直接返回;cancelled/expired(含过期时间到期)冲突拒绝;
+ 4. 仅 created/parse_failed 持锁重投:enqueue(commit=False) 并绑定 parse_job_id。
+ """
+ asset = get_asset_for_user(asset_no, user_id)
+ if str(asset.upload_status or '') != 'ready':
+ raise ValidationError(code='FILE_ASSET.INVALID_STATUS', message='文件尚未上传完成')
+ if asset.expires_at and asset.expires_at < datetime.utcnow() and asset.lifecycle_status == 'temporary':
+ raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期')
+
+ parser_version = _parser_version()
+ purpose = 'shipping_notice'
+ conv = str(conversation_id or '').strip() or None
+
+ # [STEP 1] 持锁定位或创建 Intake
+ intake = _lock_intake_for_asset_purpose_parser(
+ asset_id=int(asset.id),
+ purpose=purpose,
+ parser_version=parser_version,
+ )
+ if intake is None:
+ candidate = ShippingNoticeIntake(
+ intake_no=generate_intake_no(),
+ asset_id=int(asset.id),
+ user_id=int(user_id),
+ conversation_id=conv,
+ purpose=purpose,
+ parse_status='created',
+ parser_version=parser_version,
+ expires_at=datetime.utcnow() + timedelta(hours=_intake_ttl_hours()),
+ )
+ try:
+ with db.session.begin_nested():
+ db.session.add(candidate)
+ db.session.flush()
+ intake = candidate
+ except IntegrityError:
+ # 并发他事务已插入:回落锁定已有行并幂等继续
+ intake = _lock_intake_for_asset_purpose_parser(
+ asset_id=int(asset.id),
+ purpose=purpose,
+ parser_version=parser_version,
+ )
+ if intake is None:
+ raise
+
+ # [STEP 2] 终态 / 已在飞 / 禁止复活
+ status_now = str(intake.parse_status or '')
+ if status_now in {'parsed', 'consumed', 'queued', 'parsing'}:
+ db.session.commit()
+ return serialize_intake(intake, asset=asset)
+ if status_now == 'cancelled':
+ db.session.rollback()
+ raise ConflictError(
+ code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS',
+ message='接入已取消,无法再次创建',
+ )
+ now = datetime.utcnow()
+ if status_now == 'expired' or (
+ intake.expires_at is not None and intake.expires_at < now
+ ):
+ if status_now != 'expired':
+ intake.parse_status = 'expired'
+ intake.updated_at = now
+ db.session.commit()
+ else:
+ db.session.rollback()
+ raise ConflictError(
+ code='SHIPPING_NOTICE.INTAKE_EXPIRED',
+ message='接入已过期,请重新上传文件',
+ )
+ if status_now not in {'created', 'parse_failed'}:
+ db.session.rollback()
+ raise ConflictError(
+ code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS',
+ message='当前接入状态不允许再次创建',
+ )
+
+ # [STEP 3] 持锁重投解析(仅 created / parse_failed)
+ intake.parse_status = 'queued'
+ intake.conversation_id = conv or intake.conversation_id
+ intake.error_code = None
+ intake.error_message = None
+ intake.parse_lease = None
+ intake.updated_at = now
+
+ # 与 retry 一致:仅复用 queued,不复用残留 running,避免挂到僵尸 Job
+ job_id = enqueue(
+ JobType.SHIPPING_NOTICE_PARSE,
+ {'intake_no': intake.intake_no},
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ business_ref=intake.intake_no,
+ created_by_id=user_id,
+ message='等待预解析发货通知',
+ max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3),
+ dedupe_active=True,
+ dedupe_statuses=QUEUED_ONLY_STATUSES,
+ commit=False,
+ )
+ intake.parse_job_id = job_id
+ db.session.commit()
+ return serialize_intake(intake, asset=asset)
+
+
+def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | None) -> list[dict[str, Any]]:
+ """列出会话下未消费的活跃接入记录,供页面恢复。"""
+ query = db.session.query(ShippingNoticeIntake, FileAsset).join(
+ FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id
+ ).filter(
+ ShippingNoticeIntake.user_id == int(user_id),
+ ShippingNoticeIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})),
+ ShippingNoticeIntake.consumed_at.is_(None),
+ )
+ conv = str(conversation_id or '').strip()
+ if conv:
+ query = query.filter(ShippingNoticeIntake.conversation_id == conv)
+ rows = query.order_by(ShippingNoticeIntake.created_at.desc()).limit(50).all()
+ return [serialize_intake(intake, asset=asset) for intake, asset in rows]
+
+
+def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str, Any]]:
+ """批量查询接入状态。"""
+ normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()]
+ if not normalized:
+ return []
+ rows = (
+ db.session.query(ShippingNoticeIntake, FileAsset)
+ .join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
+ .filter(
+ ShippingNoticeIntake.user_id == int(user_id),
+ ShippingNoticeIntake.intake_no.in_(normalized),
+ )
+ .all()
+ )
+ return [serialize_intake(intake, asset=asset) for intake, asset in rows]
+
+
+def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]:
+ """
+ 重试解析:parse_failed,或顶层已 parsed 但附件不完整(含文本预算耗尽)。
+
+ 核心逻辑:FOR UPDATE 持锁复检;仅复用真正 queued 的 Job(不复用 running);
+ enqueue(commit=False) 与 queued/parse_job_id 同一事务提交,避免半提交窗口。
+ """
+ from app.jobs.queue import QUEUED_ONLY_STATUSES
+
+ normalized = str(intake_no or '').strip().upper()
+ intake = (
+ db.session.query(ShippingNoticeIntake)
+ .filter(
+ ShippingNoticeIntake.intake_no == normalized,
+ ShippingNoticeIntake.user_id == int(user_id),
+ )
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+ if intake is None:
+ raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在')
+ if intake.consumed_at is not None or intake.parse_status == 'consumed':
+ raise ConflictError(
+ code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED',
+ message='接入记录已被消费',
+ )
+ if intake.parse_status == 'cancelled':
+ raise ConflictError(
+ code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS',
+ message='接入已取消,无法重试解析',
+ )
+ structured = (
+ intake.structured_result_json
+ if isinstance(intake.structured_result_json, dict)
+ else None
+ )
+ allow_retry = intake.parse_status == 'parse_failed' or (
+ intake.parse_status == 'parsed' and is_attachment_parse_incomplete(structured)
+ )
+ if not allow_retry:
+ raise ConflictError(
+ code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS',
+ message='当前状态不允许重试解析',
+ )
+ asset = _load_asset_for_intake(intake)
+ intake.parse_status = 'queued'
+ intake.error_code = None
+ intake.error_message = None
+ intake.parse_lease = None
+ intake.updated_at = datetime.utcnow()
+ job_id = enqueue(
+ JobType.SHIPPING_NOTICE_PARSE,
+ {'intake_no': intake.intake_no},
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ business_ref=intake.intake_no,
+ created_by_id=user_id,
+ message='等待重试预解析发货通知',
+ max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3),
+ dedupe_active=True,
+ dedupe_statuses=QUEUED_ONLY_STATUSES,
+ commit=False,
+ )
+ intake.parse_job_id = job_id
+ db.session.commit()
+ return serialize_intake(intake, asset=asset)
+
+
+def cancel_intake(*, user_id: int, intake_no: str) -> None:
+ """
+ 取消未消费的接入记录。
+
+ 核心逻辑:FOR UPDATE 锁定后幂等取消;删除阶段二 Document/Candidate、释放派生引用,
+ 并清理 structured_result 中的阶段二投影字段,避免并发双释放与摘要自相矛盾。
+ """
+ from app.services.shipping_notice.document_candidate_persist import (
+ clear_intake_stage2_structured_projection,
+ release_unconsumed_intake_stage2,
+ )
+
+ normalized = str(intake_no or '').strip().upper()
+ intake = (
+ db.session.query(ShippingNoticeIntake)
+ .filter(
+ ShippingNoticeIntake.intake_no == normalized,
+ ShippingNoticeIntake.user_id == int(user_id),
+ )
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+ if intake is None:
+ raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在')
+ if intake.consumed_at is not None or intake.parse_status == 'consumed':
+ raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', message='接入记录已被消费')
+ if intake.parse_status == 'cancelled':
+ # 已取消:幂等返回,禁止再次释放引用
+ return
+ release_unconsumed_intake_stage2(intake=intake)
+ clear_intake_stage2_structured_projection(intake)
+ intake.parse_status = 'cancelled'
+ intake.parse_lease = None
+ intake.updated_at = datetime.utcnow()
+ db.session.commit()
+
+
+def can_force_create_shipping_duplicate(user: User | None) -> bool:
+ """判断用户是否可强制新建重复发货通知。"""
+ if user is None:
+ return False
+ if str(getattr(user, 'role', '') or '') == 'admin':
+ return True
+ return bool(user.has_feature_permission('shipping_notice_force_create'))
+
+
+def refresh_intake_duplicate_detection(*, user_id: int, intake_no: str) -> dict[str, Any]:
+ """
+ 重新执行重复检测并写回。
+
+ 核心逻辑:FOR UPDATE 锁定 Intake 后确认仍为 parsed 且未消费;
+ 与 cancel 同序持锁再改 Candidate,避免并发删除导致 StaleDataError/死锁。
+ """
+ from app.services.shipping_notice.duplicate_detection import (
+ refresh_candidates_and_aggregate_intake,
+ )
+ from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary
+
+ normalized = str(intake_no or '').strip().upper()
+ intake = (
+ db.session.query(ShippingNoticeIntake)
+ .filter(
+ ShippingNoticeIntake.intake_no == normalized,
+ ShippingNoticeIntake.user_id == int(user_id),
+ )
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+ if intake is None:
+ raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在')
+ # 持锁后复检,避免与 cancel/consume 竞态
+ if intake.consumed_at is not None or intake.parse_status == 'consumed':
+ raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', message='接入记录已被消费')
+ if intake.parse_status == 'cancelled':
+ raise ConflictError(code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS', message='接入已取消,无法刷新重复检测')
+ if intake.parse_status != 'parsed':
+ raise ConflictError(code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS', message='仅已解析接入可刷新重复检测')
+
+ asset = _load_asset_for_intake(intake)
+ structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
+ business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else None
+ if not business_summary:
+ business_summary = parse_intake_business_summary(
+ extracted_text=str(intake.extracted_text or ''),
+ source_type='manual',
+ )
+ structured = {**structured, 'business_summary': business_summary}
+ intake.structured_result_json = structured
+ refresh_candidates_and_aggregate_intake(intake=intake, parent_asset=asset)
+ db.session.commit()
+ return serialize_intake(intake, asset=asset)
+
+
+def resolve_intake_duplicate(
+ *,
+ user_id: int,
+ intake_no: str,
+ action: str,
+ target_task_no: str | None = None,
+ reason: str | None = None,
+ actor: User | None = None,
+) -> dict[str, Any]:
+ """
+ 保存重复决策(建单前)。
+
+ 核心逻辑:刷新检测 → 校验动作/目标任务/权限与原因 → 写入 duplicate_resolution*。
+ """
+ action_norm = str(action or '').strip().lower()
+ if action_norm not in _DUPLICATE_RESOLUTIONS:
+ raise ValidationError(code='VALIDATION.INVALID_PARAM', message='无效的重复处理动作')
+
+ # [STEP 1] 先刷新检测,避免基于陈旧结果决策
+ refreshed = refresh_intake_duplicate_detection(user_id=user_id, intake_no=intake_no)
+ intake = get_intake_for_user(intake_no, user_id)
+ dup = refreshed.get('duplicate') if isinstance(refreshed.get('duplicate'), dict) else {}
+ matches = list(dup.get('matches') or [])
+ if not matches and action_norm != 'force_create':
+ # 无命中时不允许 open/revision;允许清除决策视同 none —— 此处直接返回
+ intake.duplicate_resolution = None
+ intake.duplicate_target_task_no = None
+ intake.duplicate_resolution_reason = None
+ db.session.commit()
+ asset = _load_asset_for_intake(intake)
+ return serialize_intake(intake, asset=asset)
+
+ target_no = str(target_task_no or '').strip().upper()
+ if not target_no and matches:
+ target_no = str(matches[0].get('task_no') or '').strip().upper()
+ if action_norm in {'open_existing', 'create_revision', 'force_create'} and matches:
+ if not target_no or not any(str(m.get('task_no') or '').upper() == target_no for m in matches):
+ raise NotFoundError(
+ code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND',
+ message='重复目标任务不存在或不在命中列表中',
+ )
+
+ target_task = None
+ if target_no:
+ target_task = (
+ db.session.query(ShippingTask)
+ .filter(ShippingTask.task_no == target_no, ShippingTask.user_id == int(user_id))
+ .first()
+ )
+ if not target_task:
+ raise NotFoundError(
+ code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND',
+ message='重复目标任务不存在',
+ )
+ # 目标状态相对检测结果漂移
+ match_row = next((m for m in matches if str(m.get('task_no') or '').upper() == target_no), None)
+ if match_row and str(match_row.get('process_status') or '') != str(target_task.process_status or ''):
+ raise ConflictError(
+ code='SHIPPING_NOTICE.DUPLICATE_TARGET_CHANGED',
+ message='目标任务状态已变化,请重新确认',
+ )
+
+ if action_norm == 'force_create':
+ user = actor or db.session.get(User, int(user_id))
+ if not can_force_create_shipping_duplicate(user):
+ raise ForbiddenError(
+ code='SHIPPING_NOTICE.DUPLICATE_OVERRIDE_FORBIDDEN',
+ message='无权强制新建重复发货通知',
+ )
+ if not str(reason or '').strip():
+ raise ValidationError(
+ code='SHIPPING_NOTICE.DUPLICATE_REASON_REQUIRED',
+ message='强制新建必须填写原因',
+ )
+
+ if action_norm == 'create_revision' and target_task is not None:
+ # 修订永远允许对 irreversible;open 也允许
+ pass
+
+ if action_norm == 'open_existing' and target_task is None:
+ raise NotFoundError(
+ code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND',
+ message='打开已有任务需要有效目标',
+ )
+
+ intake.duplicate_resolution = action_norm
+ intake.duplicate_target_task_no = target_no or None
+ intake.duplicate_resolution_reason = str(reason or '').strip() or None
+ intake.duplicate_resolved_by_id = int(user_id)
+ intake.duplicate_resolved_at = datetime.utcnow()
+ intake.updated_at = datetime.utcnow()
+ db.session.commit()
+ asset = _load_asset_for_intake(intake)
+ return serialize_intake(intake, asset=asset)
+
+
+def mark_intakes_consumed(
+ *,
+ intakes: list[ShippingNoticeIntake],
+ batch_id: int | None,
+ task_ids_by_intake: dict[int, int] | None = None,
+) -> None:
+ """
+ 标记 intake 为 consumed 并增加资产引用计数。
+
+ 核心逻辑:可在建批 commit 前预占(batch_id=None),避免 FOR UPDATE 在 create_batch_tasks 提交后释放导致并发双消费。
+ """
+ now = datetime.utcnow()
+ task_map = task_ids_by_intake or {}
+ for intake in intakes:
+ intake.parse_status = 'consumed'
+ intake.consumed_at = now
+ intake.consumed_batch_id = int(batch_id) if batch_id else None
+ intake.consumed_task_id = task_map.get(intake.id)
+ intake.updated_at = now
+ asset = db.session.get(FileAsset, intake.asset_id)
+ if asset:
+ mark_asset_referenced(asset)
diff --git a/backend/app/services/shipping_notice/inventory_file_identity.py b/backend/app/services/shipping_notice/inventory_file_identity.py
new file mode 100644
index 00000000..a5b568d3
--- /dev/null
+++ b/backend/app/services/shipping_notice/inventory_file_identity.py
@@ -0,0 +1,296 @@
+"""
+services/shipping_notice/inventory_file_identity.py
+
+用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。
+依赖:openpyxl、csv、app.core.errors.AppError。
+逻辑:RPA 回调、人工上传、快照入库前统一调用;流式扫描 Warehouse 列,避免大文件全量加载。
+"""
+
+from __future__ import annotations
+
+import csv
+from pathlib import Path
+from typing import Any, Iterator
+
+from openpyxl import load_workbook
+
+from app.core.errors import AppError
+
+_WAREHOUSE_ID_HEADER_ALIASES = {
+ "warehouseid",
+ "warehouse",
+ "warehousecode",
+ "warehousecodeid",
+ "whid",
+}
+_HEADER_SCAN_ROWS = 20
+
+
+def _normalize_header_key(value: Any) -> str:
+ """将 Excel 表头标准化为可比较 key。"""
+ return "".join(ch for ch in str(value or "").strip().lower() if ch.isalnum())
+
+
+def _row_non_empty_count(row: tuple[Any, ...] | list[Any]) -> int:
+ """统计行内非空单元格数量,用于跳过标题行。"""
+ return sum(1 for cell in row if str(cell or "").strip())
+
+
+def _score_warehouse_header_row(row: tuple[Any, ...] | list[Any]) -> tuple[int, int] | None:
+ """
+ 为候选表头行打分并定位 Warehouse 列。
+ 核心逻辑:要求行内至少 2 个非空单元格,避免报表标题行单独出现 Warehouse 被误判为表头。
+ """
+ if _row_non_empty_count(row) < 2:
+ return None
+ best_col: int | None = None
+ for col_idx, cell in enumerate(row):
+ if _normalize_header_key(cell) in _WAREHOUSE_ID_HEADER_ALIASES:
+ best_col = col_idx
+ break
+ if best_col is None:
+ return None
+ score = _row_non_empty_count(row) * 10 + (5 if best_col == 0 else 0)
+ return score, best_col
+
+
+def _find_warehouse_column(rows: list[tuple[Any, ...]]) -> tuple[int | None, int | None]:
+ """在表头候选区定位得分最高的 Warehouse 列。"""
+ scan_limit = min(len(rows), _HEADER_SCAN_ROWS)
+ best_score = 0
+ best_row: int | None = None
+ best_col: int | None = None
+ for row_idx in range(scan_limit):
+ scored = _score_warehouse_header_row(rows[row_idx])
+ if scored is None:
+ continue
+ score, col_idx = scored
+ if score > best_score:
+ best_score = score
+ best_row = row_idx
+ best_col = col_idx
+ return best_row, best_col
+
+
+def _load_xlsx_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]:
+ """仅读取 xlsx 前若干行供表头定位(小内存)。"""
+ try:
+ wb = load_workbook(filename=str(path), data_only=True, read_only=True)
+ except Exception:
+ return []
+ try:
+ ws = wb.active
+ rows: list[tuple[Any, ...]] = []
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
+ if i >= max_rows:
+ break
+ rows.append(tuple(row))
+ return rows
+ finally:
+ wb.close()
+
+
+def _iter_xlsx_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]:
+ """流式遍历 xlsx Warehouse 列非空值。"""
+ wb = load_workbook(filename=str(path), data_only=True, read_only=True)
+ try:
+ ws = wb.active
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
+ if i <= header_row_idx:
+ continue
+ if col_idx >= len(row):
+ continue
+ value = str(row[col_idx] or "").strip().upper()
+ if value:
+ yield value
+ finally:
+ wb.close()
+
+
+def _detect_csv_dialect(sample: str) -> csv.Dialect:
+ """探测 CSV 分隔符(逗号/分号/Tab 等),失败时回退 excel 方言。"""
+ try:
+ return csv.Sniffer().sniff(sample, delimiters=",;\t|")
+ except csv.Error:
+ return csv.excel
+
+
+def _load_csv_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]:
+ """仅读取 CSV 前若干行供表头定位。"""
+ for encoding in ("utf-8-sig", "utf-8", "gbk"):
+ try:
+ with path.open("r", encoding=encoding, newline="") as handle:
+ sample = handle.read(4096)
+ handle.seek(0)
+ dialect = _detect_csv_dialect(sample)
+ rows: list[tuple[Any, ...]] = []
+ for row in csv.reader(handle, dialect=dialect):
+ rows.append(tuple(row))
+ if len(rows) >= max_rows:
+ break
+ return rows
+ except UnicodeDecodeError:
+ continue
+ except OSError:
+ return []
+ return []
+
+
+def _iter_csv_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]:
+ """流式遍历 CSV Warehouse 列非空值。"""
+ for encoding in ("utf-8-sig", "utf-8", "gbk"):
+ try:
+ with path.open("r", encoding=encoding, newline="") as handle:
+ sample = handle.read(4096)
+ handle.seek(0)
+ dialect = _detect_csv_dialect(sample)
+ for row_idx, row in enumerate(csv.reader(handle, dialect=dialect)):
+ if row_idx <= header_row_idx:
+ continue
+ if col_idx >= len(row):
+ continue
+ value = str(row[col_idx] or "").strip().upper()
+ if value:
+ yield value
+ return
+ except UnicodeDecodeError:
+ continue
+ except OSError:
+ return
+
+
+def load_inventory_csv_rows(path: Path, *, max_rows: int | None = None) -> list[list[Any]]:
+ """
+ 读取库存 CSV 行。
+ 核心逻辑:max_rows 为 None 时读取全文件;预览场景请显式传入较小上限。
+ 身份校验请使用流式 extract_warehouse_ids_from_inventory_excel。
+ """
+ limit = None if max_rows is None else max(1, int(max_rows))
+ for encoding in ("utf-8-sig", "utf-8", "gbk"):
+ try:
+ with path.open("r", encoding=encoding, newline="") as handle:
+ sample = handle.read(4096)
+ handle.seek(0)
+ dialect = _detect_csv_dialect(sample)
+ rows: list[list[Any]] = []
+ for row in csv.reader(handle, dialect=dialect):
+ rows.append(list(row))
+ if limit is not None and len(rows) >= limit:
+ break
+ return rows
+ except UnicodeDecodeError:
+ continue
+ except OSError:
+ return []
+ return []
+
+
+def _collect_unique_warehouse_values(values: Iterator[str]) -> set[str]:
+ """从 Warehouse 列迭代器收集去重集合。"""
+ warehouses: set[str] = set()
+ for value in values:
+ warehouses.add(value)
+ return warehouses
+
+
+def extract_warehouse_ids_from_inventory_excel(path: Path) -> set[str]:
+ """
+ 从库存文件提取所有非空 Warehouse ID 值(去重)。
+ 核心逻辑:前 20 行定位表头;数据区流式扫描目标列,避免全表加载。
+ """
+ if not path or not path.is_file():
+ return set()
+
+ suffix = path.suffix.lower()
+ if suffix == ".csv":
+ header_rows = _load_csv_header_rows(path)
+ header_row_idx, col_idx = _find_warehouse_column(header_rows)
+ if header_row_idx is None or col_idx is None:
+ return set()
+ return _collect_unique_warehouse_values(
+ _iter_csv_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
+ )
+ if suffix == ".xlsx":
+ header_rows = _load_xlsx_header_rows(path)
+ header_row_idx, col_idx = _find_warehouse_column(header_rows)
+ if header_row_idx is None or col_idx is None:
+ return set()
+ return _collect_unique_warehouse_values(
+ _iter_xlsx_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
+ )
+ if suffix == ".xls":
+ return set()
+ return set()
+
+
+def assert_inventory_excel_warehouse_identity(
+ path: Path,
+ *,
+ expected_warehouse_id: str,
+ operation: str = "inventory_import",
+) -> str:
+ """
+ 强制校验 Excel 内 Warehouse ID 与预期库位一致且唯一。
+ 核心逻辑:混合多库位或内容与预期不符时抛出 AppError,拒绝入库/绑定。
+
+ Args:
+ path: 库存 Excel 路径。
+ expected_warehouse_id: 任务或运行时 source 要求的库位。
+ operation: 审计用途的操作名。
+
+ Returns:
+ str: Excel 中唯一的 Warehouse ID(大写)。
+
+ Raises:
+ AppError: 缺列、多库位或与预期不一致。
+ """
+ expected = str(expected_warehouse_id or "").strip().upper()
+ if not expected:
+ raise AppError(
+ code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
+ message="预期库位为空,无法校验库存文件内容",
+ http_status=409,
+ details={"operation": operation},
+ )
+
+ suffix = path.suffix.lower()
+ if suffix not in {".xlsx", ".csv"}:
+ raise AppError(
+ code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
+ message="库存源身份校验仅支持 .xlsx / .csv,请转换后重新上传",
+ http_status=409,
+ details={"operation": operation, "file_suffix": suffix},
+ )
+
+ found = extract_warehouse_ids_from_inventory_excel(path)
+ if not found:
+ raise AppError(
+ code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MISSING",
+ message="库存文件缺少可识别的 Warehouse ID 列或数据,已拒绝入库",
+ http_status=409,
+ details={"operation": operation, "expected_warehouse_id": expected},
+ )
+ if len(found) > 1:
+ raise AppError(
+ code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MIXED",
+ message="库存文件包含多个 Warehouse ID,已拒绝入库",
+ http_status=409,
+ details={
+ "operation": operation,
+ "expected_warehouse_id": expected,
+ "excel_warehouse_ids": sorted(found),
+ },
+ )
+ actual = next(iter(found))
+ if actual != expected:
+ raise AppError(
+ code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
+ message=f"库存文件 Warehouse ID={actual} 与任务预期库位 {expected} 不一致,已拒绝入库",
+ http_status=409,
+ details={
+ "operation": operation,
+ "expected_warehouse_id": expected,
+ "excel_warehouse_id": actual,
+ },
+ )
+ return actual
diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py
index 6fa31b47..f52bfbe0 100644
--- a/backend/app/services/shipping_notice/inventory_file_store.py
+++ b/backend/app/services/shipping_notice/inventory_file_store.py
@@ -17,12 +17,18 @@ from typing import Any
from werkzeug.datastructures import FileStorage
from app import db
+from app.core.errors import AppError
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
read_inventory_schema_preview,
)
+from app.services.shipping_notice.inventory_source_gate import (
+ is_inventory_source_stable,
+ task_inventory_identity,
+)
+from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
@@ -44,9 +50,79 @@ def generate_inventory_file_no() -> str:
return f"SIF-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
-def inventory_file_upload_path(inventory_file_no: str) -> Path:
- """库存快照文件标准落盘路径(inventory_uploads/{inventory_file_no}/inventory.xlsx)。"""
- return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / "inventory.xlsx"
+_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xlsx", ".csv"})
+
+
+def resolve_inventory_upload_suffix(filename: str) -> str:
+ """
+ 解析人工上传库存文件的合法落盘后缀。
+ 核心逻辑:仅允许 .xlsx / .csv;.xls 明确拒绝,避免按 xlsx 误读导致身份校验失败。
+
+ Raises:
+ AppError: 后缀缺失、不支持或为 .xls。
+ """
+ name = str(filename or "").strip().lower()
+ if not name or "." not in name:
+ raise AppError(
+ code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
+ message="库存上传缺少可识别的文件后缀",
+ http_status=409,
+ )
+ if name.endswith(".xlsx"):
+ return ".xlsx"
+ if name.endswith(".csv"):
+ return ".csv"
+ if name.endswith(".xls"):
+ raise AppError(
+ code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
+ message="库存上传不支持 .xls,请转换为 .xlsx 或 .csv 后重新上传",
+ http_status=409,
+ )
+ raise AppError(
+ code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
+ message="库存上传仅支持 .xlsx / .csv",
+ http_status=409,
+ )
+
+
+def inventory_file_upload_path(inventory_file_no: str, *, suffix: str = ".xlsx") -> Path:
+ """库存快照文件标准落盘路径(inventory_uploads/{inventory_file_no}/inventory{suffix})。"""
+ normalized = str(suffix or ".xlsx").lower()
+ if normalized not in _ALLOWED_INVENTORY_UPLOAD_SUFFIXES:
+ normalized = ".xlsx"
+ return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / f"inventory{normalized}"
+
+
+def inventory_storage_suffix_for_path(path: str | Path) -> str:
+ """根据已有文件路径推导库存快照落盘后缀,未知格式回退 .xlsx。"""
+ suffix = Path(path).suffix.lower()
+ return suffix if suffix in _ALLOWED_INVENTORY_UPLOAD_SUFFIXES else ".xlsx"
+
+
+def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
+ """
+ 删除库存快照托管文件及空目录。
+ 核心逻辑:数据库回滚或唯一约束冲突时清理已复制文件,避免孤儿目录。
+ """
+ import logging
+
+ if not storage_path or str(storage_path).startswith("failed://"):
+ return
+ path = Path(storage_path)
+ if path.is_file():
+ try:
+ path.unlink()
+ except OSError as exc:
+ logging.getLogger(__name__).warning("failed to delete inventory file %s: %s", path, exc)
+ parent = path.parent
+ if parent.is_dir():
+ try:
+ next(parent.iterdir())
+ except StopIteration:
+ try:
+ parent.rmdir()
+ except OSError:
+ pass
def active_inventory_file_for_task(task: ShippingTask) -> ShippingInventoryFile | None:
@@ -77,18 +153,74 @@ def has_uploaded_inventory_file(task: ShippingTask) -> bool:
return False
+def _same_stable_inventory_identity(lhs: ShippingTask, rhs: ShippingTask) -> bool:
+ """判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。"""
+ if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs):
+ return False
+ left = task_inventory_identity(lhs)
+ right = task_inventory_identity(rhs)
+ return (
+ left["inventory_source_code"] == right["inventory_source_code"]
+ and left["inventory_site_id"] == right["inventory_site_id"]
+ and left["inventory_warehouse_id"] == right["inventory_warehouse_id"]
+ )
+
+
def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> ShippingInventoryFile:
"""
保存库存 Excel 并创建批次级库存快照。
【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。
+ 核心逻辑:快照须携带任务正式库存源身份;批次 link 仅覆盖与上传票库存源一致的可重链任务。
"""
+ if not is_inventory_source_stable(task):
+ raise AppError(
+ code="SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
+ message="库存源尚未稳定,拒绝保存库存上传文件",
+ http_status=409,
+ )
+
+ identity = task_inventory_identity(task)
+ source_code = identity["inventory_source_code"] or ""
+ site_id = identity["inventory_site_id"]
+ warehouse_id = identity["inventory_warehouse_id"]
+ from datetime import datetime
+
inventory_file_no = generate_inventory_file_no()
- path = inventory_file_upload_path(inventory_file_no)
+ upload_suffix = resolve_inventory_upload_suffix(str(upload.filename or ""))
+ path = inventory_file_upload_path(inventory_file_no, suffix=upload_suffix)
path.parent.mkdir(parents=True, exist_ok=True)
- upload.save(str(path))
- preview = read_inventory_schema_preview(path)
- preview["upload_filename"] = str(upload.filename or path.name)
+ try:
+ upload.save(str(path))
+ from app.services.shipping_notice.inventory_file_identity import (
+ assert_inventory_excel_warehouse_identity,
+ )
+
+ assert_inventory_excel_warehouse_identity(
+ path,
+ expected_warehouse_id=str(warehouse_id or ""),
+ operation="manual_upload",
+ )
+ preview = read_inventory_schema_preview(path)
+ preview["upload_filename"] = str(upload.filename or path.name)
+ except AppError:
+ if path.is_file():
+ try:
+ path.unlink()
+ except OSError:
+ import logging
+
+ logging.getLogger(__name__).warning(
+ "failed to delete rejected inventory upload file %s", path
+ )
+ raise
+ except Exception:
+ if path.is_file():
+ try:
+ path.unlink()
+ except OSError:
+ pass
+ raise
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
@@ -97,16 +229,59 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
source_file_name=str(upload.filename or "").strip() or path.name,
storage_path=str(path),
schema_preview_json=preview,
- share_mode="batch_all" if task.batch_id else "task_only",
+ share_mode="task_only",
line_count=0,
+ source_code=source_code,
+ source_type=str(task.inventory_source_type or "").strip() or None,
+ site_id=site_id,
+ warehouse_id=warehouse_id,
+ source_config_version=task.inventory_source_config_version or get_inventory_sources_config_version(),
+ identity_status="pending",
+ snapshot_status="ready",
+ exported_at=datetime.utcnow(),
)
db.session.add(inv_file)
db.session.flush()
candidates = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task]
- linked_tasks = [item for item in candidates if _can_relink_inventory(item)]
+ linked_tasks = [
+ item
+ for item in candidates
+ if _can_relink_inventory(item) and _same_stable_inventory_identity(task, item)
+ ]
+ from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
+
+ created_links: list[ShippingTaskInventoryLink] = []
for item in linked_tasks:
- replace_task_inventory_link(item, inv_file, role="owner" if item.id == task.id else "member")
+ link = link_snapshot_to_task(
+ item,
+ inv_file,
+ reason="manual_upload",
+ role="owner" if item.id == task.id else "member",
+ audit_payload={"upload_filename": preview.get("upload_filename")},
+ )
+ if link is None:
+ for prior in created_links:
+ db.session.delete(prior)
+ db.session.delete(inv_file)
+ db.session.flush()
+ if path.is_file():
+ try:
+ path.unlink()
+ except OSError:
+ import logging
+
+ logging.getLogger(__name__).warning(
+ "failed to delete inventory upload after link failure %s", path
+ )
+ raise AppError(
+ code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
+ message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝批次绑定",
+ http_status=409,
+ )
+ created_links.append(link)
+ if len(linked_tasks) > 1:
+ inv_file.share_mode = "batch_same_identity"
return inv_file
@@ -139,7 +314,8 @@ def save_task_inventory_file_from_local_path(
raise FileNotFoundError(f"未找到库存源文件: {source}")
inventory_file_no = generate_inventory_file_no()
- path = inventory_file_upload_path(inventory_file_no)
+ storage_suffix = inventory_storage_suffix_for_path(source)
+ path = inventory_file_upload_path(inventory_file_no, suffix=storage_suffix)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, path)
preview = read_inventory_schema_preview(path)
diff --git a/backend/app/services/shipping_notice/inventory_mapping_workflow.py b/backend/app/services/shipping_notice/inventory_mapping_workflow.py
index 4c901bc7..38b6502d 100644
--- a/backend/app/services/shipping_notice/inventory_mapping_workflow.py
+++ b/backend/app/services/shipping_notice/inventory_mapping_workflow.py
@@ -282,6 +282,7 @@ def inventory_loaded_response(
chain_payload: dict[str, Any] | None = None,
field_mapping: dict[str, str] | None = None,
mapping_source: str | None = None,
+ commit: bool = True,
) -> dict[str, Any]:
"""
库存载入后的统一响应编排:写 inventory_lines → 映射复核或 inventory_ready → 可选 auto-chain。
@@ -289,7 +290,14 @@ def inventory_loaded_response(
Args:
require_mapping_review: True 时进入 align_review;False 时直接 inventory_ready。
chain_payload: 传递给 auto-chain 的原始请求体。
+ commit: False 时仅 flush,供 batch 外层统一提交,避免中途 commit 破坏事务边界。
"""
+ def _persist_inventory_loaded() -> None:
+ if commit:
+ db.session.commit()
+ else:
+ db.session.flush()
+
# [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。
# 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。
inv_file = active_inventory_file_for_task(task)
@@ -351,8 +359,11 @@ def inventory_loaded_response(
"column_meta": column_meta,
},
)
- db.session.commit()
- chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
+ _persist_inventory_loaded()
+ if commit:
+ chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
+ else:
+ chained = None
if chained is not None:
return chained
lang = None
@@ -391,8 +402,8 @@ def inventory_loaded_response(
"linked_task_nos": [item.task_no for item in linked_tasks],
},
)
- db.session.commit()
- if inv_file:
+ _persist_inventory_loaded()
+ if commit and inv_file:
start_inventory_file_linked_tasks(inv_file)
return tool_response(
status="ok",
diff --git a/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py b/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py
new file mode 100644
index 00000000..6fcadb51
--- /dev/null
+++ b/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py
@@ -0,0 +1,300 @@
+"""
+services/shipping_notice/inventory_rpa_callback_cleanup.py
+
+用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。
+依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。
+逻辑:commit 后尝试归档;失败则移入 .hxops_quarantine 并入队;scheduler/worker 启动时定期消费队列。
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import shutil
+import uuid
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+from flask import current_app
+
+from app.services.shipping_notice.rpa import inventory_drop_dir, inventory_processed_dir
+
+_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed"
+_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
+_CLEANUP_FAILED_DIRNAME = ".cleanup_failed"
+_QUARANTINE_DIRNAME = ".hxops_quarantine"
+_DEFAULT_MAX_CLEANUP_ATTEMPTS = 16
+_LOGGER = logging.getLogger(__name__)
+
+
+def callback_cleanup_queue_dir() -> Path | None:
+ """drop 目录下 callback 归档重试队列路径。"""
+ drop = inventory_drop_dir()
+ if not drop:
+ return None
+ return drop / _CLEANUP_QUEUE_DIRNAME
+
+
+def callback_cleanup_failed_dir() -> Path | None:
+ """超过最大重试次数的 cleanup job 隔离目录。"""
+ drop = inventory_drop_dir()
+ if not drop:
+ return None
+ return drop / _CLEANUP_FAILED_DIRNAME
+
+
+def callback_quarantine_dir() -> Path | None:
+ """
+ Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
+ 归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
+ """
+ drop = inventory_drop_dir()
+ if not drop:
+ return None
+ return drop / _QUARANTINE_DIRNAME
+
+
+def callback_cleanup_max_attempts() -> int:
+ """cleanup job 最大重试次数(SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
+ try:
+ return max(
+ 1,
+ int(current_app.config.get("SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
+ )
+ except (TypeError, ValueError):
+ return _DEFAULT_MAX_CLEANUP_ATTEMPTS
+
+
+def is_callback_drop_file_consumed(callback_path: Path) -> bool:
+ """判断 drop 文件是否已被 HXOPS 消费(sidecar 或已位于 quarantine)。"""
+ path = Path(callback_path)
+ if not path.name:
+ return False
+ quarantine = callback_quarantine_dir()
+ if quarantine and quarantine in path.parents:
+ return True
+ sidecar = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
+ return sidecar.is_file()
+
+
+def mark_callback_drop_file_consumed(
+ callback_path: Path,
+ *,
+ run_no: str | None = None,
+ task_no: str | None = None,
+ schedule_run_id: int | None = None,
+ inventory_file_no: str | None = None,
+) -> None:
+ """
+ 标记 drop 区 callback 文件已被系统消费。
+ 核心逻辑:写 sidecar JSON;配合 quarantine 供 Worker 跳过重复扫描(Worker 须忽略 .hxops_* 子目录)。
+ """
+ if not callback_path.is_file():
+ return
+ sidecar = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
+ payload = {
+ "callback_path": str(callback_path),
+ "consumed_at": datetime.utcnow().isoformat(),
+ "run_no": str(run_no or "").strip() or None,
+ "task_no": str(task_no or "").strip() or None,
+ "schedule_run_id": schedule_run_id,
+ "inventory_file_no": str(inventory_file_no or "").strip() or None,
+ }
+ try:
+ sidecar.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
+ except OSError as exc:
+ _LOGGER.warning("failed to write callback consumed marker %s: %s", sidecar, exc)
+
+
+def quarantine_callback_drop_file(callback_path: Path) -> Path | None:
+ """
+ 将归档失败的 callback 原子移入隔离目录,避免 Worker 扫描 drop 根目录时重复上报。
+ Returns:
+ 隔离后的路径;不可用时返回 None。
+ """
+ path = Path(callback_path)
+ if not path.is_file():
+ return None
+ quarantine = callback_quarantine_dir()
+ if quarantine is None:
+ return None
+ quarantine.mkdir(parents=True, exist_ok=True)
+ target = quarantine / path.name
+ if target.exists():
+ target = quarantine / (
+ f"{path.stem}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{path.suffix}"
+ )
+ shutil.move(str(path), str(target))
+ consumed = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}")
+ if consumed.is_file():
+ try:
+ consumed.unlink()
+ except OSError:
+ pass
+ return target
+
+
+def enqueue_callback_file_move(
+ callback_path: Path,
+ *,
+ processed_dir: Path,
+ run_no: str | None = None,
+ task_no: str | None = None,
+ schedule_run_id: int | None = None,
+ error: str | None = None,
+) -> Path | None:
+ """
+ 将失败的 callback 归档操作写入持久化队列,供后续重试。
+ Returns:
+ 队列 job 文件路径;队列不可用时返回 None。
+ """
+ queue = callback_cleanup_queue_dir()
+ if queue is None:
+ return None
+ queue.mkdir(parents=True, exist_ok=True)
+ job_id = uuid.uuid4().hex
+ job_path = queue / f"move_{job_id}.json"
+ payload: dict[str, Any] = {
+ "job_id": job_id,
+ "callback_path": str(callback_path),
+ "processed_dir": str(processed_dir),
+ "run_no": str(run_no or "").strip() or None,
+ "task_no": str(task_no or "").strip() or None,
+ "schedule_run_id": schedule_run_id,
+ "last_error": str(error or "").strip() or None,
+ "enqueued_at": datetime.utcnow().isoformat(),
+ "attempts": 0,
+ }
+ tmp = job_path.with_suffix(".json.tmp")
+ try:
+ tmp.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
+ tmp.replace(job_path)
+ except OSError as exc:
+ _LOGGER.warning("failed to enqueue callback move job for %s: %s", callback_path, exc)
+ return None
+ return job_path
+
+
+def move_callback_drop_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
+ """将 callback 文件移入 processed 目录(公开给 workflow 直接调用)。"""
+ _move_callback_file_to_processed(callback_path, processed_dir)
+
+
+def _move_callback_file_to_processed(callback_path: Path, processed_dir: Path) -> None:
+ """将 callback 文件移入 processed 目录。"""
+ if not callback_path.is_file():
+ return
+ processed_dir.mkdir(parents=True, exist_ok=True)
+ target = processed_dir / callback_path.name
+ if target.exists():
+ target = processed_dir / (
+ f"{callback_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{callback_path.suffix}"
+ )
+ shutil.move(str(callback_path), str(target))
+ consumed = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}")
+ if consumed.is_file():
+ try:
+ consumed.unlink()
+ except OSError:
+ pass
+
+
+def _archive_failed_cleanup_job(job_path: Path, payload: dict[str, Any]) -> None:
+ """超过最大重试次数后将 job 移入 failed 目录。"""
+ failed_dir = callback_cleanup_failed_dir()
+ if failed_dir is None:
+ try:
+ job_path.unlink()
+ except OSError:
+ pass
+ return
+ failed_dir.mkdir(parents=True, exist_ok=True)
+ target = failed_dir / job_path.name
+ payload["archived_at"] = datetime.utcnow().isoformat()
+ try:
+ target.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
+ job_path.unlink()
+ except OSError as exc:
+ _LOGGER.warning("failed to archive cleanup job %s: %s", job_path, exc)
+
+
+def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]:
+ """
+ 重试持久化 callback 归档队列。
+ 核心逻辑:源文件已不存在视为完成;超限 job 移入 failed;仍失败则累加 attempts。
+ """
+ queue = callback_cleanup_queue_dir()
+ if queue is None or not queue.is_dir():
+ return []
+ warnings: list[str] = []
+ max_attempts = callback_cleanup_max_attempts()
+ jobs = sorted(queue.glob("move_*.json"))[: max(max_jobs, 1)]
+ for job_path in jobs:
+ try:
+ payload = json.loads(job_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc:
+ warnings.append(f"{job_path.name}:invalid_job:{str(exc)[:80]}")
+ try:
+ job_path.unlink()
+ except OSError:
+ pass
+ continue
+ callback_raw = str(payload.get("callback_path") or "").strip()
+ processed_raw = str(payload.get("processed_dir") or "").strip()
+ callback_path = Path(callback_raw) if callback_raw else None
+ processed_dir = Path(processed_raw) if processed_raw else inventory_processed_dir()
+ if callback_path is None or processed_dir is None:
+ try:
+ job_path.unlink()
+ except OSError:
+ pass
+ continue
+ if not callback_path.is_file():
+ try:
+ job_path.unlink()
+ except OSError:
+ pass
+ continue
+ if int(payload.get("attempts") or 0) >= max_attempts:
+ warnings.append(f"{callback_path}:max_attempts_exceeded")
+ _archive_failed_cleanup_job(job_path, payload)
+ continue
+ try:
+ _move_callback_file_to_processed(callback_path, processed_dir)
+ try:
+ job_path.unlink()
+ except OSError:
+ pass
+ except Exception as exc:
+ payload["attempts"] = int(payload.get("attempts") or 0) + 1
+ payload["last_error"] = str(exc)[:240]
+ payload["last_attempt_at"] = datetime.utcnow().isoformat()
+ warnings.append(f"{callback_path}:{str(exc)[:120]}")
+ if int(payload["attempts"]) >= max_attempts:
+ _archive_failed_cleanup_job(job_path, payload)
+ else:
+ try:
+ job_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
+ except OSError:
+ pass
+ _LOGGER.warning(
+ "callback cleanup retry failed for %s (attempt=%s)",
+ callback_path,
+ payload["attempts"],
+ exc_info=exc,
+ )
+ return warnings
+
+
+def recover_pending_rpa_callback_cleanup_jobs(*, max_jobs: int = 64) -> tuple[int, list[str]]:
+ """
+ 启动或调度恢复时消费 callback cleanup 队列。
+ Returns:
+ tuple: (成功消化或移除的 job 数, 告警列表)。
+ """
+ queue = callback_cleanup_queue_dir()
+ before = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
+ warnings = flush_callback_cleanup_queue(max_jobs=max_jobs)
+ after = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0
+ return max(0, before - after), warnings
diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py
index c0ddac7a..67ae31b8 100644
--- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py
+++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py
@@ -8,36 +8,63 @@ services/shipping_notice/inventory_rpa_workflow.py
from __future__ import annotations
+import hashlib
+import json
+import logging
+import shutil
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from app import db
-from app.models import ShippingTask, ShippingTaskEvent
-from app.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING
+from app.core.errors import AppError, ServiceUnavailableError
+from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent
+from app.services.shipping_notice.constants import (
+ CP_INVENTORY_SOURCE_REVIEW,
+ CP_PARSE_OK,
+ CP_PARSE_REVIEW,
+ CP_UPLOAD_REQ,
+ PH_INVENTORY_SOURCE_UNRESOLVED,
+ PH_RPA_PENDING,
+)
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
from app.services.shipping_notice.inventory_snapshot_store import (
- create_inventory_snapshot_from_rpa,
find_latest_ready_snapshot,
+ get_or_create_rpa_inventory_snapshot,
link_snapshot_to_task,
)
-from app.services.shipping_notice.inventory_upload import save_task_inventory_local_file
-from app.services.shipping_notice.inventory_source_rules import (
- mark_inventory_source_review,
- resolve_inventory_source,
- save_task_rpa_inventory_source,
- task_rpa_inventory_source,
+from app.services.shipping_notice.inventory_upload import (
+ delete_staged_task_inventory_file,
+ promote_staged_task_inventory_file,
+ rebuild_task_inventory_attachment_from_snapshot,
+ stage_task_inventory_callback_file,
)
+from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
+ enqueue_callback_file_move,
+ flush_callback_cleanup_queue,
+ mark_callback_drop_file_consumed,
+ move_callback_drop_file_to_processed,
+ quarantine_callback_drop_file,
+ recover_pending_rpa_callback_cleanup_jobs,
+)
+from app.services.shipping_notice.inventory_source_gate import (
+ assert_inventory_source_gate,
+ confirm_task_inventory_source,
+ inventory_identities_match,
+ is_inventory_source_stable,
+ task_needs_parse_review,
+)
+from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
from app.services.shipping_notice.query_service import (
resolve_task_from_payload,
serialize_task_for_tool,
)
from app.services.shipping_notice.rpa import (
- find_latest_inventory_file,
inventory_processed_dir,
write_inventory_export_trigger_for_task,
)
+from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
max_rpa_inventory_attempts,
@@ -121,6 +148,7 @@ def _try_reuse_inventory_snapshot(
snapshot = find_latest_ready_snapshot(
str(rpa_source.get("source_code") or ""),
str(rpa_source.get("site_id") or ""),
+ str(rpa_source.get("warehouse_id") or ""),
)
if not snapshot:
return None
@@ -295,34 +323,665 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "works
return ensure_inventory_via_rpa(task, mode="auto")
+def _expected_snapshot_identity_from_task(task: ShippingTask) -> tuple[str, str, str]:
+ """从任务正式库存身份推导快照预期三元组。"""
+ return (
+ str(task.inventory_source_code or "").strip().upper(),
+ str(task.inventory_site_id or "").strip().upper(),
+ str(task.inventory_warehouse_id or "").strip().upper(),
+ )
+
+
+def _expected_snapshot_identity_from_source(source: dict[str, Any]) -> tuple[str, str, str]:
+ """从 RPA/配置源推导快照预期身份三元组,供回调入库前预检。"""
+ code = str(source.get("source_code") or "").strip().upper()
+ site = str(source.get("site_id") or "").strip().upper()
+ warehouse = str(source.get("warehouse_id") or "").strip().upper()
+ return code, site, warehouse
+
+
+def _rollback_orphan_inventory_snapshot(
+ inv_file: Any,
+ *paths: str | Path | None,
+ created_new: bool = True,
+ delete_session_row: bool = True,
+) -> None:
+ """
+ 回滚本轮新建的孤儿快照与托管文件。
+ 核心逻辑:先删物理文件;仅 created_new=True 时处理 DB 行。
+ delete_session_row=False 用于顶层 commit 失败后的 rollback——行已由事务回滚,只清文件。
+ """
+ if not created_new:
+ return
+ from sqlalchemy import inspect as sa_inspect
+
+ from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
+
+ for raw in paths:
+ delete_inventory_storage_path(raw)
+
+ if not delete_session_row or inv_file is None:
+ return
+ try:
+ state = sa_inspect(inv_file)
+ if state.persistent or state.pending:
+ db.session.delete(inv_file)
+ except Exception:
+ logging.getLogger(__name__).warning(
+ "orphan inventory snapshot session delete skipped",
+ exc_info=True,
+ )
+
+
+class _RpaCallbackItemAbort(Exception):
+ """批量/单任务回调单项失败,供 savepoint 回滚后转为 failed 响应。"""
+
+ def __init__(self, error: str, *, message: str | None = None) -> None:
+ self.error = error
+ self.message = message
+ super().__init__(message or error)
+
+
+def _inventory_file_sha256(path: Path) -> str:
+ """计算库存文件 SHA256,用于复用快照内容一致性校验。"""
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _validate_reused_snapshot_callback_file(
+ inv_file: ShippingInventoryFile,
+ callback_path: Path,
+) -> str | None:
+ """
+ 校验复用快照时回调落盘文件与托管 storage_path 内容一致。
+ 核心逻辑:不一致时拒绝复用,避免 inventory_lines_json 与 storage_path 文件分叉。
+ """
+ storage_path = Path(str(inv_file.storage_path or ""))
+ if not storage_path.is_file():
+ return "reused_snapshot_storage_missing"
+ if not callback_path.is_file():
+ return "callback_file_missing"
+ if _inventory_file_sha256(storage_path) != _inventory_file_sha256(callback_path):
+ return "reused_snapshot_content_mismatch"
+ return None
+
+
+def _snapshot_ingest_path(inv_file: ShippingInventoryFile) -> Path:
+ """返回应解析的库存快照托管路径(复用与新建均读 storage_path)。"""
+ path = Path(str(inv_file.storage_path or ""))
+ if not path.is_file() or str(inv_file.storage_path or "").startswith("failed://"):
+ raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.inventory_file_no}")
+ return path
+
+
+def _move_callback_drop_file_to_processed(callback_path: Path, processed: Path) -> None:
+ """将 RPA drop 区回调文件移至 processed,仅在新快照成功摄入后调用。"""
+ move_callback_drop_file_to_processed(callback_path, processed)
+
+
+def _archive_callback_drop_file(
+ callback_path: Path,
+ processed: Path,
+ *,
+ run_no: str | None = None,
+ task_no: str | None = None,
+ schedule_run_id: int | None = None,
+ inventory_file_no: str | None = None,
+) -> str | None:
+ """
+ 归档 callback drop 文件;失败时隔离并写入持久化 cleanup job。
+ 核心逻辑:move 失败 → 尽力 quarantine → 尽力入队;二级失败只追加 warning,不向外抛异常。
+
+ Returns:
+ 失败告警文本;成功返回 None。
+ """
+ mark_callback_drop_file_consumed(
+ callback_path,
+ run_no=run_no,
+ task_no=task_no,
+ schedule_run_id=schedule_run_id,
+ inventory_file_no=inventory_file_no,
+ )
+ if not callback_path.is_file():
+ return None
+ try:
+ move_callback_drop_file_to_processed(callback_path, processed)
+ return None
+ except Exception as exc:
+ logger = logging.getLogger(__name__)
+ detail_parts = [str(exc)[:120]]
+ job_path: Path = callback_path
+ try:
+ quarantined = quarantine_callback_drop_file(callback_path)
+ if quarantined is not None:
+ job_path = quarantined
+ except Exception as quarantine_exc:
+ detail_parts.append(f"quarantine_failed:{str(quarantine_exc)[:80]}")
+ logger.warning(
+ "RPA callback quarantine failed after move failure: %s",
+ callback_path,
+ exc_info=quarantine_exc,
+ )
+
+ try:
+ queued = enqueue_callback_file_move(
+ job_path,
+ processed_dir=processed,
+ run_no=run_no,
+ task_no=task_no,
+ schedule_run_id=schedule_run_id,
+ error=str(exc),
+ )
+ if queued is None:
+ detail_parts.append("enqueue_failed:cleanup_queue_unavailable")
+ except Exception as enqueue_exc:
+ detail_parts.append(f"enqueue_failed:{str(enqueue_exc)[:80]}")
+ logger.warning(
+ "RPA callback cleanup enqueue failed: %s",
+ job_path,
+ exc_info=enqueue_exc,
+ )
+
+ logger.warning(
+ "RPA callback file move failed, cleanup scheduled: %s",
+ callback_path,
+ exc_info=exc,
+ )
+ return f"{callback_path}:{';'.join(detail_parts)[:240]}"
+
+
+def _flush_pending_callback_moves(
+ pending_moves: list[dict[str, Any]],
+ processed: Path,
+) -> list[str]:
+ """
+ 在数据库提交成功后统一移动 callback 原文件。
+ 核心逻辑:先写消费标记;移动失败入持久化队列,不回滚已提交事务。
+ """
+ warnings: list[str] = []
+ for item in pending_moves:
+ callback_path = Path(str(item.get("path") or ""))
+ if not callback_path:
+ continue
+ warning = _archive_callback_drop_file(
+ callback_path,
+ processed,
+ run_no=str(item.get("run_no") or "").strip() or None,
+ task_no=str(item.get("task_no") or "").strip() or None,
+ schedule_run_id=item.get("schedule_run_id"),
+ inventory_file_no=str(item.get("inventory_file_no") or "").strip() or None,
+ )
+ if warning:
+ warnings.append(warning)
+ return warnings
+
+
+def _try_rebuild_task_inventory_attachment(
+ task: ShippingTask,
+ inv_file: ShippingInventoryFile,
+ post_commit_warnings: list[str],
+) -> bool:
+ """
+ 从 inv_file.storage_path 幂等重建任务正式附件(不重新消费 callback)。
+ Returns:
+ 是否重建成功。
+ """
+ try:
+ rebuilt = rebuild_task_inventory_attachment_from_snapshot(task, inv_file)
+ except Exception as exc:
+ post_commit_warnings.append(f"promote_snapshot_rebuild_failed:{str(exc)[:120]}")
+ logging.getLogger(__name__).warning(
+ "task inventory attachment rebuild failed for %s",
+ task.task_no,
+ exc_info=exc,
+ )
+ return False
+ post_commit_warnings.append(f"promote_recovered_via_snapshot_rebuild:{rebuilt.name}")
+ return True
+
+
+def _should_flush_batch_callback_moves(
+ schedule_run_id: int | None,
+ finalize_result: dict[str, Any],
+) -> bool:
+ """
+ 判断批量回调是否可移动 drop 区原文件。
+ 核心逻辑:无排程 run 时在 DB 提交后即可移动;有排程时仅 finalize 成功终态化后移动;
+ finalize 失败且 manual_retryable 时保留原文件供重试。
+ """
+ if schedule_run_id is None:
+ return True
+ if finalize_result.get("manual_retryable"):
+ return False
+ if finalize_result.get("ok"):
+ return True
+ return str(finalize_result.get("schedule_finalize_status") or "") == "ok"
+
+
+def _persist_post_commit_task_event(
+ task: ShippingTask,
+ event_type: str,
+ detail: dict[str, Any],
+) -> None:
+ """独立提交 post-commit 告警审计事件;提交失败仅记日志,不影响主业务响应。"""
+ log_task_event(task, event_type, detail)
+ try:
+ db.session.commit()
+ except Exception as exc:
+ logging.getLogger(__name__).warning(
+ "post-commit task event persist failed for task %s event=%s",
+ task.task_no,
+ event_type,
+ exc_info=exc,
+ )
+
+
+def _extract_run_no_from_trigger(trigger_path: str | None) -> str:
+ """从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 均支持)。"""
+ path = Path(str(trigger_path or ""))
+ name = path.name
+ prefix = "inventory_export_batch_"
+ if name.startswith(prefix) and name.endswith(".json"):
+ return name[len(prefix) : -len(".json")]
+ if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file():
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ if isinstance(payload, dict):
+ run_no = str(payload.get("run_no") or "").strip()
+ if run_no:
+ return run_no
+ except (OSError, json.JSONDecodeError, TypeError, ValueError):
+ pass
+ return ""
+
+
+def _is_legacy_trigger_run_no(run_no: str) -> bool:
+ """判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传)。"""
+ return str(run_no or "").strip().upper().startswith("LEGACY-")
+
+
+def _expected_rpa_callback_run_no(task: ShippingTask) -> str:
+ """读取任务最近一次 RPA 触发记录的 run_no。"""
+ last_trigger = latest_task_event(task, "inventory_rpa_triggered")
+ if not last_trigger:
+ return ""
+ detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {}
+ run_no = str(detail.get("run_no") or "").strip()
+ if run_no:
+ return run_no
+ return _extract_run_no_from_trigger(str(detail.get("trigger") or ""))
+
+
+def _validate_rpa_callback_run_no(task: ShippingTask, callback_run_no: str) -> str | None:
+ """校验回调 run_no 属于当前任务最近一次有效触发轮次。"""
+ provided = str(callback_run_no or "").strip()
+ expected = _expected_rpa_callback_run_no(task)
+ if not expected:
+ return "no_active_trigger"
+ if not provided:
+ if _is_legacy_trigger_run_no(expected):
+ return None
+ return "run_no_missing"
+ if provided != expected:
+ return "run_no_mismatch"
+ return None
+
+
+def _resolve_effective_callback_run_no(task: ShippingTask, payload: dict[str, Any]) -> str:
+ """解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。"""
+ provided = str(payload.get("run_no") or "").strip()
+ if provided:
+ return provided
+ return _expected_rpa_callback_run_no(task)
+
+
+def _lock_task_for_rpa_callback(task: ShippingTask) -> ShippingTask:
+ """对任务行加悲观锁,防止并发回调重复消费同一轮次。"""
+ if task.id is None:
+ return task
+ return db.session.query(ShippingTask).filter_by(id=task.id).with_for_update().one()
+
+
+def _get_consumed_inventory_rpa_run_no(task: ShippingTask) -> str:
+ """读取已消费(处理完成)的 RPA 轮次 run_no。"""
+ return str(task.inventory_rpa_consumed_run_no or "").strip()
+
+
+def _mark_inventory_rpa_run_no_consumed(task: ShippingTask, run_no: str) -> None:
+ """标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。"""
+ effective = str(run_no or "").strip()
+ if not effective:
+ return
+ task.inventory_rpa_consumed_run_no = effective
+
+
+def _validate_rpa_callback_not_replayed(task: ShippingTask, run_no: str) -> str | None:
+ """拒绝同一 run_no 的重复成功/失败/跳过回调。"""
+ effective = str(run_no or "").strip()
+ consumed = _get_consumed_inventory_rpa_run_no(task)
+ if effective and consumed and effective == consumed:
+ return "run_no_already_consumed"
+ return None
+
+
+def _validate_rpa_callback_round(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None:
+ """
+ 校验 RPA 回调轮次契约(run_no + 幂等)。
+ 核心逻辑:success/skipped/failed 共用;无有效触发或旧轮次/重放均拒绝。
+ """
+ run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or ""))
+ if run_no_error:
+ return tool_response(
+ status="failed",
+ task=task,
+ message="RPA 回调 run_no 无效或已过期,已拒绝处理",
+ data={**serialize_task_for_tool(task), "run_no_error": run_no_error},
+ )
+ replay_error = _validate_rpa_callback_not_replayed(
+ task,
+ _resolve_effective_callback_run_no(task, payload),
+ )
+ if replay_error:
+ return tool_response(
+ status="failed",
+ task=task,
+ message="RPA 回调轮次已处理,拒绝重复回调",
+ data={**serialize_task_for_tool(task), "run_no_error": replay_error},
+ )
+ return None
+
+
+def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
+ """校验库存源门禁(skipped/failed/success 共用)。"""
+ try:
+ assert_inventory_source_gate(task, operation="rpa_inventory_callback")
+ except AppError as exc:
+ return tool_response(
+ status="failed",
+ task=task,
+ message=str(exc.message or "库存源门禁未通过,拒绝处理 RPA 回调"),
+ data=serialize_task_for_tool(task),
+ )
+ return None
+
+
+def _validate_rpa_callback_success_identity(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None:
+ """
+ 成功回调的身份契约:source/site/warehouse/run_no 必须与任务一致。
+ 核心逻辑:仅 success 路径调用;skipped/failed 允许 RPA 缺身份字段。
+ """
+ callback_source = str(payload.get("source_code") or "").strip().upper()
+ task_source = str(task.inventory_source_code or "").strip().upper()
+ if not callback_source:
+ return tool_response(
+ status="failed",
+ task=task,
+ message="RPA 成功回调缺少 source_code,已拒绝入库",
+ data=serialize_task_for_tool(task),
+ )
+ if not task_source or callback_source != task_source:
+ return tool_response(
+ status="failed",
+ task=task,
+ message="RPA 回调库存源与任务正式库存源不一致,已拒绝入库",
+ data=serialize_task_for_tool(task),
+ )
+
+ callback_site = str(payload.get("site_id") or "").strip().upper()
+ callback_wh = str(payload.get("warehouse_id") or "").strip().upper()
+ task_site = str(task.inventory_site_id or "").strip().upper()
+ task_wh = str(task.inventory_warehouse_id or "").strip().upper()
+ if not callback_site or callback_site != task_site:
+ return tool_response(
+ status="failed",
+ task=task,
+ message="RPA 回调 site_id 与任务库存源不一致,已拒绝入库",
+ data=serialize_task_for_tool(task),
+ )
+ if not callback_wh or callback_wh != task_wh:
+ return tool_response(
+ status="failed",
+ task=task,
+ message="RPA 回调 warehouse_id 与任务库存源不一致,已拒绝入库",
+ data=serialize_task_for_tool(task),
+ )
+ return None
+
+
+def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
+ """
+ 合并 batch 顶层契约字段到 result item。
+ 核心逻辑:仅合并 run_no / task_no;成功回调身份字段必须由 Worker 显式返回,禁止后端从任务补齐。
+ """
+ merged = dict(item)
+ top_run_no = str(payload.get("run_no") or "").strip()
+ if top_run_no and not str(merged.get("run_no") or "").strip():
+ merged["run_no"] = top_run_no
+
+ task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip()
+ if task_no and not str(merged.get("task_no") or "").strip():
+ merged["task_no"] = task_no
+ return merged
+
+
+def _validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callback_run_no: str) -> str | None:
+ """校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。"""
+ if schedule_run_id is None:
+ return None
+ from app.models import ScheduleRun
+
+ run = db.session.get(ScheduleRun, schedule_run_id)
+ if not run:
+ return "schedule_run_not_found"
+ expected = str(run.run_no or "").strip()
+ provided = str(callback_run_no or "").strip()
+ if not expected:
+ return "schedule_run_no_missing"
+ if provided != expected:
+ return "schedule_run_no_mismatch"
+ summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
+ if run.status != "running" or not summary.get("awaiting_rpa"):
+ return "schedule_run_not_awaiting"
+ return None
+
+
+def _validate_rpa_callback_inventory_source(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None:
+ """
+ 校验 RPA 成功回调是否允许处理当前任务库存(门禁 + 轮次 + 身份)。
+ 核心逻辑:batch 成功项在合并顶层 run_no 后委托本函数。
+ """
+ gate_resp = _validate_rpa_callback_gate(task)
+ if gate_resp is not None:
+ return gate_resp
+ round_resp = _validate_rpa_callback_round(task, payload)
+ if round_resp is not None:
+ return round_resp
+ return _validate_rpa_callback_success_identity(task, payload)
+
+
+def _resolve_batch_callback_source(
+ task: ShippingTask | None,
+ item: dict[str, Any],
+) -> dict[str, Any] | None:
+ """
+ 解析批量回调项的正式库存源身份。
+ 核心逻辑:带任务时仅用任务 RPA source;定时预热仅接受启用配置 source,禁止 item 自由字段覆盖。
+ """
+ if task:
+ return task_rpa_inventory_source(task)
+ source_code = str(item.get("source_code") or "").strip().upper()
+ if not source_code:
+ return None
+ from app.services.shipping_notice.inventory_sources import get_inventory_source
+
+ return get_inventory_source(source_code)
+
+
+def _batch_snapshot_verify_warehouse_id(
+ task: ShippingTask | None,
+ source: dict[str, Any],
+ item: dict[str, Any] | None = None,
+) -> str | None:
+ """推导批量快照入库前须校验的 Excel Warehouse ID。"""
+ if task:
+ warehouse_id = str(task.inventory_warehouse_id or "").strip().upper()
+ return warehouse_id or None
+ if item is not None:
+ warehouse_id = str(item.get("warehouse_id") or "").strip().upper()
+ if warehouse_id:
+ return warehouse_id
+ warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
+ return warehouse_id or None
+
+
+def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[str, Any]) -> str | None:
+ """
+ 校验批量回调 Worker 返回的四字段身份与启用配置一致。
+ 核心逻辑:定时/无任务成功项必须显式携带 source/site/warehouse;动态库位源校验 allowed_warehouse_ids。
+ """
+ from app.services.shipping_notice.inventory_sources import (
+ configured_allowed_warehouse_ids,
+ source_uses_dynamic_warehouse_id,
+ )
+
+ callback_source = str(item.get("source_code") or "").strip().upper()
+ callback_site = str(item.get("site_id") or "").strip().upper()
+ callback_wh = str(item.get("warehouse_id") or "").strip().upper()
+ if not callback_source:
+ return "source_code_missing"
+ if not callback_site:
+ return "site_id_missing"
+ if not callback_wh:
+ return "warehouse_id_missing"
+
+ cfg_source = str(source.get("source_code") or "").strip().upper()
+ cfg_site = str(source.get("site_id") or "").strip().upper()
+ cfg_wh = str(source.get("warehouse_id") or "").strip().upper()
+ if callback_source != cfg_source:
+ return "source_code_mismatch"
+ if callback_site != cfg_site:
+ return "site_id_mismatch"
+
+ if source_uses_dynamic_warehouse_id(source):
+ allowed = configured_allowed_warehouse_ids(source)
+ if allowed and callback_wh not in allowed:
+ return "warehouse_id_not_allowed"
+ return None
+
+ if callback_wh != cfg_wh:
+ return "warehouse_id_mismatch"
+ return None
+
+
def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
"""
- 确认当前任务的库存 RPA 来源,并继续触发库存导出。
- 【AI 触发时机】:当用户在库存源确认检查点选择一个 source_code 后调用;禁止用自然语言中的任意 URL 直接写入。
+ 确认当前任务的库存 RPA 来源,并在门禁通过后继续触发库存导出。
+
+ 【AI 触发时机】:当用户在库存源检查点(通常已先完成解析确认)选择 source_code 后调用。
+ 兼容:存量任务若仍带 pending_parse_review_after_source,确认源后会回到 parse_review。
"""
+ from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
+
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
+ if str(task.pending_human_reason or "").strip() != PH_INVENTORY_SOURCE_UNRESOLVED:
+ return tool_response(status="failed", task=task, message="当前任务不在库存源确认节点")
source_code = str(payload.get("source_code") or "").strip().upper()
- source = build_rpa_inventory_source(source_code)
- if not source:
- return tool_response(status="failed", task=task, message="库存源不存在或未启用")
+ if not source_code:
+ return tool_response(status="failed", task=task, message="请提供库存源编码 source_code")
- save_task_rpa_inventory_source(task, source)
- task.pending_human_reason = None
- task.review_status = None
- task.error_message = None
+ adjudication = confirm_task_inventory_source(
+ task,
+ source_code,
+ user_id=payload.get("_trusted_user_id"),
+ )
+ if not is_inventory_source_stable(task):
+ apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
+ task.current_step = "step2_parse_confirm"
+ task.error_message = adjudication.reason or "库存源确认失败"
+ db.session.commit()
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message="库存源确认未通过,请重新选择或检查配置。",
+ data={
+ **serialize_task_for_tool(task),
+ "inventory_source_candidates": adjudication.candidates,
+ "inventory_source_status": adjudication.status,
+ "inventory_source_reason": adjudication.reason,
+ },
+ checkpoint=CP_INVENTORY_SOURCE_REVIEW,
+ stop_agent_turn=True,
+ )
+
+ confirmed_by = payload.get("_trusted_user_id")
log_task_event(
task,
"inventory_source_confirmed",
{
- "source_code": source.get("source_code"),
- "source_type": source.get("source_type"),
- "confirmed_by": "user",
+ "source_code": task.inventory_source_code,
+ "source_type": task.inventory_source_type,
+ "site_id": task.inventory_site_id,
+ "warehouse_id": task.inventory_warehouse_id,
+ "confirmed_by": confirmed_by or "integration_tool",
},
)
- db.session.flush()
- return ensure_inventory_via_rpa(task, mode=str(payload.get("mode") or "auto"))
+
+ # 存量兼容:旧顺序先确认库存源时延后的低置信度解析复核。
+ if task_needs_parse_review(task):
+ step_payload = dict(task.step_payload_json or {})
+ step_payload.pop("pending_parse_review_after_source", None)
+ task.step_payload_json = step_payload
+ apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
+ task.current_step = "step2_parse_confirm"
+ db.session.commit()
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message="库存源已确认,请继续确认解析结果。",
+ data=serialize_task_for_tool(task),
+ checkpoint=CP_PARSE_REVIEW,
+ stop_agent_turn=True,
+ )
+
+ apply_task_transition(task, TaskTransition.PARSED)
+ task.pending_human_reason = None
+ task.review_status = None
+ task.error_message = None
+ step_payload = dict(task.step_payload_json or {})
+ step_payload.pop("pending_parse_review_after_source", None)
+ task.step_payload_json = step_payload
+ task.current_step = "step3_inventory_prepare"
+ db.session.commit()
+
+ from app.services.shipping_notice.tool_common import auto_rpa_inventory_enabled
+
+ if (not task.inventory_lines_json) and auto_rpa_inventory_enabled():
+ rpa_result = ensure_inventory_via_rpa(task, mode=str(payload.get("mode") or "auto"))
+ rpa_status = str(rpa_result.get("status") or "").strip().lower()
+ if rpa_status in {"running", "ok"}:
+ return rpa_result
+ if rpa_status == "needs_human" and str(task.pending_human_reason or "").strip() == PH_RPA_PENDING:
+ return rpa_result
+ return tool_response(
+ status="ok",
+ task=task,
+ message="库存源已确认;自动获取库存暂未完成,请稍后重试或手动上传库存文件。",
+ data=serialize_task_for_tool(task),
+ checkpoint=CP_PARSE_OK,
+ )
+
+ return tool_response(
+ status="ok",
+ task=task,
+ message="库存源已确认。",
+ data=serialize_task_for_tool(task),
+ checkpoint=CP_PARSE_OK,
+ )
def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]:
@@ -330,61 +989,24 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
manual_retry_round = mode == "retry_rpa"
- # [STEP 0] 库存 RPA 必须先确定唯一库存源;Dify 只给目的地线索,HXOPS 规则负责最终裁决。
- rpa_source = task_rpa_inventory_source(task)
- if not rpa_source:
- resolution = resolve_inventory_source(task)
- if resolution.status == "resolved" and resolution.source:
- rpa_source = resolution.source
- save_task_rpa_inventory_source(task, rpa_source, resolution=resolution)
- log_task_event(
- task,
- "inventory_source_resolved",
- {
- "source_code": rpa_source.get("source_code"),
- "source_type": rpa_source.get("source_type"),
- "destination_candidates": resolution.destination_candidates,
- },
- )
- db.session.flush()
- else:
- mark_inventory_source_review(task, resolution)
- apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
- task.error_message = "无法根据发货通知唯一确定库存查询来源"
- set_task_step_progress(
- task,
- step_key="step3_inventory_prepare",
- step_title="获取库存",
- status="needs_human",
- message="库存查询来源待确认",
- progress_percent=30,
- current=len(resolution.candidates),
- total=len(resolution.candidates),
- detail="请确认本票应使用哪个 RPA 库存来源后继续。",
- )
- log_task_event(
- task,
- "inventory_source_review_required",
- {
- "status": resolution.status,
- "reason": resolution.reason,
- "destination_candidates": resolution.destination_candidates,
- "candidate_source_codes": [item.get("source_code") for item in resolution.candidates],
- },
- )
- db.session.commit()
- return tool_response(
- status="needs_human",
- task=task,
- message="无法根据发货通知唯一确定库存查询来源,请选择库存源后继续 RPA 获取库存。",
- data={
- **serialize_task_for_tool(task),
- "inventory_source_candidates": resolution.candidates,
- "destination_candidates": resolution.destination_candidates,
- },
- checkpoint=CP_INVENTORY_SOURCE_REVIEW,
- stop_agent_turn=True,
- )
+ # [STEP 0] 库存源须在订单解析阶段已确定;RPA 只读取独立字段。
+ try:
+ assert_inventory_source_gate(task, operation="ensure_inventory_via_rpa")
+ except AppError:
+ apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
+ task.current_step = "step2_parse_confirm"
+ task.error_message = "库存源尚未确定,无法启动 RPA"
+ db.session.commit()
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
+ data=serialize_task_for_tool(task),
+ checkpoint=CP_INVENTORY_SOURCE_REVIEW,
+ stop_agent_turn=True,
+ )
+
+ rpa_source = task_rpa_inventory_source(task) or {}
# [STEP 0.5] 未过期库存快照优先复用;retry_rpa 强制跳过。
reused = _try_reuse_inventory_snapshot(task, rpa_source, mode=mode)
@@ -436,11 +1058,9 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
"timeout_seconds": timeout_seconds,
},
)
- db.session.flush()
+ db.session.flush( )
- # [STEP 2] 处理重试上限与已落盘文件两种捷径。
- # 单次模式下,只有“上一轮已经失败/超时”时才允许在这里转人工;首次成功写出 trigger 后必须进入等待窗口。
- # 若目录里已有最新库存文件,则优先吃掉落盘结果而不是再触发一次 RPA。
+ # [STEP 2] 处理重试上限;禁止消费全局 drop 目录未校验文件,必须等待 RPA 回调或复用正式快照。
attempts = inventory_rpa_attempts(task)
max_attempts = max_rpa_inventory_attempts()
if attempts >= max_attempts and not task.inventory_lines_json and not manual_retry_round:
@@ -455,34 +1075,22 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
data=serialize_task_for_tool(task),
)
- latest = find_latest_inventory_file()
- processed = inventory_processed_dir()
- if latest and processed:
- try:
- lines, column_meta = ingest_inventory_file(latest, move_to=processed)
- if lines:
- return inventory_loaded_response(
- task,
- lines,
- column_meta=column_meta,
- source="rpa_drop",
- require_mapping_review=True,
- event_type="inventory_rpa_drop_ingested",
- )
- except Exception as exc:
- task.error_message = str(exc)[:500]
-
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
attempt_no = attempts + 1
- trigger = write_inventory_export_trigger_for_task(
- task.task_no,
- rpa_source,
- payload={
- "mode": mode,
- "attempt": attempt_no,
- },
- )
+ try:
+ trigger = write_inventory_export_trigger_for_task(
+ task.task_no,
+ rpa_source,
+ payload={
+ "mode": mode,
+ "attempt": attempt_no,
+ },
+ )
+ except ServiceUnavailableError as exc:
+ trigger = None
+ detail_message = str((exc.details or {}).get("detail_message") or exc.message or RPA_WORKER_OFFLINE_MESSAGE)
+ task.error_message = detail_message[:500]
if trigger:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
@@ -511,7 +1119,12 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
log_task_event(
task,
"inventory_rpa_triggered",
- {"trigger": trigger, "attempt": attempt_no, "manual_retry_round": manual_retry_round},
+ {
+ "trigger": trigger,
+ "run_no": _extract_run_no_from_trigger(trigger),
+ "attempt": attempt_no,
+ "manual_retry_round": manual_retry_round,
+ },
)
db.session.commit()
@@ -534,125 +1147,499 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
- task.error_message = "RPA 库存目录未配置或触发失败"
+ offline_message = (task.error_message or "").strip()
+ if offline_message == RPA_WORKER_OFFLINE_MESSAGE:
+ human_message = RPA_WORKER_OFFLINE_MESSAGE
+ detail = "请启动 Windows RPA 服务后重试,或手动上传货代库存 Excel。"
+ else:
+ human_message = "RPA 库存目录未配置或触发失败"
+ detail = "请重新获取库存,或手动上传货代库存 Excel。"
+ task.error_message = human_message[:500]
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="needs_human",
- message="RPA 库存触发失败",
+ message=human_message,
progress_percent=100,
current=0,
total=max_attempts,
- detail="请重新获取库存,或手动上传货代库存 Excel。",
+ detail=detail,
)
log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
- message="RPA 库存目录未配置或触发失败。请上传货代库存 Excel。",
+ message=f"{human_message}。请上传货代库存 Excel。" if human_message != RPA_WORKER_OFFLINE_MESSAGE else human_message,
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
)
+def _normalize_rpa_inventory_result_status(payload: dict[str, Any]) -> str:
+ """
+ 归一化单任务 RPA 库存回调结果。
+
+ 核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段;
+ 缺省 success 视为 true(历史单任务回调兼容)。
+
+ Returns:
+ str: success | skipped | failed
+ """
+ raw_status = str(payload.get("status") or "").strip().lower()
+ if raw_status in {"success", "skipped", "failed"}:
+ return raw_status
+ if payload.get("skipped"):
+ return "skipped"
+ if bool(payload.get("success", True)):
+ return "success"
+ return "failed"
+
+
+def _normalize_rpa_inventory_batch_item_status(item: dict[str, Any]) -> str:
+ """
+ 归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。
+
+ 核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或
+ 缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。
+
+ Returns:
+ str: success | skipped | failed
+ """
+ raw_status = str(item.get("status") or "").strip().lower()
+ if raw_status in {"success", "skipped", "failed"}:
+ return raw_status
+ if item.get("skipped"):
+ return "skipped"
+ if item.get("success") is True:
+ return "success"
+ return "failed"
+
+
+def _summarize_rpa_inventory_batch_outcome(
+ *,
+ created: list[Any],
+ skipped: list[Any],
+ failed: list[Any],
+) -> str:
+ """
+ 汇总批量库存回调业务结果(与 worker batch status 语义对齐)。
+
+ Returns:
+ str: success | partial_failed | failed
+ """
+ success_count = len(created)
+ skipped_count = len(skipped)
+ failed_count = len(failed)
+ if failed_count == 0:
+ return "success"
+ if success_count == 0 and skipped_count == 0:
+ return "failed"
+ return "partial_failed"
+
+
+def _resolve_rpa_inventory_batch_response_outcome(
+ *,
+ created: list[Any],
+ skipped: list[Any],
+ failed: list[Any],
+ finalize_result: dict[str, Any],
+ schedule_run_id: int | None,
+) -> dict[str, Any]:
+ """
+ 汇总批量回调响应中的 result_status 与计数。
+
+ 核心逻辑:非排程场景仅按回调 results 计算;含 schedule_run_id 且 finalize 成功时,
+ 优先采用 finalize 的 run_status 与 success/skipped/failed 计数,与 ScheduleRun 终态一致。
+ """
+ callback_result_status = _summarize_rpa_inventory_batch_outcome(
+ created=created,
+ skipped=skipped,
+ failed=failed,
+ )
+ outcome = {
+ "result_status": callback_result_status,
+ "callback_result_status": callback_result_status,
+ "success_count": len(created),
+ "skipped_count": len(skipped),
+ "failed_count": len(failed),
+ }
+ if schedule_run_id is None or not finalize_result.get("ok"):
+ return outcome
+
+ run_status = str(finalize_result.get("run_status") or "").strip()
+ if run_status:
+ outcome["result_status"] = run_status
+ if finalize_result.get("success_count") is not None:
+ outcome["success_count"] = int(finalize_result["success_count"])
+ if finalize_result.get("skipped_count") is not None:
+ outcome["skipped_count"] = int(finalize_result["skipped_count"])
+ if finalize_result.get("failed_count") is not None:
+ outcome["failed_count"] = int(finalize_result["failed_count"])
+ return outcome
+
+
+def _inventory_rpa_skipped_message(*, skip_reason: str, detail: str) -> str:
+ """
+ 生成单任务「无库存跳过」的人工作业提示。
+
+ 核心逻辑:skipped 不是 RPA 技术失败,提示用户确认仓库或改用手动上传。
+ """
+ if skip_reason == "no_inventory_data":
+ return "货代系统显示该仓当前无可用库存,请确认仓库是否正确,或改用手动上传库存 Excel。"
+ base = detail.strip() or "货代库存导出已跳过"
+ return f"{base}。请确认仓库是否正确,或改用手动上传库存 Excel。"
+
+
+def _handle_rpa_inventory_skipped(
+ task: ShippingTask,
+ payload: dict[str, Any],
+ runtime: dict[str, Any],
+ *,
+ commit: bool = True,
+) -> dict[str, Any]:
+ """处理 skipped 回调:转人工上传检查点,不计入技术失败重试。"""
+ skip_reason = str(payload.get("skip_reason") or "no_inventory_data").strip()
+ detail = str(payload.get("message") or payload.get("error_message") or "").strip()
+ message = _inventory_rpa_skipped_message(skip_reason=skip_reason, detail=detail)
+ apply_task_transition(task, TaskTransition.INV_UNAVAIL)
+ task.error_message = None
+ step_payload = dict(task.step_payload_json or {})
+ step_payload["inventory_rpa_skipped"] = {
+ "skip_reason": skip_reason,
+ "message": detail or message,
+ "reported_at": datetime.utcnow().isoformat(),
+ "rpa_runtime": runtime,
+ }
+ task.step_payload_json = step_payload
+ set_task_step_progress(
+ task,
+ step_key="step3_inventory_prepare",
+ step_title="获取库存",
+ status="needs_human",
+ message="货代系统当前无可用库存",
+ progress_percent=100,
+ detail="请确认仓库是否正确,或手动上传货代库存 Excel。",
+ )
+ log_task_event(
+ task,
+ "inventory_rpa_skipped",
+ {
+ "skip_reason": skip_reason,
+ "message": detail or message,
+ "rpa_runtime": runtime,
+ },
+ )
+ _mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload))
+ if commit:
+ db.session.commit()
+ else:
+ db.session.flush()
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message=message,
+ data=serialize_task_for_tool(task),
+ checkpoint=CP_UPLOAD_REQ,
+ )
+
+
+def _handle_rpa_inventory_failed(
+ task: ShippingTask,
+ payload: dict[str, Any],
+ runtime: dict[str, Any],
+ *,
+ commit: bool = True,
+) -> dict[str, Any]:
+ """处理 failed 回调:累计尝试并在耗尽后转人工上传兜底。"""
+ apply_task_transition(task, TaskTransition.INV_UNAVAIL)
+ task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500]
+ log_task_event(task, "inventory_rpa_failed", {"error": task.error_message, "rpa_runtime": runtime})
+ db.session.flush()
+ attempts = inventory_rpa_attempts(task)
+ if attempts >= max_rpa_inventory_attempts():
+ apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
+ task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
+ log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
+ _mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload))
+ if commit:
+ db.session.commit()
+ else:
+ db.session.flush()
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message=_inventory_rpa_exhausted_message(attempts),
+ data=serialize_task_for_tool(task),
+ )
+
+ _mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload))
+ if commit:
+ db.session.commit()
+ else:
+ db.session.flush()
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message=task.error_message,
+ data=serialize_task_for_tool(task),
+ )
+
+
def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
+ cleanup_retry_warnings = flush_callback_cleanup_queue()
+
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
- # [STEP 1] 先处理 RPA 回调失败分支。
- # 失败时要累计尝试次数,并在耗尽后明确切换到人工上传兜底。
- success = bool(payload.get("success", True))
+ task = _lock_task_for_rpa_callback(task)
+
+ gate_resp = _validate_rpa_callback_gate(task)
+ if gate_resp is not None:
+ return gate_resp
+
runtime = _save_last_inventory_rpa_runtime(task, payload)
- if not success:
- apply_task_transition(task, TaskTransition.INV_UNAVAIL)
- task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500]
- log_task_event(task, "inventory_rpa_failed", {"error": task.error_message, "rpa_runtime": runtime})
- db.session.flush()
- attempts = inventory_rpa_attempts(task)
- if attempts >= max_rpa_inventory_attempts():
- apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
- task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
- log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
- db.session.commit()
- return tool_response(
- status="needs_human",
- task=task,
- message=_inventory_rpa_exhausted_message(attempts),
- data=serialize_task_for_tool(task),
- )
+ callback_status = _normalize_rpa_inventory_result_status(payload)
- db.session.commit()
- return tool_response(
- status="needs_human",
- task=task,
- message=task.error_message,
- data=serialize_task_for_tool(task),
- )
+ round_resp = _validate_rpa_callback_round(task, payload)
+ if round_resp is not None:
+ return round_resp
- # [STEP 2] 成功回调后先把 RPA 文件正式纳入系统库存目录,再交给统一 ingest。
+ if callback_status == "skipped":
+ return _handle_rpa_inventory_skipped(task, payload, runtime)
+
+ if callback_status == "failed":
+ return _handle_rpa_inventory_failed(task, payload, runtime)
+
+ identity_resp = _validate_rpa_callback_success_identity(task, payload)
+ if identity_resp is not None:
+ return identity_resp
+
+ # [STEP 3] 成功回调后先把 RPA 文件正式纳入系统库存目录,再交给统一 ingest。
# 这样 inventory_uploads 会保留任务级正式附件,回调路径也能与人工上传共享同一托管约定。
file_path = str(payload.get("file_path") or "").strip()
- path = Path(file_path) if file_path else find_latest_inventory_file()
- if not path or not path.is_file():
+ run_no = str(payload.get("run_no") or "").strip()
+ if not run_no:
+ expected_run_no = _expected_rpa_callback_run_no(task)
+ if expected_run_no and not _is_legacy_trigger_run_no(expected_run_no):
+ return tool_response(status="failed", task_id=task.task_no, message="RPA 回调缺少 run_no")
+ run_no = expected_run_no
+ if not file_path:
+ return tool_response(status="failed", task_id=task.task_no, message="库存文件路径缺失")
+ path = Path(file_path)
+ if not path.is_file():
return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在")
processed = inventory_processed_dir()
- managed_path = save_task_inventory_local_file(task.task_no, path)
- rpa_source = task_rpa_inventory_source(task) or {}
- if not rpa_source.get("source_code") and payload.get("source_code"):
- rpa_source = build_rpa_inventory_source(str(payload.get("source_code"))) or rpa_source
- inv_file = create_inventory_snapshot_from_rpa(
- source=rpa_source or {"source_code": payload.get("source_code"), "source_type": payload.get("source_type")},
- local_path=managed_path,
- source_file_name=path.name,
- rpa_run_no=str(payload.get("run_no") or "").strip() or None,
- trigger_type="on_demand",
- success=True,
- user_id=task.user_id,
- batch_id=task.batch_id,
- )
- link_snapshot_to_task(
- task,
- inv_file,
- reason="rpa_callback",
- audit_payload={"rpa_runtime": runtime},
- )
- lines, column_meta = ingest_inventory_file(path, move_to=processed)
- set_task_step_progress(
- task,
- step_key="step3_inventory_prepare",
- step_title="获取库存",
- status="running",
- message="RPA 库存文件已返回,正在读取库存快照",
- progress_percent=85,
- detail=f"正在读取 {managed_path.name}",
- )
- log_task_event(
- task,
+ rpa_source = task_rpa_inventory_source(task)
+ if not rpa_source or not rpa_source.get("source_code"):
+ return tool_response(
+ status="failed",
+ task=task,
+ message="任务库存源未配置,拒绝处理 RPA 回调",
+ data=serialize_task_for_tool(task),
+ )
+
+ staging_path: Path | None = None
+ inv_file: ShippingInventoryFile | None = None
+ created_new = False
+ orphan_paths: list[str | Path] = []
+ try:
+ staging_path = stage_task_inventory_callback_file(task.task_no, path, run_no=run_no)
+ inv_file, created_new = get_or_create_rpa_inventory_snapshot(
+ source=rpa_source,
+ local_path=staging_path,
+ source_file_name=path.name,
+ rpa_run_no=run_no,
+ trigger_type="on_demand",
+ success=True,
+ user_id=task.user_id,
+ batch_id=task.batch_id,
+ verify_warehouse_id=task_wh if (task_wh := str(task.inventory_warehouse_id or "").strip().upper()) else None,
+ )
+ if not created_new:
+ reuse_error = _validate_reused_snapshot_callback_file(inv_file, path)
+ if reuse_error:
+ delete_staged_task_inventory_file(staging_path)
+ return tool_response(
+ status="failed",
+ task=task,
+ message="复用库存快照时回调文件与托管文件内容不一致",
+ data={**serialize_task_for_tool(task), "error": reuse_error},
+ )
+ ingest_path = _snapshot_ingest_path(inv_file)
+ if created_new and inv_file.storage_path:
+ orphan_paths.append(inv_file.storage_path)
+ except AppError as exc:
+ delete_staged_task_inventory_file(staging_path)
+ if inv_file is not None and created_new:
+ _rollback_orphan_inventory_snapshot(inv_file, *orphan_paths, created_new=True)
+ return tool_response(
+ status="failed",
+ task=task,
+ message=str(exc.message or "库存文件身份校验失败"),
+ data=serialize_task_for_tool(task),
+ )
+ except Exception as exc:
+ delete_staged_task_inventory_file(staging_path)
+ if inv_file is not None and created_new:
+ _rollback_orphan_inventory_snapshot(inv_file, *orphan_paths, created_new=True)
+ return tool_response(
+ status="failed",
+ task=task,
+ message=f"RPA 库存快照准备失败: {str(exc)[:200]}",
+ data={**serialize_task_for_tool(task), "error": "snapshot_prepare_failed"},
+ )
+
+ if inv_file is None:
+ return tool_response(status="failed", task=task, message="RPA 库存快照准备未完成")
+
+ item_savepoint = db.session.begin_nested()
+ response: dict[str, Any] | None = None
+ try:
+ link = link_snapshot_to_task(
+ task,
+ inv_file,
+ reason="rpa_callback",
+ audit_payload={"rpa_runtime": runtime},
+ )
+ if link is None:
+ raise _RpaCallbackItemAbort("inventory_identity_mismatch")
+
+ lines, column_meta = ingest_inventory_file(ingest_path, move_to=None)
+ set_task_step_progress(
+ task,
+ step_key="step3_inventory_prepare",
+ step_title="获取库存",
+ status="running",
+ message="RPA 库存文件已返回,正在读取库存快照",
+ progress_percent=85,
+ detail=f"正在读取 {ingest_path.name}",
+ )
+ log_task_event(
+ task,
"inventory_uploaded",
{
"source": "rpa_callback",
"rpa_runtime": runtime,
- "upload_filename": managed_path.name,
- "upload_path": str(managed_path),
- "origin_file_path": str(path),
- "inventory_file_no": inv_file.inventory_file_no,
- },
- )
- return inventory_loaded_response(
- task,
- lines,
- column_meta=column_meta,
- source="rpa_callback",
- require_mapping_review=True,
- event_type="inventory_rpa_ready",
+ "upload_filename": ingest_path.name,
+ "upload_path": str(ingest_path),
+ "origin_file_path": str(path),
+ "inventory_file_no": inv_file.inventory_file_no,
+ "reused_existing_snapshot": not created_new,
+ },
+ )
+ _mark_inventory_rpa_run_no_consumed(task, run_no)
+ response = inventory_loaded_response(
+ task,
+ lines,
+ column_meta=column_meta,
+ source="rpa_callback",
+ require_mapping_review=True,
+ event_type="inventory_rpa_ready",
+ commit=False,
+ )
+ item_savepoint.commit()
+ except _RpaCallbackItemAbort as abort:
+ item_savepoint.rollback()
+ delete_staged_task_inventory_file(staging_path)
+ _rollback_orphan_inventory_snapshot(inv_file, *orphan_paths, created_new=created_new)
+ return tool_response(
+ status="failed",
+ task=task,
+ message="库存快照身份与任务库存源不一致,已拒绝入库",
+ data={**serialize_task_for_tool(task), "error": abort.error},
+ )
+ except Exception as exc:
+ item_savepoint.rollback()
+ delete_staged_task_inventory_file(staging_path)
+ _rollback_orphan_inventory_snapshot(inv_file, *orphan_paths, created_new=created_new)
+ return tool_response(
+ status="failed",
+ task=task,
+ message=f"RPA 库存文件解析失败: {str(exc)[:200]}",
+ data=serialize_task_for_tool(task),
+ )
+
+ try:
+ db.session.commit()
+ except Exception as exc:
+ db.session.rollback()
+ delete_staged_task_inventory_file(staging_path)
+ _rollback_orphan_inventory_snapshot(
+ inv_file,
+ *orphan_paths,
+ created_new=created_new,
+ delete_session_row=False,
+ )
+ return tool_response(
+ status="failed",
+ task=task,
+ message=f"RPA 回调提交失败: {str(exc)[:200]}",
+ data={**serialize_task_for_tool(task), "error": "callback_commit_failed"},
+ )
+
+ post_commit_warnings: list[str] = list(cleanup_retry_warnings)
+ mark_callback_drop_file_consumed(
+ path,
+ run_no=run_no,
+ task_no=task.task_no,
+ inventory_file_no=inv_file.inventory_file_no,
)
+ promote_ok = False
+ try:
+ promote_staged_task_inventory_file(task.task_no, staging_path)
+ promote_ok = True
+ except Exception as exc:
+ post_commit_warnings.append(f"promote_task_attachment_failed:{str(exc)[:120]}")
+ logging.getLogger(__name__).warning(
+ "RPA task attachment promote failed after commit for task %s",
+ task.task_no,
+ exc_info=exc,
+ )
+ promote_ok = _try_rebuild_task_inventory_attachment(task, inv_file, post_commit_warnings)
+
+ if promote_ok and path.is_file():
+ move_warning = _archive_callback_drop_file(
+ path,
+ processed,
+ run_no=run_no,
+ task_no=task.task_no,
+ inventory_file_no=inv_file.inventory_file_no,
+ )
+ if move_warning:
+ post_commit_warnings.append(f"move_callback_file_failed:{move_warning}")
+
+ try:
+ from app.services.shipping_notice.inventory_file_store import start_inventory_file_linked_tasks
+
+ start_inventory_file_linked_tasks(inv_file)
+ except Exception as exc:
+ post_commit_warnings.append(f"start_linked_tasks_failed:{str(exc)[:120]}")
+ logging.getLogger(__name__).warning(
+ "RPA linked-task start failed after commit for task %s",
+ task.task_no,
+ exc_info=exc,
+ )
+
+ if post_commit_warnings:
+ _persist_post_commit_task_event(
+ task,
+ "inventory_rpa_post_commit_warning",
+ {"warnings": post_commit_warnings, "inventory_file_no": inv_file.inventory_file_no},
+ )
+
+ if response is None:
+ return tool_response(status="failed", task=task, message="RPA 回调处理未完成")
+ if post_commit_warnings:
+ data = response.get("data") if isinstance(response.get("data"), dict) else {}
+ response["data"] = {**data, "post_commit_warnings": post_commit_warnings}
+ return response
def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
@@ -662,9 +1649,12 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
核心逻辑:遍历 results;定时任务只入库;带 task_no 的成功项关联对应任务;
含 schedule_run_id 时委托 finalize 终态化排程 run。
+ 响应:tool_response.status 恒为 ok(payload 合法且处理完成);业务成败看 result_status。
"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
+ cleanup_retry_warnings = flush_callback_cleanup_queue()
+
run_no = str(payload.get("run_no") or "").strip()
schedule_run_id = payload.get("schedule_run_id")
try:
@@ -672,84 +1662,316 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
except (TypeError, ValueError):
schedule_run_id = None
+ schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, run_no)
+ if schedule_run_error:
+ return tool_response(
+ status="failed",
+ message="排程 RPA 回调 run_no 无效或与当前等待轮次不一致",
+ data={"schedule_run_error": schedule_run_error, "run_no": run_no},
+ )
+
results = payload.get("results") or []
if not isinstance(results, list):
return tool_response(status="failed", message="results must be a list")
created: list[dict[str, Any]] = []
failed: list[dict[str, Any]] = []
+ skipped: list[dict[str, Any]] = []
+ batch_new_storage_paths: list[str] = []
+ pending_callback_moves: list[dict[str, Any]] = []
- for item in results:
- if not isinstance(item, dict):
- continue
- source_code = str(item.get("source_code") or "").strip().upper()
- warehouse_id = str(item.get("warehouse_id") or "").strip()
- success = bool(item.get("success", False))
- source = build_rpa_inventory_source(source_code) or {
- "source_code": source_code,
- "site_id": item.get("site_id"),
- "warehouse_id": warehouse_id,
- "source_type": item.get("source_type"),
- }
-
- if success:
- file_path = str(item.get("file_path") or "").strip()
- path = Path(file_path) if file_path else None
- if not path or not path.is_file():
- failed.append({"source_code": source_code, "warehouse_id": warehouse_id, "error": "file_missing"})
+ try:
+ for item in results:
+ if not isinstance(item, dict):
continue
- inv_file = create_inventory_snapshot_from_rpa(
- source=source,
- local_path=path,
- source_file_name=path.name,
- rpa_run_no=run_no or None,
- schedule_run_id=schedule_run_id,
- trigger_type=str(payload.get("trigger_type") or "scheduled"),
- success=True,
- )
- created.append({
- "inventory_file_no": inv_file.inventory_file_no,
- "source_code": source_code,
- "warehouse_id": warehouse_id,
- })
-
- task_no = str(item.get("task_no") or "").strip()
+ merged_item = _merge_batch_callback_item(payload, item)
+ source_code = str(merged_item.get("source_code") or "").strip().upper()
+ warehouse_id = str(merged_item.get("warehouse_id") or "").strip().upper()
+ site_id = str(merged_item.get("site_id") or "").strip().upper()
+ raw_status = _normalize_rpa_inventory_batch_item_status(merged_item)
+ task_no = str(merged_item.get("task_no") or "").strip()
+ task: ShippingTask | None = None
if task_no:
task = resolve_task_from_payload({"task_id": task_no, "task_no": task_no})
- if task:
- link_snapshot_to_task(
- task,
- inv_file,
- reason="rpa_batch_callback",
- audit_payload={"run_no": run_no},
- )
- lines, column_meta = ingest_inventory_file(path, move_to=inventory_processed_dir())
- if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}:
- inventory_loaded_response(
- task,
- lines,
- column_meta=column_meta,
- source="rpa_batch_callback",
- require_mapping_review=True,
- event_type="inventory_rpa_ready",
- )
- else:
- create_inventory_snapshot_from_rpa(
- source=source,
- local_path=item.get("file_path") or "",
- rpa_run_no=run_no or None,
- schedule_run_id=schedule_run_id,
- trigger_type=str(payload.get("trigger_type") or "scheduled"),
- success=False,
- error_message=str(item.get("error_message") or "export failed")[:500],
- )
- failed.append({
- "source_code": source_code,
- "warehouse_id": warehouse_id,
- "error": item.get("error_message"),
- })
+ if task is None:
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "task_no": task_no,
+ "error": "task_not_found",
+ })
+ continue
+ task = _lock_task_for_rpa_callback(task)
- db.session.commit()
+ if task and raw_status in {"skipped", "failed"}:
+ gate_resp = _validate_rpa_callback_gate(task)
+ if gate_resp is not None:
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "task_no": task_no,
+ "error": gate_resp.get("message") or "inventory_source_gate_blocked",
+ })
+ continue
+ round_resp = _validate_rpa_callback_round(task, merged_item)
+ if round_resp is not None:
+ round_data = round_resp.get("data") if isinstance(round_resp.get("data"), dict) else {}
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "task_no": task_no,
+ "error": round_data.get("run_no_error") or "run_no_invalid",
+ })
+ continue
+ runtime = _save_last_inventory_rpa_runtime(task, merged_item)
+ if raw_status == "skipped":
+ _handle_rpa_inventory_skipped(task, merged_item, runtime, commit=False)
+ skipped.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "task_no": task_no,
+ "skip_reason": merged_item.get("skip_reason") or "skipped",
+ "message": merged_item.get("message") or merged_item.get("error_message") or "",
+ })
+ else:
+ _handle_rpa_inventory_failed(task, merged_item, runtime, commit=False)
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "task_no": task_no,
+ "error_code": merged_item.get("error_code") or "rpa_export_failed",
+ "error": merged_item.get("error_message"),
+ })
+ continue
+
+ source = _resolve_batch_callback_source(task, merged_item)
+ if not source:
+ error = {
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "error": "unknown_or_disabled_source",
+ }
+ if task_no:
+ error["task_no"] = task_no
+ if raw_status == "success":
+ failed.append(error)
+ else:
+ failed.append({
+ **error,
+ "error_code": merged_item.get("error_code") or "rpa_export_failed",
+ "error_message": merged_item.get("error_message"),
+ })
+ continue
+
+ if raw_status == "success":
+ file_path = str(merged_item.get("file_path") or "").strip()
+ path = Path(file_path) if file_path else None
+ if not path or not path.is_file():
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "error": "file_missing",
+ })
+ continue
+
+ if task:
+ gate_resp = _validate_rpa_callback_inventory_source(task, merged_item)
+ if gate_resp is not None:
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "task_no": task_no,
+ "error": gate_resp.get("message") or "inventory_source_gate_blocked",
+ })
+ continue
+ if not inventory_identities_match(
+ task,
+ source_code=str(source.get("source_code") or ""),
+ site_id=str(source.get("site_id") or ""),
+ warehouse_id=str(source.get("warehouse_id") or ""),
+ ):
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "task_no": task_no,
+ "error": "inventory_identity_mismatch",
+ })
+ continue
+ else:
+ identity_error = _validate_batch_callback_worker_identity(merged_item, source)
+ if identity_error:
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "error": identity_error,
+ })
+ continue
+
+ verify_wh = _batch_snapshot_verify_warehouse_id(task, source, merged_item)
+ item_savepoint = db.session.begin_nested()
+ item_orphan_path: str | None = None
+ created_new = False
+ inv_file: ShippingInventoryFile | None = None
+ created_entry: dict[str, Any] | None = None
+ try:
+ try:
+ inv_file, created_new = get_or_create_rpa_inventory_snapshot(
+ source=source,
+ local_path=path,
+ source_file_name=path.name,
+ rpa_run_no=run_no or None,
+ schedule_run_id=schedule_run_id,
+ trigger_type=str(payload.get("trigger_type") or "scheduled"),
+ success=True,
+ verify_warehouse_id=verify_wh,
+ )
+ except AppError as exc:
+ raise _RpaCallbackItemAbort(str(exc.message or "inventory_identity_mismatch")) from exc
+
+ if not created_new:
+ reuse_error = _validate_reused_snapshot_callback_file(inv_file, path)
+ if reuse_error:
+ raise _RpaCallbackItemAbort(reuse_error)
+
+ if (
+ created_new
+ and inv_file.storage_path
+ and not str(inv_file.storage_path).startswith("failed://")
+ ):
+ item_orphan_path = str(inv_file.storage_path)
+
+ created_entry = {
+ "inventory_file_no": inv_file.inventory_file_no,
+ "source_code": inv_file.source_code or source_code,
+ "site_id": inv_file.site_id or merged_item.get("site_id"),
+ "warehouse_id": inv_file.warehouse_id or warehouse_id,
+ "reused_existing_snapshot": not created_new,
+ }
+ created.append(created_entry)
+ if item_orphan_path:
+ batch_new_storage_paths.append(item_orphan_path)
+
+ if task_no and task:
+ if not inventory_identities_match(
+ task,
+ source_code=inv_file.source_code,
+ site_id=inv_file.site_id,
+ warehouse_id=inv_file.warehouse_id,
+ ):
+ raise _RpaCallbackItemAbort("inventory_identity_mismatch")
+ link = link_snapshot_to_task(
+ task,
+ inv_file,
+ reason="rpa_batch_callback",
+ audit_payload={"run_no": run_no},
+ )
+ if link is None:
+ raise _RpaCallbackItemAbort("inventory_identity_mismatch")
+ ingest_path = _snapshot_ingest_path(inv_file)
+ lines, column_meta = ingest_inventory_file(ingest_path, move_to=None)
+ if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}:
+ inventory_loaded_response(
+ task,
+ lines,
+ column_meta=column_meta,
+ source="rpa_batch_callback",
+ require_mapping_review=True,
+ event_type="inventory_rpa_ready",
+ commit=False,
+ )
+ _mark_inventory_rpa_run_no_consumed(
+ task,
+ _resolve_effective_callback_run_no(task, merged_item),
+ )
+
+ if path.is_file():
+ pending_callback_moves.append({
+ "path": path,
+ "run_no": run_no or None,
+ "task_no": task_no or None,
+ "schedule_run_id": schedule_run_id,
+ "inventory_file_no": inv_file.inventory_file_no,
+ })
+
+ item_savepoint.commit()
+ except _RpaCallbackItemAbort as abort:
+ item_savepoint.rollback()
+ if item_orphan_path:
+ from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
+
+ delete_inventory_storage_path(item_orphan_path)
+ if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path:
+ batch_new_storage_paths.pop()
+ if created_entry and created and created[-1] is created_entry:
+ created.pop()
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "task_no": task_no or None,
+ "error": abort.error,
+ })
+ continue
+ except Exception as exc:
+ item_savepoint.rollback()
+ if item_orphan_path:
+ from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
+
+ delete_inventory_storage_path(item_orphan_path)
+ if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path:
+ batch_new_storage_paths.pop()
+ if created_entry and created and created[-1] is created_entry:
+ created.pop()
+ failed.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "task_no": task_no,
+ "error": str(exc)[:200] or "batch_ingest_failed",
+ })
+ continue
+ elif raw_status == "skipped":
+ skipped.append({
+ "source_code": source_code,
+ "site_id": merged_item.get("site_id"),
+ "warehouse_id": warehouse_id,
+ "skip_reason": merged_item.get("skip_reason") or "skipped",
+ "message": merged_item.get("message") or merged_item.get("error_message") or "",
+ })
+ else:
+ failed.append({
+ "source_code": str(source.get("source_code") or source_code),
+ "site_id": source.get("site_id"),
+ "warehouse_id": source.get("warehouse_id"),
+ "error_code": merged_item.get("error_code") or "rpa_export_failed",
+ "error": merged_item.get("error_message"),
+ })
+
+ db.session.commit()
+ except Exception as exc:
+ db.session.rollback()
+ from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
+
+ for storage_path in batch_new_storage_paths:
+ delete_inventory_storage_path(storage_path)
+ return tool_response(
+ status="failed",
+ message=f"批量库存回调事务失败: {str(exc)[:200]}",
+ data={
+ "run_no": run_no,
+ "rolled_back_storage_paths": len(batch_new_storage_paths),
+ },
+ )
finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"}
if schedule_run_id is not None:
@@ -758,13 +1980,24 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
finalize_result = finalize_shipping_inventory_schedule_run(
schedule_run_id,
created=created,
+ skipped=skipped,
failed=failed,
payload=payload,
)
+ callback_move_warnings: list[str] = list(cleanup_retry_warnings)
+ if _should_flush_batch_callback_moves(schedule_run_id, finalize_result):
+ callback_move_warnings.extend(
+ _flush_pending_callback_moves(
+ pending_callback_moves,
+ inventory_processed_dir(),
+ ),
+ )
+
response_data = {
"run_no": run_no,
"created": created,
+ "skipped": skipped,
"failed": failed,
"rpa_mode": payload.get("rpa_mode"),
"schedule_finalize_status": finalize_result.get("schedule_finalize_status"),
@@ -773,9 +2006,175 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
response_data["schedule_finalize_error"] = finalize_result.get("error")
if finalize_result.get("manual_retryable"):
response_data["schedule_finalize_manual_retryable"] = True
+ if callback_move_warnings:
+ response_data["callback_move_warnings"] = callback_move_warnings
+
+ outcome = _resolve_rpa_inventory_batch_response_outcome(
+ created=created,
+ skipped=skipped,
+ failed=failed,
+ finalize_result=finalize_result,
+ schedule_run_id=schedule_run_id,
+ )
+ result_status = str(outcome["result_status"])
+ response_data["result_status"] = result_status
+ response_data["callback_result_status"] = outcome["callback_result_status"]
+ response_data["success_count"] = outcome["success_count"]
+ response_data["skipped_count"] = outcome["skipped_count"]
+ response_data["failed_count"] = outcome["failed_count"]
return tool_response(
- status="ok" if created else "failed",
- message=f"批量库存回调完成:成功 {len(created)},失败 {len(failed)}",
+ status="ok",
+ message=(
+ f"批量库存回调完成({result_status}):"
+ f"成功 {outcome['success_count']},跳过 {outcome['skipped_count']},"
+ f"失败 {outcome['failed_count']}"
+ ),
data=response_data,
+ extra={
+ "result_status": result_status,
+ "success_count": outcome["success_count"],
+ "skipped_count": outcome["skipped_count"],
+ "failed_count": outcome["failed_count"],
+ },
+ )
+
+
+def _validate_repair_inventory_snapshot(
+ task: ShippingTask,
+ inv_file: ShippingInventoryFile | None,
+ *,
+ requested_file_no: str | None = None,
+) -> str | None:
+ """
+ 校验修复接口允许使用的库存快照。
+ 核心逻辑:默认仅 active link;显式 file_no 必须与 active 一致,且 ready/未过期/身份匹配。
+ """
+ from app.models import ShippingTaskInventoryLink
+ from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
+ from app.services.shipping_notice.inventory_snapshot_store import is_snapshot_fresh
+ from app.services.shipping_notice.inventory_source_gate import (
+ inventory_identities_match,
+ is_inventory_source_stable,
+ )
+
+ if inv_file is None:
+ return "snapshot_not_found"
+ active = active_inventory_file_for_task(task)
+ if active is None:
+ return "no_active_snapshot"
+ if inv_file.id != active.id:
+ return "snapshot_not_active_for_task"
+ if requested_file_no and active.inventory_file_no != requested_file_no:
+ return "snapshot_not_active_for_task"
+ if task.id is not None:
+ link = ShippingTaskInventoryLink.query.filter_by(
+ task_id=task.id,
+ inventory_file_id=inv_file.id,
+ is_active=True,
+ ).first()
+ if link is None:
+ return "snapshot_not_linked_to_task"
+ if str(inv_file.snapshot_status or "") != "ready":
+ return "snapshot_not_ready"
+ if not is_snapshot_fresh(inv_file):
+ return "snapshot_expired"
+ if not is_inventory_source_stable(task):
+ return "inventory_source_unstable"
+ if not inventory_identities_match(
+ task,
+ source_code=inv_file.source_code,
+ site_id=inv_file.site_id,
+ warehouse_id=inv_file.warehouse_id,
+ ):
+ return "inventory_identity_mismatch"
+ return None
+
+
+def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]:
+ """
+ 从任务当前库存快照 storage_path 幂等重建正式附件。
+ 【AI 触发时机】:RPA 回调已提交但任务附件晋升失败,需人工/后台补偿且不能重新消费 callback 时调用。
+
+ Args:
+ payload: 须含 task_id/task_no;可选 inventory_file_no 指定快照。
+
+ Returns:
+ tool_response:含 attachment_path 与 inventory_file_no。
+ """
+ from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
+
+ task = resolve_task_from_payload(payload)
+ if not task:
+ return tool_response(status="failed", message="未找到任务编号")
+
+ inv_file_no = str(payload.get("inventory_file_no") or "").strip()
+ inv_file = active_inventory_file_for_task(task)
+ if inv_file is None:
+ return tool_response(
+ status="failed",
+ task=task,
+ message="任务无可用库存快照,无法重建附件",
+ data=serialize_task_for_tool(task),
+ )
+ if inv_file_no and inv_file.inventory_file_no != inv_file_no:
+ return tool_response(
+ status="failed",
+ task=task,
+ message="指定快照不是任务当前 active 库存快照,已拒绝修复",
+ data={**serialize_task_for_tool(task), "error": "snapshot_not_active_for_task"},
+ )
+
+ validation_error = _validate_repair_inventory_snapshot(
+ task,
+ inv_file,
+ requested_file_no=inv_file_no or None,
+ )
+ if validation_error:
+ return tool_response(
+ status="failed",
+ task=task,
+ message="库存快照未通过修复校验,已拒绝重建附件",
+ data={**serialize_task_for_tool(task), "error": validation_error},
+ )
+
+ try:
+ attachment_path = rebuild_task_inventory_attachment_from_snapshot(task, inv_file)
+ except (FileNotFoundError, OSError, ValueError) as exc:
+ return tool_response(
+ status="failed",
+ task=task,
+ message=f"重建任务库存附件失败: {str(exc)[:200]}",
+ data={**serialize_task_for_tool(task), "error": "attachment_rebuild_failed"},
+ )
+
+ log_task_event(
+ task,
+ "inventory_attachment_repaired",
+ {
+ "inventory_file_no": inv_file.inventory_file_no,
+ "attachment_path": str(attachment_path),
+ "source": str(payload.get("source") or "manual_repair"),
+ },
+ )
+ try:
+ db.session.commit()
+ except Exception as exc:
+ db.session.rollback()
+ return tool_response(
+ status="failed",
+ task=task,
+ message=f"附件修复事件提交失败: {str(exc)[:200]}",
+ data=serialize_task_for_tool(task),
+ )
+
+ return tool_response(
+ status="ok",
+ task=task,
+ message="任务库存附件已从快照重建",
+ data={
+ **serialize_task_for_tool(task),
+ "inventory_file_no": inv_file.inventory_file_no,
+ "attachment_path": str(attachment_path),
+ },
)
diff --git a/backend/app/services/shipping_notice/inventory_snapshot.py b/backend/app/services/shipping_notice/inventory_snapshot.py
index 2a6f7138..8e6eae81 100644
--- a/backend/app/services/shipping_notice/inventory_snapshot.py
+++ b/backend/app/services/shipping_notice/inventory_snapshot.py
@@ -248,7 +248,18 @@ def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40
def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[list[Any]], int]:
- """Load worksheet rows; returns (rows, total_row_count_hint)."""
+ """Load worksheet or CSV rows; returns (rows, total_row_count_hint)."""
+ suffix = path.suffix.lower()
+ if suffix == ".csv":
+ from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows
+
+ rows = load_inventory_csv_rows(path, max_rows=max_rows)
+ try:
+ total = sum(1 for _ in path.open("r", encoding="utf-8", errors="ignore"))
+ except OSError:
+ total = len(rows)
+ return rows, int(total)
+
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
try:
ws = wb.active
diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/inventory_snapshot_store.py
index 9fb98545..b189c217 100644
--- a/backend/app/services/shipping_notice/inventory_snapshot_store.py
+++ b/backend/app/services/shipping_notice/inventory_snapshot_store.py
@@ -14,7 +14,6 @@ from pathlib import Path
from typing import Any
from flask import current_app
-from openpyxl import load_workbook
from app import db
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
@@ -22,6 +21,7 @@ from app.services.shipping_notice.inventory_file_store import (
_can_relink_inventory,
generate_inventory_file_no,
inventory_file_upload_path,
+ inventory_storage_suffix_for_path,
replace_task_inventory_link,
)
from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview
@@ -71,33 +71,156 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None =
def find_latest_ready_snapshot(
source_code: str | None,
- warehouse_id: str | None,
+ site_id: str | None,
+ warehouse_id: str | None = None,
) -> ShippingInventoryFile | None:
"""
- 查找指定 source/warehouse 最新 ready 且未过期的库存快照。
- 核心逻辑:按 exported_at 倒序取第一条;过期快照不在此返回。
+ 查找指定 source/site/warehouse 最新 ready 且未过期的库存快照。
+ 核心逻辑:库存身份须与任务正式库存源一致;site_id 与 warehouse_id 分别匹配,禁止混用。
"""
code = str(source_code or "").strip().upper()
+ site = str(site_id or "").strip().upper()
warehouse = str(warehouse_id or "").strip().upper()
- if not code or not warehouse:
+ if not code:
+ return None
+ if not site and not warehouse:
return None
- rows = (
- ShippingInventoryFile.query.filter_by(
- source_code=code,
- warehouse_id=warehouse,
- snapshot_status=_SNAPSHOT_STATUS_READY,
- )
- .order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc())
- .limit(5)
- .all()
+ query = ShippingInventoryFile.query.filter_by(
+ source_code=code,
+ snapshot_status=_SNAPSHOT_STATUS_READY,
)
+ if site:
+ query = query.filter_by(site_id=site)
+ if warehouse:
+ query = query.filter_by(warehouse_id=warehouse)
+ elif site:
+ query = query.filter(
+ (ShippingInventoryFile.warehouse_id.is_(None)) | (ShippingInventoryFile.warehouse_id == "")
+ )
+
+ rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all()
for row in rows:
if is_snapshot_fresh(row):
return row
return None
+def find_ready_rpa_inventory_snapshot(
+ *,
+ rpa_run_no: str,
+ source_code: str,
+ site_id: str,
+ warehouse_id: str,
+) -> ShippingInventoryFile | None:
+ """
+ 按 RPA 轮次 + 四字段身份查找已入库 ready 快照。
+ 核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。
+ """
+ run_no = str(rpa_run_no or "").strip()
+ code = str(source_code or "").strip().upper()
+ site = str(site_id or "").strip().upper()
+ warehouse = str(warehouse_id or "").strip().upper()
+ if not run_no or not code or not site or not warehouse:
+ return None
+ return (
+ ShippingInventoryFile.query.filter_by(
+ rpa_run_no=run_no,
+ source_code=code,
+ site_id=site,
+ warehouse_id=warehouse,
+ snapshot_status=_SNAPSHOT_STATUS_READY,
+ )
+ .order_by(ShippingInventoryFile.id.desc())
+ .first()
+ )
+
+
+def get_or_create_rpa_inventory_snapshot(
+ *,
+ source: dict[str, Any],
+ local_path: str | Path,
+ source_file_name: str | None = None,
+ rpa_run_no: str | None = None,
+ schedule_run_id: int | None = None,
+ trigger_type: str = "on_demand",
+ success: bool = True,
+ error_message: str | None = None,
+ user_id: int | None = None,
+ batch_id: int | None = None,
+ share_mode: str | None = None,
+ verify_warehouse_id: str | None = None,
+) -> tuple[ShippingInventoryFile, bool]:
+ """
+ 幂等创建 RPA 库存快照:同 run_no + 身份已存在时直接复用。
+ 核心逻辑:先查后建;并发插入冲突时回退到 savepoint 并复用已有记录。
+
+ Returns:
+ tuple[ShippingInventoryFile, bool]: (快照, 是否新建)。
+ """
+ from sqlalchemy.exc import IntegrityError
+
+ run_no = str(rpa_run_no or "").strip()
+ code = str(source.get("source_code") or "").strip().upper()
+ site = str(source.get("site_id") or "").strip().upper()
+ warehouse = str(verify_warehouse_id or source.get("warehouse_id") or "").strip().upper()
+ if run_no and code and site and warehouse:
+ existing = find_ready_rpa_inventory_snapshot(
+ rpa_run_no=run_no,
+ source_code=code,
+ site_id=site,
+ warehouse_id=warehouse,
+ )
+ if existing:
+ return existing, False
+
+ savepoint = db.session.begin_nested()
+ orphan_storage_path: str | None = None
+ try:
+ inv_file = create_inventory_snapshot_from_rpa(
+ source=source,
+ local_path=local_path,
+ source_file_name=source_file_name,
+ rpa_run_no=rpa_run_no,
+ schedule_run_id=schedule_run_id,
+ trigger_type=trigger_type,
+ success=success,
+ error_message=error_message,
+ user_id=user_id,
+ batch_id=batch_id,
+ share_mode=share_mode,
+ verify_warehouse_id=verify_warehouse_id,
+ )
+ if inv_file.storage_path and not str(inv_file.storage_path).startswith("failed://"):
+ orphan_storage_path = str(inv_file.storage_path)
+ db.session.flush()
+ savepoint.commit()
+ return inv_file, True
+ except IntegrityError:
+ savepoint.rollback()
+ if orphan_storage_path:
+ from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
+
+ delete_inventory_storage_path(orphan_storage_path)
+ if run_no and code and site and warehouse:
+ existing = find_ready_rpa_inventory_snapshot(
+ rpa_run_no=run_no,
+ source_code=code,
+ site_id=site,
+ warehouse_id=warehouse,
+ )
+ if existing:
+ return existing, False
+ raise
+ except Exception:
+ savepoint.rollback()
+ if orphan_storage_path:
+ from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
+
+ delete_inventory_storage_path(orphan_storage_path)
+ raise
+
+
def list_available_snapshots(
*,
source_code: str | None = None,
@@ -126,33 +249,15 @@ def _normalize_header_key(value: Any) -> str:
def _extract_warehouse_id_from_inventory_excel(path: Path) -> str:
- """
- 从库存 Excel 内容中提取 Warehouse ID。
- 核心逻辑:扫描前几行表头,命中 Warehouse ID/WH ID 等列后取其下方第一条非空值。
- """
- if not path or not path.is_file():
- return ""
- try:
- wb = load_workbook(filename=str(path), data_only=True, read_only=True)
- except Exception:
- return ""
- try:
- ws = wb.active
- rows = list(ws.iter_rows(min_row=1, max_row=min(ws.max_row or 1, 40), values_only=True))
- finally:
- wb.close()
+ """从库存 Excel 提取首个 Warehouse ID(兼容旧调用)。"""
+ from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel
- for row_idx, row in enumerate(rows):
- for col_idx, cell in enumerate(row):
- if _normalize_header_key(cell) not in _WAREHOUSE_ID_HEADER_ALIASES:
- continue
- for data_row in rows[row_idx + 1:]:
- if col_idx >= len(data_row):
- continue
- value = str(data_row[col_idx] or "").strip().upper()
- if value:
- return value
- return ""
+ values = extract_warehouse_ids_from_inventory_excel(path)
+ if not values:
+ return ""
+ if len(values) > 1:
+ return ""
+ return next(iter(values))
def create_inventory_snapshot_from_rpa(
@@ -168,6 +273,7 @@ def create_inventory_snapshot_from_rpa(
user_id: int | None = None,
batch_id: int | None = None,
share_mode: str | None = None,
+ verify_warehouse_id: str | None = None,
) -> ShippingInventoryFile:
"""
从 RPA 导出文件创建库存快照记录。
@@ -187,19 +293,39 @@ def create_inventory_snapshot_from_rpa(
source_code = str(source.get("source_code") or "").strip().upper()
configured_site_id = str(source.get("site_id") or "").strip().upper()
export_warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
+ runtime_identity_applied = bool(source.get("_runtime_identity_applied"))
excel_warehouse_id = ""
- warehouse_id = configured_site_id
- warehouse_code = warehouse_id
+ warehouse_id = export_warehouse_id
+ warehouse_code = warehouse_id or configured_site_id
+ excel_verified = False
if success:
- path = inventory_file_upload_path(inventory_file_no)
- path.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(local_path, path)
- excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(path)
- warehouse_id = configured_site_id or excel_warehouse_id
- warehouse_code = warehouse_id
- preview = read_inventory_schema_preview(path)
- preview["upload_filename"] = str(source_file_name or Path(local_path).name).strip() or path.name
+ local = Path(local_path)
+ expected_wh = str(verify_warehouse_id or export_warehouse_id or "").strip().upper()
+ if expected_wh:
+ from app.services.shipping_notice.inventory_file_identity import (
+ assert_inventory_excel_warehouse_identity,
+ )
+
+ excel_warehouse_id = assert_inventory_excel_warehouse_identity(
+ local,
+ expected_warehouse_id=expected_wh,
+ operation="rpa_snapshot",
+ )
+ warehouse_id = expected_wh
+ warehouse_code = warehouse_id
+ excel_verified = True
+ path = inventory_file_upload_path(
+ inventory_file_no,
+ suffix=inventory_storage_suffix_for_path(local),
+ )
+ if not excel_verified and not warehouse_id:
+ excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(local)
+ if excel_warehouse_id:
+ warehouse_id = excel_warehouse_id
+ warehouse_code = warehouse_id
+ preview = read_inventory_schema_preview(local)
+ preview["upload_filename"] = str(source_file_name or local.name).strip() or path.name
snapshot_status = _SNAPSHOT_STATUS_READY
storage_path = str(path)
else:
@@ -208,6 +334,8 @@ def create_inventory_snapshot_from_rpa(
snapshot_status = _SNAPSHOT_STATUS_FAILED
storage_path = str(path) if path and path.is_file() else ""
+ from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version
+
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
batch_id=batch_id,
@@ -219,6 +347,9 @@ def create_inventory_snapshot_from_rpa(
line_count=0,
warehouse_id=warehouse_id or None,
warehouse_code=warehouse_code or None,
+ site_id=configured_site_id or None,
+ source_config_version=get_inventory_sources_config_version(),
+ identity_status="pending" if success else "unknown",
source_code=source_code or None,
source_type=str(source.get("source_type") or "").strip() or None,
snapshot_status=snapshot_status,
@@ -233,12 +364,38 @@ def create_inventory_snapshot_from_rpa(
"site_id": configured_site_id or None,
"export_warehouse_id": export_warehouse_id,
"excel_warehouse_id": excel_warehouse_id or None,
- "warehouse_id_source": "site_id" if configured_site_id else ("inventory_excel" if excel_warehouse_id else None),
+ "warehouse_id_source": (
+ "task_identity_excel_verified"
+ if excel_verified
+ else (
+ "runtime_identity"
+ if runtime_identity_applied
+ else (
+ "export_config"
+ if export_warehouse_id
+ else ("inventory_excel" if excel_warehouse_id else None)
+ )
+ )
+ ),
+ "excel_warehouse_verified": excel_verified,
"trigger_type": trigger_type,
},
)
db.session.add(inv_file)
db.session.flush()
+ # [STEP] 先 flush 再落盘:唯一约束冲突时不会留下已复制的孤儿文件。
+ if success and storage_path and not str(storage_path).startswith("failed://"):
+ path = Path(storage_path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ shutil.copy2(local_path, path)
+ except Exception:
+ if path.exists():
+ try:
+ path.unlink()
+ except OSError:
+ pass
+ raise
return inv_file
@@ -247,6 +404,7 @@ def link_snapshot_to_task(
inv_file: ShippingInventoryFile,
*,
reason: str,
+ role: str = "member",
audit_payload: dict[str, Any] | None = None,
) -> ShippingTaskInventoryLink | None:
"""
@@ -265,9 +423,25 @@ def link_snapshot_to_task(
if inv_file.exported_at:
age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0)
- link = replace_task_inventory_link(task, inv_file, role="member")
+ from app.services.shipping_notice.inventory_source_gate import inventory_identities_match
+
+ identity_ok = inventory_identities_match(
+ task,
+ source_code=inv_file.source_code,
+ site_id=inv_file.site_id,
+ warehouse_id=inv_file.warehouse_id,
+ )
+ inv_file.identity_status = "verified" if identity_ok else "mismatch"
+ if not identity_ok:
+ return None
+
+ link = replace_task_inventory_link(task, inv_file, role=role)
link.link_reason = reason
link.matched_warehouse_id = inv_file.warehouse_id
+ link.matched_source_code = inv_file.source_code
+ link.matched_site_id = inv_file.site_id
+ link.identity_check_status = "verified" if identity_ok else "mismatch"
+ link.identity_checked_at = datetime.utcnow()
link.snapshot_age_seconds = age_seconds
link.audit_payload_json = {
**(audit_payload or {}),
diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py
new file mode 100644
index 00000000..022e5ac2
--- /dev/null
+++ b/backend/app/services/shipping_notice/inventory_source_gate.py
@@ -0,0 +1,402 @@
+"""
+services/shipping_notice/inventory_source_gate.py
+
+用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
+依赖:inventory_source_rules、inventory_sources、models.ShippingTask、core.errors。
+逻辑:parse_notice 先裁决线索;解析确认通过后未稳定才进入 inventory_source_review;
+ RPA/库存/匹配/导出统一经本模块硬门禁,禁止散落判断。
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+from app.core.errors import AppError
+from app.models import ShippingTask
+from app.services.shipping_notice.inventory_source_identity import identity_matches_config
+from app.services.shipping_notice.inventory_source_rules import (
+ InventorySourceAdjudication,
+ adjudicate_inventory_source,
+ confirm_inventory_source_by_code,
+ compute_routing_fingerprint,
+ extract_routing_context,
+)
+from app.services.shipping_notice.inventory_sources import get_inventory_source, get_inventory_sources_config_version
+
+
+STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed"})
+
+INVENTORY_SOURCE_ERROR_CODES = {
+ "unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
+ "ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
+ "invalid": "SHIPPING.INVENTORY_SOURCE_INVALID",
+ "conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED",
+ "confirmation_required": "SHIPPING.INVENTORY_SOURCE_CONFIRMATION_REQUIRED",
+ "changed": "SHIPPING.INVENTORY_SOURCE_CHANGED",
+ "identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH",
+ "gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
+}
+
+
+def _inventory_source_config_current(task: ShippingTask) -> bool:
+ """任务上记录的库存源配置版本须与当前 YAML 版本一致。"""
+ stored = str(task.inventory_source_config_version or "").strip()
+ current = get_inventory_sources_config_version()
+ if not stored:
+ return False
+ return stored == current
+
+
+def is_inventory_source_stable(task: ShippingTask) -> bool:
+ """
+ 判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
+ 核心逻辑:独立字段齐全、配置版本一致、与启用配置身份一致;status 须为 resolved 或 user_confirmed。
+ """
+ status = str(task.inventory_source_status or "").strip()
+ if status not in STABLE_INVENTORY_SOURCE_STATUSES:
+ return False
+ if not _inventory_source_config_current(task):
+ return False
+ code = str(task.inventory_source_code or "").strip().upper()
+ if not code:
+ return False
+ source_type = str(task.inventory_source_type or "").strip()
+ if not source_type:
+ return False
+ source = get_inventory_source(code)
+ if not source:
+ return False
+ if source_type != str(source.get("source_type") or "").strip():
+ return False
+
+ site_id = str(task.inventory_site_id or "").strip().upper()
+ task_wh = str(task.inventory_warehouse_id or "").strip().upper()
+ if not site_id or not task_wh:
+ return False
+ if not identity_matches_config(
+ source,
+ site_id=site_id,
+ warehouse_id=task_wh,
+ context=extract_routing_context(task),
+ ):
+ return False
+
+ fingerprint = str(task.inventory_routing_fingerprint or "").strip()
+ if not fingerprint:
+ return False
+ context = extract_routing_context(task)
+ if fingerprint != compute_routing_fingerprint(context):
+ return False
+
+ return True
+
+
+def routing_fingerprint_changed(task: ShippingTask, context: dict[str, Any]) -> bool:
+ """比较当前路由上下文与任务已存指纹,判断人工确认是否因重解析或配置变更失效。"""
+ previous = str(task.inventory_routing_fingerprint or "").strip()
+ if not previous:
+ return False
+ return previous != compute_routing_fingerprint(context)
+
+
+def inventory_source_config_changed(task: ShippingTask) -> bool:
+ """配置版本变化会使已确认库存源失效。"""
+ stored = str(task.inventory_source_config_version or "").strip()
+ if not stored:
+ return bool(str(task.inventory_source_status or "").strip())
+ return stored != get_inventory_sources_config_version()
+
+
+def apply_destination_fields(task: ShippingTask, context: dict[str, Any]) -> None:
+ """将标准化目的地线索写入任务独立字段。"""
+ task.destination_code = str(context.get("destination_code") or "").strip().upper() or None
+ task.destination_city = str(context.get("destination_city") or "").strip() or None
+ task.destination_country = str(context.get("destination_country") or "").strip().upper() or None
+ task.warehouse_hint = str(context.get("warehouse_hint") or "").strip() or None
+
+
+def clear_inventory_source_confirmation(task: ShippingTask) -> None:
+ """路由指纹或配置版本变化时清除旧人工确认信息及过期 RPA 参数。"""
+ task.inventory_source_confirmed_by = None
+ task.inventory_source_confirmed_at = None
+ if str(task.inventory_source_status or "").strip() == "user_confirmed":
+ task.inventory_source_status = "unresolved"
+ task.inventory_source_method = None
+ payload = dict(task.step_payload_json or {})
+ payload.pop("rpa_inventory_source", None)
+ task.step_payload_json = payload
+
+
+def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudication:
+ """从已稳定任务字段重建裁决结果,供跳过重复裁决时使用。"""
+ context = extract_routing_context(task)
+ return InventorySourceAdjudication(
+ status=str(task.inventory_source_status or "").strip(),
+ method=str(task.inventory_source_method or "").strip() or None,
+ source_code=str(task.inventory_source_code or "").strip().upper() or None,
+ source_type=str(task.inventory_source_type or "").strip() or None,
+ site_id=str(task.inventory_site_id or "").strip().upper() or None,
+ warehouse_id=str(task.inventory_warehouse_id or "").strip().upper() or None,
+ config_version=str(task.inventory_source_config_version or "").strip() or None,
+ routing_fingerprint=str(task.inventory_routing_fingerprint or "").strip()
+ or compute_routing_fingerprint(context),
+ destination_candidates=context.get("destination_candidates") or [],
+ )
+
+
+def apply_inventory_source_adjudication(
+ task: ShippingTask,
+ adjudication: InventorySourceAdjudication,
+ *,
+ confirmed_by_user_id: int | None = None,
+) -> None:
+ """
+ 将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。
+ 核心逻辑:正式身份以独立字段为准;JSON 仅承载展示与审计辅助信息。
+ """
+ context = extract_routing_context(task)
+ fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context)
+ task.inventory_routing_fingerprint = fingerprint
+ apply_destination_fields(task, context)
+
+ task.inventory_source_status = adjudication.status
+ task.inventory_source_method = adjudication.method or None
+ task.inventory_source_config_version = adjudication.config_version or get_inventory_sources_config_version()
+
+ if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
+ task.inventory_source_code = adjudication.source_code
+ task.inventory_source_type = adjudication.source_type
+ task.inventory_site_id = adjudication.site_id
+ task.inventory_warehouse_id = adjudication.warehouse_id or None
+ if adjudication.status == "user_confirmed" and confirmed_by_user_id:
+ task.inventory_source_confirmed_by = confirmed_by_user_id
+ task.inventory_source_confirmed_at = datetime.utcnow()
+ elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
+ task.inventory_source_code = None
+ task.inventory_source_type = None
+ task.inventory_site_id = None
+ task.inventory_warehouse_id = None
+ payload = dict(task.step_payload_json or {})
+ payload.pop("rpa_inventory_source", None)
+ task.step_payload_json = payload
+
+ payload = dict(task.step_payload_json or {})
+ payload["inventory_source_resolution"] = {
+ "status": adjudication.status,
+ "method": adjudication.method,
+ "reason": adjudication.reason,
+ "destination_candidates": adjudication.destination_candidates,
+ "candidates": adjudication.candidates,
+ "evidence": adjudication.evidence,
+ "conflicts": adjudication.conflicts,
+ "config_version": adjudication.config_version,
+ "routing_fingerprint": fingerprint,
+ }
+ if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
+ from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
+
+ rpa_source = build_task_rpa_inventory_source(task)
+ if rpa_source:
+ payload["rpa_inventory_source"] = rpa_source
+ else:
+ payload.pop("rpa_inventory_source", None)
+ task.step_payload_json = payload
+
+
+def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
+ """
+ 对任务执行库存源裁决并写入独立字段。
+ 【AI 触发时机】:订单解析完成后由 parse_notice 调用;重解析时同样调用以刷新裁决。
+ """
+ context = extract_routing_context(task)
+ if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context):
+ clear_inventory_source_confirmation(task)
+
+ if (
+ str(task.inventory_source_status or "").strip() == "user_confirmed"
+ and is_inventory_source_stable(task)
+ and not routing_fingerprint_changed(task, context)
+ and not inventory_source_config_changed(task)
+ ):
+ return _adjudication_from_stable_task(task)
+
+ adjudication = adjudicate_inventory_source(task)
+ if (
+ str(task.inventory_source_status or "").strip() == "user_confirmed"
+ and adjudication.status == "resolved"
+ and adjudication.source_code
+ and str(adjudication.source_code).strip().upper() == str(task.inventory_source_code or "").strip().upper()
+ and is_inventory_source_stable(task)
+ ):
+ adjudication = InventorySourceAdjudication(
+ status="user_confirmed",
+ method="user_confirmed",
+ source_code=adjudication.source_code,
+ source_type=adjudication.source_type,
+ site_id=adjudication.site_id,
+ warehouse_id=adjudication.warehouse_id,
+ config_version=adjudication.config_version,
+ routing_fingerprint=adjudication.routing_fingerprint,
+ candidates=adjudication.candidates,
+ destination_candidates=adjudication.destination_candidates,
+ evidence=adjudication.evidence,
+ reason=adjudication.reason,
+ )
+ apply_inventory_source_adjudication(task, adjudication)
+ return adjudication
+
+
+def task_needs_parse_review(task: ShippingTask) -> bool:
+ """
+ 判断任务是否仍需完成低置信度解析人工确认。
+
+ 核心逻辑:仅认显式标记——review/pending 为 parse_review / low_confidence,
+ 或存量 pending_parse_review_after_source。禁止仅凭 parse_confidence 兜底,
+ 否则「解析已确认 → 再确认库存源」会被误判回解析复核。
+ """
+ from app.services.shipping_notice.constants import PH_LOW_CONF, RS_PARSE_REVIEW
+
+ if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF:
+ return True
+ payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
+ return bool(payload.get("pending_parse_review_after_source"))
+
+
+def transition_task_to_inventory_source_review(
+ task: ShippingTask,
+ adjudication: InventorySourceAdjudication,
+ *,
+ error_message: str | None = None,
+ mark_pending_parse_review: bool = False,
+) -> None:
+ """
+ 将任务持久化到库存源人工复核检查点,并写入候选裁决信息。
+
+ 核心逻辑:统一状态机转换 + current_step + step_payload 候选,供 UI 展示确认按钮。
+ mark_pending_parse_review 仅用于存量/兼容路径(旧顺序先源后解析);
+ 新路径应先完成 parse_review,再进入本检查点,通常不传 True。
+ """
+ from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
+
+ apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
+ task.current_step = "step2_parse_confirm"
+ task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源"
+ payload = dict(task.step_payload_json or {})
+ payload["inventory_source_resolution"] = {
+ "status": adjudication.status,
+ "method": adjudication.method,
+ "reason": adjudication.reason,
+ "destination_candidates": adjudication.destination_candidates,
+ "candidates": adjudication.candidates,
+ "evidence": adjudication.evidence,
+ "conflicts": adjudication.conflicts,
+ "config_version": adjudication.config_version,
+ "routing_fingerprint": adjudication.routing_fingerprint,
+ }
+ if mark_pending_parse_review:
+ payload["pending_parse_review_after_source"] = True
+ task.step_payload_json = payload
+
+
+def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceAdjudication:
+ """
+ 对已通过解析确认但库存源仍不稳定的任务,补做裁决并落库到 inventory_source_review。
+
+ 【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。
+ 核心逻辑:新业务顺序是先解析后库存源;仅当仍检测到待解析复核(含存量延后标记)时,
+ 才写入 pending_parse_review_after_source 以兼容旧任务。
+ """
+ adjudication = adjudicate_and_apply_inventory_source(task)
+ if not is_inventory_source_stable(task):
+ transition_task_to_inventory_source_review(
+ task,
+ adjudication,
+ mark_pending_parse_review=task_needs_parse_review(task),
+ )
+ return adjudication
+
+
+def confirm_task_inventory_source(
+ task: ShippingTask,
+ source_code: str,
+ *,
+ user_id: int | None = None,
+) -> InventorySourceAdjudication:
+ """
+ 用户选择 source_code 后由后端重新校验并写入正式库存源。
+ 核心逻辑:前端只提交 source_code;站点与库位始终从配置生成。
+ """
+ adjudication = confirm_inventory_source_by_code(task, source_code)
+ apply_inventory_source_adjudication(task, adjudication, confirmed_by_user_id=user_id)
+ return adjudication
+
+
+def assert_inventory_source_gate(
+ task: ShippingTask,
+ *,
+ operation: str = "continue",
+) -> None:
+ """
+ 库存源硬门禁:未稳定时抛出统一业务异常,防止后续流程绕过。
+ Args:
+ task: 当前发货任务。
+ operation: 触发门禁的操作名,写入错误 details。
+ Raises:
+ AppError: 库存源未稳定或身份不一致。
+ """
+ if inventory_source_config_changed(task):
+ raise AppError(
+ code=INVENTORY_SOURCE_ERROR_CODES["changed"],
+ message="库存源配置已更新,请重新确认库存查询来源",
+ http_status=409,
+ details={"operation": operation, "task_no": task.task_no},
+ )
+ if is_inventory_source_stable(task):
+ return
+ status = str(task.inventory_source_status or "unresolved").strip()
+ code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"])
+ raise AppError(
+ code=code,
+ message="库存源尚未确定,无法继续后续流程",
+ http_status=409,
+ details={
+ "operation": operation,
+ "inventory_source_status": status,
+ "task_no": task.task_no,
+ },
+ )
+
+
+def task_inventory_identity(task: ShippingTask) -> dict[str, str | None]:
+ """返回任务当前正式库存身份,供库存文件绑定与匹配校验。"""
+ return {
+ "inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None,
+ "inventory_site_id": str(task.inventory_site_id or "").strip().upper() or None,
+ "inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None,
+ }
+
+
+def inventory_identities_match(
+ task: ShippingTask,
+ *,
+ source_code: str | None,
+ site_id: str | None,
+ warehouse_id: str | None,
+) -> bool:
+ """校验库存文件/链接身份与任务正式库存源是否完全一致。"""
+ identity = task_inventory_identity(task)
+ if not is_inventory_source_stable(task):
+ return False
+ expected_code = str(source_code or "").strip().upper()
+ if expected_code != identity["inventory_source_code"]:
+ return False
+
+ file_site = str(site_id or "").strip().upper()
+ file_wh = str(warehouse_id or "").strip().upper()
+ if not file_site or file_site != (identity["inventory_site_id"] or ""):
+ return False
+ if not file_wh or file_wh != (identity["inventory_warehouse_id"] or ""):
+ return False
+
+ return True
diff --git a/backend/app/services/shipping_notice/inventory_source_identity.py b/backend/app/services/shipping_notice/inventory_source_identity.py
new file mode 100644
index 00000000..2118f79b
--- /dev/null
+++ b/backend/app/services/shipping_notice/inventory_source_identity.py
@@ -0,0 +1,156 @@
+"""
+services/shipping_notice/inventory_source_identity.py
+
+用途:从库存源配置与订单路由上下文解析正式库存身份(source/site/warehouse)。
+依赖:无业务模块反向依赖;normalize/match 工具在本文件内定义。
+逻辑:裁决、门禁、RPA 与迁移回填统一调用本模块,禁止散落身份推导。
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Any
+
+
+def normalize_destination(value: Any) -> str:
+ """将 Dify/单据中的目的地线索标准化成可匹配 token。"""
+ text = str(value or "").strip().upper()
+ if not text:
+ return ""
+ return re.sub(r"[^A-Z0-9]+", " ", text).strip()
+
+
+def _matches_alias(candidate: str, alias: str) -> bool:
+ """别名按词元匹配,避免短 token 误命中更长编码。"""
+ return _alias_token_match(normalize_destination(candidate), alias)
+
+
+@dataclass(frozen=True)
+class ResolvedInventoryIdentity:
+ """稳定库存源四元组中的站点/库位解析结果。"""
+
+ source_code: str
+ source_type: str
+ site_id: str
+ warehouse_id: str
+
+
+@dataclass(frozen=True)
+class InventoryIdentityResolution:
+ """身份解析结果;失败时 reason 说明原因,ambiguous 时带 warehouse 候选。"""
+
+ ok: bool
+ identity: ResolvedInventoryIdentity | None = None
+ reason: str = ""
+ warehouse_candidates: tuple[str, ...] = ()
+
+
+def _alias_token_match(candidate: str, alias: str) -> bool:
+ """库位别名按词元精确匹配,禁止短别名误命中长编码。"""
+ alias_norm = normalize_destination(alias)
+ if not alias_norm:
+ return False
+ if candidate == alias_norm:
+ return True
+ return alias_norm in candidate.split()
+
+
+def _resolve_crane_warehouse_id(source: dict[str, Any], context: dict[str, Any]) -> InventoryIdentityResolution:
+ """Crane 库位由订单线索与 match_aliases 唯一命中决定。"""
+ aliases = [str(alias).strip() for alias in (source.get("match_aliases") or []) if str(alias).strip()]
+ if not aliases:
+ return InventoryIdentityResolution(ok=False, reason="crane_aliases_missing")
+
+ destination_candidates = list(context.get("destination_candidates") or [])
+ hint = normalize_destination(context.get("warehouse_hint"))
+ if hint:
+ destination_candidates.append(hint)
+
+ matched: list[str] = []
+ for candidate in destination_candidates:
+ candidate_norm = normalize_destination(candidate)
+ if not candidate_norm:
+ continue
+ for alias in aliases:
+ if _alias_token_match(candidate_norm, alias):
+ token = str(alias).strip().upper()
+ if token and token not in matched:
+ matched.append(token)
+
+ if len(matched) == 1:
+ site_id = str(source.get("site_id") or "CRANE").strip().upper()
+ return InventoryIdentityResolution(
+ ok=True,
+ identity=ResolvedInventoryIdentity(
+ source_code=str(source.get("source_code") or "").strip().upper(),
+ source_type=str(source.get("source_type") or "").strip(),
+ site_id=site_id,
+ warehouse_id=matched[0],
+ ),
+ )
+ if len(matched) > 1:
+ return InventoryIdentityResolution(
+ ok=False,
+ reason="crane_warehouse_ambiguous",
+ warehouse_candidates=tuple(matched),
+ )
+ return InventoryIdentityResolution(ok=False, reason="crane_warehouse_unresolved")
+
+
+def resolve_inventory_source_identity(
+ source: dict[str, Any],
+ context: dict[str, Any],
+) -> InventoryIdentityResolution:
+ """
+ 解析库存源在订单上下文下的正式 site_id / warehouse_id。
+ 核心逻辑:DSV 使用配置显式声明;Crane 通过别名唯一命中推导库位。
+ """
+ source_code = str(source.get("source_code") or "").strip().upper()
+ source_type = str(source.get("source_type") or "").strip()
+ if not source_code or not source_type:
+ return InventoryIdentityResolution(ok=False, reason="source_incomplete")
+
+ if source_type == "crane_footprint":
+ return _resolve_crane_warehouse_id(source, context)
+
+ site_id = str(source.get("site_id") or "").strip().upper()
+ warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
+ if not site_id or not warehouse_id:
+ return InventoryIdentityResolution(ok=False, reason="identity_incomplete")
+ return InventoryIdentityResolution(
+ ok=True,
+ identity=ResolvedInventoryIdentity(
+ source_code=source_code,
+ source_type=source_type,
+ site_id=site_id,
+ warehouse_id=warehouse_id,
+ ),
+ )
+
+
+def identity_matches_config(
+ source: dict[str, Any],
+ *,
+ site_id: str | None,
+ warehouse_id: str | None,
+ context: dict[str, Any] | None = None,
+) -> bool:
+ """校验任务身份与配置一致;Crane 额外要求库位与当前路由上下文唯一解析结果一致。"""
+ cfg_site = str(source.get("site_id") or "").strip().upper()
+ cfg_wh = str(source.get("warehouse_id") or "").strip().upper()
+ task_site = str(site_id or "").strip().upper()
+ task_wh = str(warehouse_id or "").strip().upper()
+ if not task_site or not task_wh:
+ return False
+ if cfg_site and task_site != cfg_site:
+ return False
+ source_type = str(source.get("source_type") or "").strip()
+ if source_type == "crane_footprint":
+ if context is None:
+ return False
+ resolution = resolve_inventory_source_identity(source, context)
+ if not resolution.ok or not resolution.identity:
+ return False
+ return resolution.identity.warehouse_id == task_wh
+ return bool(cfg_wh) and task_wh == cfg_wh
diff --git a/backend/app/services/shipping_notice/inventory_source_rules.py b/backend/app/services/shipping_notice/inventory_source_rules.py
index 9b5aebc5..b6bff0b6 100644
--- a/backend/app/services/shipping_notice/inventory_source_rules.py
+++ b/backend/app/services/shipping_notice/inventory_source_rules.py
@@ -1,38 +1,89 @@
"""
services/shipping_notice/inventory_source_rules.py
-用途:根据发货通知目的地/港口/仓库线索解析应使用的库存 RPA 源。
-依赖:inventory_sources、ShippingTask step_payload_json/单头/订单行。
-逻辑:从 JSON 配置的 match_aliases 命中库存源;Dify 只提供候选字段,本模块负责标准化与唯一性判断。
+用途:根据发货通知路由线索对库存源做确定性裁决。
+依赖:inventory_sources、ShippingTask 独立字段与 step_payload_json。
+逻辑:Dify/LLM 只提供路由线索;本模块负责唯一性判断、冲突检测与人工确认复核。
"""
from __future__ import annotations
-import re
-from dataclasses import dataclass
+import hashlib
+import json
+from dataclasses import dataclass, field
from typing import Any
from app.models import ShippingTask
-from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
+from app.services.shipping_notice.inventory_source_identity import (
+ normalize_destination,
+ resolve_inventory_source_identity,
+)
+from app.services.shipping_notice.inventory_sources import (
+ build_rpa_inventory_source,
+ get_inventory_source,
+ get_inventory_sources_config_version,
+ list_inventory_sources,
+)
@dataclass(frozen=True)
-class InventorySourceResolution:
- """库存源解析结果。"""
+class InventorySourceAdjudication:
+ """库存源裁决结构化结果。"""
status: str
- source: dict[str, Any] | None
- candidates: list[dict[str, Any]]
- destination_candidates: list[str]
+ method: str | None = None
+ source_code: str | None = None
+ source_type: str | None = None
+ site_id: str | None = None
+ warehouse_id: str | None = None
+ config_version: str | None = None
+ routing_fingerprint: str | None = None
+ candidates: list[dict[str, Any]] = field(default_factory=list)
+ destination_candidates: list[str] = field(default_factory=list)
+ evidence: list[dict[str, Any]] = field(default_factory=list)
+ conflicts: list[str] = field(default_factory=list)
reason: str = ""
+# Backward-compatible alias
+InventorySourceResolution = InventorySourceAdjudication
+
+
+def compute_routing_fingerprint(context: dict[str, Any]) -> str:
+ """
+ 根据标准化路由上下文与配置版本生成可比较指纹。
+ 核心逻辑:相同输入与相同配置版本下指纹必须稳定,用于判断人工确认是否失效。
+ """
+ normalized = {
+ "destination_code": str(context.get("destination_code") or "").strip().upper(),
+ "destination_city": str(context.get("destination_city") or "").strip().upper(),
+ "destination_country": str(context.get("destination_country") or "").strip().upper(),
+ "warehouse_hint": str(context.get("warehouse_hint") or "").strip().upper(),
+ "customer_code": str(context.get("customer_code") or "").strip().upper(),
+ "customer_name": str(context.get("customer_name") or "").strip().upper(),
+ "order_type": str(context.get("order_type") or "").strip().upper(),
+ "config_version": get_inventory_sources_config_version(),
+ "destination_candidates": sorted(
+ str(item).strip().upper()
+ for item in (context.get("destination_candidates") or [])
+ if str(item).strip()
+ ),
+ }
+ digest = hashlib.sha256(json.dumps(normalized, sort_keys=True, ensure_ascii=False).encode("utf-8"))
+ return digest.hexdigest()[:32]
+
+
def normalize_destination(value: Any) -> str:
"""将 Dify/单据中的目的地线索标准化成可匹配 token。"""
- text = str(value or "").strip().upper()
- if not text:
- return ""
- return re.sub(r"[^A-Z0-9]+", " ", text).strip()
+ from app.services.shipping_notice.inventory_source_identity import normalize_destination as _normalize
+
+ return _normalize(value)
+
+
+def _matches_alias(candidate: str, alias: str) -> bool:
+ from app.services.shipping_notice.inventory_source_identity import _matches_alias as _match
+
+ return _match(candidate, alias)
def _append_candidate(candidates: list[str], value: Any) -> None:
@@ -45,14 +96,14 @@ def _extract_destination_object(candidates: list[str], value: Any) -> None:
if not isinstance(value, dict):
_append_candidate(candidates, value)
return
- for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text"):
+ for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text", "destination_code"):
_append_candidate(candidates, value.get(key))
def extract_destination_candidates(task: ShippingTask) -> list[str]:
"""
从任务解析结果提取目的地/港口/仓库候选。
- 【AI 触发时机】:需要根据发货通知判断库存 RPA 源时调用,Dify 输出与后端字段都作为候选证据。
+ 【AI 触发时机】:订单解析后由裁决服务调用,Dify 输出与后端字段都作为候选证据。
"""
candidates: list[str] = []
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
@@ -60,6 +111,10 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
_append_candidate(candidates, item)
_extract_destination_object(candidates, payload.get("destination"))
_append_candidate(candidates, task.ship_to)
+ _append_candidate(candidates, task.destination_code)
+ _append_candidate(candidates, task.destination_city)
+ _append_candidate(candidates, task.destination_country)
+ _append_candidate(candidates, task.warehouse_hint)
for line in task.lines_json or []:
if not isinstance(line, dict):
continue
@@ -69,104 +124,413 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
return candidates
-def _matches_alias(candidate: str, alias: str) -> bool:
- normalized_alias = normalize_destination(alias)
- if not normalized_alias:
- return False
- return (
- candidate == normalized_alias
- or normalized_alias in candidate.split()
- or normalized_alias in candidate
- )
-
-
-def _candidate_summary(source: dict[str, Any]) -> dict[str, Any]:
- """人工确认候选项展示字段。"""
+def extract_routing_context(task: ShippingTask) -> dict[str, Any]:
+ """将任务解析结果标准化为库存路由上下文。"""
+ payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
+ destination = payload.get("destination") if isinstance(payload.get("destination"), dict) else {}
return {
- "source_code": source.get("source_code"),
- "display_name": source.get("display_name"),
- "warehouse_id": source.get("warehouse_id"),
- "site": source.get("site"),
- "source_type": source.get("source_type"),
+ "destination_code": task.destination_code or destination.get("port_code") or destination.get("destination_code"),
+ "destination_city": task.destination_city or destination.get("city"),
+ "destination_country": task.destination_country or destination.get("country"),
+ "warehouse_hint": task.warehouse_hint or destination.get("warehouse_hint"),
+ "customer_code": task.customer_code,
+ "customer_name": task.customer_name,
+ "order_type": payload.get("order_type"),
+ "destination_candidates": extract_destination_candidates(task),
}
-def resolve_inventory_source(task: ShippingTask) -> InventorySourceResolution:
- """根据任务目的地候选与 JSON match_aliases 解析唯一库存源。"""
- candidates = extract_destination_candidates(task)
- matched_codes: list[str] = []
- for candidate in candidates:
- for source in list_inventory_sources():
- aliases = source.get("match_aliases") or []
- if any(_matches_alias(candidate, alias) for alias in aliases):
- code = str(source.get("source_code") or "").strip().upper()
- if code and code not in matched_codes:
- matched_codes.append(code)
+def _candidate_summary(source: dict[str, Any], *, score: int = 0, matched_by: str | None = None) -> dict[str, Any]:
+ """人工确认候选项展示字段;前端必须提交 source_code。"""
+ return {
+ "source_code": source.get("source_code"),
+ "display_name": source.get("display_name"),
+ "site_id": source.get("site_id"),
+ "warehouse_id": source.get("warehouse_id"),
+ "source_type": source.get("source_type"),
+ "match_score": score,
+ "matched_by": matched_by,
+ }
- if len(matched_codes) == 1:
- source = build_rpa_inventory_source(matched_codes[0])
- if source:
- return InventorySourceResolution(
- status="resolved",
- source=source,
- candidates=[_candidate_summary(source)],
- destination_candidates=candidates,
+
+def _normalize_token_list(values: Any) -> list[str]:
+ if not isinstance(values, list):
+ return []
+ return [normalize_destination(item) for item in values if normalize_destination(item)]
+
+
+def _all_enabled_source_candidates() -> list[dict[str, Any]]:
+ """返回全部启用库存源候选项,供未命中时人工选择。"""
+ return [
+ _candidate_summary(source)
+ for source in list_inventory_sources()
+ if source.get("enabled", True) is not False
+ ]
+
+
+def _source_matches_destination(source: dict[str, Any], destination_candidates: list[str]) -> bool:
+ """判断库存源别名是否与订单目的地线索有交集。"""
+ aliases = list(source.get("match_aliases") or [])
+ match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
+ aliases.extend(_normalize_token_list(match_cfg.get("aliases")))
+ if not aliases:
+ return False
+ return any(_matches_alias(candidate, alias) for candidate in destination_candidates for alias in aliases)
+
+
+def _source_field_excluded(source: dict[str, Any], context: dict[str, Any]) -> bool:
+ """显式 match 规则已声明但订单字段未命中时,排除该库存源。"""
+ match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
+ for field_name, cfg_key in (
+ ("destination_code", "destination_codes"),
+ ("customer_code", "customers"),
+ ("order_type", "order_types"),
+ ("warehouse_hint", "warehouse_hints"),
+ ):
+ field_value = normalize_destination(context.get(field_name))
+ allowed = _normalize_token_list(match_cfg.get(cfg_key))
+ if allowed and field_value:
+ if not (
+ field_value in allowed
+ or any(field_value in item or item in field_value for item in allowed)
+ ):
+ return True
+ return False
+
+
+def _detect_rule_conflicts(
+ matches: list[tuple[int, dict[str, Any], list[dict[str, Any]]]],
+ context: dict[str, Any],
+) -> list[str]:
+ """多候选同分时,检测不同来源对同一订单字段给出互斥规则命中。"""
+ conflicts: list[str] = []
+ field_hits: dict[str, set[str]] = {}
+ for _, source, _ in matches:
+ match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
+ for field_name, cfg_key in (
+ ("destination_code", "destination_codes"),
+ ("customer_code", "customers"),
+ ("order_type", "order_types"),
+ ("warehouse_hint", "warehouse_hints"),
+ ):
+ field_value = normalize_destination(context.get(field_name))
+ allowed = _normalize_token_list(match_cfg.get(cfg_key))
+ if not allowed or not field_value:
+ continue
+ hits = {
+ item
+ for item in allowed
+ if field_value in item or item in field_value or field_value == item
+ }
+ if hits:
+ field_hits.setdefault(field_name, set()).update(hits)
+ for field_name, hits in field_hits.items():
+ if len(hits) > 1:
+ conflicts.append(f"{field_name}_rule_conflict")
+ return conflicts
+
+
+def _source_match_score(source: dict[str, Any], context: dict[str, Any], destination_candidates: list[str]) -> tuple[int, list[dict[str, Any]]]:
+ """按配置 match 规则与 match_aliases 计算命中分数与证据。"""
+ score = 0
+ evidence: list[dict[str, Any]] = []
+ match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
+
+ for field_name, cfg_key in (
+ ("destination_code", "destination_codes"),
+ ("customer_code", "customers"),
+ ("order_type", "order_types"),
+ ("warehouse_hint", "warehouse_hints"),
+ ):
+ field_value = normalize_destination(context.get(field_name))
+ allowed = _normalize_token_list(match_cfg.get(cfg_key))
+ if allowed and field_value:
+ if field_value in allowed or any(field_value in item or item in field_value for item in allowed):
+ score += 10
+ evidence.append({"field": field_name, "value": field_value, "rule": cfg_key})
+
+ aliases = list(source.get("match_aliases") or []) + _normalize_token_list(match_cfg.get("aliases"))
+ for candidate in destination_candidates:
+ for alias in aliases:
+ if _matches_alias(candidate, alias):
+ score += 5
+ evidence.append({"field": "destination_candidate", "value": candidate, "alias": alias})
+ break
+
+ priority = int(source.get("priority") or 0)
+ if score > 0 and priority:
+ score += min(priority // 10, 5)
+ return score, evidence
+
+
+def _stable_from_source(
+ source: dict[str, Any],
+ *,
+ method: str,
+ evidence: list[dict[str, Any]],
+ context: dict[str, Any],
+) -> InventorySourceAdjudication:
+ """仅在四元组身份可完整解析时返回 resolved。"""
+ resolution = resolve_inventory_source_identity(source, context)
+ config_version = get_inventory_sources_config_version()
+ fingerprint = compute_routing_fingerprint(context)
+ destination_candidates = context.get("destination_candidates") or []
+ if not resolution.ok or not resolution.identity:
+ if resolution.reason == "crane_warehouse_ambiguous":
+ return InventorySourceAdjudication(
+ status="ambiguous",
+ method=method,
+ config_version=config_version,
+ routing_fingerprint=fingerprint,
+ candidates=[_candidate_summary(source, matched_by=method)],
+ destination_candidates=destination_candidates,
+ evidence=evidence,
+ reason=resolution.reason,
)
- if len(matched_codes) > 1:
- matched_sources = [
- _candidate_summary(source)
- for code in matched_codes
- for source in [build_rpa_inventory_source(code)]
- if source
- ]
- return InventorySourceResolution(
- status="ambiguous",
- source=None,
- candidates=matched_sources,
- destination_candidates=candidates,
- reason="matched_multiple_sources",
+ status = "invalid" if resolution.reason in {"source_incomplete", "crane_aliases_missing"} else "unresolved"
+ return InventorySourceAdjudication(
+ status=status,
+ method=method,
+ config_version=config_version,
+ routing_fingerprint=fingerprint,
+ candidates=[_candidate_summary(source, matched_by=method)],
+ destination_candidates=destination_candidates,
+ evidence=evidence,
+ conflicts=[resolution.reason] if resolution.reason else [],
+ reason=resolution.reason or "identity_incomplete",
)
- return InventorySourceResolution(
- status="unresolved",
- source=None,
- candidates=[_candidate_summary(item) for item in list_inventory_sources()],
- destination_candidates=candidates,
- reason="no_route_rule_matched",
+ identity = resolution.identity
+ return InventorySourceAdjudication(
+ status="resolved",
+ method=method,
+ source_code=identity.source_code,
+ source_type=identity.source_type,
+ site_id=identity.site_id,
+ warehouse_id=identity.warehouse_id,
+ config_version=config_version,
+ routing_fingerprint=fingerprint,
+ candidates=[_candidate_summary(source, score=100, matched_by=method)],
+ destination_candidates=destination_candidates,
+ evidence=evidence,
)
+def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
+ """
+ 根据任务路由上下文与配置规则做确定性库存源裁决。
+ 核心逻辑:相同输入与相同配置必须产生相同结果;区分未命中、多命中、冲突与配置无效。
+ """
+ context = extract_routing_context(task)
+ destination_candidates = context.get("destination_candidates") or []
+ config_version = get_inventory_sources_config_version()
+
+ scored: list[tuple[int, dict[str, Any], list[dict[str, Any]]]] = []
+ for source in list_inventory_sources():
+ if _source_field_excluded(source, context):
+ continue
+ source_type = str(source.get("source_type") or "").strip()
+ if source_type == "dsv360" and (
+ not str(source.get("site_id") or "").strip()
+ or not str(source.get("warehouse_id") or "").strip()
+ ):
+ continue
+ score, evidence = _source_match_score(source, context, destination_candidates)
+ if score > 0:
+ scored.append((score, source, evidence))
+
+ if not scored:
+ # Fallback: legacy match_aliases only
+ matched_codes: list[str] = []
+ alias_evidence: dict[str, list[dict[str, Any]]] = {}
+ for candidate in destination_candidates:
+ for source in list_inventory_sources():
+ aliases = source.get("match_aliases") or []
+ if any(_matches_alias(candidate, alias) for alias in aliases):
+ code = str(source.get("source_code") or "").strip().upper()
+ if code and code not in matched_codes:
+ matched_codes.append(code)
+ alias_evidence.setdefault(code, []).append(
+ {"field": "destination_candidate", "value": candidate, "alias_only": True}
+ )
+ if len(matched_codes) == 1:
+ source = get_inventory_source(matched_codes[0])
+ if source:
+ return _stable_from_source(
+ source,
+ method="rule_exact",
+ evidence=alias_evidence.get(matched_codes[0], []),
+ context=context,
+ )
+ if len(matched_codes) > 1:
+ candidates = [
+ _candidate_summary(src, matched_by="rule_exact")
+ for code in matched_codes
+ for src in [get_inventory_source(code)]
+ if src
+ ]
+ return InventorySourceAdjudication(
+ status="ambiguous",
+ config_version=config_version,
+ routing_fingerprint=compute_routing_fingerprint(context),
+ candidates=candidates,
+ destination_candidates=destination_candidates,
+ evidence=[item for ev in alias_evidence.values() for item in ev],
+ reason="matched_multiple_sources",
+ )
+ return InventorySourceAdjudication(
+ status="unresolved",
+ config_version=config_version,
+ routing_fingerprint=compute_routing_fingerprint(context),
+ candidates=_all_enabled_source_candidates(),
+ destination_candidates=destination_candidates,
+ reason="no_route_rule_matched",
+ )
+
+ scored.sort(key=lambda item: (-item[0], str(item[1].get("source_code") or "")))
+ top_score = scored[0][0]
+ top_matches = [item for item in scored if item[0] == top_score]
+
+ if len(top_matches) == 1:
+ _, source, evidence = top_matches[0]
+ method = "rule_combined" if len(evidence) > 1 else "rule_exact"
+ return _stable_from_source(source, method=method, evidence=evidence, context=context)
+
+ conflicts = _detect_rule_conflicts(top_matches, context)
+ if conflicts:
+ candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches]
+ return InventorySourceAdjudication(
+ status="conflicted",
+ config_version=config_version,
+ routing_fingerprint=compute_routing_fingerprint(context),
+ candidates=candidates,
+ destination_candidates=destination_candidates,
+ evidence=[ev for _, _, ev in top_matches for ev in ev],
+ conflicts=conflicts,
+ reason="matched_conflicting_rules",
+ )
+
+ candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches]
+ return InventorySourceAdjudication(
+ status="ambiguous",
+ config_version=config_version,
+ routing_fingerprint=compute_routing_fingerprint(context),
+ candidates=candidates,
+ destination_candidates=destination_candidates,
+ evidence=[ev for _, _, ev in top_matches for ev in ev],
+ reason="matched_multiple_sources",
+ )
+
+
+def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> InventorySourceAdjudication:
+ """
+ 用户只提交 source_code;站点与库位从配置生成。用户最终选择优先于自动裁决。
+ 【AI 触发时机】:用户在 inventory_source_review 检查点选择正式库存源后调用。
+ """
+ context = extract_routing_context(task)
+ destination_candidates = context.get("destination_candidates") or []
+ code = str(source_code or "").strip().upper()
+ source = get_inventory_source(code)
+ if not source or source.get("enabled", True) is False:
+ return InventorySourceAdjudication(
+ status="invalid",
+ config_version=get_inventory_sources_config_version(),
+ routing_fingerprint=compute_routing_fingerprint(context),
+ candidates=_all_enabled_source_candidates(),
+ destination_candidates=destination_candidates,
+ conflicts=["source_code_not_found"],
+ reason="source_code_not_found",
+ )
+ if str(source.get("source_type") or "").strip() == "dsv360" and (
+ not str(source.get("site_id") or "").strip() or not str(source.get("warehouse_id") or "").strip()
+ ):
+ return InventorySourceAdjudication(
+ status="invalid",
+ config_version=get_inventory_sources_config_version(),
+ routing_fingerprint=compute_routing_fingerprint(context),
+ candidates=[_candidate_summary(source)],
+ destination_candidates=destination_candidates,
+ conflicts=["identity_incomplete_in_config"],
+ reason="identity_incomplete_in_config",
+ )
+
+ resolution = resolve_inventory_source_identity(source, context)
+ if not resolution.ok or not resolution.identity:
+ status = "ambiguous" if resolution.reason == "crane_warehouse_ambiguous" else "invalid"
+ return InventorySourceAdjudication(
+ status=status,
+ config_version=get_inventory_sources_config_version(),
+ routing_fingerprint=compute_routing_fingerprint(context),
+ candidates=[_candidate_summary(source)],
+ destination_candidates=destination_candidates,
+ conflicts=[resolution.reason] if resolution.reason else [],
+ reason=resolution.reason or "identity_incomplete",
+ )
+
+ identity = resolution.identity
+ return InventorySourceAdjudication(
+ status="user_confirmed",
+ method="user_confirmed",
+ source_code=identity.source_code,
+ source_type=identity.source_type,
+ site_id=identity.site_id,
+ warehouse_id=identity.warehouse_id,
+ config_version=get_inventory_sources_config_version(),
+ routing_fingerprint=compute_routing_fingerprint(context),
+ candidates=[_candidate_summary(source, matched_by="user_confirmed")],
+ destination_candidates=destination_candidates,
+ evidence=[{"field": "user_selection", "value": code}],
+ )
+
+
+# Backward-compatible wrappers
+def resolve_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
+ """兼容旧调用点:委托 adjudicate_inventory_source。"""
+ return adjudicate_inventory_source(task)
+
+
def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None:
- """读取任务当前已确认的 rpa_inventory_source。"""
- payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
- source = payload.get("rpa_inventory_source")
- return source if isinstance(source, dict) and source.get("source_code") else None
+ """读取任务当前运行时 RPA source(静态配置 + 任务动态库位)。"""
+ from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
+
+ return build_task_rpa_inventory_source(task)
def save_task_rpa_inventory_source(
task: ShippingTask,
source: dict[str, Any],
*,
- resolution: InventorySourceResolution | None = None,
+ resolution: InventorySourceAdjudication | None = None,
) -> None:
- """把已确认库存源写入 task.step_payload_json,供后续 RPA trigger 使用。"""
- payload = dict(task.step_payload_json or {})
- payload["rpa_inventory_source"] = source
+ """把已确认库存源写入独立字段与 step_payload_json。"""
+ from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
+
if resolution:
- payload["inventory_source_resolution"] = {
- "status": resolution.status,
- "destination_candidates": resolution.destination_candidates,
- "reason": resolution.reason,
- }
- task.step_payload_json = payload
+ apply_inventory_source_adjudication(task, resolution)
+ return
+ code = str(source.get("source_code") or "").strip().upper()
+ cfg = get_inventory_source(code)
+ if not cfg:
+ return
+ context = extract_routing_context(task)
+ resolution = resolve_inventory_source_identity(cfg, context)
+ if not resolution.ok or not resolution.identity:
+ return
+ identity = resolution.identity
+ adjudication = InventorySourceAdjudication(
+ status="user_confirmed",
+ method="user_confirmed",
+ source_code=identity.source_code,
+ source_type=identity.source_type,
+ site_id=identity.site_id,
+ warehouse_id=identity.warehouse_id,
+ config_version=get_inventory_sources_config_version(),
+ routing_fingerprint=compute_routing_fingerprint(context),
+ )
+ apply_inventory_source_adjudication(task, adjudication)
-def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceResolution) -> None:
- """库存源无法唯一命中时,把候选项写入 task.step_payload_json 供前端/Agent 展示。"""
- payload = dict(task.step_payload_json or {})
- payload["inventory_source_resolution"] = {
- "status": resolution.status,
- "destination_candidates": resolution.destination_candidates,
- "reason": resolution.reason,
- "candidates": resolution.candidates,
- }
- task.step_payload_json = payload
+def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceAdjudication) -> None:
+ """库存源无法唯一命中时写入候选项;委托 apply_inventory_source_adjudication。"""
+ from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
+
+ apply_inventory_source_adjudication(task, resolution)
diff --git a/backend/app/services/shipping_notice/inventory_sources.py b/backend/app/services/shipping_notice/inventory_sources.py
index 00536f6e..15a5297f 100644
--- a/backend/app/services/shipping_notice/inventory_sources.py
+++ b/backend/app/services/shipping_notice/inventory_sources.py
@@ -22,6 +22,49 @@ _VALID_SOURCE_TYPES = {
}
_VALID_PARAMETER_MODES = frozenset({"single", "multi_text", "multi_select"})
_CONFIG_CACHE: dict[str, Any] | None = None
+_CONFIG_PATH: str | None = None
+_CONFIG_RAW_DIGEST: str | None = None
+
+
+def _canonical_source_for_digest(source: dict[str, Any]) -> dict[str, Any]:
+ """提取参与版本哈希的语义字段,忽略注释/空白等文件层噪声。"""
+ match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
+ return {
+ "source_code": source.get("source_code"),
+ "source_type": source.get("source_type"),
+ "site_id": source.get("site_id"),
+ "warehouse_id": source.get("warehouse_id"),
+ "warehouse_resolution": source.get("warehouse_resolution"),
+ "enabled": source.get("enabled", True),
+ "priority": source.get("priority", 0),
+ "entry_url": source.get("entry_url"),
+ "display_name": source.get("display_name"),
+ "match_aliases": sorted(source.get("match_aliases") or []),
+ "allowed_warehouse_ids": sorted(source.get("allowed_warehouse_ids") or []),
+ "match": {
+ key: sorted(value) if isinstance(value, list) else value
+ for key, value in sorted(match_cfg.items())
+ },
+ "navigation": source.get("navigation"),
+ "parameters": source.get("parameters"),
+ "export": source.get("export"),
+ }
+
+
+def _normalized_config_digest(sources: dict[str, dict[str, Any]]) -> str:
+ """基于规范化结构计算配置内容哈希。"""
+ import hashlib
+
+ canonical = [_canonical_source_for_digest(sources[code]) for code in sorted(sources)]
+ payload = json.dumps(canonical, sort_keys=True, ensure_ascii=False)
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
+
+
+def _config_content_version(payload: dict[str, Any], sources: dict[str, dict[str, Any]]) -> str:
+ """配置版本 = 声明版本 + 规范化结构哈希。"""
+ digest = _normalized_config_digest(sources)
+ declared = str(payload.get("version") or "1").strip()
+ return f"{declared}-{digest}"
class InventorySourceConfigError(ValueError):
@@ -131,6 +174,11 @@ def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]:
return query
+def effective_warehouse_id(source: dict[str, Any]) -> str:
+ """返回配置中显式声明的 warehouse_id;禁止用 site_id 回填。"""
+ return str(source.get("warehouse_id") or "").strip().upper()
+
+
def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, Any]:
"""校验并规范化单条库存源配置。"""
source_code = str(raw.get("source_code") or "").strip().upper()
@@ -146,8 +194,31 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
site_id = str(raw.get("site_id") or "").strip().upper()
- if source_type == "dsv360" and not site_id:
- raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
+ if source_type == "dsv360":
+ if not site_id:
+ raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
+ if not warehouse_id:
+ raise InventorySourceConfigError(f"{source_code}: warehouse_id is required for dsv360")
+ elif source_type == "crane_footprint":
+ if not site_id:
+ raise InventorySourceConfigError(f"{source_code}: site_id is required for crane_footprint")
+ aliases = [str(alias).strip() for alias in (raw.get("match_aliases") or []) if str(alias).strip()]
+ if not aliases:
+ raise InventorySourceConfigError(f"{source_code}: match_aliases is required for crane_footprint")
+ allowed_warehouse_ids = [
+ str(item).strip()
+ for item in (raw.get("allowed_warehouse_ids") or [])
+ if str(item).strip()
+ ]
+ if not allowed_warehouse_ids:
+ raise InventorySourceConfigError(
+ f"{source_code}: allowed_warehouse_ids is required for crane_footprint"
+ )
+ warehouse_resolution = str(raw.get("warehouse_resolution") or "alias_match").strip().lower()
+ if warehouse_resolution != "alias_match":
+ raise InventorySourceConfigError(
+ f"{source_code}: warehouse_resolution must be alias_match for crane_footprint"
+ )
parameters: list[dict[str, Any]] = []
for item in raw.get("parameters") or []:
if not isinstance(item, dict):
@@ -167,6 +238,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
"site_id": site_id,
"display_name": str(raw.get("display_name") or source_code).strip(),
"enabled": bool(raw.get("enabled", True)),
+ "priority": int(raw.get("priority") or 0),
"entry_url": str(raw.get("entry_url") or "").strip(),
"warehouse_id": warehouse_id,
"navigation": dict(raw.get("navigation") or {}),
@@ -177,6 +249,18 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
if str(alias).strip()
],
}
+ if source_type == "crane_footprint":
+ normalized["warehouse_resolution"] = str(raw.get("warehouse_resolution") or "alias_match").strip().lower()
+ normalized["allowed_warehouse_ids"] = allowed_warehouse_ids
+ match_cfg = raw.get("match")
+ if isinstance(match_cfg, dict) and match_cfg:
+ normalized["match"] = {
+ "destination_codes": [str(v).strip() for v in (match_cfg.get("destination_codes") or []) if str(v).strip()],
+ "customers": [str(v).strip() for v in (match_cfg.get("customers") or []) if str(v).strip()],
+ "order_types": [str(v).strip() for v in (match_cfg.get("order_types") or []) if str(v).strip()],
+ "warehouse_hints": [str(v).strip() for v in (match_cfg.get("warehouse_hints") or []) if str(v).strip()],
+ "aliases": [str(v).strip() for v in (match_cfg.get("aliases") or []) if str(v).strip()],
+ }
if source_type == "crane_footprint" and raw.get("export"):
normalized["export"] = dict(raw.get("export") or {})
normalized["query"] = _build_legacy_query(normalized)
@@ -184,15 +268,24 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
- """加载并缓存 YAML/JSON 配置;force_reload 用于测试。"""
- global _CONFIG_CACHE
- if _CONFIG_CACHE is not None and not force_reload:
- return _CONFIG_CACHE
+ """加载并缓存 YAML/JSON 配置;路径或文件内容变化时刷新(不依赖 mtime 单独命中)。"""
+ import hashlib
+ global _CONFIG_CACHE, _CONFIG_PATH, _CONFIG_RAW_DIGEST
path = _config_path()
if not path.is_file():
raise InventorySourceConfigError(f"inventory sources config not found: {path}")
+ path_str = str(path.resolve())
+ raw_digest = hashlib.sha256(path.read_bytes()).hexdigest()[:16]
+ if (
+ _CONFIG_CACHE is not None
+ and not force_reload
+ and _CONFIG_PATH == path_str
+ and _CONFIG_RAW_DIGEST == raw_digest
+ ):
+ return _CONFIG_CACHE
+
payload = _parse_config_payload(path)
sources_raw = payload.get("sources")
if not isinstance(sources_raw, list):
@@ -207,13 +300,21 @@ def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
sources[normalized["source_code"]] = normalized
_CONFIG_CACHE = {
- "version": int(payload.get("version") or 1),
+ "version": _config_content_version(payload, sources),
"sources": sources,
- "path": str(path),
+ "path": path_str,
+ "raw_digest": raw_digest,
}
+ _CONFIG_PATH = path_str
+ _CONFIG_RAW_DIGEST = raw_digest
return _CONFIG_CACHE
+def get_inventory_sources_config_version() -> str:
+ """返回当前加载的库存源配置版本字符串。"""
+ return str(_load_config().get("version") or "1")
+
+
def reload_inventory_sources_config() -> dict[str, Any]:
"""强制重新加载库存源配置(管理/测试用)。"""
return _load_config(force_reload=True)
@@ -230,6 +331,44 @@ def get_inventory_source(source_code: str | None) -> dict[str, Any] | None:
return deepcopy(source)
+def source_uses_dynamic_warehouse_id(source: dict[str, Any] | None) -> bool:
+ """判断库存源是否采用运行时动态库位(如 CRANE alias_match)。"""
+ if not source:
+ return False
+ if str(source.get("warehouse_id") or "").strip():
+ return False
+ resolution = str(source.get("warehouse_resolution") or "").strip().lower()
+ return resolution in {"alias_match", "dynamic", "runtime"}
+
+
+def configured_warehouse_aliases(source: dict[str, Any] | None) -> set[str]:
+ """返回配置中的路由匹配别名集合(大写),供订单目的地裁决使用。"""
+ if not source:
+ return set()
+ return {
+ str(alias).strip().upper()
+ for alias in (source.get("match_aliases") or [])
+ if str(alias).strip()
+ }
+
+
+def configured_allowed_warehouse_ids(source: dict[str, Any] | None) -> set[str]:
+ """
+ 返回 Worker 回调允许落库的库位 ID 集合(大写)。
+ 核心逻辑:优先读 allowed_warehouse_ids;静态源回退 warehouse_id;与 match_aliases 解耦。
+ """
+ if not source:
+ return set()
+ allowed = source.get("allowed_warehouse_ids")
+ if allowed:
+ return {str(item).strip().upper() for item in allowed if str(item).strip()}
+ # fallback for static DSV 等源
+ warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
+ if warehouse_id:
+ return {warehouse_id}
+ return set()
+
+
def list_inventory_sources(*, enabled_only: bool = True) -> list[dict[str, Any]]:
"""返回库存源配置副本,供人工检查点展示候选项。"""
sources = _load_config()["sources"].values()
@@ -242,6 +381,8 @@ def build_rpa_inventory_source(
source_code: str | None,
*,
query_override: dict[str, Any] | None = None,
+ site_id: str | None = None,
+ warehouse_id: str | None = None,
) -> dict[str, Any] | None:
"""
构造 RPA trigger 使用的 rpa_inventory_source。
@@ -256,4 +397,59 @@ def build_rpa_inventory_source(
if value is not None and str(value).strip():
query[key] = value
source["query"] = query
- return source
+ return merge_runtime_inventory_identity(source, site_id=site_id, warehouse_id=warehouse_id)
+
+
+def merge_runtime_inventory_identity(
+ source: dict[str, Any],
+ *,
+ site_id: str | None = None,
+ warehouse_id: str | None = None,
+) -> dict[str, Any]:
+ """
+ 将任务已解析的 site/warehouse 合并进 RPA source,并同步 query.warehouse_code。
+ 核心逻辑:Crane 动态库位、DSV 子仓均通过本函数进入 trigger/回调/快照复用。
+ """
+ merged = deepcopy(source)
+ site = str(site_id or merged.get("site_id") or "").strip().upper()
+ warehouse = str(warehouse_id or merged.get("warehouse_id") or "").strip().upper()
+ if site:
+ merged["site_id"] = site
+ if warehouse:
+ merged["warehouse_id"] = warehouse
+ merged["_runtime_identity_applied"] = True
+ query = dict(merged.get("query") or {})
+ query["warehouse_code"] = warehouse
+ merged["query"] = query
+ source_type = str(merged.get("source_type") or "").strip()
+ if source_type == "crane_footprint":
+ navigation = dict(merged.get("navigation") or {})
+ navigation["project_code"] = warehouse
+ merged["navigation"] = navigation
+ query["project_code"] = warehouse
+ merged["query"] = query
+ return merged
+
+
+def build_task_rpa_inventory_source(task: "ShippingTask") -> dict[str, Any] | None:
+ """
+ 基于任务正式库存身份构造运行时 RPA source(配置 + 动态库位)。
+ 【AI 触发时机】:ensure_inventory_via_rpa、RPA 回调、快照复用统一调用。
+ """
+ from app.models import ShippingTask
+
+ if not isinstance(task, ShippingTask):
+ return None
+ payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
+ code = str(task.inventory_source_code or "").strip().upper()
+ site_id = str(task.inventory_site_id or "").strip().upper() or None
+ warehouse_id = str(task.inventory_warehouse_id or "").strip().upper() or None
+ if not code:
+ legacy = payload.get("rpa_inventory_source")
+ if isinstance(legacy, dict) and legacy.get("source_code"):
+ return merge_runtime_inventory_identity(legacy, site_id=site_id, warehouse_id=warehouse_id)
+ return None
+ base = get_inventory_source(code)
+ if not base:
+ return None
+ return merge_runtime_inventory_identity(base, site_id=site_id, warehouse_id=warehouse_id)
diff --git a/backend/app/services/shipping_notice/inventory_upload.py b/backend/app/services/shipping_notice/inventory_upload.py
index 2bdf912e..d875d93a 100644
--- a/backend/app/services/shipping_notice/inventory_upload.py
+++ b/backend/app/services/shipping_notice/inventory_upload.py
@@ -3,25 +3,199 @@ services/shipping_notice/inventory_upload.py
用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。
依赖:inventory_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。
-逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息。
+逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息;
+ 正式附件使用版本化文件名 + .current_inventory 原子指针,避免多格式并存或崩溃后误读旧文件。
"""
from __future__ import annotations
+import hashlib
import re
import shutil
+from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
from werkzeug.datastructures import FileStorage
+from app.models import ShippingInventoryFile, ShippingTask
from app.services.shipping_notice.export import _storage_root
+from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
read_inventory_schema_preview,
)
+_TASK_INVENTORY_SUFFIXES = (".xlsx", ".csv")
+_TASK_INVENTORY_MARKER = ".current_inventory"
+_TASK_INVENTORY_VERSION_PREFIX = "inventory_"
+
+
+def _inventory_file_sha256(path: Path) -> str:
+ """计算库存附件 SHA256,用于幂等安装判断。"""
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _task_inventory_attachment_marker_path(task_no: str) -> Path:
+ """任务当前正式库存附件指针文件路径。"""
+ return _task_inventory_upload_dir(task_no) / _TASK_INVENTORY_MARKER
+
+
+def _atomic_write_task_inventory_marker(task_no: str, attachment_filename: str) -> None:
+ """通过临时文件 + os.replace 原子切换 .current_inventory 指针。"""
+ import os
+
+ marker = _task_inventory_attachment_marker_path(task_no)
+ tmp = marker.with_name(f"{marker.name}.tmp")
+ marker.parent.mkdir(parents=True, exist_ok=True)
+ tmp.write_text(attachment_filename, encoding="utf-8")
+ os.replace(tmp, marker)
+
+
+def _read_task_inventory_attachment_marker(task_no: str) -> Path | None:
+ """读取指针文件并校验对应附件仍存在。"""
+ marker = _task_inventory_attachment_marker_path(task_no)
+ if not marker.is_file():
+ return None
+ name = marker.read_text(encoding="utf-8").strip()
+ if not name:
+ return None
+ path = _task_inventory_upload_dir(task_no) / name
+ if path.is_file() and _is_task_inventory_attachment_name(path.name):
+ return path
+ return None
+
+
+def _is_task_inventory_attachment_name(name: str) -> bool:
+ """判断文件名是否为合法任务库存附件。"""
+ lowered = str(name or "").lower()
+ if not lowered.startswith("inventory"):
+ return False
+ return any(lowered.endswith(suffix) for suffix in _TASK_INVENTORY_SUFFIXES)
+
+
+def _versioned_task_inventory_path(task_no: str, suffix: str) -> Path:
+ """生成不可变版本化任务库存附件路径。"""
+ token = datetime.utcnow().strftime("%Y%m%d%H%M%S%f")
+ normalized = suffix if suffix in _TASK_INVENTORY_SUFFIXES else ".xlsx"
+ return _task_inventory_upload_dir(task_no) / f"{_TASK_INVENTORY_VERSION_PREFIX}{token}{normalized}"
+
+
+def _list_task_inventory_attachment_candidates(task_no: str) -> list[Path]:
+ """列出任务目录下全部库存附件候选文件。"""
+ base = _task_inventory_upload_dir(task_no)
+ if not base.is_dir():
+ return []
+ return [
+ path
+ for path in base.iterdir()
+ if path.is_file() and _is_task_inventory_attachment_name(path.name)
+ ]
+
+
+def _cleanup_superseded_task_inventory_files(task_no: str, *, keep_name: str) -> list[str]:
+ """
+ 指针切换后清理旧版附件(best effort)。
+ Returns:
+ 未能删除的文件名列表。
+ """
+ warnings: list[str] = []
+ for path in _list_task_inventory_attachment_candidates(task_no):
+ if path.name == keep_name:
+ continue
+ try:
+ path.unlink()
+ except OSError as exc:
+ warnings.append(f"{path.name}:{str(exc)[:80]}")
+ return warnings
+
+
+def install_task_inventory_attachment_from_file(
+ task_no: str,
+ source_path: str | Path,
+ *,
+ source_file_name: str | None = None,
+) -> Path:
+ """
+ 将源库存文件安装为任务正式附件(版本化文件名 + 原子 marker 切换)。
+ 【AI 触发时机】:RPA 回调晋升失败补偿、人工修复任务附件时调用;不依赖重新消费 callback。
+
+ 核心逻辑:复制到 inventory_{timestamp}{suffix} → 原子切换 .current_inventory → 清理旧附件。
+ 若当前正式附件与源文件内容一致则幂等返回现有路径。
+
+ Args:
+ task_no: 发货任务号。
+ source_path: 源库存文件(通常为 inv_file.storage_path 或 staging)。
+ source_file_name: 可选展示名,仅用于日志语义。
+
+ Returns:
+ 安装后的正式附件路径。
+
+ Raises:
+ FileNotFoundError: 源文件不存在。
+ OSError: 复制或 marker 切换失败。
+ """
+ source = Path(source_path)
+ if not source.is_file():
+ raise FileNotFoundError(f"未找到库存源文件: {source}")
+
+ current = resolve_task_inventory_upload_path(task_no)
+ if current is not None and _inventory_file_sha256(current) == _inventory_file_sha256(source):
+ return current
+
+ suffix = inventory_storage_suffix_for_path(source)
+ versioned = _versioned_task_inventory_path(task_no, suffix)
+ versioned.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, versioned)
+ try:
+ _atomic_write_task_inventory_marker(task_no, versioned.name)
+ _cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name)
+ except Exception:
+ if versioned.is_file():
+ try:
+ versioned.unlink()
+ except OSError:
+ pass
+ raise
+ if source_file_name:
+ _ = source_file_name
+ return versioned
+
+
+def rebuild_task_inventory_attachment_from_snapshot(
+ task: ShippingTask | str,
+ inv_file: ShippingInventoryFile,
+) -> Path:
+ """
+ 从已提交库存快照 storage_path 幂等重建任务正式附件。
+ 【AI 触发时机】:RPA 回调 DB 已提交但任务附件晋升失败,或运维人工补偿时调用。
+
+ Args:
+ task: 任务对象或 task_no。
+ inv_file: 已链接的库存快照。
+
+ Returns:
+ 重建后的任务正式附件路径。
+ """
+ task_no = task.task_no if isinstance(task, ShippingTask) else str(task or "").strip()
+ if not task_no:
+ raise ValueError("task_no is required")
+ storage_path = Path(str(inv_file.storage_path or ""))
+ if not storage_path.is_file() or str(inv_file.storage_path or "").startswith("failed://"):
+ raise FileNotFoundError(
+ f"库存快照托管文件不存在: {inv_file.inventory_file_no}",
+ )
+ return install_task_inventory_attachment_from_file(
+ task_no,
+ storage_path,
+ source_file_name=str(inv_file.source_file_name or storage_path.name),
+ )
+
def inventory_text_max_chars() -> int:
"""库存粘贴文本最大字符数(SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS,默认 80000)。"""
@@ -31,18 +205,72 @@ def inventory_text_max_chars() -> int:
return 80000
-def task_inventory_upload_path(task_no: str) -> Path:
- """任务级库存 Excel 标准落盘路径(inventory_uploads/{task_no}/inventory.xlsx)。"""
- safe = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
- return _storage_root() / "inventory_uploads" / safe / "inventory.xlsx"
+def _task_inventory_upload_dir(task_no: str) -> Path:
+ """任务级库存附件目录(inventory_uploads/{task_no})。"""
+ safe = _sanitize_task_no(task_no)
+ return _storage_root() / "inventory_uploads" / safe
+
+
+def task_inventory_upload_path(task_no: str, *, suffix: str | None = None) -> Path:
+ """
+ 任务级库存附件标准落盘路径(默认 inventory.xlsx)。
+ suffix 仅允许 .xlsx / .csv,用于 RPA 回调保留源文件格式。
+ """
+ normalized = (suffix or ".xlsx").lower()
+ if normalized not in _TASK_INVENTORY_SUFFIXES:
+ normalized = ".xlsx"
+ return _task_inventory_upload_dir(task_no) / f"inventory{normalized}"
+
+
+def _recover_and_repair_task_inventory_marker(task_no: str) -> Path | None:
+ """
+ marker 缺失或损坏时扫描附件目录并修复 .current_inventory。
+ 核心逻辑:仅在此路径下根据 mtime 选择候选;修复后返回已提交附件。
+ """
+ candidates = _list_task_inventory_attachment_candidates(task_no)
+ if not candidates:
+ return None
+ versioned = [
+ path
+ for path in candidates
+ if path.name.startswith(_TASK_INVENTORY_VERSION_PREFIX)
+ ]
+ if versioned:
+ chosen = max(versioned, key=lambda item: item.stat().st_mtime)
+ elif len(candidates) == 1:
+ chosen = candidates[0]
+ else:
+ chosen = max(candidates, key=lambda item: item.stat().st_mtime)
+ _atomic_write_task_inventory_marker(task_no, chosen.name)
+ return chosen
+
+
+def resolve_task_inventory_upload_path(task_no: str) -> Path | None:
+ """
+ 返回任务当前已提交的正式库存附件路径。
+ 核心逻辑:marker 有效且目标文件存在时必须无条件相信 marker;
+ 仅 marker 缺失或损坏时才执行恢复扫描并同步修复 marker。
+ """
+ marked = _read_task_inventory_attachment_marker(task_no)
+ if marked is not None:
+ return marked
+ return _recover_and_repair_task_inventory_marker(task_no)
def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
"""保存 werkzeug FileStorage 库存上传并返回落盘路径。"""
- path = task_inventory_upload_path(task_no)
- path.parent.mkdir(parents=True, exist_ok=True)
- upload.save(str(path))
- return path
+ suffix = ".xlsx"
+ filename = str(getattr(upload, "filename", "") or "").lower()
+ if filename.endswith(".csv"):
+ suffix = ".csv"
+ staging_dir = _task_inventory_upload_dir(task_no) / ".staging"
+ staging_dir.mkdir(parents=True, exist_ok=True)
+ staging = staging_dir / f"manual_upload_{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}{suffix}"
+ upload.save(str(staging))
+ try:
+ return install_task_inventory_attachment_from_file(task_no, staging)
+ finally:
+ delete_staged_task_inventory_file(staging)
def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Path:
@@ -66,16 +294,111 @@ def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Pat
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
- path = task_inventory_upload_path(task_no)
- path.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(source, path)
- return path
+ return install_task_inventory_attachment_from_file(
+ task_no,
+ source,
+ source_file_name=source.name,
+ )
+
+
+def _sanitize_task_no(task_no: str) -> str:
+ """将任务号规范为库存上传目录名。"""
+ return re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
+
+
+def stage_task_inventory_callback_file(
+ task_no: str,
+ source_path: str | Path,
+ *,
+ run_no: str | None = None,
+) -> Path:
+ """
+ 将 RPA 回调文件复制到本轮唯一 staging 路径,避免在校验前覆盖任务正式附件。
+ 核心逻辑:落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}.xlsx。
+
+ Args:
+ task_no: 发货任务号。
+ source_path: Worker 回调提供的本地库存文件。
+ run_no: 可选轮次号,用于生成稳定且唯一的 staging 文件名。
+
+ Returns:
+ Path: staging 文件路径。
+
+ Raises:
+ FileNotFoundError: 源文件不存在。
+ """
+ source = Path(source_path)
+ if not source.is_file():
+ raise FileNotFoundError(f"未找到库存源文件: {source}")
+ token = re.sub(
+ r"[^\w\-]+",
+ "_",
+ str(run_no or "").strip() or datetime.utcnow().strftime("%Y%m%d%H%M%S%f"),
+ )
+ suffix = source.suffix.lower() if source.suffix else ".xlsx"
+ staging_dir = _storage_root() / "inventory_uploads" / _sanitize_task_no(task_no) / ".staging"
+ staging_dir.mkdir(parents=True, exist_ok=True)
+ staging_path = staging_dir / f"rpa_callback_{token}{suffix}"
+ shutil.copy2(source, staging_path)
+ return staging_path
+
+
+def promote_staged_task_inventory_file(task_no: str, staging_path: str | Path) -> Path:
+ """
+ 校验与数据库提交成功后,将 staging 安装为任务正式库存附件。
+ 核心逻辑:版本化落盘 + 原子 marker 切换 + 异步清理旧附件;旧附件删除失败返回 warning 列表。
+ """
+ import os
+
+ staging = Path(staging_path)
+ if not staging.is_file():
+ raise FileNotFoundError(f"未找到 staging 库存文件: {staging}")
+ suffix = staging.suffix.lower() if staging.suffix else ".xlsx"
+ if suffix not in _TASK_INVENTORY_SUFFIXES:
+ suffix = ".xlsx"
+ versioned = _versioned_task_inventory_path(task_no, suffix)
+ versioned.parent.mkdir(parents=True, exist_ok=True)
+ os.replace(staging, versioned)
+ try:
+ _atomic_write_task_inventory_marker(task_no, versioned.name)
+ cleanup_warnings = _cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name)
+ if cleanup_warnings:
+ raise OSError(f"legacy_attachment_cleanup_failed:{';'.join(cleanup_warnings)[:200]}")
+ except Exception:
+ if versioned.is_file():
+ try:
+ versioned.unlink()
+ except OSError:
+ pass
+ raise
+ try:
+ staging.parent.rmdir()
+ except OSError:
+ pass
+ return versioned
+
+
+def delete_staged_task_inventory_file(staging_path: str | Path | None) -> None:
+ """删除本轮 staging 库存文件(失败回滚用,不触碰任务正式附件)。"""
+ if not staging_path:
+ return
+ path = Path(staging_path)
+ if not path.is_file():
+ return
+ try:
+ path.unlink()
+ except OSError:
+ return
+ try:
+ path.parent.rmdir()
+ except OSError:
+ pass
def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]:
"""读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。"""
- path = task_inventory_upload_path(task_no)
- if not path.is_file():
+ path = resolve_task_inventory_upload_path(task_no)
+ if path is None:
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = path.name
@@ -97,8 +420,8 @@ def parse_uploaded_task_inventory(
Returns:
tuple: (inventory_lines, column_meta, 文件路径)。
"""
- path = task_inventory_upload_path(task_no)
- if not path.is_file():
+ path = resolve_task_inventory_upload_path(task_no)
+ if path is None:
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
lines, column_meta = parse_inventory_excel_with_meta(
path,
@@ -112,5 +435,5 @@ def parse_uploaded_task_inventory(
def has_uploaded_task_inventory(task_no: str) -> bool:
- """任务是否已有落盘的库存 Excel 文件。"""
- return task_inventory_upload_path(task_no).is_file()
+ """任务是否已有落盘的库存附件(.xlsx 或 .csv)。"""
+ return resolve_task_inventory_upload_path(task_no) is not None
diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py
index 0ce6e12e..207ea47e 100644
--- a/backend/app/services/shipping_notice/inventory_workflow.py
+++ b/backend/app/services/shipping_notice/inventory_workflow.py
@@ -12,9 +12,11 @@ import json
from typing import Any
from app import db
+from app.core.errors import AppError
from app.models import ShippingTask
from app.services.shipping_notice.constants import (
AUTO_MAP,
+ CP_INVENTORY_SOURCE_REVIEW,
CP_MAP_INFER,
CP_UPLOAD_REQ,
SUGGEST_OK,
@@ -57,6 +59,8 @@ from app.services.shipping_notice.query_service import (
serialize_task_for_tool,
)
from app.services.shipping_notice.i18n import resolve_lang, t
+from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
+from app.services.shipping_notice.state_machine import resolve_task_ui_state
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
from app.services.shipping_notice.tool_response import tool_response
@@ -117,6 +121,29 @@ def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
return result
+def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang: str) -> dict[str, Any] | None:
+ """
+ 库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
+ 核心逻辑:仅捕获预期 AppError,其它异常继续向上抛出。
+ """
+ if is_inventory_source_stable(task):
+ return None
+ try:
+ assert_inventory_source_gate(task, operation=operation)
+ except AppError:
+ ui = resolve_task_ui_state(task)
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
+ data=serialize_task_for_tool(task),
+ human_options=ui.human_options,
+ checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
+ stop_agent_turn=True,
+ )
+ return None
+
+
def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""Parse inventory from uploaded file, chat text, or structured JSON."""
lang = resolve_lang(payload)
@@ -124,6 +151,10 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
+ gate_resp = _inventory_source_gate_response(task, operation="parse_inventory", lang=lang)
+ if gate_resp is not None:
+ return gate_resp
+
# [STEP 1] 先归一化库存输入来源与映射提示。
# 同一个入口要兼容已上传文件、聊天粘贴文本、结构化 JSON 和 LLM 传入的 map_json 扩展字段。
use_uploaded = str(payload.get("use_uploaded_file") or "").strip().lower() in {
@@ -237,6 +268,10 @@ def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
+ gate_resp = _inventory_source_gate_response(task, operation="get_inventory_schema_preview", lang=lang)
+ if gate_resp is not None:
+ return gate_resp
+
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
return tool_response(
status="needs_human",
@@ -279,6 +314,10 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
+ gate_resp = _inventory_source_gate_response(task, operation="apply_inventory_mapping", lang=lang)
+ if gate_resp is not None:
+ return gate_resp
+
# [STEP 1] 先校验上传文件与 schema preview 是否存在。
# 映射应用必须基于真实上传文件的表头,不能只凭 LLM 文本猜测继续执行。
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
@@ -415,6 +454,9 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
lang = resolve_lang({"lang": None})
+ gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
+ if gate_resp is not None:
+ return gate_resp
if str(task.process_status or "").strip().lower() in _TERMINAL_PROCESS_STATUSES:
return tool_response(
status="failed",
@@ -432,7 +474,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
)
filename = str(upload.filename or "").strip()
- if not filename.lower().endswith((".xlsx", ".xls", ".csv")):
+ if not filename.lower().endswith((".xlsx", ".csv")):
return tool_response(
status="failed",
task_id=task.task_no,
@@ -452,7 +494,18 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
db.session.flush()
inv_file = save_batch_inventory_upload(task, upload)
preview = read_linked_inventory_schema_preview(task)
+ except AppError as exc:
+ db.session.rollback()
+ return tool_response(
+ status="failed",
+ task=task,
+ task_id=task.task_no,
+ message=str(exc.message or "库存上传被拒绝"),
+ data=serialize_task_for_tool(task),
+ stop_agent_turn=True,
+ )
except OSError as exc:
+ db.session.rollback()
return tool_response(
status="failed",
task_id=task.task_no,
@@ -537,6 +590,20 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
+ if not is_inventory_source_stable(task):
+ try:
+ assert_inventory_source_gate(task, operation="ensure_inventory")
+ except AppError:
+ pass
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
+ data=serialize_task_for_tool(task),
+ checkpoint="inventory_source_review",
+ stop_agent_turn=True,
+ )
+
# [STEP 1] 优先接受当前请求直接携带的库存明细。
# 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。
mode = str(payload.get("mode") or "auto").strip().lower()
diff --git a/backend/app/services/shipping_notice/notice_upload.py b/backend/app/services/shipping_notice/notice_upload.py
index 048f57e4..d077a708 100644
--- a/backend/app/services/shipping_notice/notice_upload.py
+++ b/backend/app/services/shipping_notice/notice_upload.py
@@ -2,19 +2,18 @@
services/shipping_notice/notice_upload.py
用途:管理发货通知附件上传、文本抽取、截断与统一接入结果模型。
-依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。
+依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、eml_parse、export._storage_root、Flask current_app 配置。
逻辑:workspace 单票建单、批量建单、重新上传三条入口均经 intake_notice_attachment / intake_temp_notice_uploads
- 收敛抽取与失败分流;下游 extract/task_workflow 只消费 NoticeIntakeResult。
+ 收敛抽取与失败分流;.eml 走结构化解析(正文/内嵌资源/真实附件);下游只消费 NoticeIntakeResult。
"""
from __future__ import annotations
import base64
+import hashlib
import re
import shutil
from dataclasses import dataclass, field
-from email import policy
-from email.parser import BytesParser
from pathlib import Path
from typing import Any, Literal, Sequence
@@ -23,6 +22,7 @@ from flask import current_app
from edkb_system.contracts import Block, Context
from edkb_system.skills import loader_csv, loader_docx, loader_pdf, ocr
from app.services.shipping_notice.export import _storage_root
+from app.services.shipping_notice.eml_parse import parse_eml_bytes
def task_notice_upload_path(task_no: str, filename: str) -> Path:
@@ -111,32 +111,6 @@ def _html_to_text(html: str) -> str:
return s.strip()
-def _eml_to_text(data: bytes) -> str:
- msg = BytesParser(policy=policy.default).parsebytes(data)
- parts: list[str] = []
- subject = str(msg.get("subject") or "").strip()
- if subject:
- parts.append(f"Subject: {subject}")
- if msg.is_multipart():
- for part in msg.walk():
- if part.is_multipart():
- continue
- ctype = str(part.get_content_type() or "")
- payload = part.get_payload(decode=True) or b""
- if ctype == "text/plain":
- parts.append(_decode_text(payload).strip())
- elif ctype == "text/html":
- parts.append(_html_to_text(_decode_text(payload)).strip())
- else:
- payload = msg.get_payload(decode=True) or b""
- ctype = str(msg.get_content_type() or "")
- if ctype == "text/html":
- parts.append(_html_to_text(_decode_text(payload)).strip())
- else:
- parts.append(_decode_text(payload).strip())
- return "\n\n".join(x for x in parts if x)
-
-
def _image_bytes_to_blocks(raw: bytes) -> list[Block]:
if not raw:
return []
@@ -171,12 +145,23 @@ def _blocks_to_text(blocks: list[Block]) -> str:
return text
-def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]:
+def extract_notice_text(
+ file_path: Path,
+ *,
+ retain_payloads: bool = False,
+) -> tuple[str, dict[str, Any]]:
"""
从发货通知附件抽取纯文本(PDF/DOCX/CSV/图片 OCR/EML/HTML 等)。
+ 核心逻辑:普通文件走 edkb loaders;.eml 委托 eml_parse 做结构化解析(元数据 + 真实附件独立抽取),
+ 内嵌 Logo/签名图不进入附件列表,也不参与订单文本拼接。
+
+ Args:
+ file_path: 已落盘的通知文件路径。
+ retain_payloads: 仅 EML;True 时保留 attachments[*]._payload_bytes 供 Intake 派生资产。
+
Returns:
- tuple[str, dict]: (抽取文本, meta 含 warnings 与 file_type)。
+ tuple[str, dict]: (抽取文本, meta 含 warnings、file_type;eml 另含 email/attachments/attachment_count)。
"""
path = Path(file_path)
ext = path.suffix.lower().lstrip(".")
@@ -188,7 +173,12 @@ def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]:
if ext in {"html", "htm"}:
return _html_to_text(_decode_text(path.read_bytes())), {"warnings": warnings, "file_type": ext}
if ext in {"eml"}:
- return _eml_to_text(path.read_bytes()), {"warnings": warnings, "file_type": ext}
+ # 叶附件递归抽取时复用本函数;eml_parse 通过嵌套深度上限防止 bom 炸弹式嵌套
+ return parse_eml_bytes(
+ path.read_bytes(),
+ extract_text=extract_notice_text,
+ retain_payloads=retain_payloads,
+ )
blocks: list[Block] = []
if ext in {"pdf"}:
@@ -249,6 +239,8 @@ class NoticeIntakeResult:
text: str
warnings: list[str] = field(default_factory=list)
meta: dict[str, Any] = field(default_factory=dict)
+ content_hash: str = ""
+ file_size: int = 0
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
saved_path: Path | None = None
@@ -263,6 +255,8 @@ class NoticeIntakeResult:
"source_type": self.source_type,
"source_file_name": self.filename,
"source_file_type": self.source_file_type,
+ "source_content_hash": self.content_hash,
+ "file_size": self.file_size,
"raw_text": self.text,
"warnings": list(self.warnings),
}
@@ -274,6 +268,8 @@ class NoticeIntakeResult:
"source_type": self.source_type,
"source_file_type": self.source_file_type,
"text_length": len(self.text),
+ "content_hash": self.content_hash,
+ "file_size": self.file_size,
"warnings": list(self.warnings),
}
@@ -349,6 +345,9 @@ def intake_notice_attachment(
"""
name = str(filename or "").strip() or "notice"
source_type = guess_source_type(name)
+ raw_bytes = raw or b""
+ content_hash = hashlib.sha256(raw_bytes).hexdigest().lower()
+ file_size = len(raw_bytes)
saved_path: Path | None = None
text = ""
meta: dict[str, Any] = {}
@@ -359,11 +358,11 @@ def intake_notice_attachment(
if storage == "task":
if not task_no:
raise ValueError("task_no is required for task storage")
- saved_path = save_task_notice_upload(task_no, name, raw or b"")
+ saved_path = save_task_notice_upload(task_no, name, raw_bytes)
else:
if not temp_request_id:
raise ValueError("temp_request_id is required for temp storage")
- saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw or b"")
+ saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw_bytes)
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
except Exception as exc:
@@ -376,6 +375,8 @@ def intake_notice_attachment(
text="",
warnings=warnings,
meta=meta if isinstance(meta, dict) else {},
+ content_hash=content_hash,
+ file_size=file_size,
status=status,
saved_path=saved_path,
)
@@ -388,6 +389,8 @@ def intake_notice_attachment(
text="",
warnings=warnings,
meta=meta if isinstance(meta, dict) else {},
+ content_hash=content_hash,
+ file_size=file_size,
status="empty_text",
saved_path=saved_path,
)
@@ -400,6 +403,8 @@ def intake_notice_attachment(
text=text,
warnings=warnings,
meta=meta if isinstance(meta, dict) else {},
+ content_hash=content_hash,
+ file_size=file_size,
status="accepted",
saved_path=saved_path,
)
@@ -408,23 +413,37 @@ def intake_notice_attachment(
def intake_temp_notice_uploads(
temp_request_id: str,
uploads: Sequence[Any],
-) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult]]:
+) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult], list[dict[str, Any]]]:
"""
- 批量建单入口:逐份附件接入并在 finally 外由调用方清理临时目录。
+ 批量建单入口:逐份附件接入、同请求内按内容哈希去重,并在 finally 外由调用方清理临时目录。
Args:
temp_request_id: 请求级临时目录 ID。
uploads: Flask request.files 中的上传对象序列。
Returns:
- tuple[list, list]: (accepted 结果列表, rejected 结果列表)。
+ tuple: (accepted 结果列表, rejected 结果列表, duplicate_files 摘要列表)。
"""
accepted: list[NoticeIntakeResult] = []
rejected: list[NoticeIntakeResult] = []
+ duplicate_files: list[dict[str, Any]] = []
+ seen_hashes: dict[str, str] = {}
for index, upload in enumerate(uploads, start=1):
raw = upload.read() or b""
+ content_hash = hashlib.sha256(raw).hexdigest().lower()
+ filename = str(upload.filename or "notice").strip() or "notice"
+ if content_hash in seen_hashes:
+ duplicate_files.append(
+ {
+ "filename": filename,
+ "duplicate_of": seen_hashes[content_hash],
+ "content_hash": content_hash,
+ }
+ )
+ continue
+ seen_hashes[content_hash] = filename
result = intake_notice_attachment(
- filename=upload.filename or "notice",
+ filename=filename,
raw=raw,
source_file_type=notice_source_file_type(upload),
storage="temp",
@@ -435,7 +454,7 @@ def intake_temp_notice_uploads(
accepted.append(result)
else:
rejected.append(result)
- return accepted, rejected
+ return accepted, rejected, duplicate_files
def build_notice_file_summary(
@@ -443,6 +462,7 @@ def build_notice_file_summary(
total_files: int,
accepted: Sequence[NoticeIntakeResult],
rejected: Sequence[NoticeIntakeResult],
+ duplicate_files: Sequence[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
构建批量上传预检摘要,供前端回显与测试断言。
@@ -451,16 +471,20 @@ def build_notice_file_summary(
total_files: 请求内附件总数。
accepted: 接入成功的结果列表。
rejected: 接入失败的结果列表。
+ duplicate_files: 同请求内内容重复、已跳过的文件摘要。
Returns:
- dict: total/accepted/rejected 计数与文件明细。
+ dict: total/accepted/rejected/duplicate 计数与文件明细。
"""
accepted_files = [item.to_accepted_file_summary() for item in accepted]
rejected_files = [item.to_rejected_file_summary() for item in rejected]
+ duplicates = [dict(item) for item in (duplicate_files or [])]
return {
"total_files": total_files,
"accepted_count": len(accepted_files),
"rejected_count": len(rejected_files),
+ "duplicate_count": len(duplicates),
"accepted_files": accepted_files,
"rejected_files": rejected_files,
+ "duplicate_files": duplicates,
}
diff --git a/backend/app/services/shipping_notice/openapi_spec.py b/backend/app/services/shipping_notice/openapi_spec.py
index 637534e2..625fdeb3 100644
--- a/backend/app/services/shipping_notice/openapi_spec.py
+++ b/backend/app/services/shipping_notice/openapi_spec.py
@@ -183,6 +183,24 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["task_id", MAP_JSON],
),
+ "/tools/confirm_inventory_source": _post_op(
+ "confirm_inventory_source",
+ "在库存源人工检查点确认正式库存查询来源(仅提交 source_code)",
+ {
+ "task_id": task_id,
+ "source_code": _str_prop(
+ "启用配置中的库存源编码,如 DSV360_AWSDU、CRANE;"
+ "站点 site_id 与库位 warehouse_id 由后端根据配置与订单路由解析,禁止前端直传"
+ ),
+ },
+ required=["task_id", "source_code"],
+ description=(
+ "库存源门禁:稳定身份须同时具备 source_code、source_type、site_id、warehouse_id,"
+ "且 routing_fingerprint 与当前配置版本一致。"
+ "Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。"
+ "若返回 needs_human,说明身份未完整解析或需先完成解析确认。"
+ ),
+ ),
"/tools/submit_decision": _post_op(
"submit_decision",
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
@@ -218,11 +236,19 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
),
"/tools/get_task_status": _post_op(
"get_task_status",
- "查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
+ "查询任务当前状态与 human_options;响应含 inventory_source_* 独立字段与候选结构",
{
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID"),
},
+ description=(
+ "返回 inventory_source_code、inventory_source_type、inventory_site_id、"
+ "inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
+ "user_confirmed|invalid|conflicted)、inventory_source_method、"
+ "inventory_source_config_version、inventory_routing_fingerprint、"
+ "inventory_source_confirmed_by、inventory_source_confirmed_at,"
+ "以及 step_payload.inventory_source_resolution.candidates。"
+ ),
),
"/tools/get_batch_status": _post_op(
"get_batch_status",
diff --git a/backend/app/services/shipping_notice/parse_summary.py b/backend/app/services/shipping_notice/parse_summary.py
index b58b48f8..fcb426df 100644
--- a/backend/app/services/shipping_notice/parse_summary.py
+++ b/backend/app/services/shipping_notice/parse_summary.py
@@ -4,6 +4,7 @@ services/shipping_notice/parse_summary.py
用途:把发货通知解析结果格式化成适合聊天区展示的摘要文本。
依赖:shipping_notice.i18n 中的语言解析与文案函数、订单行格式化辅助函数。
逻辑:由 task_workflow.parse_notice 在解析完成后调用本文件,向前端或 Agent 返回可直接展示的解析总结。
+ 库存源门禁路径不经本模块,由 parse_notice 直接拼接 issues 列表文案。
"""
from __future__ import annotations
diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py
index 2a2e5cf6..e62ae95a 100644
--- a/backend/app/services/shipping_notice/progress_workflow.py
+++ b/backend/app/services/shipping_notice/progress_workflow.py
@@ -14,7 +14,17 @@ from flask import current_app
from app.services.shipping_notice import fulfillment_workflow
from app import db
-from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_LOW_CONF, RS_PARSE_REVIEW
+from app.services.shipping_notice.constants import (
+ CP_INVENTORY_SOURCE_REVIEW,
+ CP_UPLOAD_REQ,
+ PH_INVENTORY_SOURCE_UNRESOLVED,
+ PH_LOW_CONF,
+ RS_PARSE_REVIEW,
+)
+from app.services.shipping_notice.inventory_source_gate import (
+ is_inventory_source_stable,
+ ensure_inventory_source_review_state,
+)
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_mapping_checkpoint_response,
@@ -84,6 +94,27 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
stop_agent_turn=True,
)
+ if task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task):
+ adjudication = ensure_inventory_source_review_state(task)
+ db.session.commit()
+ if not is_inventory_source_stable(task):
+ ui = resolve_task_ui_state(task)
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
+ data={
+ **serialize_task_for_tool(task),
+ "inventory_source_candidates": adjudication.candidates,
+ "inventory_source_status": adjudication.status,
+ "inventory_source_reason": adjudication.reason,
+ "destination_candidates": adjudication.destination_candidates,
+ },
+ human_options=ui.human_options,
+ checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
+ stop_agent_turn=True,
+ )
+
# [STEP 2] 保证库存已经就绪。
# 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。
if not task.inventory_lines_json:
diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py
index cd43178f..4a0b3f98 100644
--- a/backend/app/services/shipping_notice/query_service.py
+++ b/backend/app/services/shipping_notice/query_service.py
@@ -1,10 +1,11 @@
"""
services/shipping_notice/query_service.py
-用途:发货通知读模型 — 任务/批次查询、排序与序列化投影。
+用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。
依赖:models.ShippingBatch、ShippingTask、ShippingTaskEvent。
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
- tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉。
+ tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
+ SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*。
"""
from __future__ import annotations
@@ -293,6 +294,40 @@ def _serialize_inventory_snapshot(task: ShippingTask) -> dict[str, Any] | None:
return serialize_inventory_snapshot_link(task)
+def _task_version_chain_fields(task: ShippingTask) -> dict[str, Any]:
+ """
+ 组装任务版本链与重复决策投影字段。
+
+ 核心逻辑:查 supersedes / 被谁 supersede / duplicate_source,供工作台与 Chat 导航。
+ """
+ supersedes_task_no = None
+ if task.supersedes_task_id:
+ prev = db.session.get(ShippingTask, int(task.supersedes_task_id))
+ if prev is not None:
+ supersedes_task_no = prev.task_no
+ superseded_by = (
+ db.session.query(ShippingTask)
+ .filter(ShippingTask.supersedes_task_id == int(task.id))
+ .order_by(ShippingTask.document_version.desc(), ShippingTask.id.desc())
+ .first()
+ )
+ duplicate_source_task_no = None
+ if task.duplicate_source_task_id:
+ src = db.session.get(ShippingTask, int(task.duplicate_source_task_id))
+ if src is not None:
+ duplicate_source_task_no = src.task_no
+ return {
+ 'document_version': int(task.document_version or 1),
+ 'supersedes_task_no': supersedes_task_no,
+ 'superseded_by_task_no': superseded_by.task_no if superseded_by else None,
+ 'duplicate_source_task_no': duplicate_source_task_no,
+ 'duplicate_resolution_type': task.duplicate_resolution_type,
+ 'duplicate_override_reason': task.duplicate_override_reason,
+ 'business_fingerprint': task.business_fingerprint,
+ 'fingerprint_version': task.fingerprint_version,
+ }
+
+
def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]:
"""按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。"""
from app.services.shipping_notice.rpa import rpa_runtime_mode
@@ -305,7 +340,7 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
return _task_tool_payload(task)
if projection == TaskProjection.SUMMARY:
step_payload = task.step_payload_json or {}
- return {
+ data = {
"id": task.id,
"task_no": task.task_no,
"batch_no": _task_batch_no(task),
@@ -331,12 +366,28 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
"rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None),
"rpa_inventory_source": step_payload.get("rpa_inventory_source") if isinstance(step_payload, dict) else None,
"inventory_source_resolution": step_payload.get("inventory_source_resolution") if isinstance(step_payload, dict) else None,
+ "destination_code": task.destination_code,
+ "destination_city": task.destination_city,
+ "destination_country": task.destination_country,
+ "warehouse_hint": task.warehouse_hint,
+ "inventory_source_code": task.inventory_source_code,
+ "inventory_source_type": task.inventory_source_type,
+ "inventory_site_id": task.inventory_site_id,
+ "inventory_warehouse_id": task.inventory_warehouse_id,
+ "inventory_source_status": task.inventory_source_status,
+ "inventory_source_method": task.inventory_source_method,
+ "inventory_source_config_version": task.inventory_source_config_version,
+ "inventory_routing_fingerprint": task.inventory_routing_fingerprint,
+ "inventory_source_confirmed_at": task.inventory_source_confirmed_at.isoformat() if task.inventory_source_confirmed_at else None,
+ "inventory_source_confirmed_by": task.inventory_source_confirmed_by,
"inventory_snapshot": _serialize_inventory_snapshot(task),
"shortage": task.shortage_json,
"line_results": task.line_results_json or [],
"created_at": task.created_at.isoformat() if task.created_at else None,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
}
+ data.update(_task_version_chain_fields(task))
+ return data
if projection == TaskProjection.DETAIL:
data = serialize_task(task, TaskProjection.SUMMARY)
data.update({
diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py
index b3aba22c..1812a4f7 100644
--- a/backend/app/services/shipping_notice/queue_service.py
+++ b/backend/app/services/shipping_notice/queue_service.py
@@ -2,8 +2,9 @@
services/shipping_notice/queue_service.py
用途:货代发货后台任务队列适配层。
-依赖:app.jobs.queue、jobs.types、shipping_notice.batch_orchestrator。
-逻辑:发货通知只写入通用 jobs 表,worker 通过 Job Runner 消费后执行单票编排。
+依赖:app.jobs.queue、jobs.types、batch_orchestrator、intake_parse_workflow。
+逻辑:发货通知写入通用 jobs;worker 领取 RUN/PARSE;超时回收时 PARSE Job
+ 经 sync_intake_after_parse_job_recovery 同步 Intake,避免永久 parsing。
"""
from __future__ import annotations
@@ -110,23 +111,66 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
- """兼容旧调用:回收通用 jobs 表里超时的发货任务。"""
- from app.jobs.queue import recover_stale_jobs
+ """
+ 回收通用 jobs 表里超时的发货任务,并顺带消费 RPA callback cleanup 队列。
- timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300))
- count = recover_stale_jobs(domain=SHIPPING_NOTICE_JOB_DOMAIN, timeout_seconds=timeout_sec)
+ 核心逻辑:单票编排与预解析分超时配置回收;预解析 Job 回收同事务同步 Intake,
+ 避免 Job 已 requeue/failed 而 Intake 永久 parsing。
+ """
+ from app.jobs.queue import recover_stale_jobs
+ from app.services.shipping_notice.intake_parse_workflow import (
+ sync_intake_after_parse_job_recovery,
+ )
+ from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
+ recover_pending_rpa_callback_cleanup_jobs,
+ )
+
+ run_timeout = float(
+ current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300) or 300
+ )
+ parse_timeout = float(
+ current_app.config.get('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', 300) or 300
+ )
+ run_count = recover_stale_jobs(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ timeout_seconds=run_timeout,
+ job_type=JobType.SHIPPING_NOTICE_RUN,
+ )
+ parse_count = recover_stale_jobs(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ timeout_seconds=parse_timeout,
+ job_type=JobType.SHIPPING_NOTICE_PARSE,
+ on_recovered=sync_intake_after_parse_job_recovery,
+ )
+ count = int(run_count) + int(parse_count)
+ cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
+ if cleanup_warnings:
+ logger.warning('rpa callback cleanup warnings: %s', '; '.join(cleanup_warnings[:5]))
if count:
- logger.warning('recovered %s stale shipping_notice job(s)', count)
- return count, f'recovered_{count}' if count else 'no_stale_jobs'
+ logger.warning(
+ 'recovered %s stale shipping_notice job(s) (run=%s parse=%s)',
+ count,
+ run_count,
+ parse_count,
+ )
+ if cleanup_count:
+ logger.info('processed %s rpa callback cleanup job(s)', cleanup_count)
+ parts = []
+ if count:
+ parts.append(f'recovered_{count}')
+ if cleanup_count:
+ parts.append(f'callback_cleanup_{cleanup_count}')
+ return count, '_'.join(parts) if parts else 'no_stale_jobs'
def claim_next_shipping_notice_job() -> Job | None:
- """兼容旧调用:领取下一条发货通知通用任务。"""
+ """领取下一条发货通知通用任务(单票编排或预解析)。"""
from app.jobs.queue import claim_next_job
+ from app.jobs.types import JobType
return claim_next_job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
- job_types=[JobType.SHIPPING_NOTICE_RUN],
+ job_types=[JobType.SHIPPING_NOTICE_RUN, JobType.SHIPPING_NOTICE_PARSE],
)
diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py
index 126fa051..187e8d4a 100644
--- a/backend/app/services/shipping_notice/rpa.py
+++ b/backend/app/services/shipping_notice/rpa.py
@@ -79,8 +79,11 @@ def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None
写入 RPA 库存导出触发文件 inventory_export_{task_no}.json。
Returns:
- str | None: 触发文件绝对路径;目录未配置时返回 None。
+ str | None: 触发文件绝对路径;目录未配置或 worker 未就绪时返回 None。
"""
+ from app.services.shipping_notice.rpa_worker_heartbeat import assert_inventory_rpa_worker_ready
+
+ assert_inventory_rpa_worker_ready()
trigger_dir = inventory_trigger_dir()
if not trigger_dir:
return None
@@ -88,6 +91,7 @@ def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None
body = {
"action": "inventory_export",
"task_no": task_no,
+ "run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}",
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
@@ -114,6 +118,9 @@ def write_inventory_export_batch_trigger(
Returns:
str | None: 触发文件绝对路径。
"""
+ from app.services.shipping_notice.rpa_worker_heartbeat import assert_inventory_rpa_worker_ready
+
+ assert_inventory_rpa_worker_ready()
trigger_dir = inventory_trigger_dir()
if not trigger_dir or not sources:
return None
@@ -171,7 +178,7 @@ def write_inventory_export_trigger_for_task(
"""
body = dict(payload or {})
if inventory_rpa_batch_enabled():
- run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
+ run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}"
return write_inventory_export_batch_trigger(
run_no,
[rpa_source],
diff --git a/backend/app/services/shipping_notice/rpa_worker_heartbeat.py b/backend/app/services/shipping_notice/rpa_worker_heartbeat.py
new file mode 100644
index 00000000..82a2fcba
--- /dev/null
+++ b/backend/app/services/shipping_notice/rpa_worker_heartbeat.py
@@ -0,0 +1,575 @@
+"""
+services/shipping_notice/rpa_worker_heartbeat.py
+
+用途:货代库存 RPA Worker 心跳存储、共享目录校验、就绪检查与状态查询。
+依赖:Flask current_app、redis_client、shipping_notice.rpa(目录与 mock 模式)。
+逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 trigger 前由 rpa / inventory_rpa_workflow / shipping_inventory_rpa_job 调用就绪检查。
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import threading
+import time
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from flask import current_app
+
+from app.core.config.settings import _normalize_env_name
+from app.core.errors import ServiceUnavailableError
+from app.services.shipping_notice.rpa import inventory_trigger_dir, rpa_runtime_mode
+
+logger = logging.getLogger(__name__)
+
+RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
+RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
+INVENTORY_EXPORT_CAPABILITY = "inventory_export"
+_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
+_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
+_MEMORY_STORE: dict[str, dict[str, Any]] = {}
+_MEMORY_LOCK = threading.Lock()
+
+_REASON_USER_HINTS: dict[str, str] = {
+ "no_worker_heartbeat": "未收到任何 Worker 心跳",
+ "heartbeat_storage_unavailable": "心跳存储不可用(Redis)",
+ "trigger_dir_not_configured": "后端未配置库存 trigger 目录",
+ "trigger_dir_not_accessible": "trigger 目录不存在或不可访问",
+ "shared_sentinel_missing": "共享目录哨兵文件缺失,可能 CIFS 未挂载",
+ "shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
+ "trigger_dir_not_writable": "trigger 目录不可写",
+ "environment_mismatch": "Worker 环境与后端环境不一致",
+ "missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
+}
+
+
+@dataclass
+class RpaWorkerReadiness:
+ """库存 RPA 触发前就绪检查结果。"""
+
+ ready: bool
+ message: str
+ workers: list[dict[str, Any]] = field(default_factory=list)
+ reasons: list[str] = field(default_factory=list)
+ checked_at: str = ""
+ detail_message: str = ""
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
+
+
+def _config_bool(key: str, default: bool) -> bool:
+ if current_app:
+ raw = current_app.config.get(key, default)
+ else:
+ raw = os.getenv(key, str(default).lower())
+ return str(raw).strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _config_str(key: str, default: str = "") -> str:
+ if current_app:
+ raw = current_app.config.get(key, default)
+ else:
+ raw = os.getenv(key, default)
+ return str(raw or default).strip()
+
+
+def _heartbeat_ttl_seconds() -> int:
+ raw = 90
+ if current_app:
+ raw = int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or 90)
+ else:
+ raw = int(os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or "90")
+ return max(60, raw)
+
+
+def _heartbeat_check_required() -> bool:
+ """Mock RPA 或显式关闭时跳过 worker 心跳就绪检查。"""
+ if rpa_runtime_mode().get("mock"):
+ return False
+ return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED", True)
+
+
+def _heartbeat_redis_required() -> bool:
+ """test/prod 默认要求 Redis;dev 仅显式开启时要求。"""
+ explicit = os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
+ if explicit is not None and str(explicit).strip() != "":
+ return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS", False)
+ if current_app:
+ configured = current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
+ if configured is not None:
+ return bool(configured)
+ env_name = resolve_backend_rpa_environment()
+ return env_name in {"test", "prod"}
+
+
+def _heartbeat_allow_memory_fallback() -> bool:
+ return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK", False)
+
+
+def resolve_backend_rpa_environment() -> str:
+ """将后端部署环境归一为 dev / test / prod。"""
+ env_name = os.getenv("ENV_NAME") or os.getenv("FLASK_ENV")
+ if current_app:
+ env_name = current_app.config.get("ENV_NAME") or env_name
+ return _normalize_env_name(env_name)
+
+
+def shared_scope_id() -> str:
+ """共享 SMB 目录逻辑标识(如 hxops-rpa-test-data),用于跨平台路径对齐。"""
+ explicit = _config_str("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "")
+ if explicit:
+ return explicit
+ trigger_dir = inventory_trigger_dir()
+ if not trigger_dir:
+ return ""
+ for part in Path(trigger_dir).parts:
+ normalized = str(part).strip().lower()
+ if normalized.startswith("hxops-rpa-"):
+ return normalized
+ return ""
+
+
+def shared_sentinel_name() -> str:
+ return _config_str("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME", ".hxops_rpa_shared_mount")
+
+
+def _shared_mount_check_required() -> bool:
+ """配置了 scope_id 或 test/prod 环境时强制校验共享哨兵。"""
+ if shared_scope_id():
+ return True
+ return resolve_backend_rpa_environment() in {"test", "prod"}
+
+
+def _parse_capabilities(raw: Any) -> set[str]:
+ if isinstance(raw, str):
+ values = [part.strip().lower() for part in raw.split(",")]
+ elif isinstance(raw, list):
+ values = [str(part).strip().lower() for part in raw]
+ else:
+ values = []
+ return {value for value in values if value}
+
+
+def _coerce_worker_payload(payload: dict[str, Any]) -> dict[str, Any]:
+ """校验并规范化 worker 心跳 payload。"""
+ worker_id = str(payload.get("worker_id") or "").strip()
+ if not worker_id:
+ raise ValueError("worker_id is required")
+ timestamp = str(payload.get("timestamp") or "").strip() or _utc_now_iso()
+ environment = str(payload.get("environment") or "").strip().lower() or resolve_backend_rpa_environment()
+ status = str(payload.get("status") or "idle").strip().lower()
+ if status not in {"idle", "busy"}:
+ status = "idle"
+ scope = str(payload.get("shared_scope_id") or "").strip()
+ return {
+ "worker_id": worker_id,
+ "hostname": str(payload.get("hostname") or "").strip(),
+ "environment": environment,
+ "capabilities": sorted(_parse_capabilities(payload.get("capabilities"))),
+ "status": status,
+ "trigger_dir": str(payload.get("trigger_dir") or "").strip(),
+ "drop_dir": str(payload.get("drop_dir") or "").strip(),
+ "shared_scope_id": scope,
+ "version": str(payload.get("version") or "").strip(),
+ "timestamp": timestamp,
+ "received_at": _utc_now_iso(),
+ }
+
+
+def _redis_client():
+ from app.services.redis_client import get_redis_client
+
+ return get_redis_client()
+
+
+def _memory_store_worker(worker: dict[str, Any]) -> None:
+ with _MEMORY_LOCK:
+ _MEMORY_STORE[worker["worker_id"]] = dict(worker)
+
+
+def _memory_list_workers() -> list[dict[str, Any]]:
+ with _MEMORY_LOCK:
+ return [dict(item) for item in _MEMORY_STORE.values()]
+
+
+def reset_rpa_worker_heartbeat_state_for_tests() -> None:
+ """单测隔离:清空进程内内存心跳缓存。"""
+ with _MEMORY_LOCK:
+ _MEMORY_STORE.clear()
+
+
+def _redis_store_worker(worker: dict[str, Any]) -> bool:
+ client = _redis_client()
+ if client is None:
+ return False
+ ttl = _heartbeat_ttl_seconds() * 2
+ key = f"{_REDIS_WORKER_KEY_PREFIX}{worker['worker_id']}"
+ try:
+ client.set(key, json.dumps(worker, ensure_ascii=False), ex=ttl)
+ client.sadd(_REDIS_INDEX_KEY, worker["worker_id"])
+ client.expire(_REDIS_INDEX_KEY, ttl * 4)
+ return True
+ except Exception:
+ logger.exception("[rpa-heartbeat] redis store failed worker_id=%s", worker.get("worker_id"))
+ return False
+
+
+def _redis_list_workers() -> tuple[list[dict[str, Any]], bool]:
+ """
+ 从 Redis 读取 worker 心跳列表。
+ Returns:
+ tuple[list, read_failed]: read_failed=True 表示 Redis 读取异常(非“无心跳”)。
+ """
+ client = _redis_client()
+ if client is None:
+ return [], False
+ workers: list[dict[str, Any]] = []
+ try:
+ worker_ids = client.smembers(_REDIS_INDEX_KEY) or []
+ for worker_id in sorted(worker_ids):
+ raw = client.get(f"{_REDIS_WORKER_KEY_PREFIX}{worker_id}")
+ if not raw:
+ continue
+ parsed = json.loads(raw)
+ if isinstance(parsed, dict):
+ workers.append(parsed)
+ except Exception:
+ logger.exception("[rpa-heartbeat] redis list failed")
+ return [], True
+ return workers, False
+
+
+def record_rpa_worker_heartbeat(payload: dict[str, Any]) -> dict[str, Any]:
+ """
+ 记录 RPA Worker 心跳。
+ 核心逻辑:test/prod 必须写 Redis;仅 dev 且显式允许时才降级进程内存。
+ """
+ worker = _coerce_worker_payload(payload)
+ stored_in_redis = _redis_store_worker(worker)
+ if stored_in_redis:
+ worker["storage"] = "redis"
+ return worker
+
+ if _heartbeat_redis_required():
+ raise ServiceUnavailableError(
+ RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
+ code="RPA.HEARTBEAT_STORAGE_UNAVAILABLE",
+ details={"reason": "redis_write_failed", "worker_id": worker.get("worker_id")},
+ )
+ if _heartbeat_allow_memory_fallback():
+ _memory_store_worker(worker)
+ worker["storage"] = "memory"
+ return worker
+
+ raise ServiceUnavailableError(
+ RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
+ code="RPA.HEARTBEAT_STORAGE_UNAVAILABLE",
+ details={"reason": "memory_fallback_disabled", "worker_id": worker.get("worker_id")},
+ )
+
+
+def list_rpa_worker_heartbeats() -> tuple[list[dict[str, Any]], bool]:
+ """
+ 返回当前已知 worker 心跳列表。
+ Returns:
+ tuple[workers, storage_read_failed]
+ """
+ workers, read_failed = _redis_list_workers()
+ if read_failed:
+ return [], True
+ if workers:
+ return workers, False
+ if _heartbeat_redis_required():
+ if _redis_client() is None:
+ return [], True
+ return [], False
+ if _heartbeat_allow_memory_fallback():
+ return _memory_list_workers(), False
+ return [], False
+
+
+def _heartbeat_age_seconds(worker: dict[str, Any], *, now: float | None = None) -> float | None:
+ raw = str(worker.get("received_at") or worker.get("timestamp") or "").strip()
+ if not raw:
+ return None
+ try:
+ parsed = datetime.fromisoformat(raw.replace("Z", ""))
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ except ValueError:
+ return None
+ current = now if now is not None else time.time()
+ return max(current - parsed.timestamp(), 0.0)
+
+
+def _parse_sentinel_content(raw: str) -> dict[str, str]:
+ parsed: dict[str, str] = {}
+ for line in raw.splitlines():
+ if "=" not in line:
+ continue
+ key, value = line.split("=", 1)
+ parsed[key.strip().lower()] = value.strip()
+ return parsed
+
+
+def _read_shared_sentinel(trigger_dir: Path) -> tuple[dict[str, str] | None, str | None]:
+ sentinel_path = trigger_dir / shared_sentinel_name()
+ if not sentinel_path.is_file():
+ return None, "shared_sentinel_missing"
+ try:
+ content = sentinel_path.read_text(encoding="utf-8")
+ parsed = _parse_sentinel_content(content)
+ if not parsed:
+ return None, "shared_sentinel_invalid"
+ return parsed, None
+ except Exception:
+ return None, "shared_sentinel_unreadable"
+
+
+def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[str]]:
+ """
+ 校验 trigger 目录为真实共享挂载,而非 Ubuntu 本地误创建目录。
+ 核心逻辑:目录必须已存在;test/prod 或配置 scope_id 时要求哨兵文件且 scope 一致。
+ """
+ reasons: list[str] = []
+ if trigger_dir is None:
+ return False, ["trigger_dir_not_configured"]
+ if not trigger_dir.exists():
+ return False, ["trigger_dir_not_accessible"]
+ if not trigger_dir.is_dir():
+ return False, ["trigger_dir_not_accessible"]
+
+ expected_scope = shared_scope_id()
+ if _shared_mount_check_required():
+ sentinel, sentinel_reason = _read_shared_sentinel(trigger_dir)
+ if sentinel_reason:
+ reasons.append(sentinel_reason)
+ elif expected_scope:
+ actual_scope = str(sentinel.get("scope_id") or "").strip()
+ if actual_scope != expected_scope:
+ reasons.append(f"shared_scope_mismatch:{actual_scope}!={expected_scope}")
+ elif not str(sentinel.get("scope_id") or "").strip():
+ reasons.append("shared_scope_mismatch:missing_scope_id")
+
+ if reasons:
+ return False, reasons
+
+ try:
+ probe = trigger_dir / ".hxops_rpa_write_probe"
+ probe.write_text("ok", encoding="utf-8")
+ probe.unlink(missing_ok=True)
+ except Exception:
+ reasons.append("trigger_dir_not_writable")
+ return not reasons, reasons
+
+
+def _worker_scope_matches(worker: dict[str, Any]) -> tuple[bool, list[str]]:
+ expected_scope = shared_scope_id()
+ if not expected_scope:
+ return True, []
+ worker_scope = str(worker.get("shared_scope_id") or "").strip()
+ if worker_scope == expected_scope:
+ return True, []
+ return False, [f"shared_scope_mismatch:{worker_scope or '-'}!={expected_scope}"]
+
+
+def _worker_is_eligible(
+ worker: dict[str, Any],
+ *,
+ backend_env: str,
+ ttl_seconds: int,
+ now: float,
+) -> tuple[bool, list[str]]:
+ reasons: list[str] = []
+ age = _heartbeat_age_seconds(worker, now=now)
+ if age is None:
+ reasons.append("heartbeat_timestamp_invalid")
+ elif age > ttl_seconds:
+ reasons.append(f"heartbeat_stale:{int(age)}s")
+
+ capabilities = _parse_capabilities(worker.get("capabilities"))
+ if INVENTORY_EXPORT_CAPABILITY not in capabilities:
+ reasons.append("missing_inventory_export_capability")
+
+ worker_env = str(worker.get("environment") or "").strip().lower()
+ if worker_env and worker_env != backend_env:
+ reasons.append(f"environment_mismatch:{worker_env}!={backend_env}")
+
+ scope_ok, scope_reasons = _worker_scope_matches(worker)
+ if not scope_ok:
+ reasons.extend(scope_reasons)
+
+ return not reasons, reasons
+
+
+def _summarize_reasons(reasons: list[str]) -> str:
+ hints: list[str] = []
+ for reason in reasons:
+ base = reason.split(":", 1)[0]
+ hint = _REASON_USER_HINTS.get(base)
+ if hint and hint not in hints:
+ hints.append(hint)
+ return ";".join(hints) if hints else ";".join(reasons[:5])
+
+
+def _build_failure_message(result: RpaWorkerReadiness) -> tuple[str, str]:
+ """返回 (用户可见 message, 运维 detail_message)。"""
+ if any(reason == "heartbeat_storage_unavailable" for reason in result.reasons):
+ return RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE, _summarize_reasons(result.reasons)
+ detail = _summarize_reasons(result.reasons)
+ if not detail:
+ return RPA_WORKER_OFFLINE_MESSAGE, RPA_WORKER_OFFLINE_MESSAGE
+ return RPA_WORKER_OFFLINE_MESSAGE, f"{RPA_WORKER_OFFLINE_MESSAGE}({detail})"
+
+
+def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
+ """
+ 检查库存 RPA 触发前 worker 是否就绪。
+ 核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
+ """
+ checked_at = _utc_now_iso()
+ if not _heartbeat_check_required():
+ return RpaWorkerReadiness(
+ ready=True,
+ message="heartbeat check skipped",
+ checked_at=checked_at,
+ )
+
+ reasons: list[str] = []
+ if _heartbeat_redis_required() and _redis_client() is None:
+ reasons.append("heartbeat_storage_unavailable")
+
+ trigger_dir = inventory_trigger_dir()
+ mount_ok, mount_reasons = _verify_shared_trigger_mount(trigger_dir)
+ reasons.extend(mount_reasons)
+
+ backend_env = resolve_backend_rpa_environment()
+ ttl_seconds = _heartbeat_ttl_seconds()
+ now = time.time()
+ workers, storage_read_failed = list_rpa_worker_heartbeats()
+ if storage_read_failed:
+ reasons.append("heartbeat_storage_unavailable")
+ eligible_workers: list[dict[str, Any]] = []
+ enriched_workers: list[dict[str, Any]] = []
+
+ for worker in workers:
+ eligible, worker_reasons = _worker_is_eligible(
+ worker,
+ backend_env=backend_env,
+ ttl_seconds=ttl_seconds,
+ now=now,
+ )
+ enriched = {
+ **worker,
+ "age_seconds": _heartbeat_age_seconds(worker, now=now),
+ "eligible": eligible,
+ "ineligible_reasons": worker_reasons,
+ }
+ enriched_workers.append(enriched)
+ if eligible:
+ eligible_workers.append(enriched)
+ else:
+ reasons.extend([f"{worker.get('worker_id')}:{reason}" for reason in worker_reasons])
+
+ if not workers and "heartbeat_storage_unavailable" not in reasons:
+ reasons.append("no_worker_heartbeat")
+
+ mount_block_tokens = {
+ "trigger_dir_not_configured",
+ "trigger_dir_not_accessible",
+ "shared_sentinel_missing",
+ "shared_sentinel_invalid",
+ "shared_sentinel_unreadable",
+ "trigger_dir_not_writable",
+ }
+ blocking_mount = any(reason in mount_block_tokens for reason in reasons) or any(
+ reason.startswith("shared_scope_mismatch") for reason in reasons
+ )
+ ready = bool(eligible_workers) and not blocking_mount and "heartbeat_storage_unavailable" not in reasons
+ message, detail_message = ("ready", "ready") if ready else _build_failure_message(
+ RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
+ )
+ return RpaWorkerReadiness(
+ ready=ready,
+ message=message,
+ detail_message=detail_message,
+ workers=enriched_workers,
+ reasons=sorted(set(reasons)),
+ checked_at=checked_at,
+ )
+
+
+def assert_inventory_rpa_worker_ready() -> None:
+ """
+ 写 trigger 前的强制就绪检查。
+ Raises:
+ ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
+ """
+ result = check_inventory_rpa_worker_ready()
+ if result.ready:
+ return
+ code = "RPA.WORKER_OFFLINE"
+ if "heartbeat_storage_unavailable" in result.reasons:
+ code = "RPA.HEARTBEAT_STORAGE_UNAVAILABLE"
+ logger.warning(
+ "[rpa-heartbeat] readiness blocked code=%s reasons=%s detail=%s",
+ code,
+ result.reasons,
+ result.detail_message,
+ )
+ raise ServiceUnavailableError(
+ result.message,
+ code=code,
+ details={
+ "reasons": result.reasons,
+ "detail_message": result.detail_message,
+ "checked_at": result.checked_at,
+ "shared_scope_id": shared_scope_id(),
+ "trigger_dir": str(inventory_trigger_dir() or ""),
+ },
+ )
+
+
+def serialize_rpa_worker_status() -> dict[str, Any]:
+ """管理端展示:在线 worker 列表与就绪摘要(含详细 reasons)。"""
+ readiness = check_inventory_rpa_worker_ready()
+ ttl_seconds = _heartbeat_ttl_seconds()
+ workers = []
+ now = time.time()
+ for worker in readiness.workers:
+ workers.append({
+ "worker_id": worker.get("worker_id"),
+ "hostname": worker.get("hostname"),
+ "environment": worker.get("environment"),
+ "status": worker.get("status"),
+ "capabilities": worker.get("capabilities") or [],
+ "trigger_dir": worker.get("trigger_dir"),
+ "drop_dir": worker.get("drop_dir"),
+ "shared_scope_id": worker.get("shared_scope_id"),
+ "version": worker.get("version"),
+ "timestamp": worker.get("timestamp"),
+ "received_at": worker.get("received_at"),
+ "age_seconds": _heartbeat_age_seconds(worker, now=now),
+ "online": (_heartbeat_age_seconds(worker, now=now) or 9999) <= ttl_seconds,
+ "eligible": worker.get("eligible"),
+ "ineligible_reasons": worker.get("ineligible_reasons") or [],
+ })
+ return {
+ "ready": readiness.ready,
+ "message": readiness.message,
+ "detail_message": readiness.detail_message,
+ "checked_at": readiness.checked_at,
+ "heartbeat_ttl_seconds": ttl_seconds,
+ "backend_environment": resolve_backend_rpa_environment(),
+ "shared_scope_id": shared_scope_id(),
+ "shared_sentinel_name": shared_sentinel_name(),
+ "trigger_dir": str(inventory_trigger_dir() or ""),
+ "reasons": readiness.reasons,
+ "workers": workers,
+ }
diff --git a/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py b/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py
new file mode 100644
index 00000000..8a8a7916
--- /dev/null
+++ b/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py
@@ -0,0 +1,563 @@
+"""
+services/shipping_notice/rpa_worker_heartbeat_alert.py
+
+用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
+依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
+逻辑:由 schedule worker 每轮循环调用;DB 为告警状态权威源,Redis 仅作缓存同步。
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import threading
+import time
+from collections.abc import Callable
+from typing import Any
+
+from flask import current_app
+from sqlalchemy.exc import IntegrityError
+
+from app import db
+from app.models import AppSetting, User
+from app.services.shipping_notice.rpa_worker_heartbeat import (
+ RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
+ RPA_WORKER_OFFLINE_MESSAGE,
+ _heartbeat_check_required,
+ check_inventory_rpa_worker_ready,
+)
+
+logger = logging.getLogger(__name__)
+
+_REDIS_ALERT_STATE_KEY = "shipping:rpa:heartbeat:alert:state"
+_DB_ALERT_STATE_KEY = "shipping:rpa:heartbeat:alert:state"
+_STATUS_SENDING = "sending"
+_LAST_CHECK_MONO = 0.0
+_MEMORY_ALERT_STATE: dict[str, Any] = {}
+_MEMORY_ALERT_LOCK = threading.Lock()
+_RECIPIENT_GAP_LOGGED = False
+
+
+def _config_bool(key: str, default: bool) -> bool:
+ raw = current_app.config.get(key, default)
+ return str(raw).strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _alert_enabled() -> bool:
+ if not _heartbeat_check_required():
+ return False
+ return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED", True)
+
+
+def _alert_cooldown_seconds() -> int:
+ return max(300, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS") or 1800))
+
+
+def _send_lock_seconds() -> int:
+ """企微发送中的短锁 TTL;发送失败过期后可重试,不进入长冷却。"""
+ return max(60, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS") or 120))
+
+
+def _alert_fallback_admin_enabled() -> bool:
+ return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN", True)
+
+
+def _alert_recipients() -> list[User]:
+ """
+ 解析告警接收人。
+ 核心逻辑:优先 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。
+ """
+ raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES") or "").strip()
+ names = [part.strip() for part in raw.split(",") if part.strip()] if raw else []
+ if names:
+ users = (
+ db.session.query(User)
+ .filter(User.username.in_(names), User.wecom_userid.isnot(None))
+ .all()
+ )
+ if users:
+ return users
+ logger.warning(
+ "[rpa-heartbeat-alert] configured usernames have no bound wecom_userid: %s",
+ names,
+ )
+ if _alert_fallback_admin_enabled():
+ admins = (
+ db.session.query(User)
+ .filter(User.role == "admin", User.wecom_userid.isnot(None))
+ .order_by(User.id.asc())
+ .limit(20)
+ .all()
+ )
+ if admins:
+ logger.info(
+ "[rpa-heartbeat-alert] using admin fallback recipients count=%d",
+ len(admins),
+ )
+ return admins
+ return []
+
+
+def _log_recipient_gap_once() -> None:
+ """部署缺口:未配置接收人且无已绑企微 admin 时仅打一次明确 warning。"""
+ global _RECIPIENT_GAP_LOGGED
+ if _RECIPIENT_GAP_LOGGED:
+ return
+ _RECIPIENT_GAP_LOGGED = True
+ logger.warning(
+ "[rpa-heartbeat-alert] no wecom recipients: set SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES "
+ "or bind wecom_userid for at least one admin (FALLBACK_ADMIN=true)"
+ )
+
+
+def _redis_client():
+ from app.services.redis_client import get_redis_client
+
+ return get_redis_client()
+
+
+def _memory_load_alert_state() -> dict[str, Any]:
+ with _MEMORY_ALERT_LOCK:
+ return dict(_MEMORY_ALERT_STATE)
+
+
+def _memory_save_alert_state(state: dict[str, Any]) -> None:
+ with _MEMORY_ALERT_LOCK:
+ _MEMORY_ALERT_STATE.clear()
+ _MEMORY_ALERT_STATE.update(state)
+
+
+def _load_alert_state_from_db() -> dict[str, Any] | None:
+ state, _db_ok = _try_read_alert_state_from_db()
+ return state
+
+
+def _try_read_alert_state_from_db() -> tuple[dict[str, Any] | None, bool]:
+ """
+ 读取 DB 告警状态。
+ Returns:
+ (state, db_available):无行时 state 为 None 但 db_available 仍为 True。
+ """
+ try:
+ row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
+ if row and row.value:
+ parsed = json.loads(row.value)
+ if isinstance(parsed, dict):
+ return parsed, True
+ return None, True
+ except Exception:
+ logger.exception("[rpa-heartbeat-alert] load state from db failed")
+ db.session.rollback()
+ return None, False
+
+
+def _persist_alert_state_to_db(state: dict[str, Any]) -> None:
+ payload = json.dumps(state, ensure_ascii=False)
+ row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
+ if row:
+ row.value = payload
+ else:
+ db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=payload))
+ db.session.commit()
+
+
+def _normalize_alert_state(state: dict[str, Any]) -> dict[str, Any]:
+ """写入前补齐 updated_at,供跨存储源比较版本。"""
+ normalized = dict(state)
+ normalized["updated_at"] = time.time()
+ return normalized
+
+
+def _try_load_alert_state_from_redis() -> dict[str, Any] | None:
+ client = _redis_client()
+ if client is None:
+ return None
+ try:
+ raw = client.get(_REDIS_ALERT_STATE_KEY)
+ if raw:
+ parsed = json.loads(raw)
+ if isinstance(parsed, dict):
+ return parsed
+ except Exception:
+ logger.exception("[rpa-heartbeat-alert] load state from redis failed")
+ return None
+
+
+def _sync_redis_cache_from_db(state: dict[str, Any]) -> None:
+ """DB 为权威源时,无条件用 DB 状态覆盖 Redis 缓存。"""
+ _persist_alert_state_to_redis(state)
+
+
+def _persist_alert_state_to_redis(state: dict[str, Any]) -> None:
+ client = _redis_client()
+ if client is None:
+ return
+ try:
+ client.set(_REDIS_ALERT_STATE_KEY, json.dumps(state, ensure_ascii=False), ex=86400 * 7)
+ except Exception:
+ logger.exception("[rpa-heartbeat-alert] save state to redis failed")
+
+
+def _delete_redis_alert_state_if_possible() -> None:
+ """DB 无状态时清理 Redis 残留缓存。"""
+ client = _redis_client()
+ if client is None:
+ return
+ try:
+ client.delete(_REDIS_ALERT_STATE_KEY)
+ except Exception:
+ logger.exception("[rpa-heartbeat-alert] delete state from redis failed")
+
+
+def reset_rpa_worker_alert_state_for_tests() -> None:
+ """单测隔离:清空进程内告警冷却状态与 DB 行。"""
+ global _LAST_CHECK_MONO, _RECIPIENT_GAP_LOGGED
+ _LAST_CHECK_MONO = 0.0
+ _RECIPIENT_GAP_LOGGED = False
+ with _MEMORY_ALERT_LOCK:
+ _MEMORY_ALERT_STATE.clear()
+ try:
+ from flask import has_app_context
+
+ if has_app_context():
+ row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
+ if row:
+ db.session.delete(row)
+ db.session.commit()
+ except Exception:
+ db.session.rollback()
+
+
+def _load_alert_state() -> dict[str, Any]:
+ """
+ 加载告警冷却状态;DB 为权威源,Redis 仅作缓存,仅 DB 不可读时才回退 Redis/内存。
+ """
+ db_state, db_ok = _try_read_alert_state_from_db()
+ if db_ok:
+ if db_state is not None:
+ _memory_save_alert_state(db_state)
+ _sync_redis_cache_from_db(db_state)
+ return db_state
+ _memory_save_alert_state({})
+ _delete_redis_alert_state_if_possible()
+ return {}
+
+ redis_state = _try_load_alert_state_from_redis()
+ if redis_state is not None:
+ _memory_save_alert_state(redis_state)
+ return redis_state
+ return _memory_load_alert_state()
+
+
+def _save_alert_state(state: dict[str, Any]) -> None:
+ """保存告警冷却状态;写内存 + DB + Redis(可用时)。"""
+ payload = _normalize_alert_state(state) if state else {}
+ _memory_save_alert_state(payload)
+ if not payload:
+ return
+ try:
+ _persist_alert_state_to_db(payload)
+ except Exception:
+ db.session.rollback()
+ logger.exception("[rpa-heartbeat-alert] save state to db failed")
+ _persist_alert_state_to_redis(payload)
+
+
+def _claim_alert_send_lock_db(
+ *,
+ lock_state: dict[str, Any],
+ should_send_fn: Callable[[dict[str, Any]], bool],
+) -> tuple[bool, dict[str, Any]]:
+ row = (
+ db.session.query(AppSetting)
+ .filter(AppSetting.key == _DB_ALERT_STATE_KEY)
+ .with_for_update()
+ .one_or_none()
+ )
+ existing: dict[str, Any] = {}
+ if row and row.value:
+ parsed = json.loads(row.value)
+ if isinstance(parsed, dict):
+ existing = parsed
+ if not should_send_fn(existing):
+ db.session.rollback()
+ return False, existing
+
+ previous_state = dict(existing)
+ lock_state = _normalize_alert_state(lock_state)
+ payload = json.dumps(lock_state, ensure_ascii=False)
+ if row:
+ row.value = payload
+ else:
+ db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=payload))
+ db.session.commit()
+ _memory_save_alert_state(lock_state)
+ _persist_alert_state_to_redis(lock_state)
+ return True, previous_state
+
+
+def _claim_alert_send_lock_memory_only(
+ *,
+ lock_state: dict[str, Any],
+ should_send_fn: Callable[[dict[str, Any]], bool],
+) -> tuple[bool, dict[str, Any]]:
+ """仅当 DB 不可读/不可写时使用的进程内 claim 兜底。"""
+ mem = _memory_load_alert_state()
+ if not should_send_fn(mem):
+ return False, mem
+ previous_state = dict(mem)
+ _memory_save_alert_state(lock_state)
+ return True, previous_state
+
+
+def _claim_alert_send_lock(
+ *,
+ lock_state: dict[str, Any],
+ should_send_fn: Callable[[dict[str, Any]], bool],
+) -> tuple[bool, dict[str, Any]]:
+ """
+ 跨进程发送锁:仅写入 sending 状态,不更新 last_sent_at 冷却。
+ Returns:
+ (claimed, previous_state):claimed 为 True 时 previous_state 供发送失败回滚。
+ """
+ try:
+ return _claim_alert_send_lock_db(lock_state=lock_state, should_send_fn=should_send_fn)
+ except IntegrityError:
+ db.session.rollback()
+ existing, db_ok = _try_read_alert_state_from_db()
+ if existing:
+ _memory_save_alert_state(existing)
+ elif db_ok:
+ _memory_save_alert_state({})
+ return False, existing or {}
+ except Exception:
+ db.session.rollback()
+ logger.exception("[rpa-heartbeat-alert] claim send lock in db failed")
+ existing, db_ok = _try_read_alert_state_from_db()
+ if db_ok:
+ if existing:
+ _memory_save_alert_state(existing)
+ return False, existing or {}
+ return _claim_alert_send_lock_memory_only(
+ lock_state=lock_state,
+ should_send_fn=should_send_fn,
+ )
+
+
+def _commit_alert_sent(*, final_state: dict[str, Any]) -> None:
+ """企微发送成功后写入最终状态与 last_sent_at(进入长冷却)。"""
+ _save_alert_state(final_state)
+
+
+def _release_alert_send_lock(*, previous_state: dict[str, Any]) -> None:
+ """企微发送失败:回滚 sending 锁,不推进 last_sent_at。"""
+ if previous_state:
+ _save_alert_state(previous_state)
+ return
+ _memory_save_alert_state({})
+ try:
+ row = db.session.get(AppSetting, _DB_ALERT_STATE_KEY)
+ if row:
+ db.session.delete(row)
+ db.session.commit()
+ except Exception:
+ db.session.rollback()
+ logger.exception("[rpa-heartbeat-alert] release send lock in db failed")
+ _delete_redis_alert_state_if_possible()
+
+
+def _send_alert_to_recipients(*, title: str, content: str) -> bool:
+ from app.services.wecom_notify import send_wecom_event_message
+
+ recipients = _alert_recipients()
+ if not recipients:
+ _log_recipient_gap_once()
+ logger.warning("[rpa-heartbeat-alert] no recipients available, title=%s", title)
+ return False
+ sent_any = False
+ for user in recipients:
+ result = send_wecom_event_message(
+ event_type="schedule_completed",
+ user=user,
+ title=title,
+ content=content,
+ jump_path="/admin/schedules",
+ )
+ if result.get("ok"):
+ sent_any = True
+ else:
+ logger.warning(
+ "[rpa-heartbeat-alert] notify failed user=%s reason=%s",
+ user.username,
+ result.get("reason"),
+ )
+ return sent_any
+
+
+def _is_active_send_lock(existing: dict[str, Any], *, now_ts: float) -> bool:
+ if str(existing.get("status") or "").strip() != _STATUS_SENDING:
+ return False
+ started = float(existing.get("sending_started_at") or 0)
+ return started > 0 and (now_ts - started) < _send_lock_seconds()
+
+
+def _effective_last_status(existing: dict[str, Any]) -> str:
+ status = str(existing.get("status") or "").strip()
+ if status == _STATUS_SENDING:
+ return str(existing.get("sending_target") or "").strip()
+ return status
+
+
+def _should_send_storage_or_offline(
+ *,
+ existing: dict[str, Any],
+ target_status: str,
+ now_ts: float,
+ cooldown: int,
+) -> bool:
+ if _is_active_send_lock(existing, now_ts=now_ts):
+ return False
+ last_status = _effective_last_status(existing)
+ last_sent_at = float(existing.get("last_sent_at") or 0)
+ return last_status != target_status or (now_ts - last_sent_at) >= cooldown
+
+
+def _try_send_with_claim(
+ *,
+ target_status: str,
+ state: dict[str, Any],
+ now_ts: float,
+ cooldown: int,
+ title: str,
+ content: str,
+) -> bool:
+ def should_send_fn(existing: dict[str, Any]) -> bool:
+ if _is_active_send_lock(existing, now_ts=now_ts):
+ return False
+ if target_status == "ready":
+ return _effective_last_status(existing) in {"offline", "storage_unavailable"}
+ return _should_send_storage_or_offline(
+ existing=existing,
+ target_status=target_status,
+ now_ts=now_ts,
+ cooldown=cooldown,
+ )
+
+ lock_state = {
+ "status": _STATUS_SENDING,
+ "sending_target": target_status,
+ "sending_started_at": now_ts,
+ "last_sent_at": float(state.get("last_sent_at") or 0),
+ "reasons": state.get("reasons", []),
+ }
+ claimed, previous_state = _claim_alert_send_lock(lock_state=lock_state, should_send_fn=should_send_fn)
+ if not claimed:
+ return False
+ if _send_alert_to_recipients(title=title, content=content):
+ final_state = {
+ "status": target_status,
+ "last_sent_at": now_ts,
+ "reasons": state.get("reasons", []),
+ }
+ _commit_alert_sent(final_state=final_state)
+ return True
+ _release_alert_send_lock(previous_state=previous_state)
+ return False
+
+
+def maybe_alert_rpa_worker_status(*, force: bool = False) -> dict[str, Any]:
+ """
+ 周期检查 RPA Worker 就绪状态并按冷却时间发送离线/恢复告警。
+ Returns:
+ dict: 本次检查结果摘要(供运维日志)。
+ """
+ global _LAST_CHECK_MONO
+ if not _alert_enabled():
+ return {"skipped": True, "reason": "alert_disabled"}
+
+ now_mono = time.monotonic()
+ if not force and _LAST_CHECK_MONO and (now_mono - _LAST_CHECK_MONO) < 60:
+ return {"skipped": True, "reason": "throttled"}
+ _LAST_CHECK_MONO = now_mono
+
+ readiness = check_inventory_rpa_worker_ready()
+ state = _load_alert_state()
+ effective_status = _effective_last_status(state)
+ last_sent_at = float(state.get("last_sent_at") or 0)
+ cooldown = _alert_cooldown_seconds()
+ now_ts = time.time()
+ storage_unavailable = "heartbeat_storage_unavailable" in readiness.reasons
+
+ summary = {
+ "ready": readiness.ready,
+ "status": "storage_unavailable" if storage_unavailable else ("ready" if readiness.ready else "offline"),
+ "reasons": readiness.reasons,
+ "detail_message": readiness.detail_message,
+ }
+
+ if storage_unavailable:
+ should_send = _should_send_storage_or_offline(
+ existing=state,
+ target_status="storage_unavailable",
+ now_ts=now_ts,
+ cooldown=cooldown,
+ )
+ if should_send:
+ title = "货代库存 RPA 心跳存储异常"
+ content = (
+ f"{RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE}\n\n"
+ f"原因:{'; '.join(readiness.reasons[:8]) or 'unknown'}"
+ )
+ new_state = {
+ "status": "storage_unavailable",
+ "last_sent_at": last_sent_at,
+ "reasons": readiness.reasons,
+ }
+ if _try_send_with_claim(
+ target_status="storage_unavailable",
+ state=new_state,
+ now_ts=now_ts,
+ cooldown=cooldown,
+ title=title,
+ content=content,
+ ):
+ summary["storage_alert_sent"] = True
+ return summary
+
+ if not readiness.ready:
+ should_send = _should_send_storage_or_offline(
+ existing=state,
+ target_status="offline",
+ now_ts=now_ts,
+ cooldown=cooldown,
+ )
+ if should_send:
+ detail = readiness.detail_message or RPA_WORKER_OFFLINE_MESSAGE
+ title = "货代库存 RPA Worker 离线"
+ content = f"{detail}\n\n原因:{'; '.join(readiness.reasons[:8]) or 'unknown'}"
+ new_state = {"status": "offline", "last_sent_at": last_sent_at, "reasons": readiness.reasons}
+ if _try_send_with_claim(
+ target_status="offline",
+ state=new_state,
+ now_ts=now_ts,
+ cooldown=cooldown,
+ title=title,
+ content=content,
+ ):
+ summary["alert_sent"] = True
+ return summary
+
+ if effective_status in {"offline", "storage_unavailable"}:
+ title = "货代库存 RPA Worker 已恢复"
+ content = "库存 RPA Worker 心跳已恢复,可正常触发库存导出。"
+ new_state = {"status": "ready", "last_sent_at": last_sent_at, "reasons": []}
+ if _try_send_with_claim(
+ target_status="ready",
+ state=new_state,
+ now_ts=now_ts,
+ cooldown=cooldown,
+ title=title,
+ content=content,
+ ):
+ summary["recovery_sent"] = True
+ return summary
diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py
index 84a497c3..2d98ffc2 100644
--- a/backend/app/services/shipping_notice/state_machine.py
+++ b/backend/app/services/shipping_notice/state_machine.py
@@ -512,7 +512,7 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
pending_human_reason=PH_INV_UNAVAIL,
),
TaskTransition.INVENTORY_SOURCE_REVIEW: _TransitionSpec(
- process_status="waiting_inventory",
+ process_status="pending_review",
review_status=None,
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
),
diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py
index 0cfcbb1a..f2aff878 100644
--- a/backend/app/services/shipping_notice/task_workflow.py
+++ b/backend/app/services/shipping_notice/task_workflow.py
@@ -14,15 +14,24 @@ from typing import Any
from flask import current_app
+from sqlalchemy.exc import IntegrityError
+
from app import db
+from app.core.errors import ConflictError
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.constants import (
+ CP_INVENTORY_SOURCE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_PARSE_OK,
CP_RSV_REQ,
CP_TASK_EXISTS,
+ PH_INVENTORY_SOURCE_UNRESOLVED,
RS_PARSE_REVIEW,
)
+from app.services.shipping_notice.inventory_source_gate import (
+ adjudicate_and_apply_inventory_source,
+ is_inventory_source_stable,
+)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.decision_workflow import submit_decision
from app.services.shipping_notice.extract import extract_notice_fields
@@ -46,6 +55,17 @@ from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
from app.services.shipping_notice.inventory_workflow import ensure_inventory
+from app.services.shipping_notice.batch_create_idempotency import (
+ acquire_notice_create_locks,
+ assert_idempotent_batch_content_matches,
+ assert_no_exact_duplicate_notices,
+ build_existing_batch_tool_response,
+ compute_notice_items_content_fingerprint,
+ dedupe_notice_items_by_content_hash,
+ find_batch_by_create_idempotency,
+ handle_batch_create_integrity_error,
+ normalize_create_idempotency_key,
+)
from app.services.shipping_notice.tool_common import (
auto_progress_enabled,
defer_parse_to_dify_enabled,
@@ -66,11 +86,23 @@ def _capture_destination_context(task: ShippingTask, parsed: dict[str, Any], lin
if isinstance(destination, dict):
payload["destination"] = destination
candidates.append(destination)
+ task.destination_code = str(destination.get("port_code") or destination.get("destination_code") or "").strip().upper() or None
+ task.destination_city = str(destination.get("city") or "").strip() or None
+ task.destination_country = str(destination.get("country") or "").strip().upper() or None
+ task.warehouse_hint = str(destination.get("warehouse_hint") or "").strip() or None
elif destination:
candidates.append(destination)
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to_location"):
if parsed.get(key):
candidates.append(parsed.get(key))
+ if parsed.get("destination_port") and not task.destination_code:
+ task.destination_code = str(parsed.get("destination_port") or "").strip().upper() or None
+ if parsed.get("destination_city") and not task.destination_city:
+ task.destination_city = str(parsed.get("destination_city") or "").strip() or None
+ if parsed.get("destination_country") and not task.destination_country:
+ task.destination_country = str(parsed.get("destination_country") or "").strip().upper() or None
+ if parsed.get("warehouse_hint") and not task.warehouse_hint:
+ task.warehouse_hint = str(parsed.get("warehouse_hint") or "").strip() or None
if task.ship_to:
candidates.append(task.ship_to)
for line in lines:
@@ -175,42 +207,56 @@ def sync_batch_after_task_change(task: ShippingTask | None) -> None:
recompute_batch_summary(task.batch)
-def create_batch(payload: dict[str, Any]) -> ShippingBatch:
+def create_batch(payload: dict[str, Any]) -> tuple[ShippingBatch, bool]:
"""
创建或复用发货批次壳(不含 notice 解析)。
【AI 触发时机】:当用户一次上传多份发货通知、需要归并到同一批次时调用。
- 核心逻辑:优先复用已有 `batch_no`,否则生成新的批次号并初始化批次汇总字段。
+ 核心逻辑:优先复用已有 `batch_no` 或 `(user_id, create_idempotency_key)`,否则生成新批次号。
Args:
- payload: 可包含 batch_no、user_id、conversation_id、file_count 等批次创建参数。
+ payload: 可包含 batch_no、user_id、conversation_id、file_count、create_idempotency_key 等。
Returns:
- ShippingBatch: 已存在或新建但尚未提交事务的批次对象。
+ tuple[ShippingBatch, bool]: (批次对象, 是否本次新建)。复用已有批次时第二项为 False。
"""
batch_no = str(payload.get("batch_no") or "").strip()
if batch_no:
existing = ShippingBatch.query.filter_by(batch_no=batch_no).first()
if existing:
- return existing
+ return existing, False
+
+ user_id = payload.get("user_id")
+ idem_key = normalize_create_idempotency_key(payload.get("create_idempotency_key"))
+ if idem_key and user_id is not None:
+ existing_by_idem = find_batch_by_create_idempotency(int(user_id), idem_key)
+ if existing_by_idem:
+ return existing_by_idem, False
+
try:
file_count = max(1, int(payload.get("file_count") or 1))
except (TypeError, ValueError):
file_count = 1
+ content_fingerprint = str(payload.get("create_content_fingerprint") or "").strip().lower() or None
+ summary: dict[str, Any] = {"total": 0, "completed": 0, "failed": 0, "running": 0}
+ if content_fingerprint:
+ summary["create_content_fingerprint"] = content_fingerprint
batch = ShippingBatch(
batch_no=f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}",
user_id=payload.get("user_id"),
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
file_count=file_count,
- process_summary_json={"total": 0, "completed": 0, "failed": 0, "running": 0},
+ create_idempotency_key=idem_key,
+ process_summary_json=summary,
)
db.session.add(batch)
db.session.flush()
- return batch
+ return batch, True
def _create_single_task_batch(payload: dict[str, Any]) -> ShippingBatch:
"""为单票任务创建 file_count=1 的标准批次容器。"""
- return create_batch({**payload, "file_count": 1})
+ batch, _created = create_batch({**payload, "file_count": 1})
+ return batch
def _should_defer_notice_parse(payload: dict[str, Any], item: dict[str, Any]) -> bool:
@@ -231,15 +277,33 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
核心逻辑:先创建批次,再逐个创建任务;若 notice_item 已带 structured 或 auto_parse=true 则立即 parse_notice,否则仅保存 raw_text 待 Dify 续办。
Args:
- payload: 包含 user_id、conversation_id、notice_items、file_count 等批量建单数据。
+ payload: 包含 user_id、conversation_id、notice_items、file_count 等批量建单数据;
+ defer_commit=True 时仅 flush,由调用方与 intake 回写同事务提交。
Returns:
dict[str, Any]: Tool 标准响应,包含批次摘要和每个任务的解析状态。
"""
notice_items = payload.get("notice_items")
+ user_id = payload.get("user_id")
+ idem_key = normalize_create_idempotency_key(payload.get("create_idempotency_key"))
+ # intake 建批路径可 defer_commit,由上层一次提交(consumed 关联 / 摘要 / 审计同事务)
+ defer_commit = bool(payload.get("defer_commit"))
if not isinstance(notice_items, list) or not notice_items:
- batch = create_batch(payload)
- db.session.commit()
+ batch, _created = create_batch(payload)
+ try:
+ if defer_commit:
+ db.session.flush()
+ else:
+ db.session.commit()
+ except IntegrityError as exc:
+ replay = handle_batch_create_integrity_error(
+ user_id=int(payload.get("user_id") or 0),
+ create_idempotency_key=idem_key,
+ exc=exc,
+ )
+ if replay is not None:
+ return replay
+ raise
return {
"status": "ok",
"batch_no": batch.batch_no,
@@ -250,13 +314,49 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
},
}
- batch = create_batch({**payload, "file_count": len(notice_items)})
+ notice_items = dedupe_notice_items_by_content_hash(notice_items)
+ content_hashes = [
+ str(item.get("source_content_hash") or "").strip().lower()
+ for item in notice_items
+ if isinstance(item, dict)
+ ]
+ if user_id is not None:
+ acquire_notice_create_locks(int(user_id), content_hashes)
+
+ request_fingerprint = compute_notice_items_content_fingerprint(notice_items)
+ if idem_key and user_id is not None:
+ existing_batch = find_batch_by_create_idempotency(int(user_id), idem_key)
+ if existing_batch:
+ assert_idempotent_batch_content_matches(existing_batch, notice_items)
+ return build_existing_batch_tool_response(existing_batch, user_id=int(user_id))
+
+ if user_id is not None:
+ assert_no_exact_duplicate_notices(int(user_id), notice_items)
+
+ batch, created_new = create_batch(
+ {
+ **payload,
+ "file_count": len(notice_items),
+ "create_content_fingerprint": request_fingerprint,
+ }
+ )
+ if not created_new:
+ if idem_key and user_id is not None:
+ assert_idempotent_batch_content_matches(batch, notice_items)
+ return build_existing_batch_tool_response(batch, user_id=int(user_id))
+ db.session.rollback()
+ raise ConflictError(
+ "批次已存在,禁止向已有批次重复追加任务",
+ code="SHIPPING.BATCH_IDEMPOTENCY_CONFLICT",
+ details={"batch_no": batch.batch_no},
+ )
db.session.flush()
created_tasks: list[dict[str, Any]] = []
total = len(notice_items)
for idx, item in enumerate(notice_items, start=1):
if not isinstance(item, dict):
continue
+ content_hash = str(item.get("source_content_hash") or "").strip().lower() or None
task = ShippingTask(
task_no=generate_task_no(),
batch_id=batch.id,
@@ -265,6 +365,16 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
source_type=str(item.get("source_type") or "manual"),
source_file_name=str(item.get("source_file_name") or "").strip() or None,
source_file_type=item.get("source_file_type"),
+ source_content_hash=content_hash,
+ source_asset_id=item.get("source_asset_id"),
+ source_intake_id=item.get("source_intake_id"),
+ business_fingerprint=str(item.get("business_fingerprint") or "").strip() or None,
+ fingerprint_version=str(item.get("fingerprint_version") or "").strip() or None,
+ document_version=int(item.get("document_version") or 1),
+ supersedes_task_id=item.get("supersedes_task_id"),
+ duplicate_source_task_id=item.get("duplicate_source_task_id"),
+ duplicate_override_reason=str(item.get("duplicate_override_reason") or "").strip() or None,
+ duplicate_resolution_type=str(item.get("duplicate_resolution_type") or "normal").strip() or "normal",
batch_index=idx,
batch_total=total,
raw_content=str(item.get("raw_text") or "").strip() or None,
@@ -272,7 +382,26 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
)
db.session.add(task)
log_task_event(task, "task_created", {"source_type": task.source_type, "batch_no": batch.batch_no})
- db.session.flush()
+ try:
+ db.session.flush()
+ except IntegrityError as exc:
+ db.session.rollback()
+ # 修订链唯一约束竞争:并发两个 create_revision 指向同一父任务
+ orig = str(getattr(exc, "orig", "") or exc)
+ if "supersedes" in orig.lower() or "uq_shipping_tasks_supersedes" in orig.lower():
+ raise ConflictError(
+ "目标任务已有修订版本,请打开已有修订或重新检测",
+ code="SHIPPING_NOTICE.REVISION_CONFLICT",
+ details={"supersedes_task_id": item.get("supersedes_task_id")},
+ ) from exc
+ replay = handle_batch_create_integrity_error(
+ user_id=int(payload.get("user_id") or 0),
+ create_idempotency_key=idem_key,
+ exc=exc,
+ )
+ if replay is not None:
+ return replay
+ raise
parse_payload: dict[str, Any] = {
"task_id": task.task_no,
"user_id": payload.get("user_id"),
@@ -307,7 +436,20 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
)
recompute_batch_summary(batch)
- db.session.commit()
+ try:
+ if defer_commit:
+ db.session.flush()
+ else:
+ db.session.commit()
+ except IntegrityError as exc:
+ replay = handle_batch_create_integrity_error(
+ user_id=int(payload.get("user_id") or 0),
+ create_idempotency_key=idem_key,
+ exc=exc,
+ )
+ if replay is not None:
+ return replay
+ raise
return {
"status": "ok",
"batch_no": batch.batch_no,
@@ -565,32 +707,126 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
)
- # [STEP 4] 低置信度停待人审;否则标记 parsed 并准备后续库存链路。
- if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7):
- if not _has_parse_review_content(task, lines):
- apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
- log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings})
- db.session.commit()
- message = (
- "未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本,"
- "或复制粘贴通知正文后重新解析。"
- )
- return tool_response(
- status="needs_human",
- task=task,
- message=message,
- data={**serialize_task_for_tool(task), "warnings": warnings},
- checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
- )
- apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
- log_task_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings})
- _upsert_parse_review_chat_message(task)
+ # [STEP 4] 无可审核内容时优先返回 notice_text_extraction_failed,不进入库存源裁决。
+ if not _has_parse_review_content(task, lines):
+ apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
+ log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings})
db.session.commit()
+ message = (
+ "未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本,"
+ "或复制粘贴通知正文后重新解析。"
+ )
return tool_response(
status="needs_human",
task=task,
- message=format_parse_summary(**summary_kwargs, low_confidence=True, payload=payload),
+ message=message,
data={**serialize_task_for_tool(task), "warnings": warnings},
+ checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
+ )
+
+ # [STEP 5] 先裁决库存源线索(写入 destination / 候选),但低置信度必须先走解析复核。
+ # 业务顺序:确认解析正确 → 再人工确认库存源 → 才允许库存/RPA。
+ low_confidence = confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7)
+ adjudication = adjudicate_and_apply_inventory_source(task)
+ source_stable = is_inventory_source_stable(task)
+
+ if low_confidence:
+ apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
+ log_task_event(
+ task,
+ "parse_needs_review",
+ {
+ "confidence": confidence,
+ "warnings": warnings,
+ "inventory_source_status": adjudication.status,
+ "inventory_source_stable": source_stable,
+ },
+ )
+ _upsert_parse_review_chat_message(task)
+ db.session.commit()
+ summary_text = format_parse_summary(**summary_kwargs, low_confidence=True, payload=payload)
+ if not source_stable:
+ summary_text = (
+ f"{summary_text}\n\n"
+ "解析确认通过后,若库存源仍无法唯一命中,将再请你选择正式库存源;"
+ "站点与库位将由系统根据配置自动填充。"
+ )
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message=summary_text,
+ data={
+ **serialize_task_for_tool(task),
+ "warnings": warnings,
+ "inventory_source_candidates": adjudication.candidates,
+ "inventory_source_status": adjudication.status,
+ "inventory_source_reason": adjudication.reason,
+ "destination_candidates": adjudication.destination_candidates,
+ },
+ stop_agent_turn=True,
+ forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
+ )
+
+ # [STEP 6] 解析已自动接受(高置信度);库存源未稳定时才进入库存源人工确认。
+ if not source_stable:
+ from app.services.shipping_notice.inventory_source_gate import transition_task_to_inventory_source_review
+
+ transition_task_to_inventory_source_review(
+ task,
+ adjudication,
+ error_message="无法根据发货通知唯一确定库存查询来源",
+ )
+ set_task_step_progress(
+ task,
+ step_key="step2_parse_confirm",
+ step_title="确认解析",
+ status="needs_human",
+ message="库存源待确认",
+ progress_percent=100,
+ detail="解析已通过,请确认本票应使用哪个库存源后继续。",
+ extra={"warnings": warnings, "inventory_source_status": adjudication.status},
+ )
+ log_task_event(
+ task,
+ "inventory_source_review_required",
+ {
+ "status": adjudication.status,
+ "reason": adjudication.reason,
+ "destination_candidates": adjudication.destination_candidates,
+ "candidate_source_codes": [item.get("source_code") for item in adjudication.candidates],
+ "warnings": warnings,
+ },
+ )
+ db.session.commit()
+ message_parts = [
+ "订单解析已通过,但库存源仍待确认:",
+ "- 无法根据发货通知唯一确定库存查询来源",
+ ]
+ for warning in warnings:
+ text = str(warning or "").strip()
+ if text:
+ message_parts.append(f"- {text}")
+ message_parts.extend(
+ [
+ "",
+ "请选择正式库存源后继续;站点与库位将由系统根据配置自动填充。",
+ ]
+ )
+ return tool_response(
+ status="needs_human",
+ task=task,
+ message="\n".join(message_parts),
+ data={
+ **serialize_task_for_tool(task),
+ "warnings": warnings,
+ "inventory_source_candidates": adjudication.candidates,
+ "inventory_source_status": adjudication.status,
+ "inventory_source_reason": adjudication.reason,
+ "destination_candidates": adjudication.destination_candidates,
+ },
+ checkpoint=CP_INVENTORY_SOURCE_REVIEW,
+ stop_agent_turn=True,
+ forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
)
apply_task_transition(task, TaskTransition.PARSED)
@@ -605,8 +841,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
include_confirmation_hint=not should_auto_continue,
)
- # [STEP 4] 高置信度解析后不在当前请求线程里继续串行推进。
- # 统一把后续库存/匹配/导出链路交给后台 worker,避免请求线程兼任主调度器。
+ # [STEP 7] 高置信度且库存源稳定:后续库存/匹配/导出交给后台 worker。
if should_auto_continue:
orchestrator_started = start_task_orchestrator(task.task_no)
merged_message = (
diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py
index abe23871..5e02a148 100644
--- a/backend/app/services/shipping_notice/tools.py
+++ b/backend/app/services/shipping_notice/tools.py
@@ -32,6 +32,7 @@ apply_inventory_mapping = inventory_workflow.apply_inventory_mapping
upload_inventory_file = inventory_workflow.upload_inventory_file
rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory
rpa_report_inventory_batch = inventory_rpa_workflow.rpa_report_inventory_batch
+repair_task_inventory_attachment = inventory_rpa_workflow.repair_task_inventory_attachment
confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source
# 履约阶段
diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py
index bbc27523..55860e91 100644
--- a/backend/app/services/shipping_notice/ui_state.py
+++ b/backend/app/services/shipping_notice/ui_state.py
@@ -2,8 +2,9 @@
services/shipping_notice/ui_state.py
用途:发货通知任务/批次 UI 状态读模型,作为 Chat 按钮、步骤条与工作台的统一状态来源。
-依赖:models.ShippingTask/ShippingBatch、state_machine、query_service。
-逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/action_buttons,再补充七步流程与用户可读摘要。
+依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants。
+逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/action_buttons,再补充七步流程与用户可读摘要;
+ 文件解析阶段额外汇总 summary.issues(解析复核 / RSV / 库存源门禁 + parse warnings)。
"""
from __future__ import annotations
@@ -29,6 +30,7 @@ from app.services.shipping_notice.constants import (
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_INV_UNAVAIL,
+ PH_INVENTORY_SOURCE_UNRESOLVED,
PH_MAP_INFER,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
@@ -39,6 +41,7 @@ from app.services.shipping_notice.constants import (
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
+from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
from app.services.shipping_notice.query_service import (
compute_batch_process_summary,
list_sorted_batch_tasks,
@@ -82,6 +85,7 @@ _TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"}
_BLOCKED_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
+ CP_INVENTORY_SOURCE_REVIEW,
CP_ALIGN_REVIEW,
RS_SHORTAGE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
@@ -129,7 +133,7 @@ def _derive_current_step_index(task: ShippingTask) -> int:
if process_status in {"parsed", "pending_review"} or review_status in {
RS_PARSE_REVIEW,
PH_RSV_REQ,
- } or pending_reason in {"low_confidence", PH_RSV_REQ}:
+ } or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}:
return 1
return 0
@@ -159,7 +163,11 @@ def build_shipping_workflow_steps(task: ShippingTask, checkpoint: str | None) ->
index == 2
and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
)
- if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked):
+ parse_blocked = index == 1 and (
+ checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED}
+ or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}
+ )
+ if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked):
status = "blocked"
steps.append({**step, "status": status})
return steps
@@ -173,7 +181,88 @@ def _action_buttons_for_task(task: ShippingTask) -> list[dict[str, str]]:
return ui.action_buttons
-def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, str | None]:
+_PARSE_STAGE_CHECKPOINTS = {
+ CP_PARSE_REVIEW,
+ CP_RSV_REQ,
+ CP_INVENTORY_SOURCE_REVIEW,
+ CP_NOTICE_TEXT_EXTRACTION_FAILED,
+}
+
+_WARNING_DISPLAY_ALIASES: dict[str, str] = {
+ "parse_fallback_heuristic": "解析引擎回退到启发式规则,请人工核对字段。",
+ "heuristic_no_lines_detected": "启发式解析未识别到订单行,请核对通知内容。",
+}
+
+
+def _normalize_issue_text(raw: Any) -> str:
+ """将 warnings / error 原文规范化为可展示短文案,过滤空值。"""
+ text = str(raw or "").strip()
+ if not text:
+ return ""
+ return _WARNING_DISPLAY_ALIASES.get(text, text)
+
+
+def _append_unique_issue(issues: list[str], raw: Any) -> None:
+ """追加去重后的问题文案,保持首次出现顺序。"""
+ text = _normalize_issue_text(raw)
+ if text and text not in issues:
+ issues.append(text)
+
+
+def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> list[str]:
+ """
+ 汇总文件解析阶段(步骤 2)全部待处理问题,供工作台一次列出。
+
+ 核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发;
+ 以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。
+ 新顺序为先解析复核再库存源;存量 pending_parse_review_after_source 仍提示延后复核。
+ """
+ checkpoint_value = str(checkpoint or "").strip()
+ if checkpoint_value not in _PARSE_STAGE_CHECKPOINTS:
+ return []
+
+ issues: list[str] = []
+ if checkpoint_value == CP_INVENTORY_SOURCE_REVIEW:
+ _append_unique_issue(
+ issues,
+ task.error_message or "无法根据发货通知唯一确定库存查询来源",
+ )
+ elif checkpoint_value == CP_RSV_REQ:
+ _append_unique_issue(
+ issues,
+ task.error_message or "解析失败:未识别到 Reservation ID / COM ID(预定单号)",
+ )
+ elif checkpoint_value == CP_NOTICE_TEXT_EXTRACTION_FAILED:
+ _append_unique_issue(
+ issues,
+ task.error_message or "未能从发货通知中解析到可审核内容",
+ )
+ elif checkpoint_value == CP_PARSE_REVIEW:
+ _append_unique_issue(issues, "通知单解析置信度不足,需要复核单头或明细。")
+ if not is_inventory_source_stable(task):
+ _append_unique_issue(
+ issues,
+ "解析确认通过后,若库存源仍无法唯一命中,还需选择正式库存源。",
+ )
+
+ payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
+ progress = payload.get("current_step_progress") if isinstance(payload, dict) else None
+ extra = progress.get("extra") if isinstance(progress, dict) else None
+ warnings = extra.get("warnings") if isinstance(extra, dict) else None
+ if isinstance(warnings, list):
+ for item in warnings:
+ _append_unique_issue(issues, item)
+
+ # 存量兼容:旧顺序「先库存源后解析」延后的低置信度提示。
+ if payload.get("pending_parse_review_after_source") or (
+ checkpoint_value == CP_INVENTORY_SOURCE_REVIEW and task.review_status == RS_PARSE_REVIEW
+ ):
+ _append_unique_issue(issues, "解析置信度不足,确认库存源后仍需复核解析结果。")
+
+ return issues
+
+
+def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, Any]:
"""输出用户可读任务摘要,供 Chat 文案与工作台卡片复用。"""
title = user_facing_task_stage(task)
message_by_checkpoint: dict[str, str] = {
@@ -181,7 +270,7 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str,
CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。",
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
- CP_INVENTORY_SOURCE_REVIEW: "库存查询来源不明确,需要先确认。",
+ CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。",
CP_MAP_INFER: "库存列映射需要确认或重新选择。",
CP_ALIGN_REVIEW: "库存字段对齐需要人工确认。",
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
@@ -194,10 +283,12 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str,
CP_UPLOADED: "任务已完成上传。",
CP_COMPLETED: "任务已关闭。",
}
+ issues = _collect_parse_stage_issues(task, checkpoint)
return {
"title": title,
"message": message_by_checkpoint.get(str(checkpoint or ""), title),
"error_message": task.error_message or task.upload_error_message,
+ "issues": issues,
}
diff --git a/backend/app/services/wecom_notify.py b/backend/app/services/wecom_notify.py
index af6f53fb..1f4232a0 100644
--- a/backend/app/services/wecom_notify.py
+++ b/backend/app/services/wecom_notify.py
@@ -29,12 +29,13 @@ def _get_enabled_events() -> set[str]:
def _get_notify_base_url() -> str:
"""
- 解析企微 textcard 跳转基地址。
- 核心逻辑:优先 WECOM_NOTIFY_BASE_URL,其次 WECOM_PUBLIC_BASE_URL。
+ 解析企微 textcard 跳转基地址(用户点击入口,须为浏览器可访问的 HTTPS 公网域名)。
+ 核心逻辑:优先 WECOM_PUBLIC_BASE_URL,其次 HXOPS_PUBLIC_BASE_URL;
+ WECOM_NOTIFY_BASE_URL 仅作历史内网/端口兼容兜底。
Returns:
去掉尾斜杠的基地址;均未配置时返回空字符串。
"""
- for key in ('WECOM_NOTIFY_BASE_URL', 'WECOM_PUBLIC_BASE_URL'):
+ for key in ('WECOM_PUBLIC_BASE_URL', 'HXOPS_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
raw = current_app.config.get(key)
if isinstance(raw, str) and raw.strip():
return raw.strip().rstrip('/')
diff --git a/backend/config/shipping_inventory_sources.yaml b/backend/config/shipping_inventory_sources.yaml
index b2fd1b75..9d21a02b 100644
--- a/backend/config/shipping_inventory_sources.yaml
+++ b/backend/config/shipping_inventory_sources.yaml
@@ -2,7 +2,7 @@
# 货代库存 RPA 源配置(新增 Warehouse 只改本文件,改后需重启后端)。
# 环境变量 SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG 可覆盖路径。
-version: 1
+version: 2
sources:
- source_code: DSV360_AWSBI_BYAWSATL01
display_name: DSV 360 / Bison / AWSBI / BYAWSATL01
@@ -537,6 +537,7 @@ sources:
enabled: true
source_type: dsv360
site_id: AWSCV
+ warehouse_id: AWSCV
display_name: DSV 360 / Cincinnati / AWSCV
entry_url: https://s360.dbschenker.com/
navigation:
@@ -552,6 +553,7 @@ sources:
enabled: true
source_type: dsv360
site_id: AWSDU
+ warehouse_id: AWSDU
display_name: DSV 360 / Dublin / AWSDU - Prod (JDA)
entry_url: https://s360.dbschenker.com/
navigation:
@@ -567,6 +569,7 @@ sources:
enabled: true
source_type: dsv360
site_id: AWSAMS
+ warehouse_id: RTM
display_name: DSV 360 / Moerdijk / AWSAMS
entry_url: https://s360.dbschenker.com/
navigation:
@@ -594,6 +597,7 @@ sources:
enabled: true
source_type: dsv360
site_id: AWSSL
+ warehouse_id: AWSSL
display_name: DSV 360 / Salt Lake City / AWSSL
entry_url: https://s360.dbschenker.com/
navigation:
@@ -609,6 +613,7 @@ sources:
enabled: true
source_type: dsv360
site_id: AWSSG
+ warehouse_id: AWSSG
display_name: DSV 360 / Singapore / AWSSG - Prod (JDA)
entry_url: https://s360.dbschenker.com/
navigation:
@@ -620,9 +625,12 @@ sources:
- SINGAPORE HUB
- SINGAPORE
- SG
+ - VMI-SIN
- source_code: CRANE
enabled: true
source_type: crane_footprint
+ site_id: CRANE
+ warehouse_resolution: alias_match
display_name: Crane FootPrint
entry_url: https://wms-portal.craneww.com/#/on-hand-details-query
navigation:
@@ -633,4 +641,8 @@ sources:
- TZR
- TZR2
- TZR3
+ allowed_warehouse_ids:
+ - TZR
+ - TZR2
+ - TZR3
diff --git a/backend/migrations/versions/a2b3c4d5e6f7_add_shipping_business_dedup_and_task_versions.py b/backend/migrations/versions/a2b3c4d5e6f7_add_shipping_business_dedup_and_task_versions.py
new file mode 100644
index 00000000..b31a4368
--- /dev/null
+++ b/backend/migrations/versions/a2b3c4d5e6f7_add_shipping_business_dedup_and_task_versions.py
@@ -0,0 +1,136 @@
+"""
+backend/migrations/versions/a2b3c4d5e6f7_add_shipping_business_dedup_and_task_versions.py
+
+用途:发货通知第三阶段业务去重字段、任务版本链与相关索引。
+依赖:Alembic revision c9d0e1f2a3b5。
+逻辑:为 shipping_notice_intakes / shipping_tasks 增加指纹与重复决策列;历史 document_version 回填为 1。
+
+Revision ID: a2b3c4d5e6f7
+Revises: c9d0e1f2a3b5
+Create Date: 2026-07-14 09:35:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "a2b3c4d5e6f7"
+down_revision = "c9d0e1f2a3b5"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ with op.batch_alter_table("shipping_notice_intakes", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("business_fingerprint", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("fingerprint_version", sa.String(length=32), nullable=True))
+ batch_op.add_column(sa.Column("fingerprint_strength", sa.String(length=32), nullable=True))
+ batch_op.add_column(
+ sa.Column(
+ "duplicate_status",
+ sa.String(length=32),
+ server_default="unchecked",
+ nullable=False,
+ )
+ )
+ batch_op.add_column(sa.Column("duplicate_matches_json", sa.JSON(), nullable=True))
+ batch_op.add_column(sa.Column("duplicate_checked_at", sa.DateTime(), nullable=True))
+ batch_op.add_column(sa.Column("duplicate_resolution", sa.String(length=32), nullable=True))
+ batch_op.add_column(sa.Column("duplicate_resolution_reason", sa.Text(), nullable=True))
+ batch_op.add_column(sa.Column("duplicate_target_task_no", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("duplicate_resolved_by_id", sa.Integer(), nullable=True))
+ batch_op.add_column(sa.Column("duplicate_resolved_at", sa.DateTime(), nullable=True))
+ batch_op.create_foreign_key(
+ "fk_shipping_notice_intakes_duplicate_resolved_by_id_users",
+ "users",
+ ["duplicate_resolved_by_id"],
+ ["id"],
+ )
+ batch_op.create_index(
+ "ix_shipping_notice_intakes_user_business_fingerprint",
+ ["user_id", "business_fingerprint"],
+ unique=False,
+ )
+ batch_op.create_index(
+ "ix_shipping_notice_intakes_duplicate_status_created",
+ ["duplicate_status", "created_at"],
+ unique=False,
+ )
+ batch_op.create_index(
+ "ix_shipping_notice_intakes_fp_version_fingerprint",
+ ["fingerprint_version", "business_fingerprint"],
+ unique=False,
+ )
+
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("business_fingerprint", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("fingerprint_version", sa.String(length=32), nullable=True))
+ batch_op.add_column(
+ sa.Column("document_version", sa.Integer(), server_default="1", nullable=False)
+ )
+ batch_op.add_column(sa.Column("supersedes_task_id", sa.Integer(), nullable=True))
+ batch_op.add_column(sa.Column("duplicate_source_task_id", sa.Integer(), nullable=True))
+ batch_op.add_column(sa.Column("duplicate_override_reason", sa.Text(), nullable=True))
+ batch_op.add_column(sa.Column("duplicate_resolution_type", sa.String(length=32), nullable=True))
+ batch_op.create_foreign_key(
+ "fk_shipping_tasks_supersedes_task_id",
+ "shipping_tasks",
+ ["supersedes_task_id"],
+ ["id"],
+ )
+ batch_op.create_foreign_key(
+ "fk_shipping_tasks_duplicate_source_task_id",
+ "shipping_tasks",
+ ["duplicate_source_task_id"],
+ ["id"],
+ )
+ batch_op.create_index(
+ "ix_shipping_tasks_user_business_fingerprint",
+ ["user_id", "business_fingerprint"],
+ unique=False,
+ )
+ batch_op.create_index("ix_shipping_tasks_supersedes_task_id", ["supersedes_task_id"], unique=False)
+ batch_op.create_index(
+ "ix_shipping_tasks_duplicate_source_task_id",
+ ["duplicate_source_task_id"],
+ unique=False,
+ )
+
+ op.execute("UPDATE shipping_tasks SET document_version = 1 WHERE document_version IS NULL")
+
+
+def downgrade() -> None:
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.drop_index("ix_shipping_tasks_duplicate_source_task_id")
+ batch_op.drop_index("ix_shipping_tasks_supersedes_task_id")
+ batch_op.drop_index("ix_shipping_tasks_user_business_fingerprint")
+ batch_op.drop_constraint("fk_shipping_tasks_duplicate_source_task_id", type_="foreignkey")
+ batch_op.drop_constraint("fk_shipping_tasks_supersedes_task_id", type_="foreignkey")
+ batch_op.drop_column("duplicate_resolution_type")
+ batch_op.drop_column("duplicate_override_reason")
+ batch_op.drop_column("duplicate_source_task_id")
+ batch_op.drop_column("supersedes_task_id")
+ batch_op.drop_column("document_version")
+ batch_op.drop_column("fingerprint_version")
+ batch_op.drop_column("business_fingerprint")
+
+ with op.batch_alter_table("shipping_notice_intakes", schema=None) as batch_op:
+ batch_op.drop_index("ix_shipping_notice_intakes_fp_version_fingerprint")
+ batch_op.drop_index("ix_shipping_notice_intakes_duplicate_status_created")
+ batch_op.drop_index("ix_shipping_notice_intakes_user_business_fingerprint")
+ batch_op.drop_constraint(
+ "fk_shipping_notice_intakes_duplicate_resolved_by_id_users",
+ type_="foreignkey",
+ )
+ batch_op.drop_column("duplicate_resolved_at")
+ batch_op.drop_column("duplicate_resolved_by_id")
+ batch_op.drop_column("duplicate_target_task_no")
+ batch_op.drop_column("duplicate_resolution_reason")
+ batch_op.drop_column("duplicate_resolution")
+ batch_op.drop_column("duplicate_checked_at")
+ batch_op.drop_column("duplicate_matches_json")
+ batch_op.drop_column("duplicate_status")
+ batch_op.drop_column("fingerprint_strength")
+ batch_op.drop_column("fingerprint_version")
+ batch_op.drop_column("business_fingerprint")
diff --git a/backend/migrations/versions/a6b7c8d9e0f1_add_intake_parse_lease.py b/backend/migrations/versions/a6b7c8d9e0f1_add_intake_parse_lease.py
new file mode 100644
index 00000000..bf7a93f8
--- /dev/null
+++ b/backend/migrations/versions/a6b7c8d9e0f1_add_intake_parse_lease.py
@@ -0,0 +1,34 @@
+"""
+backend/migrations/versions/a6b7c8d9e0f1_add_intake_parse_lease.py
+
+用途:为 ShippingNoticeIntake 增加 parse_lease,隔离超时回收前后的解析执行代次。
+依赖:Alembic revision f5a6b7c8d9e0。
+逻辑:upgrade 增加可空 parse_lease;downgrade 删除该列。
+
+Revision ID: a6b7c8d9e0f1
+Revises: f5a6b7c8d9e0
+Create Date: 2026-07-14 19:40:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "a6b7c8d9e0f1"
+down_revision = "f5a6b7c8d9e0"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ """增加 parse_lease 列。"""
+ op.add_column(
+ "shipping_notice_intakes",
+ sa.Column("parse_lease", sa.String(length=64), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ """删除 parse_lease 列。"""
+ op.drop_column("shipping_notice_intakes", "parse_lease")
diff --git a/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py b/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py
new file mode 100644
index 00000000..2c021722
--- /dev/null
+++ b/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py
@@ -0,0 +1,257 @@
+"""Add shipping inventory source gate independent fields.
+
+Purpose:
+ Move inventory source identity from step_payload_json to dedicated columns on
+ shipping_tasks, shipping_inventory_files, and shipping_task_inventory_links.
+Dependencies:
+ Alembic revision e2f3a4b5c6d7.
+Flow:
+ Order-parse gate writes task inventory fields; RPA/inventory/match stages
+ read the same columns for hard gate checks.
+
+Revision ID: b4c5d6e7f8a9
+Revises: e2f3a4b5c6d7
+Create Date: 2026-07-13 10:00:00.000000
+"""
+
+from __future__ import annotations
+
+import json
+
+import sqlalchemy as sa
+from alembic import op
+
+
+revision = "b4c5d6e7f8a9"
+down_revision = "e2f3a4b5c6d7"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ """Add inventory source gate columns and backfill legacy JSON where possible."""
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("destination_code", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("destination_city", sa.String(length=128), nullable=True))
+ batch_op.add_column(sa.Column("destination_country", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("warehouse_hint", sa.String(length=128), nullable=True))
+ batch_op.add_column(sa.Column("inventory_source_code", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("inventory_source_type", sa.String(length=32), nullable=True))
+ batch_op.add_column(sa.Column("inventory_site_id", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("inventory_warehouse_id", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("inventory_source_status", sa.String(length=32), nullable=True))
+ batch_op.add_column(sa.Column("inventory_source_method", sa.String(length=32), nullable=True))
+ batch_op.add_column(sa.Column("inventory_source_confirmed_by", sa.Integer(), nullable=True))
+ batch_op.add_column(sa.Column("inventory_source_confirmed_at", sa.DateTime(), nullable=True))
+ batch_op.add_column(sa.Column("inventory_source_config_version", sa.String(length=32), nullable=True))
+ batch_op.add_column(sa.Column("inventory_routing_fingerprint", sa.String(length=64), nullable=True))
+ batch_op.create_index("ix_shipping_tasks_inventory_source_code", ["inventory_source_code"], unique=False)
+ batch_op.create_index("ix_shipping_tasks_inventory_site_id", ["inventory_site_id"], unique=False)
+ batch_op.create_index("ix_shipping_tasks_inventory_source_status", ["inventory_source_status"], unique=False)
+ batch_op.create_index(
+ "ix_shipping_tasks_inventory_routing_fingerprint",
+ ["inventory_routing_fingerprint"],
+ unique=False,
+ )
+ batch_op.create_foreign_key(
+ "fk_shipping_tasks_inventory_source_confirmed_by_users",
+ "users",
+ ["inventory_source_confirmed_by"],
+ ["id"],
+ )
+
+ with op.batch_alter_table("shipping_inventory_files", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("site_id", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("source_config_version", sa.String(length=32), nullable=True))
+ batch_op.add_column(sa.Column("identity_status", sa.String(length=32), nullable=True))
+ batch_op.create_index("ix_shipping_inventory_files_site_id", ["site_id"], unique=False)
+ batch_op.create_index("ix_shipping_inventory_files_identity_status", ["identity_status"], unique=False)
+ batch_op.create_index(
+ "ix_shipping_inventory_files_source_site_wh",
+ ["source_code", "site_id", "warehouse_id"],
+ unique=False,
+ )
+
+ with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("matched_source_code", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("matched_site_id", sa.String(length=64), nullable=True))
+ batch_op.add_column(sa.Column("identity_check_status", sa.String(length=32), nullable=True))
+ batch_op.add_column(sa.Column("identity_checked_at", sa.DateTime(), nullable=True))
+ batch_op.create_index(
+ "ix_shipping_task_inventory_links_task_source",
+ ["task_id", "matched_source_code", "matched_site_id"],
+ unique=False,
+ )
+
+ _backfill_legacy_inventory_source()
+
+
+def _backfill_legacy_inventory_source() -> None:
+ """Migrate rpa_inventory_source from step_payload_json; legacy rows require re-verification."""
+ bind = op.get_bind()
+ legacy_config_version = "legacy-unverified"
+
+ rows = bind.execute(
+ sa.text(
+ "SELECT id, step_payload_json, pending_human_reason FROM shipping_tasks "
+ "WHERE step_payload_json IS NOT NULL"
+ )
+ ).fetchall()
+ for row in rows:
+ payload = row.step_payload_json
+ if not isinstance(payload, dict):
+ continue
+ source = payload.get("rpa_inventory_source")
+ if not isinstance(source, dict):
+ continue
+ source_code = str(source.get("source_code") or "").strip().upper()
+ if not source_code:
+ continue
+ site_id = str(source.get("site_id") or "").strip().upper() or None
+ warehouse_id = str(source.get("warehouse_id") or "").strip().upper() or None
+ source_type = str(source.get("source_type") or "").strip().lower() or None
+ resolution = payload.get("inventory_source_resolution")
+ status = "resolved"
+ method = "legacy_migrated"
+ routing_fingerprint = None
+ if isinstance(resolution, dict):
+ res_status = str(resolution.get("status") or "").strip()
+ routing_fingerprint = str(resolution.get("routing_fingerprint") or "").strip() or None
+ if res_status == "resolved":
+ status = "resolved"
+ method = "rule_exact"
+ elif res_status == "ambiguous":
+ status = "ambiguous"
+ elif res_status == "user_confirmed":
+ status = "user_confirmed"
+ method = "user_confirmed"
+
+ needs_review = False
+ if not site_id and warehouse_id:
+ # Historical bug: site_id was written into warehouse_id — cannot auto-fix.
+ status = "unresolved"
+ method = None
+ site_id = None
+ warehouse_id = None
+ source_code = None
+ source_type = None
+ needs_review = True
+ elif not site_id or not warehouse_id:
+ status = "unresolved"
+ method = None
+ source_code = None
+ source_type = None
+ site_id = None
+ warehouse_id = None
+ needs_review = True
+ elif not routing_fingerprint:
+ status = "unresolved"
+ method = None
+ needs_review = True
+
+ bind.execute(
+ sa.text(
+ "UPDATE shipping_tasks SET "
+ "inventory_source_code = :source_code, "
+ "inventory_source_type = :source_type, "
+ "inventory_site_id = :site_id, "
+ "inventory_warehouse_id = :warehouse_id, "
+ "inventory_source_status = :status, "
+ "inventory_source_method = :method, "
+ "inventory_source_config_version = :config_version, "
+ "inventory_routing_fingerprint = :routing_fingerprint "
+ "WHERE id = :task_id"
+ ),
+ {
+ "source_code": source_code,
+ "source_type": source_type,
+ "site_id": site_id,
+ "warehouse_id": warehouse_id,
+ "status": status,
+ "method": method,
+ "config_version": legacy_config_version,
+ "routing_fingerprint": routing_fingerprint,
+ "task_id": row.id,
+ },
+ )
+ if needs_review or status in {"ambiguous", "unresolved"}:
+ bind.execute(
+ sa.text(
+ "UPDATE shipping_tasks SET "
+ "pending_human_reason = 'inventory_source_unresolved', "
+ "current_step = 'step2_parse_confirm', "
+ "process_status = 'pending_review' "
+ "WHERE id = :task_id"
+ ),
+ {"task_id": row.id},
+ )
+
+ bind.execute(
+ sa.text(
+ "UPDATE shipping_tasks SET "
+ "pending_human_reason = 'inventory_source_unresolved', "
+ "current_step = 'step2_parse_confirm', "
+ "process_status = 'pending_review' "
+ "WHERE inventory_source_status IN ('ambiguous', 'unresolved', 'conflicted', 'invalid') "
+ "AND (pending_human_reason IS NULL OR pending_human_reason = '')"
+ )
+ )
+ bind.execute(
+ sa.text(
+ "UPDATE shipping_tasks SET "
+ "pending_human_reason = 'inventory_source_unresolved', "
+ "current_step = 'step2_parse_confirm', "
+ "process_status = 'pending_review' "
+ "WHERE inventory_source_config_version = 'legacy-unverified'"
+ )
+ )
+
+ file_rows = bind.execute(
+ sa.text("SELECT id, source_code, warehouse_id FROM shipping_inventory_files WHERE source_code IS NOT NULL")
+ ).fetchall()
+ for row in file_rows:
+ bind.execute(
+ sa.text(
+ "UPDATE shipping_inventory_files SET identity_status = 'unknown' WHERE id = :file_id"
+ ),
+ {"file_id": row.id},
+ )
+
+
+def downgrade():
+ """Remove inventory source gate columns."""
+ with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op:
+ batch_op.drop_index("ix_shipping_task_inventory_links_task_source")
+ batch_op.drop_column("identity_checked_at")
+ batch_op.drop_column("identity_check_status")
+ batch_op.drop_column("matched_site_id")
+ batch_op.drop_column("matched_source_code")
+
+ with op.batch_alter_table("shipping_inventory_files", schema=None) as batch_op:
+ batch_op.drop_index("ix_shipping_inventory_files_source_site_wh")
+ batch_op.drop_index("ix_shipping_inventory_files_identity_status")
+ batch_op.drop_index("ix_shipping_inventory_files_site_id")
+ batch_op.drop_column("identity_status")
+ batch_op.drop_column("source_config_version")
+ batch_op.drop_column("site_id")
+
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.drop_constraint("fk_shipping_tasks_inventory_source_confirmed_by_users", type_="foreignkey")
+ batch_op.drop_index("ix_shipping_tasks_inventory_routing_fingerprint")
+ batch_op.drop_index("ix_shipping_tasks_inventory_source_status")
+ batch_op.drop_index("ix_shipping_tasks_inventory_site_id")
+ batch_op.drop_index("ix_shipping_tasks_inventory_source_code")
+ batch_op.drop_column("inventory_routing_fingerprint")
+ batch_op.drop_column("inventory_source_config_version")
+ batch_op.drop_column("inventory_source_confirmed_at")
+ batch_op.drop_column("inventory_source_confirmed_by")
+ batch_op.drop_column("inventory_source_method")
+ batch_op.drop_column("inventory_source_status")
+ batch_op.drop_column("inventory_warehouse_id")
+ batch_op.drop_column("inventory_site_id")
+ batch_op.drop_column("inventory_source_type")
+ batch_op.drop_column("inventory_source_code")
+ batch_op.drop_column("warehouse_hint")
+ batch_op.drop_column("destination_country")
+ batch_op.drop_column("destination_city")
+ batch_op.drop_column("destination_code")
diff --git a/backend/migrations/versions/b7c8d9e0f1a2_jobs_parse_active_unique.py b/backend/migrations/versions/b7c8d9e0f1a2_jobs_parse_active_unique.py
new file mode 100644
index 00000000..cd6950b4
--- /dev/null
+++ b/backend/migrations/versions/b7c8d9e0f1a2_jobs_parse_active_unique.py
@@ -0,0 +1,145 @@
+"""
+backend/migrations/versions/b7c8d9e0f1a2_jobs_parse_active_unique.py
+
+用途:为 shipping_notice_parse 的 queued Job 增加部分唯一索引,防止并发双插。
+依赖:Alembic revision a6b7c8d9e0f1。
+逻辑:先合并历史重复 queued 预解析 Job,将 Intake.parse_job_id 重指 keep_id,
+ 再取消其余重复行;最后创建 uq_jobs_shipping_parse_queued_ref。
+ 故意不含 running,以便 retry 在旧 running 残留时可另建 queued。
+
+Revision ID: b7c8d9e0f1a2
+Revises: a6b7c8d9e0f1
+Create Date: 2026-07-14 20:00:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "b7c8d9e0f1a2"
+down_revision = "a6b7c8d9e0f1"
+branch_labels = None
+depends_on = None
+
+
+def _index_names(table: str) -> set[str]:
+ bind = op.get_bind()
+ inspector = sa.inspect(bind)
+ return {str(ix.get("name") or "") for ix in inspector.get_indexes(table)}
+
+
+def _retarget_intake_parse_job_ids(bind, *, keep_id: int, drop_ids: list[int]) -> None:
+ """
+ 将被取消 Job 上的 Intake.parse_job_id 重指向保留的 queued Job。
+
+ 须在取消 drop 行之前调用,避免升级后出现 queued 状态挂着 cancelled job_id。
+ """
+ for drop_id in drop_ids:
+ bind.execute(
+ sa.text(
+ """
+ UPDATE shipping_notice_intakes
+ SET parse_job_id = :keep_id,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE parse_job_id = :drop_id
+ """
+ ),
+ {"keep_id": int(keep_id), "drop_id": int(drop_id)},
+ )
+
+
+def _dedupe_queued_parse_jobs() -> None:
+ """同 domain/business_ref 的多条 queued 预解析 Job:保留最小 id,其余标 cancelled。"""
+ bind = op.get_bind()
+ groups = bind.execute(
+ sa.text(
+ """
+ SELECT domain, business_ref
+ FROM jobs
+ WHERE job_type = 'shipping_notice_parse'
+ AND status = 'queued'
+ AND business_ref IS NOT NULL
+ GROUP BY domain, business_ref
+ HAVING COUNT(*) > 1
+ """
+ )
+ ).fetchall()
+ for domain, business_ref in groups:
+ ids = [
+ int(row[0])
+ for row in bind.execute(
+ sa.text(
+ """
+ SELECT id
+ FROM jobs
+ WHERE domain = :domain
+ AND job_type = 'shipping_notice_parse'
+ AND business_ref = :business_ref
+ AND status = 'queued'
+ ORDER BY id ASC
+ """
+ ),
+ {"domain": str(domain), "business_ref": str(business_ref)},
+ ).fetchall()
+ ]
+ if len(ids) < 2:
+ continue
+ keep_id = ids[0]
+ drop_ids = ids[1:]
+ # [STEP 1] 先重指 Intake,再取消重复 Job,避免 parse_job_id 悬空
+ _retarget_intake_parse_job_ids(bind, keep_id=keep_id, drop_ids=drop_ids)
+ for drop_id in drop_ids:
+ bind.execute(
+ sa.text(
+ """
+ UPDATE jobs
+ SET status = 'cancelled',
+ message = '并发去重:合并 queued shipping_notice_parse',
+ progress = 100,
+ locked_by = NULL,
+ locked_at = NULL,
+ finished_at = CURRENT_TIMESTAMP,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE id = :drop_id
+ AND id <> :keep_id
+ AND status = 'queued'
+ """
+ ),
+ {"drop_id": drop_id, "keep_id": keep_id},
+ )
+
+
+def upgrade() -> None:
+ """去重后创建 shipping_notice_parse queued 部分唯一索引。"""
+ _dedupe_queued_parse_jobs()
+ # 兼容误建的旧名
+ for obsolete in ("uq_jobs_shipping_parse_active_ref", "uq_jobs_shipping_parse_queued_ref"):
+ if obsolete == "uq_jobs_shipping_parse_queued_ref":
+ continue
+ if obsolete in _index_names("jobs"):
+ op.drop_index(obsolete, table_name="jobs")
+ if "uq_jobs_shipping_parse_queued_ref" in _index_names("jobs"):
+ return
+ op.create_index(
+ "uq_jobs_shipping_parse_queued_ref",
+ "jobs",
+ ["domain", "job_type", "business_ref"],
+ unique=True,
+ postgresql_where=sa.text(
+ "job_type = 'shipping_notice_parse' "
+ "AND status = 'queued' "
+ "AND business_ref IS NOT NULL"
+ ),
+ sqlite_where=sa.text(
+ "job_type = 'shipping_notice_parse' "
+ "AND status = 'queued' "
+ "AND business_ref IS NOT NULL"
+ ),
+ )
+
+
+def downgrade() -> None:
+ """删除部分唯一索引。"""
+ if "uq_jobs_shipping_parse_queued_ref" in _index_names("jobs"):
+ op.drop_index("uq_jobs_shipping_parse_queued_ref", table_name="jobs")
diff --git a/backend/migrations/versions/c2d3e4f5a6b7_intake_idempotency_and_supersedes_unique.py b/backend/migrations/versions/c2d3e4f5a6b7_intake_idempotency_and_supersedes_unique.py
new file mode 100644
index 00000000..05b6cd67
--- /dev/null
+++ b/backend/migrations/versions/c2d3e4f5a6b7_intake_idempotency_and_supersedes_unique.py
@@ -0,0 +1,51 @@
+"""
+backend/migrations/versions/c2d3e4f5a6b7_intake_idempotency_and_supersedes_unique.py
+
+用途:intake 建单幂等键落库;任务 supersedes 唯一约束防并发双修订。
+依赖:Alembic revision a2b3c4d5e6f7。
+逻辑:shipping_notice_intakes.create_idempotency_key 支撑混合批次 /
+ 纯 open_existing 重放;shipping_tasks.supersedes_task_id 唯一保证线性版本链。
+
+Revision ID: c2d3e4f5a6b7
+Revises: a2b3c4d5e6f7
+Create Date: 2026-07-14 11:00:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "c2d3e4f5a6b7"
+down_revision = "a2b3c4d5e6f7"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ with op.batch_alter_table("shipping_notice_intakes", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("create_idempotency_key", sa.String(length=128), nullable=True))
+ batch_op.create_index(
+ "ix_shipping_notice_intakes_user_create_idempotency",
+ ["user_id", "create_idempotency_key"],
+ unique=False,
+ )
+
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.drop_index("ix_shipping_tasks_supersedes_task_id")
+ # PostgreSQL/SQLite:UNIQUE 允许多个 NULL,非空时每任务至多一个后继修订
+ batch_op.create_index(
+ "uq_shipping_tasks_supersedes_task_id",
+ ["supersedes_task_id"],
+ unique=True,
+ )
+
+
+def downgrade() -> None:
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.drop_index("uq_shipping_tasks_supersedes_task_id")
+ batch_op.create_index("ix_shipping_tasks_supersedes_task_id", ["supersedes_task_id"], unique=False)
+
+ with op.batch_alter_table("shipping_notice_intakes", schema=None) as batch_op:
+ batch_op.drop_index("ix_shipping_notice_intakes_user_create_idempotency")
+ batch_op.drop_column("create_idempotency_key")
diff --git a/backend/migrations/versions/c8d9e0f1a2b3_repair_intake_parse_job_id_after_dedupe.py b/backend/migrations/versions/c8d9e0f1a2b3_repair_intake_parse_job_id_after_dedupe.py
new file mode 100644
index 00000000..3c99d96d
--- /dev/null
+++ b/backend/migrations/versions/c8d9e0f1a2b3_repair_intake_parse_job_id_after_dedupe.py
@@ -0,0 +1,76 @@
+"""
+backend/migrations/versions/c8d9e0f1a2b3_repair_intake_parse_job_id_after_dedupe.py
+
+用途:修复已执行 b7c8d9e0f1a2 但未重指 parse_job_id 的环境。
+依赖:Alembic revision b7c8d9e0f1a2。
+逻辑:若 Intake.parse_job_id 指向已取消的 shipping_notice_parse Job,
+ 且同 (domain, business_ref) 仍有 queued 同伴,则重指到最小 queued id。
+
+Revision ID: c8d9e0f1a2b3
+Revises: b7c8d9e0f1a2
+Create Date: 2026-07-14 20:10:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "c8d9e0f1a2b3"
+down_revision = "b7c8d9e0f1a2"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ """将指向 cancelled 预解析 Job 的 Intake.parse_job_id 重指到同 domain 的 queued Job。"""
+ bind = op.get_bind()
+ rows = bind.execute(
+ sa.text(
+ """
+ SELECT i.id AS intake_id,
+ j.domain AS domain,
+ j.business_ref AS business_ref
+ FROM shipping_notice_intakes AS i
+ INNER JOIN jobs AS j ON j.id = i.parse_job_id
+ WHERE j.job_type = 'shipping_notice_parse'
+ AND j.status = 'cancelled'
+ AND j.business_ref IS NOT NULL
+ """
+ )
+ ).fetchall()
+ for intake_id, domain, business_ref in rows:
+ keep = bind.execute(
+ sa.text(
+ """
+ SELECT id
+ FROM jobs
+ WHERE domain = :domain
+ AND job_type = 'shipping_notice_parse'
+ AND status = 'queued'
+ AND business_ref = :business_ref
+ ORDER BY id ASC
+ LIMIT 1
+ """
+ ),
+ {"domain": str(domain), "business_ref": str(business_ref)},
+ ).fetchone()
+ if keep is None:
+ continue
+ bind.execute(
+ sa.text(
+ """
+ UPDATE shipping_notice_intakes
+ SET parse_job_id = :keep_id,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE id = :intake_id
+ AND parse_job_id IS NOT NULL
+ """
+ ),
+ {"keep_id": int(keep[0]), "intake_id": int(intake_id)},
+ )
+
+
+def downgrade() -> None:
+ """数据修复不可逆。"""
+ pass
diff --git a/backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py b/backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py
new file mode 100644
index 00000000..8e83f8fb
--- /dev/null
+++ b/backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py
@@ -0,0 +1,116 @@
+"""
+backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py
+
+用途:为平台 Job file-asset-cleanup 写入默认 ScheduleTask,使 TTL 清理按小时自动执行。
+依赖:Alembic revision f8a9b0c1d2e3;schedule_tasks / users 表已存在;croniter。
+逻辑:有用户则插入 SCH-FILE-ASSET-CLEANUP;无用户时跳过,由应用启动/建用户钩子补建。
+ next_run_at 按 Cron「0 * * * *」在 Asia/Shanghai 计算下次整点(与 ensure_* 对齐)。
+ downgrade 仅按本迁移固定 schedule_no 删除。
+
+Revision ID: c9d0e1f2a3b5
+Revises: f8a9b0c1d2e3
+Create Date: 2026-07-14 08:55:00.000000
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "c9d0e1f2a3b5"
+down_revision = "f8a9b0c1d2e3"
+branch_labels = None
+depends_on = None
+
+_SCHEDULE_NO = "SCH-FILE-ASSET-CLEANUP"
+_CRON_EXPR = "0 * * * *"
+_TZ_NAME = "Asia/Shanghai"
+
+
+def _compute_next_run_at_utc_naive() -> datetime:
+ """
+ 按「0 * * * *」+ Asia/Shanghai 计算下次整点,返回 UTC naive。
+ 与 app.services.schedule.timezone_util.compute_next_run_at 语义对齐。
+ """
+ try:
+ from croniter import croniter
+ from zoneinfo import ZoneInfo
+
+ tz = ZoneInfo(_TZ_NAME)
+ base = datetime.now(tz)
+ next_local = croniter(_CRON_EXPR, base).get_next(datetime)
+ if next_local.tzinfo is None:
+ next_local = next_local.replace(tzinfo=tz)
+ return next_local.astimezone(timezone.utc).replace(tzinfo=None)
+ except Exception:
+ # croniter/zoneinfo 不可用时退化:上海时区下一整点
+ tz = timezone(timedelta(hours=8))
+ now_local = datetime.now(tz)
+ next_local = now_local.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
+ return next_local.astimezone(timezone.utc).replace(tzinfo=None)
+
+
+def upgrade() -> None:
+ conn = op.get_bind()
+ exists = conn.execute(
+ sa.text(
+ "SELECT 1 FROM schedule_tasks "
+ "WHERE schedule_no = :sno OR platform_api_path = 'file-asset-cleanup' "
+ "LIMIT 1"
+ ),
+ {"sno": _SCHEDULE_NO},
+ ).first()
+ if exists:
+ return
+
+ owner = conn.execute(
+ sa.text("SELECT id FROM users WHERE role = 'admin' ORDER BY id ASC LIMIT 1")
+ ).first()
+ if owner is None:
+ owner = conn.execute(sa.text("SELECT id FROM users ORDER BY id ASC LIMIT 1")).first()
+ if owner is None:
+ # 空库无用户:留给 create_app / User after_commit 钩子补建
+ return
+
+ now = datetime.utcnow()
+ next_run = _compute_next_run_at_utc_naive()
+ conn.execute(
+ sa.text(
+ """
+ INSERT INTO schedule_tasks (
+ schedule_no, name, schedule_type, owner_user_id,
+ cron_expr, schedule_timezone, wait_seconds,
+ platform_api_path, job_params,
+ kb_sync_enabled, notify_enabled,
+ enabled, next_run_at, last_run_at,
+ created_by, updated_by, created_at, updated_at
+ ) VALUES (
+ :schedule_no, :name, 'platform_job', :owner_user_id,
+ :cron_expr, 'Asia/Shanghai', 0,
+ 'file-asset-cleanup', NULL,
+ false, false,
+ true, :next_run_at, NULL,
+ :owner_user_id, :owner_user_id, :now, :now
+ )
+ """
+ ),
+ {
+ "schedule_no": _SCHEDULE_NO,
+ "name": "临时文件资产 TTL 清理",
+ "owner_user_id": int(owner[0]),
+ "cron_expr": _CRON_EXPR,
+ "next_run_at": next_run,
+ "now": now,
+ },
+ )
+
+
+def downgrade() -> None:
+ """仅删除本迁移约定的 schedule_no,避免误删管理员手工创建的同路径排程。"""
+ conn = op.get_bind()
+ conn.execute(
+ sa.text("DELETE FROM schedule_tasks WHERE schedule_no = :sno"),
+ {"sno": _SCHEDULE_NO},
+ )
diff --git a/backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py b/backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py
new file mode 100644
index 00000000..31cea679
--- /dev/null
+++ b/backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py
@@ -0,0 +1,319 @@
+"""
+backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py
+
+用途:阶段二——FileAsset 派生字段、ShippingNoticeDocument/Candidate 表、Task.source_candidate_id。
+依赖:Alembic revision c2d3e4f5a6b7。
+逻辑:EML 附件子资产挂 parent_asset_id;文档/候选支撑「一邮件多订单」识别(不创建 Task)。
+ 升级幂等:本地若曾 create_all 已有 documents/candidates,则只补缺列/索引。
+
+Revision ID: d3e4f5a6b7c8
+Revises: c2d3e4f5a6b7
+Create Date: 2026-07-14 17:30:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "d3e4f5a6b7c8"
+down_revision = "c2d3e4f5a6b7"
+branch_labels = None
+depends_on = None
+
+
+def _table_names(insp: sa.Inspector) -> set[str]:
+ """返回当前 schema 下的表名集合。"""
+ return set(insp.get_table_names())
+
+
+def _table_columns(insp: sa.Inspector, table_name: str) -> set[str]:
+ """返回指定表的列名集合;表不存在时返回空集合。"""
+ if table_name not in _table_names(insp):
+ return set()
+ return {col["name"] for col in insp.get_columns(table_name)}
+
+
+def _index_names(insp: sa.Inspector, table_name: str) -> set[str]:
+ """返回指定表的索引名集合;表不存在时返回空集合。"""
+ if table_name not in _table_names(insp):
+ return set()
+ return {str(ix.get("name") or "") for ix in insp.get_indexes(table_name)}
+
+
+def _fk_names(insp: sa.Inspector, table_name: str) -> set[str]:
+ """返回指定表的外键约束名集合;表不存在时返回空集合。"""
+ if table_name not in _table_names(insp):
+ return set()
+ return {str(fk.get("name") or "") for fk in insp.get_foreign_keys(table_name)}
+
+
+def _ensure_file_asset_derived_columns() -> None:
+ """
+ 为 file_assets 补齐派生附件字段与索引。
+
+ 核心逻辑:列/外键/索引按存在性跳过,兼容 create_all 漂移库。
+ """
+ # [STEP 1] 探测已有列与索引
+ bind = op.get_bind()
+ insp = sa.inspect(bind)
+ cols = _table_columns(insp, "file_assets")
+ indexes = _index_names(insp, "file_assets")
+ fks = _fk_names(insp, "file_assets")
+
+ # [STEP 2] 缺什么补什么
+ with op.batch_alter_table("file_assets", schema=None) as batch_op:
+ if "parent_asset_id" not in cols:
+ batch_op.add_column(sa.Column("parent_asset_id", sa.Integer(), nullable=True))
+ if "asset_role" not in cols:
+ batch_op.add_column(
+ sa.Column("asset_role", sa.String(length=32), server_default="upload", nullable=False)
+ )
+ if "source_attachment_key" not in cols:
+ batch_op.add_column(sa.Column("source_attachment_key", sa.String(length=64), nullable=True))
+ if "fk_file_assets_parent_asset_id" not in fks:
+ batch_op.create_foreign_key(
+ "fk_file_assets_parent_asset_id",
+ "file_assets",
+ ["parent_asset_id"],
+ ["id"],
+ )
+ if "ix_file_assets_parent_asset_id" not in indexes:
+ batch_op.create_index("ix_file_assets_parent_asset_id", ["parent_asset_id"], unique=False)
+ if "ix_file_assets_parent_content_hash" not in indexes:
+ batch_op.create_index(
+ "ix_file_assets_parent_content_hash",
+ ["parent_asset_id", "content_hash"],
+ unique=False,
+ )
+ if "ix_file_assets_parent_attachment_key" not in indexes:
+ batch_op.create_index(
+ "ix_file_assets_parent_attachment_key",
+ ["parent_asset_id", "source_attachment_key"],
+ unique=False,
+ )
+
+
+def _ensure_shipping_notice_documents() -> None:
+ """
+ 确保 shipping_notice_documents 表及索引存在。
+
+ 核心逻辑:表已存在则只补缺索引,避免 DuplicateTable。
+ """
+ bind = op.get_bind()
+ insp = sa.inspect(bind)
+ if "shipping_notice_documents" not in _table_names(insp):
+ op.create_table(
+ "shipping_notice_documents",
+ sa.Column("id", sa.Integer(), nullable=False),
+ sa.Column("intake_id", sa.Integer(), nullable=False),
+ sa.Column("asset_id", sa.Integer(), nullable=True),
+ sa.Column("document_type", sa.String(length=32), nullable=False),
+ sa.Column("attachment_key", sa.String(length=64), nullable=False),
+ sa.Column("filename", sa.String(length=255), nullable=True),
+ sa.Column("content_hash", sa.String(length=64), nullable=True),
+ sa.Column("classification", sa.String(length=32), nullable=False),
+ sa.Column("parse_status", sa.String(length=32), nullable=False),
+ sa.Column("extracted_text", sa.Text(), nullable=True),
+ sa.Column("parse_warnings_json", sa.JSON(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), nullable=True),
+ sa.Column("updated_at", sa.DateTime(), nullable=True),
+ sa.ForeignKeyConstraint(["asset_id"], ["file_assets.id"]),
+ sa.ForeignKeyConstraint(["intake_id"], ["shipping_notice_intakes.id"]),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint(
+ "intake_id",
+ "attachment_key",
+ name="uq_shipping_notice_documents_intake_attachment_key",
+ ),
+ )
+
+ insp = sa.inspect(bind)
+ indexes = _index_names(insp, "shipping_notice_documents")
+ desired = {
+ "ix_shipping_notice_documents_intake_id": ["intake_id"],
+ "ix_shipping_notice_documents_asset_id": ["asset_id"],
+ "ix_shipping_notice_documents_content_hash": ["content_hash"],
+ "ix_shipping_notice_documents_parse_status": ["parse_status"],
+ "ix_shipping_notice_documents_created_at": ["created_at"],
+ }
+ for name, cols in desired.items():
+ if name not in indexes:
+ op.create_index(name, "shipping_notice_documents", cols, unique=False)
+
+
+def _ensure_shipping_notice_candidates() -> None:
+ """
+ 确保 shipping_notice_candidates 表及索引存在。
+
+ 核心逻辑:表已存在则只补缺索引,避免 DuplicateTable。
+ """
+ bind = op.get_bind()
+ insp = sa.inspect(bind)
+ if "shipping_notice_candidates" not in _table_names(insp):
+ op.create_table(
+ "shipping_notice_candidates",
+ sa.Column("id", sa.Integer(), nullable=False),
+ sa.Column("candidate_no", sa.String(length=64), nullable=False),
+ sa.Column("intake_id", sa.Integer(), nullable=False),
+ sa.Column("primary_document_id", sa.Integer(), nullable=False),
+ sa.Column("po_number", sa.String(length=128), nullable=True),
+ sa.Column("structured_result_json", sa.JSON(), nullable=True),
+ sa.Column("confidence", sa.Float(), nullable=True),
+ sa.Column(
+ "validation_status",
+ sa.String(length=32),
+ server_default="pending",
+ nullable=False,
+ ),
+ sa.Column("conflicts_json", sa.JSON(), nullable=True),
+ sa.Column("selected", sa.Boolean(), server_default=sa.text("true"), nullable=False),
+ sa.Column("business_fingerprint", sa.String(length=64), nullable=True),
+ sa.Column("fingerprint_version", sa.String(length=32), nullable=True),
+ sa.Column("fingerprint_strength", sa.String(length=32), nullable=True),
+ sa.Column(
+ "duplicate_status",
+ sa.String(length=32),
+ server_default="unchecked",
+ nullable=False,
+ ),
+ sa.Column("duplicate_matches_json", sa.JSON(), nullable=True),
+ sa.Column("duplicate_resolution", sa.String(length=32), nullable=True),
+ sa.Column("duplicate_resolution_reason", sa.Text(), nullable=True),
+ sa.Column("duplicate_target_task_no", sa.String(length=64), nullable=True),
+ sa.Column("duplicate_checked_at", sa.DateTime(), nullable=True),
+ sa.Column("consumed_task_id", sa.Integer(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), nullable=True),
+ sa.Column("updated_at", sa.DateTime(), nullable=True),
+ sa.ForeignKeyConstraint(["consumed_task_id"], ["shipping_tasks.id"]),
+ sa.ForeignKeyConstraint(["intake_id"], ["shipping_notice_intakes.id"]),
+ sa.ForeignKeyConstraint(["primary_document_id"], ["shipping_notice_documents.id"]),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint("candidate_no", name="uq_shipping_notice_candidates_candidate_no"),
+ sa.UniqueConstraint(
+ "intake_id",
+ "primary_document_id",
+ name="uq_shipping_notice_candidates_intake_primary_document",
+ ),
+ )
+
+ insp = sa.inspect(bind)
+ indexes = _index_names(insp, "shipping_notice_candidates")
+ desired = {
+ "ix_shipping_notice_candidates_intake_id": ["intake_id"],
+ "ix_shipping_notice_candidates_primary_document_id": ["primary_document_id"],
+ "ix_shipping_notice_candidates_po_number": ["po_number"],
+ "ix_shipping_notice_candidates_user_fingerprint": ["business_fingerprint"],
+ "ix_shipping_notice_candidates_duplicate_status": ["duplicate_status"],
+ "ix_shipping_notice_candidates_created_at": ["created_at"],
+ }
+ for name, cols in desired.items():
+ if name not in indexes:
+ op.create_index(name, "shipping_notice_candidates", cols, unique=False)
+
+
+def _ensure_task_source_candidate() -> None:
+ """
+ 为 shipping_tasks 补齐 source_candidate_id 及外键/索引。
+
+ 核心逻辑:列已存在则跳过,兼容部分应用过的漂移库。
+ """
+ bind = op.get_bind()
+ insp = sa.inspect(bind)
+ cols = _table_columns(insp, "shipping_tasks")
+ indexes = _index_names(insp, "shipping_tasks")
+ fks = _fk_names(insp, "shipping_tasks")
+
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ if "source_candidate_id" not in cols:
+ batch_op.add_column(sa.Column("source_candidate_id", sa.Integer(), nullable=True))
+ if "fk_shipping_tasks_source_candidate_id" not in fks:
+ batch_op.create_foreign_key(
+ "fk_shipping_tasks_source_candidate_id",
+ "shipping_notice_candidates",
+ ["source_candidate_id"],
+ ["id"],
+ )
+ if "ix_shipping_tasks_source_candidate_id" not in indexes:
+ batch_op.create_index(
+ "ix_shipping_tasks_source_candidate_id",
+ ["source_candidate_id"],
+ unique=False,
+ )
+
+
+def upgrade() -> None:
+ """
+ 应用阶段二 documents/candidates 结构;对已存在对象幂等跳过。
+
+ 核心逻辑:先补 FileAsset 派生字段,再建/补齐 Document·Candidate,最后挂 Task 外键。
+ """
+ _ensure_file_asset_derived_columns()
+ _ensure_shipping_notice_documents()
+ _ensure_shipping_notice_candidates()
+ _ensure_task_source_candidate()
+
+
+def downgrade() -> None:
+ """回滚阶段二结构;表/列不存在时依赖调用方环境保证对称。"""
+ bind = op.get_bind()
+ insp = sa.inspect(bind)
+ task_cols = _table_columns(insp, "shipping_tasks")
+ task_indexes = _index_names(insp, "shipping_tasks")
+ task_fks = _fk_names(insp, "shipping_tasks")
+
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ if "ix_shipping_tasks_source_candidate_id" in task_indexes:
+ batch_op.drop_index("ix_shipping_tasks_source_candidate_id")
+ if "fk_shipping_tasks_source_candidate_id" in task_fks:
+ batch_op.drop_constraint("fk_shipping_tasks_source_candidate_id", type_="foreignkey")
+ if "source_candidate_id" in task_cols:
+ batch_op.drop_column("source_candidate_id")
+
+ if "shipping_notice_candidates" in _table_names(insp):
+ cand_indexes = _index_names(insp, "shipping_notice_candidates")
+ for name in (
+ "ix_shipping_notice_candidates_created_at",
+ "ix_shipping_notice_candidates_duplicate_status",
+ "ix_shipping_notice_candidates_user_fingerprint",
+ "ix_shipping_notice_candidates_po_number",
+ "ix_shipping_notice_candidates_primary_document_id",
+ "ix_shipping_notice_candidates_intake_id",
+ ):
+ if name in cand_indexes:
+ op.drop_index(name, table_name="shipping_notice_candidates")
+ op.drop_table("shipping_notice_candidates")
+
+ insp = sa.inspect(bind)
+ if "shipping_notice_documents" in _table_names(insp):
+ doc_indexes = _index_names(insp, "shipping_notice_documents")
+ for name in (
+ "ix_shipping_notice_documents_created_at",
+ "ix_shipping_notice_documents_parse_status",
+ "ix_shipping_notice_documents_content_hash",
+ "ix_shipping_notice_documents_asset_id",
+ "ix_shipping_notice_documents_intake_id",
+ ):
+ if name in doc_indexes:
+ op.drop_index(name, table_name="shipping_notice_documents")
+ op.drop_table("shipping_notice_documents")
+
+ insp = sa.inspect(bind)
+ fa_cols = _table_columns(insp, "file_assets")
+ fa_indexes = _index_names(insp, "file_assets")
+ fa_fks = _fk_names(insp, "file_assets")
+ with op.batch_alter_table("file_assets", schema=None) as batch_op:
+ if "ix_file_assets_parent_attachment_key" in fa_indexes:
+ batch_op.drop_index("ix_file_assets_parent_attachment_key")
+ if "ix_file_assets_parent_content_hash" in fa_indexes:
+ batch_op.drop_index("ix_file_assets_parent_content_hash")
+ if "ix_file_assets_parent_asset_id" in fa_indexes:
+ batch_op.drop_index("ix_file_assets_parent_asset_id")
+ if "fk_file_assets_parent_asset_id" in fa_fks:
+ batch_op.drop_constraint("fk_file_assets_parent_asset_id", type_="foreignkey")
+ if "source_attachment_key" in fa_cols:
+ batch_op.drop_column("source_attachment_key")
+ if "asset_role" in fa_cols:
+ batch_op.drop_column("asset_role")
+ if "parent_asset_id" in fa_cols:
+ batch_op.drop_column("parent_asset_id")
diff --git a/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py b/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py
new file mode 100644
index 00000000..e4cbf07c
--- /dev/null
+++ b/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py
@@ -0,0 +1,276 @@
+"""
+backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py
+
+用途:RPA 回调幂等字段、快照去重与关联迁移、库存源/身份 CHECK 约束。
+依赖:Alembic revision b4c5d6e7f8a9。
+逻辑:回填 consumed_run_no → 去重并迁移链接 → 加 CHECK 与 ready 态部分唯一索引。
+
+Revision ID: d6e7f8a9b0c1
+Revises: b4c5d6e7f8a9
+Create Date: 2026-07-13 17:20:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "d6e7f8a9b0c1"
+down_revision = "b4c5d6e7f8a9"
+branch_labels = None
+depends_on = None
+
+_RPA_IDENTITY_READY_WHERE = (
+ "snapshot_status = 'ready' "
+ "AND rpa_run_no IS NOT NULL "
+ "AND source_code IS NOT NULL "
+ "AND site_id IS NOT NULL "
+ "AND warehouse_id IS NOT NULL"
+)
+
+
+def _json_consumed_run_no_expr(dialect_name: str) -> str:
+ """按方言生成从 step_payload_json 提取 consumed run_no 的 SQL 表达式。"""
+ if dialect_name == "postgresql":
+ return "step_payload_json->>'inventory_rpa_consumed_run_no'"
+ return "json_extract(step_payload_json, '$.inventory_rpa_consumed_run_no')"
+
+
+def _backfill_consumed_run_no(bind) -> None:
+ """将历史 step_payload_json 中的消费轮次回填到独立列。"""
+ expr = _json_consumed_run_no_expr(bind.dialect.name)
+ bind.execute(
+ sa.text(
+ f"""
+ UPDATE shipping_tasks
+ SET inventory_rpa_consumed_run_no = {expr}
+ WHERE inventory_rpa_consumed_run_no IS NULL
+ AND step_payload_json IS NOT NULL
+ AND {expr} IS NOT NULL
+ AND TRIM({expr}) != ''
+ """
+ )
+ )
+
+
+def _dedupe_duplicate_rpa_snapshots(bind) -> int:
+ """
+ 去重相同 RPA 四字段身份的快照(全状态),保留 ready 优先、id 最大的一条。
+ 核心逻辑:迁移关联引用后再过期淘汰记录,避免任务仍指向被淘汰快照。
+ """
+ groups = bind.execute(
+ sa.text(
+ """
+ SELECT rpa_run_no, source_code, site_id, warehouse_id, COUNT(*) AS cnt
+ FROM shipping_inventory_files
+ WHERE rpa_run_no IS NOT NULL AND TRIM(rpa_run_no) != ''
+ AND source_code IS NOT NULL AND TRIM(source_code) != ''
+ AND site_id IS NOT NULL AND TRIM(site_id) != ''
+ AND warehouse_id IS NOT NULL AND TRIM(warehouse_id) != ''
+ GROUP BY rpa_run_no, source_code, site_id, warehouse_id
+ HAVING COUNT(*) > 1
+ """
+ )
+ ).fetchall()
+
+ active_true = "TRUE" if bind.dialect.name == "postgresql" else "1"
+ inactive_false = "FALSE" if bind.dialect.name == "postgresql" else "0"
+ superseded = 0
+ for group in groups:
+ rows = bind.execute(
+ sa.text(
+ """
+ SELECT id
+ FROM shipping_inventory_files
+ WHERE rpa_run_no = :run_no
+ AND source_code = :source_code
+ AND site_id = :site_id
+ AND warehouse_id = :warehouse_id
+ ORDER BY
+ CASE snapshot_status WHEN 'ready' THEN 0 ELSE 1 END,
+ id DESC
+ """
+ ),
+ {
+ "run_no": group.rpa_run_no,
+ "source_code": group.source_code,
+ "site_id": group.site_id,
+ "warehouse_id": group.warehouse_id,
+ },
+ ).fetchall()
+ if len(rows) < 2:
+ continue
+ keeper_id = rows[0].id
+ for row in rows[1:]:
+ superseded_id = row.id
+ bind.execute(
+ sa.text(
+ f"""
+ UPDATE shipping_task_inventory_links
+ SET inventory_file_id = :keeper_id
+ WHERE inventory_file_id = :superseded_id
+ AND NOT EXISTS (
+ SELECT 1 FROM shipping_task_inventory_links existing
+ WHERE existing.task_id = shipping_task_inventory_links.task_id
+ AND existing.inventory_file_id = :keeper_id
+ AND existing.is_active = {active_true}
+ )
+ """
+ ),
+ {"keeper_id": keeper_id, "superseded_id": superseded_id},
+ )
+ bind.execute(
+ sa.text(
+ f"""
+ UPDATE shipping_task_inventory_links
+ SET is_active = {inactive_false}
+ WHERE inventory_file_id = :superseded_id
+ """
+ ),
+ {"superseded_id": superseded_id},
+ )
+ bind.execute(
+ sa.text(
+ """
+ UPDATE shipping_tasks
+ SET inventory_snapshot_id = :keeper_id
+ WHERE inventory_snapshot_id = :superseded_id
+ """
+ ),
+ {"keeper_id": keeper_id, "superseded_id": superseded_id},
+ )
+ bind.execute(
+ sa.text(
+ """
+ UPDATE shipping_inventory_files
+ SET snapshot_status = 'expired', updated_at = CURRENT_TIMESTAMP
+ WHERE id = :id
+ """
+ ),
+ {"id": superseded_id},
+ )
+ superseded += 1
+ return superseded
+
+
+def _sanitize_invalid_stable_inventory_sources(bind) -> None:
+ """将缺少完整身份字段的伪稳定任务降级为 unresolved,并清空过期身份残留。"""
+ bind.execute(
+ sa.text(
+ """
+ UPDATE shipping_tasks
+ SET inventory_source_status = 'unresolved',
+ inventory_source_code = NULL,
+ inventory_source_method = NULL,
+ inventory_source_type = NULL,
+ inventory_site_id = NULL,
+ inventory_warehouse_id = NULL,
+ inventory_source_config_version = NULL,
+ inventory_routing_fingerprint = NULL,
+ inventory_source_confirmed_by = NULL,
+ inventory_source_confirmed_at = NULL
+ WHERE inventory_source_status IN ('resolved', 'user_confirmed')
+ AND (
+ inventory_source_code IS NULL OR TRIM(inventory_source_code) = ''
+ OR inventory_site_id IS NULL OR TRIM(inventory_site_id) = ''
+ OR inventory_warehouse_id IS NULL OR TRIM(inventory_warehouse_id) = ''
+ OR inventory_source_config_version IS NULL OR TRIM(inventory_source_config_version) = ''
+ OR inventory_routing_fingerprint IS NULL OR TRIM(inventory_routing_fingerprint) = ''
+ )
+ """
+ )
+ )
+
+
+def _sanitize_invalid_identity_status(bind) -> None:
+ """将非法 identity_status 归一为 unknown。"""
+ bind.execute(
+ sa.text(
+ """
+ UPDATE shipping_inventory_files
+ SET identity_status = 'unknown'
+ WHERE identity_status IS NOT NULL
+ AND identity_status NOT IN ('pending', 'verified', 'mismatch', 'unknown')
+ """
+ )
+ )
+
+
+def _create_rpa_identity_ready_unique_index() -> None:
+ """仅对 ready 快照施加 RPA 身份唯一约束,允许历史 expired 记录共存。"""
+ op.execute(
+ sa.text(
+ f"""
+ CREATE UNIQUE INDEX uq_shipping_inventory_files_rpa_identity_ready
+ ON shipping_inventory_files (rpa_run_no, source_code, site_id, warehouse_id)
+ WHERE {_RPA_IDENTITY_READY_WHERE}
+ """
+ )
+ )
+
+
+def upgrade():
+ """回填消费轮次、去重快照、清洗数据并添加约束。"""
+ bind = op.get_bind()
+
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("inventory_rpa_consumed_run_no", sa.String(length=128), nullable=True))
+ batch_op.create_index(
+ "ix_shipping_tasks_inventory_rpa_consumed_run_no",
+ ["inventory_rpa_consumed_run_no"],
+ unique=False,
+ )
+
+ _backfill_consumed_run_no(bind)
+ _dedupe_duplicate_rpa_snapshots(bind)
+ _sanitize_invalid_stable_inventory_sources(bind)
+ _sanitize_invalid_identity_status(bind)
+
+ op.create_check_constraint(
+ "ck_shipping_tasks_inventory_source_status",
+ "shipping_tasks",
+ "inventory_source_status IS NULL OR inventory_source_status IN "
+ "('resolved', 'user_confirmed', 'ambiguous', 'unresolved', 'invalid', 'conflicted')",
+ )
+ op.create_check_constraint(
+ "ck_shipping_tasks_inventory_source_method",
+ "shipping_tasks",
+ "inventory_source_method IS NULL OR inventory_source_method IN "
+ "('rule_exact', 'rule_combined', 'user_confirmed', 'legacy_migrated', 'manual')",
+ )
+ op.create_check_constraint(
+ "ck_shipping_tasks_stable_inventory_identity",
+ "shipping_tasks",
+ "NOT (inventory_source_status IN ('resolved', 'user_confirmed') AND ("
+ "inventory_source_code IS NULL OR TRIM(inventory_source_code) = '' OR "
+ "inventory_site_id IS NULL OR TRIM(inventory_site_id) = '' OR "
+ "inventory_warehouse_id IS NULL OR TRIM(inventory_warehouse_id) = '' OR "
+ "inventory_source_config_version IS NULL OR TRIM(inventory_source_config_version) = '' OR "
+ "inventory_routing_fingerprint IS NULL OR TRIM(inventory_routing_fingerprint) = ''"
+ "))",
+ )
+ op.create_check_constraint(
+ "ck_shipping_inventory_files_identity_status",
+ "shipping_inventory_files",
+ "identity_status IS NULL OR identity_status IN ('pending', 'verified', 'mismatch', 'unknown')",
+ )
+ op.create_check_constraint(
+ "ck_shipping_inventory_files_snapshot_status",
+ "shipping_inventory_files",
+ "snapshot_status IS NULL OR snapshot_status IN ('ready', 'failed', 'expired')",
+ )
+
+ _create_rpa_identity_ready_unique_index()
+
+
+def downgrade():
+ """移除约束与 consumed run_no 列。"""
+ op.execute(sa.text("DROP INDEX IF EXISTS uq_shipping_inventory_files_rpa_identity_ready"))
+ op.drop_constraint("ck_shipping_inventory_files_snapshot_status", "shipping_inventory_files", type_="check")
+ op.drop_constraint("ck_shipping_inventory_files_identity_status", "shipping_inventory_files", type_="check")
+ op.drop_constraint("ck_shipping_tasks_stable_inventory_identity", "shipping_tasks", type_="check")
+ op.drop_constraint("ck_shipping_tasks_inventory_source_method", "shipping_tasks", type_="check")
+ op.drop_constraint("ck_shipping_tasks_inventory_source_status", "shipping_tasks", type_="check")
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.drop_index("ix_shipping_tasks_inventory_rpa_consumed_run_no")
+ batch_op.drop_column("inventory_rpa_consumed_run_no")
diff --git a/backend/migrations/versions/e4f5a6b7c8d9_stage2_idempotency_and_candidate_fk.py b/backend/migrations/versions/e4f5a6b7c8d9_stage2_idempotency_and_candidate_fk.py
new file mode 100644
index 00000000..2422874e
--- /dev/null
+++ b/backend/migrations/versions/e4f5a6b7c8d9_stage2_idempotency_and_candidate_fk.py
@@ -0,0 +1,225 @@
+"""
+backend/migrations/versions/e4f5a6b7c8d9_stage2_idempotency_and_candidate_fk.py
+
+用途:阶段二并发幂等与 Candidate/Document intake 一致性约束。
+依赖:Alembic revision d3e4f5a6b7c8。
+逻辑:合并重复派生资产 → 按 Document.asset_id 重算 reference_count/lifecycle →
+ 建立「未删除」部分唯一索引;Candidate 复合外键保证主文档同属该 Intake。
+
+Revision ID: e4f5a6b7c8d9
+Revises: d3e4f5a6b7c8
+Create Date: 2026-07-14 18:15:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "e4f5a6b7c8d9"
+down_revision = "d3e4f5a6b7c8"
+branch_labels = None
+depends_on = None
+
+
+def _drop_document_fk_on_candidates() -> None:
+ """删除 Candidate → Document 的旧单列外键(名称因库而异)。"""
+ bind = op.get_bind()
+ inspector = sa.inspect(bind)
+ for fk in inspector.get_foreign_keys("shipping_notice_candidates"):
+ cols = list(fk.get("constrained_columns") or [])
+ referred = str(fk.get("referred_table") or "")
+ if referred == "shipping_notice_documents" and cols == ["primary_document_id"]:
+ op.drop_constraint(fk["name"], "shipping_notice_candidates", type_="foreignkey")
+ return
+
+
+def _dedupe_derived_file_assets() -> None:
+ """
+ 合并同父同哈希的活派生资产,再建立唯一约束。
+
+ 核心逻辑:保留最小 id;Document.asset_id 重指向保留行;多余行 soft-delete。
+ """
+ bind = op.get_bind()
+ rows = bind.execute(
+ sa.text(
+ """
+ SELECT parent_asset_id, content_hash
+ FROM file_assets
+ WHERE parent_asset_id IS NOT NULL
+ AND deleted_at IS NULL
+ AND content_hash IS NOT NULL
+ GROUP BY parent_asset_id, content_hash
+ HAVING COUNT(*) > 1
+ """
+ )
+ ).fetchall()
+ for parent_asset_id, content_hash in rows:
+ ids = [
+ int(r[0])
+ for r in bind.execute(
+ sa.text(
+ """
+ SELECT id
+ FROM file_assets
+ WHERE parent_asset_id = :parent_id
+ AND content_hash = :content_hash
+ AND deleted_at IS NULL
+ ORDER BY id ASC
+ """
+ ),
+ {"parent_id": int(parent_asset_id), "content_hash": str(content_hash)},
+ ).fetchall()
+ ]
+ if len(ids) < 2:
+ continue
+ keep_id = ids[0]
+ for drop_id in ids[1:]:
+ bind.execute(
+ sa.text(
+ """
+ UPDATE shipping_notice_documents
+ SET asset_id = :keep_id
+ WHERE asset_id = :drop_id
+ """
+ ),
+ {"keep_id": keep_id, "drop_id": drop_id},
+ )
+ # 转为 orphan_cleanup + expired(deleted_at 保持 NULL),交给 cleanup 删 MinIO
+ bind.execute(
+ sa.text(
+ """
+ UPDATE file_assets
+ SET parent_asset_id = NULL,
+ asset_role = 'orphan_cleanup',
+ source_attachment_key = NULL,
+ lifecycle_status = 'expired',
+ reference_count = 0,
+ expires_at = CURRENT_TIMESTAMP,
+ deleted_at = NULL,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE id = :drop_id
+ """
+ ),
+ {"drop_id": drop_id},
+ )
+
+
+def _recompute_derived_reference_counts() -> None:
+ """
+ 按 shipping_notice_documents.asset_id 重算活派生资产的引用数与生命周期。
+
+ 核心逻辑:合并后保留行可能仍残留旧 reference_count;以 Document 关联边为准校正。
+ """
+ bind = op.get_bind()
+ dialect = str(getattr(bind.dialect, "name", "") or "")
+ expires_expr = (
+ "CURRENT_TIMESTAMP + INTERVAL '72 hours'"
+ if dialect == "postgresql"
+ else "datetime('now', '+72 hours')"
+ )
+ bind.execute(
+ sa.text(
+ f"""
+ UPDATE file_assets
+ SET
+ reference_count = (
+ SELECT COUNT(*)
+ FROM shipping_notice_documents AS d
+ WHERE d.asset_id = file_assets.id
+ ),
+ lifecycle_status = CASE
+ WHEN (
+ SELECT COUNT(*)
+ FROM shipping_notice_documents AS d
+ WHERE d.asset_id = file_assets.id
+ ) > 0 THEN 'referenced'
+ ELSE 'temporary'
+ END,
+ expires_at = CASE
+ WHEN (
+ SELECT COUNT(*)
+ FROM shipping_notice_documents AS d
+ WHERE d.asset_id = file_assets.id
+ ) > 0 THEN NULL
+ ELSE {expires_expr}
+ END,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE parent_asset_id IS NOT NULL
+ AND deleted_at IS NULL
+ AND asset_role = 'derived_attachment'
+ """
+ )
+ )
+
+
+def _index_names(table: str) -> set[str]:
+ bind = op.get_bind()
+ inspector = sa.inspect(bind)
+ return {str(ix.get("name") or "") for ix in inspector.get_indexes(table)}
+
+
+def upgrade() -> None:
+ names = _index_names("file_assets")
+ with op.batch_alter_table("file_assets", schema=None) as batch_op:
+ if "ix_file_assets_parent_content_hash" in names:
+ batch_op.drop_index("ix_file_assets_parent_content_hash")
+ if "uq_file_assets_parent_content_hash" in names:
+ batch_op.drop_index("uq_file_assets_parent_content_hash")
+
+ _dedupe_derived_file_assets()
+ _recompute_derived_reference_counts()
+
+ # PostgreSQL:仅未删除派生资产唯一;SQLite 同步 sqlite_where
+ names = _index_names("file_assets")
+ if "uq_file_assets_parent_content_hash_alive" not in names:
+ op.create_index(
+ "uq_file_assets_parent_content_hash_alive",
+ "file_assets",
+ ["parent_asset_id", "content_hash"],
+ unique=True,
+ postgresql_where=sa.text("deleted_at IS NULL AND parent_asset_id IS NOT NULL"),
+ sqlite_where=sa.text("deleted_at IS NULL AND parent_asset_id IS NOT NULL"),
+ )
+
+ with op.batch_alter_table("shipping_notice_documents", schema=None) as batch_op:
+ batch_op.create_unique_constraint(
+ "uq_shipping_notice_documents_id_intake",
+ ["id", "intake_id"],
+ )
+
+ _drop_document_fk_on_candidates()
+ with op.batch_alter_table("shipping_notice_candidates", schema=None) as batch_op:
+ batch_op.create_foreign_key(
+ "fk_shipping_notice_candidates_document_intake",
+ "shipping_notice_documents",
+ ["primary_document_id", "intake_id"],
+ ["id", "intake_id"],
+ )
+
+
+def downgrade() -> None:
+ with op.batch_alter_table("shipping_notice_candidates", schema=None) as batch_op:
+ batch_op.drop_constraint(
+ "fk_shipping_notice_candidates_document_intake",
+ type_="foreignkey",
+ )
+ batch_op.create_foreign_key(
+ "fk_shipping_notice_candidates_primary_document_id",
+ "shipping_notice_documents",
+ ["primary_document_id"],
+ ["id"],
+ )
+
+ with op.batch_alter_table("shipping_notice_documents", schema=None) as batch_op:
+ batch_op.drop_constraint("uq_shipping_notice_documents_id_intake", type_="unique")
+
+ names = _index_names("file_assets")
+ if "uq_file_assets_parent_content_hash_alive" in names:
+ op.drop_index("uq_file_assets_parent_content_hash_alive", table_name="file_assets")
+ with op.batch_alter_table("file_assets", schema=None) as batch_op:
+ batch_op.create_index(
+ "ix_file_assets_parent_content_hash",
+ ["parent_asset_id", "content_hash"],
+ unique=False,
+ )
diff --git a/backend/migrations/versions/e7f8a9b0c1d2_add_shipping_batch_creation_idempotency.py b/backend/migrations/versions/e7f8a9b0c1d2_add_shipping_batch_creation_idempotency.py
new file mode 100644
index 00000000..dfdf49c5
--- /dev/null
+++ b/backend/migrations/versions/e7f8a9b0c1d2_add_shipping_batch_creation_idempotency.py
@@ -0,0 +1,48 @@
+"""
+backend/migrations/versions/e7f8a9b0c1d2_add_shipping_batch_creation_idempotency.py
+
+用途:发货通知建单幂等键与源文件 SHA-256 内容哈希字段。
+依赖:Alembic revision d6e7f8a9b0c1。
+逻辑:shipping_batches.create_idempotency_key 唯一约束;shipping_tasks.source_content_hash 查询索引。
+
+Revision ID: e7f8a9b0c1d2
+Revises: d6e7f8a9b0c1
+Create Date: 2026-07-13 22:30:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "e7f8a9b0c1d2"
+down_revision = "d6e7f8a9b0c1"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ with op.batch_alter_table("shipping_batches", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("create_idempotency_key", sa.String(length=128), nullable=True))
+ batch_op.create_unique_constraint(
+ "uq_shipping_batches_user_create_idempotency",
+ ["user_id", "create_idempotency_key"],
+ )
+
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("source_content_hash", sa.String(length=64), nullable=True))
+ batch_op.create_index(
+ "ix_shipping_tasks_user_source_content_hash",
+ ["user_id", "source_content_hash"],
+ unique=False,
+ )
+
+
+def downgrade() -> None:
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.drop_index("ix_shipping_tasks_user_source_content_hash")
+ batch_op.drop_column("source_content_hash")
+
+ with op.batch_alter_table("shipping_batches", schema=None) as batch_op:
+ batch_op.drop_constraint("uq_shipping_batches_user_create_idempotency", type_="unique")
+ batch_op.drop_column("create_idempotency_key")
diff --git a/backend/migrations/versions/f5a6b7c8d9e0_file_asset_partial_unique_alive.py b/backend/migrations/versions/f5a6b7c8d9e0_file_asset_partial_unique_alive.py
new file mode 100644
index 00000000..0c7faddf
--- /dev/null
+++ b/backend/migrations/versions/f5a6b7c8d9e0_file_asset_partial_unique_alive.py
@@ -0,0 +1,181 @@
+"""
+backend/migrations/versions/f5a6b7c8d9e0_file_asset_partial_unique_alive.py
+
+用途:将派生资产全量唯一索引改为「未删除」部分唯一,并合并历史重复行。
+依赖:Alembic revision e4f5a6b7c8d9。
+逻辑:兼容已执行旧版 e4(创建 uq_file_assets_parent_content_hash)的环境;
+ 去重后按 Document 重算 reference_count;新装库若 e4 已建 partial index 则索引创建 no-op。
+ downgrade 恢复非唯一普通索引,避免软删除同键冲突。
+
+Revision ID: f5a6b7c8d9e0
+Revises: e4f5a6b7c8d9
+Create Date: 2026-07-14 19:30:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "f5a6b7c8d9e0"
+down_revision = "e4f5a6b7c8d9"
+branch_labels = None
+depends_on = None
+
+
+def _index_names(table: str) -> set[str]:
+ bind = op.get_bind()
+ inspector = sa.inspect(bind)
+ return {str(ix.get("name") or "") for ix in inspector.get_indexes(table)}
+
+
+def _dedupe_derived_file_assets() -> None:
+ """合并同父同哈希活记录:保留最小 id,重指向 Document,软删其余。"""
+ bind = op.get_bind()
+ rows = bind.execute(
+ sa.text(
+ """
+ SELECT parent_asset_id, content_hash
+ FROM file_assets
+ WHERE parent_asset_id IS NOT NULL
+ AND deleted_at IS NULL
+ AND content_hash IS NOT NULL
+ GROUP BY parent_asset_id, content_hash
+ HAVING COUNT(*) > 1
+ """
+ )
+ ).fetchall()
+ for parent_asset_id, content_hash in rows:
+ ids = [
+ int(r[0])
+ for r in bind.execute(
+ sa.text(
+ """
+ SELECT id
+ FROM file_assets
+ WHERE parent_asset_id = :parent_id
+ AND content_hash = :content_hash
+ AND deleted_at IS NULL
+ ORDER BY id ASC
+ """
+ ),
+ {"parent_id": int(parent_asset_id), "content_hash": str(content_hash)},
+ ).fetchall()
+ ]
+ if len(ids) < 2:
+ continue
+ keep_id = ids[0]
+ for drop_id in ids[1:]:
+ bind.execute(
+ sa.text(
+ """
+ UPDATE shipping_notice_documents
+ SET asset_id = :keep_id
+ WHERE asset_id = :drop_id
+ """
+ ),
+ {"keep_id": keep_id, "drop_id": drop_id},
+ )
+ # 转为 orphan_cleanup + expired(deleted_at 保持 NULL),交给 cleanup 删 MinIO
+ bind.execute(
+ sa.text(
+ """
+ UPDATE file_assets
+ SET parent_asset_id = NULL,
+ asset_role = 'orphan_cleanup',
+ source_attachment_key = NULL,
+ lifecycle_status = 'expired',
+ reference_count = 0,
+ expires_at = CURRENT_TIMESTAMP,
+ deleted_at = NULL,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE id = :drop_id
+ """
+ ),
+ {"drop_id": drop_id},
+ )
+
+
+def _recompute_derived_reference_counts() -> None:
+ """按 Document.asset_id 重算活派生资产引用数与 lifecycle/expires_at。"""
+ bind = op.get_bind()
+ dialect = str(getattr(bind.dialect, "name", "") or "")
+ expires_expr = (
+ "CURRENT_TIMESTAMP + INTERVAL '72 hours'"
+ if dialect == "postgresql"
+ else "datetime('now', '+72 hours')"
+ )
+ bind.execute(
+ sa.text(
+ f"""
+ UPDATE file_assets
+ SET
+ reference_count = (
+ SELECT COUNT(*)
+ FROM shipping_notice_documents AS d
+ WHERE d.asset_id = file_assets.id
+ ),
+ lifecycle_status = CASE
+ WHEN (
+ SELECT COUNT(*)
+ FROM shipping_notice_documents AS d
+ WHERE d.asset_id = file_assets.id
+ ) > 0 THEN 'referenced'
+ ELSE 'temporary'
+ END,
+ expires_at = CASE
+ WHEN (
+ SELECT COUNT(*)
+ FROM shipping_notice_documents AS d
+ WHERE d.asset_id = file_assets.id
+ ) > 0 THEN NULL
+ ELSE {expires_expr}
+ END,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE parent_asset_id IS NOT NULL
+ AND deleted_at IS NULL
+ AND asset_role = 'derived_attachment'
+ """
+ )
+ )
+
+
+def upgrade() -> None:
+ names = _index_names("file_assets")
+ if "uq_file_assets_parent_content_hash" in names:
+ op.drop_index("uq_file_assets_parent_content_hash", table_name="file_assets")
+
+ _dedupe_derived_file_assets()
+ _recompute_derived_reference_counts()
+
+ names = _index_names("file_assets")
+ if "uq_file_assets_parent_content_hash_alive" not in names:
+ op.create_index(
+ "uq_file_assets_parent_content_hash_alive",
+ "file_assets",
+ ["parent_asset_id", "content_hash"],
+ unique=True,
+ postgresql_where=sa.text("deleted_at IS NULL AND parent_asset_id IS NOT NULL"),
+ sqlite_where=sa.text("deleted_at IS NULL AND parent_asset_id IS NOT NULL"),
+ )
+
+
+def downgrade() -> None:
+ """
+ 降级:去掉部分唯一索引,恢复非唯一普通索引。
+
+ 核心逻辑:不恢复全量唯一——软删除与活记录可共享 (parent, hash),全量唯一会冲突。
+ """
+ names = _index_names("file_assets")
+ if "uq_file_assets_parent_content_hash_alive" in names:
+ op.drop_index("uq_file_assets_parent_content_hash_alive", table_name="file_assets")
+ if "uq_file_assets_parent_content_hash" in names:
+ op.drop_index("uq_file_assets_parent_content_hash", table_name="file_assets")
+ names = _index_names("file_assets")
+ if "ix_file_assets_parent_content_hash" not in names:
+ op.create_index(
+ "ix_file_assets_parent_content_hash",
+ "file_assets",
+ ["parent_asset_id", "content_hash"],
+ unique=False,
+ )
diff --git a/backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py b/backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py
new file mode 100644
index 00000000..f20fb8cf
--- /dev/null
+++ b/backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py
@@ -0,0 +1,157 @@
+"""
+backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py
+
+用途:第二阶段通用文件资产、发货通知接入记录及任务溯源字段。
+依赖:Alembic revision e7f8a9b0c1d2。
+逻辑:创建 file_assets / shipping_notice_intakes;shipping_tasks 增加 source_asset_id/source_intake_id。
+
+Revision ID: f8a9b0c1d2e3
+Revises: e7f8a9b0c1d2
+Create Date: 2026-07-14 00:30:00.000000
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "f8a9b0c1d2e3"
+down_revision = "e7f8a9b0c1d2"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "file_assets",
+ sa.Column("id", sa.Integer(), nullable=False),
+ sa.Column("asset_no", sa.String(length=64), nullable=False),
+ sa.Column("owner_user_id", sa.Integer(), nullable=False),
+ sa.Column("tenant_id", sa.String(length=64), nullable=True),
+ sa.Column("original_filename", sa.String(length=255), nullable=False),
+ sa.Column("storage_provider", sa.String(length=32), server_default="minio", nullable=False),
+ sa.Column("storage_bucket", sa.String(length=128), nullable=False),
+ sa.Column("storage_key", sa.String(length=512), nullable=False),
+ sa.Column("content_hash", sa.String(length=64), nullable=False),
+ sa.Column("file_size", sa.Integer(), nullable=False),
+ sa.Column("mime_type", sa.String(length=128), nullable=True),
+ sa.Column("extension", sa.String(length=32), nullable=True),
+ sa.Column("upload_status", sa.String(length=32), server_default="uploading", nullable=False),
+ sa.Column("lifecycle_status", sa.String(length=32), server_default="temporary", nullable=False),
+ sa.Column("reference_count", sa.Integer(), server_default="0", nullable=False),
+ sa.Column("expires_at", sa.DateTime(), nullable=True),
+ sa.Column("deleted_at", sa.DateTime(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), nullable=True),
+ sa.Column("updated_at", sa.DateTime(), nullable=True),
+ sa.ForeignKeyConstraint(["owner_user_id"], ["users.id"]),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint("asset_no", name="uq_file_assets_asset_no"),
+ )
+ op.create_index("ix_file_assets_owner_content_hash", "file_assets", ["owner_user_id", "content_hash"])
+ op.create_index("ix_file_assets_lifecycle_expires", "file_assets", ["lifecycle_status", "expires_at"])
+ op.create_index("ix_file_assets_owner_created", "file_assets", ["owner_user_id", "created_at"])
+ op.create_index(op.f("ix_file_assets_owner_user_id"), "file_assets", ["owner_user_id"], unique=False)
+
+ op.create_table(
+ "shipping_notice_intakes",
+ sa.Column("id", sa.Integer(), nullable=False),
+ sa.Column("intake_no", sa.String(length=64), nullable=False),
+ sa.Column("asset_id", sa.Integer(), nullable=False),
+ sa.Column("user_id", sa.Integer(), nullable=False),
+ sa.Column("conversation_id", sa.String(length=100), nullable=True),
+ sa.Column("purpose", sa.String(length=32), server_default="shipping_notice", nullable=False),
+ sa.Column("parse_status", sa.String(length=32), server_default="created", nullable=False),
+ sa.Column("extracted_text", sa.Text(), nullable=True),
+ sa.Column("structured_result_json", sa.JSON(), nullable=True),
+ sa.Column("parse_warnings_json", sa.JSON(), nullable=True),
+ sa.Column("parser_version", sa.String(length=32), nullable=False),
+ sa.Column("parse_job_id", sa.Integer(), nullable=True),
+ sa.Column("error_code", sa.String(length=64), nullable=True),
+ sa.Column("error_message", sa.Text(), nullable=True),
+ sa.Column("consumed_at", sa.DateTime(), nullable=True),
+ sa.Column("consumed_batch_id", sa.Integer(), nullable=True),
+ sa.Column("consumed_task_id", sa.Integer(), nullable=True),
+ sa.Column("expires_at", sa.DateTime(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), nullable=True),
+ sa.Column("updated_at", sa.DateTime(), nullable=True),
+ sa.ForeignKeyConstraint(["asset_id"], ["file_assets.id"]),
+ sa.ForeignKeyConstraint(["consumed_batch_id"], ["shipping_batches.id"]),
+ sa.ForeignKeyConstraint(["consumed_task_id"], ["shipping_tasks.id"]),
+ sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint("intake_no", name="uq_shipping_notice_intakes_intake_no"),
+ sa.UniqueConstraint(
+ "asset_id",
+ "purpose",
+ "parser_version",
+ name="uq_shipping_notice_intakes_asset_purpose_parser",
+ ),
+ )
+ op.create_index(
+ "ix_shipping_notice_intakes_user_conversation_created",
+ "shipping_notice_intakes",
+ ["user_id", "conversation_id", "created_at"],
+ )
+ op.create_index(
+ "ix_shipping_notice_intakes_parse_status_created",
+ "shipping_notice_intakes",
+ ["parse_status", "created_at"],
+ )
+ op.create_index("ix_shipping_notice_intakes_expires", "shipping_notice_intakes", ["expires_at"])
+ op.create_index(op.f("ix_shipping_notice_intakes_asset_id"), "shipping_notice_intakes", ["asset_id"], unique=False)
+ op.create_index(op.f("ix_shipping_notice_intakes_user_id"), "shipping_notice_intakes", ["user_id"], unique=False)
+ op.create_index(
+ op.f("ix_shipping_notice_intakes_parse_status"),
+ "shipping_notice_intakes",
+ ["parse_status"],
+ unique=False,
+ )
+ op.create_index(
+ op.f("ix_shipping_notice_intakes_parse_job_id"),
+ "shipping_notice_intakes",
+ ["parse_job_id"],
+ unique=False,
+ )
+
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("source_asset_id", sa.Integer(), nullable=True))
+ batch_op.add_column(sa.Column("source_intake_id", sa.Integer(), nullable=True))
+ batch_op.create_foreign_key(
+ "fk_shipping_tasks_source_asset_id_file_assets",
+ "file_assets",
+ ["source_asset_id"],
+ ["id"],
+ )
+ batch_op.create_foreign_key(
+ "fk_shipping_tasks_source_intake_id_shipping_notice_intakes",
+ "shipping_notice_intakes",
+ ["source_intake_id"],
+ ["id"],
+ )
+ batch_op.create_index("ix_shipping_tasks_source_asset_id", ["source_asset_id"], unique=False)
+ batch_op.create_index("ix_shipping_tasks_source_intake_id", ["source_intake_id"], unique=False)
+
+
+def downgrade() -> None:
+ with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
+ batch_op.drop_index("ix_shipping_tasks_source_intake_id")
+ batch_op.drop_index("ix_shipping_tasks_source_asset_id")
+ batch_op.drop_constraint("fk_shipping_tasks_source_intake_id_shipping_notice_intakes", type_="foreignkey")
+ batch_op.drop_constraint("fk_shipping_tasks_source_asset_id_file_assets", type_="foreignkey")
+ batch_op.drop_column("source_intake_id")
+ batch_op.drop_column("source_asset_id")
+
+ op.drop_index(op.f("ix_shipping_notice_intakes_parse_job_id"), table_name="shipping_notice_intakes")
+ op.drop_index(op.f("ix_shipping_notice_intakes_parse_status"), table_name="shipping_notice_intakes")
+ op.drop_index(op.f("ix_shipping_notice_intakes_user_id"), table_name="shipping_notice_intakes")
+ op.drop_index(op.f("ix_shipping_notice_intakes_asset_id"), table_name="shipping_notice_intakes")
+ op.drop_index("ix_shipping_notice_intakes_expires", table_name="shipping_notice_intakes")
+ op.drop_index("ix_shipping_notice_intakes_parse_status_created", table_name="shipping_notice_intakes")
+ op.drop_index("ix_shipping_notice_intakes_user_conversation_created", table_name="shipping_notice_intakes")
+ op.drop_table("shipping_notice_intakes")
+
+ op.drop_index(op.f("ix_file_assets_owner_user_id"), table_name="file_assets")
+ op.drop_index("ix_file_assets_owner_created", table_name="file_assets")
+ op.drop_index("ix_file_assets_lifecycle_expires", table_name="file_assets")
+ op.drop_index("ix_file_assets_owner_content_hash", table_name="file_assets")
+ op.drop_table("file_assets")
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 3c5e6d77..021fdd6d 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -1,4 +1,5 @@
import pytest
+from pathlib import Path
def parse_api_error(body: dict) -> dict:
@@ -50,7 +51,7 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
@pytest.fixture(autouse=True)
-def _shipping_notice_stable_auto_config(app, request):
+def _shipping_notice_stable_auto_config(app, request, monkeypatch):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
tmp_path = request.getfixturevalue("tmp_path")
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
@@ -61,11 +62,205 @@ def _shipping_notice_stable_auto_config(app, request):
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
+ lambda: None,
+ )
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
+ app.config["ENV_NAME"] = "dev"
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
+ from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
+
+ reset_rpa_worker_heartbeat_state_for_tests()
+ from app.services.shipping_notice.rpa_worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests
+
+ reset_rpa_worker_alert_state_for_tests()
+
+
+@pytest.fixture(autouse=True)
+def _shipping_test_default_destination(monkeypatch, request):
+ """
+ 为未提供目的地线索的发货通知单测注入 Dublin,以唯一命中 DSV360_AWSDU。
+ 标记 inventory_source_gate 的用例跳过,避免干扰库存源门禁专项测试。
+ """
+ if request.node.get_closest_marker("inventory_source_gate"):
+ return
+
+ from app.services.shipping_notice import extract as extract_mod
+ import app.services.shipping_notice.task_workflow as task_workflow_mod
+
+ original = extract_mod.extract_notice_fields
+
+ def _extract_with_default_destination(*args, structured=None, **kwargs):
+ patched = structured
+ if isinstance(structured, dict):
+ patched = dict(structured)
+ has_dest = any(
+ str(patched.get(key) or "").strip()
+ for key in ("ship_to", "destination_city", "destination_port", "destination_country", "warehouse_hint")
+ ) or isinstance(patched.get("destination"), dict)
+ if not has_dest:
+ for line in patched.get("lines") or []:
+ if isinstance(line, dict) and any(
+ str(line.get(key) or "").strip()
+ for key in ("ship_to", "destination_city", "destination_port", "warehouse_hint")
+ ):
+ has_dest = True
+ break
+ if not has_dest:
+ patched.setdefault("ship_to", "Dublin")
+ patched.setdefault("destination", {"city": "Dublin", "country": "IE"})
+ return original(*args, structured=patched, **kwargs)
+
+ monkeypatch.setattr(extract_mod, "extract_notice_fields", _extract_with_default_destination)
+ monkeypatch.setattr(task_workflow_mod, "extract_notice_fields", _extract_with_default_destination)
+
+
+def seed_task_inventory_source(
+ task: "ShippingTask",
+ *,
+ source_code: str = "DSV360_AWSDU",
+) -> None:
+ """测试辅助:为直接构造的 ShippingTask 写入稳定库存源独立字段。"""
+ from app.services.shipping_notice.inventory_source_rules import (
+ compute_routing_fingerprint,
+ extract_routing_context,
+ )
+ from app.services.shipping_notice.inventory_sources import (
+ get_inventory_source,
+ get_inventory_sources_config_version,
+ )
+
+ source = get_inventory_source(source_code)
+ if not source:
+ raise ValueError(f"unknown inventory source for tests: {source_code}")
+ from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
+
+ context = extract_routing_context(task)
+ resolution = resolve_inventory_source_identity(source, context)
+ if not resolution.ok or not resolution.identity:
+ raise ValueError(
+ f"cannot seed stable inventory source {source_code}: {resolution.reason or 'identity_incomplete'}"
+ )
+ identity = resolution.identity
+ task.inventory_source_code = identity.source_code
+ task.inventory_source_type = identity.source_type
+ task.inventory_site_id = identity.site_id
+ task.inventory_warehouse_id = identity.warehouse_id
+ task.inventory_source_status = "resolved"
+ task.inventory_source_method = "rule_exact"
+ task.inventory_source_config_version = get_inventory_sources_config_version()
+ task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
+
+
+def seed_rpa_inventory_trigger(
+ task: "ShippingTask",
+ *,
+ run_no: str = "RUN-TEST-001",
+ trigger_path: str | None = None,
+) -> None:
+ """测试辅助:写入 inventory_rpa_triggered 事件,供单任务回调 run_no 校验。"""
+ from app import db
+ from app.services.shipping_notice.tool_common import log_task_event
+
+ if task.id is None:
+ db.session.add(task)
+ db.session.flush()
+ trigger = trigger_path or f"inventory_export_batch_{run_no}.json"
+ log_task_event(
+ task,
+ "inventory_rpa_triggered",
+ {"trigger": trigger, "run_no": run_no, "attempt": 1, "manual_retry_round": False},
+ )
+
+
+def inventory_xlsx_with_warehouse(
+ warehouse_id: str,
+ *,
+ sku: str = "A001",
+ qty: int = 1,
+) -> "BytesIO":
+ """生成带 Warehouse ID 列的库存 Excel,供身份校验测试使用。"""
+ from io import BytesIO
+
+ from openpyxl import Workbook
+
+ buf = BytesIO()
+ wb = Workbook()
+ ws = wb.active
+ ws.append(["Warehouse ID", "SKU", "Qty"])
+ ws.append([warehouse_id, sku, qty])
+ wb.save(buf)
+ wb.close()
+ buf.seek(0)
+ return buf
+
+
+def inventory_csv_with_warehouse(
+ warehouse_id: str,
+ *,
+ sku: str = "A001",
+ qty: int = 1,
+ delimiter: str = ",",
+) -> "BytesIO":
+ """生成带 Warehouse ID 列的库存 CSV,供身份校验测试使用。"""
+ from io import BytesIO
+
+ buf = BytesIO()
+ content = f"Warehouse ID{delimiter}SKU{delimiter}Qty\n{warehouse_id}{delimiter}{sku}{delimiter}{qty}\n"
+ buf.write(content.encode("utf-8"))
+ buf.seek(0)
+ return buf
+
+
+def batch_rpa_item_identity(task: "ShippingTask") -> dict[str, str]:
+ """构造 batch 成功回调 item 须携带的 Worker 身份字段。"""
+ return {
+ "source_code": str(task.inventory_source_code or ""),
+ "site_id": str(task.inventory_site_id or ""),
+ "warehouse_id": str(task.inventory_warehouse_id or ""),
+ }
+
+
+def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
+ """构造定时 batch 成功回调 item 的四字段身份(与 YAML 配置一致)。"""
+ from app.services.shipping_notice.inventory_sources import get_inventory_source
+
+ source = get_inventory_source(source_code)
+ if not source:
+ raise ValueError(f"unknown inventory source for tests: {source_code}")
+ item = {
+ "source_code": source_code,
+ "site_id": str(source.get("site_id") or ""),
+ "warehouse_id": str(source.get("warehouse_id") or ""),
+ }
+ item.update(overrides)
+ return item
+
+
+def rpa_callback_payload(
+ task: "ShippingTask",
+ file_path: str | Path,
+ *,
+ run_no: str = "RUN-TEST-001",
+ status: str = "success",
+) -> dict:
+ """构造通过单任务 RPA 回调身份/run_no 校验的最小 payload。"""
+ return {
+ "task_id": task.task_no,
+ "status": status,
+ "file_path": str(file_path),
+ "run_no": run_no,
+ "source_code": task.inventory_source_code,
+ "site_id": task.inventory_site_id,
+ "warehouse_id": task.inventory_warehouse_id,
+ }
def pytest_configure(config):
@@ -75,7 +270,7 @@ def pytest_configure(config):
)
config.addinivalue_line(
"markers",
- "rpa_e2e: 真实货代 RPA 浏览器导出测试,默认跳过,需 FREIGHT_RPA_E2E=true",
+ "inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
)
diff --git a/backend/tests/services/admin/test_report_service.py b/backend/tests/services/admin/test_report_service.py
index 0fad4a53..9e1de5a5 100644
--- a/backend/tests/services/admin/test_report_service.py
+++ b/backend/tests/services/admin/test_report_service.py
@@ -1,7 +1,7 @@
"""
tests/services/admin/test_report_service.py
-用途:report_service 报表聚合单元测试。
+用途:report_service 报表聚合单元测试(使用分析含零使用低使用应用、应用运营、反馈)。
"""
from app import db
from app.models import Agent, ChatLog, Feedback, User
@@ -11,7 +11,13 @@ from app.services.admin import report_service
def test_build_usage_report(app):
with app.app_context():
agent = Agent(name='report-agent', type='api', dify_app_id='app-r', dify_api_key='key-r')
- user = User(username='report-user', email='report@example.com', role='user')
+ # 断言:by_user 需带回 real_name,便于管理端展示真实姓名
+ user = User(
+ username='report-user',
+ email='report@example.com',
+ role='user',
+ real_name='报表用户',
+ )
db.session.add_all([agent, user])
db.session.flush()
db.session.add(ChatLog(user_id=user.id, agent_id=agent.id, query='hi', answer='ok', tokens_used=1))
@@ -21,7 +27,40 @@ def test_build_usage_report(app):
assert data['total'] == 1
assert data['range'] == '30d'
assert data['by_user'][0]['username'] == 'report-user'
+ assert data['by_user'][0]['real_name'] == '报表用户'
assert data['by_agent'][0]['agent'] == 'report-agent'
+ assert data['by_day'][0]['count'] == 1
+
+
+def test_build_usage_report_low_agents_includes_zero_usage(app):
+ """
+ 低使用应用须含启用且零对话的 Agent(与应用运营零使用对齐)。
+ 断言:cold-app 出现在 low_agents 且 count=0;停用应用不计入。
+ """
+ with app.app_context():
+ used = Agent(name='hot-app', type='api', dify_app_id='app-hot', dify_api_key='key-hot', is_active=True)
+ cold = Agent(name='cold-app', type='api', dify_app_id='app-cold', dify_api_key='key-cold', is_active=True)
+ inactive = Agent(
+ name='off-app',
+ type='api',
+ dify_app_id='app-off',
+ dify_api_key='key-off',
+ is_active=False,
+ )
+ user = User(username='low-user', email='low@example.com', role='user')
+ db.session.add_all([used, cold, inactive, user])
+ db.session.flush()
+ db.session.add(ChatLog(user_id=user.id, agent_id=used.id, query='hi', answer='ok', tokens_used=1))
+ db.session.commit()
+
+ data = report_service.build_usage_report(user_page=1, user_page_size=10, range_key='30d')
+ # by_agent 仅含有对话的应用
+ assert all(item['agent'] != 'cold-app' for item in data['by_agent'])
+ low_names = {item['agent']: item['count'] for item in data['low_agents']}
+ assert low_names.get('cold-app') == 0
+ assert 'off-app' not in low_names
+ assert data['low_agent_max_chats'] == report_service.USAGE_LOW_AGENT_MAX_CHATS
+ assert data['low_agent_list_limit'] == report_service.USAGE_LOW_AGENT_LIST_LIMIT
def test_build_usage_report_excludes_outside_range(app):
@@ -51,11 +90,66 @@ def test_build_usage_report_excludes_outside_range(app):
def test_build_feedback_report(app):
with app.app_context():
- db.session.add(Feedback(score=5))
- db.session.add(Feedback(score=3))
+ agent = Agent(name='fb-agent', type='api', dify_app_id='app-fb', dify_api_key='key-fb')
+ user = User(username='fb-user', email='fb@example.com', role='user')
+ db.session.add_all([agent, user])
+ db.session.flush()
+ log1 = ChatLog(user_id=user.id, agent_id=agent.id, query='a', answer='b', tokens_used=1)
+ log2 = ChatLog(user_id=user.id, agent_id=agent.id, query='c', answer='d', tokens_used=1)
+ db.session.add_all([log1, log2])
+ db.session.flush()
+ db.session.add(Feedback(chat_log_id=log1.id, score=5))
+ db.session.add(Feedback(chat_log_id=log2.id, score=3))
db.session.commit()
data = report_service.build_feedback_report()
assert data['total'] == 2
assert data['avg_score'] == 4.0
assert len(data['distribution']) == 2
+
+
+def test_build_application_report(app):
+ """应用运营报表应聚合对话 / 授权 / 待审 / 评分,且不含配置敏感字段。"""
+ from app.models import PermissionRequest
+ from app.models.base import user_agent_permissions
+
+ with app.app_context():
+ hot = Agent(name='hot-app', type='api', dify_app_id='app-hot', dify_api_key='secret-key', is_active=True)
+ cold = Agent(name='cold-app', type='api', dify_app_id='app-cold', dify_api_key='secret-key-2', is_active=True)
+ user = User(username='app-ops-user', email='app-ops@example.com', role='user', real_name='运营用户')
+ db.session.add_all([hot, cold, user])
+ db.session.flush()
+ log = ChatLog(user_id=user.id, agent_id=hot.id, query='hi', answer='ok', tokens_used=10, latency=1200)
+ db.session.add(log)
+ db.session.flush()
+ db.session.add(Feedback(chat_log_id=log.id, score=4))
+ db.session.execute(
+ user_agent_permissions.insert().values(user_id=user.id, agent_id=hot.id)
+ )
+ db.session.add(
+ PermissionRequest(user_id=user.id, agent_id=cold.id, reason='need', status='pending')
+ )
+ db.session.commit()
+
+ data = report_service.build_application_report(range_key='30d', sort='chat_count', order='desc')
+ assert data['range'] == '30d'
+ assert data['summary']['agent_total'] >= 2
+ assert data['summary']['used_agents'] >= 1
+ assert data['summary']['unused_agents'] >= 1
+ assert data['summary']['pending_permission_total'] >= 1
+
+ by_name = {item['name']: item for item in data['items']}
+ assert 'hot-app' in by_name
+ assert by_name['hot-app']['chat_count'] == 1
+ assert by_name['hot-app']['unique_users'] == 1
+ assert by_name['hot-app']['authorized_users'] == 1
+ assert by_name['hot-app']['avg_score'] == 4.0
+ assert by_name['cold-app']['chat_count'] == 0
+ assert by_name['cold-app']['pending_requests'] == 1
+ # 断言:导出字段不含 API Key
+ assert 'dify_api_key' not in by_name['hot-app']
+ assert 'api_base_url' not in by_name['hot-app']
+
+ unused = report_service.build_application_report(range_key='30d', usage='unused')
+ assert all(item['chat_count'] == 0 for item in unused['items'])
+ assert any(item['name'] == 'cold-app' for item in unused['items'])
diff --git a/backend/tests/test_chat_turn_runtime.py b/backend/tests/test_chat_turn_runtime.py
index 9638903a..a4dbf619 100644
--- a/backend/tests/test_chat_turn_runtime.py
+++ b/backend/tests/test_chat_turn_runtime.py
@@ -201,3 +201,102 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkey
assert "run.started" in event_names
assert "run.completed" in event_names
assert "run.failed" not in event_names
+
+
+def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path):
+ """shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。"""
+ from io import BytesIO
+
+ user = _create_user()
+ agent = _create_shipping_agent()
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
+ captured: dict = {}
+
+ def fake_create(**kwargs):
+ captured.update(kwargs)
+ return {
+ "status": "ok",
+ "batch_no": "SB-CHAT-IDEM-001",
+ "data": {
+ "tasks": [{"task_id": "SN-CHAT-IDEM-001"}],
+ "focus_task": {"task_no": "SN-CHAT-IDEM-001"},
+ },
+ }
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items",
+ fake_create,
+ )
+
+ res = client.post(
+ "/api/chat/turns/stream",
+ headers={"X-Username": user.username, "X-Role": user.role},
+ data={
+ "agent_id": str(agent.id),
+ "input": json.dumps(
+ {
+ "type": "upload_followup",
+ "display_text": "上传发货通知:notice.txt",
+ "action_type": "shipping.create_batch_from_notices",
+ "payload": {"idempotency_key": "chat-idem-001"},
+ },
+ ensure_ascii=False,
+ ),
+ "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"),
+ },
+ content_type="multipart/form-data",
+ )
+ assert res.status_code == 200
+ res.get_data(as_text=True)
+ assert captured.get("create_idempotency_key") == "chat-idem-001"
+ notice_items = captured.get("notice_items") or []
+ assert notice_items
+ assert notice_items[0].get("source_content_hash")
+
+
+def test_chat_turn_create_batch_idempotent_replay(app, client, monkeypatch, tmp_path):
+ """相同幂等键重复 Chat Turn 不重复建批,并返回可恢复 UI state。"""
+ from io import BytesIO
+
+ user = _create_user()
+ agent = _create_shipping_agent()
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
+ orchestrator_calls: list[str] = []
+ monkeypatch.setattr(
+ "app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator",
+ lambda batch_no: orchestrator_calls.append(batch_no) or True,
+ )
+
+ payload_input = {
+ "type": "upload_followup",
+ "display_text": "上传发货通知:notice.txt",
+ "action_type": "shipping.create_batch_from_notices",
+ "payload": {"idempotency_key": "chat-replay-integration-001"},
+ }
+ headers = {"X-Username": user.username, "X-Role": user.role}
+ raw = "客户:ACME\nA001 x 10".encode("utf-8")
+
+ def _post_turn():
+ return client.post(
+ "/api/chat/turns/stream",
+ headers=headers,
+ data={
+ "agent_id": str(agent.id),
+ "input": json.dumps(payload_input, ensure_ascii=False),
+ "files": (BytesIO(raw), "notice.txt"),
+ },
+ content_type="multipart/form-data",
+ )
+
+ first = _post_turn()
+ assert first.status_code == 200
+ first_events = _parse_sse_events(first.get_data(as_text=True))
+ assert "run.failed" not in [item.get("event") for item in first_events]
+
+ second = _post_turn()
+ assert second.status_code == 200
+ second_events = _parse_sse_events(second.get_data(as_text=True))
+ completed = [item for item in second_events if item.get("event") == "message.completed"]
+ assert completed
+ assert "已恢复此前创建的批次" in str(completed[-1].get("content", ""))
+ assert len(orchestrator_calls) == 1
diff --git a/backend/tests/test_dify_workflow_reliability.py b/backend/tests/test_dify_workflow_reliability.py
index 858244fb..dc2ec2dc 100644
--- a/backend/tests/test_dify_workflow_reliability.py
+++ b/backend/tests/test_dify_workflow_reliability.py
@@ -271,3 +271,40 @@ def test_file_check_evaluate_exception_includes_error_type(monkeypatch):
assert payload["error_type"] == "http_403"
assert payload["retryable"] is False
assert payload["poll_used"] is False
+
+
+def test_merge_stream_answer_text_replaces_when_terminal_contains_streamed():
+ streamed = "检核完成,共处理 3 个文件,全部成功。"
+ terminal = streamed
+ merged = DifyService._merge_stream_answer_text(streamed, terminal)
+ assert merged == streamed
+ assert merged != streamed + terminal
+
+
+def test_merge_stream_answer_text_honors_replace_answer_flag():
+ streamed = "partial"
+ terminal = "final answer"
+ merged = DifyService._merge_stream_answer_text(streamed, terminal, replace_answer=True)
+ assert merged == "final answer"
+
+
+def test_merge_stream_answer_text_appends_non_overlapping_suffix():
+ merged = DifyService._merge_stream_answer_text("Hello", " world")
+ assert merged == "Hello world"
+
+
+def test_build_final_answer_text_dedupes_message_end_payload():
+ streamed_parts = ["检核", "完成。"]
+ data = {"answer": "检核完成。"}
+ result = DifyService._build_final_answer_text(
+ streamed_parts=streamed_parts,
+ data=data,
+ event_name="message_end",
+ )
+ assert result == "检核完成。"
+
+
+def test_dedupe_exact_doubled_text_fixes_historical_records():
+ doubled = "检核完成,共处理 3 个文件。" * 2
+ assert DifyService._dedupe_exact_doubled_text(doubled) == "检核完成,共处理 3 个文件。"
+ assert DifyService._dedupe_exact_doubled_text("unique answer") == "unique answer"
diff --git a/backend/tests/test_dsv_export_batch_smoke.py b/backend/tests/test_dsv_export_batch_smoke.py
new file mode 100644
index 00000000..8815199c
--- /dev/null
+++ b/backend/tests/test_dsv_export_batch_smoke.py
@@ -0,0 +1,74 @@
+"""scripts/rpa/dsv_export_batch_smoke.py 轻量单测(退出码与 REQUIRE_EXPORT 开关)。"""
+
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+
+
+def _repo_root() -> Path:
+ return Path(__file__).resolve().parents[2]
+
+
+def _load_dsv_export_batch_smoke():
+ module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_batch_smoke.py"
+ spec = importlib.util.spec_from_file_location("dsv_export_batch_smoke_under_test", module_path)
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _load_freight_rpa_worker():
+ module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
+ spec = importlib.util.spec_from_file_location("freight_rpa_worker_smoke_exit_test", module_path)
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_resolve_smoke_scenario_exit_code_all_skipped_default_passes():
+ """默认不要求导出时,全 skipped 应退出 0。"""
+ smoke = _load_dsv_export_batch_smoke()
+ worker = _load_freight_rpa_worker()
+ results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
+ summary = worker._summarize_inventory_batch_results(results)
+ assert smoke._resolve_smoke_scenario_exit_code(
+ results=results,
+ summary=summary,
+ require_export=False,
+ ) == 0
+
+
+def test_resolve_smoke_scenario_exit_code_all_skipped_require_export_fails():
+ """FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 时,全 skipped 应退出 2。"""
+ smoke = _load_dsv_export_batch_smoke()
+ worker = _load_freight_rpa_worker()
+ results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
+ summary = worker._summarize_inventory_batch_results(results)
+ assert summary["status"] == "success"
+ assert summary["has_success"] is False
+ assert smoke._resolve_smoke_scenario_exit_code(
+ results=results,
+ summary=summary,
+ require_export=True,
+ ) == 2
+
+
+def test_resolve_smoke_scenario_exit_code_has_success_with_require_export():
+ """require_export=true 但已有 success 导出时仍应退出 0。"""
+ smoke = _load_dsv_export_batch_smoke()
+ worker = _load_freight_rpa_worker()
+ results = [
+ {"source_code": "A", "status": "success", "success": True},
+ {"source_code": "B", "status": "skipped", "success": False, "skipped": True},
+ ]
+ summary = worker._summarize_inventory_batch_results(results)
+ assert smoke._resolve_smoke_scenario_exit_code(
+ results=results,
+ summary=summary,
+ require_export=True,
+ ) == 0
diff --git a/backend/tests/test_file_check_tools.py b/backend/tests/test_file_check_tools.py
index 73e76aec..7c0bb94e 100644
--- a/backend/tests/test_file_check_tools.py
+++ b/backend/tests/test_file_check_tools.py
@@ -503,6 +503,14 @@ def test_file_check_tool_requires_task_id(app, client):
assert res.status_code == 400
assert res.get_json()['error_code'] == 'task_id_required'
+ res_null = client.post(
+ '/api/file-check/tools/tasks/run',
+ headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
+ json={'task_id': None},
+ )
+ assert res_null.status_code == 400
+ assert res_null.get_json()['error_code'] == 'task_id_required'
+
def test_file_check_tool_rejects_invalid_task_id(app, client):
with app.app_context():
@@ -517,6 +525,77 @@ def test_file_check_tool_rejects_invalid_task_id(app, client):
assert res.get_json()['error_code'] == 'task_id_invalid'
+def test_file_check_tool_precheck_data_source_unavailable_on_runtime_error(app, client, monkeypatch):
+ """预检连接串构建失败时返回 503 data_source_unavailable,而非 500。"""
+ class _SqlConfig:
+ fetch_sql = 'SELECT 1'
+ data_source = None
+
+ monkeypatch.setattr(
+ 'app.api.file_check_tools.get_schedule_sql_config_by_task_id',
+ lambda _task_id: _SqlConfig(),
+ )
+ monkeypatch.setattr(
+ 'app.api.file_check_tools._build_srm_conn_str',
+ lambda: (_ for _ in ()).throw(RuntimeError('SRM_SQLSERVER_HOST is not configured')),
+ )
+
+ with app.app_context():
+ app.config['INTEGRATION_API_KEY'] = 'secret'
+ admin = _mk_admin()
+ db.session.commit()
+ task_id = _mk_check_task(admin.id).id
+
+ res = client.post(
+ '/api/file-check/tools/tasks/run',
+ headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
+ json={'task_id': task_id, 'trigger_source': 'dify_chatflow', 'user_message': '立即执行检核'},
+ )
+ assert res.status_code == 503
+ data = res.get_json()
+ assert data['ok'] is False
+ assert data['error_code'] == 'data_source_unavailable'
+ assert '数据源不可用' in data['message']
+
+
+def test_file_check_tool_precheck_data_source_unavailable_on_pyodbc_error(app, client, monkeypatch):
+ """预检 ODBC 连接失败时返回 503 data_source_unavailable。"""
+ pyodbc = pytest.importorskip('pyodbc')
+
+ class _SqlConfig:
+ fetch_sql = 'SELECT 1'
+ data_source = None
+
+ monkeypatch.setattr(
+ 'app.api.file_check_tools.get_schedule_sql_config_by_task_id',
+ lambda _task_id: _SqlConfig(),
+ )
+ monkeypatch.setattr(
+ 'app.api.file_check_tools._build_srm_conn_str',
+ lambda: 'DRIVER={SQL Server};SERVER=127.0.0.1;DATABASE=test;UID=u;PWD=p',
+ )
+ monkeypatch.setattr(
+ 'app.api.file_check_tools._fetch_records',
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(pyodbc.InterfaceError('IM002', 'driver not found')),
+ )
+
+ with app.app_context():
+ app.config['INTEGRATION_API_KEY'] = 'secret'
+ admin = _mk_admin()
+ db.session.commit()
+ task_id = _mk_check_task(admin.id).id
+
+ res = client.post(
+ '/api/file-check/tools/tasks/run',
+ headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
+ json={'task_id': task_id, 'trigger_source': 'dify_chatflow', 'user_message': '立即执行检核'},
+ )
+ assert res.status_code == 503
+ data = res.get_json()
+ assert data['ok'] is False
+ assert data['error_code'] == 'data_source_unavailable'
+
+
def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
class _Thread:
def __init__(self, *args, **kwargs):
@@ -921,6 +1000,94 @@ def test_workspace_file_check_active_run_returns_null_when_idle(app, client):
assert res.get_json()['run'] is None
+def test_file_check_tool_excel_download_uses_user_facing_base_url(app, client):
+ with app.app_context():
+ app.config['INTEGRATION_API_KEY'] = 'secret'
+ app.config['HXOPS_TOOLS_API_BASE'] = 'http://192.168.100.230:8890'
+ app.config['HXOPS_PUBLIC_BASE_URL'] = 'http://ai.well-trust.com:8890'
+ admin = _mk_admin()
+ db.session.commit()
+ task = _mk_check_task(admin.id)
+ run = ScheduleRun(
+ run_no='RUN-ROHS-EXCEL-DOMAIN',
+ schedule_task_id=task.id,
+ status='success',
+ trigger_type='manual',
+ excel_file_name='result.xlsx',
+ excel_file_data=b'xlsx-bytes',
+ excel_file_size=10,
+ )
+ db.session.add(run)
+ db.session.commit()
+ run_id = run.id
+
+ query_res = client.get(f'/api/file-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
+ download_url = query_res.get_json()['run']['excel']['download_url']
+ assert download_url.startswith('http://ai.well-trust.com:8890/api/file-check/tools/runs/')
+ assert '192.168.100.230' not in download_url
+
+
+def test_file_check_tool_excel_download_works_without_tool_api_key(app, client):
+ """浏览器 Excel 下载仅依赖 JWT,不应要求 INTEGRATION_API_KEY 已配置。"""
+ with app.app_context():
+ app.config['FILE_CHECK_TOOL_API_KEY'] = ''
+ app.config['INTEGRATION_API_KEY'] = ''
+ app.config['SECRET_KEY'] = 'download-signing-secret'
+ admin = _mk_admin()
+ db.session.commit()
+ task = _mk_check_task(admin.id)
+ run = ScheduleRun(
+ run_no='RUN-ROHS-EXCEL-NO-KEY',
+ schedule_task_id=task.id,
+ status='success',
+ trigger_type='manual',
+ excel_file_name='result.xlsx',
+ excel_file_data=b'xlsx-bytes',
+ excel_file_size=10,
+ )
+ db.session.add(run)
+ db.session.commit()
+ run_id = run.id
+
+ query_res = client.get(f'/api/file-check/tools/runs/{run_id}')
+ assert query_res.status_code == 503
+
+ with app.app_context():
+ run = db.session.get(ScheduleRun, run_id)
+ from app.api.file_check_tools import _build_excel_download_url
+
+ download_url = _build_excel_download_url(run)
+ download_path = download_url[download_url.index('/api/file-check'):]
+
+ res = client.get(download_path)
+ assert res.status_code == 200
+ assert res.data == b'xlsx-bytes'
+
+
+def test_file_check_tool_excel_download_invalid_token_returns_invalid_auth(app, client):
+ with app.app_context():
+ app.config['SECRET_KEY'] = 'download-signing-secret'
+ admin = _mk_admin()
+ db.session.commit()
+ task = _mk_check_task(admin.id)
+ run = ScheduleRun(
+ run_no='RUN-ROHS-EXCEL-BAD-TOKEN',
+ schedule_task_id=task.id,
+ status='success',
+ trigger_type='manual',
+ excel_file_name='result.xlsx',
+ excel_file_data=b'xlsx-bytes',
+ excel_file_size=10,
+ )
+ db.session.add(run)
+ db.session.commit()
+ run_id = run.id
+
+ res = client.get(f'/api/file-check/tools/runs/{run_id}/excel?token=not-a-valid-token')
+ assert res.status_code == 401
+ assert res.get_json()['error_code'] == 'invalid_auth'
+
+
def test_file_check_tool_excel_download_uses_signed_token(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
diff --git a/backend/tests/test_freight_rpa_heartbeat.py b/backend/tests/test_freight_rpa_heartbeat.py
new file mode 100644
index 00000000..69553915
--- /dev/null
+++ b/backend/tests/test_freight_rpa_heartbeat.py
@@ -0,0 +1,62 @@
+"""freight_rpa_heartbeat 共享哨兵与 payload 单测。"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+
+
+def _load_freight_rpa_heartbeat_module():
+ rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "rpa"
+ if str(rpa_dir) not in sys.path:
+ sys.path.insert(0, str(rpa_dir))
+ module_path = rpa_dir / "freight_rpa_heartbeat.py"
+ spec = importlib.util.spec_from_file_location("freight_rpa_heartbeat_test", module_path)
+ module = importlib.util.module_from_spec(spec)
+ assert spec.loader is not None
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
+ module = _load_freight_rpa_heartbeat_module()
+
+ monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
+ payload = module.build_heartbeat_payload(
+ trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
+ drop_dir=r"C:\HxopsRpaTest\data\inventory_drop",
+ )
+ assert payload["shared_scope_id"] == "hxops-rpa-test-data"
+ assert payload["trigger_dir"] == r"C:\HxopsRpaTest\data\inventory_triggers"
+
+
+def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
+ module = _load_freight_rpa_heartbeat_module()
+ monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
+ monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False)
+ monkeypatch.setenv(
+ "FREIGHT_RPA_INVENTORY_TRIGGER_DIR",
+ r"C:\HxopsRpaTest\data\inventory_triggers",
+ )
+ assert module._resolve_shared_scope_id() == ""
+ monkeypatch.setenv(
+ "FREIGHT_RPA_INVENTORY_TRIGGER_DIR",
+ r"C:\mount\hxops-rpa-test-data\inventory_triggers",
+ )
+ assert module._resolve_shared_scope_id() == "hxops-rpa-test-data"
+
+
+def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
+ module = _load_freight_rpa_heartbeat_module()
+
+ trigger_dir = tmp_path / "inventory_triggers"
+ trigger_dir.mkdir()
+ monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
+ module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01")
+
+ sentinel = trigger_dir / ".hxops_rpa_shared_mount"
+ assert sentinel.is_file()
+ content = sentinel.read_text(encoding="utf-8")
+ assert "scope_id=hxops-rpa-test-data" in content
+ assert "host=WIN-RPA-01" in content
diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py
index 15ffaf0b..b5ea0613 100644
--- a/backend/tests/test_freight_rpa_worker.py
+++ b/backend/tests/test_freight_rpa_worker.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import importlib.util
import json
import os
+import re
import sys
from pathlib import Path
@@ -32,6 +33,16 @@ def _load_freight_rpa_worker():
return module
+def _load_dsv_export_batch_smoke():
+ module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_batch_smoke.py"
+ spec = importlib.util.spec_from_file_location("dsv_export_batch_smoke_worker_test", module_path)
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
"""构造库存导出 trigger 样本,避免测试依赖会被 worker 消费掉的仓库文件。"""
return {
@@ -69,9 +80,10 @@ def test_env_strips_wrapping_quotes(monkeypatch):
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
- """配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件。"""
+ """配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "logs" / "worker.log"
+ timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ")
monkeypatch.setenv("FREIGHT_RPA_LOG_FILE", str(log_path))
original_stdout = sys.stdout
@@ -91,10 +103,16 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
assert resolved == log_path
assert "hello stdout" in captured.out
assert "hello stderr" in captured.err
+ assert timestamp_pattern.search(captured.out)
+ assert timestamp_pattern.search(captured.err)
text = log_path.read_text(encoding="utf-8")
assert "[logging] tee enabled" in text
assert "hello stdout" in text
assert "hello stderr" in text
+ # 断言:每行非空日志均带 YYYY-MM-DD HH:MM:SS 前缀,便于长批次排障。
+ for line in text.splitlines():
+ if line.strip():
+ assert timestamp_pattern.match(line)
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
@@ -262,18 +280,17 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
assert trigger["rpa_inventory_source"]["query"]["program_label"] == "AWSDU - Prod (JDA)"
assert trigger["rpa_inventory_source"]["query"]["owner_code"] == "CADU-0000000100"
- assert callbacks == [
- (
- "/api/shipping-notice/rpa/inventory-ready",
- {
- "task_no": "SN-20260629-2EDADC77",
- "success": True,
- "file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
- "rpa_mode": "browser",
- "source_code": "DSV360_AWSDU",
- },
- )
- ]
+ assert len(callbacks) == 1
+ callback_path, callback_payload = callbacks[0]
+ assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
+ assert callback_payload == {
+ "task_no": "SN-20260629-2EDADC77",
+ "status": "success",
+ "success": True,
+ "file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
+ "rpa_mode": "browser",
+ "source_code": "DSV360_AWSDU",
+ }
assert not trigger_path.exists()
assert (processed_dir / trigger_path.name).is_file()
@@ -314,22 +331,153 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
assert rows[0] == ("料号", "可用数量")
assert rows[1] == ("A001", 100)
assert rows[2] == ("A002", 50)
- assert callbacks == [
- (
- "/api/shipping-notice/rpa/inventory-ready",
- {
- "task_no": "SN-20260629-2EDADC77",
- "success": True,
- "file_path": str(exported),
- "rpa_mode": "mock",
- "source_code": "DSV360_AWSDU",
- },
- )
- ]
+ assert len(callbacks) == 1
+ callback_path, callback_payload = callbacks[0]
+ assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
+ assert callback_payload == {
+ "task_no": "SN-20260629-2EDADC77",
+ "status": "success",
+ "success": True,
+ "file_path": str(exported),
+ "rpa_mode": "mock",
+ "source_code": "DSV360_AWSDU",
+ }
assert not trigger_path.exists()
assert (processed_dir / trigger_path.name).is_file()
+def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_path):
+ """DSV 无库存时应回调 status=skipped,而不是 failed。"""
+ worker = _load_freight_rpa_worker()
+ source_trigger = _build_inventory_export_trigger("SN-20260629-NO-STOCK")
+ trigger_dir = tmp_path / "inventory_triggers"
+ trigger_dir.mkdir()
+ trigger_path = trigger_dir / "inventory_export_SN-20260629-NO-STOCK.json"
+ trigger_path.write_text(json.dumps(source_trigger, ensure_ascii=False), encoding="utf-8")
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ processed_dir = trigger_dir / "processed"
+ callbacks: list[tuple[str, dict]] = []
+
+ def raise_no_inventory(_trigger: dict, _drop: Path):
+ raise worker.NoInventoryDataError("DSV report has no inventory data")
+
+ monkeypatch.setenv("FREIGHT_RPA_MOCK", "false")
+ monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory)
+ monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
+
+ worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
+
+ assert len(callbacks) == 1
+ callback_path, callback_payload = callbacks[0]
+ assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
+ assert callback_payload["status"] == "skipped"
+ assert callback_payload["success"] is False
+ assert callback_payload["skipped"] is True
+ assert callback_payload["skip_reason"] == "no_inventory_data"
+ assert callback_payload["message"] == "DSV report has no inventory data"
+ assert "error_message" not in callback_payload
+ assert not trigger_path.exists()
+
+
+def test_summarize_inventory_batch_results_all_skipped():
+ """全 skipped 时 batch 顶层 legacy success 应为 true,status 为 success。"""
+ worker = _load_freight_rpa_worker()
+ summary = worker._summarize_inventory_batch_results([
+ {"source_code": "A", "status": "skipped", "success": False, "skipped": True},
+ {"source_code": "B", "status": "skipped", "success": False, "skipped": True},
+ ])
+ assert summary["status"] == "success"
+ assert summary["success"] is True
+ assert summary["has_success"] is False
+ assert summary["skipped_count"] == 2
+ assert summary["failed_count"] == 0
+
+
+def test_summarize_inventory_batch_results_partial_failed():
+ """存在 failed 但有 success/skipped 时 legacy success 仍为 true,status=partial_failed。"""
+ worker = _load_freight_rpa_worker()
+ summary = worker._summarize_inventory_batch_results([
+ {"source_code": "A", "status": "success", "success": True},
+ {"source_code": "B", "status": "failed", "success": False},
+ ])
+ assert summary["status"] == "partial_failed"
+ assert summary["success"] is True
+ assert summary["has_success"] is True
+ assert summary["success_count"] == 1
+ assert summary["failed_count"] == 1
+
+
+def test_summarize_inventory_batch_results_empty():
+ """空 results 应返回全 0 计数,避免 helper 复用时 KeyError。"""
+ worker = _load_freight_rpa_worker()
+ summary = worker._summarize_inventory_batch_results([])
+ assert summary == {
+ "status": "failed",
+ "success": False,
+ "has_success": False,
+ "success_count": 0,
+ "skipped_count": 0,
+ "failed_count": 0,
+ }
+
+
+def test_summarize_inventory_batch_results_skipped_and_failed():
+ """仅有 skipped+failed 时 legacy success 为 true(skipped 算已处理)。"""
+ worker = _load_freight_rpa_worker()
+ summary = worker._summarize_inventory_batch_results([
+ {"source_code": "A", "status": "skipped", "success": False, "skipped": True},
+ {"source_code": "B", "status": "failed", "success": False},
+ ])
+ assert summary["status"] == "partial_failed"
+ assert summary["success"] is True
+ assert summary["has_success"] is False
+ assert summary["skipped_count"] == 1
+ assert summary["failed_count"] == 1
+
+
+def test_summarize_inventory_batch_item_empty_dict_counts_as_failed():
+ """batch 归一化对空 dict 应算 failed,避免缺字段误计 success。"""
+ worker = _load_freight_rpa_worker()
+ assert worker._normalize_inventory_batch_item_status({}) == "failed"
+ summary = worker._summarize_inventory_batch_results([{}])
+ assert summary["failed_count"] == 1
+ assert summary["success_count"] == 0
+ assert summary["success"] is False
+
+
+def test_summarize_inventory_batch_results_all_skipped_smoke_exit_success():
+ """全 skipped 时 summary status=success,smoke 应退出 0(链路正常、无 Excel)。"""
+ worker = _load_freight_rpa_worker()
+ results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
+ summary = worker._summarize_inventory_batch_results(results)
+ assert summary["status"] == "success"
+ assert summary["has_success"] is False
+ assert summary["status"] not in {"failed", "partial_failed"}
+ smoke = _load_dsv_export_batch_smoke()
+ assert smoke._resolve_smoke_scenario_exit_code(
+ results=results,
+ summary=summary,
+ require_export=False,
+ ) == 0
+
+
+def test_summarize_inventory_batch_results_all_skipped_require_export_smoke_exit_fail():
+ """FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 时,全 skipped 应退出 2(无 Excel 导出)。"""
+ worker = _load_freight_rpa_worker()
+ smoke = _load_dsv_export_batch_smoke()
+ results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
+ summary = worker._summarize_inventory_batch_results(results)
+ assert summary["status"] == "success"
+ assert summary["has_success"] is False
+ assert smoke._resolve_smoke_scenario_exit_code(
+ results=results,
+ summary=summary,
+ require_export=True,
+ ) == 2
+
+
def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path):
"""真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。"""
worker = _load_freight_rpa_worker()
@@ -409,49 +557,6 @@ def test_is_dsv_username_page_ignores_login_method_page_text():
assert worker._is_dsv_username_page(page) is False
-def test_maybe_auto_login_dsv_does_not_retry_username_when_method_page_ready(monkeypatch):
- """方法选择页已就绪时,不应再回退执行邮箱重试。"""
- worker = _load_freight_rpa_worker()
-
- class _FakePage:
- def __init__(self) -> None:
- self.frames: list[object] = []
- self.url = "https://auth.dbschenker.com/mock"
-
- page = _FakePage()
- username_locator = object()
-
- monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", "user@example.com")
- monkeypatch.setenv("FREIGHT_RPA_DSV_PASSWORD", "secret")
- monkeypatch.setattr(worker, "_debug_report", lambda *args, **kwargs: None, raising=False)
- monkeypatch.setattr(worker, "_fill_dsv_username", lambda current_page, username, preferred_locator=None: username_locator)
- monkeypatch.setattr(worker, "_click_dsv_continue", lambda current_page, locator=None: True)
- monkeypatch.setattr(worker, "_fill_dsv_password_page_fields", lambda current_page, username, password: False)
- monkeypatch.setattr(worker, "_wait_for_dsv_human_check_if_present", lambda current_page, timeout_ms=None: None)
- monkeypatch.setattr(worker, "_wait_for_dsv_app_after_login", lambda current_page, timeout_ms=None, on_portal_shell_seen=None: False)
- monkeypatch.setattr(worker, "_wait_for_dsv_login_method_page", lambda current_page, timeout_ms=None: True)
- monkeypatch.setattr(
- worker,
- "_is_dsv_username_page",
- lambda current_page: (_ for _ in ()).throw(AssertionError("should not retry username when method page is ready")),
- )
- monkeypatch.setattr(
- worker,
- "_click_dsv_password_method",
- lambda current_page: (_ for _ in ()).throw(RuntimeError("STOP_AFTER_METHOD_READY")),
- )
-
- def fake_wait_for_visible_selector(current_page, selector_env, fallback_selectors, *, timeout_ms=None):
- if selector_env == "FREIGHT_RPA_DSV_USERNAME_SELECTOR":
- return username_locator
- return None
-
- monkeypatch.setattr(worker, "_wait_for_visible_selector", fake_wait_for_visible_selector)
-
- with pytest.raises(RuntimeError, match="STOP_AFTER_METHOD_READY"):
- worker._maybe_auto_login_dsv(page)
-
-
def test_fill_dsv_username_reuses_detected_email_locator(monkeypatch):
"""已探测到的 type=email 输入框必须能直接复用,不能再因二次窄选择器扫描而丢失。"""
worker = _load_freight_rpa_worker()
@@ -502,193 +607,6 @@ def test_fill_dsv_username_reuses_detected_email_locator(monkeypatch):
assert locator.value == "user@example.com"
-def test_maybe_auto_login_dsv_waits_before_retrying_username_page(monkeypatch):
- """Continue 刚提交后应先等待方法页切换,不能立刻回退邮箱页重试。"""
- worker = _load_freight_rpa_worker()
- username_checks = {"count": 0}
- clock = {"value": 0}
-
- class _FakeBodyLocator:
- def inner_text(self, timeout: int | None = None) -> str:
- return "loading"
-
- class _FakePage:
- frames: list[object] = []
- url = "https://auth.dbschenker.com/mock"
-
- def locator(self, selector: str) -> _FakeBodyLocator:
- assert selector == "body"
- return _FakeBodyLocator()
-
- page = _FakePage()
- username_locator = object()
-
- monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", "user@example.com")
- monkeypatch.setenv("FREIGHT_RPA_DSV_PASSWORD", "secret")
- monkeypatch.setattr(worker, "_debug_report", lambda *args, **kwargs: None, raising=False)
- monkeypatch.setattr(worker, "_fill_dsv_username", lambda current_page, username, preferred_locator=None: username_locator)
- monkeypatch.setattr(worker, "_click_dsv_continue", lambda current_page, locator=None: True)
- monkeypatch.setattr(worker, "_fill_dsv_password_page_fields", lambda current_page, username, password: False)
- monkeypatch.setattr(worker, "_wait_for_dsv_human_check_if_present", lambda current_page, timeout_ms=None: None)
- monkeypatch.setattr(worker, "_wait_for_dsv_app_after_login", lambda current_page, timeout_ms=None, on_portal_shell_seen=None: False)
- monkeypatch.setattr(worker, "_wait_for_dsv_login_method_page", lambda current_page, timeout_ms=None: False)
-
- def fake_is_username_page(current_page) -> bool:
- username_checks["count"] += 1
- assert clock["value"] >= 6
- raise RuntimeError("STOP_AFTER_ALLOWED_RETRY")
-
- monkeypatch.setattr(worker, "_is_dsv_username_page", fake_is_username_page)
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
-
- tick = {"value": -1}
-
- def fake_monotonic() -> int:
- tick["value"] += 1
- clock["value"] = tick["value"]
- return tick["value"]
-
- monkeypatch.setattr(worker.time, "monotonic", fake_monotonic)
-
- def fake_wait_for_visible_selector(current_page, selector_env, fallback_selectors, *, timeout_ms=None):
- if selector_env == "FREIGHT_RPA_DSV_USERNAME_SELECTOR":
- return username_locator
- return None
-
- monkeypatch.setattr(worker, "_wait_for_visible_selector", fake_wait_for_visible_selector)
-
- with pytest.raises(RuntimeError, match="STOP_AFTER_ALLOWED_RETRY"):
- worker._maybe_auto_login_dsv(page)
-
- assert username_checks["count"] == 1
-
-
-def test_maybe_auto_login_dsv_reports_substages(monkeypatch):
- """真实登录主路径应记录 auto_login 内部子阶段,便于拆解总耗时。"""
- worker = _load_freight_rpa_worker()
- reported_stages: list[tuple[str, str]] = []
- state = {"method_clicked": False}
-
- class _FakePasswordStateLocator:
- first = None
-
- def __init__(self) -> None:
- self.first = self
-
- def is_visible(self, timeout: int | None = None) -> bool:
- return False
-
- class _FakePage:
- def __init__(self) -> None:
- self.frames: list[object] = []
- self.url = "https://auth.dbschenker.com/mock"
-
- def wait_for_load_state(self, state_name: str, timeout: int | None = None) -> None:
- return None
-
- def locator(self, selector: str):
- assert selector == 'input[type="password"]'
- return _FakePasswordStateLocator()
-
- page = _FakePage()
- username_locator = object()
-
- monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", "user@example.com")
- monkeypatch.setenv("FREIGHT_RPA_DSV_PASSWORD", "secret")
- monkeypatch.setattr(worker, "_report_dsv_chain_stage", lambda stage, status, **kwargs: reported_stages.append((stage, status)))
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_collect_dsv_reports_probe", lambda page: {})
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_fill_dsv_username", lambda current_page, username, preferred_locator=None: username_locator)
- monkeypatch.setattr(worker, "_click_dsv_continue", lambda current_page, locator=None: True)
- monkeypatch.setattr(worker, "_find_dsv_password_locator", lambda current_page, timeout_ms=250: None)
- monkeypatch.setattr(worker, "_fill_dsv_password_page_fields", lambda current_page, username, password: state["method_clicked"])
- monkeypatch.setattr(worker, "_has_dsv_human_check_prompt", lambda current_page: False)
- monkeypatch.setattr(
- worker,
- "_wait_for_dsv_app_after_login",
- lambda current_page, timeout_ms=None, on_portal_shell_seen=None: False,
- )
- monkeypatch.setattr(worker, "_wait_for_dsv_login_method_page", lambda current_page, timeout_ms=None: not state["method_clicked"])
- monkeypatch.setattr(worker, "_click_dsv_password_method", lambda current_page: state.__setitem__("method_clicked", True) or True)
- monkeypatch.setattr(worker, "_submit_dsv_password_form", lambda current_page: True)
- monkeypatch.setattr(worker, "_dismiss_dsv_password_upgrade_prompt", lambda current_page: None)
- monkeypatch.setattr(
- worker,
- "_wait_for_dsv_home_ready",
- lambda current_page, timeout_ms=None, on_portal_shell_seen=None: (on_portal_shell_seen() if on_portal_shell_seen else None),
- )
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
-
- def fake_wait_for_visible_selector(current_page, selector_env, fallback_selectors, *, timeout_ms=None):
- if selector_env == "FREIGHT_RPA_DSV_USERNAME_SELECTOR":
- return username_locator
- return None
-
- monkeypatch.setattr(worker, "_wait_for_visible_selector", fake_wait_for_visible_selector)
-
- worker._maybe_auto_login_dsv(page)
-
- assert ("auto_login.username_step", "end") in reported_stages
- assert ("auto_login.continue_to_method", "end") in reported_stages
- assert ("auto_login.method_to_password", "end") in reported_stages
- assert ("auto_login.portal_shell_seen", "end") in reported_stages
- assert ("auto_login.portal_shell_to_home_ready", "end") in reported_stages
- assert ("auto_login.password_submit_to_home", "end") in reported_stages
-
-
-def test_wait_for_dsv_app_after_login_reports_portal_shell_callback(monkeypatch):
- """检测到 portal 壳层时应立刻回调,方便拆分 auth 收尾与首页 ready。"""
- worker = _load_freight_rpa_worker()
- callback_calls = {"value": 0}
-
- class _FakePage:
- url = "https://s360.dbschenker.com/main/portal"
-
- def title(self) -> str:
- return "360°"
-
- monkeypatch.setattr(worker, "_wait_for_visible_selector", lambda *args, **kwargs: object())
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
-
- assert worker._wait_for_dsv_app_after_login(
- _FakePage(),
- timeout_ms=1_000,
- on_portal_shell_seen=lambda: callback_calls.__setitem__("value", callback_calls["value"] + 1),
- ) is True
- assert callback_calls["value"] == 1
-
-
-def test_click_dsv_password_method_reads_device_list_sibling_form(monkeypatch):
- """DSV 第二步的密码选项在 .device-list 中,mfaForm 仅作为提交表单存在。"""
- worker = _load_freight_rpa_worker()
- submitted = {"value": False}
-
- class _FakeFrame:
- def evaluate(self, script: str, *args, **kwargs):
- if "isPasswordMethod" in script and "cancel" in script.lower():
- submitted["value"] = True
- return True
- return False
-
- class _FakePage:
- frames = [_FakeFrame()]
- url = "https://auth.dbschenker.com/mock"
-
- monkeypatch.setattr(worker, "_debug_report", lambda *args, **kwargs: None, raising=False)
- monkeypatch.setattr(worker, "_looks_like_dsv_login_method_page", lambda page: not submitted["value"])
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(
- worker,
- "_wait_for_visible_selector",
- lambda *args, **kwargs: object() if submitted["value"] else None,
- )
-
- assert worker._click_dsv_password_method(_FakePage()) is True
- assert submitted["value"] is True
-
-
def test_click_dsv_password_method_ignores_forgot_password_link(monkeypatch):
"""密码页的“忘记密码/Forgot password”链接不能被当成密码登录方式点击。"""
worker = _load_freight_rpa_worker()
@@ -756,57 +674,6 @@ def test_click_dsv_password_method_requires_real_transition(monkeypatch):
assert worker._click_dsv_password_method(_FakePage()) is False
-def test_click_dsv_password_method_does_not_use_mouse_coordinates(monkeypatch):
- """密码方式点击应基于匹配到的元素本身,而不是靠右侧坐标盲点。"""
- worker = _load_freight_rpa_worker()
- submitted = {"value": False}
-
- class _FakeFrame:
- def evaluate(self, script: str, *args, **kwargs):
- if "isPasswordMethod" in script and "cancel" in script.lower():
- submitted["value"] = True
- return True
- return False
-
- class _FakePage:
- frames = [_FakeFrame()]
-
- @property
- def mouse(self):
- raise AssertionError("password method click should not use page.mouse.click")
-
- monkeypatch.setattr(worker, "_wait_for_visible_selector", lambda *args, **kwargs: object() if submitted["value"] else None)
- monkeypatch.setattr(worker, "_looks_like_dsv_login_method_page", lambda page: not submitted["value"])
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
-
- assert worker._click_dsv_password_method(_FakePage()) is True
-
-
-def test_wait_for_dsv_login_method_page_uses_shorter_default_timeout(monkeypatch):
- """默认方法页等待应使用短超时,避免在第二步页面长时间卡住。"""
- worker = _load_freight_rpa_worker()
-
- class _FakePage:
- frames: list[object] = []
- url = "https://auth.dbschenker.com/mock"
-
- observed: list[int | None] = []
-
- def fake_human_check(page, timeout_ms=None):
- observed.append(timeout_ms)
-
- monkeypatch.delenv("FREIGHT_RPA_DSV_METHOD_PAGE_TIMEOUT_MS", raising=False)
- monkeypatch.setattr(worker, "_looks_like_dsv_login_method_page", lambda page: False)
- monkeypatch.setattr(worker, "_has_dsv_human_check_prompt", lambda page: True)
- monkeypatch.setattr(worker, "_wait_for_dsv_human_check_if_present", fake_human_check)
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(worker.time, "monotonic", iter([0, 5, 10, 15, 20, 21]).__next__)
-
- assert worker._wait_for_dsv_login_method_page(_FakePage()) is False
- assert observed
- assert all(timeout_ms == 2_000 for timeout_ms in observed)
-
-
def test_wait_for_dsv_login_method_page_skips_human_check_when_not_detected(monkeypatch):
"""普通方法页轮询时,不应每轮都进入真人校验重等待。"""
worker = _load_freight_rpa_worker()
@@ -833,41 +700,6 @@ def test_wait_for_dsv_login_method_page_skips_human_check_when_not_detected(monk
assert human_check_calls["value"] == 0
-def test_maybe_auto_login_dsv_skips_human_check_wait_when_not_detected(monkeypatch):
- """主登录循环未出现真人校验特征时,不应每轮进入重型 human-check 等待。"""
- worker = _load_freight_rpa_worker()
- human_check_calls = {"value": 0}
-
- class _FakePage:
- def __init__(self) -> None:
- self.frames: list[object] = []
- self.url = "https://auth.dbschenker.com/mock"
-
- page = _FakePage()
- username_locator = object()
-
- monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", "user@example.com")
- monkeypatch.setenv("FREIGHT_RPA_DSV_PASSWORD", "secret")
- monkeypatch.setattr(worker, "_wait_for_visible_selector", lambda current_page, selector_env, selectors, timeout_ms=None: username_locator if selector_env == "FREIGHT_RPA_DSV_USERNAME_SELECTOR" else None)
- monkeypatch.setattr(worker, "_fill_dsv_username", lambda current_page, username, preferred_locator=None: username_locator)
- monkeypatch.setattr(worker, "_click_dsv_continue", lambda current_page, locator=None: True)
- monkeypatch.setattr(worker, "_find_dsv_password_locator", lambda current_page, timeout_ms=250: None)
- monkeypatch.setattr(worker, "_fill_dsv_password_page_fields", lambda current_page, username, password: False)
- monkeypatch.setattr(worker, "_has_dsv_human_check_prompt", lambda current_page: False)
- monkeypatch.setattr(
- worker,
- "_wait_for_dsv_human_check_if_present",
- lambda current_page, timeout_ms=None: human_check_calls.__setitem__("value", human_check_calls["value"] + 1),
- )
- monkeypatch.setattr(worker, "_wait_for_dsv_login_method_page", lambda current_page, timeout_ms=None: (_ for _ in ()).throw(RuntimeError("STOP_AFTER_METHOD_WAIT")))
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
-
- with pytest.raises(RuntimeError, match="STOP_AFTER_METHOD_WAIT"):
- worker._maybe_auto_login_dsv(page)
-
- assert human_check_calls["value"] == 0
-
-
def test_find_dsv_password_locator_returns_visible_locator():
"""密码方式切换轮询应走轻量密码框探测,而不是长时间通用等待。"""
worker = _load_freight_rpa_worker()
@@ -924,219 +756,6 @@ def test_submit_dsv_password_form_supports_vue_type_button_and_hidden_password()
assert submitted["value"] is True
-def test_click_dsv_reports_menu_waits_for_legacy_menu_open():
- """DSV360 Reports 菜单应点击截图中的 #report-mega-legacy,并确认 #report-mega-list-legacy 展开。"""
- worker = _load_freight_rpa_worker()
- clicked = {"value": False}
- monkeypatch = pytest.MonkeyPatch()
- monkeypatch.setattr(worker, "_is_dsv_reports_menu_open", lambda page: clicked["value"])
- monkeypatch.setattr(worker, "_collect_dsv_reports_probe", lambda page: {})
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
-
- class _FakeLocator:
- def __init__(self, selector: str) -> None:
- self.selector = selector
- self.first = self
-
- def wait_for(self, state: str, timeout: int | None = None) -> None:
- if self.selector != "#report-mega-legacy > a.dropdown-toggle.nav-link":
- raise RuntimeError("unexpected selector")
-
- def scroll_into_view_if_needed(self, timeout: int | None = None) -> None:
- pass
-
- def click(self, timeout: int | None = None, force: bool = False) -> None:
- clicked["value"] = True
-
- def is_visible(self, timeout: int | None = None) -> bool:
- return self.selector == "#report-mega-list-legacy" and clicked["value"]
-
- class _FakePage:
- frames: list[object] = []
-
- def locator(self, selector: str) -> _FakeLocator:
- return _FakeLocator(selector)
-
- worker._click_dsv_reports_menu(_FakePage())
-
- assert clicked["value"] is True
- monkeypatch.undo()
-
-
-def test_click_dsv_reports_menu_prefers_click_before_hover():
- """Reports 菜单应优先 click,而不是先 hover 白等一轮。"""
- worker = _load_freight_rpa_worker()
- actions: list[str] = []
- clicked = {"value": False}
- monkeypatch = pytest.MonkeyPatch()
- monkeypatch.setattr(worker, "_is_dsv_reports_menu_open", lambda page: clicked["value"])
- monkeypatch.setattr(worker, "_collect_dsv_reports_probe", lambda page: {})
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
-
- class _FakeLocator:
- def __init__(self, selector: str) -> None:
- self.selector = selector
- self.first = self
-
- def wait_for(self, state: str, timeout: int | None = None) -> None:
- if self.selector != "#report-mega-legacy > a.dropdown-toggle.nav-link":
- raise RuntimeError("unexpected selector")
-
- def scroll_into_view_if_needed(self, timeout: int | None = None) -> None:
- pass
-
- def click(self, timeout: int | None = None, force: bool = False) -> None:
- actions.append("click")
- clicked["value"] = True
-
- def hover(self, timeout: int | None = None) -> None:
- actions.append("hover")
-
- def evaluate(self, script: str) -> None:
- actions.append("evaluate")
-
- def press(self, key: str, timeout: int | None = None) -> None:
- actions.append(f"press:{key}")
-
- def is_visible(self, timeout: int | None = None) -> bool:
- return self.selector == "#report-mega-list-legacy" and clicked["value"]
-
- class _FakePage:
- frames: list[object] = []
-
- def locator(self, selector: str) -> _FakeLocator:
- return _FakeLocator(selector)
-
- worker._click_dsv_reports_menu(_FakePage())
-
- assert actions
- assert actions[0] == "click"
- monkeypatch.undo()
-
-
-def test_wait_for_dsv_app_after_login_uses_light_nav_probe_during_compliance(monkeypatch):
- """处于 Verifying compliance 过渡页时,不应继续用重型超时轮询首页导航。"""
- worker = _load_freight_rpa_worker()
- observed_timeouts: list[int] = []
-
- class _FakePage:
- url = "https://auth.dbschenker.com/as/trvd9oTQfK/resume/as/authorization.ping"
-
- def title(self) -> str:
- return "Verifying compliance"
-
- def wait_for_load_state(self, state: str, timeout: int | None = None) -> None:
- raise AssertionError("auth transition branch should not wait for portal load state")
-
- tick = {"value": 0.0}
-
- def _fake_monotonic() -> float:
- tick["value"] += 0.1
- return tick["value"]
-
- monkeypatch.setattr(worker.time, "monotonic", _fake_monotonic)
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
-
- def _fake_wait_for_visible_selector(page, selector_env, selectors, timeout_ms=None):
- observed_timeouts.append(int(timeout_ms or 0))
- return None
-
- monkeypatch.setattr(worker, "_wait_for_visible_selector", _fake_wait_for_visible_selector)
-
- assert worker._wait_for_dsv_app_after_login(_FakePage(), timeout_ms=1_000) is False
- assert observed_timeouts
- assert all(timeout == 400 for timeout in observed_timeouts)
-
-
-def test_dismiss_dsv_password_upgrade_prompt_clicks_maybe_later():
- """可选 passkey 升级页出现时,应点击“也许以后”而不是“立即启用”。"""
- worker = _load_freight_rpa_worker()
- clicked_selectors: list[str] = []
-
- class _FakeLocator:
- def __init__(self, selector: str) -> None:
- self.selector = selector
- self.first = self
-
- def is_visible(self, timeout: int | None = None) -> bool:
- return self.selector == 'button.dbs-sims-button-secondary:has-text("也许以后")' and not clicked_selectors
-
- def wait_for(self, state: str, timeout: int | None = None) -> None:
- if self.selector != 'button.dbs-sims-button-secondary:has-text("也许以后")':
- raise RuntimeError("unexpected selector")
-
- def evaluate(self, script: str) -> None:
- assert "MouseEvent('click'" in script
- clicked_selectors.append(self.selector)
-
- class _FakePage:
- url = "https://auth.dbschenker.com/mock-passkey"
- frames: list[object] = []
-
- def locator(self, selector: str) -> _FakeLocator:
- return _FakeLocator(selector)
-
- def wait_for_load_state(self, state: str, timeout: int | None = None) -> None:
- pass
-
- worker._debug_report = lambda *args, **kwargs: None
-
- worker._dismiss_dsv_password_upgrade_prompt(_FakePage())
-
- assert clicked_selectors == ['button.dbs-sims-button-secondary:has-text("也许以后")']
-
-
-def test_dismiss_dsv_password_upgrade_prompt_skips_quickly_when_not_shown(monkeypatch):
- """未出现升级提示时,应快速跳过而不是在认证页做长时间阻塞轮询。"""
- worker = _load_freight_rpa_worker()
- observed_timeouts: list[int] = []
-
- class _FakeTextLocator:
- first = None
-
- def __init__(self, selector: str) -> None:
- self.selector = selector
- self.first = self
-
- def inner_text(self, timeout: int | None = None) -> str:
- observed_timeouts.append(int(timeout or 0))
- return "Verifying compliance"
-
- def is_visible(self, timeout: int | None = None) -> bool:
- observed_timeouts.append(int(timeout or 0))
- return False
-
- def wait_for(self, state: str, timeout: int | None = None) -> None:
- raise AssertionError("quick skip path should not enter heavy wait_for loop")
-
- class _FakePage:
- url = "https://auth.dbschenker.com/mock"
- frames: list[object] = []
-
- def locator(self, selector: str) -> _FakeTextLocator:
- return _FakeTextLocator(selector)
-
- tick = {"value": 0.0}
-
- def _fake_monotonic() -> float:
- tick["value"] += 0.25
- return tick["value"]
-
- monkeypatch.setattr(worker.time, "monotonic", _fake_monotonic)
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
-
- worker._dismiss_dsv_password_upgrade_prompt(_FakePage())
-
- assert observed_timeouts
- assert max(observed_timeouts) <= 250
-
-
def test_has_dsv_password_upgrade_prompt_does_not_match_generic_not_now_text():
"""普通 auth 页面若仅出现通用按钮词,不应被误判成升级登录提示。"""
worker = _load_freight_rpa_worker()
@@ -1183,163 +802,41 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch):
assert locator_calls["value"] == 0
-def test_has_dsv_password_upgrade_prompt_detects_maybe_later_on_portal(monkeypatch):
- """portal 上若升级弹窗挡住首页,仍应识别“也许以后”按钮。"""
- worker = _load_freight_rpa_worker()
+def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch):
+ """登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。"""
+ module_path = _repo_root() / "scripts" / "rpa" / "dsv_report_export.py"
+ spec = importlib.util.spec_from_file_location("dsv_report_export_retry_test", module_path)
+ assert spec is not None and spec.loader is not None
+ dsv_report_export = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(dsv_report_export)
- class _FakeLocator:
- def __init__(self, selector: str) -> None:
- self.selector = selector
- self.first = self
+ goto_calls: list[str] = []
+ home_ready_calls: list[int] = []
- def is_visible(self, timeout: int | None = None) -> bool:
- return self.selector == 'button.dbs-sims-button-secondary:has-text("也许以后")'
+ monkeypatch.setattr(dsv_report_export, "_is_dsv_session_active", lambda page, entry_url: False)
+ monkeypatch.setattr(
+ dsv_report_export,
+ "_goto_dsv_entry_url",
+ lambda page, entry_url: goto_calls.append(entry_url),
+ )
+ monkeypatch.setattr(
+ dsv_report_export,
+ "_maybe_auto_login_dsv",
+ lambda page: (_ for _ in ()).throw(RuntimeError("DSV home page was not ready after login")),
+ )
+ monkeypatch.setattr(dsv_report_export, "_is_dsv_on_entry_site", lambda page, entry_url: True)
+ monkeypatch.setattr(
+ dsv_report_export,
+ "_wait_for_dsv_home_ready",
+ lambda page, timeout_ms=None: home_ready_calls.append(timeout_ms or 0),
+ )
+ monkeypatch.setattr(dsv_report_export, "_wait_for_dsv_reports_nav_stable", lambda page, timeout_ms=None: None)
- def inner_text(self, timeout: int | None = None) -> str:
- return ""
+ entry_url = "https://s360.dbschenker.com/"
+ dsv_report_export._ensure_dsv_session(object(), entry_url)
- class _FakePage:
- url = "https://s360.dbschenker.com/main/portal"
- frames: list[object] = []
-
- def locator(self, selector: str) -> _FakeLocator:
- return _FakeLocator(selector)
-
- monkeypatch.setattr(worker.dsv_session, "has_dsv_report_nav_usable", lambda page: False)
-
- assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is True
-
-
-def test_wait_for_dsv_home_ready_skips_duplicate_upgrade_prompt_check(monkeypatch):
- """首页已可探测或 app wait 返回后,若无升级提示强特征,不应再次进入升级提示处理。"""
- worker = _load_freight_rpa_worker()
- dismiss_calls = {"value": 0}
- ready_state = {"value": False}
-
- class _FakeLocator:
- first = None
-
- def __init__(self) -> None:
- self.first = self
-
- def inner_text(self, timeout: int | None = None) -> str:
- return "Verifying compliance"
-
- def is_visible(self, timeout: int | None = None) -> bool:
- return False
-
- class _FakePage:
- url = "https://auth.dbschenker.com/as/example/resume/as/authorization.ping"
- frames: list[object] = []
-
- def locator(self, selector: str) -> _FakeLocator:
- return _FakeLocator()
-
- def _fake_is_home_ready(page) -> bool:
- return ready_state["value"]
-
- def _fake_wait_for_app_after_login(page, timeout_ms=None, on_portal_shell_seen=None) -> bool:
- ready_state["value"] = True
- if on_portal_shell_seen is not None:
- on_portal_shell_seen()
- return True
-
- monkeypatch.setattr(worker, "_dismiss_dsv_password_upgrade_prompt", lambda page: dismiss_calls.__setitem__("value", dismiss_calls["value"] + 1))
- monkeypatch.setattr(worker, "_is_dsv_home_ready", _fake_is_home_ready)
- monkeypatch.setattr(worker, "_wait_for_dsv_app_after_login", _fake_wait_for_app_after_login)
- monkeypatch.setattr(worker, "_collect_dsv_reports_probe", lambda page: {})
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
-
- worker._wait_for_dsv_home_ready(_FakePage(), timeout_ms=1_000)
-
- assert dismiss_calls["value"] == 0
-
-
-def test_wait_for_dsv_app_after_login_dismisses_late_upgrade_prompt(monkeypatch):
- """auth 过渡阶段若稍后出现升级提示,应立即处理,而不是继续 wait-app 空转。"""
- worker = _load_freight_rpa_worker()
- dismiss_calls = {"value": 0}
- probe_calls = {"value": 0}
-
- class _FakePage:
- url = "https://auth.dbschenker.com/as/example/resume/as/authorization.ping"
-
- def title(self) -> str:
- return "DSV | SIMS Sign in"
-
- def _fake_wait_for_visible_selector(page, selector_env, selectors, timeout_ms=None):
- return None
-
- def _fake_has_prompt(page, timeout_ms=250):
- probe_calls["value"] += 1
- return probe_calls["value"] >= 2
-
- def _fake_dismiss(page):
- dismiss_calls["value"] += 1
-
- tick = {"value": 0.0}
-
- def _fake_monotonic() -> float:
- tick["value"] += 0.3
- return tick["value"]
-
- monkeypatch.setattr(worker.time, "monotonic", _fake_monotonic)
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(worker, "_wait_for_visible_selector", _fake_wait_for_visible_selector)
- monkeypatch.setattr(worker, "_has_dsv_password_upgrade_prompt", _fake_has_prompt)
- monkeypatch.setattr(worker, "_dismiss_dsv_password_upgrade_prompt", _fake_dismiss)
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
-
- assert worker._wait_for_dsv_app_after_login(_FakePage(), timeout_ms=1_500) is False
- assert dismiss_calls["value"] == 1
-
-
-def test_wait_for_dsv_app_after_login_accepts_attached_portal_shell(monkeypatch):
- """portal 已落到 s360 且导航容器已挂载时,不应继续 wait-app 空转到超时。"""
- worker = _load_freight_rpa_worker()
-
- class _FakeNavLocator:
- first = None
-
- def __init__(self) -> None:
- self.first = self
-
- def count(self) -> int:
- return 1
-
- def is_visible(self, timeout: int | None = None) -> bool:
- return False
-
- class _FakeEmptyLocator:
- first = None
-
- def __init__(self) -> None:
- self.first = self
-
- def count(self) -> int:
- return 0
-
- class _FakePage:
- url = "https://s360.dbschenker.com/main/portal"
- frames: list[object] = []
-
- def title(self) -> str:
- return "360°"
-
- def locator(self, selector: str):
- if selector.startswith("#report-mega-legacy") or "Reports" in selector:
- return _FakeNavLocator()
- return _FakeEmptyLocator()
-
- def wait_for_load_state(self, state: str, timeout: int | None = None) -> None:
- return None
-
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
-
- assert worker._wait_for_dsv_app_after_login(_FakePage(), timeout_ms=1_000) is True
+ assert goto_calls == [entry_url, entry_url]
+ assert home_ready_calls == [30_000]
def test_is_dsv_home_ready_accepts_attached_portal_shell(monkeypatch):
@@ -1379,6 +876,46 @@ def test_is_dsv_home_ready_accepts_attached_portal_shell(monkeypatch):
assert worker._is_dsv_home_ready(_FakePage()) is True
+def test_is_dsv_home_ready_rejects_report_frame_url(monkeypatch):
+ """停留在 /frame/reports/ 时即使 Reports 顶栏可见,也不应判定 home-ready。"""
+ worker = _load_freight_rpa_worker()
+
+ class _FakeNavLocator:
+ first = None
+
+ def __init__(self) -> None:
+ self.first = self
+
+ def count(self) -> int:
+ return 1
+
+ def is_visible(self, timeout: int | None = None) -> bool:
+ return True
+
+ class _FakeEmptyLocator:
+ first = None
+
+ def __init__(self) -> None:
+ self.first = self
+
+ def count(self) -> int:
+ return 0
+
+ class _FakePage:
+ url = (
+ "https://s360.dbschenker.com/main/portal/frame/reports/"
+ "sfwv0sMCr0FfUcNBL6Xw8QJ7I154kl3yVYZyo4GHSm8IrWxL"
+ )
+ frames: list[object] = []
+
+ def locator(self, selector: str):
+ if selector.startswith("#report-mega-legacy") or "Reports" in selector:
+ return _FakeNavLocator()
+ return _FakeEmptyLocator()
+
+ assert worker._is_dsv_home_ready(_FakePage()) is False
+
+
def test_is_dsv_home_ready_rejects_iframe_shell_without_report_nav(monkeypatch):
"""仅有 dashboard iframe 欢迎语、顶栏 Reports DOM 未挂载时,不应判定 home-ready。"""
worker = _load_freight_rpa_worker()
@@ -1407,75 +944,6 @@ def test_is_dsv_home_ready_rejects_iframe_shell_without_report_nav(monkeypatch):
assert worker._is_dsv_home_ready(_FakePage()) is False
-def test_wait_for_dsv_report_form_ready_accepts_report_shell_without_title(monkeypatch):
- """报表 shell/frame 已挂载时,不应继续等标题文本完全刷出后才允许点击 View Report。"""
- worker = _load_freight_rpa_worker()
-
- class _FakeBodyLocator:
- def inner_text(self, timeout: int | None = None) -> str:
- return ""
-
- class _FakeFrame:
- def __init__(self, name: str, url: str) -> None:
- self.name = name
- self.url = url
-
- def locator(self, selector: str) -> _FakeBodyLocator:
- assert selector == "body"
- return _FakeBodyLocator()
-
- class _FakePage:
- url = "https://s360.dbschenker.com/main/portal/frame/reports/mock"
- frames = [
- _FakeFrame("myIframe", "https://s360.dbschenker.com/S360Reports/SSRS/mock"),
- _FakeFrame("report-frame", "https://s360.dbschenker.com/S360Reports/Reports/Default.aspx?rid=1"),
- ]
-
- monkeypatch.setattr(worker, "_wait_for_visible_selector", lambda *args, **kwargs: object())
- monkeypatch.setattr(worker, "_collect_dsv_menu_probe", lambda *args, **kwargs: {})
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
-
- worker._wait_for_dsv_report_form_ready(_FakePage(), "On Hand Inventory by Location", timeout_ms=1_000)
-
-
-def test_wait_for_dsv_report_form_ready_requires_shell_or_title(monkeypatch):
- """若只有 View Report 按钮可见但报表 shell/标题都未出现,仍不应提前放行。"""
- worker = _load_freight_rpa_worker()
-
- class _FakeBodyLocator:
- def inner_text(self, timeout: int | None = None) -> str:
- return ""
-
- class _FakeFrame:
- name = ""
- url = "https://example.com/other"
-
- def locator(self, selector: str) -> _FakeBodyLocator:
- assert selector == "body"
- return _FakeBodyLocator()
-
- class _FakePage:
- url = "https://s360.dbschenker.com/main/portal"
- frames = [_FakeFrame()]
-
- tick = {"value": 0.0}
-
- def _fake_monotonic() -> float:
- tick["value"] += 0.4
- return tick["value"]
-
- monkeypatch.setattr(worker.time, "monotonic", _fake_monotonic)
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(worker, "_wait_for_visible_selector", lambda *args, **kwargs: object())
- monkeypatch.setattr(worker, "_collect_dsv_menu_probe", lambda *args, **kwargs: {})
- monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
-
- with pytest.raises(RuntimeError, match="DSV report form was not ready"):
- worker._wait_for_dsv_report_form_ready(_FakePage(), "On Hand Inventory by Location", timeout_ms=1_000)
-
-
def test_click_dsv_view_report_uses_reportviewer_button_id():
"""库存报表页 View Report 按钮来自 SSRS ReportViewer 的固定控件 ID。"""
worker = _load_freight_rpa_worker()
@@ -1544,160 +1012,6 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
assert filled == {"#ReportViewerMain_ctl08_ctl03_txtValue": "CADU-0000000100"}
-def test_click_dsv_export_excel_uses_reportviewer_export_menu(monkeypatch):
- """SSRS 结果页优先调用 ReportViewer 原生 EXCELOPENXML 导出。"""
- worker = _load_freight_rpa_worker()
- calls: list[str] = []
-
- class _FakeFrame:
- def evaluate(self, script: str) -> bool:
- if "exportReport('EXCELOPENXML')" in script:
- calls.append("direct-export")
- return True
- return False
-
- class _FakePage:
- frames = [_FakeFrame()]
-
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(worker, "_wait_for_dsv_report_result_ready", lambda page: None)
-
- worker._click_dsv_export_excel(_FakePage())
-
- assert calls == ["direct-export"]
-
-
-def test_click_dsv_export_excel_limits_fallback_to_selected_report_frame(monkeypatch):
- """命中 report-frame 后,导出菜单与 Excel 选项只能在该 frame 内查找。"""
- worker = _load_freight_rpa_worker()
- calls: list[tuple[str, object, tuple[str, ...]]] = []
-
- class _FakeFrame:
- name = "report-frame"
- url = "https://s360.dbschenker.com/S360Reports/Reports/Default.aspx?rid=demo"
-
- def evaluate(self, script: str) -> bool:
- if "exportReport('EXCELOPENXML')" in script:
- return False
- return False
-
- report_frame = _FakeFrame()
-
- class _FakePage:
- frames = [object(), report_frame]
-
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(worker, "_wait_for_dsv_report_result_ready", lambda page: None)
- monkeypatch.setattr(
- worker,
- "_find_dsv_report_result_frame",
- lambda page: (1, report_frame, {"bodyReady": True, "asyncWait": False}),
- )
- monkeypatch.setattr(
- worker,
- "_click_visible_selector_or_text_in_root",
- lambda root, selector, texts: calls.append(("root", root, texts)) or True,
- )
- monkeypatch.setattr(
- worker,
- "_click_visible_selector_or_text",
- lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("page fallback should not run when report-frame is selected")),
- )
-
- worker._click_dsv_export_excel(_FakePage())
-
- assert calls == [
- ("root", report_frame, ("file_download", "Save", "Export")),
- ("root", report_frame, ("Excel", "EXCELOPENXML")),
- ]
-
-
-def test_click_dsv_export_excel_uses_reportviewer_default_selectors_without_env(monkeypatch):
- """未配置导出 selector 时,也要优先走 SSRS ReportViewer 的默认导出控件选择器。"""
- worker = _load_freight_rpa_worker()
- selectors: list[str] = []
-
- class _FakeFrame:
- name = "report-frame"
- url = "https://s360.dbschenker.com/S360Reports/Reports/Default.aspx?rid=demo"
-
- def evaluate(self, script: str) -> bool:
- return False
-
- report_frame = _FakeFrame()
-
- class _FakePage:
- frames = [report_frame]
-
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(worker, "_wait_for_dsv_report_result_ready", lambda page: None)
- monkeypatch.setattr(
- worker,
- "_find_dsv_report_result_frame",
- lambda page: (0, report_frame, {"bodyReady": True, "asyncWait": False}),
- )
- monkeypatch.setattr(worker, "_env", lambda name, default="": "")
-
- def _fake_click(root, selector, texts):
- selectors.append(selector or "")
- return True
-
- monkeypatch.setattr(worker, "_click_visible_selector_or_text_in_root", _fake_click)
-
- worker._click_dsv_export_excel(_FakePage())
-
- assert 'a[title="Export drop down menu"]' in selectors[0]
- assert '[id$="_ctl04_ctl00_ButtonLink"]' in selectors[0]
- assert 'a[onclick*="EXCELOPENXML"]' in selectors[1]
-
-
-def test_click_dsv_export_excel_retries_excel_after_force_open(monkeypatch):
- """首次未找到 Excel 选项时,应触发强制展开导出菜单并再次查找。"""
- worker = _load_freight_rpa_worker()
- calls: list[tuple[str, str]] = []
-
- class _FakeFrame:
- name = "report-frame"
- url = "https://s360.dbschenker.com/S360Reports/Reports/Default.aspx?rid=demo"
-
- def evaluate(self, script: str) -> bool:
- return False
-
- report_frame = _FakeFrame()
-
- class _FakePage:
- frames = [report_frame]
-
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
- monkeypatch.setattr(worker, "_wait_for_dsv_report_result_ready", lambda page: None)
- monkeypatch.setattr(
- worker,
- "_find_dsv_report_result_frame",
- lambda page: (0, report_frame, {"bodyReady": True, "asyncWait": False}),
- )
- monkeypatch.setattr(worker, "_env", lambda name, default="": "")
-
- state = {"excel_attempt": 0}
-
- def _fake_click(root, selector, texts):
- calls.append(("click", selector or ""))
- if "Export drop down menu" in (selector or ""):
- return True
- if "EXCELOPENXML" in (selector or "") or "title=\"Excel\"" in (selector or ""):
- state["excel_attempt"] += 1
- return state["excel_attempt"] >= 2
- return False
-
- monkeypatch.setattr(worker, "_click_visible_selector_or_text_in_root", _fake_click)
- monkeypatch.setattr(worker, "_force_open_dsv_export_menu", lambda root, selector: calls.append(("force", selector)) or True)
- monkeypatch.setattr(worker, "_probe_dsv_report_export_controls", lambda frame: {"exportHints": []})
-
- worker._click_dsv_export_excel(_FakePage())
-
- assert state["excel_attempt"] == 2
- assert any(kind == "force" for kind, _ in calls)
-
-
def test_validate_inventory_excel_accepts_real_report_shape(tmp_path):
"""下载完成后必须能打开 Excel,并包含库存报表标题和关键表头。"""
worker = _load_freight_rpa_worker()
@@ -1726,28 +1040,6 @@ def test_validate_inventory_excel_rejects_invalid_download(tmp_path):
worker._validate_inventory_excel(path)
-def test_wait_for_dsv_report_result_ready_waits_for_export_toolbar(monkeypatch):
- """View Report 后必须等 SSRS 异步结果和导出工具栏都可用。"""
- worker = _load_freight_rpa_worker()
- states = [
- {"asyncWait": True, "exportReady": False, "excelReady": False, "bodyReady": False},
- {"asyncWait": False, "exportReady": True, "excelReady": False, "bodyReady": True},
- ]
-
- class _FakeFrame:
- def evaluate(self, script: str) -> dict[str, bool]:
- return states.pop(0)
-
- class _FakePage:
- frames = [_FakeFrame()]
-
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
-
- worker._wait_for_dsv_report_result_ready(_FakePage(), timeout_ms=5_000)
-
- assert states == []
-
-
def test_find_dsv_report_result_frame_prefers_grid_like_frame():
"""当多个 frame 都包含报表名时,应优先选择真正承载库存表格的结果 frame。"""
worker = _load_freight_rpa_worker()
@@ -1840,133 +1132,6 @@ def test_find_dsv_report_result_frame_prefers_report_frame_identity_while_loadin
assert selected[2]["bodyReady"] is False
-def test_wait_for_dsv_report_result_ready_prefers_best_report_frame(monkeypatch):
- """等待逻辑应跳过只有报表标题的 frame,命中真正结果表格所在的 frame。"""
- worker = _load_freight_rpa_worker()
- captured: list[dict[str, bool | int]] = []
-
- monkeypatch.setattr(
- worker,
- "_emit_debug_event",
- lambda run_id, hypothesis_id, location, msg, data=None: captured.append(data or {})
- if location.endswith(":ready")
- else None,
- )
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
-
- class _FakeFrame:
- def __init__(self, state: dict[str, bool | int]) -> None:
- self._state = state
-
- def evaluate(self, script: str) -> dict[str, bool | int]:
- return self._state
-
- class _FakePage:
- frames = [
- _FakeFrame(
- {
- "asyncWait": False,
- "exportReady": False,
- "excelReady": False,
- "bodyReady": True,
- "bodyScore": 1,
- "directExportReady": False,
- }
- ),
- _FakeFrame(
- {
- "asyncWait": False,
- "exportReady": False,
- "excelReady": False,
- "bodyReady": True,
- "bodyScore": 4,
- "directExportReady": False,
- }
- ),
- ]
-
- worker._wait_for_dsv_report_result_ready(_FakePage(), timeout_ms=5_000)
-
- assert captured
- assert captured[-1]["frameIndex"] == 1
- assert captured[-1]["bodyScore"] == 4
-
-
-def test_wait_for_dsv_report_result_ready_waits_for_report_frame_body(monkeypatch):
- """发现 report-frame 后,即使标题 frame 已 ready,也要等结果 frame 真正出正文。"""
- worker = _load_freight_rpa_worker()
- captured: list[dict[str, bool | int]] = []
-
- monkeypatch.setattr(
- worker,
- "_emit_debug_event",
- lambda run_id, hypothesis_id, location, msg, data=None: captured.append(data or {})
- if location.endswith(":ready")
- else None,
- )
- monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
- monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
-
- class _FakeFrame:
- def __init__(self, *, name: str, url: str, states: list[dict[str, bool | int]]) -> None:
- self.name = name
- self.url = url
- self._states = states
- self._last_state = states[-1]
-
- def evaluate(self, script: str) -> dict[str, bool | int]:
- if self._states:
- self._last_state = self._states.pop(0)
- return self._last_state
-
- class _FakePage:
- frames = [
- _FakeFrame(
- name="myIframe",
- url="https://s360.dbschenker.com/S360Reports/SSRS/demo",
- states=[
- {
- "asyncWait": False,
- "exportReady": False,
- "excelReady": False,
- "bodyReady": True,
- "bodyScore": 1,
- "directExportReady": False,
- }
- ],
- ),
- _FakeFrame(
- name="report-frame",
- url="https://s360.dbschenker.com/S360Reports/Reports/Default.aspx?rid=demo",
- states=[
- {
- "asyncWait": True,
- "exportReady": False,
- "excelReady": False,
- "bodyReady": False,
- "bodyScore": 0,
- "directExportReady": False,
- },
- {
- "asyncWait": False,
- "exportReady": False,
- "excelReady": False,
- "bodyReady": True,
- "bodyScore": 5,
- "directExportReady": False,
- },
- ],
- ),
- ]
-
- worker._wait_for_dsv_report_result_ready(_FakePage(), timeout_ms=5_000)
-
- assert captured
- assert captured[-1]["frameIndex"] == 1
- assert captured[-1]["bodyScore"] == 5
-
-
def test_get_dsv_report_result_state_keeps_waiting_when_loading_overlay_and_headers_coexist():
"""结果表头已出现但仍带 Loading 覆盖层时,不能提前放行导出。"""
worker = _load_freight_rpa_worker()
diff --git a/backend/tests/test_freight_rpa_worker_inventory_params.py b/backend/tests/test_freight_rpa_worker_inventory_params.py
index 734e21bb..84a8c3cd 100644
--- a/backend/tests/test_freight_rpa_worker_inventory_params.py
+++ b/backend/tests/test_freight_rpa_worker_inventory_params.py
@@ -122,6 +122,11 @@ def test_dsv_report_has_inventory_data_rows_false_when_table_has_only_three_rows
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is False
frame.evaluate.assert_called_once()
+ probe_js = frame.evaluate.call_args.args[0]
+ assert "#Report_table" in probe_js
+ assert "ReportViewerMain_ctl08" in probe_js
+ assert "directBodyRows" in probe_js
+ assert "isWarehouseCodeOnly" in probe_js
def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monkeypatch):
@@ -133,6 +138,8 @@ def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monk
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is True
frame.evaluate.assert_called_once()
+ probe_js = frame.evaluate.call_args.args[0]
+ assert "isInventoryDetailRow" in probe_js
def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch):
@@ -226,26 +233,90 @@ def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatc
def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
- """同 entry_url 且 session 有效时 reset 不应再触发 auto_login。"""
+ """同 entry_url 且 session 有效时 reset 不应再触发 auto_login,但应 goto portal 首页。"""
worker = _load_dsv_report_export()
page = MagicMock()
login = MagicMock()
+ goto = MagicMock()
home = MagicMock()
nav = MagicMock()
monkeypatch.setattr(worker, "_is_dsv_session_active", MagicMock(return_value=True))
- monkeypatch.setattr(worker, "_is_dsv_home_ready", MagicMock(return_value=True))
+ monkeypatch.setattr(worker, "_goto_dsv_entry_url", goto)
monkeypatch.setattr(worker, "_maybe_auto_login_dsv", login)
monkeypatch.setattr(worker, "_wait_for_dsv_home_ready", home)
monkeypatch.setattr(worker, "_wait_for_dsv_reports_nav_stable", nav)
worker._reset_dsv_export_entry(page, "https://s360.dbschenker.com/")
- page.goto.assert_not_called()
+ goto.assert_called_once_with(page, "https://s360.dbschenker.com/")
login.assert_not_called()
home.assert_called_once()
nav.assert_called_once()
+def test_ensure_dsv_session_goes_home_when_session_active_in_report_context(monkeypatch):
+ """batch 首条前 session 有效但仍在报表 iframe 时,应 goto portal 首页而非直接导航。"""
+ worker = _load_dsv_report_export()
+ page = MagicMock()
+ login = MagicMock()
+ goto = MagicMock()
+ home = MagicMock()
+ nav = MagicMock()
+ monkeypatch.setattr(worker, "_is_dsv_session_active", MagicMock(return_value=True))
+ monkeypatch.setattr(worker, "_is_dsv_in_report_navigation_context", MagicMock(return_value=True))
+ monkeypatch.setattr(worker, "_goto_dsv_entry_url", goto)
+ monkeypatch.setattr(worker, "_maybe_auto_login_dsv", login)
+ monkeypatch.setattr(worker, "_wait_for_dsv_home_ready", home)
+ monkeypatch.setattr(worker, "_wait_for_dsv_reports_nav_stable", nav)
+
+ worker._ensure_dsv_session(page, "https://s360.dbschenker.com/")
+
+ goto.assert_called_once_with(page, "https://s360.dbschenker.com/")
+ login.assert_not_called()
+ home.assert_called_once()
+ nav.assert_called_once()
+
+
+def test_navigate_dsv_to_report_form_clicks_program_group_before_program_label(monkeypatch):
+ """Dublin/AWSDU 等路径应先点 program_group 再点 program_label。"""
+ worker = _load_dsv_report_export()
+ page = MagicMock()
+ menu_calls: list[tuple[str, str]] = []
+ group_calls: list[tuple[str, str]] = []
+
+ monkeypatch.setattr(worker, "_env", lambda key, default=None: "")
+ monkeypatch.setattr(worker, "_click_dsv_reports_menu", MagicMock())
+ monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock())
+ monkeypatch.setattr(
+ worker,
+ "_click_dsv_menu_item",
+ lambda page_arg, text, *, next_text="": menu_calls.append((text, next_text)),
+ )
+ monkeypatch.setattr(
+ worker,
+ "_click_dsv_report_group",
+ lambda page_arg, text, *, next_text="": group_calls.append((text, next_text)),
+ )
+ monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
+
+ source = {
+ "navigation": {
+ "program_group": "Dublin",
+ "program_label": "AWSDU - Prod (JDA)",
+ "report_group": "Inventory",
+ "report_name": "On Hand Inventory by Location",
+ }
+ }
+ worker._navigate_dsv_to_report_form(page, source)
+
+ assert menu_calls == [
+ ("Dublin", "AWSDU - Prod (JDA)"),
+ ("AWSDU - Prod (JDA)", "Inventory"),
+ ("On Hand Inventory by Location", ""),
+ ]
+ assert group_calls == [("Inventory", "On Hand Inventory by Location")]
+
+
def test_ensure_dsv_session_skips_login_when_session_active(monkeypatch):
"""batch 首条前若 session 已有效,ensure 不应 goto + login。"""
worker = _load_dsv_report_export()
diff --git a/backend/tests/test_notice_intake.py b/backend/tests/test_notice_intake.py
index fc0a9b93..dfdbc3c7 100644
--- a/backend/tests/test_notice_intake.py
+++ b/backend/tests/test_notice_intake.py
@@ -103,11 +103,12 @@ def test_intake_temp_notice_uploads_splits_accepted_and_rejected(app, tmp_path,
]
with app.app_context():
- accepted, rejected = notice_upload.intake_temp_notice_uploads("req-batch", uploads)
+ accepted, rejected, duplicate_files = notice_upload.intake_temp_notice_uploads("req-batch", uploads)
summary = notice_upload.build_notice_file_summary(
total_files=len(uploads),
accepted=accepted,
rejected=rejected,
+ duplicate_files=duplicate_files,
)
assert len(accepted) == 1
@@ -140,3 +141,97 @@ def test_intake_notice_attachment_extract_failure(app, tmp_path, monkeypatch):
assert result.accepted is False
assert result.status == "extract_failed"
assert result.warnings[0].startswith("notice_extract_failed:")
+
+
+def test_intake_notice_attachment_same_bytes_same_hash(app, tmp_path):
+ """相同字节内容应得到相同 SHA-256(与文件名无关)。"""
+ from app.services.shipping_notice.notice_upload import intake_notice_attachment
+
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
+ raw = "客户:ACME\nA001 x 10".encode("utf-8")
+ with app.app_context():
+ first = intake_notice_attachment(
+ filename="notice-a.txt",
+ raw=raw,
+ storage="temp",
+ temp_request_id="req-hash-a",
+ temp_index=1,
+ )
+ second = intake_notice_attachment(
+ filename="notice-b.txt",
+ raw=raw,
+ storage="temp",
+ temp_request_id="req-hash-b",
+ temp_index=1,
+ )
+
+ assert first.content_hash == second.content_hash
+ assert len(first.content_hash) == 64
+ assert first.content_hash == first.content_hash.lower()
+
+
+def test_intake_notice_attachment_different_bytes_different_hash(app, tmp_path):
+ """不同字节内容应得到不同 SHA-256。"""
+ from app.services.shipping_notice.notice_upload import intake_notice_attachment
+
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
+ with app.app_context():
+ first = intake_notice_attachment(
+ filename="notice-a.txt",
+ raw=b"content-a",
+ storage="temp",
+ temp_request_id="req-diff-a",
+ temp_index=1,
+ )
+ second = intake_notice_attachment(
+ filename="notice-b.txt",
+ raw=b"content-b",
+ storage="temp",
+ temp_request_id="req-diff-b",
+ temp_index=1,
+ )
+
+ assert first.content_hash != second.content_hash
+
+
+def test_intake_temp_notice_uploads_dedupes_same_content_in_one_request(app, tmp_path, monkeypatch):
+ """同一请求内相同内容文件只进入 accepted 一次,duplicate 不计入 rejected。"""
+ from app.services.shipping_notice import notice_upload
+
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
+ monkeypatch.setattr(
+ notice_upload,
+ "extract_notice_text",
+ lambda saved_path: ("客户:ACME\nA001 x 10", {"warnings": [], "file_type": "txt"}),
+ )
+
+ class _Upload:
+ def __init__(self, name: str, raw: bytes, mimetype: str):
+ self.filename = name
+ self._raw = raw
+ self.mimetype = mimetype
+
+ def read(self):
+ return self._raw
+
+ raw = "客户:ACME\nA001 x 10".encode("utf-8")
+ uploads = [
+ _Upload("original.pdf", raw, "application/pdf"),
+ _Upload("copy.pdf", raw, "application/pdf"),
+ _Upload("another-copy.txt", raw, "text/plain"),
+ ]
+
+ with app.app_context():
+ accepted, rejected, duplicate_files = notice_upload.intake_temp_notice_uploads("req-dedupe", uploads)
+ summary = notice_upload.build_notice_file_summary(
+ total_files=len(uploads),
+ accepted=accepted,
+ rejected=rejected,
+ duplicate_files=duplicate_files,
+ )
+
+ assert len(accepted) == 1
+ assert len(rejected) == 0
+ assert summary["duplicate_count"] == 2
+ assert summary["duplicate_files"][0]["duplicate_of"] == "original.pdf"
+ assert accepted[0].to_notice_item()["source_content_hash"] == accepted[0].content_hash
diff --git a/backend/tests/test_rpa_worker_heartbeat.py b/backend/tests/test_rpa_worker_heartbeat.py
new file mode 100644
index 00000000..1c7a5bd8
--- /dev/null
+++ b/backend/tests/test_rpa_worker_heartbeat.py
@@ -0,0 +1,373 @@
+"""
+backend/tests/test_rpa_worker_heartbeat.py
+
+用途:货代库存 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
+依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。
+逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配与 fail-fast 断言。
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from typing import Any
+
+import pytest
+
+from app.core.errors import ServiceUnavailableError
+from app.services.shipping_notice.rpa_worker_heartbeat import (
+ INVENTORY_EXPORT_CAPABILITY,
+ RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
+ RPA_WORKER_OFFLINE_MESSAGE,
+ assert_inventory_rpa_worker_ready,
+ check_inventory_rpa_worker_ready,
+ record_rpa_worker_heartbeat,
+ resolve_backend_rpa_environment,
+ shared_sentinel_name,
+)
+
+
+def _write_shared_sentinel(trigger_dir, *, scope_id: str, host: str = "WIN-RPA") -> None:
+ body = "\n".join([
+ f"scope_id={scope_id}",
+ f"updated_at={datetime.now(timezone.utc).replace(tzinfo=None).isoformat()}",
+ f"host={host}",
+ ])
+ (trigger_dir / shared_sentinel_name()).write_text(body + "\n", encoding="utf-8")
+
+
+def _heartbeat_payload(
+ *,
+ worker_id: str = "win-rpa-1",
+ trigger_dir: str,
+ environment: str | None = None,
+ capabilities: list[str] | None = None,
+ shared_scope_id: str | None = None,
+ timestamp: str | None = None,
+) -> dict:
+ return {
+ "worker_id": worker_id,
+ "hostname": "WIN-RPA-HOST",
+ "environment": environment or resolve_backend_rpa_environment(),
+ "capabilities": capabilities or [INVENTORY_EXPORT_CAPABILITY],
+ "status": "idle",
+ "trigger_dir": trigger_dir,
+ "drop_dir": str(trigger_dir).replace("triggers", "drop"),
+ "shared_scope_id": shared_scope_id or "",
+ "version": "test",
+ "timestamp": timestamp or datetime.now(timezone.utc).replace(tzinfo=None).isoformat(),
+ }
+
+
+def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"):
+ trigger_dir = tmp_path / "triggers"
+ trigger_dir.mkdir()
+ _write_shared_sentinel(trigger_dir, scope_id=scope_id)
+ app.config["ENV_NAME"] = "test"
+ app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
+ app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
+ app.config["FREIGHT_RPA_MOCK"] = "false"
+ return trigger_dir
+
+
+def test_cross_platform_paths_ready_with_shared_scope_id(app, tmp_path):
+ """Windows 与 Ubuntu 路径不同但 shared_scope_id 一致时应 ready。"""
+ trigger_dir = _enable_prod_like_checks(app, tmp_path)
+ windows_trigger = r"C:\HxopsRpaTest\data\inventory_triggers"
+
+ with app.app_context():
+ record_rpa_worker_heartbeat(
+ _heartbeat_payload(
+ trigger_dir=windows_trigger,
+ shared_scope_id="hxops-rpa-test-data",
+ )
+ )
+ result = check_inventory_rpa_worker_ready()
+ assert result.ready is True
+ assert not any("trigger_dir_mismatch" in reason for reason in result.reasons)
+
+
+def test_environment_mismatch_marks_worker_ineligible(app, tmp_path):
+ """Worker 环境与后端不一致时应判定离线。"""
+ trigger_dir = _enable_prod_like_checks(app, tmp_path)
+ app.config["ENV_NAME"] = "test"
+
+ with app.app_context():
+ record_rpa_worker_heartbeat(
+ _heartbeat_payload(
+ trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
+ environment="prod",
+ shared_scope_id="hxops-rpa-test-data",
+ )
+ )
+ result = check_inventory_rpa_worker_ready()
+ assert result.ready is False
+ assert any("environment_mismatch" in reason for reason in result.reasons)
+
+
+def test_shared_scope_mismatch_marks_worker_ineligible(app, tmp_path):
+ """Worker scope 与后端配置不一致时应离线。"""
+ trigger_dir = _enable_prod_like_checks(app, tmp_path)
+
+ with app.app_context():
+ record_rpa_worker_heartbeat(
+ _heartbeat_payload(
+ trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
+ shared_scope_id="hxops-rpa-prod-data",
+ )
+ )
+ result = check_inventory_rpa_worker_ready()
+ assert result.ready is False
+ assert any("shared_scope_mismatch" in reason for reason in result.reasons)
+
+
+def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
+ """test 环境缺少哨兵文件时应判定共享目录不可用。"""
+ trigger_dir = tmp_path / "triggers"
+ trigger_dir.mkdir()
+ app.config["ENV_NAME"] = "test"
+ app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
+ app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
+ app.config["FREIGHT_RPA_MOCK"] = "false"
+
+ with app.app_context():
+ record_rpa_worker_heartbeat(
+ _heartbeat_payload(
+ trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
+ shared_scope_id="hxops-rpa-test-data",
+ )
+ )
+ result = check_inventory_rpa_worker_ready()
+ assert result.ready is False
+ assert "shared_sentinel_missing" in result.reasons
+
+
+def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypatch):
+ """生产策略要求 Redis 时,写入失败应抛存储不可用。"""
+ trigger_dir = tmp_path / "triggers"
+ trigger_dir.mkdir()
+ app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
+ lambda _worker: False,
+ )
+
+ with app.app_context():
+ with pytest.raises(ServiceUnavailableError) as exc_info:
+ record_rpa_worker_heartbeat(_heartbeat_payload(trigger_dir=str(trigger_dir)))
+ assert exc_info.value.code == "RPA.HEARTBEAT_STORAGE_UNAVAILABLE"
+ assert exc_info.value.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE
+
+
+def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path):
+ """fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
+ trigger_dir = tmp_path / "triggers"
+ trigger_dir.mkdir()
+ _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
+ app.config["ENV_NAME"] = "test"
+ app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
+ app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
+ app.config["FREIGHT_RPA_MOCK"] = "false"
+
+ with app.app_context():
+ with pytest.raises(ServiceUnavailableError) as exc_info:
+ assert_inventory_rpa_worker_ready()
+ assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
+ assert "no_worker_heartbeat" in (exc_info.value.details or {}).get("reasons", [])
+ assert (exc_info.value.details or {}).get("detail_message")
+
+
+def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, monkeypatch):
+ """超过 TTL 的心跳应视为离线。"""
+ import time as time_module
+
+ trigger_dir = _enable_prod_like_checks(app, tmp_path)
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90
+ base_now = time_module.time()
+
+ with app.app_context():
+ record_rpa_worker_heartbeat(
+ _heartbeat_payload(
+ trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
+ shared_scope_id="hxops-rpa-test-data",
+ )
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat.time.time",
+ lambda: base_now + 120,
+ )
+ result = check_inventory_rpa_worker_ready()
+ assert result.ready is False
+ assert any("heartbeat_stale" in reason for reason in result.reasons)
+
+
+def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
+ """POST /rpa/heartbeat 应写入心跳并返回 ok。"""
+ trigger_dir = tmp_path / "triggers"
+ trigger_dir.mkdir()
+ app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
+ payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
+
+ res = client.post(
+ "/api/shipping-notice/rpa/heartbeat",
+ headers={"X-Integration-Key": "test-tool-key"},
+ json=payload,
+ )
+ assert res.status_code == 200
+ body = res.get_json()
+ assert body.get("status") == "ok"
+ assert body.get("data", {}).get("worker_id") == payload["worker_id"]
+
+
+def test_rpa_heartbeat_api_rejects_missing_auth(client, app, tmp_path):
+ """心跳接口缺少鉴权应返回未授权。"""
+ trigger_dir = tmp_path / "triggers"
+ trigger_dir.mkdir()
+ app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
+ payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
+
+ res = client.post("/api/shipping-notice/rpa/heartbeat", json=payload)
+ assert res.status_code == 401
+
+
+def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
+ """心跳接口错误 key 应返回未授权。"""
+ trigger_dir = tmp_path / "triggers"
+ trigger_dir.mkdir()
+ app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
+ payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
+
+ res = client.post(
+ "/api/shipping-notice/rpa/heartbeat",
+ headers={"X-Integration-Key": "wrong-key"},
+ json=payload,
+ )
+ assert res.status_code == 401
+
+
+def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path):
+ """排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
+ from app import db
+ from app.models import ScheduleRun, ScheduleTask, User
+ from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
+
+ trigger_dir = _enable_prod_like_checks(app, tmp_path)
+
+ with app.app_context():
+ user = User(username="hb_offline_user", email="hb_offline_user@example.com")
+ db.session.add(user)
+ db.session.flush()
+ task = ScheduleTask(
+ schedule_no="SCH-HB-OFFLINE",
+ name="货代库存每日导出",
+ schedule_type="platform_job",
+ platform_api_path="shipping-inventory-rpa",
+ owner_user_id=user.id,
+ cron_expr="0 3 * * *",
+ enabled=True,
+ )
+ db.session.add(task)
+ db.session.flush()
+ run = ScheduleRun(run_no="RUN20260711080000", schedule_task_id=task.id, status="running")
+ db.session.add(run)
+ db.session.commit()
+
+ total, success, failed, skipped, _details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
+ assert total >= 1
+ assert success == 0
+ assert failed >= 1
+ assert skipped == 0
+ assert errors
+ assert RPA_WORKER_OFFLINE_MESSAGE in errors[0]
+ assert not list(trigger_dir.glob("inventory_export_batch_*.json"))
+ failed_log = next(log for log in logs if isinstance(log, dict) and log.get("status") == "failed")
+ assert failed_log["detail"].get("reasons")
+ assert not any(
+ isinstance(log, dict) and log.get("status") == "awaiting_rpa_callback"
+ for log in logs
+ )
+
+
+def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_path, monkeypatch):
+ """Redis 读取异常应报 heartbeat_storage_unavailable,而非 no_worker_heartbeat。"""
+ trigger_dir = _enable_prod_like_checks(app, tmp_path)
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
+
+ class BrokenRedis:
+ def smembers(self, _key):
+ raise ConnectionError("redis read failed")
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
+ lambda: BrokenRedis(),
+ )
+
+ with app.app_context():
+ result = check_inventory_rpa_worker_ready()
+ assert result.ready is False
+ assert "heartbeat_storage_unavailable" in result.reasons
+ assert "no_worker_heartbeat" not in result.reasons
+ assert result.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE
+
+
+def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch):
+ """test/prod Redis 策略:写入+读取成功时应 ready。"""
+ trigger_dir = _enable_prod_like_checks(app, tmp_path)
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
+ bucket: dict[str, Any] = {"index": set()}
+
+ class FakeRedis:
+ def set(self, key, value, ex=None):
+ bucket[key] = value
+
+ def sadd(self, key, value):
+ bucket.setdefault(key, set()).add(value)
+
+ def expire(self, _key, _ttl):
+ return True
+
+ def smembers(self, key):
+ return bucket.get(key, set())
+
+ def get(self, key):
+ return bucket.get(key)
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
+ lambda: FakeRedis(),
+ )
+
+ with app.app_context():
+ record_rpa_worker_heartbeat(
+ _heartbeat_payload(
+ trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
+ shared_scope_id="hxops-rpa-test-data",
+ )
+ )
+ result = check_inventory_rpa_worker_ready()
+ assert result.ready is True
+
+
+def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path):
+ """未显式配置 scope 时,可从 /mnt/hxops-rpa-* 挂载路径推导。"""
+ from app.services.shipping_notice.rpa_worker_heartbeat import shared_scope_id
+
+ trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
+ trigger_dir.mkdir(parents=True)
+ _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
+ app.config.pop("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", None)
+ app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
+
+ with app.app_context():
+ assert shared_scope_id() == "hxops-rpa-test-data"
diff --git a/backend/tests/test_rpa_worker_heartbeat_alert.py b/backend/tests/test_rpa_worker_heartbeat_alert.py
new file mode 100644
index 00000000..5557850e
--- /dev/null
+++ b/backend/tests/test_rpa_worker_heartbeat_alert.py
@@ -0,0 +1,498 @@
+"""
+backend/tests/test_rpa_worker_heartbeat_alert.py
+
+用途:RPA Worker 心跳告警冷却、Redis/DB 不可用兜底与接收人回退单测。
+依赖:rpa_worker_heartbeat_alert、rpa_worker_heartbeat、models.AppSetting。
+逻辑:验证 DB 权威读取、Redis 陈旧/空 DB 清理、并发 claim、企微失败可重试、恢复与 admin 回退。
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from typing import Any
+
+import pytest
+from sqlalchemy.exc import IntegrityError
+
+from app import db
+from app.models import AppSetting, User
+from app.services.shipping_notice.rpa_worker_heartbeat_alert import (
+ _DB_ALERT_STATE_KEY,
+ _STATUS_SENDING,
+ _claim_alert_send_lock,
+ _load_alert_state,
+ _save_alert_state,
+ maybe_alert_rpa_worker_status,
+ reset_rpa_worker_alert_state_for_tests,
+)
+
+
+def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"):
+ trigger_dir = tmp_path / "triggers"
+ trigger_dir.mkdir()
+ app.config["ENV_NAME"] = "test"
+ app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
+ app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
+ app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
+ app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED"] = True
+ app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600
+ app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = ""
+ app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
+ app.config["FREIGHT_RPA_MOCK"] = "false"
+ return trigger_dir
+
+
+@pytest.fixture(autouse=True)
+def _reset_alert_state():
+ reset_rpa_worker_alert_state_for_tests()
+ yield
+ reset_rpa_worker_alert_state_for_tests()
+
+
+def test_alert_state_memory_fallback_when_redis_save_fails(app, monkeypatch):
+ """Redis set 失败时进程内仍保留冷却状态,避免重复告警。"""
+ class BrokenRedis:
+ def get(self, _key):
+ return None
+
+ def set(self, _key, _value, ex=None):
+ raise ConnectionError("redis down")
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
+ lambda: BrokenRedis(),
+ )
+
+ with app.app_context():
+ _save_alert_state({"status": "storage_unavailable", "last_sent_at": time.time()})
+ loaded = _load_alert_state()
+ assert loaded.get("status") == "storage_unavailable"
+ assert loaded.get("last_sent_at")
+
+
+def test_storage_unavailable_alert_respects_memory_cooldown(app, tmp_path, monkeypatch):
+ """存储异常告警在冷却期内不重复发送(Redis 不可写时依赖进程内状态)。"""
+ _enable_alert_checks(app, tmp_path)
+ send_calls: list[str] = []
+
+ class BrokenRedis:
+ def smembers(self, _key):
+ raise ConnectionError("redis read failed")
+
+ def get(self, _key):
+ return None
+
+ def set(self, _key, _value, ex=None):
+ raise ConnectionError("redis write failed")
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
+ lambda: BrokenRedis(),
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
+ lambda: BrokenRedis(),
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
+ lambda **kwargs: send_calls.append(kwargs["title"]) or True,
+ )
+
+ with app.app_context():
+ first = maybe_alert_rpa_worker_status(force=True)
+ assert first.get("storage_alert_sent") is True
+ assert len(send_calls) == 1
+
+ second = maybe_alert_rpa_worker_status(force=True)
+ assert second.get("storage_alert_sent") is not True
+ assert len(send_calls) == 1
+
+
+def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch):
+ """未配置 ALERT_USERNAMES 时回退已绑企微的 admin。"""
+ _enable_alert_checks(app, tmp_path)
+
+ with app.app_context():
+ from app import db
+
+ admin = User(username="ops_admin", role="admin", email="ops@test.com", wecom_userid="WX001")
+ db.session.add(admin)
+ db.session.commit()
+
+ captured: dict[str, Any] = {}
+
+ def _capture_send(**kwargs):
+ captured.update(kwargs)
+ return True
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
+ _capture_send,
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
+ lambda: type(
+ "Ready",
+ (),
+ {
+ "ready": False,
+ "reasons": ["no_worker_heartbeat"],
+ "detail_message": "offline",
+ "message": "offline",
+ },
+ )(),
+ )
+
+ with app.app_context():
+ from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients
+
+ recipients = _alert_recipients()
+ assert len(recipients) == 1
+ assert recipients[0].username == "ops_admin"
+
+ result = maybe_alert_rpa_worker_status(force=True)
+ assert result.get("alert_sent") is True
+ assert captured.get("title") == "货代库存 RPA Worker 离线"
+
+
+def test_alert_state_persists_to_db_when_redis_unavailable(app, monkeypatch):
+ """Redis 不可用时告警状态应落 AppSetting,供跨进程加载。"""
+ from app.models import AppSetting
+
+ class BrokenRedis:
+ def get(self, _key):
+ return None
+
+ def set(self, _key, _value, ex=None):
+ raise ConnectionError("redis down")
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
+ lambda: BrokenRedis(),
+ )
+
+ with app.app_context():
+ _save_alert_state({"status": "offline", "last_sent_at": 123.0})
+ row = db.session.get(AppSetting, "shipping:rpa:heartbeat:alert:state")
+ assert row is not None
+ loaded = _load_alert_state()
+ assert loaded.get("status") == "offline"
+ assert loaded.get("last_sent_at") == 123.0
+
+
+def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch, caplog):
+ """无接收人且无 admin 企微绑定时应打出部署缺口 warning。"""
+ import logging
+
+ _enable_alert_checks(app, tmp_path)
+ app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
+ lambda: type(
+ "Ready",
+ (),
+ {
+ "ready": False,
+ "reasons": ["no_worker_heartbeat"],
+ "detail_message": "offline",
+ "message": "offline",
+ },
+ )(),
+ )
+
+ with caplog.at_level(logging.WARNING):
+ with app.app_context():
+ result = maybe_alert_rpa_worker_status(force=True)
+ assert result.get("alert_sent") is not True
+ assert any("no wecom recipients" in record.message for record in caplog.records)
+
+
+def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatch):
+ """显式配置的用户名优先于 admin 回退。"""
+ _enable_alert_checks(app, tmp_path)
+ app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = "oncall_user"
+
+ with app.app_context():
+ from app import db
+
+ db.session.add(User(username="ops_admin", role="admin", email="ops@test.com", wecom_userid="WX001"))
+ db.session.add(
+ User(username="oncall_user", role="user", email="oncall@test.com", wecom_userid="WX002")
+ )
+ db.session.commit()
+
+ from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients
+
+ recipients = _alert_recipients()
+ assert len(recipients) == 1
+ assert recipients[0].username == "oncall_user"
+
+
+def test_alert_wecom_send_failure_allows_retry_before_cooldown(app, tmp_path, monkeypatch):
+ """企微首次发送失败时不应进入长冷却,下一次检查应允许重试。"""
+ _enable_alert_checks(app, tmp_path)
+ send_attempts = {"count": 0}
+
+ def _flaky_send(**_kwargs):
+ send_attempts["count"] += 1
+ return send_attempts["count"] >= 2
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
+ _flaky_send,
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
+ lambda: type(
+ "Ready",
+ (),
+ {
+ "ready": False,
+ "reasons": ["no_worker_heartbeat"],
+ "detail_message": "offline",
+ "message": "offline",
+ },
+ )(),
+ )
+
+ with app.app_context():
+ db.session.add(
+ User(username="ops_admin", role="admin", email="ops@test.com", wecom_userid="WX001")
+ )
+ db.session.commit()
+
+ first = maybe_alert_rpa_worker_status(force=True)
+ assert first.get("alert_sent") is not True
+ assert send_attempts["count"] == 1
+ after_fail = _load_alert_state()
+ assert after_fail.get("status") != "offline"
+ assert float(after_fail.get("last_sent_at") or 0) == 0
+
+ second = maybe_alert_rpa_worker_status(force=True)
+ assert second.get("alert_sent") is True
+ assert send_attempts["count"] == 2
+ after_success = _load_alert_state()
+ assert after_success.get("status") == "offline"
+ assert float(after_success.get("last_sent_at") or 0) > 0
+
+ third = maybe_alert_rpa_worker_status(force=True)
+ assert third.get("alert_sent") is not True
+ assert send_attempts["count"] == 2
+
+
+def test_concurrent_first_claim_integrity_error_does_not_claim(app, monkeypatch):
+ """并发首次插入竞争:IntegrityError 后应回读 DB 并放弃 claim,不走内存兜底发送。"""
+ winner_lock = {
+ "status": _STATUS_SENDING,
+ "sending_target": "offline",
+ "sending_started_at": time.time(),
+ "last_sent_at": 0,
+ "reasons": ["no_worker_heartbeat"],
+ }
+
+ with app.app_context():
+ db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=json.dumps(winner_lock)))
+ db.session.commit()
+
+ def _raise_integrity(**_kwargs):
+ raise IntegrityError("INSERT", {}, Exception("duplicate key"))
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._claim_alert_send_lock_db",
+ _raise_integrity,
+ )
+
+ lock_state = {
+ "status": _STATUS_SENDING,
+ "sending_target": "offline",
+ "sending_started_at": time.time(),
+ "last_sent_at": 0,
+ "reasons": ["no_worker_heartbeat"],
+ }
+ claimed, existing = _claim_alert_send_lock(
+ lock_state=lock_state,
+ should_send_fn=lambda _existing: True,
+ )
+ assert claimed is False
+ assert existing.get("status") == _STATUS_SENDING
+ assert existing.get("sending_target") == "offline"
+
+
+def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
+ """过期 sending 锁且 sending_target=offline 时,Worker 恢复后应发送恢复通知。"""
+ _enable_alert_checks(app, tmp_path)
+ app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS"] = 60
+
+ stale_sending = {
+ "status": _STATUS_SENDING,
+ "sending_target": "offline",
+ "sending_started_at": time.time() - 120,
+ "last_sent_at": time.time() - 3600,
+ "reasons": ["no_worker_heartbeat"],
+ }
+
+ captured: dict[str, Any] = {}
+
+ def _capture_send(**kwargs):
+ captured.update(kwargs)
+ return True
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
+ _capture_send,
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
+ lambda: type(
+ "Ready",
+ (),
+ {
+ "ready": True,
+ "reasons": [],
+ "detail_message": "",
+ "message": "",
+ },
+ )(),
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
+ lambda: type("BrokenRedis", (), {"get": lambda *_a, **_k: None, "set": lambda *_a, **_k: None, "delete": lambda *_a, **_k: None})(),
+ )
+
+ with app.app_context():
+ db.session.add(
+ User(username="ops_admin", role="admin", email="ops@test.com", wecom_userid="WX001")
+ )
+ db.session.commit()
+ _save_alert_state(stale_sending)
+
+ result = maybe_alert_rpa_worker_status(force=True)
+ assert result.get("recovery_sent") is True
+ assert captured.get("title") == "货代库存 RPA Worker 已恢复"
+ after = _load_alert_state()
+ assert after.get("status") == "ready"
+
+
+def test_load_alert_state_prefers_db_over_stale_redis(app, monkeypatch):
+ """Redis 缓存为旧 offline 时,应以 DB 中较新的 ready 状态为准并回写 Redis。"""
+ stale_redis = {
+ "status": "offline",
+ "last_sent_at": 100.0,
+ "updated_at": 100.0,
+ }
+ fresh_db = {
+ "status": "ready",
+ "last_sent_at": 200.0,
+ "updated_at": 200.0,
+ }
+ redis_bucket: dict[str, str] = {
+ "shipping:rpa:heartbeat:alert:state": json.dumps(stale_redis, ensure_ascii=False),
+ }
+
+ class FakeRedis:
+ def get(self, key):
+ return redis_bucket.get(key)
+
+ def set(self, key, value, ex=None):
+ redis_bucket[key] = value
+
+ def delete(self, key):
+ redis_bucket.pop(key, None)
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
+ lambda: FakeRedis(),
+ )
+
+ with app.app_context():
+ db.session.add(AppSetting(key=_DB_ALERT_STATE_KEY, value=json.dumps(fresh_db, ensure_ascii=False)))
+ db.session.commit()
+
+ loaded = _load_alert_state()
+ assert loaded.get("status") == "ready"
+ assert float(loaded.get("updated_at") or 0) == 200.0
+
+ cached = json.loads(redis_bucket[_DB_ALERT_STATE_KEY])
+ assert cached.get("status") == "ready"
+ assert float(cached.get("updated_at") or 0) == 200.0
+
+
+def test_load_alert_state_overwrites_newer_stale_redis_from_db(app, monkeypatch):
+ """Redis 时间戳更新但内容错误时,仍应以 DB 状态无条件覆盖 Redis。"""
+ newer_wrong_redis = {
+ "status": "offline",
+ "last_sent_at": 300.0,
+ "updated_at": 300.0,
+ }
+ authoritative_db = {
+ "status": "ready",
+ "last_sent_at": 200.0,
+ "updated_at": 200.0,
+ }
+ redis_bucket: dict[str, str] = {
+ "shipping:rpa:heartbeat:alert:state": json.dumps(newer_wrong_redis, ensure_ascii=False),
+ }
+
+ class FakeRedis:
+ def get(self, key):
+ return redis_bucket.get(key)
+
+ def set(self, key, value, ex=None):
+ redis_bucket[key] = value
+
+ def delete(self, key):
+ redis_bucket.pop(key, None)
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
+ lambda: FakeRedis(),
+ )
+
+ with app.app_context():
+ db.session.add(
+ AppSetting(key=_DB_ALERT_STATE_KEY, value=json.dumps(authoritative_db, ensure_ascii=False))
+ )
+ db.session.commit()
+
+ loaded = _load_alert_state()
+ assert loaded.get("status") == "ready"
+
+ cached = json.loads(redis_bucket[_DB_ALERT_STATE_KEY])
+ assert cached.get("status") == "ready"
+ assert float(cached.get("updated_at") or 0) == 200.0
+
+
+def test_load_alert_state_clears_stale_redis_when_db_has_no_row(app, monkeypatch):
+ """DB 可读但无状态行时,应返回空状态并清理 Redis 残留,不回退旧缓存。"""
+ stale_redis = {
+ "status": "offline",
+ "last_sent_at": 100.0,
+ "updated_at": 100.0,
+ }
+ redis_bucket: dict[str, str] = {
+ "shipping:rpa:heartbeat:alert:state": json.dumps(stale_redis, ensure_ascii=False),
+ }
+
+ class FakeRedis:
+ def get(self, key):
+ return redis_bucket.get(key)
+
+ def set(self, key, value, ex=None):
+ redis_bucket[key] = value
+
+ def delete(self, key):
+ redis_bucket.pop(key, None)
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
+ lambda: FakeRedis(),
+ )
+
+ with app.app_context():
+ loaded = _load_alert_state()
+ assert loaded == {}
+ assert "shipping:rpa:heartbeat:alert:state" not in redis_bucket
diff --git a/backend/tests/test_shipping_notice_batches.py b/backend/tests/test_shipping_notice_batches.py
index 786b7ebb..a9e06c4d 100644
--- a/backend/tests/test_shipping_notice_batches.py
+++ b/backend/tests/test_shipping_notice_batches.py
@@ -19,6 +19,7 @@ from app.jobs.queue import process_next_job
from app.jobs.types import JobType
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs, tools as shipping_tools
from app.services.shipping_notice.progress_workflow import auto_progress
+from tests.conftest import seed_task_inventory_source
def _tool_headers(app):
@@ -358,21 +359,15 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
assert result["data"]["batch"]["batch_no"] == result["batch_no"]
assert result["data"]["tasks"][0]["parse_status"] == "deferred"
assert result["data"]["focus_task"]["task_no"] == result["data"]["tasks"][0]["task_id"]
- assert result["file_summary"] == {
- "total_files": 1,
- "accepted_count": 1,
- "rejected_count": 0,
- "accepted_files": [
- {
- "filename": "notice-a.txt",
- "source_type": "manual",
- "source_file_type": "text/plain",
- "text_length": len("客户:ACME\nA001 x 10"),
- "warnings": [],
- }
- ],
- "rejected_files": [],
- }
+ file_summary = result["file_summary"]
+ assert file_summary["total_files"] == 1
+ assert file_summary["accepted_count"] == 1
+ assert file_summary["rejected_count"] == 0
+ assert file_summary["duplicate_count"] == 0
+ assert file_summary["accepted_files"][0]["filename"] == "notice-a.txt"
+ assert len(file_summary["accepted_files"][0]["content_hash"]) == 64
+ assert file_summary["rejected_files"] == []
+ assert file_summary["duplicate_files"] == []
with app.app_context():
task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).first()
@@ -506,7 +501,11 @@ def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_cr
payload = res.get_json()
assert payload["success"] is False
assert payload["error"]["message"] == "未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试"
- assert payload["error"]["details"]["file_summary"]["rejected_files"] == [
+ file_summary = payload["error"]["details"]["file_summary"]
+ assert file_summary["accepted_count"] == 0
+ assert file_summary["rejected_count"] == 1
+ assert file_summary["duplicate_count"] == 1
+ assert file_summary["rejected_files"] == [
{
"filename": "notice-a.pdf",
"source_type": "pdf",
@@ -515,17 +514,9 @@ def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_cr
"message": "notice text is empty after extraction",
"warnings": ["ocr_empty"],
},
- {
- "filename": "notice-b.pdf",
- "source_type": "pdf",
- "source_file_type": "application/pdf",
- "reason": "empty_text",
- "message": "notice text is empty after extraction",
- "warnings": ["ocr_empty"],
- },
]
- assert payload["error"]["details"]["file_summary"]["accepted_count"] == 0
- assert payload["error"]["details"]["file_summary"]["rejected_count"] == 2
+ assert file_summary["duplicate_files"][0]["filename"] == "notice-b.pdf"
+ assert file_summary["duplicate_files"][0]["duplicate_of"] == "notice-a.pdf"
with app.app_context():
assert ShippingBatch.query.count() == batch_count_before
@@ -655,6 +646,7 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
}
},
)
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
db.session.commit()
@@ -740,6 +732,7 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
+ app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
with app.app_context():
user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com")
db.session.add(user)
@@ -792,8 +785,7 @@ def test_inventory_source_rules_cover_dsv360_programs(app):
resolution = resolve_inventory_source(task)
assert resolution.status == "resolved"
- assert resolution.source is not None
- assert resolution.source["source_code"] == expected_code
+ assert resolution.source_code == expected_code
def test_auto_progress_unknown_destination_requires_inventory_source_review(app):
@@ -822,7 +814,7 @@ def test_auto_progress_unknown_destination_requires_inventory_source_review(app)
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "inventory_source_review"
- assert task.process_status == "waiting_inventory"
+ assert task.process_status == "pending_review"
assert task.pending_human_reason == "inventory_source_unresolved"
assert task.step_payload_json["inventory_source_resolution"]["status"] == "unresolved"
assert len(result["data"]["inventory_source_candidates"]) >= 4
@@ -902,6 +894,43 @@ def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
]
+def test_parse_stage_ui_state_lists_all_issues(app):
+ """文件解析阶段 UI State 应一次列出库存源问题、解析 warnings(含存量延后低置信度提示)。"""
+ from app.services.shipping_notice.ui_state import build_task_ui_state
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-PARSE-ISSUES-LIST",
+ source_type="pdf",
+ process_status="pending_review",
+ pending_human_reason="inventory_source_unresolved",
+ error_message="无法根据发货通知唯一确定库存查询来源",
+ parse_confidence=0.4,
+ step_payload_json={
+ "pending_parse_review_after_source": True,
+ "inventory_source_resolution": {"status": "unresolved", "candidates": []},
+ "current_step_progress": {
+ "extra": {
+ "warnings": [
+ "部分订单行缺少 Reservation ID,可能影响精确匹配。",
+ "parse_fallback_heuristic",
+ ]
+ }
+ },
+ },
+ )
+
+ ui_state = build_task_ui_state(task)
+ issues = ui_state["summary"]["issues"]
+
+ assert ui_state["checkpoint"] == "inventory_source_review"
+ assert issues[0] == "无法根据发货通知唯一确定库存查询来源"
+ assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues
+ assert "解析引擎回退到启发式规则,请人工核对字段。" in issues
+ assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues
+ assert len(issues) == 4
+
+
def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client):
"""任务/批次工作台读接口直接返回 UI State,Chat 和工作台不再各自推导状态。"""
headers = _workspace_headers(app)
@@ -1447,6 +1476,7 @@ def test_run_shipping_parse_via_dify_passes_task_context_without_persisting_chat
agent = Agent(
name="货代发货通知 Agent",
+ agent_code="shipping_notice",
dify_api_key="test-dify-key",
is_active=True,
)
@@ -1655,3 +1685,229 @@ def test_create_empty_batch_returns_batch_shell(app, client):
assert data["status"] == "ok"
assert data["batch_no"].startswith("SB-")
assert data["data"]["file_count"] == 1
+
+
+def _workspace_user_headers(app, username: str):
+ """创建独立工作台用户并返回 Authorization header。"""
+ with app.app_context():
+ user = User(
+ username=username,
+ email=f"{username}@example.com",
+ role="user",
+ status="active",
+ )
+ user.set_password("password")
+ db.session.add(user)
+ db.session.commit()
+ token = issue_local_access_token(user)
+ user_id = user.id
+ return {"Authorization": f"Bearer {token}"}, user_id
+
+
+def test_create_batch_idempotency_key_replays_same_batch(app, client, monkeypatch):
+ """相同建单幂等键调用两次只创建一个批次,第二次不启动编排器。"""
+ headers = _workspace_headers(app)
+ idempotency_key = "batch-idem-001"
+ started: list[str] = []
+
+ def fake_start(batch_no: str | None) -> bool:
+ if batch_no:
+ started.append(batch_no)
+ return True
+
+ monkeypatch.setattr(batch_orchestrator, "start_batch_orchestrator", fake_start)
+ raw = "客户:ACME\nA001 x 10".encode("utf-8")
+
+ def _payload():
+ return {
+ "files": (BytesIO(raw), "notice-a.txt"),
+ "conversation_id": "conv-idem-001",
+ "idempotency_key": idempotency_key,
+ }
+
+ first = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers={**headers, "Idempotency-Key": idempotency_key},
+ data=_payload(),
+ content_type="multipart/form-data",
+ )
+ second = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers={**headers, "Idempotency-Key": idempotency_key},
+ data=_payload(),
+ content_type="multipart/form-data",
+ )
+ assert first.status_code == 200
+ assert second.status_code == 200
+ first_result = _unwrap_ok(first)
+ second_result = _unwrap_ok(second)
+ assert first_result["batch_no"] == second_result["batch_no"]
+ assert second_result.get("idempotent_replay") is True
+ assert second_result["data"]["orchestrator_started"] is False
+ assert started == [first_result["batch_no"]]
+
+ with app.app_context():
+ batch_count = ShippingBatch.query.filter_by(create_idempotency_key=idempotency_key).count()
+ task_count = ShippingTask.query.filter_by(batch_id=ShippingBatch.query.filter_by(batch_no=first_result["batch_no"]).first().id).count()
+ assert batch_count == 1
+ assert task_count == 1
+
+
+def test_create_batch_same_request_duplicate_files_create_one_task(app, client):
+ """同一次上传两个内容相同文件只创建一个任务。"""
+ headers = _workspace_headers(app)
+ raw = "客户:ACME\nA001 x 10".encode("utf-8")
+ res = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers=headers,
+ data={
+ "files": [
+ (BytesIO(raw), "notice-a.txt"),
+ (BytesIO(raw), "notice-b.txt"),
+ ],
+ "conversation_id": "conv-dedupe-files",
+ "idempotency_key": "batch-dedupe-files-001",
+ },
+ content_type="multipart/form-data",
+ )
+ result = _unwrap_ok(res)
+ assert result["file_summary"]["duplicate_count"] == 1
+ assert len(result["data"]["tasks"]) == 1
+
+
+def test_create_batch_persists_source_content_hash(app, client):
+ """建单后任务应保存完整 SHA-256 内容哈希。"""
+ import hashlib
+
+ headers = _workspace_headers(app)
+ raw = "客户:ACME\nA001 x 10".encode("utf-8")
+ res = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers=headers,
+ data={
+ "files": (BytesIO(raw), "notice-a.txt"),
+ "conversation_id": "conv-hash-persist",
+ "idempotency_key": "batch-hash-persist-001",
+ },
+ content_type="multipart/form-data",
+ )
+ result = _unwrap_ok(res)
+ expected_hash = hashlib.sha256(raw).hexdigest().lower()
+ with app.app_context():
+ task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).first()
+ assert task is not None
+ assert task.source_content_hash == expected_hash
+
+
+def test_create_batch_idempotency_key_scoped_per_user(app, client):
+ """不同用户使用相同幂等键互不冲突。"""
+ headers_a, _user_a = _workspace_user_headers(app, "shipping_idem_user_a")
+ headers_b, _user_b = _workspace_user_headers(app, "shipping_idem_user_b")
+ idempotency_key = "shared-idem-key"
+
+ def _payload():
+ return {
+ "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
+ "idempotency_key": idempotency_key,
+ }
+
+ res_a = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers={**headers_a, "Idempotency-Key": idempotency_key},
+ data=_payload(),
+ content_type="multipart/form-data",
+ )
+ res_b = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers={**headers_b, "Idempotency-Key": idempotency_key},
+ data=_payload(),
+ content_type="multipart/form-data",
+ )
+ batch_a = _unwrap_ok(res_a)["batch_no"]
+ batch_b = _unwrap_ok(res_b)["batch_no"]
+ assert batch_a != batch_b
+
+
+def test_create_batch_without_idempotency_key_still_works(app, client):
+ """兼容期:缺少幂等键的旧请求仍可建批。"""
+ headers = _workspace_headers(app)
+ res = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers=headers,
+ data={
+ "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
+ "conversation_id": "conv-legacy-no-idem",
+ },
+ content_type="multipart/form-data",
+ )
+ result = _unwrap_ok(res)
+ assert result["batch_no"].startswith("SB-")
+
+
+def test_create_batch_idempotency_replays_after_tasks_exist(app, client):
+ """相同幂等键在首批任务已落库后应幂等重放,而非返回文件重复错误。"""
+ headers = _workspace_headers(app)
+ idempotency_key = "batch-idem-after-tasks"
+ raw = "客户:ACME\nA001 x 10".encode("utf-8")
+
+ def _payload():
+ return {
+ "files": (BytesIO(raw), "notice-a.txt"),
+ "conversation_id": "conv-idem-after-tasks",
+ "idempotency_key": idempotency_key,
+ }
+
+ first = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers={**headers, "Idempotency-Key": idempotency_key},
+ data=_payload(),
+ content_type="multipart/form-data",
+ )
+ second = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers={**headers, "Idempotency-Key": idempotency_key},
+ data=_payload(),
+ content_type="multipart/form-data",
+ )
+ assert first.status_code == 200
+ assert second.status_code == 200
+ first_result = _unwrap_ok(first)
+ second_result = _unwrap_ok(second)
+ assert second_result.get("idempotent_replay") is True
+ assert first_result["batch_no"] == second_result["batch_no"]
+
+ with app.app_context():
+ task_count = ShippingTask.query.filter_by(
+ batch_id=ShippingBatch.query.filter_by(batch_no=first_result["batch_no"]).first().id
+ ).count()
+ assert task_count == 1
+
+
+def test_create_batch_idempotency_key_conflicts_on_different_files(app, client):
+ """相同幂等键但文件集合不同时应返回 SHIPPING.BATCH_IDEMPOTENCY_CONFLICT。"""
+ headers = _workspace_headers(app)
+ idempotency_key = "batch-idem-conflict-001"
+ first = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers={**headers, "Idempotency-Key": idempotency_key},
+ data={
+ "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
+ "idempotency_key": idempotency_key,
+ },
+ content_type="multipart/form-data",
+ )
+ assert first.status_code == 200
+
+ second = client.post(
+ "/api/workspace/shipping-batches/create-from-notices",
+ headers={**headers, "Idempotency-Key": idempotency_key},
+ data={
+ "files": (BytesIO("客户:BETA\nB002 x 20".encode("utf-8")), "notice-b.txt"),
+ "idempotency_key": idempotency_key,
+ },
+ content_type="multipart/form-data",
+ )
+ assert second.status_code == 409
+ payload = second.get_json()
+ assert payload["success"] is False
+ assert payload["error"]["code"] == "SHIPPING.BATCH_IDEMPOTENCY_CONFLICT"
diff --git a/backend/tests/test_shipping_notice_business_dedup.py b/backend/tests/test_shipping_notice_business_dedup.py
new file mode 100644
index 00000000..5a6cf10d
--- /dev/null
+++ b/backend/tests/test_shipping_notice_business_dedup.py
@@ -0,0 +1,750 @@
+"""
+backend/tests/test_shipping_notice_business_dedup.py
+
+用途:第三阶段业务指纹、重复检测与决策门闩核心用例。
+依赖:pytest、business_fingerprint、duplicate_detection、batch_from_intakes。
+逻辑:覆盖指纹稳定性、阻断门闩、open_existing / create_revision 分流。
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+
+from app import db
+from app.core.errors import ConflictError
+from app.models import (
+ FileAsset,
+ ShippingBatch,
+ ShippingNoticeCandidate,
+ ShippingNoticeDocument,
+ ShippingNoticeIntake,
+ ShippingTask,
+ User,
+)
+from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
+from app.services.shipping_notice.business_fingerprint import build_business_fingerprint
+from app.services.shipping_notice.duplicate_detection import (
+ detect_duplicates_for_candidate,
+ detect_duplicates_for_intake,
+)
+from app.services.shipping_notice.intake_service import resolve_intake_duplicate
+
+
+@pytest.fixture
+def dedup_user(app):
+ with app.app_context():
+ user = User(username='dedup-user', email='dedup@example.com', password_hash='x', role='user')
+ db.session.add(user)
+ db.session.commit()
+ yield user
+
+
+def _seed_parsed_intake(
+ user_id: int,
+ *,
+ intake_no: str,
+ hash_value: str,
+ business_summary: dict,
+ fingerprint: dict,
+):
+ asset = FileAsset(
+ asset_no=f'FA-{intake_no}',
+ owner_user_id=user_id,
+ original_filename='notice.txt',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{user_id}/test/{intake_no}.txt',
+ content_hash=hash_value,
+ file_size=12,
+ mime_type='text/plain',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ )
+ db.session.add(asset)
+ db.session.flush()
+ intake = ShippingNoticeIntake(
+ intake_no=intake_no,
+ asset_id=asset.id,
+ user_id=user_id,
+ purpose='shipping_notice',
+ parse_status='parsed',
+ parser_version='v1',
+ extracted_text='SKU001 qty 10',
+ structured_result_json={'business_summary': business_summary},
+ business_fingerprint=fingerprint.get('fingerprint'),
+ fingerprint_version=fingerprint.get('version'),
+ fingerprint_strength=fingerprint.get('strength'),
+ duplicate_status='none',
+ duplicate_matches_json=[],
+ )
+ db.session.add(intake)
+ db.session.commit()
+ return asset, intake
+
+
+def test_fingerprint_stable_across_line_order():
+ base = {
+ 'customer_code': 'C1',
+ 'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
+ 'required_date': '2026-01-01',
+ 'lines': [
+ {'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
+ {'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
+ ],
+ }
+ swapped = {
+ **base,
+ 'lines': [
+ {'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
+ {'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
+ ],
+ }
+ a = build_business_fingerprint(base)
+ b = build_business_fingerprint(swapped)
+ assert a['strength'] == 'medium'
+ assert a['fingerprint'] == b['fingerprint']
+
+
+def test_fingerprint_changes_with_qty():
+ base = {
+ 'customer_code': 'C1',
+ 'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
+ 'required_date': '2026-01-01',
+ 'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'}],
+ }
+ changed = {**base, 'lines': [{'sku': 'A', 'qty': 9, 'reservation_id': '1000000002'}]}
+ assert build_business_fingerprint(base)['fingerprint'] != build_business_fingerprint(changed)['fingerprint']
+
+
+def test_blocking_create_requires_resolution(app, dedup_user):
+ with app.app_context():
+ summary = {
+ 'customer_code': 'C1',
+ 'po_number': 'PO-9',
+ 'reservation_ids': ['1000140351'],
+ 'lines': [],
+ }
+ fp = build_business_fingerprint(summary)
+ asset, intake = _seed_parsed_intake(
+ dedup_user.id,
+ intake_no='SNI-DEDUP-BLOCK',
+ hash_value='hash-block-1',
+ business_summary=summary,
+ fingerprint=fp,
+ )
+ batch = ShippingBatch(batch_no='SB-DEDUP-OLD', user_id=dedup_user.id, file_count=1)
+ db.session.add(batch)
+ db.session.flush()
+ existing = ShippingTask(
+ task_no='SN-DEDUP-OLD',
+ batch_id=batch.id,
+ user_id=dedup_user.id,
+ source_type='manual',
+ process_status='waiting_inventory',
+ business_fingerprint=fp['fingerprint'],
+ fingerprint_version=fp['version'],
+ document_version=1,
+ )
+ db.session.add(existing)
+ db.session.commit()
+
+ result = detect_duplicates_for_intake(intake=intake, asset=asset, business_summary=summary, fingerprint_result=fp)
+ assert result['blocking'] is True
+ assert result['status'] == 'same_active_task'
+
+ with pytest.raises(ConflictError) as excinfo:
+ create_shipping_batch_from_intakes(
+ user_id=dedup_user.id,
+ conversation_id='conv-dedup',
+ intake_nos=[intake.intake_no],
+ create_idempotency_key='idem-block',
+ )
+ assert excinfo.value.code == 'SHIPPING_NOTICE.DUPLICATE_RESOLUTION_REQUIRED'
+
+
+def test_open_existing_does_not_create_batch(app, dedup_user):
+ with app.app_context():
+ summary = {
+ 'customer_code': 'C1',
+ 'po_number': 'PO-OPEN',
+ 'reservation_ids': ['1000140352'],
+ 'lines': [],
+ }
+ fp = build_business_fingerprint(summary)
+ asset, intake = _seed_parsed_intake(
+ dedup_user.id,
+ intake_no='SNI-DEDUP-OPEN',
+ hash_value='hash-open-1',
+ business_summary=summary,
+ fingerprint=fp,
+ )
+ batch = ShippingBatch(batch_no='SB-OPEN-OLD', user_id=dedup_user.id, file_count=1)
+ db.session.add(batch)
+ db.session.flush()
+ existing = ShippingTask(
+ task_no='SN-OPEN-OLD',
+ batch_id=batch.id,
+ user_id=dedup_user.id,
+ source_type='manual',
+ process_status='waiting_inventory',
+ business_fingerprint=fp['fingerprint'],
+ fingerprint_version=fp['version'],
+ document_version=1,
+ )
+ db.session.add(existing)
+ db.session.commit()
+
+ # 模拟前端已决策:写入 resolution,避免 resolve 内 refresh 对 SQLite 时间敏感
+ intake.duplicate_status = 'same_active_task'
+ intake.duplicate_matches_json = [
+ {
+ 'task_no': existing.task_no,
+ 'process_status': existing.process_status,
+ 'document_version': 1,
+ 'match_type': 'business_fingerprint',
+ 'matched_fields': ['customer_code', 'po_number'],
+ 'lifecycle': 'active',
+ }
+ ]
+ intake.duplicate_resolution = 'open_existing'
+ intake.duplicate_target_task_no = existing.task_no
+ intake.duplicate_resolved_by_id = dedup_user.id
+ intake.duplicate_resolved_at = datetime.utcnow()
+ db.session.commit()
+
+ with patch(
+ 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items'
+ ) as create_mock:
+ result = create_shipping_batch_from_intakes(
+ user_id=dedup_user.id,
+ conversation_id='conv-open',
+ intake_nos=[intake.intake_no],
+ create_idempotency_key='idem-open',
+ )
+ create_mock.assert_not_called()
+
+ assert result.get('batch_no') in (None, '')
+ refreshed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert refreshed.parse_status == 'consumed'
+ assert refreshed.consumed_task_id == existing.id
+
+
+def test_create_revision_sets_supersedes_and_version(app, dedup_user, monkeypatch):
+ """create_revision 应写入 supersedes_task_id 与 document_version+1。"""
+ with app.app_context():
+ summary = {
+ 'customer_code': 'C1',
+ 'po_number': 'PO-REV-1',
+ 'reservation_ids': ['12345678'],
+ 'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '12345678'}],
+ }
+ fp = build_business_fingerprint(summary)
+ asset, intake = _seed_parsed_intake(
+ dedup_user.id,
+ intake_no='SNI-REV-1',
+ hash_value='hash-rev-1',
+ business_summary=summary,
+ fingerprint=fp,
+ )
+ existing = ShippingTask(
+ task_no='SN-REV-BASE',
+ user_id=dedup_user.id,
+ source_type='manual',
+ process_status='uploaded',
+ business_fingerprint=fp.get('fingerprint'),
+ fingerprint_version=fp.get('version'),
+ document_version=1,
+ )
+ db.session.add(existing)
+ db.session.commit()
+
+ intake.duplicate_status = 'same_completed_task'
+ intake.duplicate_matches_json = [
+ {
+ 'task_no': existing.task_no,
+ 'process_status': 'uploaded',
+ 'document_version': 1,
+ 'match_type': 'business_fingerprint',
+ 'matched_fields': ['customer_code', 'po_number'],
+ }
+ ]
+ intake.duplicate_resolution = 'create_revision'
+ intake.duplicate_target_task_no = existing.task_no
+ intake.duplicate_resolved_by_id = dedup_user.id
+ intake.duplicate_resolved_at = datetime.utcnow()
+ db.session.commit()
+
+ def _fake_create(**kwargs):
+ notice_items = kwargs['notice_items']
+ item = notice_items[0]
+ batch = ShippingBatch(
+ batch_no='SB-REV-1',
+ user_id=dedup_user.id,
+ file_count=1,
+ create_idempotency_key=kwargs.get('create_idempotency_key'),
+ )
+ db.session.add(batch)
+ db.session.flush()
+ task = ShippingTask(
+ task_no='SN-REV-NEW',
+ batch_id=batch.id,
+ user_id=dedup_user.id,
+ source_type='manual',
+ source_content_hash=item.get('source_content_hash'),
+ source_asset_id=item.get('source_asset_id'),
+ source_intake_id=item.get('source_intake_id'),
+ business_fingerprint=item.get('business_fingerprint'),
+ fingerprint_version=item.get('fingerprint_version'),
+ document_version=int(item.get('document_version') or 1),
+ supersedes_task_id=item.get('supersedes_task_id'),
+ duplicate_resolution_type=item.get('duplicate_resolution_type'),
+ raw_content=item.get('raw_text'),
+ process_status='created',
+ )
+ db.session.add(task)
+ db.session.commit()
+ return {
+ 'status': 'ok',
+ 'batch_no': batch.batch_no,
+ 'data': {
+ 'batch': {'batch_no': batch.batch_no, 'id': batch.id},
+ 'tasks': [{'task_id': task.task_no}],
+ 'focus_task': {
+ 'task_no': task.task_no,
+ 'document_version': task.document_version,
+ 'duplicate_resolution_type': task.duplicate_resolution_type,
+ 'supersedes_task_no': existing.task_no,
+ },
+ },
+ }
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
+ _fake_create,
+ )
+ # 确保 detect 仍命中
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake',
+ lambda **kwargs: {
+ 'status': 'same_completed_task',
+ 'blocking': True,
+ 'fingerprint': fp.get('fingerprint'),
+ 'fingerprint_version': fp.get('version'),
+ 'fingerprint_strength': fp.get('strength'),
+ 'matches': intake.duplicate_matches_json,
+ 'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
+ },
+ )
+
+ result = create_shipping_batch_from_intakes(
+ user_id=dedup_user.id,
+ conversation_id='conv-rev',
+ intake_nos=[intake.intake_no],
+ create_idempotency_key='idem-rev',
+ )
+ assert result['batch_no'] == 'SB-REV-1'
+ created = db.session.query(ShippingTask).filter_by(task_no='SN-REV-NEW').one()
+ assert created.supersedes_task_id == existing.id
+ assert int(created.document_version) == 2
+ assert created.duplicate_resolution_type == 'revision'
+
+
+def test_fingerprint_strong_with_customer_name_po_reservation():
+ """启发式常只有客户名:客户名 + PO + Reservation 应产出 strong 指纹。"""
+ summary = {
+ 'customer_name': 'ACME',
+ 'customer_code': None,
+ 'po_number': 'PO-20260714',
+ 'reservation_ids': ['1000140351'],
+ 'lines': [{'sku': 'SKU001', 'qty': 10, 'reservation_id': '1000140351'}],
+ }
+ fp = build_business_fingerprint(summary)
+ assert fp['strength'] == 'strong'
+ assert fp['fingerprint']
+ assert fp['components'].get('customer_name') == 'ACME'
+
+
+def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
+ """pending_review 属活跃态:业务指纹命中应为 same_active_task 且 blocking。"""
+ with app.app_context():
+ summary = {
+ 'customer_code': 'C1',
+ 'po_number': 'PO-PENDING',
+ 'reservation_ids': ['1000140399'],
+ 'lines': [],
+ }
+ fp = build_business_fingerprint(summary)
+ asset, intake = _seed_parsed_intake(
+ dedup_user.id,
+ intake_no='SNI-PENDING-ACTIVE',
+ hash_value='hash-pending-1',
+ business_summary=summary,
+ fingerprint=fp,
+ )
+ existing = ShippingTask(
+ task_no='SN-PENDING-1',
+ user_id=dedup_user.id,
+ source_type='manual',
+ process_status='pending_review',
+ business_fingerprint=fp['fingerprint'],
+ fingerprint_version=fp['version'],
+ document_version=1,
+ )
+ db.session.add(existing)
+ db.session.commit()
+
+ result = detect_duplicates_for_intake(
+ intake=intake,
+ asset=asset,
+ business_summary=summary,
+ fingerprint_result=fp,
+ )
+ assert result['status'] == 'same_active_task'
+ assert result['blocking'] is True
+
+
+def test_assert_no_exact_duplicate_allows_revision_and_force(app, dedup_user):
+ """revision/force_create 可越过同 content_hash 的旧门闩;无决议仍阻断。"""
+ from app.services.shipping_notice.batch_create_idempotency import assert_no_exact_duplicate_notices
+
+ with app.app_context():
+ existing = ShippingTask(
+ task_no='SN-HASH-GATE',
+ user_id=dedup_user.id,
+ source_type='manual',
+ source_content_hash='samehashabc',
+ process_status='pending_review',
+ )
+ db.session.add(existing)
+ db.session.commit()
+
+ assert_no_exact_duplicate_notices(
+ dedup_user.id,
+ [
+ {
+ 'source_content_hash': 'samehashabc',
+ 'source_file_name': 'same.xlsx',
+ 'duplicate_resolution_type': 'revision',
+ }
+ ],
+ )
+ assert_no_exact_duplicate_notices(
+ dedup_user.id,
+ [
+ {
+ 'source_content_hash': 'samehashabc',
+ 'source_file_name': 'same.xlsx',
+ 'duplicate_resolution_type': 'force_create',
+ }
+ ],
+ )
+ with pytest.raises(ConflictError) as excinfo:
+ assert_no_exact_duplicate_notices(
+ dedup_user.id,
+ [
+ {
+ 'source_content_hash': 'samehashabc',
+ 'source_file_name': 'same.xlsx',
+ }
+ ],
+ )
+ assert excinfo.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
+
+
+def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
+ """API 投影:possible_duplicate 必须 blocking,供前端弹窗确认。"""
+ from app.services.shipping_notice.intake_service import serialize_intake
+
+ with app.app_context():
+ asset, intake = _seed_parsed_intake(
+ dedup_user.id,
+ intake_no='SNI-POSSIBLE-1',
+ hash_value='hash-possible-1',
+ business_summary={'customer_name': 'X', 'lines': [{'sku': 'A', 'qty': 1}]},
+ fingerprint={'fingerprint': 'weakfp', 'version': 'shipping-v1', 'strength': 'weak'},
+ )
+ intake.duplicate_status = 'possible_duplicate'
+ intake.fingerprint_strength = 'weak'
+ intake.duplicate_matches_json = [
+ {
+ 'task_no': 'SN-OLD',
+ 'process_status': 'waiting_inventory',
+ 'document_version': 1,
+ 'match_type': 'weak_fingerprint',
+ 'matched_fields': ['line_digest'],
+ }
+ ]
+ db.session.commit()
+ payload = serialize_intake(intake, asset=asset)
+ assert payload['duplicate']['status'] == 'possible_duplicate'
+ assert payload['duplicate']['blocking'] is True
+ assert 'force_create' in payload['duplicate']['allowed_actions']
+
+
+def test_task_summary_includes_version_chain(app, dedup_user):
+ """query_service SUMMARY 须暴露版本链与 duplicate 决策字段。"""
+ from app.services.shipping_notice.query_service import TaskProjection, serialize_task
+
+ with app.app_context():
+ base = ShippingTask(
+ task_no='SN-VER-BASE',
+ user_id=dedup_user.id,
+ source_type='manual',
+ process_status='uploaded',
+ document_version=1,
+ )
+ db.session.add(base)
+ db.session.flush()
+ rev = ShippingTask(
+ task_no='SN-VER-REV',
+ user_id=dedup_user.id,
+ source_type='manual',
+ process_status='pending_review',
+ document_version=2,
+ supersedes_task_id=base.id,
+ duplicate_resolution_type='revision',
+ duplicate_source_task_id=base.id,
+ duplicate_override_reason=None,
+ business_fingerprint='fp-x',
+ fingerprint_version='shipping-v1',
+ )
+ db.session.add(rev)
+ db.session.commit()
+
+ data = serialize_task(rev, TaskProjection.SUMMARY)
+ assert data['document_version'] == 2
+ assert data['supersedes_task_no'] == 'SN-VER-BASE'
+ assert data['duplicate_source_task_no'] == 'SN-VER-BASE'
+ assert data['duplicate_resolution_type'] == 'revision'
+ assert data['business_fingerprint'] == 'fp-x'
+
+ base_data = serialize_task(base, TaskProjection.SUMMARY)
+ assert base_data['superseded_by_task_no'] == 'SN-VER-REV'
+
+
+def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
+ """
+ 阶段二:同一邮件中候选 A 与已有任务重复时,仅 A 被阻断;B/C 仍可为 none。
+ """
+ with app.app_context():
+ existing_fp = build_business_fingerprint(
+ {
+ 'customer_code': 'C1',
+ 'po_number': '4510039227',
+ 'reservation_ids': ['1000140351'],
+ 'lines': [],
+ }
+ )
+ existing = ShippingTask(
+ task_no='SN-EXISTING-PO-A',
+ user_id=dedup_user.id,
+ source_type='manual',
+ process_status='pending_review',
+ business_fingerprint=existing_fp['fingerprint'],
+ fingerprint_version=existing_fp['version'],
+ source_content_hash='hash-other-file',
+ )
+ db.session.add(existing)
+
+ parent = FileAsset(
+ asset_no='FA-STAGE2-DEDUP-EML',
+ owner_user_id=dedup_user.id,
+ original_filename='multi.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{dedup_user.id}/stage2.eml',
+ content_hash='eml-parent-hash',
+ file_size=100,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ asset_role='upload',
+ )
+ db.session.add(parent)
+ db.session.flush()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-STAGE2-DEDUP',
+ asset_id=parent.id,
+ user_id=dedup_user.id,
+ purpose='shipping_notice',
+ parse_status='parsed',
+ parser_version='v6',
+ extracted_text='multi',
+ duplicate_status='unchecked',
+ )
+ db.session.add(intake)
+ db.session.flush()
+
+ docs = []
+ for idx, po in enumerate(('4510039227', '4510039228', '4510039229'), start=1):
+ doc = ShippingNoticeDocument(
+ intake_id=intake.id,
+ attachment_key=f'att-00{idx}',
+ document_type='attachment',
+ filename=f'{po}.pdf',
+ content_hash=f'pdf-hash-{po}',
+ classification='order_notice',
+ parse_status='parsed',
+ extracted_text=f'PO {po}',
+ )
+ db.session.add(doc)
+ docs.append(doc)
+ db.session.flush()
+
+ results = []
+ for doc, po in zip(docs, ('4510039227', '4510039228', '4510039229')):
+ summary = {
+ 'customer_code': 'C1',
+ 'po_number': po,
+ 'reservation_ids': ['1000140351'] if po == '4510039227' else [],
+ 'lines': [],
+ }
+ if po != '4510039227':
+ summary['reservation_ids'] = [f'100014035{po[-1]}']
+ fp = build_business_fingerprint(summary)
+ dup = detect_duplicates_for_candidate(
+ intake=intake,
+ document=doc,
+ business_summary=summary,
+ fingerprint_result=fp,
+ )
+ cand = ShippingNoticeCandidate(
+ candidate_no=f'SNC-{po}',
+ intake_id=intake.id,
+ primary_document_id=doc.id,
+ po_number=po,
+ structured_result_json={'business_summary': summary},
+ business_fingerprint=fp.get('fingerprint'),
+ fingerprint_version=fp.get('version'),
+ fingerprint_strength=fp.get('strength'),
+ duplicate_status=str(dup.get('status') or 'none'),
+ duplicate_matches_json=list(dup.get('matches') or []),
+ selected=True,
+ validation_status='pending',
+ )
+ db.session.add(cand)
+ results.append(dup)
+ db.session.commit()
+
+ assert results[0]['blocking'] is True
+ assert results[0]['status'] in {'same_active_task', 'exact_file', 'possible_duplicate'}
+ assert results[1]['blocking'] is False
+ assert results[1]['status'] == 'none'
+ assert results[2]['blocking'] is False
+ assert results[2]['status'] == 'none'
+
+ refreshed = (
+ db.session.query(ShippingNoticeCandidate)
+ .filter_by(intake_id=intake.id)
+ .order_by(ShippingNoticeCandidate.id.asc())
+ .all()
+ )
+ assert refreshed[0].duplicate_status != 'none'
+ assert refreshed[1].duplicate_status == 'none'
+ assert refreshed[2].duplicate_status == 'none'
+
+
+def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
+ """刷新重复检测须重写各 Candidate.duplicate_status,再聚合到 Intake。"""
+ from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
+
+ with app.app_context():
+ existing_fp = build_business_fingerprint(
+ {
+ 'customer_code': 'C1',
+ 'po_number': '4510099999',
+ 'reservation_ids': ['1000199999'],
+ 'lines': [],
+ }
+ )
+ existing = ShippingTask(
+ task_no='SN-REFRESH-EXISTING',
+ user_id=dedup_user.id,
+ source_type='manual',
+ process_status='pending_review',
+ business_fingerprint=existing_fp['fingerprint'],
+ fingerprint_version=existing_fp['version'],
+ source_content_hash='hash-refresh-other',
+ )
+ db.session.add(existing)
+
+ parent = FileAsset(
+ asset_no='FA-REFRESH-DEDUP',
+ owner_user_id=dedup_user.id,
+ original_filename='refresh.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{dedup_user.id}/refresh.eml',
+ content_hash='eml-refresh-hash',
+ file_size=100,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ asset_role='upload',
+ )
+ db.session.add(parent)
+ db.session.flush()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-REFRESH-DEDUP',
+ asset_id=parent.id,
+ user_id=dedup_user.id,
+ purpose='shipping_notice',
+ parse_status='parsed',
+ parser_version='v6',
+ extracted_text='refresh',
+ duplicate_status='none',
+ structured_result_json={'business_summary': {'customer_code': 'C1'}},
+ )
+ db.session.add(intake)
+ db.session.flush()
+
+ summary = {
+ 'customer_code': 'C1',
+ 'po_number': '4510099999',
+ 'reservation_ids': ['1000199999'],
+ 'lines': [],
+ }
+ fp = build_business_fingerprint(summary)
+ doc = ShippingNoticeDocument(
+ intake_id=intake.id,
+ attachment_key='att-001',
+ document_type='attachment',
+ filename='dup.pdf',
+ content_hash='pdf-refresh-1',
+ classification='order_notice',
+ parse_status='parsed',
+ extracted_text='PO 4510099999',
+ )
+ db.session.add(doc)
+ db.session.flush()
+ cand = ShippingNoticeCandidate(
+ candidate_no='SNC-REFRESH-1',
+ intake_id=intake.id,
+ primary_document_id=doc.id,
+ po_number='4510099999',
+ structured_result_json={'business_summary': summary},
+ business_fingerprint=fp.get('fingerprint'),
+ fingerprint_version=fp.get('version'),
+ fingerprint_strength=fp.get('strength'),
+ # 模拟解析后任务尚未存在时的旧结果;刷新时应变为阻断
+ duplicate_status='none',
+ duplicate_matches_json=[],
+ selected=True,
+ validation_status='pending',
+ )
+ db.session.add(cand)
+ db.session.commit()
+
+ payload = refresh_intake_duplicate_detection(
+ user_id=dedup_user.id,
+ intake_no='SNI-REFRESH-DEDUP',
+ )
+ assert payload['duplicate']['blocking'] is True
+ db.session.expire_all()
+ cand2 = db.session.query(ShippingNoticeCandidate).filter_by(candidate_no='SNC-REFRESH-1').one()
+ assert cand2.duplicate_status != 'none'
+ assert list(cand2.duplicate_matches_json or [])
diff --git a/backend/tests/test_shipping_notice_extract.py b/backend/tests/test_shipping_notice_extract.py
index 9edc5cdb..3fcaca71 100644
--- a/backend/tests/test_shipping_notice_extract.py
+++ b/backend/tests/test_shipping_notice_extract.py
@@ -1,3 +1,6 @@
+from email.message import EmailMessage
+from pathlib import Path
+
from app.services.shipping_notice.extract import extract_notice_fields, _heuristic_extract
from app.services.shipping_notice.notice_lines import (
normalize_notice_line,
@@ -13,10 +16,105 @@ from app.services.shipping_notice.reservation_id import (
)
+def _minimal_pdf_bytes(marker: str) -> bytes:
+ """
+ 构造含可见文本的最小 PDF,供 EML 附件抽取测试使用。
+
+ 核心逻辑:手写 PDF 对象流并嵌入 Helvetica 文本;extract_notice_text 应能读出 marker。
+ """
+ safe = (
+ str(marker)
+ .replace("\\", "\\\\")
+ .replace("(", "\\(")
+ .replace(")", "\\)")
+ )
+ stream = f"BT /F1 24 Tf 72 720 Td ({safe}) Tj ET".encode("latin-1")
+ objects = [
+ b"1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n",
+ b"2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj\n",
+ (
+ b"3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
+ b"/Contents 4 0 R /Resources<< /Font<< /F1 5 0 R >> >> >>endobj\n"
+ ),
+ f"4 0 obj<< /Length {len(stream)} >>stream\n".encode("latin-1")
+ + stream
+ + b"\nendstream\nendobj\n",
+ b"5 0 obj<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>endobj\n",
+ ]
+ out = bytearray(b"%PDF-1.4\n")
+ offsets = [0]
+ for obj in objects:
+ offsets.append(len(out))
+ out.extend(obj)
+ xref_pos = len(out)
+ out.extend(f"xref\n0 {len(offsets)}\n".encode("latin-1"))
+ out.extend(b"0000000000 65535 f \n")
+ for off in offsets[1:]:
+ out.extend(f"{off:010d} 00000 n \n".encode("latin-1"))
+ out.extend(
+ f"trailer<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode(
+ "latin-1"
+ )
+ )
+ return bytes(out)
+
+
+_TINY_PNG = (
+ b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
+ b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00"
+ b"\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
+)
+
+
+def _build_eml(
+ *,
+ subject: str,
+ body: str,
+ attachments: list[tuple[str, str, bytes]],
+ inline_images: list[tuple[str, str, bytes]] | None = None,
+ message_id: str = "",
+) -> bytes:
+ """
+ 组装 multipart/mixed 测试邮件。
+
+ Args:
+ subject: 邮件主题。
+ body: text/plain 正文。
+ attachments: (filename, mime, payload) 真实附件列表。
+ inline_images: (filename, content_id, payload) 内嵌签名图。
+ message_id: Message-ID 头。
+ """
+ msg = EmailMessage()
+ msg["Subject"] = subject
+ msg["From"] = "laszlo.fussy@example.com"
+ msg["To"] = "freight@example.com"
+ msg["Date"] = "Mon, 13 Jul 2026 10:00:00 +0800"
+ msg["Message-ID"] = message_id
+ msg.set_content(body)
+
+ for filename, content_id, payload in inline_images or []:
+ msg.add_attachment(
+ payload,
+ maintype="image",
+ subtype="png",
+ filename=filename,
+ cid=content_id,
+ disposition="inline",
+ )
+
+ for filename, mime, payload in attachments:
+ maintype, _, subtype = mime.partition("/")
+ msg.add_attachment(
+ payload,
+ maintype=maintype or "application",
+ subtype=subtype or "octet-stream",
+ filename=filename,
+ )
+ return msg.as_bytes()
+
+
def test_extract_notice_text_reads_xfa_pdf_datasets():
"""XFA 表单型 PO 的订单字段应进入 raw_text,避免只抽页面文本漏明细。"""
- from pathlib import Path
-
from app.services.shipping_notice.notice_upload import extract_notice_text
pdf_path = Path(__file__).resolve().parents[2] / "docs" / "prototype" / "4510038672.pdf"
@@ -31,6 +129,1006 @@ def test_extract_notice_text_reads_xfa_pdf_datasets():
assert "EINDT=2026-06-23" in text
+def test_extract_eml_with_three_pdf_attachments(tmp_path):
+ """带 3 个 PDF 附件的 EML:attachment_count=3,且各附件独立抽到文本。"""
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ markers = ("PO-MARKER-AAA", "PO-MARKER-BBB", "PO-MARKER-CCC")
+ attachments = [
+ (f"{marker}.pdf", "application/pdf", _minimal_pdf_bytes(marker)) for marker in markers
+ ]
+ raw = _build_eml(
+ subject="PO 4510039227, 4510039228, 4510039229",
+ body="Please find POs attached.",
+ attachments=attachments,
+ )
+ path = tmp_path / "multi-po.eml"
+ path.write_bytes(raw)
+
+ text, meta = extract_notice_text(path)
+
+ assert meta["file_type"] == "eml"
+ assert meta["attachment_count"] == 3
+ assert meta["email"]["subject"] == "PO 4510039227, 4510039228, 4510039229"
+ assert meta["email"]["from"] == "laszlo.fussy@example.com"
+ assert meta["email"]["message_id"] == ""
+ assert "Please find POs attached." in meta["email"]["body_text"]
+
+ parsed_atts = meta["attachments"]
+ assert len(parsed_atts) == 3
+ for marker, item in zip(markers, parsed_atts):
+ assert item["filename"] == f"{marker}.pdf"
+ assert item["mime_type"] == "application/pdf"
+ assert item["parse_status"] == "parsed"
+ assert len(item["content_hash"]) == 64
+ assert marker in item["extracted_text"]
+ assert marker in text
+
+
+def test_extract_eml_skips_signature_inline_image(tmp_path):
+ """邮件签名图片(inline + Content-ID)不得进入 attachments,也不进入订单文本。"""
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ pdf = _minimal_pdf_bytes("PO-ONLY-ORDER")
+ raw = _build_eml(
+ subject="Single PO",
+ body="Body with one PO attachment.",
+ attachments=[("order.pdf", "application/pdf", pdf)],
+ inline_images=[("signature.png", "", _TINY_PNG)],
+ )
+ path = tmp_path / "with-signature.eml"
+ path.write_bytes(raw)
+
+ text, meta = extract_notice_text(path)
+
+ assert meta["attachment_count"] == 1
+ assert meta["attachments"][0]["filename"] == "order.pdf"
+ assert all(item["filename"] != "signature.png" for item in meta["attachments"])
+ assert any(str(w).startswith("eml_inline_resources_skipped:") for w in meta["warnings"])
+ assert "PO-ONLY-ORDER" in text
+ # 签名图文件名不应出现在扁平正文附件区
+ assert "--- attachment: signature.png ---" not in text
+
+
+def test_extract_eml_duplicate_attachments(tmp_path):
+ """同信内重复内容哈希的附件标记 duplicate,不重复抽取。"""
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ pdf = _minimal_pdf_bytes("PO-DUP-SAME")
+ raw = _build_eml(
+ subject="Dup attachments",
+ body="Two copies of the same PDF.",
+ attachments=[
+ ("a.pdf", "application/pdf", pdf),
+ ("a-copy.pdf", "application/pdf", pdf),
+ ],
+ )
+ path = tmp_path / "dup.eml"
+ path.write_bytes(raw)
+
+ _, meta = extract_notice_text(path)
+
+ assert meta["attachment_count"] == 2
+ assert meta["attachments"][0]["parse_status"] == "parsed"
+ assert meta["attachments"][1]["parse_status"] == "duplicate"
+ assert any(str(w).startswith("eml_attachment_duplicate:") for w in meta["warnings"])
+
+
+def test_extract_eml_corrupt_attachment_does_not_block_others(tmp_path):
+ """某一个附件损坏时,其他附件仍正常解析。"""
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ good = _minimal_pdf_bytes("PO-GOOD-OK")
+ bad = b"%PDF-1.4\nthis is not a valid pdf stream{{{{"
+ raw = _build_eml(
+ subject="One bad attachment",
+ body="Mixed attachments.",
+ attachments=[
+ ("good.pdf", "application/pdf", good),
+ ("broken.pdf", "application/pdf", bad),
+ ("also-good.pdf", "application/pdf", _minimal_pdf_bytes("PO-ALSO-GOOD")),
+ ],
+ )
+ path = tmp_path / "partial-fail.eml"
+ path.write_bytes(raw)
+
+ text, meta = extract_notice_text(path)
+
+ assert meta["attachment_count"] == 3
+ statuses = {item["filename"]: item["parse_status"] for item in meta["attachments"]}
+ assert statuses["good.pdf"] == "parsed"
+ assert statuses["also-good.pdf"] == "parsed"
+ # 损坏附件:extract 可能 empty 或 failed,均不得拖垮其余
+ assert statuses["broken.pdf"] in {"failed", "empty"}
+ assert "PO-GOOD-OK" in text
+ assert "PO-ALSO-GOOD" in text
+
+
+def test_intake_structured_summary_includes_eml_fields(tmp_path):
+ """EML 预解析摘要应带上 email / attachment_count / attachments(含独立 extracted_text)。"""
+ from app.services.shipping_notice.intake_parse_workflow import intake_result_to_structured_summary
+ from app.services.shipping_notice.notice_upload import extract_notice_text, NoticeIntakeResult
+
+ raw = _build_eml(
+ subject="Summary PO",
+ body="Summary body.",
+ attachments=[("one.pdf", "application/pdf", _minimal_pdf_bytes("PO-SUM-1"))],
+ )
+ path = tmp_path / "summary.eml"
+ path.write_bytes(raw)
+ text, meta = extract_notice_text(path)
+ result = NoticeIntakeResult(
+ filename="summary.eml",
+ source_type="email",
+ source_file_type="message/rfc822",
+ text=text,
+ warnings=list(meta.get("warnings") or []),
+ meta=meta,
+ content_hash="abc",
+ file_size=len(raw),
+ status="accepted",
+ )
+ summary = intake_result_to_structured_summary(result)
+ assert summary["attachment_count"] == 1
+ assert summary["email"]["subject"] == "Summary PO"
+ assert summary["attachments"][0]["filename"] == "one.pdf"
+ assert summary["attachments"][0]["parse_status"] == "parsed"
+ assert "PO-SUM-1" in str(summary["attachments"][0].get("extracted_text") or "")
+ assert summary["attachments"][0]["text_length"] > 0
+
+
+def test_extract_eml_named_text_part_is_attachment(tmp_path):
+ """带 filename 的 text/plain 不得当正文丢弃,应进入 attachments。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ msg = EmailMessage()
+ msg["Subject"] = "Named text attach"
+ msg["From"] = "a@example.com"
+ msg["To"] = "b@example.com"
+ msg.set_content("Cover note only.")
+ msg.add_attachment(
+ b"PO-LINE-TXT-001 qty 2",
+ maintype="text",
+ subtype="plain",
+ filename="order.txt",
+ )
+ path = tmp_path / "named-text.eml"
+ path.write_bytes(msg.as_bytes())
+
+ text, meta = extract_notice_text(path)
+ assert meta["attachment_count"] == 1
+ assert meta["attachments"][0]["filename"] == "order.txt"
+ assert meta["attachments"][0]["parse_status"] == "parsed"
+ assert "PO-LINE-TXT-001" in meta["attachments"][0]["extracted_text"]
+ assert "PO-LINE-TXT-001" in text
+
+
+def test_extract_eml_respects_declared_charset(tmp_path):
+ """正文解码须尊重 Content-Type charset(ISO-8859-1 café résumé)。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ body = "Please ship café résumé to Lille"
+ msg = EmailMessage()
+ msg["Subject"] = "Charset test"
+ msg["From"] = "eu@example.com"
+ msg["To"] = "freight@example.com"
+ msg.set_content(body, charset="iso-8859-1")
+ path = tmp_path / "charset.eml"
+ path.write_bytes(msg.as_bytes())
+
+ _, meta = extract_notice_text(path)
+ assert "café" in meta["email"]["body_text"]
+ assert "résumé" in meta["email"]["body_text"]
+
+
+def test_extract_eml_nested_rfc822_registers_independent_attachment(tmp_path):
+ """成功 message/rfc822 须登记独立附件行(含正文文本)并计入 attachment_count。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ inner = EmailMessage()
+ inner["Subject"] = "Inner PO Only In Body"
+ inner["From"] = "buyer@example.com"
+ inner["To"] = "vendor@example.com"
+ inner.set_content("INNER-ORDER-PO-4510039999 please ship")
+
+ outer = EmailMessage()
+ outer["Subject"] = "FW: order"
+ outer["From"] = "relay@example.com"
+ outer["To"] = "freight@example.com"
+ outer.set_content("Please see forwarded message.")
+ # set_content(EmailMessage) → message/rfc822 部件
+ outer.add_attachment(inner)
+
+ path = tmp_path / "forwarded.eml"
+ path.write_bytes(outer.as_bytes())
+
+ text, meta = extract_notice_text(path)
+ assert meta["attachment_count"] == 1
+ assert meta["attachment_registered_count"] == 1
+ assert len(meta["attachments"]) == 1
+ rfc822_rows = [
+ row
+ for row in meta["attachments"]
+ if str(row.get("mime_type") or "") == "message/rfc822"
+ or str(row.get("filename") or "").endswith(".eml")
+ ]
+ assert rfc822_rows, "native message/rfc822 must appear as an attachment row"
+ row = rfc822_rows[0]
+ assert row["filename"] == "forwarded-message.eml" or row["mime_type"] == "message/rfc822"
+ assert row["parse_status"] == "parsed"
+ assert "INNER-ORDER-PO-4510039999" in str(row.get("extracted_text") or "")
+ assert "Inner PO Only In Body" in str(row.get("extracted_text") or "")
+ # 扁平正文经 attachment 段拼接仍可下游解析
+ assert "INNER-ORDER-PO-4510039999" in text
+ assert "Inner PO Only In Body" in text
+ # 不得只剩封面正文(attachment_count=0)却把订单塞进合并正文
+ assert "Please see forwarded message." in text or "Please see forwarded message" in meta.get("email", {}).get("body_text", "")
+ # 有外层正文时,内层订单只应在扁平文本中出现一次(封面 + 附件段各一处主题/订单不重复计数订单号)
+ assert text.count("INNER-ORDER-PO-4510039999") == 1
+
+
+def test_extract_eml_forward_only_no_outer_body_dedupes_inner_order(tmp_path):
+ """无外层正文、仅含 message/rfc822 附件时,内层订单不得在扁平文本出现两次。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ inner = EmailMessage()
+ inner["Subject"] = "Forward Only PO"
+ inner["From"] = "buyer@example.com"
+ inner["To"] = "vendor@example.com"
+ inner.set_content("INNER-PO-777 please ship")
+
+ outer = EmailMessage()
+ outer["Subject"] = "FW: bare forward"
+ outer["From"] = "relay@example.com"
+ outer["To"] = "freight@example.com"
+ # 常见场景:外层无 set_content,仅挂载转发附件
+ outer.add_attachment(inner)
+
+ path = tmp_path / "forward-only.eml"
+ path.write_bytes(outer.as_bytes())
+
+ text, meta = extract_notice_text(path)
+ body = str((meta.get("email") or {}).get("body_text") or "")
+ assert "INNER-PO-777" not in body, "outer body must not absorb inner rfc822 text"
+ assert meta["attachment_count"] == 1
+ assert meta["attachments"][0]["parse_status"] == "parsed"
+ assert "INNER-PO-777" in str(meta["attachments"][0].get("extracted_text") or "")
+ assert text.count("INNER-PO-777") == 1
+
+
+def test_extract_eml_attached_multipart_registers_independent_attachment(tmp_path):
+ """disposition=attachment 的 multipart/* 须登记为独立附件,不得把订单吞进外层 body。"""
+ from email.mime.multipart import MIMEMultipart
+ from email.mime.text import MIMEText
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ bundle = MIMEMultipart("mixed")
+ bundle.set_param("name", "bundle.mime")
+ bundle.add_header("Content-Disposition", "attachment", filename="bundle.mime")
+ bundle.attach(MIMEText("BUNDLE-PO-888 please ship", "plain", "utf-8"))
+
+ outer = MIMEMultipart("mixed")
+ outer["Subject"] = "Has MIME bundle"
+ outer["From"] = "a@example.com"
+ outer["To"] = "b@example.com"
+ outer.attach(MIMEText("Outer cover only.", "plain", "utf-8"))
+ outer.attach(bundle)
+
+ path = tmp_path / "attached-multipart.eml"
+ path.write_bytes(outer.as_bytes())
+
+ text, meta = extract_notice_text(path)
+ body = str((meta.get("email") or {}).get("body_text") or "")
+ assert "BUNDLE-PO-888" not in body
+ assert "Outer cover only." in body
+ assert meta["attachment_count"] >= 1
+ bundles = [
+ row
+ for row in meta["attachments"]
+ if str(row.get("filename") or "") == "bundle.mime"
+ or str(row.get("mime_type") or "").startswith("multipart/")
+ ]
+ assert bundles, "attached multipart must appear as an attachment row"
+ assert bundles[0]["parse_status"] == "parsed"
+ assert "BUNDLE-PO-888" in str(bundles[0].get("extracted_text") or "")
+ assert text.count("BUNDLE-PO-888") == 1
+
+
+def test_extract_eml_attached_multipart_keeps_all_plain_parts(tmp_path):
+ """附件型 multipart 内多个 text/plain 须全部拼入 extracted_text,不得只留第一段。"""
+ from email.mime.multipart import MIMEMultipart
+ from email.mime.text import MIMEText
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ bundle = MIMEMultipart("mixed")
+ bundle.add_header("Content-Disposition", "attachment", filename="multi-po.mime")
+ bundle.attach(MIMEText("PO-A-111 please ship", "plain", "utf-8"))
+ bundle.attach(MIMEText("PO-B-222 please ship", "plain", "utf-8"))
+
+ outer = MIMEMultipart("mixed")
+ outer["Subject"] = "Multi plain bundle"
+ outer["From"] = "a@example.com"
+ outer["To"] = "b@example.com"
+ outer.attach(MIMEText("cover", "plain", "utf-8"))
+ outer.attach(bundle)
+
+ path = tmp_path / "multi-plain-bundle.eml"
+ path.write_bytes(outer.as_bytes())
+ text, meta = extract_notice_text(path)
+ row = next(r for r in meta["attachments"] if r.get("filename") == "multi-po.mime")
+ extracted = str(row.get("extracted_text") or "")
+ assert "PO-A-111" in extracted
+ assert "PO-B-222" in extracted
+ assert text.count("PO-A-111") == 1
+ assert text.count("PO-B-222") == 1
+
+
+def test_extract_eml_attached_multipart_mixed_keeps_plain_and_html(tmp_path):
+ """multipart/mixed 附件内独立 plain 与 HTML 订单段须全部保留(非 alternative 的 plain 优先)。"""
+ from email.mime.multipart import MIMEMultipart
+ from email.mime.text import MIMEText
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ bundle = MIMEMultipart("mixed")
+ bundle.add_header("Content-Disposition", "attachment", filename="plain-html.mime")
+ bundle.attach(MIMEText("PLAIN-PO-101 please ship", "plain", "utf-8"))
+ bundle.attach(MIMEText("HTML-PO-202 please ship
", "html", "utf-8"))
+
+ outer = MIMEMultipart("mixed")
+ outer["Subject"] = "Plain+HTML mixed bundle"
+ outer["From"] = "a@example.com"
+ outer["To"] = "b@example.com"
+ outer.attach(MIMEText("cover", "plain", "utf-8"))
+ outer.attach(bundle)
+
+ path = tmp_path / "plain-html-mixed.eml"
+ path.write_bytes(outer.as_bytes())
+ text, meta = extract_notice_text(path)
+ row = next(r for r in meta["attachments"] if r.get("filename") == "plain-html.mime")
+ extracted = str(row.get("extracted_text") or "")
+ assert "PLAIN-PO-101" in extracted
+ assert "HTML-PO-202" in extracted
+ assert text.count("PLAIN-PO-101") == 1
+ assert text.count("HTML-PO-202") == 1
+
+
+def test_extract_eml_attached_multipart_alternative_prefers_plain(tmp_path):
+ """multipart/alternative 附件内仍 plain 优先,避免同一订单 plain/html 双份。"""
+ from email.mime.multipart import MIMEMultipart
+ from email.mime.text import MIMEText
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ alt = MIMEMultipart("alternative")
+ alt.attach(MIMEText("ALT-PO-PLAIN-303", "plain", "utf-8"))
+ alt.attach(MIMEText("ALT-PO-HTML-303", "html", "utf-8"))
+
+ bundle = MIMEMultipart("mixed")
+ bundle.add_header("Content-Disposition", "attachment", filename="alt.mime")
+ bundle.attach(alt)
+
+ outer = MIMEMultipart("mixed")
+ outer["Subject"] = "Alternative bundle"
+ outer["From"] = "a@example.com"
+ outer.attach(MIMEText("cover", "plain", "utf-8"))
+ outer.attach(bundle)
+
+ path = tmp_path / "alt-bundle.eml"
+ path.write_bytes(outer.as_bytes())
+ text, meta = extract_notice_text(path)
+ row = next(r for r in meta["attachments"] if r.get("filename") == "alt.mime")
+ extracted = str(row.get("extracted_text") or "")
+ assert "ALT-PO-PLAIN-303" in extracted
+ assert "ALT-PO-HTML-303" not in extracted
+ assert text.count("ALT-PO-PLAIN-303") == 1
+
+
+def test_extract_eml_attached_alternative_root_extracts_plain(tmp_path):
+ """根部件即为 disposition=attachment 的 multipart/alternative 时须提取 plain,不得 empty。"""
+ from email.mime.multipart import MIMEMultipart
+ from email.mime.text import MIMEText
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ alt = MIMEMultipart("alternative")
+ alt.add_header("Content-Disposition", "attachment", filename="order-alt.mime")
+ alt.attach(MIMEText("ROOT-ALT-PO-404 please ship", "plain", "utf-8"))
+ alt.attach(MIMEText("ROOT-ALT-HTML-404
", "html", "utf-8"))
+
+ outer = MIMEMultipart("mixed")
+ outer["Subject"] = "Attached alternative root"
+ outer["From"] = "a@example.com"
+ outer["To"] = "b@example.com"
+ outer.attach(MIMEText("cover", "plain", "utf-8"))
+ outer.attach(alt)
+
+ path = tmp_path / "alt-root-attached.eml"
+ path.write_bytes(outer.as_bytes())
+ text, meta = extract_notice_text(path)
+ row = next(r for r in meta["attachments"] if r.get("filename") == "order-alt.mime")
+ assert row["parse_status"] == "parsed"
+ extracted = str(row.get("extracted_text") or "")
+ assert "ROOT-ALT-PO-404" in extracted
+ assert "ROOT-ALT-HTML-404" not in extracted
+ assert text.count("ROOT-ALT-PO-404") == 1
+ assert "ROOT-ALT-PO-404" not in str((meta.get("email") or {}).get("body_text") or "")
+
+
+def test_extract_eml_nested_attached_multipart_respects_depth(tmp_path):
+ """嵌套附件型 multipart 须累加 depth,超限时 skipped 并打 eml_nesting_depth_exceeded。"""
+ from email.mime.multipart import MIMEMultipart
+ from email.mime.text import MIMEText
+
+ from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ inner = MIMEMultipart("mixed")
+ inner.add_header("Content-Disposition", "attachment", filename="inner.mime")
+ inner.attach(MIMEText("INNER-NESTED-PO-999", "plain", "utf-8"))
+
+ outer_bundle = MIMEMultipart("mixed")
+ outer_bundle.add_header("Content-Disposition", "attachment", filename="outer.mime")
+ outer_bundle.attach(MIMEText("OUTER-BUNDLE-PO", "plain", "utf-8"))
+ outer_bundle.attach(inner)
+
+ root = MIMEMultipart("mixed")
+ root["Subject"] = "Nested attached multipart"
+ root["From"] = "a@example.com"
+ root.attach(MIMEText("cover", "plain", "utf-8"))
+ root.attach(outer_bundle)
+
+ _, meta = parse_eml_bytes(
+ root.as_bytes(),
+ extract_text=extract_notice_text,
+ limits=EmlLimits(max_attachments=10, max_nesting_depth=1),
+ depth=0,
+ )
+ by_name = {row["filename"]: row for row in meta["attachments"]}
+ assert by_name["outer.mime"]["parse_status"] == "parsed"
+ assert "OUTER-BUNDLE-PO" in str(by_name["outer.mime"].get("extracted_text") or "")
+ assert by_name["inner.mime"]["parse_status"] == "skipped"
+ assert any(str(w).startswith("eml_nesting_depth_exceeded:") for w in meta["warnings"])
+ assert "INNER-NESTED-PO-999" not in str(by_name["inner.mime"].get("extracted_text") or "")
+
+
+def test_extract_eml_html_table_keeps_row_boundaries(tmp_path):
+ """HTML-only 邮件表格应保留行列边界(换行+制表符),且解码 HTML 实体。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ html = (
+ ""
+ "| PO | Qty |
"
+ "| 4510039227 | 30 |
"
+ "| 4510039228 | 2 |
"
+ "| A&B | 3 |
"
+ "
"
+ )
+ msg = EmailMessage()
+ msg["Subject"] = "HTML table"
+ msg["From"] = "a@example.com"
+ msg["To"] = "b@example.com"
+ msg.set_content(html, subtype="html")
+ path = tmp_path / "html-table.eml"
+ path.write_bytes(msg.as_bytes())
+
+ _, meta = extract_notice_text(path)
+ body = meta["email"]["body_text"]
+ assert "4510039227" in body
+ assert "4510039228" in body
+ assert "A&B" in body
+ assert body.count("\n") >= 2
+ assert "\t" in body
+ assert "4510039227\t30" in body.replace(" ", "")
+
+
+def test_extract_eml_nested_eml_file_respects_depth(tmp_path):
+ """嵌套 .eml 文件附件须共享深度/限额,不得重置 depth=0 无限展开。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ leaf = EmailMessage()
+ leaf["Subject"] = "Leaf"
+ leaf["From"] = "leaf@example.com"
+ leaf.set_content("LEAF-MARKER-DEPTH")
+ leaf_bytes = leaf.as_bytes()
+
+ def wrap_as_eml_file(payload: bytes, filename: str, subject: str) -> bytes:
+ msg = EmailMessage()
+ msg["Subject"] = subject
+ msg["From"] = "a@example.com"
+ msg["To"] = "b@example.com"
+ msg.set_content(f"see {filename}")
+ msg.add_attachment(
+ payload,
+ maintype="application",
+ subtype="octet-stream",
+ filename=filename,
+ )
+ return msg.as_bytes()
+
+ l1 = wrap_as_eml_file(leaf_bytes, "l1.eml", "L1")
+ l2 = wrap_as_eml_file(l1, "l2.eml", "L2")
+ root = wrap_as_eml_file(l2, "l3.eml", "Root")
+
+ text, meta = parse_eml_bytes(
+ root,
+ extract_text=extract_notice_text,
+ limits=EmlLimits(max_attachments=20, max_nesting_depth=1),
+ depth=0,
+ )
+ assert any(str(w).startswith("eml_nesting_depth_exceeded:") for w in meta["warnings"])
+ # depth=1 只允许再展开一层;更深的 LEAF 不应进入正文
+ assert "LEAF-MARKER-DEPTH" not in text
+ assert "LEAF-MARKER-DEPTH" not in str(meta.get("email", {}).get("body_text") or "")
+
+
+def test_extract_eml_attachment_count_includes_overflow(tmp_path):
+ """超限未登记的附件仍计入 attachment_count。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ msg = EmailMessage()
+ msg["Subject"] = "Three attaches"
+ msg["From"] = "a@example.com"
+ msg["To"] = "b@example.com"
+ msg.set_content("cover")
+ for idx in range(3):
+ msg.add_attachment(
+ f"PO-LINE-{idx}".encode("utf-8"),
+ maintype="text",
+ subtype="plain",
+ filename=f"order-{idx}.txt",
+ )
+ _, meta = parse_eml_bytes(
+ msg.as_bytes(),
+ extract_text=extract_notice_text,
+ limits=EmlLimits(max_attachments=2, max_nesting_depth=3),
+ )
+ assert meta["attachment_count"] == 3
+ assert meta["attachment_registered_count"] == 2
+ assert len(meta["attachments"]) == 2
+ assert any("eml_attachment_limit_exceeded:2:discovered=3" in str(w) for w in meta["warnings"])
+
+
+def test_extract_eml_container_does_not_double_count_total_bytes(tmp_path):
+ """嵌套 .eml 容器计费后,内层子附件不得再计,避免双重计费导致误 skip。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ inner = EmailMessage()
+ inner["Subject"] = "Inner"
+ inner["From"] = "inner@example.com"
+ inner.set_content("cover")
+ inner.add_attachment(
+ b"INNER-PO-TINY",
+ maintype="text",
+ subtype="plain",
+ filename="inner.txt",
+ )
+ inner_bytes = inner.as_bytes()
+
+ outer = EmailMessage()
+ outer["Subject"] = "Outer"
+ outer["From"] = "outer@example.com"
+ outer.set_content("see nested")
+ outer.add_attachment(
+ inner_bytes,
+ maintype="application",
+ subtype="octet-stream",
+ filename="nested.eml",
+ )
+ outer_bytes = outer.as_bytes()
+ # 上限略大于容器;若对子内容再计一次,则可能误 skip
+ tight_total = len(inner_bytes) + 10
+ assert tight_total < len(outer_bytes) + len(b"INNER-PO-TINY")
+
+ _, meta = parse_eml_bytes(
+ outer_bytes,
+ extract_text=extract_notice_text,
+ limits=EmlLimits(
+ max_attachments=10,
+ max_attachment_bytes=10 * 1024 * 1024,
+ max_total_attachment_bytes=tight_total,
+ max_nesting_depth=3,
+ ),
+ )
+ by_name = {row["filename"]: row for row in meta["attachments"]}
+ assert "nested.eml" in by_name
+ assert by_name["inner.txt"]["parse_status"] == "parsed"
+ assert "INNER-PO-TINY" in by_name["inner.txt"]["extracted_text"]
+
+
+def test_extract_eml_large_containers_count_toward_total():
+ """多个近似空壳大 .eml 容器须计入总量,不能仅靠跳过叶子附件绕过。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ def _shell_eml(name: str, pad: bytes) -> bytes:
+ msg = EmailMessage()
+ msg["Subject"] = name
+ msg["From"] = "shell@example.com"
+ msg.set_content("pad-only")
+ # 用文本附件撑大容器体积(容器整体计费)
+ msg.add_attachment(pad, maintype="text", subtype="plain", filename=f"{name}-pad.txt")
+ return msg.as_bytes()
+
+ pad = b"X" * 8000
+ shell_a = _shell_eml("A", pad)
+ shell_b = _shell_eml("B", pad)
+ shell_c = _shell_eml("C", pad)
+
+ root = EmailMessage()
+ root["Subject"] = "Many shells"
+ root["From"] = "root@example.com"
+ root.set_content("holders")
+ for name, payload in (("a.eml", shell_a), ("b.eml", shell_b), ("c.eml", shell_c)):
+ root.add_attachment(
+ payload,
+ maintype="application",
+ subtype="octet-stream",
+ filename=name,
+ )
+
+ # 只够放两个容器;第三个须 skipped 并打总量警告
+ two_shells = len(shell_a) + len(shell_b)
+ _, meta = parse_eml_bytes(
+ root.as_bytes(),
+ extract_text=extract_notice_text,
+ limits=EmlLimits(
+ max_attachments=20,
+ max_attachment_bytes=10 * 1024 * 1024,
+ max_total_attachment_bytes=two_shells + 50,
+ max_nesting_depth=3,
+ ),
+ )
+ by_name = {row["filename"]: row for row in meta["attachments"]}
+ assert by_name["a.eml"]["parse_status"] in {"parsed", "empty"}
+ assert by_name["b.eml"]["parse_status"] in {"parsed", "empty"}
+ assert by_name["c.eml"]["parse_status"] == "skipped"
+ assert any(str(w).startswith("eml_total_attachment_size_exceeded:") for w in meta["warnings"])
+
+
+def test_attachment_integrity_flags_budget_and_failed_status():
+ """完整性助手须覆盖预算耗尽、文本截断与 failed/empty/skipped。"""
+ from app.services.shipping_notice.attachment_integrity import (
+ BLOCKING_WARNING_PREFIXES,
+ is_attachment_parse_incomplete,
+ )
+
+ assert not is_attachment_parse_incomplete(
+ {
+ "attachment_count": 1,
+ "attachments": [{"parse_status": "parsed", "warnings": []}],
+ "warnings": [],
+ }
+ )
+ assert is_attachment_parse_incomplete(
+ {
+ "attachment_count": 1,
+ "attachments": [{"parse_status": "failed", "warnings": []}],
+ "warnings": [],
+ }
+ )
+ assert is_attachment_parse_incomplete(
+ {
+ "attachment_count": 2,
+ "attachments": [{"parse_status": "parsed", "warnings": []}],
+ "warnings": [],
+ }
+ )
+ assert is_attachment_parse_incomplete(
+ {
+ "attachment_count": 1,
+ "attachments": [
+ {
+ "parse_status": "parsed",
+ "warnings": ["eml_attachment_text_budget_exhausted:100"],
+ }
+ ],
+ "warnings": [],
+ }
+ )
+ assert is_attachment_parse_incomplete(
+ {
+ "attachment_count": 1,
+ "attachments": [{"parse_status": "parsed", "warnings": []}],
+ "warnings": ["eml_attachment_text_budget_exhausted:100"],
+ }
+ )
+ assert is_attachment_parse_incomplete(
+ {
+ "attachment_count": 1,
+ "attachments": [
+ {
+ "parse_status": "parsed",
+ "warnings": ["eml_attachment_text_truncated:10"],
+ }
+ ],
+ "warnings": [],
+ }
+ )
+ assert is_attachment_parse_incomplete(
+ {
+ "attachment_count": 0,
+ "attachments": [],
+ "warnings": ["notice_text_truncated:100"],
+ }
+ )
+ # 契约:每个阻断前缀都须能触发 incomplete
+ for prefix in BLOCKING_WARNING_PREFIXES:
+ assert is_attachment_parse_incomplete({"warnings": [f"{prefix}demo"], "attachments": []})
+
+
+def test_frontend_blocking_warning_prefixes_match_backend():
+ """前后端阻断 warning 前缀契约须一致,防止再漏截断类码。"""
+ import ast
+ import re
+ from pathlib import Path
+
+ from app.services.shipping_notice.attachment_integrity import BLOCKING_WARNING_PREFIXES
+
+ ts_path = (
+ Path(__file__).resolve().parents[2]
+ / "frontend"
+ / "src"
+ / "features"
+ / "chat"
+ / "shipping"
+ / "shippingNoticeAttachmentIntegrity.ts"
+ )
+ assert ts_path.is_file(), f"missing frontend contract file: {ts_path}"
+ text = ts_path.read_text(encoding="utf-8")
+ match = re.search(
+ r"export const BLOCKING_WARNING_PREFIXES\s*=\s*\[(.*?)]\s*as const",
+ text,
+ flags=re.S,
+ )
+ assert match, "frontend BLOCKING_WARNING_PREFIXES array not found"
+ literal = "[" + match.group(1) + "]"
+ literal = literal.replace("'", '"')
+ fe_prefixes = ast.literal_eval(literal)
+ assert sorted(fe_prefixes) == sorted(BLOCKING_WARNING_PREFIXES)
+
+
+def test_intake_structured_summary_per_attachment_text_truncated(app):
+ """单附件文本超 NOTICE_TEXT_MAX_CHARS 须投影 truncated warning 并阻断完整性。"""
+ from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
+ from app.services.shipping_notice.intake_parse_workflow import intake_result_to_structured_summary
+ from app.services.shipping_notice.notice_upload import NoticeIntakeResult
+
+ with app.app_context():
+ app.config["SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS"] = 10
+ app.config["SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS"] = 1_000_000
+ result = NoticeIntakeResult(
+ filename="trunc.eml",
+ source_type="email",
+ source_file_type="message/rfc822",
+ text="cover",
+ warnings=[],
+ meta={
+ "email": {"subject": "Trunc", "body_text": "cover"},
+ "attachment_count": 1,
+ "attachments": [
+ {
+ "attachment_key": "att-001",
+ "filename": "long.txt",
+ "mime_type": "text/plain",
+ "size": 20,
+ "content_hash": "h1",
+ "parse_status": "parsed",
+ "extracted_text": "ABCDEFGHIJKLMNOP", # 16 chars → 截断为 10
+ "warnings": [],
+ }
+ ],
+ },
+ content_hash="trunc-hash",
+ file_size=100,
+ status="accepted",
+ )
+ summary = intake_result_to_structured_summary(result)
+ row = summary["attachments"][0]
+ assert row["parse_status"] == "parsed"
+ assert row["stored_text_length"] == 10
+ assert any(str(w).startswith("eml_attachment_text_truncated:") for w in row["warnings"])
+ assert is_attachment_parse_incomplete(summary)
+
+
+def test_notice_text_truncated_blocks_integrity(app):
+ """扁平正文 notice_text_truncated 须进入完整性门禁。"""
+ from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
+ from app.services.shipping_notice.notice_upload import truncate_notice_text
+
+ with app.app_context():
+ app.config["SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS"] = 20
+ text, warnings = truncate_notice_text("X" * 50, [])
+ assert len(text) == 20
+ assert any(str(w).startswith("notice_text_truncated:") for w in warnings)
+ assert is_attachment_parse_incomplete(
+ {
+ "warnings": warnings,
+ "attachment_count": 0,
+ "attachments": [],
+ }
+ )
+
+
+def test_extract_eml_rfc822_forward_respects_size_limits():
+ """原生 message/rfc822 转发须受单附件/总量上限约束,不可静默完整展开。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ forwarded = EmailMessage()
+ forwarded["Subject"] = "Huge forward"
+ forwarded["From"] = "inner@example.com"
+ forwarded.set_content("Y" * 5000)
+
+ root = EmailMessage()
+ root["Subject"] = "Wrapper"
+ root["From"] = "outer@example.com"
+ root.set_content("see forward")
+ root.add_attachment(forwarded)
+
+ _, meta = parse_eml_bytes(
+ root.as_bytes(),
+ extract_text=extract_notice_text,
+ limits=EmlLimits(
+ max_attachments=10,
+ max_attachment_bytes=100,
+ max_total_attachment_bytes=100,
+ max_nesting_depth=3,
+ ),
+ )
+ assert any(
+ str(w).startswith("eml_attachment_too_large:")
+ or str(w).startswith("eml_total_attachment_size_exceeded:")
+ for w in meta["warnings"]
+ )
+ assert any(row.get("parse_status") == "skipped" for row in meta["attachments"])
+ flat_body = str((meta.get("email") or {}).get("body_text") or "")
+ assert ("Y" * 200) not in flat_body
+
+
+def test_intake_structured_summary_attachment_text_budget(app):
+ """附件文本总预算部分/完全耗尽时须投影 warning,且第二附件文本可被截断或清空。"""
+ from app.services.shipping_notice.intake_parse_workflow import intake_result_to_structured_summary
+ from app.services.shipping_notice.notice_upload import NoticeIntakeResult
+ from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
+
+ with app.app_context():
+ app.config["SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS"] = 30
+ result = NoticeIntakeResult(
+ filename="budget.eml",
+ source_type="email",
+ source_file_type="message/rfc822",
+ text="cover",
+ warnings=[],
+ meta={
+ "email": {"subject": "Budget", "body_text": "cover"},
+ "attachment_count": 2,
+ "attachments": [
+ {
+ "attachment_key": "att-001",
+ "filename": "a.txt",
+ "mime_type": "text/plain",
+ "size": 20,
+ "content_hash": "h1",
+ "parse_status": "parsed",
+ "extracted_text": "AAAAAAAAAA" * 3, # 30 chars
+ "warnings": [],
+ },
+ {
+ "attachment_key": "att-002",
+ "filename": "b.txt",
+ "mime_type": "text/plain",
+ "size": 20,
+ "content_hash": "h2",
+ "parse_status": "parsed",
+ "extracted_text": "BBBBBBBBBB" * 3,
+ "warnings": [],
+ },
+ ],
+ },
+ content_hash="budget-hash",
+ file_size=100,
+ status="accepted",
+ )
+ summary = intake_result_to_structured_summary(result)
+ assert any(
+ str(w).startswith("eml_attachment_text_budget_exhausted:") for w in summary["warnings"]
+ )
+ assert summary["attachments"][0]["stored_text_length"] == 30
+ assert summary["attachments"][1]["stored_text_length"] == 0
+ assert is_attachment_parse_incomplete(summary)
+
+
+def test_extract_eml_rfc822_depth_registers_skipped_row(tmp_path):
+ """超深 message/rfc822 应登记 skipped 附件行,便于前端感知不完整。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ deepest = EmailMessage()
+ deepest["Subject"] = "Deep"
+ deepest.set_content("DEEP-ORDER-SHOULD-SKIP")
+
+ mid = EmailMessage()
+ mid["Subject"] = "Mid"
+ mid.set_content("mid")
+ mid.add_attachment(deepest)
+
+ root = EmailMessage()
+ root["Subject"] = "Root"
+ root["From"] = "a@example.com"
+ root.set_content("root")
+ root.add_attachment(mid)
+
+ _, meta = parse_eml_bytes(
+ root.as_bytes(),
+ extract_text=extract_notice_text,
+ limits=EmlLimits(max_attachments=10, max_nesting_depth=0),
+ depth=0,
+ )
+ assert any(str(w).startswith("eml_nesting_depth_exceeded:") for w in meta["warnings"])
+ skipped = [row for row in meta["attachments"] if row.get("parse_status") == "skipped"]
+ assert skipped
+ assert any(
+ any(str(w).startswith("eml_nesting_depth_exceeded:") for w in (row.get("warnings") or []))
+ for row in skipped
+ )
+
+
+def test_extract_eml_keeps_inline_pdf_attachment(tmp_path):
+ """Content-Disposition: inline 的 PDF 不得被当成签名图丢弃。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.notice_upload import extract_notice_text
+
+ msg = EmailMessage()
+ msg["Subject"] = "Inline PDF"
+ msg["From"] = "a@example.com"
+ msg["To"] = "b@example.com"
+ msg.set_content("See PDF.")
+ msg.add_attachment(
+ _minimal_pdf_bytes("PO-INLINE-PDF"),
+ maintype="application",
+ subtype="pdf",
+ filename="inline-order.pdf",
+ disposition="inline",
+ )
+ path = tmp_path / "inline-pdf.eml"
+ path.write_bytes(msg.as_bytes())
+
+ text, meta = extract_notice_text(path)
+ assert meta["attachment_count"] == 1
+ assert meta["attachments"][0]["filename"] == "inline-order.pdf"
+ assert meta["attachments"][0]["parse_status"] == "parsed"
+ assert "PO-INLINE-PDF" in text
+
+
def test_extract_reservation_id_from_pr_number():
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
diff --git a/backend/tests/test_shipping_notice_intakes.py b/backend/tests/test_shipping_notice_intakes.py
new file mode 100644
index 00000000..1fc2d20f
--- /dev/null
+++ b/backend/tests/test_shipping_notice_intakes.py
@@ -0,0 +1,3929 @@
+"""
+backend/tests/test_shipping_notice_intakes.py
+
+用途:验证 FileAsset + ShippingNoticeIntake 创建、消费与幂等回放主路径。
+依赖:pytest、conftest app fixture、MinIO/建批路径 mock。
+逻辑:覆盖上传≠建单、parsed 才可建单、消费后幂等键可恢复、异常 kwargs 不抛 TypeError。
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+from werkzeug.datastructures import FileStorage
+from io import BytesIO
+
+from app import db
+from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
+from app.models import (
+ FileAsset,
+ ShippingBatch,
+ ShippingNoticeCandidate,
+ ShippingNoticeDocument,
+ ShippingNoticeIntake,
+ ShippingTask,
+ User,
+)
+from app.services.file_assets.service import upload_file_asset
+from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
+from app.services.shipping_notice.intake_service import create_shipping_notice_intake
+
+
+@pytest.fixture
+def shipping_user(app):
+ with app.app_context():
+ user = User(username='intake-user', email='intake@example.com', password_hash='x')
+ db.session.add(user)
+ db.session.commit()
+ yield user
+
+
+def _make_upload(content: bytes = b'customer order line', filename: str = 'notice.txt') -> FileStorage:
+ return FileStorage(stream=BytesIO(content), filename=filename, content_type='text/plain')
+
+
+def test_upload_file_asset_creates_ready_record(app, shipping_user):
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ result = upload_file_asset(user_id=shipping_user.id, upload=_make_upload())
+ asset = db.session.query(FileAsset).filter_by(asset_no=result['asset_no']).one()
+ assert asset.upload_status == 'ready'
+ assert asset.lifecycle_status == 'temporary'
+ assert asset.content_hash
+ assert 'storage_key' not in result
+
+
+def test_create_intake_queues_parse_job(app, shipping_user):
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset = upload_file_asset(user_id=shipping_user.id, upload=_make_upload())
+ with patch('app.services.shipping_notice.intake_service.enqueue', return_value=101) as enqueue_mock:
+ intake_data = create_shipping_notice_intake(
+ user_id=shipping_user.id,
+ asset_no=asset['asset_no'],
+ conversation_id='conv-intake-1',
+ )
+ assert intake_data['parse_status'] == 'queued'
+ enqueue_mock.assert_called_once()
+ assert enqueue_mock.call_args.kwargs.get('commit') is False
+ intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_data['intake_no']).one()
+ assert intake.parse_job_id == 101
+
+
+def test_create_intake_integrity_race_returns_existing(app, shipping_user, monkeypatch):
+ """并发首次插入撞唯一约束时须回落已有 Intake,不得 500。"""
+ with app.app_context():
+ from sqlalchemy.exc import IntegrityError
+
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(user_id=shipping_user.id, upload=_make_upload(b'race-intake'))
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ winner = ShippingNoticeIntake(
+ intake_no='SNI-RACE-WIN',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='queued',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ parse_job_id=555,
+ )
+ db.session.add(winner)
+ db.session.commit()
+
+ calls = {'n': 0}
+
+ def _lock_side_effect(*, asset_id, purpose, parser_version):
+ calls['n'] += 1
+ if calls['n'] == 1:
+ return None
+ return (
+ db.session.query(ShippingNoticeIntake)
+ .filter_by(intake_no='SNI-RACE-WIN')
+ .execution_options(populate_existing=True)
+ .with_for_update()
+ .first()
+ )
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_service._lock_intake_for_asset_purpose_parser',
+ _lock_side_effect,
+ )
+
+ def _boom_nested():
+ class _CM:
+ def __enter__(self):
+ raise IntegrityError('stmt', {}, Exception('uq'))
+
+ def __exit__(self, *args):
+ return False
+
+ return _CM()
+
+ monkeypatch.setattr(db.session, 'begin_nested', _boom_nested)
+
+ payload = create_shipping_notice_intake(
+ user_id=shipping_user.id,
+ asset_no=asset.asset_no,
+ conversation_id='conv-race',
+ )
+ assert payload['intake_no'] == 'SNI-RACE-WIN'
+ assert payload['parse_status'] == 'queued'
+ assert db.session.query(ShippingNoticeIntake).filter_by(asset_id=asset.id).count() == 1
+
+
+def test_create_parse_failed_twice_reuses_single_parse_job(app, shipping_user):
+ """parse_failed 并发式连续创建须串行持锁并复用同一 active Job。"""
+ with app.app_context():
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'parse-failed-reuse'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-FAIL-REUSE',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parse_failed',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
+ )
+ db.session.add(intake)
+ db.session.commit()
+
+ first = create_shipping_notice_intake(
+ user_id=shipping_user.id,
+ asset_no=asset.asset_no,
+ )
+ second = create_shipping_notice_intake(
+ user_id=shipping_user.id,
+ asset_no=asset.asset_no,
+ )
+ assert first['intake_no'] == second['intake_no'] == 'SNI-FAIL-REUSE'
+ assert first['parse_status'] == second['parse_status'] == 'queued'
+ jobs = (
+ db.session.query(Job)
+ .filter(
+ Job.domain == SHIPPING_NOTICE_JOB_DOMAIN,
+ Job.job_type == JobType.SHIPPING_NOTICE_PARSE.value,
+ Job.business_ref == 'SNI-FAIL-REUSE',
+ Job.status.in_(('queued', 'running')),
+ )
+ .all()
+ )
+ assert len(jobs) == 1
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-FAIL-REUSE').one()
+ assert refreshed.parse_job_id == jobs[0].id
+
+
+def test_create_intake_ignores_old_parser_version_reuse(app, shipping_user):
+ """同一 FileAsset 上旧 parser_version 的 parsed Intake 不得被新版本直接复用。"""
+ with app.app_context():
+ app.config['SHIPPING_NOTICE_PARSER_VERSION'] = 'v6'
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(user_id=shipping_user.id, upload=_make_upload(b'legacy-v5-body'))
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ # 覆盖本次升级:v5 仅有 JSON 附件摘要,无 Document/Candidate/派生资产,须强制重解析
+ old = ShippingNoticeIntake(
+ intake_no='SNI-OLD-PARSER-V5',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsed',
+ parser_version='v5',
+ extracted_text='stale without documents candidates or derived assets',
+ structured_result_json={'attachment_count': 0, 'attachments': [], 'warnings': []},
+ )
+ db.session.add(old)
+ db.session.commit()
+
+ with patch('app.services.shipping_notice.intake_service.enqueue', return_value=909) as enq:
+ payload = create_shipping_notice_intake(
+ user_id=shipping_user.id,
+ asset_no=asset.asset_no,
+ conversation_id='conv-parser-bump',
+ )
+ enq.assert_called_once()
+ assert payload['intake_no'] != old.intake_no
+ assert payload['parse_status'] == 'queued'
+ assert payload['parser_version'] == 'v6'
+ created = db.session.query(ShippingNoticeIntake).filter_by(intake_no=payload['intake_no']).one()
+ assert created.parser_version == 'v6'
+ assert created.asset_id == asset.id
+ # 旧版行仍在,但未被返回/复用
+ assert db.session.get(ShippingNoticeIntake, old.id).parse_status == 'parsed'
+
+
+def test_error_classes_accept_custom_code_kwargs(app):
+ """业务异常支持 code= 关键字,避免新分支抛 TypeError → 500。"""
+ with app.app_context():
+ err = NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
+ assert err.code == 'FILE_ASSET.NOT_FOUND'
+ err2 = ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问')
+ assert err2.code == 'FILE_ASSET.FORBIDDEN'
+ err3 = ValidationError(code='FILE_ASSET.EXPIRED', message='已过期')
+ assert err3.code == 'FILE_ASSET.EXPIRED'
+
+
+def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_value: str = 'abc123'):
+ asset = FileAsset(
+ asset_no=f'FA-{intake_no}',
+ owner_user_id=user_id,
+ original_filename='notice.txt',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{user_id}/test/{intake_no}.txt',
+ content_hash=hash_value,
+ file_size=12,
+ mime_type='text/plain',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ )
+ db.session.add(asset)
+ db.session.flush()
+ intake = ShippingNoticeIntake(
+ intake_no=intake_no,
+ asset_id=asset.id,
+ user_id=user_id,
+ purpose='shipping_notice',
+ parse_status='parsed',
+ parser_version='v1',
+ extracted_text='SKU001 qty 10',
+ )
+ db.session.add(intake)
+ db.session.commit()
+ return asset, intake
+
+
+def test_create_batch_from_intakes_marks_consumed_and_links_task(app, shipping_user, monkeypatch):
+ with app.app_context():
+ asset, intake = _seed_parsed_intake(shipping_user.id)
+
+ def _fake_create_batch_from_notice_items(**kwargs):
+ notice_items = kwargs['notice_items']
+ batch = ShippingBatch(
+ batch_no='SB-TEST-0001',
+ user_id=shipping_user.id,
+ file_count=1,
+ create_idempotency_key=kwargs.get('create_idempotency_key'),
+ )
+ db.session.add(batch)
+ db.session.flush()
+ item = notice_items[0]
+ task = ShippingTask(
+ task_no='SN-TEST-0001',
+ batch_id=batch.id,
+ user_id=shipping_user.id,
+ source_type='manual',
+ source_content_hash=item.get('source_content_hash'),
+ source_asset_id=item.get('source_asset_id'),
+ source_intake_id=item.get('source_intake_id'),
+ raw_content=item.get('raw_text'),
+ process_status='created',
+ )
+ db.session.add(task)
+ db.session.commit()
+ return {
+ 'status': 'ok',
+ 'batch_no': batch.batch_no,
+ 'data': {
+ 'batch': {'batch_no': batch.batch_no, 'id': batch.id},
+ 'tasks': [{'task_id': task.task_no}],
+ },
+ }
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
+ _fake_create_batch_from_notice_items,
+ )
+
+ result = create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-intake-1',
+ intake_nos=[intake.intake_no],
+ create_idempotency_key='idem-1',
+ )
+ assert result['batch_no'] == 'SB-TEST-0001'
+
+ refreshed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert refreshed.parse_status == 'consumed'
+ assert refreshed.consumed_batch_id is not None
+ assert refreshed.consumed_task_id is not None
+
+ task = db.session.query(ShippingTask).filter_by(task_no='SN-TEST-0001').one()
+ assert task.source_asset_id == asset.id
+ assert task.source_intake_id == intake.id
+
+ asset_ref = db.session.get(FileAsset, asset.id)
+ assert asset_ref.lifecycle_status == 'referenced'
+ assert int(asset_ref.reference_count or 0) >= 1
+
+
+def test_create_batch_from_intakes_idempotent_replay_after_consumed(app, shipping_user, monkeypatch):
+ with app.app_context():
+ asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-REPLAY')
+ batch = ShippingBatch(
+ batch_no='SB-TEST-REPLAY',
+ user_id=shipping_user.id,
+ file_count=1,
+ create_idempotency_key='idem-replay',
+ )
+ db.session.add(batch)
+ db.session.flush()
+ task = ShippingTask(
+ task_no='SN-TEST-REPLAY',
+ batch_id=batch.id,
+ user_id=shipping_user.id,
+ source_type='manual',
+ source_asset_id=asset.id,
+ source_intake_id=intake.id,
+ process_status='created',
+ )
+ intake.parse_status = 'consumed'
+ intake.consumed_at = datetime.utcnow()
+ intake.consumed_batch_id = batch.id
+ intake.consumed_task_id = None
+ db.session.add(task)
+ db.session.commit()
+ intake.consumed_task_id = task.id
+ db.session.commit()
+
+ called = {'count': 0}
+
+ def _should_not_create(**kwargs):
+ called['count'] += 1
+ raise AssertionError('idempotent replay must not create again')
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
+ _should_not_create,
+ )
+
+ result = create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-replay',
+ intake_nos=['SNI-TEST-REPLAY'],
+ create_idempotency_key='idem-replay',
+ )
+ assert result.get('idempotent_replay') is True
+ assert result['batch_no'] == 'SB-TEST-REPLAY'
+ assert called['count'] == 0
+
+
+def test_mixed_open_existing_and_create_idempotent_replay(app, shipping_user, monkeypatch):
+ """混合批次:open_existing 挂旧批次时,同幂等键重试须成功回放而非集合冲突。"""
+ with app.app_context():
+ # 旧任务(open_existing 目标)
+ old_batch = ShippingBatch(batch_no='SB-MIX-OLD', user_id=shipping_user.id, file_count=1)
+ db.session.add(old_batch)
+ db.session.flush()
+ old_task = ShippingTask(
+ task_no='SN-MIX-OLD',
+ batch_id=old_batch.id,
+ user_id=shipping_user.id,
+ source_type='manual',
+ process_status='waiting_inventory',
+ document_version=1,
+ )
+ db.session.add(old_task)
+ db.session.flush()
+
+ asset_a, intake_a = _seed_parsed_intake(
+ shipping_user.id, intake_no='SNI-MIX-A', hash_value='hash-mix-a'
+ )
+ asset_b, intake_b = _seed_parsed_intake(
+ shipping_user.id, intake_no='SNI-MIX-B', hash_value='hash-mix-b'
+ )
+ intake_a.duplicate_resolution = 'open_existing'
+ intake_a.duplicate_target_task_no = old_task.task_no
+ intake_a.duplicate_status = 'same_active_task'
+ intake_a.duplicate_matches_json = [
+ {
+ 'task_no': old_task.task_no,
+ 'process_status': old_task.process_status,
+ 'document_version': 1,
+ 'match_type': 'business_fingerprint',
+ 'matched_fields': ['po_number'],
+ 'lifecycle': 'active',
+ }
+ ]
+ db.session.commit()
+
+ def _fake_create(**kwargs):
+ batch = ShippingBatch(
+ batch_no='SB-MIX-NEW',
+ user_id=shipping_user.id,
+ file_count=1,
+ create_idempotency_key=kwargs.get('create_idempotency_key'),
+ process_summary_json={'request_intake_nos': ['SNI-MIX-A', 'SNI-MIX-B']},
+ )
+ db.session.add(batch)
+ db.session.flush()
+ item = kwargs['notice_items'][0]
+ task = ShippingTask(
+ task_no='SN-MIX-NEW',
+ batch_id=batch.id,
+ user_id=shipping_user.id,
+ source_type='manual',
+ source_intake_id=item.get('source_intake_id'),
+ source_asset_id=item.get('source_asset_id'),
+ process_status='created',
+ )
+ db.session.add(task)
+ db.session.commit()
+ return {
+ 'status': 'ok',
+ 'batch_no': batch.batch_no,
+ 'data': {
+ 'batch': {'batch_no': batch.batch_no, 'id': batch.id},
+ 'tasks': [{'task_id': task.task_no}],
+ 'focus_task': {'task_no': task.task_no},
+ },
+ }
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
+ _fake_create,
+ )
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake',
+ lambda **kwargs: {
+ 'status': kwargs['intake'].duplicate_status or 'none',
+ 'blocking': kwargs['intake'].duplicate_resolution == 'open_existing',
+ 'fingerprint': None,
+ 'fingerprint_version': 'shipping-v1',
+ 'fingerprint_strength': 'strong',
+ 'matches': list(kwargs['intake'].duplicate_matches_json or []),
+ 'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
+ },
+ )
+
+ first = create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-mix',
+ intake_nos=['SNI-MIX-A', 'SNI-MIX-B'],
+ create_idempotency_key='idem-mix-1',
+ )
+ assert first.get('batch_no') == 'SB-MIX-NEW'
+ assert first.get('idempotent_replay') is not True
+ assert any(x.get('task_no') == 'SN-MIX-OLD' for x in (first.get('opened_existing') or []))
+
+ second = create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-mix',
+ intake_nos=['SNI-MIX-A', 'SNI-MIX-B'],
+ create_idempotency_key='idem-mix-1',
+ )
+ assert second.get('idempotent_replay') is True
+ assert second.get('batch_no') == 'SB-MIX-NEW'
+ assert any(x.get('task_no') == 'SN-MIX-OLD' for x in (second.get('opened_existing') or []))
+
+
+def test_pure_open_existing_idempotent_replay(app, shipping_user, monkeypatch):
+ """纯 open_existing:无新批次时凭 intake 幂等键重放,不报已消费。"""
+ with app.app_context():
+ old_batch = ShippingBatch(batch_no='SB-OPEN-ONLY', user_id=shipping_user.id, file_count=1)
+ db.session.add(old_batch)
+ db.session.flush()
+ old_task = ShippingTask(
+ task_no='SN-OPEN-ONLY',
+ batch_id=old_batch.id,
+ user_id=shipping_user.id,
+ source_type='manual',
+ process_status='pending_review',
+ )
+ db.session.add(old_task)
+ _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-OPEN-ONLY', hash_value='hash-open-only')
+ intake.duplicate_resolution = 'open_existing'
+ intake.duplicate_target_task_no = old_task.task_no
+ intake.duplicate_status = 'same_active_task'
+ intake.duplicate_matches_json = [
+ {
+ 'task_no': old_task.task_no,
+ 'process_status': 'pending_review',
+ 'document_version': 1,
+ 'match_type': 'business_fingerprint',
+ 'matched_fields': ['po_number'],
+ 'lifecycle': 'active',
+ }
+ ]
+ db.session.commit()
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake',
+ lambda **kwargs: {
+ 'status': 'same_active_task',
+ 'blocking': True,
+ 'fingerprint': 'fp',
+ 'fingerprint_version': 'shipping-v1',
+ 'fingerprint_strength': 'strong',
+ 'matches': list(intake.duplicate_matches_json or []),
+ 'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
+ },
+ )
+
+ first = create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-open-only',
+ intake_nos=['SNI-OPEN-ONLY'],
+ create_idempotency_key='idem-open-only',
+ )
+ assert first.get('batch_no') in (None, '')
+ assert first.get('idempotent_replay') is False
+
+ second = create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-open-only',
+ intake_nos=['SNI-OPEN-ONLY'],
+ create_idempotency_key='idem-open-only',
+ )
+ assert second.get('idempotent_replay') is True
+ assert (second.get('opened_existing') or [])[0].get('task_no') == 'SN-OPEN-ONLY'
+
+
+def test_intake_replay_heals_missing_consumed_batch_id(app, shipping_user):
+ """批次已创建但 intake.consumed_batch_id 未回填时,重放须恢复批次而非「未创建新批次」。"""
+ with app.app_context():
+ asset, intake = _seed_parsed_intake(
+ shipping_user.id, intake_no='SNI-HEAL-1', hash_value='hash-heal-1'
+ )
+ batch = ShippingBatch(
+ batch_no='SB-HEAL-1',
+ user_id=shipping_user.id,
+ file_count=1,
+ create_idempotency_key='idem-heal-1',
+ )
+ db.session.add(batch)
+ db.session.flush()
+ task = ShippingTask(
+ task_no='SN-HEAL-1',
+ batch_id=batch.id,
+ user_id=shipping_user.id,
+ source_type='manual',
+ source_intake_id=intake.id,
+ source_asset_id=asset.id,
+ process_status='created',
+ )
+ db.session.add(task)
+ # 模拟提交断点:已 stamp + consumed,但尚未回填 consumed_batch_id
+ intake.parse_status = 'consumed'
+ intake.consumed_at = datetime.utcnow()
+ intake.create_idempotency_key = 'idem-heal-1'
+ intake.consumed_batch_id = None
+ intake.consumed_task_id = None
+ db.session.commit()
+
+ result = create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-heal',
+ intake_nos=['SNI-HEAL-1'],
+ create_idempotency_key='idem-heal-1',
+ )
+ assert result.get('idempotent_replay') is True
+ assert result.get('batch_no') == 'SB-HEAL-1'
+ assert '未创建新批次' not in str(result.get('message') or '')
+ refreshed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert refreshed.consumed_batch_id == batch.id
+ assert refreshed.consumed_task_id == task.id
+
+
+def test_revision_conflict_when_successor_exists(app, shipping_user):
+ """已有后继修订时,再次 create_revision 应冲突。"""
+ from app.services.shipping_notice.intake_parse_workflow import intake_to_notice_item
+
+ with app.app_context():
+ base = ShippingTask(
+ task_no='SN-REV-LOCK-BASE',
+ user_id=shipping_user.id,
+ source_type='manual',
+ process_status='uploaded',
+ document_version=1,
+ )
+ db.session.add(base)
+ db.session.flush()
+ successor = ShippingTask(
+ task_no='SN-REV-LOCK-V2',
+ user_id=shipping_user.id,
+ source_type='manual',
+ process_status='pending_review',
+ document_version=2,
+ supersedes_task_id=base.id,
+ duplicate_resolution_type='revision',
+ )
+ db.session.add(successor)
+ asset, intake = _seed_parsed_intake(
+ shipping_user.id, intake_no='SNI-REV-LOCK', hash_value='hash-rev-lock'
+ )
+ intake.duplicate_resolution = 'create_revision'
+ intake.duplicate_target_task_no = base.task_no
+ db.session.commit()
+
+ with pytest.raises(ConflictError) as excinfo:
+ intake_to_notice_item(intake, asset)
+ assert excinfo.value.code == 'SHIPPING_NOTICE.REVISION_CONFLICT'
+
+
+def test_queued_intake_cannot_create_batch(app, shipping_user):
+ with app.app_context():
+ _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-QUEUED')
+ intake.parse_status = 'queued'
+ db.session.commit()
+ with pytest.raises(Exception) as excinfo:
+ create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id=None,
+ intake_nos=[intake.intake_no],
+ create_idempotency_key='idem-queued',
+ )
+ assert 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' in str(getattr(excinfo.value, 'code', '')) or True
+ from app.core.errors import ConflictError
+ assert isinstance(excinfo.value, ConflictError)
+ assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING'
+
+
+def test_incomplete_attachments_cannot_create_batch(app, shipping_user):
+ """顶层 parsed 但附件不完整时,建批须被后端门禁拒绝。"""
+ with app.app_context():
+ _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-INCOMPLETE-ATT')
+ intake.structured_result_json = {
+ 'filename': 'mail.eml',
+ 'source_type': 'email',
+ 'attachment_count': 2,
+ 'attachments': [
+ {'filename': 'ok.pdf', 'parse_status': 'parsed', 'warnings': []},
+ {'filename': 'bad.pdf', 'parse_status': 'failed', 'warnings': []},
+ ],
+ 'warnings': [],
+ }
+ db.session.commit()
+ with pytest.raises(ConflictError) as excinfo:
+ create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id=None,
+ intake_nos=[intake.intake_no],
+ create_idempotency_key='idem-incomplete-att',
+ )
+ assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE'
+
+
+def test_text_budget_exhausted_cannot_create_batch(app, shipping_user):
+ """文本预算耗尽警告须进入建批完整性门禁。"""
+ with app.app_context():
+ _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-BUDGET-BLOCK')
+ intake.structured_result_json = {
+ 'filename': 'mail.eml',
+ 'source_type': 'email',
+ 'attachment_count': 1,
+ 'attachments': [
+ {
+ 'filename': 'big.txt',
+ 'parse_status': 'parsed',
+ 'warnings': ['eml_attachment_text_budget_exhausted:500000'],
+ }
+ ],
+ 'warnings': ['eml_attachment_text_budget_exhausted:500000'],
+ }
+ db.session.commit()
+ with pytest.raises(ConflictError) as excinfo:
+ create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id=None,
+ intake_nos=[intake.intake_no],
+ create_idempotency_key='idem-budget-block',
+ )
+ assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE'
+
+
+def test_retry_parse_allows_incomplete_parsed_intake(app, shipping_user):
+ """附件不完整但顶层 parsed 时须允许重试解析。"""
+ from app.services.shipping_notice.intake_service import retry_intake_parse
+
+ with app.app_context():
+ _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-RETRY-INCOMPLETE')
+ intake.structured_result_json = {
+ 'attachment_count': 1,
+ 'attachments': [{'filename': 'x.pdf', 'parse_status': 'failed', 'warnings': []}],
+ 'warnings': [],
+ }
+ db.session.commit()
+ with patch('app.services.shipping_notice.intake_service.enqueue', return_value=4242) as enq:
+ payload = retry_intake_parse(user_id=shipping_user.id, intake_no=intake.intake_no)
+ enq.assert_called_once()
+ kwargs = enq.call_args.kwargs
+ assert kwargs.get('commit') is False
+ assert kwargs.get('dedupe_statuses') == ('queued',)
+ assert payload['parse_status'] == 'queued'
+ refreshed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert refreshed.parse_status == 'queued'
+ assert refreshed.parse_job_id == 4242
+
+
+def test_retry_parse_does_not_reuse_running_job(app, shipping_user):
+ """重试不得复用仍为 running 的原 Job,须新建 queued Job。"""
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.intake_service import retry_intake_parse
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-RETRY-RUNNING')
+ intake.parse_status = 'parse_failed'
+ db.session.flush()
+ running = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref=intake.intake_no,
+ payload_json={'intake_no': intake.intake_no},
+ progress=50,
+ message='running old parse',
+ attempts=1,
+ max_attempts=3,
+ created_by_id=shipping_user.id,
+ )
+ db.session.add(running)
+ db.session.commit()
+ old_id = int(running.id)
+
+ payload = retry_intake_parse(user_id=shipping_user.id, intake_no=intake.intake_no)
+ assert payload['parse_status'] == 'queued'
+ refreshed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert int(refreshed.parse_job_id or 0) != old_id
+ new_job = db.session.get(Job, int(refreshed.parse_job_id))
+ assert new_job is not None
+ assert new_job.status == 'queued'
+ assert db.session.get(Job, old_id).status == 'running'
+
+
+def test_enqueue_commit_false_keeps_job_uncommitted_until_outer_commit(app, shipping_user):
+ """enqueue(commit=False) 仅 flush,外层 rollback 后 Job 不得残留。"""
+ from app.jobs.queue import enqueue
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ job_id = enqueue(
+ JobType.SHIPPING_NOTICE_PARSE,
+ {'intake_no': 'SNI-ENQ-FLUSH'},
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ business_ref='SNI-ENQ-FLUSH',
+ created_by_id=shipping_user.id,
+ commit=False,
+ dedupe_active=False,
+ )
+ assert int(job_id) > 0
+ assert db.session.get(Job, job_id) is not None
+ db.session.rollback()
+ assert db.session.get(Job, job_id) is None
+
+
+def test_enqueue_unique_conflict_does_not_poison_outer_transaction(app, shipping_user):
+ """
+ 唯一冲突必须落在 SAVEPOINT 内:外层 Intake 修改不得因 PendingRollbackError 丢失。
+ """
+ from app.jobs.queue import enqueue
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'enq-savepoint'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-ENQ-SAVEPOINT',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parse_failed',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ existing = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='queued',
+ priority=0,
+ business_ref='SNI-ENQ-SAVEPOINT',
+ payload_json={'intake_no': 'SNI-ENQ-SAVEPOINT'},
+ progress=0,
+ message='winner',
+ attempts=0,
+ max_attempts=3,
+ created_by_id=shipping_user.id,
+ )
+ db.session.add(intake)
+ db.session.add(existing)
+ db.session.commit()
+ keep_id = int(existing.id)
+
+ # 外层事务:先改 Intake,再强制插入撞唯一(dedupe 关闭)
+ locked = (
+ db.session.query(ShippingNoticeIntake)
+ .filter_by(intake_no='SNI-ENQ-SAVEPOINT')
+ .with_for_update()
+ .one()
+ )
+ locked.parse_status = 'queued'
+ locked.error_message = None
+ returned_id = enqueue(
+ JobType.SHIPPING_NOTICE_PARSE,
+ {'intake_no': 'SNI-ENQ-SAVEPOINT'},
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ business_ref='SNI-ENQ-SAVEPOINT',
+ created_by_id=shipping_user.id,
+ dedupe_active=False,
+ commit=False,
+ )
+ assert returned_id == keep_id
+ locked.parse_job_id = returned_id
+ db.session.commit()
+
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-ENQ-SAVEPOINT'
+ ).one()
+ assert refreshed.parse_status == 'queued'
+ assert refreshed.parse_job_id == keep_id
+ assert (
+ db.session.query(Job)
+ .filter(
+ Job.business_ref == 'SNI-ENQ-SAVEPOINT',
+ Job.status == 'queued',
+ )
+ .count()
+ == 1
+ )
+
+
+def test_fail_job_supersedes_running_when_queued_sibling_exists(app, shipping_user):
+ """旧 running 失败重试时若已有 queued 同伴,须 cancelled 并重指 parse_job_id。"""
+ from datetime import datetime, timedelta
+
+ from app.jobs.queue import fail_job
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'fail-supersede'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-FAIL-SUPERSEDE',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ parse_lease='1:1',
+ )
+ running = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-FAIL-SUPERSEDE',
+ payload_json={'intake_no': 'SNI-FAIL-SUPERSEDE'},
+ progress=50,
+ message='old running',
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(minutes=10),
+ created_by_id=shipping_user.id,
+ )
+ queued = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='queued',
+ priority=0,
+ business_ref='SNI-FAIL-SUPERSEDE',
+ payload_json={'intake_no': 'SNI-FAIL-SUPERSEDE'},
+ progress=0,
+ message='new queued',
+ attempts=0,
+ max_attempts=3,
+ created_by_id=shipping_user.id,
+ )
+ db.session.add_all([intake, running, queued])
+ db.session.flush()
+ intake.parse_job_id = int(running.id)
+ db.session.commit()
+ old_id = int(running.id)
+ keep_id = int(queued.id)
+
+ ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1)
+ assert ok is True
+ assert db.session.get(Job, old_id).status == 'cancelled'
+ assert db.session.get(Job, keep_id).status == 'queued'
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-FAIL-SUPERSEDE'
+ ).one()
+ assert refreshed.parse_job_id == keep_id
+ assert refreshed.parse_status == 'queued'
+ assert refreshed.parse_lease is None
+
+
+def test_fail_job_retarget_preserves_running_sibling_lease(app, shipping_user):
+ """替代 Job 已真正 claim Intake(精确 lease)时,supersede 须保留 parsing/lease。"""
+ from datetime import datetime, timedelta
+
+ from app.jobs.queue import fail_job
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'fail-preserve-lease'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-PRESERVE-LEASE',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ old = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-PRESERVE-LEASE',
+ payload_json={'intake_no': 'SNI-PRESERVE-LEASE'},
+ progress=50,
+ message='old',
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(minutes=10),
+ created_by_id=shipping_user.id,
+ )
+ keep = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-PRESERVE-LEASE',
+ payload_json={'intake_no': 'SNI-PRESERVE-LEASE'},
+ progress=20,
+ message='new worker',
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow(),
+ created_by_id=shipping_user.id,
+ )
+ db.session.add_all([intake, old, keep])
+ db.session.flush()
+ keep_id = int(keep.id)
+ intake.parse_job_id = keep_id
+ intake.parse_lease = f'{keep_id}:1'
+ db.session.commit()
+ old_id = int(old.id)
+
+ ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1)
+ assert ok is True
+ assert db.session.get(Job, old_id).status == 'cancelled'
+ assert db.session.get(Job, keep_id).status == 'running'
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-PRESERVE-LEASE'
+ ).one()
+ assert refreshed.parse_job_id == keep_id
+ assert refreshed.parse_status == 'parsing'
+ assert refreshed.parse_lease == f'{keep_id}:1'
+
+
+def test_fail_job_does_not_supersede_unowned_running_sibling(app, shipping_user):
+ """
+ 同伴仅 Job.running、尚未 claim Intake 时不得 supersede。
+
+ 模拟:新 Worker 已读到旧 parse_job_id 将决定 skip+finish;若旧失败线程把 lease
+ 伪造给新 Job,会导致 Intake 永久 parsing。此时旧 Job 应正常 requeue。
+ """
+ from datetime import datetime, timedelta
+
+ from app.jobs.queue import fail_job
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'fail-unowned-running'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-UNOWNED-RUNNING',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ old = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-UNOWNED-RUNNING',
+ payload_json={'intake_no': 'SNI-UNOWNED-RUNNING'},
+ progress=50,
+ message='old still owns intake',
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(minutes=10),
+ created_by_id=shipping_user.id,
+ )
+ peer = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-UNOWNED-RUNNING',
+ payload_json={'intake_no': 'SNI-UNOWNED-RUNNING'},
+ progress=10,
+ message='claimed job but not intake yet',
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow(),
+ created_by_id=shipping_user.id,
+ )
+ db.session.add_all([intake, old, peer])
+ db.session.flush()
+ old_id = int(old.id)
+ peer_id = int(peer.id)
+ # Intake 仍属旧 Job(新 Worker 预检会看到非本 Job 并 skip)
+ intake.parse_job_id = old_id
+ intake.parse_lease = f'{old_id}:1'
+ db.session.commit()
+
+ ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1)
+ assert ok is True
+ refreshed_old = db.session.get(Job, old_id)
+ assert refreshed_old is not None
+ # 不得 cancelled + 伪造 lease;应 requeue 旧 Job,并同步 Intake 离开 parsing
+ assert refreshed_old.status == 'queued'
+ assert refreshed_old.started_at is None
+ assert db.session.get(Job, peer_id).status == 'running'
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-UNOWNED-RUNNING'
+ ).one()
+ assert refreshed.parse_job_id == old_id
+ assert refreshed.parse_status == 'queued'
+ assert refreshed.parse_lease is None
+
+
+def test_fail_job_requeue_clears_started_at_so_recover_does_not_demote(app, shipping_user):
+ """fail_job requeue 必须清空 started_at,否则 claim 后会被超时回收立刻打回。"""
+ from datetime import datetime, timedelta
+
+ from app.jobs.queue import claim_next_job, fail_job, recover_stale_jobs
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'fail-started-at'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-STARTED-AT',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ job = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-STARTED-AT',
+ payload_json={'intake_no': 'SNI-STARTED-AT'},
+ progress=50,
+ message='long running',
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(hours=2),
+ created_by_id=shipping_user.id,
+ )
+ db.session.add_all([intake, job])
+ db.session.flush()
+ job_id = int(job.id)
+ intake.parse_job_id = job_id
+ intake.parse_lease = f'{job_id}:1'
+ db.session.commit()
+
+ assert fail_job(job_id, error='retryable', retryable=True, owned_attempt=1) is True
+ queued = db.session.get(Job, job_id)
+ assert queued is not None and queued.status == 'queued'
+ assert queued.started_at is None
+
+ claimed = claim_next_job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_types=[JobType.SHIPPING_NOTICE_PARSE],
+ )
+ assert claimed is not None and int(claimed.id) == job_id
+ claim_started = claimed.started_at
+ assert claim_started is not None
+
+ recovered = recover_stale_jobs(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ timeout_seconds=60,
+ job_type=JobType.SHIPPING_NOTICE_PARSE,
+ )
+ assert recovered == 0
+ still = db.session.get(Job, job_id)
+ assert still is not None
+ assert still.status == 'running'
+ assert still.started_at == claim_started
+
+
+def test_fail_job_prefers_queued_over_lower_id_unowned_running(app, shipping_user):
+ """不安全 running id 更小时,仍须选择后面的 queued 替代旧 Job。"""
+ from datetime import datetime, timedelta
+
+ from app.jobs.queue import fail_job
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'fail-prefer-queued'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-FAIL-PREFER-QUEUED',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ old = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-FAIL-PREFER-QUEUED',
+ payload_json={'intake_no': 'SNI-FAIL-PREFER-QUEUED'},
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(minutes=10),
+ created_by_id=shipping_user.id,
+ )
+ unowned = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-FAIL-PREFER-QUEUED',
+ payload_json={'intake_no': 'SNI-FAIL-PREFER-QUEUED'},
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow(),
+ created_by_id=shipping_user.id,
+ )
+ queued = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='queued',
+ priority=0,
+ business_ref='SNI-FAIL-PREFER-QUEUED',
+ payload_json={'intake_no': 'SNI-FAIL-PREFER-QUEUED'},
+ attempts=0,
+ max_attempts=3,
+ created_by_id=shipping_user.id,
+ )
+ db.session.add_all([intake, old, unowned, queued])
+ db.session.flush()
+ old_id = int(old.id)
+ unowned_id = int(unowned.id)
+ queued_id = int(queued.id)
+ assert unowned_id < queued_id
+ intake.parse_job_id = old_id
+ intake.parse_lease = f'{old_id}:1'
+ db.session.commit()
+
+ ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1)
+ assert ok is True
+ assert db.session.get(Job, old_id).status == 'cancelled'
+ assert db.session.get(Job, unowned_id).status == 'running'
+ assert db.session.get(Job, queued_id).status == 'queued'
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-FAIL-PREFER-QUEUED'
+ ).one()
+ assert refreshed.parse_job_id == queued_id
+ assert refreshed.parse_status == 'queued'
+ assert refreshed.parse_lease is None
+
+
+def test_create_intake_rejects_cancelled_and_expired(app, shipping_user):
+ """创建入口不得复活 cancelled/expired;过期须落 expired 并 CONFLICT。"""
+ from datetime import datetime, timedelta
+
+ from app.core.errors import ConflictError
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_cancelled = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'create-cancel'),
+ )
+ asset_expired = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'create-expire'),
+ )
+ a1 = db.session.query(FileAsset).filter_by(asset_no=asset_cancelled['asset_no']).one()
+ a2 = db.session.query(FileAsset).filter_by(asset_no=asset_expired['asset_no']).one()
+ cancelled = ShippingNoticeIntake(
+ intake_no='SNI-CREATE-CANCELLED',
+ asset_id=a1.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='cancelled',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ expired = ShippingNoticeIntake(
+ intake_no='SNI-CREATE-EXPIRED',
+ asset_id=a2.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parse_failed',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ expires_at=datetime.utcnow() - timedelta(hours=1),
+ )
+ db.session.add_all([cancelled, expired])
+ db.session.commit()
+
+ with pytest.raises(ConflictError) as cancelled_exc:
+ create_shipping_notice_intake(
+ user_id=shipping_user.id,
+ asset_no=a1.asset_no,
+ )
+ assert cancelled_exc.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS'
+ assert (
+ db.session.query(ShippingNoticeIntake)
+ .filter_by(intake_no='SNI-CREATE-CANCELLED')
+ .one()
+ .parse_status
+ == 'cancelled'
+ )
+
+ with pytest.raises(ConflictError) as expired_exc:
+ create_shipping_notice_intake(
+ user_id=shipping_user.id,
+ asset_no=a2.asset_no,
+ )
+ assert expired_exc.value.code == 'SHIPPING_NOTICE.INTAKE_EXPIRED'
+ assert (
+ db.session.query(ShippingNoticeIntake)
+ .filter_by(intake_no='SNI-CREATE-EXPIRED')
+ .one()
+ .parse_status
+ == 'expired'
+ )
+
+
+def test_recover_stale_supersedes_running_when_queued_sibling_exists(app, shipping_user):
+ """超时回收旧 running 时若已有 queued 同伴,须 cancelled 并重指 Intake。"""
+ from datetime import datetime, timedelta
+
+ from app.jobs.queue import recover_stale_jobs
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.intake_parse_workflow import (
+ sync_intake_after_parse_job_recovery,
+ )
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'recover-supersede'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-RECOVER-SUPERSEDE',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ parse_lease='9:1',
+ )
+ running = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-RECOVER-SUPERSEDE',
+ payload_json={'intake_no': 'SNI-RECOVER-SUPERSEDE'},
+ progress=50,
+ message='stale running',
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(hours=1),
+ created_by_id=shipping_user.id,
+ )
+ queued = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='queued',
+ priority=0,
+ business_ref='SNI-RECOVER-SUPERSEDE',
+ payload_json={'intake_no': 'SNI-RECOVER-SUPERSEDE'},
+ progress=0,
+ message='replacement',
+ attempts=0,
+ max_attempts=3,
+ created_by_id=shipping_user.id,
+ )
+ db.session.add_all([intake, running, queued])
+ db.session.flush()
+ intake.parse_job_id = int(running.id)
+ db.session.commit()
+ old_id = int(running.id)
+ keep_id = int(queued.id)
+
+ count = recover_stale_jobs(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ timeout_seconds=60,
+ job_type=JobType.SHIPPING_NOTICE_PARSE,
+ on_recovered=sync_intake_after_parse_job_recovery,
+ )
+ assert count == 1
+ assert db.session.get(Job, old_id).status == 'cancelled'
+ assert db.session.get(Job, keep_id).status == 'queued'
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-RECOVER-SUPERSEDE'
+ ).one()
+ assert refreshed.parse_job_id == keep_id
+ assert refreshed.parse_status == 'queued'
+ assert refreshed.parse_lease is None
+
+
+def test_recover_stale_prefers_queued_over_lower_id_unowned_running(app, shipping_user):
+ """回收时不得让较小 id 的不安全 running 遮挡 queued 替代者。"""
+ from datetime import datetime, timedelta
+
+ from app.jobs.queue import recover_stale_jobs
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.intake_parse_workflow import (
+ sync_intake_after_parse_job_recovery,
+ )
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'recover-prefer-queued'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-RECOVER-PREFER-QUEUED',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ old = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-RECOVER-PREFER-QUEUED',
+ payload_json={'intake_no': 'SNI-RECOVER-PREFER-QUEUED'},
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(hours=2),
+ created_by_id=shipping_user.id,
+ )
+ unowned = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ priority=0,
+ business_ref='SNI-RECOVER-PREFER-QUEUED',
+ payload_json={'intake_no': 'SNI-RECOVER-PREFER-QUEUED'},
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow(),
+ created_by_id=shipping_user.id,
+ )
+ queued = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='queued',
+ priority=0,
+ business_ref='SNI-RECOVER-PREFER-QUEUED',
+ payload_json={'intake_no': 'SNI-RECOVER-PREFER-QUEUED'},
+ attempts=0,
+ max_attempts=3,
+ created_by_id=shipping_user.id,
+ )
+ db.session.add_all([intake, old, unowned, queued])
+ db.session.flush()
+ old_id = int(old.id)
+ unowned_id = int(unowned.id)
+ queued_id = int(queued.id)
+ assert unowned_id < queued_id
+ intake.parse_job_id = old_id
+ intake.parse_lease = f'{old_id}:1'
+ db.session.commit()
+
+ count = recover_stale_jobs(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ timeout_seconds=60,
+ job_type=JobType.SHIPPING_NOTICE_PARSE,
+ on_recovered=sync_intake_after_parse_job_recovery,
+ )
+ assert count == 1
+ assert db.session.get(Job, old_id).status == 'cancelled'
+ assert db.session.get(Job, unowned_id).status == 'running'
+ assert db.session.get(Job, queued_id).status == 'queued'
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-RECOVER-PREFER-QUEUED'
+ ).one()
+ assert refreshed.parse_job_id == queued_id
+ assert refreshed.parse_status == 'queued'
+ assert refreshed.parse_lease is None
+
+
+def test_migration_retarget_helper_updates_intake_parse_job_id(app, shipping_user):
+ """迁移去重辅助:取消重复 Job 前须把 Intake.parse_job_id 重指 keep_id。"""
+ import importlib.util
+ from pathlib import Path
+
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=_make_upload(b'mig-retarget'),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ keep = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='queued',
+ priority=0,
+ business_ref='SNI-MIG-RETARGET',
+ payload_json={'intake_no': 'SNI-MIG-RETARGET'},
+ progress=0,
+ message='keep',
+ attempts=0,
+ max_attempts=3,
+ created_by_id=shipping_user.id,
+ )
+ drop = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='cancelled',
+ priority=0,
+ business_ref='SNI-MIG-RETARGET',
+ payload_json={'intake_no': 'SNI-MIG-RETARGET'},
+ progress=100,
+ message='drop',
+ attempts=0,
+ max_attempts=3,
+ created_by_id=shipping_user.id,
+ )
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-MIG-RETARGET',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='queued',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ db.session.add_all([keep, drop, intake])
+ db.session.flush()
+ intake.parse_job_id = int(drop.id)
+ db.session.commit()
+ keep_id = int(keep.id)
+ drop_id = int(drop.id)
+
+ mig_path = (
+ Path(__file__).resolve().parents[1]
+ / 'migrations'
+ / 'versions'
+ / 'b7c8d9e0f1a2_jobs_parse_active_unique.py'
+ )
+ spec = importlib.util.spec_from_file_location('mig_b7_parse_uq', mig_path)
+ assert spec and spec.loader
+ mig = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mig)
+ mig._retarget_intake_parse_job_ids(
+ db.session.connection(),
+ keep_id=keep_id,
+ drop_ids=[drop_id],
+ )
+ db.session.commit()
+
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-MIG-RETARGET'
+ ).one()
+ assert refreshed.parse_job_id == keep_id
+
+
+def test_create_batch_failure_rolls_back_preconsume(app, shipping_user, monkeypatch):
+ """建批业务异常后预占 consumed 须回滚,否则用户无法重试。"""
+ with app.app_context():
+ _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-ROLLBACK')
+
+ def _raise_conflict(**kwargs):
+ raise ConflictError(
+ '精确重复通知',
+ code='SHIPPING.EXACT_DUPLICATE',
+ )
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
+ _raise_conflict,
+ )
+
+ with pytest.raises(ConflictError) as excinfo:
+ create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-rollback',
+ intake_nos=[intake.intake_no],
+ create_idempotency_key='idem-rollback',
+ )
+ assert excinfo.value.code == 'SHIPPING.EXACT_DUPLICATE'
+
+ refreshed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert refreshed.parse_status == 'parsed'
+ assert refreshed.consumed_at is None
+ assert refreshed.consumed_batch_id is None
+
+
+def test_create_batch_dedupes_same_content_hash_intakes(app, shipping_user, monkeypatch):
+ """相同 content_hash 的多个 intake:只建一个任务,附属 intake 也关联到同一任务。"""
+ with app.app_context():
+ asset1, intake1 = _seed_parsed_intake(
+ shipping_user.id, intake_no='SNI-DEDUP-1', hash_value='same-hash-xx'
+ )
+ asset2, intake2 = _seed_parsed_intake(
+ shipping_user.id, intake_no='SNI-DEDUP-2', hash_value='same-hash-xx'
+ )
+
+ def _fake_create(**kwargs):
+ notice_items = kwargs['notice_items']
+ assert len(notice_items) == 1
+ batch = ShippingBatch(
+ batch_no='SB-DEDUP-1',
+ user_id=shipping_user.id,
+ file_count=1,
+ create_idempotency_key=kwargs.get('create_idempotency_key'),
+ )
+ db.session.add(batch)
+ db.session.flush()
+ item = notice_items[0]
+ task = ShippingTask(
+ task_no='SN-DEDUP-1',
+ batch_id=batch.id,
+ user_id=shipping_user.id,
+ source_type='manual',
+ source_content_hash=item.get('source_content_hash'),
+ source_asset_id=item.get('source_asset_id'),
+ source_intake_id=item.get('source_intake_id'),
+ raw_content=item.get('raw_text'),
+ process_status='created',
+ )
+ db.session.add(task)
+ db.session.commit()
+ return {
+ 'status': 'ok',
+ 'batch_no': batch.batch_no,
+ 'data': {
+ 'batch': {'batch_no': batch.batch_no, 'id': batch.id},
+ 'tasks': [{'task_id': task.task_no}],
+ },
+ }
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
+ _fake_create,
+ )
+
+ result = create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-dedup',
+ intake_nos=[intake1.intake_no, intake2.intake_no],
+ create_idempotency_key='idem-dedup',
+ )
+ assert result['batch_no'] == 'SB-DEDUP-1'
+
+ r1 = db.session.get(ShippingNoticeIntake, intake1.id)
+ r2 = db.session.get(ShippingNoticeIntake, intake2.id)
+ assert r1.parse_status == 'consumed'
+ assert r2.parse_status == 'consumed'
+ assert r1.consumed_batch_id == r2.consumed_batch_id
+ assert r1.consumed_task_id == r2.consumed_task_id
+ assert r1.consumed_task_id is not None
+
+ # 同键重放不应因「请求 2 个 intake / 任务只绑 1 个」而冲突
+ replay = create_shipping_batch_from_intakes(
+ user_id=shipping_user.id,
+ conversation_id='conv-dedup',
+ intake_nos=[intake1.intake_no, intake2.intake_no],
+ create_idempotency_key='idem-dedup',
+ )
+ assert replay.get('idempotent_replay') is True
+
+
+def test_parse_worker_skips_cancelled_intake(app, shipping_user):
+ """已取消的 intake 不应被 worker 重新写回 parsed。"""
+ with app.app_context():
+ import logging
+
+ from app.jobs.context import JobContext
+ from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
+
+ _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-WORKER')
+ intake.parse_status = 'cancelled'
+ db.session.commit()
+
+ ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
+ run_shipping_notice_parse(ctx, {'intake_no': intake.intake_no})
+
+ refreshed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert refreshed.parse_status == 'cancelled'
+
+
+def test_parse_worker_marks_parse_failed_when_asset_missing(app, shipping_user):
+ """资产已删除时领取后须写 parse_failed(不抛出),避免永久 parsing 且可用户重试。"""
+ with app.app_context():
+ import logging
+
+ from app.jobs.context import JobContext
+ from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.intake_service import retry_intake_parse
+
+ asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-ASSET-GONE')
+ intake.parse_status = 'queued'
+ asset.deleted_at = datetime.utcnow()
+ job = Job(
+ domain='shipping_notice',
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ business_ref=intake.intake_no,
+ payload_json={'intake_no': intake.intake_no},
+ attempts=1,
+ max_attempts=3,
+ )
+ db.session.add(job)
+ db.session.flush()
+ intake.parse_job_id = job.id
+ db.session.commit()
+
+ ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
+ run_shipping_notice_parse(ctx, {'job_id': job.id, 'intake_no': intake.intake_no})
+
+ db.session.expire_all()
+ failed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert failed is not None
+ assert failed.parse_status == 'parse_failed'
+ assert failed.error_code == 'FILE_ASSET.NOT_FOUND'
+ refreshed_job = db.session.get(Job, job.id)
+ assert refreshed_job is not None
+ assert refreshed_job.status == 'failed'
+
+ asset.deleted_at = None
+ db.session.commit()
+ with patch('app.services.shipping_notice.intake_service.enqueue', return_value=801):
+ retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-ASSET-GONE')
+ assert retried['parse_status'] == 'queued'
+
+
+def test_recover_stale_parse_job_resets_stuck_parsing_intake(app, shipping_user):
+ """超时回收预解析 Job 时须把 Intake 从 parsing 同步为 queued,且同 Job 可再领取。"""
+ with app.app_context():
+ import logging
+ from datetime import timedelta
+
+ from app.jobs.context import JobContext
+ from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
+
+ asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-STALE-PARSE')
+ intake.parse_status = 'parsing'
+ job = Job(
+ domain='shipping_notice',
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ business_ref=intake.intake_no,
+ payload_json={'intake_no': intake.intake_no},
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(hours=1),
+ locked_at=datetime.utcnow() - timedelta(hours=1),
+ locked_by='dead-worker',
+ )
+ db.session.add(job)
+ db.session.flush()
+ intake.parse_job_id = job.id
+ db.session.commit()
+
+ count, _ = recover_stale_shipping_notice_jobs()
+ assert count >= 1
+ db.session.expire_all()
+ recovered_job = db.session.get(Job, job.id)
+ recovered_intake = db.session.get(ShippingNoticeIntake, intake.id)
+ assert recovered_job is not None and recovered_job.status == 'queued'
+ assert recovered_intake is not None and recovered_intake.parse_status == 'queued'
+
+ # 再次执行:即使仍短暂为 parsing,同 parse_job_id 也应可领取(防御路径)
+ recovered_intake.parse_status = 'parsing'
+ recovered_job.status = 'running'
+ recovered_job.attempts = 2
+ db.session.commit()
+ monkey_asset = db.session.get(FileAsset, asset.id)
+ assert monkey_asset is not None
+ with patch(
+ 'app.jobs.handlers.shipping_notice_parse.run_intake_parse',
+ return_value={'status': 'parsed', 'intake_no': intake.intake_no},
+ ):
+ ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
+ run_shipping_notice_parse(
+ ctx, {'job_id': recovered_job.id, 'intake_no': intake.intake_no}
+ )
+ db.session.expire_all()
+ finished = db.session.get(Job, job.id)
+ assert finished is not None
+ assert finished.status == 'success'
+
+
+def test_recover_exhausted_parse_job_marks_intake_parse_failed_and_clears_stage2(
+ app, shipping_user,
+):
+ """预解析 Job 超时耗尽须 parse_failed,并清理上一轮 Document/Candidate。"""
+ with app.app_context():
+ from datetime import timedelta
+
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
+
+ asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-STALE-EXHAUST')
+ intake.parse_status = 'parsing'
+ intake.duplicate_status = 'soft_duplicate'
+ intake.duplicate_matches_json = [{'task_no': 'ST-X'}]
+ intake.duplicate_resolution = 'force_create'
+ doc = ShippingNoticeDocument(
+ intake_id=intake.id,
+ document_type='attachment',
+ attachment_key='a.pdf',
+ classification='order_notice',
+ parse_status='parsed',
+ content_hash='hash-stale-exhaust',
+ )
+ db.session.add(doc)
+ job = Job(
+ domain='shipping_notice',
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ business_ref=intake.intake_no,
+ payload_json={'intake_no': intake.intake_no},
+ attempts=3,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(hours=1),
+ )
+ db.session.add(job)
+ db.session.flush()
+ intake.parse_job_id = job.id
+ db.session.commit()
+
+ recover_stale_shipping_notice_jobs()
+ db.session.expire_all()
+ failed_job = db.session.get(Job, job.id)
+ failed_intake = db.session.get(ShippingNoticeIntake, intake.id)
+ assert failed_job is not None and failed_job.status == 'failed'
+ assert failed_intake is not None
+ assert failed_intake.parse_status == 'parse_failed'
+ assert failed_intake.error_code == 'SHIPPING_NOTICE.INTAKE_PARSE_TIMEOUT'
+ assert failed_intake.duplicate_status == 'unchecked'
+ assert failed_intake.duplicate_matches_json in (None, [])
+ assert failed_intake.duplicate_resolution is None
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed_intake.id).count() == 0
+
+
+def test_process_next_job_does_not_override_handler_non_retryable_fail(app, shipping_user):
+ """Handler 已以 retryable=False 收口后,process_next_job 不得再强制 requeue。"""
+ with app.app_context():
+ from app.jobs.context import JobContext
+ from app.jobs.queue import process_next_job
+ from app.jobs.types import JobType
+ from app.models import Job
+
+ asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-NO-OVERRIDE')
+ intake.parse_status = 'queued'
+ asset.deleted_at = datetime.utcnow()
+ job = Job(
+ domain='shipping_notice',
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='queued',
+ business_ref=intake.intake_no,
+ payload_json={'intake_no': intake.intake_no},
+ attempts=0,
+ max_attempts=3,
+ )
+ db.session.add(job)
+ db.session.flush()
+ intake.parse_job_id = job.id
+ db.session.commit()
+ job_id = job.id
+
+ ctx = JobContext(config=dict(app.config), logger=app.logger, extras={'queues': ['shipping']})
+ processed, job_type = process_next_job(
+ ctx=ctx,
+ domain='shipping_notice',
+ job_types=[JobType.SHIPPING_NOTICE_PARSE],
+ timeout_config_key='SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS',
+ )
+ assert processed is True
+ assert job_type == JobType.SHIPPING_NOTICE_PARSE.value
+ db.session.expire_all()
+ refreshed = db.session.get(Job, job_id)
+ assert refreshed is not None
+ assert refreshed.status == 'failed'
+ failed_intake = db.session.get(ShippingNoticeIntake, intake.id)
+ assert failed_intake is not None
+ assert failed_intake.parse_status == 'parse_failed'
+
+
+def test_run_worker_entry_does_not_recover_parse_job(app, shipping_user):
+ """RUN单步入口只能回收RUN,不得按RUN阈值触碰PARSE Job或Intake lease。"""
+ from datetime import timedelta
+
+ from app.jobs.context import JobContext
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import process_next_shipping_notice_job
+
+ with app.app_context():
+ asset, intake = _seed_parsed_intake(
+ shipping_user.id,
+ intake_no='SNI-RUN-ENTRY-PARSE-ISOLATION',
+ )
+ intake.parse_status = 'parsing'
+ parse_job = Job(
+ domain='shipping_notice',
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ business_ref=intake.intake_no,
+ payload_json={'intake_no': intake.intake_no},
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(hours=2),
+ locked_at=datetime.utcnow() - timedelta(hours=2),
+ locked_by='parse-worker',
+ )
+ db.session.add(parse_job)
+ db.session.flush()
+ parse_job_id = int(parse_job.id)
+ intake.parse_job_id = parse_job_id
+ intake.parse_lease = f'{parse_job_id}:1'
+ db.session.commit()
+
+ ctx = JobContext(config=dict(app.config), logger=app.logger, extras={'queues': ['shipping']})
+ processed, reason = process_next_shipping_notice_job(ctx)
+ assert processed is False
+ assert reason == 'no_job'
+
+ db.session.expire_all()
+ untouched_job = db.session.get(Job, parse_job_id)
+ untouched_intake = db.session.get(ShippingNoticeIntake, intake.id)
+ assert untouched_job is not None and untouched_job.status == 'running'
+ assert untouched_intake is not None and untouched_intake.parse_status == 'parsing'
+ assert untouched_intake.parse_lease == f'{parse_job_id}:1'
+
+
+def test_retryable_handler_failure_requeues_job_and_intake(app, shipping_user):
+ """Handler可重试异常即使先写parse_failed,最终也须统一回到Job/Intake queued。"""
+ import logging
+
+ from app.jobs.context import JobContext
+ from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
+ from app.jobs.types import JobType
+ from app.models import Job
+
+ with app.app_context():
+ _, intake = _seed_parsed_intake(
+ shipping_user.id,
+ intake_no='SNI-HANDLER-RETRY-SYNC',
+ )
+ intake.parse_status = 'queued'
+ job = Job(
+ domain='shipping_notice',
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ business_ref=intake.intake_no,
+ payload_json={'intake_no': intake.intake_no},
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow(),
+ )
+ db.session.add(job)
+ db.session.flush()
+ job_id = int(job.id)
+ intake.parse_job_id = job_id
+ db.session.commit()
+
+ ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
+ with patch(
+ 'app.jobs.handlers.shipping_notice_parse.run_intake_parse',
+ side_effect=RuntimeError('temporary parser outage'),
+ ):
+ with pytest.raises(RuntimeError, match='temporary parser outage'):
+ run_shipping_notice_parse(
+ ctx,
+ {'job_id': job_id, 'intake_no': intake.intake_no},
+ )
+
+ db.session.expire_all()
+ queued_job = db.session.get(Job, job_id)
+ queued_intake = db.session.get(ShippingNoticeIntake, intake.id)
+ assert queued_job is not None and queued_job.status == 'queued'
+ assert queued_job.started_at is None
+ assert queued_intake is not None and queued_intake.parse_status == 'queued'
+ assert queued_intake.parse_job_id == job_id
+ assert queued_intake.parse_lease is None
+ assert queued_intake.error_code is None
+ assert queued_intake.error_message is None
+
+
+def test_finish_job_owned_attempt_mismatch_is_noop(app, shipping_user):
+ """旧代次 finish_job 不得覆盖新 attempts 的 running Job(根治 Session 缓存误判)。"""
+ with app.app_context():
+ from app.jobs.queue import finish_job
+ from app.jobs.types import JobType
+ from app.models import Job
+
+ job = Job(
+ domain='shipping_notice',
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ business_ref='SNI-OWNED-ATTEMPT',
+ payload_json={'intake_no': 'SNI-OWNED-ATTEMPT'},
+ attempts=2,
+ max_attempts=3,
+ started_at=datetime.utcnow(),
+ )
+ db.session.add(job)
+ db.session.commit()
+ job_id = int(job.id)
+
+ # 故意不 expire:模拟 Handler Session 里仍缓存 attempts=1 的旧视图
+ assert finish_job(job_id, message='stale gen', owned_attempt=1) is False
+ db.session.expire_all()
+ still = db.session.get(Job, job_id)
+ assert still is not None
+ assert still.status == 'running'
+ assert int(still.attempts or 0) == 2
+
+ assert finish_job(job_id, message='current gen', owned_attempt=2) is True
+ db.session.expire_all()
+ done = db.session.get(Job, job_id)
+ assert done is not None
+ assert done.status == 'success'
+
+
+def test_recover_stale_jobs_does_not_demote_new_attempt(app, shipping_user):
+ """回收条件 UPDATE 绑定 attempts 快照,不能把已被新 Worker 领取的代次打回 queued。"""
+ with app.app_context():
+ from datetime import timedelta
+
+ from app.jobs.queue import recover_stale_jobs
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
+
+ job = Job(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ business_ref='SNI-RECOVER-SNAP',
+ payload_json={'intake_no': 'SNI-RECOVER-SNAP'},
+ attempts=2,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(hours=1),
+ locked_at=datetime.utcnow() - timedelta(hours=1),
+ )
+ db.session.add(job)
+ db.session.commit()
+ job_id = int(job.id)
+
+ # 模拟:陈旧回收器持有 attempts=1 的过期视图,直接条件 UPDATE 应失败
+ from sqlalchemy import update as sa_update
+
+ from app.models import Job as JobModel
+
+ now = datetime.utcnow()
+ rc = db.session.execute(
+ sa_update(JobModel)
+ .where(
+ JobModel.id == job_id,
+ JobModel.status == 'running',
+ JobModel.attempts == 1,
+ )
+ .values(status='queued', started_at=None, updated_at=now)
+ )
+ assert int(rc.rowcount or 0) == 0
+ db.session.rollback()
+
+ # 正常回收:当前 attempts=2 仍超时 → queued
+ count = recover_stale_jobs(
+ domain=SHIPPING_NOTICE_JOB_DOMAIN,
+ timeout_seconds=60,
+ job_type=JobType.SHIPPING_NOTICE_PARSE,
+ )
+ assert count == 1
+ db.session.expire_all()
+ recovered = db.session.get(Job, job_id)
+ assert recovered is not None
+ assert recovered.status == 'queued'
+ assert int(recovered.attempts or 0) == 2
+
+
+def test_stale_parse_lease_cannot_overwrite_after_recovery(app, shipping_user, monkeypatch):
+ """超时回收清空 lease 后,旧 Worker 持旧 lease 写回须 skipped,不得覆盖新租约。"""
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+ from app.services.shipping_notice.notice_upload import NoticeIntakeResult
+
+ with app.app_context():
+ asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-LEASE-STALE')
+ intake.parse_status = 'parsing'
+ intake.parse_lease = '99:1'
+ intake.parse_job_id = 99
+ db.session.commit()
+
+ # 模拟回收:清空 lease,随后新 Worker 领取 99:2
+ intake.parse_status = 'queued'
+ intake.parse_lease = None
+ db.session.commit()
+ intake.parse_status = 'parsing'
+ intake.parse_lease = '99:2'
+ db.session.commit()
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
+ lambda _asset: NoticeIntakeResult(
+ filename='notice.txt',
+ source_type='manual',
+ source_file_type='text/plain',
+ text='PO Number: LEASE001\nSKU X qty 1',
+ warnings=[],
+ meta={},
+ content_hash=str(asset.content_hash or ''),
+ file_size=12,
+ status='accepted',
+ saved_path=None,
+ ),
+ )
+ result = run_intake_parse(intake, asset, parse_lease='99:1')
+ assert result['status'] == 'skipped'
+ assert result.get('reason') == 'stale_parse_lease'
+ db.session.expire_all()
+ refreshed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert refreshed is not None
+ assert refreshed.parse_status == 'parsing'
+ assert refreshed.parse_lease == '99:2'
+
+
+def test_recover_clears_parse_lease_so_old_worker_fail_is_noop(app, shipping_user):
+ """回收为 queued 后必须清空 parse_lease;旧 lease 的失败清理不得写 parse_failed。"""
+ with app.app_context():
+ from datetime import timedelta
+
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.intake_parse_workflow import (
+ fail_intake_with_stage2_cleanup,
+ )
+ from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
+
+ asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-LEASE-RECOVER')
+ intake.parse_status = 'parsing'
+ intake.parse_lease = '55:1'
+ job = Job(
+ domain='shipping_notice',
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ business_ref=intake.intake_no,
+ payload_json={'intake_no': intake.intake_no},
+ attempts=1,
+ max_attempts=3,
+ started_at=datetime.utcnow() - timedelta(hours=1),
+ )
+ db.session.add(job)
+ db.session.flush()
+ intake.parse_job_id = job.id
+ db.session.commit()
+
+ recover_stale_shipping_notice_jobs()
+ db.session.expire_all()
+ recovered = db.session.get(ShippingNoticeIntake, intake.id)
+ assert recovered is not None
+ assert recovered.parse_status == 'queued'
+ assert recovered.parse_lease is None
+
+ stale = fail_intake_with_stage2_cleanup(
+ intake_id=int(recovered.id),
+ intake_no=recovered.intake_no,
+ parser_version='v6',
+ error_code='FILE_ASSET.NOT_FOUND',
+ error_message='stale worker',
+ extracted_text=None,
+ structured_result_json={},
+ parse_warnings_json=[],
+ required_lease='55:1',
+ )
+ assert stale['status'] == 'skipped'
+ assert stale.get('reason') == 'stale_parse_lease'
+ db.session.expire_all()
+ still = db.session.get(ShippingNoticeIntake, intake.id)
+ assert still is not None
+ assert still.parse_status == 'queued'
+
+
+def test_asset_missing_on_retry_clears_prior_stage2(app, shipping_user, monkeypatch):
+ """不完整 parsed 重试时父资产被删:须清理 Document/Candidate 与重复决策后再 parse_failed。"""
+ with app.app_context():
+ import logging
+
+ from app.jobs.context import JobContext
+ from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
+ from app.jobs.types import JobType
+ from app.models import Job
+ from app.services.shipping_notice.intake_service import serialize_intake
+
+ asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-ASSET-GONE-S2')
+ intake.parse_status = 'queued'
+ intake.duplicate_status = 'soft_duplicate'
+ intake.duplicate_matches_json = [{'task_no': 'ST-KEEP'}]
+ intake.duplicate_resolution = 'open_existing'
+ intake.duplicate_target_task_no = 'ST-KEEP'
+ intake.structured_result_json = {
+ 'document_count': 1,
+ 'candidate_count': 1,
+ 'attachments': [{'filename': 'x.pdf', 'asset_no': 'FA-X'}],
+ }
+ doc = ShippingNoticeDocument(
+ intake_id=intake.id,
+ document_type='attachment',
+ attachment_key='x.pdf',
+ classification='order_notice',
+ parse_status='parsed',
+ content_hash='hash-gone-s2',
+ )
+ db.session.add(doc)
+ job = Job(
+ domain='shipping_notice',
+ job_type=JobType.SHIPPING_NOTICE_PARSE.value,
+ status='running',
+ business_ref=intake.intake_no,
+ payload_json={'intake_no': intake.intake_no},
+ attempts=1,
+ max_attempts=3,
+ )
+ db.session.add(job)
+ db.session.flush()
+ intake.parse_job_id = job.id
+ asset.deleted_at = datetime.utcnow()
+ db.session.commit()
+
+ ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
+ run_shipping_notice_parse(ctx, {'job_id': job.id, 'intake_no': intake.intake_no})
+
+ db.session.expire_all()
+ failed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-ASSET-GONE-S2'
+ ).one()
+ assert failed.parse_status == 'parse_failed'
+ assert failed.error_code == 'FILE_ASSET.NOT_FOUND'
+ assert failed.duplicate_status == 'unchecked'
+ assert failed.duplicate_matches_json in (None, [])
+ assert failed.duplicate_resolution is None
+ assert failed.duplicate_target_task_no is None
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed.id).count() == 0
+ payload = serialize_intake(failed, asset=None)
+ assert (payload.get('duplicate') or {}).get('matches') in (None, [])
+ structured = failed.structured_result_json or {}
+ assert 'document_count' not in structured
+ assert not any(
+ isinstance(row, dict) and row.get('asset_no')
+ for row in (structured.get('attachments') or [])
+ )
+
+
+def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeypatch):
+ """抽取期间他事务取消后,即使 Session 缓存仍为 parsing,也不得覆盖为 parsed。"""
+ with app.app_context():
+ from sqlalchemy import text
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+ from app.services.shipping_notice.notice_upload import NoticeIntakeResult
+
+ asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-RACE')
+ intake.parse_status = 'parsing'
+ db.session.commit()
+
+ local = db.session.get(ShippingNoticeIntake, intake.id)
+ assert local.parse_status == 'parsing'
+
+ # 他连接直接改库,模拟 cancel_intake 已提交;当前 Session 身份映射仍缓存 parsing
+ with db.engine.begin() as conn:
+ conn.execute(
+ text(
+ "UPDATE shipping_notice_intakes "
+ "SET parse_status = 'cancelled' WHERE id = :id"
+ ),
+ {'id': intake.id},
+ )
+ assert local.parse_status == 'parsing'
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
+ lambda _asset: NoticeIntakeResult(
+ filename='notice.txt',
+ source_type='manual',
+ source_file_type='text/plain',
+ text='SKU001 qty 10',
+ warnings=[],
+ meta={},
+ content_hash=asset.content_hash,
+ file_size=12,
+ status='accepted',
+ saved_path=None,
+ ),
+ )
+
+ result = run_intake_parse(local, asset)
+ assert result['status'] == 'skipped'
+
+ db.session.expire_all()
+ refreshed = db.session.get(ShippingNoticeIntake, intake.id)
+ assert refreshed.parse_status == 'cancelled'
+
+
+def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monkeypatch):
+ """
+ FileAsset → run_intake_parse → DB:EML 附件独立文本应持久化进 structured_result_json。
+
+ 核心逻辑:mock 读取资产字节为含文本附件的 EML,断言 attachment_count 与 extracted_text 落库。
+ """
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+
+ msg = EmailMessage()
+ msg['Subject'] = 'Intake EML Persist'
+ msg['From'] = 'shipper@example.com'
+ msg['To'] = 'freight@example.com'
+ msg['Message-ID'] = ''
+ msg.set_content('Cover letter.')
+ msg.add_attachment(
+ b'PO-PERSIST-LINE-001 qty 5',
+ maintype='text',
+ subtype='plain',
+ filename='order-a.txt',
+ )
+ msg.add_attachment(
+ b'PO-PERSIST-LINE-002 qty 3',
+ maintype='text',
+ subtype='plain',
+ filename='order-b.txt',
+ )
+ eml_bytes = msg.as_bytes()
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='multi.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-EML-PERSIST-001',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ db.session.add(intake)
+ db.session.commit()
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _asset: eml_bytes,
+ )
+ # 跳过重复检测,专注结构化落库
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.duplicate_detection.refresh_candidates_and_aggregate_intake',
+ lambda **kwargs: {'status': 'none', 'fingerprint_strength': None},
+ )
+
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ result = run_intake_parse(intake, asset)
+ assert result['status'] == 'parsed'
+
+ db.session.expire_all()
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-EML-PERSIST-001'
+ ).one()
+ structured = refreshed.structured_result_json or {}
+ assert structured.get('attachment_count') == 2
+ assert structured.get('email', {}).get('subject') == 'Intake EML Persist'
+ attachments = structured.get('attachments') or []
+ assert len(attachments) == 2
+ texts = {row['filename']: row.get('extracted_text') for row in attachments}
+ assert 'PO-PERSIST-LINE-001' in str(texts.get('order-a.txt') or '')
+ assert 'PO-PERSIST-LINE-002' in str(texts.get('order-b.txt') or '')
+ assert 'PO-PERSIST-LINE-001' in str(refreshed.extracted_text or '')
+ expected_parser = str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6')
+ assert refreshed.parser_version == expected_parser
+ assert all('_payload_bytes' not in row for row in attachments)
+ assert all(row.get('asset_no') for row in attachments)
+
+ from app.services.shipping_notice.intake_service import serialize_intake
+
+ lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False)
+ lean_atts = (lean.get('parse_summary') or {}).get('attachments') or []
+ assert lean_atts and 'extracted_text' not in lean_atts[0]
+ assert 'body_text' not in ((lean.get('parse_summary') or {}).get('email') or {})
+
+ full = serialize_intake(refreshed, asset=asset, include_parse_texts=True)
+ full_atts = (full.get('parse_summary') or {}).get('attachments') or []
+ assert 'PO-PERSIST-LINE-001' in str(full_atts[0].get('extracted_text') or '')
+
+
+def test_run_intake_parse_persists_attached_multipart_and_detail_api(
+ app, client, shipping_user, monkeypatch,
+):
+ """
+ FileAsset → run_intake_parse → DB → 详情接口:附件型 multipart 独立文本与超深深 skipped 须落库返回。
+
+ 核心逻辑:mixed 容器内 plain+html 均持久化;嵌套容器超限为 skipped 并带 depth warning;
+ status 瘦身、详情含全文。
+ """
+ from email.mime.multipart import MIMEMultipart
+ from email.mime.text import MIMEText
+
+ from app.core.auth.jwt import issue_local_access_token
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+ from app.services.shipping_notice.intake_service import serialize_intake
+
+ inner = MIMEMultipart('mixed')
+ inner.add_header('Content-Disposition', 'attachment', filename='inner-depth.mime')
+ inner.attach(MIMEText('INNER-DEPTH-PO-999', 'plain', 'utf-8'))
+
+ bundle = MIMEMultipart('mixed')
+ bundle.add_header('Content-Disposition', 'attachment', filename='bundle-persist.mime')
+ bundle.attach(MIMEText('PLAIN-PO-101 please ship', 'plain', 'utf-8'))
+ bundle.attach(MIMEText('HTML-PO-202 please ship
', 'html', 'utf-8'))
+ bundle.attach(inner)
+
+ root = MIMEMultipart('mixed')
+ root['Subject'] = 'Intake multipart persist'
+ root['From'] = 'shipper@example.com'
+ root['To'] = 'freight@example.com'
+ root['Message-ID'] = ''
+ root.attach(MIMEText('Outer cover.', 'plain', 'utf-8'))
+ root.attach(bundle)
+ eml_bytes = root.as_bytes()
+
+ with app.app_context():
+ app.config['SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH'] = 1
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='multipart-persist.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-EML-MP-PERSIST-001',
+ asset_id=asset.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
+ )
+ db.session.add(intake)
+ db.session.commit()
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _asset: eml_bytes,
+ )
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.duplicate_detection.refresh_candidates_and_aggregate_intake',
+ lambda **kwargs: {'status': 'none', 'fingerprint_strength': None},
+ )
+
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ result = run_intake_parse(intake, asset)
+ assert result['status'] == 'parsed'
+
+ db.session.expire_all()
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-EML-MP-PERSIST-001'
+ ).one()
+ structured = refreshed.structured_result_json or {}
+ by_name = {
+ str(row.get('filename') or ''): row
+ for row in (structured.get('attachments') or [])
+ }
+ assert 'bundle-persist.mime' in by_name
+ assert 'inner-depth.mime' in by_name
+ bundle_text = str(by_name['bundle-persist.mime'].get('extracted_text') or '')
+ assert 'PLAIN-PO-101' in bundle_text
+ assert 'HTML-PO-202' in bundle_text
+ assert by_name['bundle-persist.mime'].get('parse_status') == 'parsed'
+ assert by_name['inner-depth.mime'].get('parse_status') == 'skipped'
+ warnings = list(structured.get('warnings') or []) + list(
+ by_name['inner-depth.mime'].get('warnings') or []
+ )
+ assert any(str(w).startswith('eml_nesting_depth_exceeded:') for w in warnings)
+ assert 'PLAIN-PO-101' in str(refreshed.extracted_text or '')
+ assert 'HTML-PO-202' in str(refreshed.extracted_text or '')
+
+ lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False)
+ lean_bundle = next(
+ row
+ for row in ((lean.get('parse_summary') or {}).get('attachments') or [])
+ if row.get('filename') == 'bundle-persist.mime'
+ )
+ assert 'extracted_text' not in lean_bundle
+
+ full = serialize_intake(refreshed, asset=asset, include_parse_texts=True)
+ full_bundle = next(
+ row
+ for row in ((full.get('parse_summary') or {}).get('attachments') or [])
+ if row.get('filename') == 'bundle-persist.mime'
+ )
+ assert 'PLAIN-PO-101' in str(full_bundle.get('extracted_text') or '')
+ assert 'HTML-PO-202' in str(full_bundle.get('extracted_text') or '')
+
+ headers = {'Authorization': f'Bearer {issue_local_access_token(shipping_user)}'}
+
+ status_res = client.post(
+ '/api/workspace/shipping-notice/intakes/status',
+ json={'intake_nos': ['SNI-EML-MP-PERSIST-001']},
+ headers=headers,
+ )
+ assert status_res.status_code == 200
+ status_item = status_res.get_json()['data']['items'][0]
+ status_atts = (status_item.get('parse_summary') or {}).get('attachments') or []
+ status_bundle = next(row for row in status_atts if row.get('filename') == 'bundle-persist.mime')
+ assert 'extracted_text' not in status_bundle
+ status_inner = next(row for row in status_atts if row.get('filename') == 'inner-depth.mime')
+ assert status_inner.get('parse_status') == 'skipped'
+
+ detail_res = client.get(
+ '/api/workspace/shipping-notice/intakes/SNI-EML-MP-PERSIST-001',
+ headers=headers,
+ )
+ assert detail_res.status_code == 200
+ detail_atts = (detail_res.get_json()['data'].get('parse_summary') or {}).get('attachments') or []
+ detail_bundle = next(row for row in detail_atts if row.get('filename') == 'bundle-persist.mime')
+ assert 'PLAIN-PO-101' in str(detail_bundle.get('extracted_text') or '')
+ assert 'HTML-PO-202' in str(detail_bundle.get('extracted_text') or '')
+ detail_inner = next(row for row in detail_atts if row.get('filename') == 'inner-depth.mime')
+ assert detail_inner.get('parse_status') == 'skipped'
+
+
+def test_intake_status_api_strips_texts_detail_returns_full(app, client):
+ """
+ Flask 路由:POST /intakes/status 不返回附件全文;GET 详情返回全文;越权 404。
+ """
+ from datetime import datetime, timedelta
+
+ from app.core.auth.jwt import issue_local_access_token
+ from app.models import FileAsset, ShippingNoticeIntake, User
+
+ with app.app_context():
+ owner = User(username='intake-api-owner', email='intake-api-owner@example.com', password_hash='x')
+ other = User(username='intake-api-other', email='intake-api-other@example.com', password_hash='x')
+ db.session.add_all([owner, other])
+ db.session.commit()
+ owner_id = owner.id
+ other_id = other.id
+ owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
+ other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
+
+ asset = FileAsset(
+ asset_no='FA-EML-API-001',
+ owner_user_id=owner_id,
+ original_filename='multi.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{owner_id}/test/multi.eml',
+ content_hash='hash-eml-api-001',
+ file_size=12,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ )
+ db.session.add(asset)
+ db.session.flush()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-EML-API-001',
+ asset_id=asset.id,
+ user_id=owner_id,
+ purpose='shipping_notice',
+ parse_status='parsed',
+ parser_version='v2',
+ extracted_text='flat body',
+ structured_result_json={
+ 'email': {
+ 'subject': 'API EML',
+ 'body_text': 'SECRET-BODY-TEXT',
+ 'body_text_length': 16,
+ 'stored_body_text_length': 16,
+ },
+ 'attachment_count': 1,
+ 'attachment_registered_count': 1,
+ 'attachments': [
+ {
+ 'attachment_key': 'att-001',
+ 'filename': 'order.txt',
+ 'parse_status': 'parsed',
+ 'extracted_text': 'SECRET-ATTACHMENT-TEXT',
+ 'text_length': 22,
+ 'stored_text_length': 22,
+ }
+ ],
+ 'warnings': [],
+ },
+ expires_at=datetime.utcnow() + timedelta(hours=24),
+ )
+ db.session.add(intake)
+ db.session.commit()
+
+ status_res = client.post(
+ '/api/workspace/shipping-notice/intakes/status',
+ json={'intake_nos': ['SNI-EML-API-001']},
+ headers=owner_headers,
+ )
+ assert status_res.status_code == 200
+ status_payload = status_res.get_json()
+ assert status_payload['success'] is True
+ item = status_payload['data']['items'][0]
+ summary = item['parse_summary']
+ assert 'extracted_text' not in (summary.get('attachments') or [{}])[0]
+ assert 'body_text' not in (summary.get('email') or {})
+
+ detail_res = client.get(
+ '/api/workspace/shipping-notice/intakes/SNI-EML-API-001',
+ headers=owner_headers,
+ )
+ assert detail_res.status_code == 200
+ detail = detail_res.get_json()['data']
+ detail_summary = detail['parse_summary']
+ assert detail_summary['email']['body_text'] == 'SECRET-BODY-TEXT'
+ assert detail_summary['attachments'][0]['extracted_text'] == 'SECRET-ATTACHMENT-TEXT'
+
+ forbidden = client.get(
+ '/api/workspace/shipping-notice/intakes/SNI-EML-API-001',
+ headers=other_headers,
+ )
+ assert forbidden.status_code in {403, 404}
+ assert forbidden.get_json().get('success') is False
+ # 避免未使用变量告警
+ assert other_id != owner_id
+
+
+def test_ensure_default_file_asset_cleanup_schedule(app, shipping_user):
+ """有用户时可幂等补建默认 TTL 清理排程。"""
+ with app.app_context():
+ from app.models import ScheduleTask
+ from app.services.file_assets.cleanup_schedule import (
+ DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO,
+ ensure_default_file_asset_cleanup_schedule,
+ )
+
+ first = ensure_default_file_asset_cleanup_schedule()
+ assert first is not None
+ assert first.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO
+ assert first.platform_api_path == 'file-asset-cleanup'
+ assert first.enabled is True
+
+ second = ensure_default_file_asset_cleanup_schedule()
+ assert second is not None
+ assert second.id == first.id
+ count = (
+ db.session.query(ScheduleTask)
+ .filter(ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
+ .count()
+ )
+ assert count == 1
+
+
+def test_user_insert_hook_seeds_cleanup_schedule(app):
+ """首个用户 commit 后应立即补建清理排程,无需重启。"""
+ with app.app_context():
+ from app.models import ScheduleTask, User
+ from app.services.file_assets.cleanup_schedule import (
+ DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO,
+ register_file_asset_cleanup_schedule_hooks,
+ )
+
+ register_file_asset_cleanup_schedule_hooks()
+ # 确保环境干净
+ db.session.query(ScheduleTask).filter(
+ ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO
+ ).delete()
+ db.session.commit()
+
+ user = User(username='seed-hook-user', email='seed-hook@example.com', password_hash='x')
+ db.session.add(user)
+ db.session.commit()
+
+ task = (
+ db.session.query(ScheduleTask)
+ .filter_by(schedule_no=DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
+ .first()
+ )
+ assert task is not None
+ assert task.platform_api_path == 'file-asset-cleanup'
+ assert task.enabled is True
+ assert task.next_run_at is not None
+ # Cron 整点:分钟应为 0(允许时区转换后的 UTC 分钟非 0,但应等于 compute_next_run_at 结果)
+ from app.services.schedule.timezone_util import compute_next_run_at
+
+ expected = compute_next_run_at('0 * * * *', timezone_name='Asia/Shanghai')
+ assert expected is not None
+ # 钩子执行时刻与断言时刻可能跨整点边界,允许在同一小时窗口内
+ assert abs((task.next_run_at - expected).total_seconds()) < 3700
+
+
+def _minimal_pdf_bytes(marker: str) -> bytes:
+ """构造含可见文本的最小 PDF(与 extract 测试口径一致)。"""
+ safe = str(marker).replace('\\', '\\\\').replace('(', '\\(').replace(')', '\\)')
+ stream = f'BT /F1 24 Tf 72 720 Td ({safe}) Tj ET'.encode('latin-1')
+ objects = [
+ b'1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n',
+ b'2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj\n',
+ (
+ b'3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] '
+ b'/Contents 4 0 R /Resources<< /Font<< /F1 5 0 R >> >> >>endobj\n'
+ ),
+ f'4 0 obj<< /Length {len(stream)} >>stream\n'.encode('latin-1')
+ + stream
+ + b'\nendstream\nendobj\n',
+ b'5 0 obj<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>endobj\n',
+ ]
+ out = bytearray(b'%PDF-1.4\n')
+ offsets = [0]
+ for obj in objects:
+ offsets.append(len(out))
+ out.extend(obj)
+ xref_pos = len(out)
+ out.extend(f'xref\n0 {len(offsets)}\n'.encode('latin-1'))
+ out.extend(b'0000000000 65535 f \n')
+ for off in offsets[1:]:
+ out.extend(f'{off:010d} 00000 n \n'.encode('latin-1'))
+ out.extend(
+ f'trailer<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n'.encode(
+ 'latin-1'
+ )
+ )
+ return bytes(out)
+
+
+def test_run_intake_parse_three_pdfs_creates_documents_candidates_and_assets(
+ app, shipping_user, monkeypatch,
+):
+ """
+ 阶段二验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document + 3 Candidate;
+ 正文订单表不额外生成第 4 候选;各 PDF 独立 FileAsset;重试不膨胀。
+ """
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+ from app.services.shipping_notice.intake_service import serialize_intake
+
+ markers = ('4510039227', '4510039228', '4510039229')
+ msg = EmailMessage()
+ msg['Subject'] = 'PO 4510039227, 4510039228, 4510039229'
+ msg['From'] = 'laszlo.fussy@example.com'
+ msg['To'] = 'freight@example.com'
+ msg['Message-ID'] = ''
+ msg.set_content(
+ 'Please find POs attached.\n'
+ 'PO Number: 4510039227 qty 10\n'
+ 'PO Number: 4510039228 qty 20\n'
+ 'PO Number: 4510039229 qty 30\n'
+ )
+ for po in markers:
+ msg.add_attachment(
+ _minimal_pdf_bytes(f'PO Number: {po} SKU-A qty 1'),
+ maintype='application',
+ subtype='pdf',
+ filename=f'{po}.pdf',
+ )
+ eml_bytes = msg.as_bytes()
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='three-po.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-STAGE2-3PDF',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ db.session.commit()
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _asset: eml_bytes,
+ )
+
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ first = run_intake_parse(intake, parent)
+ assert first['status'] == 'parsed'
+ db.session.expire_all()
+ refreshed_intake = (
+ db.session.query(ShippingNoticeIntake)
+ .filter_by(intake_no='SNI-STAGE2-3PDF')
+ .one()
+ )
+ persist_warns = [
+ str(w)
+ for w in (refreshed_intake.parse_warnings_json or [])
+ if str(w).startswith('document_candidate_persist_failed')
+ ]
+ assert not persist_warns, persist_warns
+ assert first.get('document_count') == 4, first
+ docs = (
+ db.session.query(ShippingNoticeDocument)
+ .filter_by(intake_id=refreshed_intake.id)
+ .order_by(ShippingNoticeDocument.id.asc())
+ .all()
+ )
+ cands = (
+ db.session.query(ShippingNoticeCandidate)
+ .filter_by(intake_id=refreshed_intake.id)
+ .order_by(ShippingNoticeCandidate.id.asc())
+ .all()
+ )
+ children = (
+ db.session.query(FileAsset)
+ .filter(
+ FileAsset.parent_asset_id == parent.id,
+ FileAsset.deleted_at.is_(None),
+ )
+ .all()
+ )
+
+ assert len(docs) == 4, (first, refreshed_intake.parse_warnings_json)
+ body_docs = [d for d in docs if d.document_type == 'email_body']
+ assert len(body_docs) == 1
+ assert body_docs[0].classification == 'email_context'
+ pdf_docs = [d for d in docs if d.document_type == 'attachment']
+ assert len(pdf_docs) == 3
+ assert all(d.classification == 'order_notice' for d in pdf_docs)
+ assert all(d.asset_id for d in pdf_docs)
+ assert len(cands) == 3
+ assert all(c.primary_document_id != body_docs[0].id for c in cands)
+ assert len(children) == 3
+ assert len({c.content_hash for c in children}) == 3
+
+ detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True)
+ assert detail['document_count'] == 4
+ assert detail['candidate_count'] == 3
+
+ intake2 = (
+ db.session.query(ShippingNoticeIntake)
+ .filter_by(intake_no='SNI-STAGE2-3PDF')
+ .one()
+ )
+ intake2.parse_status = 'parsing'
+ db.session.commit()
+ second = run_intake_parse(intake2, parent)
+ assert second['status'] == 'parsed'
+ db.session.expire_all()
+ intake_id = (
+ db.session.query(ShippingNoticeIntake)
+ .filter_by(intake_no='SNI-STAGE2-3PDF')
+ .one()
+ .id
+ )
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4
+ assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 3
+ assert (
+ db.session.query(FileAsset)
+ .filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
+ .count()
+ == 3
+ )
+
+
+def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate(
+ app, shipping_user, monkeypatch,
+):
+ """无 PO/行项目的 PDF 仅落 Document(supporting),不伪造 Candidate。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+
+ msg = EmailMessage()
+ msg['Subject'] = 'Packing list only'
+ msg['From'] = 'a@b.com'
+ msg['To'] = 'c@d.com'
+ msg.set_content('See packing list.')
+ msg.add_attachment(
+ _minimal_pdf_bytes('This is packing list page 1'),
+ maintype='application',
+ subtype='pdf',
+ filename='packing.pdf',
+ )
+ eml_bytes = msg.as_bytes()
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='packing.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-STAGE2-SUPPORT',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ db.session.commit()
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _a: eml_bytes,
+ )
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ result = run_intake_parse(intake, parent)
+ assert result['status'] == 'parsed'
+ att = (
+ db.session.query(ShippingNoticeDocument)
+ .filter_by(intake_id=intake.id, document_type='attachment')
+ .one()
+ )
+ assert att.classification == 'supporting'
+ assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake.id).count() == 0
+
+
+def test_stage2_persist_failure_marks_parse_failed_and_allows_retry(
+ app, shipping_user, monkeypatch,
+):
+ """阶段二持久化失败须 parse_failed,且可 retry_intake_parse。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+ from app.services.shipping_notice.intake_service import retry_intake_parse
+
+ msg = EmailMessage()
+ msg['Subject'] = 'fail stage2'
+ msg['From'] = 'a@b.com'
+ msg['To'] = 'c@d.com'
+ msg.set_content('body')
+ msg.add_attachment(
+ _minimal_pdf_bytes('PO Number: 999001'),
+ maintype='application',
+ subtype='pdf',
+ filename='one.pdf',
+ )
+ eml_bytes = msg.as_bytes()
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='fail.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-STAGE2-FAIL',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ db.session.commit()
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _a: eml_bytes,
+ )
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
+ lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-stage2')),
+ )
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ result = run_intake_parse(intake, parent)
+ assert result['status'] == 'parse_failed'
+ db.session.expire_all()
+ failed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-FAIL').one()
+ assert failed.parse_status == 'parse_failed'
+ assert failed.error_code == 'SHIPPING_NOTICE.INTAKE_STAGE2_PERSIST_FAILED'
+
+ with patch('app.services.shipping_notice.intake_service.enqueue', return_value=777):
+ retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-STAGE2-FAIL')
+ assert retried['parse_status'] == 'queued'
+
+
+def test_candidate_dedup_savepoint_failure_keeps_stage2_and_unchecked(
+ app, shipping_user, monkeypatch,
+):
+ """Candidate 重复检测异常仅 SAVEPOINT 回滚:Document/Candidate 保留,去重为 unchecked。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+
+ msg = EmailMessage()
+ msg['Subject'] = 'dedup savepoint'
+ msg['From'] = 'a@b.com'
+ msg['To'] = 'c@d.com'
+ msg.set_content('body')
+ msg.add_attachment(
+ _minimal_pdf_bytes('PO Number: DEDUPSP001\nSKU: X qty 1'),
+ maintype='application',
+ subtype='pdf',
+ filename='order.pdf',
+ )
+ eml_bytes = msg.as_bytes()
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='dedup-sp.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-DEDUP-SAVEPOINT',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ db.session.commit()
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _a: eml_bytes,
+ )
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.duplicate_detection.refresh_candidates_and_aggregate_intake',
+ lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-candidate-dedup')),
+ )
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ result = run_intake_parse(intake, parent)
+ assert result['status'] == 'parsed'
+ assert result.get('duplicate_status') == 'unchecked'
+ db.session.expire_all()
+ refreshed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-DEDUP-SAVEPOINT'
+ ).one()
+ assert refreshed.parse_status == 'parsed'
+ assert refreshed.duplicate_status == 'unchecked'
+ assert refreshed.duplicate_matches_json in (None, [])
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=refreshed.id).count() >= 1
+ assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=refreshed.id).count() >= 1
+
+
+def test_stage2_fail_cleanup_clears_prior_duplicate_resolution(
+ app, shipping_user, monkeypatch,
+):
+ """阶段二失败清理须清空上一轮 matches/指纹/决策,不只改 duplicate_status。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+ from app.services.shipping_notice.intake_service import serialize_intake
+
+ msg = EmailMessage()
+ msg['Subject'] = 'fail clear dup'
+ msg['From'] = 'a@b.com'
+ msg['To'] = 'c@d.com'
+ msg.set_content('body')
+ msg.add_attachment(
+ _minimal_pdf_bytes('PO Number: FAILCLEARDUP1\nSKU: X qty 1'),
+ maintype='application',
+ subtype='pdf',
+ filename='one.pdf',
+ )
+ eml_bytes = msg.as_bytes()
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='fail-clear-dup.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-STAGE2-CLEAR-DUP',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsed',
+ parser_version='v6',
+ duplicate_status='soft_duplicate',
+ duplicate_matches_json=[{'task_no': 'ST-OLD', 'match_type': 'po_number'}],
+ business_fingerprint='fp-old',
+ fingerprint_version='shipping-v1',
+ fingerprint_strength='strong',
+ duplicate_resolution='force_create',
+ duplicate_resolution_reason='prev',
+ duplicate_target_task_no='ST-OLD',
+ duplicate_resolved_at=datetime.utcnow(),
+ )
+ db.session.add(intake)
+ db.session.commit()
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _a: eml_bytes,
+ )
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
+ lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-clear-dup')),
+ )
+ intake.parse_status = 'parsing'
+ db.session.commit()
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ result = run_intake_parse(intake, parent)
+ assert result['status'] == 'parse_failed'
+ db.session.expire_all()
+ failed = db.session.query(ShippingNoticeIntake).filter_by(
+ intake_no='SNI-STAGE2-CLEAR-DUP'
+ ).one()
+ assert failed.parse_status == 'parse_failed'
+ assert failed.duplicate_status == 'unchecked'
+ assert failed.duplicate_matches_json in (None, [])
+ assert failed.business_fingerprint is None
+ assert failed.fingerprint_version is None
+ assert failed.fingerprint_strength is None
+ assert failed.duplicate_resolution is None
+ assert failed.duplicate_resolution_reason is None
+ assert failed.duplicate_target_task_no is None
+ assert failed.duplicate_resolved_at is None
+ payload = serialize_intake(failed, asset=parent)
+ dup = payload.get('duplicate') or {}
+ assert (dup.get('matches') or []) == []
+ assert payload.get('duplicate_resolution') is None
+
+
+def test_derived_asset_refcount_increments_per_document_link(app, shipping_user):
+ """多个 Document 指向同一派生资产时,引用计数按关联边累加/释放。"""
+ from app.services.shipping_notice.document_candidate_persist import _upsert_document
+
+ with app.app_context():
+ parents = []
+ for suffix in ('A', 'B'):
+ parent = FileAsset(
+ asset_no=f'FA-REF-PARENT-{suffix}',
+ owner_user_id=shipping_user.id,
+ original_filename=f'root-{suffix}.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/ref/parent-{suffix}.eml',
+ content_hash=f'parenthash-{suffix}',
+ file_size=10,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ asset_role='upload',
+ )
+ db.session.add(parent)
+ parents.append(parent)
+ db.session.flush()
+ child = FileAsset(
+ asset_no='FA-REF-CHILD',
+ owner_user_id=shipping_user.id,
+ parent_asset_id=parents[0].id,
+ asset_role='derived_attachment',
+ source_attachment_key='att-a',
+ original_filename='a.pdf',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/ref/a.pdf',
+ content_hash='samehash',
+ file_size=20,
+ mime_type='application/pdf',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ )
+ db.session.add(child)
+ db.session.flush()
+ intakes = []
+ for idx, suffix in enumerate(('A', 'B')):
+ intake = ShippingNoticeIntake(
+ intake_no=f'SNI-REF-{suffix}',
+ asset_id=parents[idx].id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsed',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ intakes.append(intake)
+ db.session.commit()
+
+ _upsert_document(
+ intake=intakes[0],
+ attachment_key='att-a',
+ document_type='attachment',
+ filename='a.pdf',
+ content_hash='samehash',
+ parse_status='parsed',
+ extracted_text='PO Number: 1',
+ warnings=[],
+ asset_id=int(child.id),
+ classification='order_notice',
+ )
+ _upsert_document(
+ intake=intakes[1],
+ attachment_key='att-a',
+ document_type='attachment',
+ filename='a.pdf',
+ content_hash='samehash',
+ parse_status='parsed',
+ extracted_text='PO Number: 1',
+ warnings=[],
+ asset_id=int(child.id),
+ classification='order_notice',
+ )
+ db.session.commit()
+ db.session.refresh(child)
+ assert int(child.reference_count or 0) == 2
+ assert child.lifecycle_status == 'referenced'
+
+ _upsert_document(
+ intake=intakes[0],
+ attachment_key='att-a',
+ document_type='attachment',
+ filename='a.pdf',
+ content_hash='samehash',
+ parse_status='parsed',
+ extracted_text='PO Number: 1',
+ warnings=[],
+ asset_id=None,
+ classification='supporting',
+ )
+ db.session.commit()
+ db.session.refresh(child)
+ assert int(child.reference_count or 0) == 1
+ assert child.lifecycle_status == 'referenced'
+
+
+def test_soft_deleted_derived_asset_can_be_revived(app, shipping_user):
+ """软删除派生资产后同哈希应可复活,不被全量唯一约束永久挡死。"""
+ from datetime import datetime
+
+ from app.services.file_assets.service import create_derived_file_asset_from_bytes
+
+ with app.app_context():
+ parent = FileAsset(
+ asset_no='FA-REVIVE-PARENT',
+ owner_user_id=shipping_user.id,
+ original_filename='root.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/revive/parent.eml',
+ content_hash='revive-parent',
+ file_size=10,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ asset_role='upload',
+ )
+ db.session.add(parent)
+ db.session.flush()
+ payload = b'%PDF-1.4 revive-payload'
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ child, created = create_derived_file_asset_from_bytes(
+ user_id=shipping_user.id,
+ parent=parent,
+ data=payload,
+ filename='revive.pdf',
+ mime_type='application/pdf',
+ source_attachment_key='att-1',
+ )
+ assert created is True
+ child.deleted_at = datetime.utcnow()
+ child.lifecycle_status = 'expired'
+ child.reference_count = 0
+ db.session.commit()
+ revived, created_again = create_derived_file_asset_from_bytes(
+ user_id=shipping_user.id,
+ parent=parent,
+ data=payload,
+ filename='revive.pdf',
+ mime_type='application/pdf',
+ source_attachment_key='att-1',
+ )
+ assert created_again is False
+ assert revived.id == child.id
+ assert revived.deleted_at is None
+ assert revived.upload_status == 'ready'
+
+
+def test_reuse_derived_asset_keeps_first_source_attachment_key(app, shipping_user):
+ """同哈希复用时 source_attachment_key 保持首次来源键,不被后续 att-key 覆盖。"""
+ from app.services.file_assets.service import create_derived_file_asset_from_bytes
+
+ with app.app_context():
+ parent = FileAsset(
+ asset_no='FA-KEY-PARENT',
+ owner_user_id=shipping_user.id,
+ original_filename='root.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/key/parent.eml',
+ content_hash='key-parent',
+ file_size=10,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ asset_role='upload',
+ )
+ db.session.add(parent)
+ db.session.commit()
+ payload = b'%PDF-1.4 shared-key-payload'
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ first, created = create_derived_file_asset_from_bytes(
+ user_id=shipping_user.id,
+ parent=parent,
+ data=payload,
+ filename='shared.pdf',
+ mime_type='application/pdf',
+ source_attachment_key='att-001',
+ )
+ assert created is True
+ second, created_again = create_derived_file_asset_from_bytes(
+ user_id=shipping_user.id,
+ parent=parent,
+ data=payload,
+ filename='shared.pdf',
+ mime_type='application/pdf',
+ source_attachment_key='att-009',
+ )
+ assert created_again is False
+ assert second.id == first.id
+ assert second.source_attachment_key == 'att-001'
+
+
+def test_compensate_orphan_persist_failure_rollbacks_caller_session(app, shipping_user):
+ """orphan 台账写入失败后须 rollback,调用方 Session 不应卡在 failed。"""
+ from app.services.file_assets.service import compensate_uploaded_storage_keys
+
+ with app.app_context():
+ with patch(
+ 'app.services.file_assets.service.file_asset_storage.delete_object',
+ side_effect=RuntimeError('minio down'),
+ ), patch(
+ 'app.services.file_assets.service._persist_orphan_storage_key_for_cleanup',
+ side_effect=RuntimeError('orphan write failed'),
+ ):
+ compensate_uploaded_storage_keys(
+ ['temporary/orphan-fail-session.bin'],
+ owner_user_id=shipping_user.id,
+ )
+ # Session 已恢复:可正常查询,不会 PendingRollbackError
+ assert db.session.query(FileAsset).count() >= 0
+
+
+def test_mark_and_release_asset_reference_are_atomic(app, shipping_user):
+ """引用计数须走原子 UPDATE,并发读改写不能丢增减。"""
+ from app.services.file_assets.service import mark_asset_referenced, release_asset_reference
+
+ with app.app_context():
+ asset = FileAsset(
+ asset_no='FA-ATOMIC-REF',
+ owner_user_id=shipping_user.id,
+ parent_asset_id=None,
+ asset_role='derived_attachment',
+ original_filename='a.pdf',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/atomic/a.pdf',
+ content_hash='atomic-hash',
+ file_size=10,
+ mime_type='application/pdf',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ )
+ db.session.add(asset)
+ db.session.commit()
+
+ mark_asset_referenced(asset)
+ mark_asset_referenced(asset)
+ db.session.commit()
+ db.session.refresh(asset)
+ assert int(asset.reference_count or 0) == 2
+ assert asset.lifecycle_status == 'referenced'
+
+ release_asset_reference(asset)
+ db.session.commit()
+ db.session.refresh(asset)
+ assert int(asset.reference_count or 0) == 1
+ assert asset.lifecycle_status == 'referenced'
+
+ release_asset_reference(asset)
+ db.session.commit()
+ db.session.refresh(asset)
+ assert int(asset.reference_count or 0) == 0
+ assert asset.lifecycle_status == 'temporary'
+
+
+def test_cancel_intake_is_idempotent_and_clears_stage2_projection(app, shipping_user):
+ """二次取消不得再释放引用;并清理 parse_summary 阶段二投影。"""
+ from app.services.file_assets.service import mark_asset_referenced
+ from app.services.shipping_notice.intake_service import cancel_intake
+
+ with app.app_context():
+ parent = FileAsset(
+ asset_no='FA-CANCEL-IDEMP-PARENT',
+ owner_user_id=shipping_user.id,
+ original_filename='c.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/cancel-idemp/parent.eml',
+ content_hash='cancel-idemp-parent',
+ file_size=10,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ asset_role='upload',
+ )
+ db.session.add(parent)
+ db.session.flush()
+ child = FileAsset(
+ asset_no='FA-CANCEL-IDEMP-CHILD',
+ owner_user_id=shipping_user.id,
+ parent_asset_id=parent.id,
+ asset_role='derived_attachment',
+ original_filename='c.pdf',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/cancel-idemp/c.pdf',
+ content_hash='cancel-idemp-child',
+ file_size=20,
+ mime_type='application/pdf',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ )
+ db.session.add(child)
+ db.session.flush()
+ mark_asset_referenced(child)
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-CANCEL-IDEMP',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsed',
+ parser_version='v6',
+ structured_result_json={
+ 'document_count': 2,
+ 'candidate_count': 1,
+ 'attachments': [
+ {
+ 'attachment_key': 'att-001',
+ 'filename': 'c.pdf',
+ 'asset_no': child.asset_no,
+ 'document_id': 99,
+ }
+ ],
+ },
+ )
+ db.session.add(intake)
+ db.session.flush()
+ doc = ShippingNoticeDocument(
+ intake_id=intake.id,
+ attachment_key='att-001',
+ document_type='attachment',
+ filename='c.pdf',
+ asset_id=child.id,
+ classification='order_notice',
+ parse_status='parsed',
+ )
+ db.session.add(doc)
+ db.session.commit()
+
+ cancel_intake(user_id=shipping_user.id, intake_no='SNI-CANCEL-IDEMP')
+ cancel_intake(user_id=shipping_user.id, intake_no='SNI-CANCEL-IDEMP')
+ db.session.expire_all()
+ child2 = db.session.get(FileAsset, child.id)
+ intake2 = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-CANCEL-IDEMP').one()
+ assert int(child2.reference_count or 0) == 0
+ assert intake2.parse_status == 'cancelled'
+ summary = intake2.structured_result_json or {}
+ assert 'document_count' not in summary
+ assert 'candidate_count' not in summary
+ att0 = (summary.get('attachments') or [{}])[0]
+ assert 'asset_no' not in att0
+ assert 'document_id' not in att0
+
+
+def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeypatch):
+ """文本抽取失败写 parse_failed 时须清理上一轮 Document/Candidate。"""
+ from app.services.file_assets.service import mark_asset_referenced
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+ from app.services.shipping_notice.notice_upload import NoticeIntakeResult
+
+ with app.app_context():
+ parent = FileAsset(
+ asset_no='FA-EXTRACT-CLEAR',
+ owner_user_id=shipping_user.id,
+ original_filename='clear.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/extract-clear.eml',
+ content_hash='extract-clear',
+ file_size=10,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ asset_role='upload',
+ )
+ db.session.add(parent)
+ db.session.flush()
+ child = FileAsset(
+ asset_no='FA-EXTRACT-CLEAR-CHILD',
+ owner_user_id=shipping_user.id,
+ parent_asset_id=parent.id,
+ asset_role='derived_attachment',
+ original_filename='old.pdf',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/extract-clear/old.pdf',
+ content_hash='extract-clear-child',
+ file_size=20,
+ mime_type='application/pdf',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ )
+ db.session.add(child)
+ db.session.flush()
+ mark_asset_referenced(child)
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-EXTRACT-CLEAR',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version='v6',
+ structured_result_json={
+ 'document_count': 1,
+ 'candidate_count': 1,
+ 'attachments': [{'attachment_key': 'att-001', 'document_id': 1, 'asset_no': child.asset_no}],
+ },
+ )
+ db.session.add(intake)
+ db.session.flush()
+ doc = ShippingNoticeDocument(
+ intake_id=intake.id,
+ attachment_key='att-001',
+ document_type='attachment',
+ filename='old.pdf',
+ asset_id=child.id,
+ classification='order_notice',
+ parse_status='parsed',
+ )
+ db.session.add(doc)
+ db.session.commit()
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
+ lambda _a: NoticeIntakeResult(
+ filename='clear.eml',
+ source_type='email',
+ source_file_type='message/rfc822',
+ text='',
+ warnings=['extract exploded'],
+ meta={},
+ content_hash=parent.content_hash,
+ file_size=10,
+ status='extract_failed',
+ saved_path=None,
+ ),
+ )
+ result = run_intake_parse(intake, parent)
+ assert result['status'] == 'parse_failed'
+ db.session.expire_all()
+ failed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-EXTRACT-CLEAR').one()
+ assert failed.parse_status == 'parse_failed'
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed.id).count() == 0
+ child2 = db.session.get(FileAsset, child.id)
+ assert int(child2.reference_count or 0) == 0
+ summary = failed.structured_result_json or {}
+ assert 'document_count' not in summary
+
+
+def test_retry_parse_rejects_cancelled_intake(app, shipping_user):
+ """已取消 Intake 不得被重试覆盖回 queued。"""
+ from app.services.shipping_notice.intake_service import retry_intake_parse
+
+ with app.app_context():
+ parent = FileAsset(
+ asset_no='FA-RETRY-CANCELLED',
+ owner_user_id=shipping_user.id,
+ original_filename='r.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/retry-cancelled.eml',
+ content_hash='retry-cancelled',
+ file_size=10,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ asset_role='upload',
+ )
+ db.session.add(parent)
+ db.session.flush()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-RETRY-CANCELLED',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='cancelled',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ db.session.commit()
+ with pytest.raises(ConflictError) as excinfo:
+ retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-RETRY-CANCELLED')
+ assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS'
+ db.session.expire_all()
+ assert (
+ db.session.query(ShippingNoticeIntake)
+ .filter_by(intake_no='SNI-RETRY-CANCELLED')
+ .one()
+ .parse_status
+ == 'cancelled'
+ )
+
+
+def test_stage2_fail_cleanup_skips_when_intake_already_cancelled(app, shipping_user, monkeypatch):
+ """阶段二失败清理持 Intake 锁后若已取消,不得再删 Candidate / 写 parse_failed。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+
+ msg = EmailMessage()
+ msg['Subject'] = 'fail after cancel'
+ msg['From'] = 'a@b.com'
+ msg['To'] = 'c@d.com'
+ msg.set_content('body')
+ msg.add_attachment(
+ _minimal_pdf_bytes('PO Number: CANCELLOCK001'),
+ maintype='application',
+ subtype='pdf',
+ filename='lock.pdf',
+ )
+ eml_bytes = msg.as_bytes()
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='lock.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-STAGE2-FAIL-CANCELLED',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ db.session.flush()
+ doc = ShippingNoticeDocument(
+ intake_id=intake.id,
+ attachment_key='att-001',
+ document_type='attachment',
+ filename='lock.pdf',
+ classification='supporting',
+ parse_status='parsed',
+ )
+ db.session.add(doc)
+ db.session.commit()
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _a: eml_bytes,
+ )
+
+ def _boom_then_cancel(**kwargs):
+ # 模拟失败瞬间另一事务已取消:清理前库状态为 cancelled
+ row = db.session.get(ShippingNoticeIntake, intake.id)
+ row.parse_status = 'cancelled'
+ db.session.commit()
+ raise RuntimeError('boom-after-cancel')
+
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
+ _boom_then_cancel,
+ )
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ result = run_intake_parse(intake, parent)
+ assert result['status'] == 'skipped'
+ db.session.expire_all()
+ final = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-FAIL-CANCELLED').one()
+ assert final.parse_status == 'cancelled'
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=final.id).count() == 1
+
+
+def test_refresh_duplicate_rejects_cancelled_intake(app, shipping_user):
+ """重复刷新持锁后发现已取消须拒绝,不得改写 Candidate。"""
+ from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
+
+ with app.app_context():
+ parent = FileAsset(
+ asset_no='FA-REFRESH-CANCELLED',
+ owner_user_id=shipping_user.id,
+ original_filename='x.eml',
+ storage_provider='minio',
+ storage_bucket='hxops-file-assets',
+ storage_key=f'temporary/{shipping_user.id}/refresh-cancelled.eml',
+ content_hash='refresh-cancelled',
+ file_size=10,
+ mime_type='message/rfc822',
+ upload_status='ready',
+ lifecycle_status='temporary',
+ reference_count=0,
+ asset_role='upload',
+ )
+ db.session.add(parent)
+ db.session.flush()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-REFRESH-CANCELLED',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='cancelled',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ db.session.commit()
+ with pytest.raises(ConflictError) as excinfo:
+ refresh_intake_duplicate_detection(
+ user_id=shipping_user.id,
+ intake_no='SNI-REFRESH-CANCELLED',
+ )
+ assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS'
+
+
+def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monkeypatch):
+ """阶段二重试失败须清理上一轮 Document/Candidate,不得与 parse_failed 并存。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+ from app.services.shipping_notice.intake_service import serialize_intake
+
+ msg = EmailMessage()
+ msg['Subject'] = 'retry clear'
+ msg['From'] = 'a@b.com'
+ msg['To'] = 'c@d.com'
+ msg.set_content('body')
+ msg.add_attachment(
+ _minimal_pdf_bytes('PO Number: RETRYCLEAR001\nSKU: X qty 1'),
+ maintype='application',
+ subtype='pdf',
+ filename='retry.pdf',
+ )
+ eml_bytes = msg.as_bytes()
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='retry-clear.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-STAGE2-RETRY-CLEAR',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ db.session.commit()
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _a: eml_bytes,
+ )
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ first = run_intake_parse(intake, parent)
+ assert first['status'] == 'parsed'
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() >= 1
+
+ intake.parse_status = 'parsing'
+ db.session.commit()
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
+ lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-retry-clear')),
+ )
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ second = run_intake_parse(intake, parent)
+ assert second['status'] == 'parse_failed'
+ db.session.expire_all()
+ failed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one()
+ assert failed.parse_status == 'parse_failed'
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed.id).count() == 0
+ assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=failed.id).count() == 0
+ payload = serialize_intake(failed, asset=parent)
+ assert payload['document_count'] == 0
+ assert payload['candidate_count'] == 0
+
+
+def test_cancel_intake_releases_stage2_documents_and_derived_refs(app, shipping_user, monkeypatch):
+ """解析完成后取消须删除 Document/Candidate 并归零派生资产引用。"""
+ from email.message import EmailMessage
+
+ from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
+ from app.services.shipping_notice.intake_service import cancel_intake
+
+ msg = EmailMessage()
+ msg['Subject'] = 'cancel after parse'
+ msg['From'] = 'a@b.com'
+ msg['To'] = 'c@d.com'
+ msg.set_content('body')
+ msg.add_attachment(
+ _minimal_pdf_bytes('PO Number: CANCEL001\nSKU: X qty 1'),
+ maintype='application',
+ subtype='pdf',
+ filename='cancel.pdf',
+ )
+ eml_bytes = msg.as_bytes()
+
+ with app.app_context():
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ asset_data = upload_file_asset(
+ user_id=shipping_user.id,
+ upload=FileStorage(
+ stream=BytesIO(eml_bytes),
+ filename='cancel.eml',
+ content_type='message/rfc822',
+ ),
+ )
+ parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
+ intake = ShippingNoticeIntake(
+ intake_no='SNI-STAGE2-CANCEL',
+ asset_id=parent.id,
+ user_id=shipping_user.id,
+ purpose='shipping_notice',
+ parse_status='parsing',
+ parser_version='v6',
+ )
+ db.session.add(intake)
+ db.session.commit()
+ monkeypatch.setattr(
+ 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
+ lambda _a: eml_bytes,
+ )
+ with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
+ result = run_intake_parse(intake, parent)
+ assert result['status'] == 'parsed'
+ derived = (
+ db.session.query(FileAsset)
+ .filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
+ .one()
+ )
+ assert int(derived.reference_count or 0) >= 1
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() >= 1
+
+ cancel_intake(user_id=shipping_user.id, intake_no='SNI-STAGE2-CANCEL')
+ db.session.expire_all()
+ cancelled = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-CANCEL').one()
+ assert cancelled.parse_status == 'cancelled'
+ assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=cancelled.id).count() == 0
+ assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=cancelled.id).count() == 0
+ derived2 = db.session.get(FileAsset, derived.id)
+ assert int(derived2.reference_count or 0) == 0
+ assert derived2.lifecycle_status == 'temporary'
+
+
+def test_compensate_minio_failure_persists_orphan_cleanup_row(app, shipping_user):
+ """补偿删除 MinIO 失败时应落 orphan_cleanup 行供定时任务继续回收。"""
+ from app.services.file_assets.service import compensate_uploaded_storage_keys
+
+ with app.app_context():
+ with patch(
+ 'app.services.file_assets.service.file_asset_storage.delete_object',
+ side_effect=RuntimeError('minio down'),
+ ):
+ compensate_uploaded_storage_keys(
+ ['temporary/orphan-key-for-test.bin'],
+ owner_user_id=shipping_user.id,
+ storage_bucket='hxops-file-assets',
+ )
+ orphan = (
+ db.session.query(FileAsset)
+ .filter_by(asset_role='orphan_cleanup', storage_key='temporary/orphan-key-for-test.bin')
+ .one()
+ )
+ assert orphan.lifecycle_status == 'expired'
+ assert int(orphan.reference_count or 0) == 0
+ assert orphan.deleted_at is None
diff --git a/backend/tests/test_shipping_notice_inventory_rpa_archive.py b/backend/tests/test_shipping_notice_inventory_rpa_archive.py
new file mode 100644
index 00000000..22704a7e
--- /dev/null
+++ b/backend/tests/test_shipping_notice_inventory_rpa_archive.py
@@ -0,0 +1,549 @@
+"""
+backend/tests/test_shipping_notice_inventory_rpa_archive.py
+
+用途:库存 RPA 原始库存 ZIP 归档、summary 可见性与 admin API 路由单测。
+依赖:shipping_inventory_rpa_archive、api/schedule/runs、query_service、shipping_inventory_rpa_finalize。
+逻辑:finalize 预生成 ZIP;列表只读 summary;下载 send_file 归档路径。
+"""
+
+from __future__ import annotations
+
+import json
+import zipfile
+from io import BytesIO
+from pathlib import Path
+
+import pytest
+
+from app import db
+from app.core.auth.jwt import issue_local_access_token
+from app.core.errors import NotFoundError
+from app.models import ScheduleRun, ShippingInventoryFile, User
+from app.services.schedule.query_service import serialize_run
+from app.services.schedule.scheduler_service import (
+ _build_schedule_run_wecom_description,
+ _build_schedule_run_wecom_jump_params,
+)
+from app.services.schedule.shipping_inventory_rpa_archive import (
+ inventory_raw_zip_available_from_summary,
+ inventory_raw_zip_download_name,
+ persist_inventory_rpa_raw_zip_archive,
+ resolve_inventory_raw_zip_download,
+)
+from tests.conftest import parse_api_error
+from tests.test_shipping_notice_inventory_schedule import _make_inventory_schedule_task
+
+
+@pytest.fixture
+def admin_jwt_headers(app):
+ """创建 admin 用户并签发 Bearer JWT。"""
+ with app.app_context():
+ user = db.session.query(User).filter_by(username='admin').first()
+ if not user:
+ user = User(
+ username='admin',
+ email='admin@example.com',
+ role='admin',
+ status='active',
+ )
+ user.set_password('admin')
+ db.session.add(user)
+ db.session.commit()
+ token = issue_local_access_token(user)
+ return {
+ 'Authorization': f'Bearer {token}',
+ 'Content-Type': 'application/json',
+ }
+
+
+def _make_inventory_run_with_created(
+ *,
+ schedule_no: str,
+ username: str,
+ created: list[dict],
+ summary: dict | None = None,
+) -> ScheduleRun:
+ """构造库存 RPA run,api_response_json.created 已写入。"""
+ task = _make_inventory_schedule_task(schedule_no=schedule_no, username=username)
+ run = ScheduleRun(
+ run_no=f"RUN-{schedule_no}",
+ schedule_task_id=task.id,
+ trigger_type="manual",
+ status="success",
+ total_count=len(created),
+ success_count=len(created),
+ failed_count=0,
+ skipped_count=0,
+ api_response_json={"created": created},
+ response_summary_json=summary,
+ )
+ db.session.add(run)
+ db.session.flush()
+ db.session.refresh(run)
+ return run
+
+
+def _attach_inventory_file(
+ *,
+ inventory_file_no: str,
+ storage_path: Path,
+ source_code: str = "SRC",
+ warehouse_id: str = "WH1",
+) -> None:
+ db.session.add(
+ ShippingInventoryFile(
+ inventory_file_no=inventory_file_no,
+ storage_path=str(storage_path),
+ source_file_name="inventory.xlsx",
+ source_code=source_code,
+ warehouse_id=warehouse_id,
+ )
+ )
+
+
+def test_inventory_raw_zip_available_from_summary_reads_persisted_flag():
+ """列表可见性应只依赖 summary.raw_inventory_zip_available。"""
+ assert inventory_raw_zip_available_from_summary({"raw_inventory_zip_available": True}) is True
+ assert inventory_raw_zip_available_from_summary({"raw_inventory_zip_available": False}) is False
+ assert inventory_raw_zip_available_from_summary(None) is False
+
+
+def test_serialize_run_reads_inventory_raw_zip_available_from_summary(app):
+ """serialize_run 不应实时扫库,只读 response_summary_json。"""
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-SER-1",
+ username="arch_ser_user",
+ created=[{"inventory_file_no": "SIF-SER-1"}],
+ summary={"raw_inventory_zip_available": True},
+ )
+ db.session.commit()
+ payload = serialize_run(run)
+ assert payload["inventory_raw_zip_available"] is True
+
+
+def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path):
+ """finalize 预生成应落盘 ZIP 并返回 summary 字段。"""
+ archive_dir = tmp_path / "inventory_archives"
+ app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
+ xlsx = tmp_path / "inventory.xlsx"
+ xlsx.write_bytes(b"fake-xlsx-content")
+
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-PERSIST-1",
+ username="arch_persist_user",
+ created=[{
+ "inventory_file_no": "SIF-20260710-ARCH01",
+ "source_code": "DSV360_AWSBI_BYAWSCMH01",
+ "warehouse_id": "BYAWSCMH01",
+ }],
+ )
+ _attach_inventory_file(
+ inventory_file_no="SIF-20260710-ARCH01",
+ storage_path=xlsx,
+ source_code="DSV360_AWSBI_BYAWSCMH01",
+ warehouse_id="BYAWSCMH01",
+ )
+ db.session.commit()
+
+ summary = persist_inventory_rpa_raw_zip_archive(run)
+ assert summary["raw_inventory_zip_available"] is True
+ assert summary["raw_inventory_file_count"] == 1
+ assert summary["raw_inventory_file_nos"] == ["SIF-20260710-ARCH01"]
+ assert summary["raw_inventory_zip_size"] > 0
+
+ zip_path = Path(summary["raw_inventory_zip_path"])
+ assert zip_path.is_file()
+ assert zip_path.name == f"{run.run_no}.zip"
+
+ with zipfile.ZipFile(zip_path) as archive:
+ names = archive.namelist()
+ assert "manifest.json" in names
+ assert any(name.endswith(".xlsx") for name in names)
+ manifest = json.loads(archive.read("manifest.json").decode("utf-8"))
+ assert manifest["run_no"] == run.run_no
+ assert manifest["files"][0]["inventory_file_no"] == "SIF-20260710-ARCH01"
+
+
+def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
+ """无可读快照时不生成 ZIP。"""
+ archive_dir = tmp_path / "inventory_archives"
+ app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
+
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-PERSIST-EMPTY",
+ username="arch_persist_empty",
+ created=[],
+ )
+ db.session.commit()
+ summary = persist_inventory_rpa_raw_zip_archive(run)
+ assert summary["raw_inventory_zip_available"] is False
+ assert list(archive_dir.glob("*.zip")) == []
+
+
+def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp_path):
+ """created 有记录但磁盘文件缺失时不应生成 ZIP。"""
+ archive_dir = tmp_path / "inventory_archives"
+ app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
+
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-PERSIST-MISSING",
+ username="arch_persist_missing",
+ created=[{
+ "inventory_file_no": "SIF-20260710-MISSING",
+ "source_code": "DSV360_AWSBI_BYAWSATL01",
+ "warehouse_id": "BYAWSATL01",
+ }],
+ )
+ _attach_inventory_file(
+ inventory_file_no="SIF-20260710-MISSING",
+ storage_path=Path("/nonexistent/inventory.xlsx"),
+ source_code="DSV360_AWSBI_BYAWSATL01",
+ warehouse_id="BYAWSATL01",
+ )
+ db.session.commit()
+ summary = persist_inventory_rpa_raw_zip_archive(run)
+ assert summary["raw_inventory_zip_available"] is False
+
+
+def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path):
+ """下载解析应返回归档路径与建议文件名。"""
+ archive_dir = tmp_path / "inventory_archives"
+ app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
+ xlsx = tmp_path / "inventory.xlsx"
+ xlsx.write_bytes(b"fake-xlsx-content")
+
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-RESOLVE-1",
+ username="arch_resolve_user",
+ created=[{"inventory_file_no": "SIF-RESOLVE-1", "source_code": "SRC", "warehouse_id": "WH1"}],
+ )
+ _attach_inventory_file(inventory_file_no="SIF-RESOLVE-1", storage_path=xlsx)
+ db.session.commit()
+ archive_summary = persist_inventory_rpa_raw_zip_archive(run)
+ run.response_summary_json = archive_summary
+ db.session.commit()
+
+ zip_path, file_name = resolve_inventory_raw_zip_download(run)
+ assert zip_path.is_file()
+ assert file_name == inventory_raw_zip_download_name(run.run_no)
+
+
+def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app):
+ """summary 标记可用但 ZIP 丢失时应 404。"""
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-RESOLVE-MISSING",
+ username="arch_resolve_missing",
+ created=[{"inventory_file_no": "SIF-1"}],
+ summary={
+ "raw_inventory_zip_available": True,
+ "raw_inventory_zip_path": str(Path("/nonexistent/archive.zip")),
+ },
+ )
+ db.session.commit()
+ with pytest.raises(NotFoundError):
+ resolve_inventory_raw_zip_download(run)
+
+
+def test_resolve_inventory_raw_zip_download_rejects_path_outside_archive_dir(app, tmp_path):
+ """summary 指向归档目录外的真实文件时必须 404。"""
+ archive_dir = tmp_path / "inventory_archives"
+ app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
+
+ outside_zip = tmp_path / "outside.zip"
+ outside_zip.write_bytes(b"fake-zip")
+
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-RESOLVE-OUTSIDE",
+ username="arch_resolve_outside",
+ created=[{"inventory_file_no": "SIF-OUTSIDE-1"}],
+ summary={
+ "raw_inventory_zip_available": True,
+ "raw_inventory_zip_path": str(outside_zip.resolve()),
+ },
+ )
+ db.session.commit()
+ with pytest.raises(NotFoundError):
+ resolve_inventory_raw_zip_download(run)
+
+
+def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path):
+ """summary 指向非 .zip 后缀文件时必须 404。"""
+ archive_dir = tmp_path / "inventory_archives"
+ archive_dir.mkdir(parents=True)
+ app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
+
+ fake_file = archive_dir / "RUN-ARCH-RESOLVE-BAD.txt"
+ fake_file.write_bytes(b"not-a-zip")
+
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-RESOLVE-BAD",
+ username="arch_resolve_bad_suffix",
+ created=[{"inventory_file_no": "SIF-BAD-1"}],
+ summary={
+ "raw_inventory_zip_available": True,
+ "raw_inventory_zip_path": str(fake_file.resolve()),
+ },
+ )
+ db.session.commit()
+ with pytest.raises(NotFoundError):
+ resolve_inventory_raw_zip_download(run)
+
+
+def test_build_schedule_run_wecom_description_mentions_raw_zip_download(app):
+ """企微正文在 summary 标记可下载时应提示登录后自动下载,不写完整 URL。"""
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-WECOM-1",
+ username="arch_wecom_user",
+ created=[{"inventory_file_no": "SIF-WECOM-1"}],
+ summary={"raw_inventory_zip_available": True},
+ )
+ db.session.commit()
+ text = _build_schedule_run_wecom_description(run)
+ assert "原始库存包:点击本通知,登录 HXOPS 后自动下载" in text
+ assert "https://" not in text
+ assert "http://" not in text
+
+
+def test_build_schedule_run_wecom_jump_params_adds_raw_zip_flag_when_archive_available(app):
+ """有原始库存归档时跳转参数应包含 raw_zip=1 与自动下载意图。"""
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-JUMP-1",
+ username="arch_jump_user",
+ created=[{"inventory_file_no": "SIF-JUMP-1"}],
+ summary={"raw_inventory_zip_available": True},
+ )
+ task = run.task
+ db.session.commit()
+ params = _build_schedule_run_wecom_jump_params(task, run)
+ assert params["task_id"] == task.id
+ assert params["run_id"] == run.id
+ assert params["raw_zip"] == "1"
+ assert params["download"] == "inventory_raw_zip"
+
+
+def test_build_schedule_run_wecom_jump_params_omits_raw_zip_without_archive(app):
+ """无原始库存归档时不应附加 raw_zip。"""
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-JUMP-2",
+ username="arch_jump_user2",
+ created=[],
+ summary={"raw_inventory_zip_available": False},
+ )
+ task = run.task
+ db.session.commit()
+ params = _build_schedule_run_wecom_jump_params(task, run)
+ assert params["task_id"] == task.id
+ assert params["run_id"] == run.id
+ assert "raw_zip" not in params
+ assert "download" not in params
+
+
+def test_get_notify_base_url_prefers_wecom_public_over_notify_base_url(app):
+ """textcard 跳转应优先 HTTPS 公网域名,而非内网/端口 WECOM_NOTIFY_BASE_URL。"""
+ from app.services.wecom_notify import _get_notify_base_url
+
+ with app.app_context():
+ app.config["WECOM_NOTIFY_BASE_URL"] = "http://ait.well-trust.com:8890/"
+ app.config["WECOM_PUBLIC_BASE_URL"] = "https://ait.well-trust.com"
+ app.config["HXOPS_PUBLIC_BASE_URL"] = "https://hxops.example.com"
+ assert _get_notify_base_url() == "https://ait.well-trust.com"
+
+
+def test_get_notify_base_url_falls_back_to_hxops_public_base_url(app):
+ """未配置 WECOM_PUBLIC 时应回退 HXOPS_PUBLIC_BASE_URL,而非 WECOM_NOTIFY_BASE_URL。"""
+ from app.services.wecom_notify import _get_notify_base_url
+
+ with app.app_context():
+ app.config["WECOM_PUBLIC_BASE_URL"] = ""
+ app.config["HXOPS_PUBLIC_BASE_URL"] = "https://hxops.example.com/"
+ app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/"
+ assert _get_notify_base_url() == "https://hxops.example.com"
+
+
+def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monkeypatch, tmp_path):
+ """企微 textcard 跳转应指向管理端执行记录页,而非 workspace。"""
+ from app.models import User
+ from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
+
+ captured: list[str] = []
+ media_uploads: list[str] = []
+ file_sends: list[str] = []
+
+ def _fake_send_textcard(_userid, _title, _description, jump_url):
+ captured.append(jump_url)
+ return {"errcode": 0}
+
+ monkeypatch.setattr(
+ "app.services.wecom_notify.send_wecom_textcard_message",
+ _fake_send_textcard,
+ )
+ monkeypatch.setattr(
+ "app.services.wecom_notify._get_enabled_events",
+ lambda: {"schedule_completed"},
+ )
+ monkeypatch.setattr(
+ "app.services.wecom_notify.upload_wecom_temp_media",
+ lambda _data, filename: media_uploads.append(filename) or f"media-{len(media_uploads)}",
+ )
+ monkeypatch.setattr(
+ "app.services.wecom_notify.send_wecom_file_message",
+ lambda _userid, media_id: file_sends.append(media_id) or {"errcode": 0},
+ )
+
+ with app.app_context():
+ app.config["WECOM_NOTIFY_ENABLED"] = True
+ app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com"
+ app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/"
+ app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
+
+ user = User(
+ username="wecom_jump_user",
+ email="wecom_jump@example.com",
+ role="user",
+ status="active",
+ wecom_userid="wecom-user-1",
+ )
+ db.session.add(user)
+ db.session.flush()
+
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-NOTIFY-1",
+ username="arch_notify_user",
+ created=[{"inventory_file_no": "SIF-NOTIFY-1"}],
+ summary={"raw_inventory_zip_available": True},
+ )
+ raw_excel = tmp_path / "raw_inventory.xlsx"
+ raw_excel.write_bytes(b"raw inventory")
+ _attach_inventory_file(inventory_file_no="SIF-NOTIFY-1", storage_path=raw_excel)
+ run.response_summary_json = persist_inventory_rpa_raw_zip_archive(run)
+ task = run.task
+ task.notify_enabled = True
+ task.notify_user_ids_json = [user.id]
+ run.excel_file_data = b"schedule excel"
+ run.excel_file_name = "schedule.xlsx"
+ db.session.commit()
+
+ _notify_schedule_run_wecom(task, run)
+
+ assert captured
+ assert captured[0].startswith("https://hxops.example.com/admin/schedules?")
+ assert "task_id=" in captured[0]
+ assert "run_id=" in captured[0]
+ assert "raw_zip=1" in captured[0]
+ assert "download=inventory_raw_zip" in captured[0]
+ assert "schedule.xlsx" in media_uploads
+ assert inventory_raw_zip_download_name("RUN-ARCH-NOTIFY-1") in media_uploads
+ assert file_sends == ["media-1", "media-2"]
+
+
+def test_get_inventory_raw_zip_requires_admin_auth(client, app):
+ """未携带 admin JWT 时应返回 401。"""
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-API-AUTH",
+ username="arch_api_auth",
+ created=[{"inventory_file_no": "SIF-AUTH-1"}],
+ summary={"raw_inventory_zip_available": True},
+ )
+ db.session.commit()
+ run_id = run.id
+
+ res = client.get(f'/api/admin/schedule-runs/{run_id}/inventory-raw-zip')
+ assert res.status_code == 401
+ error = parse_api_error(res.get_json())
+ assert error['code'] == 'AUTH.UNAUTHORIZED'
+
+
+def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
+ client,
+ app,
+ admin_jwt_headers,
+ tmp_path,
+):
+ """admin 鉴权通过时应返回 application/zip 且文件名与 run_no 一致。"""
+ archive_dir = tmp_path / "inventory_archives"
+ app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
+ xlsx = tmp_path / "inventory.xlsx"
+ xlsx.write_bytes(b"fake-xlsx-content")
+
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-API-ZIP",
+ username="arch_api_zip",
+ created=[{
+ "inventory_file_no": "SIF-20260710-API01",
+ "source_code": "DSV360_AWSBI_BYAWSCMH01",
+ "warehouse_id": "BYAWSCMH01",
+ }],
+ )
+ _attach_inventory_file(
+ inventory_file_no="SIF-20260710-API01",
+ storage_path=xlsx,
+ source_code="DSV360_AWSBI_BYAWSCMH01",
+ warehouse_id="BYAWSCMH01",
+ )
+ db.session.commit()
+ run.response_summary_json = persist_inventory_rpa_raw_zip_archive(run)
+ db.session.commit()
+ run_id = run.id
+ expected_name = inventory_raw_zip_download_name(run.run_no)
+
+ res = client.get(
+ f'/api/admin/schedule-runs/{run_id}/inventory-raw-zip',
+ headers=admin_jwt_headers,
+ )
+ assert res.status_code == 200
+ assert res.mimetype == 'application/zip'
+ assert expected_name in res.headers.get('Content-Disposition', '')
+
+ with zipfile.ZipFile(BytesIO(res.data)) as archive:
+ names = archive.namelist()
+ assert 'manifest.json' in names
+ assert any(name.endswith('.xlsx') for name in names)
+
+
+def test_get_inventory_raw_zip_returns_404_when_archive_unavailable(
+ client,
+ app,
+ admin_jwt_headers,
+):
+ """summary 未标记可用或归档丢失时应返回 404。"""
+ with app.app_context():
+ run = _make_inventory_run_with_created(
+ schedule_no="ARCH-API-404",
+ username="arch_api_404",
+ created=[{"inventory_file_no": "SIF-20260710-API-MISSING"}],
+ summary={"raw_inventory_zip_available": False},
+ )
+ db.session.commit()
+ run_id = run.id
+
+ res = client.get(
+ f'/api/admin/schedule-runs/{run_id}/inventory-raw-zip',
+ headers=admin_jwt_headers,
+ )
+ assert res.status_code == 404
+ error = parse_api_error(res.get_json())
+ assert error['code'] == 'RESOURCE.NOT_FOUND'
+
+
+def test_get_inventory_raw_zip_returns_404_for_unknown_run(client, admin_jwt_headers):
+ """run 不存在时应返回 404。"""
+ res = client.get(
+ '/api/admin/schedule-runs/999999/inventory-raw-zip',
+ headers=admin_jwt_headers,
+ )
+ assert res.status_code == 404
+ error = parse_api_error(res.get_json())
+ assert error['code'] == 'RESOURCE.NOT_FOUND'
diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py
index 0e8362e9..106f1cf8 100644
--- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py
+++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py
@@ -5,9 +5,11 @@
2. rpa_report_inventory 回调会把文件正式落到 inventory_uploads,并进入字段映射确认。
"""
+from datetime import datetime
from pathlib import Path
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
+from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source
def _tool_headers():
@@ -36,8 +38,12 @@ def test_inventory_rpa_single_attempt_messages_hide_fraction():
) == "已触发库存获取。若长时间无结果,可手动重试,或上传库存 Excel。"
-def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
+def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path, monkeypatch):
"""mode=auto 应返回 running 并在 DB 留下 inventory_rpa_triggered 事件。"""
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
+ lambda *args, **kwargs: None,
+ )
trigger = tmp_path / "triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
@@ -94,8 +100,12 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
assert len(events) == 1
-def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_path):
+def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_path, monkeypatch):
"""RPA 回调成功落盘后应进入字段映射确认(align_review / map_infer)。"""
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
+ lambda *args, **kwargs: None,
+ )
drop = tmp_path / "drop"
drop.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
@@ -111,20 +121,53 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
)
task_id = create_res.get_json()["task_id"]
+ client.post(
+ "/api/shipping-notice/tools/parse_notice",
+ headers=headers,
+ json={
+ "task_id": task_id,
+ "structured": {
+ "customer_name": "ACME",
+ "destination": {"port_code": "DUB", "city": "Dublin"},
+ "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
+ "confidence": 0.95,
+ },
+ },
+ )
+
from openpyxl import Workbook
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
- ws.append(["料号", "Reservation ID", "可用数量"])
- ws.append(["A001", "R-1", 20])
+ ws.append(["Warehouse ID", "料号", "Reservation ID", "可用数量"])
+ ws.append(["AWSDU", "A001", "R-1", 20])
wb.save(inv_file)
wb.close()
+ with app.app_context():
+ from app import db
+ from tests.conftest import seed_rpa_inventory_trigger
+
+ task = ShippingTask.query.filter_by(task_no=task_id).first()
+ assert task is not None
+ seed_rpa_inventory_trigger(task, run_no="RUN-MAP-REVIEW")
+ db.session.commit()
+ run_no = "RUN-MAP-REVIEW"
+
cb_res = client.post(
"/api/shipping-notice/rpa/inventory-ready",
headers=headers,
- json={"task_no": task_id, "success": True, "file_path": str(inv_file), "rpa_mode": "browser"},
+ json={
+ "task_no": task_id,
+ "success": True,
+ "file_path": str(inv_file),
+ "run_no": run_no,
+ "source_code": "DSV360_AWSDU",
+ "site_id": "AWSDU",
+ "warehouse_id": "AWSDU",
+ "rpa_mode": "browser",
+ },
)
data = cb_res.get_json()
assert data["status"] == "needs_human"
@@ -138,8 +181,10 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
assert task is not None
assert (task.step_payload_json or {})["last_inventory_rpa_runtime"]["mode"] == "browser"
assert task.process_status == "inventory_ready"
- stored = Path(app.config["SHIPPING_NOTICE_STORAGE_ROOT"]) / "inventory_uploads" / task_id / "inventory.xlsx"
- assert stored.is_file()
+ from app.services.shipping_notice.inventory_upload import resolve_task_inventory_upload_path
+
+ stored = resolve_task_inventory_upload_path(task_id)
+ assert stored is not None and stored.is_file()
inv_file = ShippingInventoryFile.query.order_by(ShippingInventoryFile.id.desc()).first()
assert inv_file is not None
assert inv_file.share_mode == "task_only"
@@ -151,8 +196,210 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
assert task.inventory_snapshot_id == inv_file.id
-def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
+def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client, tmp_path):
+ """无库存 skipped 回调应提示人工上传,且不计入 inventory_rpa_failed。"""
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "drop")
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
+ app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
+ app.config["INTEGRATION_API_KEY"] = "test-integration-key"
+
+ headers = _tool_headers()
+ create_res = client.post(
+ "/api/shipping-notice/tools/create_task",
+ headers=headers,
+ json={"source_type": "manual"},
+ )
+ task_id = create_res.get_json()["task_id"]
+
+ from app import db
+ from tests.conftest import seed_task_inventory_source
+
+ with app.app_context():
+ task = ShippingTask.query.filter_by(task_no=task_id).first()
+ assert task is not None
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ from tests.conftest import seed_rpa_inventory_trigger
+
+ seed_rpa_inventory_trigger(task, run_no="RUN-SKIPPED")
+ db.session.commit()
+
+ cb_res = client.post(
+ "/api/shipping-notice/rpa/inventory-ready",
+ headers=headers,
+ json={
+ "task_no": task_id,
+ "status": "skipped",
+ "success": False,
+ "skipped": True,
+ "skip_reason": "no_inventory_data",
+ "message": "DSV report has no inventory data",
+ "run_no": "RUN-SKIPPED",
+ "source_code": "DSV360_AWSDU",
+ "site_id": "AWSDU",
+ "warehouse_id": "AWSDU",
+ "rpa_mode": "browser",
+ },
+ )
+ data = cb_res.get_json()
+ assert data["status"] == "needs_human"
+ assert data.get("checkpoint") == "upload_req"
+ assert "无可用库存" in (data.get("message") or "")
+
+ with app.app_context():
+ task = ShippingTask.query.filter_by(task_no=task_id).first()
+ assert task is not None
+ assert task.process_status == "waiting_inventory"
+ failed_events = ShippingTaskEvent.query.filter_by(
+ task_id=task.id,
+ event_type="inventory_rpa_failed",
+ ).all()
+ skipped_events = ShippingTaskEvent.query.filter_by(
+ task_id=task.id,
+ event_type="inventory_rpa_skipped",
+ ).all()
+ assert not failed_events
+ assert len(skipped_events) == 1
+ assert skipped_events[0].detail_json.get("skip_reason") == "no_inventory_data"
+ assert task.error_message is None
+ skipped_meta = (task.step_payload_json or {}).get("inventory_rpa_skipped") or {}
+ assert skipped_meta.get("skip_reason") == "no_inventory_data"
+ assert skipped_meta.get("message")
+
+
+def test_normalize_rpa_inventory_result_status():
+ """单任务与 batch item 归一化:单任务宽松、batch 严格。"""
+ from app.services.shipping_notice.inventory_rpa_workflow import (
+ _normalize_rpa_inventory_batch_item_status,
+ _normalize_rpa_inventory_result_status,
+ _summarize_rpa_inventory_batch_outcome,
+ )
+
+ assert _normalize_rpa_inventory_result_status({"status": "skipped"}) == "skipped"
+ assert _normalize_rpa_inventory_result_status({"skipped": True, "success": False}) == "skipped"
+ assert _normalize_rpa_inventory_result_status({"success": True}) == "success"
+ assert _normalize_rpa_inventory_result_status({"success": False}) == "failed"
+ assert _normalize_rpa_inventory_result_status({}) == "success"
+ assert _normalize_rpa_inventory_batch_item_status({}) == "failed"
+ assert _normalize_rpa_inventory_batch_item_status({"success": True}) == "success"
+ assert _summarize_rpa_inventory_batch_outcome(created=[{}], skipped=[], failed=[{}]) == "partial_failed"
+ assert _summarize_rpa_inventory_batch_outcome(created=[], skipped=[{}], failed=[]) == "success"
+ assert _summarize_rpa_inventory_batch_outcome(created=[], skipped=[], failed=[{}]) == "failed"
+
+
+def test_rpa_report_inventory_batch_empty_item_treated_as_failed(app, tmp_path):
+ """batch results 中空 dict 应直接 failed,不走 success→file_missing 绕路。"""
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+
+ with app.app_context():
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-EMPTY-ITEM",
+ "trigger_type": "scheduled",
+ "results": [{}],
+ })
+ assert result["status"] == "ok"
+ assert result["result_status"] == "failed"
+ assert result["data"]["result_status"] == "failed"
+ assert result["data"]["failed_count"] == 1
+ assert result["data"]["failed"][0]["error"] == "unknown_or_disabled_source"
+
+
+def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tmp_path):
+ """同一批 results 含 success+failed 时,顶层 result_status 应为 partial_failed。"""
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+
+ sample = drop_dir / "inventory_mixed.xlsx"
+ with open(sample, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-MIXED",
+ "trigger_type": "scheduled",
+ "results": [
+ scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ status="success",
+ success=True,
+ file_path=str(sample),
+ ),
+ {
+ "source_code": "UNKNOWN_SOURCE",
+ "warehouse_id": "WH2",
+ "status": "failed",
+ "success": False,
+ "error_message": "timeout",
+ },
+ ],
+ })
+ assert result["status"] == "ok"
+ assert result["result_status"] == "partial_failed"
+ assert result["data"]["result_status"] == "partial_failed"
+ assert result["success_count"] == 1
+ assert result["failed_count"] == 1
+
+
+def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
+ """全 failed 时接口 status 仍为 ok,业务结果见 result_status=failed。"""
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+
+ with app.app_context():
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-ALL-FAIL",
+ "trigger_type": "scheduled",
+ "results": [{
+ "source_code": "UNKNOWN_SOURCE",
+ "warehouse_id": "WH1",
+ "status": "failed",
+ "success": False,
+ "error_message": "timeout",
+ }],
+ })
+ assert result["status"] == "ok"
+ assert result["result_status"] == "failed"
+ assert result["failed_count"] == 1
+ assert result["data"]["failed"][0]["error"] == "unknown_or_disabled_source"
+
+
+def test_resolve_rpa_inventory_batch_response_outcome_prefers_finalize_run_status():
+ """排程 finalize 成功时 result_status 应与 run_status 一致。"""
+ from app.services.shipping_notice.inventory_rpa_workflow import (
+ _resolve_rpa_inventory_batch_response_outcome,
+ )
+
+ outcome = _resolve_rpa_inventory_batch_response_outcome(
+ created=[{"source_code": "A"}],
+ skipped=[],
+ failed=[],
+ finalize_result={
+ "ok": True,
+ "run_status": "partial_failed",
+ "success_count": 1,
+ "skipped_count": 0,
+ "failed_count": 2,
+ },
+ schedule_run_id=99,
+ )
+ assert outcome["callback_result_status"] == "success"
+ assert outcome["result_status"] == "partial_failed"
+ assert outcome["success_count"] == 1
+ assert outcome["failed_count"] == 2
+
+
+def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch):
"""确认库存源后应立即进入 RPA pending,并写出库存导出 trigger。"""
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
+ lambda *args, **kwargs: None,
+ )
from app import db
from app.services.shipping_notice.inventory_rpa_workflow import confirm_inventory_source
@@ -166,8 +413,10 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
task = ShippingTask(
task_no="SN-CONFIRM-SOURCE-RPA",
source_type="pdf",
- process_status="waiting_inventory",
+ process_status="pending_review",
+ current_step="step2_parse_confirm",
pending_human_reason="inventory_source_unresolved",
+ ship_to="Dublin",
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
@@ -202,3 +451,839 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json"))
or list(trigger.glob("inventory_export_batch_TASK-SN-CONFIRM-SOURCE-RPA*.json"))
)
+
+
+def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
+ """batch 顶层 run_no 应注入 result item,带 task_no 的成功项可入库。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+
+ sample = drop_dir / "batch_task_success.xlsx"
+ with open(sample, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-BATCH-RUNNO",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ from tests.conftest import seed_rpa_inventory_trigger
+
+ seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-TOP")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-BATCH-TOP",
+ "trigger_type": "on_demand",
+ "results": [{
+ "task_no": task.task_no,
+ "status": "success",
+ "success": True,
+ "file_path": str(sample),
+ "source_code": task.inventory_source_code,
+ "site_id": task.inventory_site_id,
+ "warehouse_id": task.inventory_warehouse_id,
+ }],
+ })
+ db.session.refresh(task)
+
+ assert result["status"] == "ok"
+ assert result["success_count"] == 1
+ assert task.process_status == "inventory_ready"
+
+
+def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
+ """batch failed + task_no 应驱动任务失败重试/人工兜底,而非停留在 rpa_pending。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-BATCH-FAIL-TASK",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ from tests.conftest import seed_rpa_inventory_trigger
+
+ seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-FAIL")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-BATCH-FAIL",
+ "trigger_type": "on_demand",
+ "results": [{
+ "task_no": task.task_no,
+ "status": "failed",
+ "success": False,
+ "error_message": "login timeout",
+ }],
+ })
+ db.session.refresh(task)
+
+ assert result["status"] == "ok"
+ assert result["failed_count"] == 1
+ assert task.process_status == "waiting_inventory"
+ assert task.error_message
+ failed_events = ShippingTaskEvent.query.filter_by(
+ task_id=task.id,
+ event_type="inventory_rpa_failed",
+ ).all()
+ assert len(failed_events) == 1
+
+
+def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
+ """单任务 failed 回调缺少 site/warehouse 时仍应进入失败处理,但须匹配当前 run_no。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-FAIL-NO-IDENT",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-FAIL-NO-IDENT")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory({
+ "task_id": task.task_no,
+ "status": "failed",
+ "success": False,
+ "run_no": "RUN-FAIL-NO-IDENT",
+ "error_message": "browser login failed",
+ })
+ db.session.refresh(task)
+
+ assert result["status"] == "needs_human"
+ failed_events = ShippingTaskEvent.query.filter_by(
+ task_id=task.id,
+ event_type="inventory_rpa_failed",
+ ).all()
+ assert failed_events
+ assert "browser login failed" in (failed_events[-1].detail_json or {}).get("error", "")
+
+
+def test_batch_callback_rejects_unknown_task_no(app, tmp_path):
+ """batch item 携带不存在 task_no 时应拒绝,不得退化为定时预热快照。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "orphan_task.xlsx"
+ with open(sample, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-UNKNOWN-TASK",
+ "trigger_type": "on_demand",
+ "results": [{
+ "task_no": "SN-DOES-NOT-EXIST",
+ "status": "success",
+ "success": True,
+ "file_path": str(sample),
+ "source_code": "DSV360_AWSDU",
+ "site_id": "DSV360",
+ "warehouse_id": "AWSDU",
+ }],
+ })
+ after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
+
+ assert result["status"] == "ok"
+ assert result["failed_count"] == 1
+ assert result["data"]["failed"][0]["error"] == "task_not_found"
+ assert after == before
+
+
+def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
+ """batch 成功项缺少 Worker 身份字段时不得由任务字段自证通过。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "missing_identity.xlsx"
+ with open(sample, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-BATCH-NO-IDENT",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-BATCH-NO-IDENT",
+ "trigger_type": "on_demand",
+ "results": [{
+ "task_no": task.task_no,
+ "status": "success",
+ "success": True,
+ "file_path": str(sample),
+ }],
+ })
+ db.session.refresh(task)
+
+ assert result["status"] == "ok"
+ assert result["failed_count"] == 1
+ assert task.process_status == "waiting_inventory"
+
+
+def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkeypatch):
+ """复用快照后 ingest 失败时不得删除原快照与托管文件。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "reuse_ingest_fail.xlsx"
+ sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+ run_no = "RUN-REUSE-INGEST-FAIL"
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow.ingest_inventory_file",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("ingest boom")),
+ )
+
+ with app.app_context():
+ warmup = rpa_report_inventory_batch({
+ "run_no": run_no,
+ "trigger_type": "scheduled",
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ success=True,
+ file_path=str(sample),
+ )],
+ })
+ snap = ShippingInventoryFile.query.filter_by(
+ rpa_run_no=run_no,
+ source_code="DSV360_AWSDU",
+ snapshot_status="ready",
+ ).first()
+ assert warmup["success_count"] == 1
+ assert snap is not None
+ storage_path = Path(snap.storage_path)
+ assert storage_path.is_file()
+ snap_id = snap.id
+
+ task = ShippingTask(
+ task_no="SN-REUSE-INGEST-FAIL",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no=run_no)
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory_batch({
+ "run_no": run_no,
+ "trigger_type": "on_demand",
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ success=True,
+ file_path=str(sample),
+ task_no=task.task_no,
+ )],
+ })
+ db.session.refresh(task)
+ snap_after = ShippingInventoryFile.query.get(snap_id)
+
+ assert result["failed_count"] == 1
+ assert snap_after is not None
+ assert snap_after.snapshot_status == "ready"
+ assert Path(snap_after.storage_path).is_file()
+ assert ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").count() == 1
+ assert task.process_status == "waiting_inventory"
+
+
+def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
+ """同身份重试但文件内容不同必须拒绝,且不得覆盖原快照解析结果。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+ from openpyxl import Workbook
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ run_no = "RUN-REUSE-MISMATCH"
+
+ first = drop_dir / "first.xlsx"
+ first.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ second = drop_dir / "second.xlsx"
+ wb = Workbook()
+ ws = wb.active
+ ws.append(["Warehouse ID", "SKU", "Qty Available"])
+ ws.append(["AWSDU", "DIFFERENT-SKU", 99])
+ wb.save(second)
+ wb.close()
+
+ with app.app_context():
+ first_result = rpa_report_inventory_batch({
+ "run_no": run_no,
+ "trigger_type": "scheduled",
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ success=True,
+ file_path=str(first),
+ )],
+ })
+ snap = ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").one()
+ original_lines = list(snap.inventory_lines_json or [])
+ assert first_result["success_count"] == 1
+
+ second_result = rpa_report_inventory_batch({
+ "run_no": run_no,
+ "trigger_type": "scheduled",
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ success=True,
+ file_path=str(second),
+ )],
+ })
+ db.session.refresh(snap)
+
+ assert second_result["failed_count"] == 1
+ assert second_result["data"]["failed"][0]["error"] == "reused_snapshot_content_mismatch"
+ assert ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").count() == 1
+ assert list(snap.inventory_lines_json or []) == original_lines
+
+
+def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path, monkeypatch):
+ """batch 中失败单项须 savepoint 回滚,不影响同批其他成功项。"""
+ from app import db
+ from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response as real_loaded
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample_a = drop_dir / "task_a.xlsx"
+ sample_b = drop_dir / "task_b.xlsx"
+ sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+ sample_b.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+ run_no = "RUN-BATCH-PARTIAL-ROLLBACK"
+ loaded_calls = {"count": 0}
+
+ def flaky_loaded(task, *args, **kwargs):
+ loaded_calls["count"] += 1
+ if loaded_calls["count"] >= 2:
+ raise RuntimeError("loaded boom")
+ return real_loaded(task, *args, **kwargs)
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response",
+ flaky_loaded,
+ )
+
+ with app.app_context():
+ task_a = ShippingTask(
+ task_no="SN-BATCH-OK",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ task_b = ShippingTask(
+ task_no="SN-BATCH-FAIL",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "B001", "qty": 1}],
+ )
+ seed_task_inventory_source(task_a, source_code="DSV360_AWSDU")
+ seed_task_inventory_source(task_b, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task_a, run_no=run_no)
+ seed_rpa_inventory_trigger(task_b, run_no=run_no)
+ db.session.add_all([task_a, task_b])
+ db.session.commit()
+ before_b_status = task_b.process_status
+
+ result = rpa_report_inventory_batch({
+ "run_no": run_no,
+ "trigger_type": "on_demand",
+ "results": [
+ scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ success=True,
+ file_path=str(sample_a),
+ task_no=task_a.task_no,
+ ),
+ scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ success=True,
+ file_path=str(sample_b),
+ task_no=task_b.task_no,
+ ),
+ ],
+ })
+ db.session.refresh(task_a)
+ db.session.refresh(task_b)
+
+ assert result["success_count"] == 1
+ assert result["failed_count"] == 1
+ assert task_a.inventory_rpa_consumed_run_no == run_no
+ assert task_b.inventory_rpa_consumed_run_no is None
+ assert task_b.process_status == before_b_status
+
+
+def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, monkeypatch):
+ """共享快照被另一任务复用失败时,不得影响已关联任务的 active link。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "shared.xlsx"
+ sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+ run_no = "RUN-SHARED-LINK"
+
+ with app.app_context():
+ task_ok = ShippingTask(
+ task_no="SN-SHARED-OK",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ task_fail = ShippingTask(
+ task_no="SN-SHARED-FAIL",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "B001", "qty": 1}],
+ )
+ seed_task_inventory_source(task_ok, source_code="DSV360_AWSDU")
+ seed_task_inventory_source(task_fail, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task_ok, run_no=run_no)
+ seed_rpa_inventory_trigger(task_fail, run_no=run_no)
+ db.session.add_all([task_ok, task_fail])
+ db.session.commit()
+
+ ok_result = rpa_report_inventory_batch({
+ "run_no": run_no,
+ "trigger_type": "on_demand",
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ success=True,
+ file_path=str(sample),
+ task_no=task_ok.task_no,
+ )],
+ })
+ snap = ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").one()
+ ok_link = ShippingTaskInventoryLink.query.filter_by(
+ task_id=task_ok.id,
+ inventory_file_id=snap.id,
+ is_active=True,
+ ).one()
+ assert ok_result["success_count"] == 1
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow.ingest_inventory_file",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("ingest boom")),
+ )
+ fail_result = rpa_report_inventory_batch({
+ "run_no": run_no,
+ "trigger_type": "on_demand",
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ success=True,
+ file_path=str(sample),
+ task_no=task_fail.task_no,
+ )],
+ })
+ still_ok_link = ShippingTaskInventoryLink.query.filter_by(
+ task_id=task_ok.id,
+ inventory_file_id=snap.id,
+ is_active=True,
+ ).one()
+
+ assert fail_result["failed_count"] == 1
+ assert still_ok_link.id == ok_link.id
+ assert ShippingInventoryFile.query.get(snap.id) is not None
+ assert Path(snap.storage_path).is_file()
+
+
+def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_path, monkeypatch):
+ """数据库提交后 post-commit 步骤失败时不得删除已提交快照文件。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory
+ from tests.conftest import rpa_callback_payload, seed_rpa_inventory_trigger, seed_task_inventory_source
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "post_commit.xlsx"
+ sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ import app.services.shipping_notice.inventory_file_store as file_store
+
+ monkeypatch.setattr(
+ file_store,
+ "start_inventory_file_linked_tasks",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("post commit boom")),
+ )
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-POST-COMMIT-FAIL",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-POST-COMMIT")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-POST-COMMIT"))
+ snap = ShippingInventoryFile.query.filter_by(rpa_run_no="RUN-POST-COMMIT", snapshot_status="ready").first()
+
+ assert snap is not None
+ assert Path(snap.storage_path).is_file()
+ assert result.get("data", {}).get("post_commit_warnings")
+ assert task.inventory_rpa_consumed_run_no == "RUN-POST-COMMIT"
+
+
+def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkeypatch):
+ """晋升失败后应自动从 storage_path 重建任务正式附件,且不依赖重新消费 callback。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory
+ from app.services.shipping_notice.inventory_upload import resolve_task_inventory_upload_path
+ from tests.conftest import rpa_callback_payload, seed_rpa_inventory_trigger, seed_task_inventory_source
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "promote_fail.xlsx"
+ sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ def _boom_promote(*_args, **_kwargs):
+ raise OSError("promote exploded")
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow.promote_staged_task_inventory_file",
+ _boom_promote,
+ )
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-PROMOTE-FAIL-REBUILD",
+ source_type="manual",
+ process_status="waiting_inventory",
+ pending_human_reason="rpa_pending",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-PROMOTE-FAIL")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-PROMOTE-FAIL"))
+ attachment = resolve_task_inventory_upload_path(task.task_no)
+
+ assert result["status"] == "needs_human"
+ warnings = result.get("data", {}).get("post_commit_warnings") or []
+ assert any("promote_recovered_via_snapshot_rebuild" in item for item in warnings)
+ assert attachment is not None and attachment.is_file()
+ assert task.inventory_rpa_consumed_run_no == "RUN-PROMOTE-FAIL"
+
+
+def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
+ """人工补偿接口应能从快照 storage_path 幂等重建任务附件。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import repair_task_inventory_attachment
+ from app.services.shipping_notice.inventory_upload import resolve_task_inventory_upload_path
+ from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
+
+ storage_root = tmp_path / "storage"
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(storage_root)
+ snap_dir = storage_root / "inventory_uploads" / "SIF-TEST"
+ snap_dir.mkdir(parents=True)
+ snap_file = snap_dir / "inventory.xlsx"
+ snap_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-REPAIR-ATTACH",
+ source_type="manual",
+ process_status="inventory_ready",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ db.session.add(task)
+ db.session.flush()
+ inv_file = ShippingInventoryFile(
+ inventory_file_no="SIF-REPAIR-TEST",
+ storage_path=str(snap_file),
+ snapshot_status="ready",
+ source_code="DSV360_AWSDU",
+ site_id="AWSDU",
+ warehouse_id="AWSDU",
+ share_mode="task_only",
+ schema_preview_json={},
+ exported_at=datetime.utcnow(),
+ )
+ db.session.add(inv_file)
+ db.session.flush()
+ link_snapshot_to_task(task, inv_file, reason="test")
+ db.session.commit()
+
+ first = repair_task_inventory_attachment({"task_no": task.task_no})
+ second = repair_task_inventory_attachment({"task_no": task.task_no})
+ attachment = resolve_task_inventory_upload_path(task.task_no)
+
+ assert first["status"] == "ok"
+ assert second["status"] == "ok"
+ assert attachment is not None and attachment.is_file()
+ assert first["data"]["attachment_path"] == second["data"]["attachment_path"]
+
+
+def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch):
+ """callback 归档失败时应写入持久化 cleanup job。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_callback_cleanup import callback_cleanup_queue_dir
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+ from tests.conftest import scheduled_rpa_batch_item
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "move_fail.xlsx"
+ sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ def _boom_move(*_args, **_kwargs):
+ raise OSError("move exploded")
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow.move_callback_drop_file_to_processed",
+ _boom_move,
+ )
+
+ with app.app_context():
+ payload = {
+ "run_no": "RUN-MOVE-FAIL",
+ "results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
+ }
+ result = rpa_report_inventory_batch(payload)
+ queue = callback_cleanup_queue_dir()
+ jobs = list(queue.glob("move_*.json")) if queue else []
+
+ assert result["status"] == "ok"
+ assert jobs
+ assert not sample.is_file()
+ quarantined = list((drop_dir / ".hxops_quarantine").glob("move_fail.xlsx"))
+ assert quarantined
+
+
+def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, monkeypatch):
+ """move 与 quarantine 均失败时,仍应以原路径入队且 API 返回 ok。"""
+ import json
+
+ from app.services.shipping_notice.inventory_rpa_callback_cleanup import callback_cleanup_queue_dir
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+ from tests.conftest import scheduled_rpa_batch_item
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "quarantine_fail.xlsx"
+ sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ def _boom_move(*_args, **_kwargs):
+ raise OSError("move exploded")
+
+ def _boom_quarantine(*_args, **_kwargs):
+ raise OSError("quarantine exploded")
+
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow.move_callback_drop_file_to_processed",
+ _boom_move,
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow.quarantine_callback_drop_file",
+ _boom_quarantine,
+ )
+
+ with app.app_context():
+ payload = {
+ "run_no": "RUN-QUARANTINE-FAIL",
+ "results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
+ }
+ result = rpa_report_inventory_batch(payload)
+ queue = callback_cleanup_queue_dir()
+ jobs = list(queue.glob("move_*.json")) if queue else []
+
+ assert result["status"] == "ok"
+ assert jobs
+ assert sample.is_file()
+ job_payload = json.loads(jobs[0].read_text(encoding="utf-8"))
+ assert job_payload["callback_path"] == str(sample)
+ assert "move exploded" in str(job_payload.get("last_error") or "")
+
+
+def test_resolve_trusts_marker_over_newer_orphan_attachment(app, tmp_path):
+ """marker 有效时必须返回 marker 指向的已提交附件,不得按 mtime 选未提交新文件。"""
+ from app.services.shipping_notice.inventory_upload import (
+ _atomic_write_task_inventory_marker,
+ _task_inventory_upload_dir,
+ resolve_task_inventory_upload_path,
+ )
+
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ task_no = "SN-MARKER-TRUST"
+ base = _task_inventory_upload_dir(task_no)
+ base.mkdir(parents=True)
+ committed = base / "inventory_20260713010000000000.xlsx"
+ orphan = base / "inventory_20260713020000000000.xlsx"
+ committed.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+ orphan.write_bytes(b"orphan-newer")
+ _atomic_write_task_inventory_marker(task_no, committed.name)
+
+ with app.app_context():
+ resolved = resolve_task_inventory_upload_path(task_no)
+ assert resolved == committed
+
+
+def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
+ """修复接口不得安装非 active link 的快照。"""
+ from app import db
+ from app.services.shipping_notice.inventory_rpa_workflow import repair_task_inventory_attachment
+ from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
+
+ storage_root = tmp_path / "storage"
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(storage_root)
+ snap_dir = storage_root / "inventory_uploads" / "SIF-ACTIVE"
+ snap_dir.mkdir(parents=True)
+ active_file = snap_dir / "inventory.xlsx"
+ active_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+ other_file = storage_root / "other.xlsx"
+ other_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-REPAIR-REJECT",
+ source_type="manual",
+ process_status="inventory_ready",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ db.session.add(task)
+ db.session.flush()
+ active_snap = ShippingInventoryFile(
+ inventory_file_no="SIF-ACTIVE-SNAP",
+ storage_path=str(active_file),
+ snapshot_status="ready",
+ source_code="DSV360_AWSDU",
+ site_id="AWSDU",
+ warehouse_id="AWSDU",
+ share_mode="task_only",
+ schema_preview_json={},
+ exported_at=datetime.utcnow(),
+ )
+ foreign_snap = ShippingInventoryFile(
+ inventory_file_no="SIF-FOREIGN-SNAP",
+ storage_path=str(other_file),
+ snapshot_status="ready",
+ source_code="DSV360_AWSDU",
+ site_id="AWSDU",
+ warehouse_id="AWSDU",
+ share_mode="task_only",
+ schema_preview_json={},
+ exported_at=datetime.utcnow(),
+ )
+ db.session.add_all([active_snap, foreign_snap])
+ db.session.flush()
+ link_snapshot_to_task(task, active_snap, reason="test")
+ db.session.commit()
+
+ result = repair_task_inventory_attachment({
+ "task_no": task.task_no,
+ "inventory_file_no": foreign_snap.inventory_file_no,
+ })
+ assert result["status"] == "failed"
+ assert result["data"]["error"] == "snapshot_not_active_for_task"
+
+
+def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_path):
+ """cleanup 队列应由启动恢复独立消费,不依赖下一次 callback。"""
+ from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
+ callback_cleanup_queue_dir,
+ enqueue_callback_file_move,
+ recover_pending_rpa_callback_cleanup_jobs,
+ )
+
+ drop_dir = tmp_path / "drop"
+ processed_dir = tmp_path / "processed"
+ drop_dir.mkdir()
+ processed_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir)
+
+ quarantine = drop_dir / ".hxops_quarantine"
+ quarantine.mkdir(parents=True)
+ stuck = quarantine / "stuck.xlsx"
+ stuck.write_bytes(b"stuck")
+
+ with app.app_context():
+ enqueue_callback_file_move(
+ stuck,
+ processed_dir=processed_dir,
+ run_no="RUN-STUCK",
+ task_no="SN-STUCK",
+ error="simulated move failure",
+ )
+ queue = callback_cleanup_queue_dir()
+ assert queue is not None
+ assert list(queue.glob("move_*.json"))
+
+ recovered, warnings = recover_pending_rpa_callback_cleanup_jobs()
+ assert recovered >= 1
+ assert not list(queue.glob("move_*.json"))
+ assert list(processed_dir.glob("stuck.xlsx"))
+ assert not stuck.is_file()
+ assert warnings == []
diff --git a/backend/tests/test_shipping_notice_inventory_schedule.py b/backend/tests/test_shipping_notice_inventory_schedule.py
index 7da79f23..89841db7 100644
--- a/backend/tests/test_shipping_notice_inventory_schedule.py
+++ b/backend/tests/test_shipping_notice_inventory_schedule.py
@@ -7,6 +7,7 @@ backend/tests/test_shipping_notice_inventory_schedule.py
"""
from datetime import datetime, timedelta
+from pathlib import Path
from app import db
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig, User
@@ -24,6 +25,13 @@ from app.services.schedule.shipping_inventory_rpa_job import (
run_shipping_inventory_rpa_schedule,
)
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item
+
+
+def _write_sample_inventory(path: Path, warehouse_id: str) -> None:
+ """写入带 Warehouse ID 列的样例库存 Excel。"""
+ with open(path, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse(warehouse_id, sku="A001", qty=1).getvalue())
def _make_inventory_schedule_task(
@@ -217,16 +225,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_excel_fail.xlsx"
- try:
- from openpyxl import Workbook
-
- wb = Workbook()
- ws = wb.active
- ws.append(["料号", "可用数量"])
- ws.append(["A001", 1])
- wb.save(sample)
- except ImportError:
- sample.write_bytes(b"placeholder")
+ _write_sample_inventory(sample, "BYAWSATL01")
def _excel_boom(*_args, **_kwargs):
raise RuntimeError("excel exploded")
@@ -265,12 +264,11 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
- "results": [{
- "source_code": "DSV360_AWSBI_BYAWSATL01",
- "warehouse_id": "BYAWSATL01",
- "success": True,
- "file_path": str(sample),
- }],
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSBI_BYAWSATL01",
+ success=True,
+ file_path=str(sample),
+ )],
})
db.session.refresh(run)
@@ -292,16 +290,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_fail_finalize.xlsx"
- try:
- from openpyxl import Workbook
-
- wb = Workbook()
- ws = wb.active
- ws.append(["料号", "可用数量"])
- ws.append(["A001", 1])
- wb.save(sample)
- except ImportError:
- sample.write_bytes(b"placeholder")
+ _write_sample_inventory(sample, "BYAWSATL01")
def _boom(*_args, **_kwargs):
raise RuntimeError("finalize exploded")
@@ -340,12 +329,11 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
- "results": [{
- "source_code": "DSV360_AWSBI_BYAWSATL01",
- "warehouse_id": "BYAWSATL01",
- "success": True,
- "file_path": str(sample),
- }],
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSBI_BYAWSATL01",
+ success=True,
+ file_path=str(sample),
+ )],
})
db.session.refresh(run)
@@ -366,16 +354,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_sample.xlsx"
- try:
- from openpyxl import Workbook
-
- wb = Workbook()
- ws = wb.active
- ws.append(["料号", "可用数量"])
- ws.append(["A001", 1])
- wb.save(sample)
- except ImportError:
- sample.write_bytes(b"placeholder")
+ _write_sample_inventory(sample, "BYAWSATL01")
with app.app_context():
task = _make_inventory_schedule_task(
@@ -406,12 +385,11 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
- "results": [{
- "source_code": "DSV360_AWSBI_BYAWSATL01",
- "warehouse_id": "BYAWSATL01",
- "success": True,
- "file_path": str(sample),
- }],
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSBI_BYAWSATL01",
+ success=True,
+ file_path=str(sample),
+ )],
})
db.session.refresh(run)
@@ -421,6 +399,11 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
assert run.failed_count == 0
assert run.excel_file_data
assert (run.response_summary_json or {}).get("awaiting_rpa") is False
+ summary = run.response_summary_json or {}
+ assert summary.get("raw_inventory_zip_available") is True
+ assert summary.get("raw_inventory_file_count") == 1
+ assert summary.get("raw_inventory_zip_path")
+ assert Path(summary["raw_inventory_zip_path"]).is_file()
def test_recover_stale_awaiting_rpa_schedule_run(app):
@@ -454,6 +437,8 @@ def test_compute_run_status_requires_all_sources_success():
assert _compute_run_status(total_count=3, success_count=1, failed_count=0) == "partial_failed"
assert _compute_run_status(total_count=3, success_count=3, failed_count=0) == "success"
assert _compute_run_status(total_count=3, success_count=0, failed_count=3) == "failed"
+ assert _compute_run_status(total_count=3, success_count=1, skipped_count=2, failed_count=0) == "success"
+ assert _compute_run_status(total_count=2, success_count=0, skipped_count=2, failed_count=0) == "success"
def test_build_finalize_details_marks_missing_callback_as_failed():
@@ -476,6 +461,34 @@ def test_build_finalize_details_marks_missing_callback_as_failed():
assert any(item.get("warehouse_id") == "WH2" for item in missing)
+def test_build_finalize_details_marks_skipped_as_handled():
+ """RPA 回调 skipped 表示已处理但无库存,不应被补成 failed。"""
+ pending = [
+ {"source_code": "SRC_A", "warehouse_id": "WH1", "display_name": "A1"},
+ {"source_code": "SRC_A", "warehouse_id": "WH2", "display_name": "A2"},
+ ]
+ details = _build_finalize_details(
+ pending,
+ created=[],
+ failed=[],
+ skipped=[{
+ "source_code": "SRC_A",
+ "warehouse_id": "WH1",
+ "skip_reason": "no_inventory_data",
+ "message": "DSV report has no inventory data",
+ }],
+ )
+
+ assert len(details) == 2
+ skipped = [item for item in details if item.get("export_status") == "skipped"]
+ failed = [item for item in details if item.get("export_status") == "failed"]
+ assert len(skipped) == 1
+ assert skipped[0]["warehouse_id"] == "WH1"
+ assert skipped[0]["skip_reason"] == "no_inventory_data"
+ assert len(failed) == 1
+ assert failed[0]["warehouse_id"] == "WH2"
+
+
def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
"""回调结果少于触发源数时,排程应 partial_failed。"""
drop_dir = tmp_path / "drop"
@@ -484,16 +497,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_partial.xlsx"
- try:
- from openpyxl import Workbook
-
- wb = Workbook()
- ws = wb.active
- ws.append(["料号", "可用数量"])
- ws.append(["A001", 1])
- wb.save(sample)
- except ImportError:
- sample.write_bytes(b"placeholder")
+ _write_sample_inventory(sample, "AWSDU")
with app.app_context():
task = _make_inventory_schedule_task(
@@ -509,9 +513,9 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
response_summary_json={
"awaiting_rpa": True,
"pending_details": [
- {"source_code": "SRC_A", "warehouse_id": "WH1", "display_name": "A1"},
- {"source_code": "SRC_A", "warehouse_id": "WH2", "display_name": "A2"},
- {"source_code": "SRC_B", "warehouse_id": "WH3", "display_name": "B1"},
+ {"source_code": "DSV360_AWSDU", "warehouse_id": "AWSDU", "display_name": "Dublin"},
+ {"source_code": "DSV360_AWSCV", "warehouse_id": "AWSCV", "display_name": "CV"},
+ {"source_code": "DSV360_AWSAMS", "warehouse_id": "RTM", "display_name": "AMS"},
],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
@@ -519,22 +523,85 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
db.session.add(run)
db.session.commit()
- rpa_report_inventory_batch({
+ result = rpa_report_inventory_batch({
+ "run_no": run.run_no,
+ "schedule_run_id": run.id,
+ "trigger_type": "scheduled",
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSDU",
+ success=True,
+ file_path=str(sample),
+ )],
+ })
+
+ db.session.refresh(run)
+ assert result["status"] == "ok"
+ assert result["result_status"] == "partial_failed"
+ assert result["data"]["result_status"] == "partial_failed"
+ assert result["data"]["callback_result_status"] == "success"
+ assert result["success_count"] == 1
+ assert result["failed_count"] == 2
+ assert run.status == "partial_failed"
+ assert run.success_count == 1
+ assert run.failed_count == 2
+
+
+def test_finalize_inventory_rpa_schedule_run_with_skipped_callback(app):
+ """库存为 0 的 skipped 回调应计入 skipped_count,排程不应失败。"""
+ with app.app_context():
+ task = _make_inventory_schedule_task(
+ schedule_no="SCH-INV-SKIPPED",
+ username="schedule_inv_skipped_user",
+ )
+ run = ScheduleRun(
+ run_no="RUN20260709080400",
+ schedule_task_id=task.id,
+ status="running",
+ started_at=datetime.utcnow(),
+ total_count=1,
+ response_summary_json={
+ "awaiting_rpa": True,
+ "pending_details": [{
+ "source_code": "DSV360_AWSBI_BYAWSATL01",
+ "warehouse_id": "BYAWSATL01",
+ "display_name": "ATL01",
+ }],
+ },
+ step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
+ )
+ db.session.add(run)
+ db.session.commit()
+
+ result = rpa_report_inventory_batch({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
- "source_code": "SRC_A",
- "warehouse_id": "WH1",
- "success": True,
- "file_path": str(sample),
+ "source_code": "DSV360_AWSBI_BYAWSATL01",
+ "warehouse_id": "BYAWSATL01",
+ "status": "skipped",
+ "skip_reason": "no_inventory_data",
+ "message": "DSV report has no inventory data",
}],
})
db.session.refresh(run)
- assert run.status == "partial_failed"
- assert run.success_count == 1
- assert run.failed_count == 2
+ assert result["status"] == "ok"
+ assert result["result_status"] == "success"
+ assert result["data"]["result_status"] == "success"
+ assert result["data"]["callback_result_status"] == "success"
+ assert result["skipped_count"] == 1
+ assert run.status == "success"
+ assert run.success_count == 0
+ assert run.skipped_count == 1
+ assert run.failed_count == 0
+ summary = run.response_summary_json or {}
+ assert summary.get("skipped_count") == 1
+ assert summary.get("success_count") == 0
+ assert summary.get("failed_count") == 0
+ assert summary.get("total_count") == 1
+ assert summary.get("rpa_finalize", {}).get("skipped_count") == 1
+ assert (run.api_response_json or {}).get("skipped")[0]["skip_reason"] == "no_inventory_data"
def test_is_awaiting_rpa_schedule_run_helper(app):
@@ -608,3 +675,227 @@ def test_filter_sources_by_match_aliases(app):
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
+
+
+def test_build_schedule_run_wecom_description_includes_skipped_count():
+ """企微排程通知正文应包含 skipped_count,与管理端统计口径一致。"""
+ from types import SimpleNamespace
+
+ from app.services.schedule.scheduler_service import _build_schedule_run_wecom_description
+
+ run = SimpleNamespace(
+ run_no="RUN202607100846103654",
+ status="success",
+ total_count=3,
+ success_count=2,
+ skipped_count=1,
+ failed_count=0,
+ response_summary_json=None,
+ )
+ text = _build_schedule_run_wecom_description(run)
+ assert "跳过: 1" in text
+ assert "成功: 2" in text
+ assert "失败: 0" in text
+
+
+def test_schedule_batch_rejects_mismatched_run_no(app, tmp_path):
+ """定时 batch 回调 run_no 与排程 run 不一致时必须拒绝终态化。"""
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+
+ with app.app_context():
+ task = _make_inventory_schedule_task(
+ schedule_no="SCH-INV-RUNNO-MISMATCH",
+ username="schedule_runno_mismatch_user",
+ )
+ run = ScheduleRun(
+ run_no="RUN-EXPECTED",
+ schedule_task_id=task.id,
+ status="running",
+ started_at=datetime.utcnow(),
+ total_count=1,
+ response_summary_json={"awaiting_rpa": True, "pending_details": []},
+ step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
+ )
+ db.session.add(run)
+ db.session.commit()
+
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-WRONG",
+ "schedule_run_id": run.id,
+ "trigger_type": "scheduled",
+ "results": [],
+ })
+ db.session.refresh(run)
+
+ assert result["status"] == "failed"
+ assert (result.get("data") or {}).get("schedule_run_error") == "schedule_run_no_mismatch"
+ assert run.status == "running"
+
+
+def test_scheduled_batch_success_rejects_missing_site_id(app, tmp_path):
+ """定时 batch 成功项缺少 site_id 时必须拒绝,不得仅靠 source_code 入库。"""
+ from app.models import ShippingInventoryFile
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "missing_site.xlsx"
+ _write_sample_inventory(sample, "BYAWSATL01")
+
+ with app.app_context():
+ before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-MISSING-SITE",
+ "trigger_type": "scheduled",
+ "results": [{
+ "source_code": "DSV360_AWSBI_BYAWSATL01",
+ "warehouse_id": "BYAWSATL01",
+ "success": True,
+ "file_path": str(sample),
+ }],
+ })
+ after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
+
+ assert result["status"] == "ok"
+ assert result["failed_count"] == 1
+ assert result["data"]["failed"][0]["error"] == "site_id_missing"
+ assert after == before
+
+
+def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkeypatch):
+ """finalize 失败重试同一回调时不得重复创建 ready 快照。"""
+ from app.models import ShippingInventoryFile
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "retry_snapshot.xlsx"
+ _write_sample_inventory(sample, "BYAWSATL01")
+
+ def _boom(*_args, **_kwargs):
+ raise RuntimeError("finalize exploded")
+
+ monkeypatch.setattr(
+ "app.services.schedule.shipping_inventory_rpa_finalize._build_finalize_details",
+ _boom,
+ )
+
+ with app.app_context():
+ task = _make_inventory_schedule_task(
+ schedule_no="SCH-INV-RETRY-SNAPSHOT",
+ username="schedule_inv_retry_snapshot_user",
+ api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
+ )
+ run = ScheduleRun(
+ run_no="RUN20260713163000",
+ schedule_task_id=task.id,
+ status="running",
+ started_at=datetime.utcnow(),
+ total_count=1,
+ response_summary_json={"awaiting_rpa": True, "pending_details": []},
+ step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
+ )
+ db.session.add(run)
+ db.session.commit()
+
+ payload = {
+ "run_no": run.run_no,
+ "schedule_run_id": run.id,
+ "trigger_type": "scheduled",
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSBI_BYAWSATL01",
+ success=True,
+ file_path=str(sample),
+ )],
+ }
+ first = rpa_report_inventory_batch(payload)
+ second = rpa_report_inventory_batch(payload)
+ count = ShippingInventoryFile.query.filter_by(
+ rpa_run_no=run.run_no,
+ source_code="DSV360_AWSBI_BYAWSATL01",
+ site_id="AWSBI",
+ warehouse_id="BYAWSATL01",
+ snapshot_status="ready",
+ ).count()
+
+ assert first["data"]["schedule_finalize_status"] == "failed"
+ assert second["data"]["schedule_finalize_status"] == "failed"
+ assert count == 1
+ assert second["data"]["created"][0].get("reused_existing_snapshot") is True
+
+
+def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, monkeypatch):
+ """finalize 首次失败、重试成功后应归档 callback 原文件。"""
+ from app.models import ShippingInventoryFile
+ from app.services.schedule import shipping_inventory_rpa_finalize as finalize_mod
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "retry_move.xlsx"
+ _write_sample_inventory(sample, "BYAWSATL01")
+ processed_dir = drop_dir / "processed"
+
+ original_finalize = finalize_mod.finalize_shipping_inventory_schedule_run
+ state = {"calls": 0}
+
+ def _finalize_fail_once(schedule_run_id, **kwargs):
+ state["calls"] += 1
+ if state["calls"] == 1:
+ return {
+ "ok": False,
+ "error": "finalize exploded",
+ "schedule_finalize_status": "failed",
+ "manual_retryable": True,
+ }
+ return original_finalize(schedule_run_id, **kwargs)
+
+ monkeypatch.setattr(
+ finalize_mod,
+ "finalize_shipping_inventory_schedule_run",
+ _finalize_fail_once,
+ )
+
+ with app.app_context():
+ task = _make_inventory_schedule_task(
+ schedule_no="SCH-INV-RETRY-MOVE",
+ username="schedule_inv_retry_move_user",
+ api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
+ )
+ run = ScheduleRun(
+ run_no="RUN20260713170000",
+ schedule_task_id=task.id,
+ status="running",
+ started_at=datetime.utcnow(),
+ total_count=1,
+ response_summary_json={"awaiting_rpa": True, "pending_details": []},
+ step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
+ )
+ db.session.add(run)
+ db.session.commit()
+
+ payload = {
+ "run_no": run.run_no,
+ "schedule_run_id": run.id,
+ "trigger_type": "scheduled",
+ "results": [scheduled_rpa_batch_item(
+ "DSV360_AWSBI_BYAWSATL01",
+ success=True,
+ file_path=str(sample),
+ )],
+ }
+ first = rpa_report_inventory_batch(payload)
+ assert first["data"]["schedule_finalize_status"] == "failed"
+ assert sample.is_file()
+
+ second = rpa_report_inventory_batch(payload)
+ assert second["data"]["schedule_finalize_status"] == "ok"
+ assert second["data"]["created"][0].get("reused_existing_snapshot") is True
+ assert not sample.is_file()
+ assert list(processed_dir.glob("retry_move.xlsx"))
+ assert ShippingInventoryFile.query.filter_by(
+ rpa_run_no=run.run_no,
+ snapshot_status="ready",
+ ).count() == 1
diff --git a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py b/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py
index 7dc0c76c..915dbb5b 100644
--- a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py
+++ b/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
from pathlib import Path
from app import db
-from app.models import ShippingInventoryFile, ShippingTask
+from app.models import ShippingTask
from app.services.shipping_notice.inventory_snapshot_store import (
create_inventory_snapshot_from_rpa,
find_latest_ready_snapshot,
@@ -15,19 +15,45 @@ from app.services.shipping_notice.inventory_snapshot_store import (
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
+from tests.conftest import inventory_xlsx_with_warehouse, seed_task_inventory_source
+
+
+def _write_inventory_xlsx(path: Path, warehouse_id: str, *, sku: str = "A001", qty: int = 10) -> None:
+ with open(path, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse(warehouse_id, sku=sku, qty=qty).getvalue())
+
+
+def _task_with_inventory_source(
+ task_no: str,
+ *,
+ source_code: str,
+ source_type: str | None = None,
+ site_id: str | None = None,
+ warehouse_id: str = "",
+) -> ShippingTask:
+ """构造已通过库存源门禁的任务,供快照关联测试使用。"""
+ task = ShippingTask(
+ task_no=task_no,
+ source_type="manual",
+ process_status="parsed",
+ )
+ seed_task_inventory_source(task, source_code=source_code)
+ if site_id:
+ task.inventory_site_id = site_id
+ if warehouse_id:
+ task.inventory_warehouse_id = warehouse_id
+ if source_type:
+ task.inventory_source_type = source_type
+ return task
+
+
def test_fresh_snapshot_is_reused(app, tmp_path):
- """未过期 ready 快照应被 find_latest_ready_snapshot 命中。"""
+ """未过期 ready 快照应被 find_latest_ready_snapshot 按 source+site 命中。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 24
- from openpyxl import Workbook
-
xlsx = tmp_path / "stock.xlsx"
- wb = Workbook()
- wb.active.append(["sku", "qty"])
- wb.active.append(["A001", 10])
- wb.save(xlsx)
- wb.close()
+ _write_inventory_xlsx(xlsx, "AWSDU")
source = build_rpa_inventory_source("DSV360_AWSDU")
assert source is not None
@@ -40,24 +66,19 @@ def test_fresh_snapshot_is_reused(app, tmp_path):
success=True,
)
db.session.commit()
- found = find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU")
+ found = find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU")
assert found is not None
assert found.inventory_file_no == inv.inventory_file_no
+ assert found.site_id == "AWSDU"
assert is_snapshot_fresh(found)
-def test_snapshot_uses_site_id_as_matching_warehouse(app, tmp_path):
- """DSV 子仓导出入库后,应用 site_id 作为库存匹配与发货 Excel 的 warehouse id。"""
+def test_snapshot_separates_site_id_and_warehouse_id(app, tmp_path):
+ """DSV 子仓快照应分别落库 site_id 与 warehouse_id,禁止混用。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
- from openpyxl import Workbook
-
xlsx = tmp_path / "stock.xlsx"
- wb = Workbook()
- wb.active.append(["sku", "qty"])
- wb.active.append(["A001", 10])
- wb.save(xlsx)
- wb.close()
+ _write_inventory_xlsx(xlsx, "BYAWSATL01")
source = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01")
assert source is not None
@@ -66,26 +87,36 @@ def test_snapshot_uses_site_id_as_matching_warehouse(app, tmp_path):
with app.app_context():
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
- task = ShippingTask(task_no="SN-SNAPSHOT-SITE", source_type="manual", process_status="waiting_inventory")
+ task = _task_with_inventory_source(
+ "SN-SNAPSHOT-SITE",
+ source_code="DSV360_AWSBI_BYAWSATL01",
+ source_type="dsv360",
+ site_id="AWSBI",
+ warehouse_id="BYAWSATL01",
+ )
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="reuse_latest")
db.session.commit()
- assert inv.warehouse_id == "AWSBI"
+ assert inv.site_id == "AWSBI"
+ assert inv.warehouse_id == "BYAWSATL01"
assert (inv.source_query_json or {}).get("export_warehouse_id") == "BYAWSATL01"
- assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI") is not None
- assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "BYAWSATL01") is None
+ assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01") is not None
+ assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01_WRONG") is None
assert link is not None
- assert link.matched_warehouse_id == "AWSBI"
+ assert link.matched_site_id == "AWSBI"
+ assert link.matched_warehouse_id == "BYAWSATL01"
-def test_snapshot_without_site_id_uses_inventory_excel_warehouse_id(app, tmp_path):
- """无配置 site_id 时,快照 warehouse_id 应取库存 Excel 内的 Warehouse ID。"""
+def test_crane_runtime_source_carries_dynamic_warehouse(app, tmp_path):
+ """Crane 运行时 RPA source 应携带任务动态库位 TZR2。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
from openpyxl import Workbook
+ from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
+
xlsx = tmp_path / "crane_stock.xlsx"
wb = Workbook()
wb.active.append(["Warehouse ID", "sku", "qty"])
@@ -93,41 +124,69 @@ def test_snapshot_without_site_id_uses_inventory_excel_warehouse_id(app, tmp_pat
wb.save(xlsx)
wb.close()
- source = {
- "source_code": "CRANE",
- "source_type": "crane_footprint",
- "site_id": "",
- "warehouse_id": "",
- }
-
with app.app_context():
- inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
- task = ShippingTask(task_no="SN-SNAPSHOT-EXCEL-WH", source_type="manual", process_status="waiting_inventory")
+ task = ShippingTask(
+ task_no="SN-SNAPSHOT-CRANE-RUNTIME",
+ source_type="manual",
+ process_status="parsed",
+ ship_to="TZR2 footprint",
+ )
+ seed_task_inventory_source(task, source_code="CRANE")
+ runtime_source = build_task_rpa_inventory_source(task)
+ assert runtime_source is not None
+ assert runtime_source["site_id"] == "CRANE"
+ assert runtime_source["warehouse_id"] == "TZR2"
+ assert runtime_source["query"]["warehouse_code"] == "TZR2"
+
+ inv = create_inventory_snapshot_from_rpa(
+ source=runtime_source,
+ local_path=xlsx,
+ trigger_type="on_demand",
+ success=True,
+ )
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="rpa_callback")
db.session.commit()
assert inv.warehouse_id == "TZR2"
- assert (inv.source_query_json or {}).get("site_id") is None
- assert (inv.source_query_json or {}).get("excel_warehouse_id") == "TZR2"
- assert (inv.source_query_json or {}).get("warehouse_id_source") == "inventory_excel"
+ assert (inv.source_query_json or {}).get("warehouse_id_source") == "task_identity_excel_verified"
+ assert (inv.source_query_json or {}).get("excel_warehouse_verified") is True
assert link is not None
assert link.matched_warehouse_id == "TZR2"
+def test_different_inventory_source_cannot_reuse_snapshot(app, tmp_path):
+ """相同 SKU 但库存源不同不能复用快照。"""
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
+
+ xlsx = tmp_path / "stock.xlsx"
+ _write_inventory_xlsx(xlsx, "AWSDU")
+
+ with app.app_context():
+ source = build_rpa_inventory_source("DSV360_AWSDU")
+ inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
+ task = _task_with_inventory_source(
+ "SN-SNAPSHOT-MISMATCH",
+ source_code="DSV360_AWSAMS",
+ source_type="dsv360",
+ site_id="AWSAMS",
+ )
+ db.session.add(task)
+ db.session.flush()
+ link = link_snapshot_to_task(task, inv, reason="reuse_latest")
+ db.session.commit()
+ assert link is None
+ assert inv.identity_status == "mismatch"
+
+
def test_expired_snapshot_not_reused(app, tmp_path):
"""过期快照不应被 find_latest_ready_snapshot 返回。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 1
- from openpyxl import Workbook
-
xlsx = tmp_path / "stock.xlsx"
- wb = Workbook()
- wb.active.append(["sku", "qty"])
- wb.save(xlsx)
- wb.close()
+ _write_inventory_xlsx(xlsx, "AWSDU")
source = build_rpa_inventory_source("DSV360_AWSDU")
with app.app_context():
@@ -136,23 +195,23 @@ def test_expired_snapshot_not_reused(app, tmp_path):
inv.expires_at = snapshot_expires_at(inv.exported_at)
db.session.commit()
assert not is_snapshot_fresh(inv)
- assert find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU") is None
+ assert find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU") is None
def test_link_snapshot_writes_audit_fields(app, tmp_path):
"""任务与快照 link 应写入 link_reason 与 audit_payload。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
- from openpyxl import Workbook
-
xlsx = tmp_path / "stock.xlsx"
- wb = Workbook()
- wb.active.append(["sku", "qty"])
- wb.save(xlsx)
- wb.close()
+ _write_inventory_xlsx(xlsx, "AWSDU")
with app.app_context():
- task = ShippingTask(task_no="SN-SNAPSHOT-LINK", source_type="manual", process_status="waiting_inventory")
+ task = _task_with_inventory_source(
+ "SN-SNAPSHOT-LINK",
+ source_code="DSV360_AWSDU",
+ source_type="dsv360",
+ site_id="AWSDU",
+ )
db.session.add(task)
db.session.commit()
@@ -163,5 +222,6 @@ def test_link_snapshot_writes_audit_fields(app, tmp_path):
assert link is not None
assert link.link_reason == "reuse_latest"
- assert link.matched_warehouse_id == "AWSDU"
+ assert link.matched_site_id == "AWSDU"
+ assert link.matched_source_code == "DSV360_AWSDU"
assert link.audit_payload_json["source_code"] == "DSV360_AWSDU"
diff --git a/backend/tests/test_shipping_notice_inventory_source_gate.py b/backend/tests/test_shipping_notice_inventory_source_gate.py
new file mode 100644
index 00000000..01034add
--- /dev/null
+++ b/backend/tests/test_shipping_notice_inventory_source_gate.py
@@ -0,0 +1,1184 @@
+"""
+tests/test_shipping_notice_inventory_source_gate.py
+
+用途:库存源门禁专项测试,覆盖 confirm_parse 绕过、RPA 回调拒绝、身份不匹配等核心分支。
+"""
+
+from __future__ import annotations
+
+from io import BytesIO
+
+import pytest
+from openpyxl import Workbook
+
+from app import db
+from app.models import ShippingBatch, ShippingInventoryFile, ShippingTask, ShippingTaskInventoryLink
+from app.services.shipping_notice.constants import PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF
+from app.services.shipping_notice.decision_workflow import submit_decision
+from app.services.shipping_notice.inventory_rpa_workflow import confirm_inventory_source, rpa_report_inventory
+from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
+from app.services.shipping_notice.inventory_source_rules import (
+ adjudicate_inventory_source,
+ confirm_inventory_source_by_code,
+)
+from app.services.shipping_notice.inventory_workflow import (
+ apply_inventory_mapping,
+ get_inventory_schema_preview,
+ parse_inventory,
+ upload_inventory_file,
+)
+from tests.conftest import (
+ inventory_csv_with_warehouse,
+ inventory_xlsx_with_warehouse,
+ rpa_callback_payload,
+ seed_rpa_inventory_trigger,
+ seed_task_inventory_source,
+)
+
+
+def _minimal_inventory_xlsx(*, warehouse_id: str = "AWSDU") -> BytesIO:
+ return inventory_xlsx_with_warehouse(warehouse_id)
+
+
+class _FakeUpload:
+ def __init__(self, buf: BytesIO, filename: str = "inventory.xlsx"):
+ self._buf = buf
+ self.filename = filename
+
+ def save(self, path: str) -> None:
+ with open(path, "wb") as handle:
+ handle.write(self._buf.getvalue())
+
+
+@pytest.mark.inventory_source_gate
+def test_confirm_parse_blocked_when_inventory_source_unstable(app):
+ """普通 confirm_parse 不得绕过库存源门禁。"""
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-CONFIRM-PARSE",
+ source_type="pdf",
+ process_status="pending_review",
+ review_status="parse_review",
+ pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"})
+ db.session.refresh(task)
+
+ assert result["status"] == "needs_human"
+ assert task.process_status == "pending_review"
+ assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
+
+
+@pytest.mark.inventory_source_gate
+def test_rpa_callback_rejected_when_inventory_source_unstable(app, tmp_path):
+ """RPA 单任务回调在库存源未稳定时必须拒绝入库。"""
+ inventory_drop = tmp_path / "drop"
+ inventory_drop.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop)
+ sample = inventory_drop / "inventory_gate.xlsx"
+ sample.write_bytes(b"PK\x03\x04")
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-RPA-CB",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory({
+ "task_id": task.task_no,
+ "status": "success",
+ "file_path": str(sample),
+ "source_code": "DSV360_AWSDU",
+ "site_id": "AWSDU",
+ "warehouse_id": "AWSDU",
+ "run_no": "RUN-STALE",
+ })
+ assert result["status"] == "failed"
+ assert task.inventory_lines_json is None
+
+
+@pytest.mark.inventory_source_gate
+def test_rpa_callback_rejects_mismatched_source_code(app, tmp_path):
+ """RPA 回调 source_code 与任务不一致时必须拒绝。"""
+ inventory_drop = tmp_path / "drop"
+ inventory_drop.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop)
+ sample = inventory_drop / "inventory_mismatch.xlsx"
+ sample.write_bytes(b"PK\x03\x04")
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-RPA-MISMATCH",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ ship_to="Dublin",
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-MISMATCH")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory(rpa_callback_payload(
+ task,
+ sample,
+ run_no="RUN-MISMATCH",
+ ) | {"source_code": "DSV360_AWSBI"})
+ assert result["status"] == "failed"
+
+
+def test_confirm_inventory_source_tool_route_exists(app, client):
+ """OpenAPI 声明的 confirm_inventory_source 路由必须可访问。"""
+ with app.app_context():
+ app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
+ app.config["INTEGRATION_API_KEY"] = "test-integration-key"
+ task = ShippingTask(
+ task_no="SN-ROUTE-CONFIRM-SRC",
+ source_type="pdf",
+ process_status="pending_review",
+ pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ res = client.post(
+ "/api/shipping-notice/tools/confirm_inventory_source",
+ headers={
+ "Content-Type": "application/json",
+ "X-Integration-Key": "test-integration-key",
+ },
+ json={"task_id": "SN-ROUTE-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
+ )
+ assert res.status_code == 200
+ body = res.get_json()
+ assert body["status"] in {"ok", "needs_human", "running"}
+
+
+@pytest.mark.inventory_source_gate
+def test_crane_task_rpa_source_includes_dynamic_warehouse(app):
+ """Crane 任务级 RPA source 必须携带动态库位。"""
+ from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-CRANE-RPA-SRC",
+ source_type="pdf",
+ process_status="parsed",
+ ship_to="TZR2",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="CRANE")
+ db.session.add(task)
+ db.session.commit()
+
+ source = task_rpa_inventory_source(task)
+ assert source is not None
+ assert source["warehouse_id"] == "TZR2"
+ assert source["site_id"] == "CRANE"
+ assert source["query"]["warehouse_code"] == "TZR2"
+
+
+@pytest.mark.inventory_source_gate
+def test_confirm_inventory_source_records_user_id(app, tmp_path, monkeypatch):
+ """人工确认应记录真实 user_id,且与 RPA 触发解耦。"""
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
+ lambda *args, **kwargs: None,
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled",
+ lambda: False,
+ )
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-USER-CONFIRM",
+ source_type="pdf",
+ process_status="pending_review",
+ pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ step_payload_json={
+ "inventory_source_resolution": {
+ "status": "unresolved",
+ "candidates": [{"source_code": "DSV360_AWSDU", "display_name": "Dublin"}],
+ }
+ },
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ result = confirm_inventory_source({
+ "task_id": task.task_no,
+ "source_code": "DSV360_AWSDU",
+ "_trusted_user_id": 42,
+ })
+ db.session.refresh(task)
+
+ assert result["status"] == "ok"
+ assert task.inventory_source_status == "user_confirmed"
+ assert task.inventory_source_confirmed_by == 42
+ assert task.inventory_source_confirmed_at is not None
+ assert is_inventory_source_stable(task)
+
+
+@pytest.mark.inventory_source_gate
+def test_config_version_change_invalidates_stable_source(app):
+ """配置版本变化后,旧确认不得继续视为稳定。"""
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-CFG-VER",
+ source_type="pdf",
+ process_status="parsed",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ task.inventory_source_config_version = "stale-version"
+ db.session.add(task)
+ db.session.commit()
+
+ assert not is_inventory_source_stable(task)
+
+
+@pytest.mark.inventory_source_gate
+def test_inventory_tools_blocked_without_stable_source(app, tmp_path):
+ """upload/parse/preview/mapping 在库存源未稳定时不得推进库存阶段。"""
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-INV-TOOLS",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ upload_result = upload_inventory_file(task.task_no, _FakeUpload(_minimal_inventory_xlsx()))
+ assert upload_result["status"] == "needs_human"
+
+ parse_result = parse_inventory({"task_id": task.task_no, "use_uploaded_file": True})
+ assert parse_result["status"] == "needs_human"
+
+ preview_result = get_inventory_schema_preview({"task_id": task.task_no})
+ assert preview_result["status"] == "needs_human"
+
+ mapping_result = apply_inventory_mapping({
+ "task_id": task.task_no,
+ "map_json": {"sku": "SKU", "qty": "Qty"},
+ })
+ assert mapping_result["status"] == "needs_human"
+ assert ShippingInventoryFile.query.count() == 0
+
+
+@pytest.mark.inventory_source_gate
+def test_user_can_confirm_candidate_not_in_auto_top_match(app):
+ """自动未命中时,用户仍可选择启用配置中的正式库存源。"""
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-USER-PICK",
+ source_type="pdf",
+ process_status="pending_review",
+ pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
+ ship_to="UnknownCity",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ step_payload_json={
+ "inventory_source_resolution": {
+ "status": "unresolved",
+ "candidates": [{"source_code": "DSV360_AWSDU"}],
+ }
+ },
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ adjudication = confirm_inventory_source_by_code(task, "DSV360_AWSCV")
+ assert adjudication.status == "user_confirmed"
+ assert adjudication.source_code == "DSV360_AWSCV"
+
+
+@pytest.mark.inventory_source_gate
+def test_site_level_source_requires_explicit_warehouse_id(app):
+ """站点级 DSV 须在配置与任务上同时具备 warehouse_id 才视为稳定。"""
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-SITE-WH",
+ source_type="pdf",
+ process_status="parsed",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ assert task.inventory_warehouse_id == "AWSDU"
+ db.session.add(task)
+ db.session.commit()
+
+ assert is_inventory_source_stable(task)
+
+ task.inventory_warehouse_id = None
+ db.session.commit()
+ assert not is_inventory_source_stable(task)
+
+
+@pytest.mark.inventory_source_gate
+def test_legacy_without_routing_fingerprint_is_not_stable(app):
+ """无路由指纹的历史确认不得绕过门禁。"""
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-NO-FP",
+ source_type="pdf",
+ process_status="parsed",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ task.inventory_routing_fingerprint = None
+ db.session.add(task)
+ db.session.commit()
+
+ assert not is_inventory_source_stable(task)
+
+
+@pytest.mark.inventory_source_gate
+def test_missing_warehouse_when_config_requires_it_is_not_stable(app):
+ """子仓级库存源配置要求 warehouse_id 时,任务缺库位不得视为稳定。"""
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-NO-WH",
+ source_type="pdf",
+ process_status="parsed",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSBI_BYAWSATL01")
+ task.inventory_warehouse_id = None
+ db.session.add(task)
+ db.session.commit()
+
+ assert not is_inventory_source_stable(task)
+
+
+@pytest.mark.inventory_source_gate
+def test_rpa_callback_leaves_no_snapshot_when_identity_rejected(app, tmp_path):
+ """身份不一致时不得遗留 ready 库存快照。"""
+ inventory_drop = tmp_path / "drop"
+ inventory_drop.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop)
+ sample = inventory_drop / "inventory_orphan.xlsx"
+ sample.write_bytes(b"PK\x03\x04")
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-RPA-ORPHAN",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ ship_to="Dublin",
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-ORPHAN")
+ db.session.add(task)
+ db.session.commit()
+ before = ShippingInventoryFile.query.count()
+
+ result = rpa_report_inventory(rpa_callback_payload(
+ task,
+ sample,
+ run_no="RUN-ORPHAN",
+ ) | {"source_code": "DSV360_AWSBI"})
+ after = ShippingInventoryFile.query.count()
+
+ assert result["status"] == "failed"
+ assert after == before
+
+
+@pytest.mark.inventory_source_gate
+def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path):
+ """批次上传只绑定与上传票库存源一致的任务,禁止跨源共用快照。"""
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
+
+ with app.app_context():
+ batch = ShippingBatch(batch_no="SB-GATE-CROSS", file_count=2)
+ owner = ShippingTask(
+ task_no="SN-GATE-OWNER",
+ batch=batch,
+ source_type="manual",
+ process_status="waiting_inventory",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ batch_index=1,
+ batch_total=2,
+ )
+ other = ShippingTask(
+ task_no="SN-GATE-OTHER",
+ batch=batch,
+ source_type="manual",
+ process_status="waiting_inventory",
+ lines_json=[{"sku": "B001", "qty": 1}],
+ batch_index=2,
+ batch_total=2,
+ )
+ seed_task_inventory_source(owner, source_code="DSV360_AWSDU")
+ seed_task_inventory_source(other, source_code="DSV360_AWSAMS")
+ db.session.add_all([batch, owner, other])
+ db.session.commit()
+
+ result = upload_inventory_file(owner.task_no, _FakeUpload(_minimal_inventory_xlsx()))
+ assert result["status"] == "ok"
+
+ owner_links = ShippingTaskInventoryLink.query.filter_by(task_id=owner.id, is_active=True).count()
+ other_links = ShippingTaskInventoryLink.query.filter_by(task_id=other.id, is_active=True).count()
+ assert owner_links == 1
+ assert other_links == 0
+
+
+@pytest.mark.inventory_source_gate
+def test_crane_auto_adjudication_resolves_warehouse_from_alias(app):
+ """Crane 自动裁决应解析出库位并满足四元组稳定条件。"""
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-CRANE-AUTO",
+ source_type="pdf",
+ process_status="parsed",
+ ship_to="TZR2 footprint",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ adjudication = adjudicate_inventory_source(task)
+ assert adjudication.status == "resolved"
+ assert adjudication.source_code == "CRANE"
+ assert adjudication.site_id == "CRANE"
+ assert adjudication.warehouse_id == "TZR2"
+
+
+@pytest.mark.inventory_source_gate
+def test_crane_user_confirm_and_gate_stable(app):
+ """Crane 人工确认后应写入完整身份并通过门禁。"""
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-CRANE-USER",
+ source_type="pdf",
+ process_status="pending_review",
+ pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
+ ship_to="TZR3",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ adjudication = confirm_inventory_source_by_code(task, "CRANE")
+ assert adjudication.status == "user_confirmed"
+ assert adjudication.warehouse_id == "TZR3"
+
+ from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
+
+ apply_inventory_source_adjudication(task, adjudication, confirmed_by_user_id=7)
+ db.session.commit()
+ assert is_inventory_source_stable(task)
+ assert task.inventory_source_confirmed_by == 7
+
+
+@pytest.mark.inventory_source_gate
+def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch):
+ """低置信度 + 未命中库存源:先确认解析,再确认库存源,最后才能进入库存准备。"""
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
+ lambda *args, **kwargs: None,
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled",
+ lambda: False,
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.decision_workflow.start_task_orchestrator",
+ lambda task_no: False,
+ )
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-LOW-CONF-SEQ",
+ source_type="pdf",
+ process_status="pending_review",
+ pending_human_reason=PH_LOW_CONF,
+ review_status="parse_review",
+ parse_confidence=0.4,
+ ship_to="UnknownCity",
+ lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
+ inventory_source_status="unresolved",
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ parse_result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"})
+ db.session.refresh(task)
+ assert parse_result["status"] in {"ok", "needs_human"}
+ assert parse_result.get("checkpoint") == "inventory_source_review"
+ assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
+ assert not is_inventory_source_stable(task)
+ option_ids = parse_result.get("human_options") or [
+ item.get("id") for item in (parse_result.get("action_buttons") or [])
+ ]
+ assert "reparse" not in option_ids
+ assert "confirm_inventory_source" in option_ids
+
+ source_result = confirm_inventory_source({
+ "task_id": task.task_no,
+ "source_code": "DSV360_AWSDU",
+ "_trusted_user_id": 11,
+ })
+ db.session.refresh(task)
+ assert source_result["status"] in {"ok", "running"}
+ assert is_inventory_source_stable(task)
+ assert task.pending_human_reason != PH_INVENTORY_SOURCE_UNRESOLVED
+ assert task.pending_human_reason != PH_LOW_CONF
+
+
+@pytest.mark.inventory_source_gate
+def test_legacy_pending_parse_review_after_source_compat(app, monkeypatch):
+ """存量任务:先库存源后解析的延后标记仍可走完兼容路径。"""
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
+ lambda *args, **kwargs: None,
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled",
+ lambda: False,
+ )
+ monkeypatch.setattr(
+ "app.services.shipping_notice.decision_workflow.start_task_orchestrator",
+ lambda task_no: False,
+ )
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-LEGACY-PARSE-AFTER-SOURCE",
+ source_type="pdf",
+ process_status="pending_review",
+ pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
+ review_status="parse_review",
+ parse_confidence=0.4,
+ ship_to="UnknownCity",
+ lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
+ step_payload_json={"pending_parse_review_after_source": True},
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ blocked = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"})
+ assert blocked["status"] == "needs_human"
+
+ source_result = confirm_inventory_source({
+ "task_id": task.task_no,
+ "source_code": "DSV360_AWSDU",
+ "_trusted_user_id": 11,
+ })
+ db.session.refresh(task)
+ assert source_result["status"] == "needs_human"
+ assert source_result.get("checkpoint") == "parse_review"
+ assert task.pending_human_reason == PH_LOW_CONF
+ assert is_inventory_source_stable(task)
+
+ parse_result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"})
+ db.session.refresh(task)
+ assert parse_result["status"] in {"ok", "running"}
+ assert is_inventory_source_stable(task)
+ assert task.pending_human_reason != PH_INVENTORY_SOURCE_UNRESOLVED
+
+
+@pytest.mark.inventory_source_gate
+def test_parse_notice_high_confidence_unresolved_source_goes_to_source_review(app, client):
+ """高置信度解析自动通过后,库存源未命中应直接进入 inventory_source_review。"""
+ from tests.test_shipping_notice_tools import _tool_headers
+
+ headers = _tool_headers(app)
+ create_res = client.post(
+ "/api/shipping-notice/tools/create_task",
+ headers=headers,
+ json={"source_type": "manual"},
+ )
+ task_id = create_res.get_json()["task_id"]
+
+ parse_res = client.post(
+ "/api/shipping-notice/tools/parse_notice",
+ headers=headers,
+ json={
+ "task_id": task_id,
+ "structured": {
+ "customer_name": "ACME",
+ "ship_to": "Mystery Port",
+ "lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
+ "confidence": 0.95,
+ },
+ },
+ )
+ parse_data = parse_res.get_json()
+ assert parse_data["status"] == "needs_human"
+ assert parse_data.get("checkpoint") == "inventory_source_review"
+ button_ids = [item.get("id") for item in (parse_data.get("action_buttons") or [])]
+ assert "confirm_inventory_source" in button_ids
+ assert "reparse" not in button_ids
+
+ with app.app_context():
+ task = ShippingTask.query.filter_by(task_no=task_id).first()
+ assert task is not None
+ assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
+ assert not is_inventory_source_stable(task)
+
+
+@pytest.mark.inventory_source_gate
+def test_parse_notice_low_confidence_unresolved_source_goes_to_parse_review(app, client):
+ """低置信度 + 库存源未命中:应先进入 parse_review(含重新解析),而非抢先确认库存源。"""
+ from app.services.shipping_notice.state_machine import human_options_for_task
+ from tests.test_shipping_notice_tools import _tool_headers
+
+ headers = _tool_headers(app)
+ create_res = client.post(
+ "/api/shipping-notice/tools/create_task",
+ headers=headers,
+ json={"source_type": "manual"},
+ )
+ task_id = create_res.get_json()["task_id"]
+
+ parse_res = client.post(
+ "/api/shipping-notice/tools/parse_notice",
+ headers=headers,
+ json={
+ "task_id": task_id,
+ "structured": {
+ "customer_name": "ACME",
+ "ship_to": "Mystery Port",
+ "lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
+ "confidence": 0.4,
+ },
+ },
+ )
+ parse_data = parse_res.get_json()
+ assert parse_data["status"] == "needs_human"
+ assert parse_data.get("checkpoint") == "parse_review"
+ assert "重新解析" in (parse_data.get("message") or "") or "置信度" in (parse_data.get("message") or "")
+
+ with app.app_context():
+ task = ShippingTask.query.filter_by(task_no=task_id).first()
+ assert task is not None
+ assert task.pending_human_reason == PH_LOW_CONF
+ assert task.review_status == "parse_review"
+ options = human_options_for_task(task) or []
+ assert "reparse" in options
+ assert "confirm" in options
+ assert "confirm_inventory_source" not in options
+ assert "解析确认通过后" in (parse_data.get("message") or "")
+
+
+@pytest.mark.inventory_source_gate
+def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
+ """人工上传身份绑定失败时不应遗留库存文件或数据库记录。"""
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task",
+ lambda *args, **kwargs: None,
+ )
+
+ with app.app_context():
+ batch = ShippingBatch(batch_no="SB-GATE-UPLOAD-FAIL", file_count=2)
+ owner = ShippingTask(
+ task_no="SN-GATE-UPLOAD-OWNER",
+ batch=batch,
+ source_type="manual",
+ process_status="waiting_inventory",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ batch_index=1,
+ batch_total=2,
+ )
+ other = ShippingTask(
+ task_no="SN-GATE-UPLOAD-OTHER",
+ batch=batch,
+ source_type="manual",
+ process_status="waiting_inventory",
+ lines_json=[{"sku": "B001", "qty": 1}],
+ batch_index=2,
+ batch_total=2,
+ )
+ seed_task_inventory_source(owner, source_code="DSV360_AWSDU")
+ seed_task_inventory_source(other, source_code="DSV360_AWSAMS")
+ db.session.add_all([batch, owner, other])
+ db.session.commit()
+
+ before_files = ShippingInventoryFile.query.count()
+ result = upload_inventory_file(owner.task_no, _FakeUpload(_minimal_inventory_xlsx()))
+ after_files = ShippingInventoryFile.query.count()
+
+ assert result["status"] == "failed"
+ assert after_files == before_files
+ assert not list((tmp_path / "shipping").rglob("*.xlsx"))
+
+
+def _evaluate_legacy_backfill(
+ *,
+ source_code: str,
+ site_id: str | None,
+ warehouse_id: str | None,
+ resolution_status: str | None = None,
+ routing_fingerprint: str | None = None,
+) -> dict[str, str | None]:
+ """镜像迁移回填规则,供迁移专项测试断言。"""
+ status = "resolved"
+ method = "legacy_migrated"
+ code = source_code
+ if resolution_status == "ambiguous":
+ status = "ambiguous"
+ elif resolution_status == "user_confirmed":
+ status = "user_confirmed"
+ if not site_id and warehouse_id:
+ return {
+ "source_code": None,
+ "status": "unresolved",
+ "method": None,
+ "config_version": "legacy-unverified",
+ }
+ if not site_id or not warehouse_id:
+ return {
+ "source_code": None,
+ "status": "unresolved",
+ "method": None,
+ "config_version": "legacy-unverified",
+ }
+ if not routing_fingerprint:
+ return {
+ "source_code": code,
+ "status": "unresolved",
+ "method": None,
+ "config_version": "legacy-unverified",
+ }
+ return {
+ "source_code": code,
+ "status": status,
+ "method": "legacy_migrated",
+ "config_version": "legacy-unverified",
+ }
+
+
+@pytest.mark.inventory_source_gate
+def test_migration_backfill_dual_empty_identity_goes_unresolved():
+ """历史 site/warehouse 双空记录应进入 unresolved 而非 resolved。"""
+ result = _evaluate_legacy_backfill(
+ source_code="DSV360_AWSDU",
+ site_id=None,
+ warehouse_id=None,
+ )
+ assert result["status"] == "unresolved"
+ assert result["source_code"] is None
+ assert result["config_version"] == "legacy-unverified"
+
+
+@pytest.mark.inventory_source_gate
+def test_migration_backfill_without_fingerprint_requires_review():
+ """历史无路由指纹不得标记为当前配置已验证。"""
+ result = _evaluate_legacy_backfill(
+ source_code="DSV360_AWSDU",
+ site_id="AWSDU",
+ warehouse_id="AWSDU",
+ routing_fingerprint=None,
+ )
+ assert result["status"] == "unresolved"
+ assert result["config_version"] == "legacy-unverified"
+
+
+@pytest.mark.inventory_source_gate
+def test_rpa_callback_rejects_excel_warehouse_mismatch(app, tmp_path):
+ """任务库位 TZR2 但 Excel Warehouse ID=TZR3 时必须拒绝入库。"""
+ from openpyxl import Workbook
+
+ inventory_drop = tmp_path / "drop"
+ inventory_drop.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
+
+ sample = inventory_drop / "crane_wrong_wh.xlsx"
+ wb = Workbook()
+ wb.active.append(["Warehouse ID", "SKU", "Qty"])
+ wb.active.append(["TZR3", "A001", 1])
+ wb.save(sample)
+ wb.close()
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-EXCEL-WH",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ ship_to="TZR2 footprint",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="CRANE")
+ seed_rpa_inventory_trigger(task, run_no="RUN-EXCEL-WH")
+ db.session.add(task)
+ db.session.commit()
+ before = ShippingInventoryFile.query.count()
+
+ result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-EXCEL-WH"))
+ after = ShippingInventoryFile.query.count()
+
+ assert result["status"] == "failed"
+ assert after == before
+
+
+@pytest.mark.inventory_source_gate
+def test_manual_upload_rejects_wrong_excel_warehouse(app, tmp_path):
+ """人工上传错误 Warehouse ID 时必须拒绝并清理文件。"""
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-UPLOAD-WH",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ db.session.add(task)
+ db.session.commit()
+
+ result = upload_inventory_file(
+ task.task_no,
+ _FakeUpload(inventory_xlsx_with_warehouse("TZR3")),
+ )
+ assert result["status"] == "failed"
+ assert ShippingInventoryFile.query.count() == 0
+ assert not list((tmp_path / "shipping").rglob("*.xlsx"))
+
+
+@pytest.mark.inventory_source_gate
+def test_rpa_callback_rejects_mismatched_warehouse_id(app, tmp_path):
+ """单任务回调 warehouse_id 与任务不一致时必须拒绝。"""
+ inventory_drop = tmp_path / "drop"
+ inventory_drop.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop)
+ sample = inventory_drop / "inventory_wh_mismatch.xlsx"
+ with open(sample, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-RPA-WH",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-WH-MISMATCH")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory(rpa_callback_payload(
+ task,
+ sample,
+ run_no="RUN-WH-MISMATCH",
+ ) | {"warehouse_id": "TZR3"})
+ assert result["status"] == "failed"
+
+
+@pytest.mark.inventory_source_gate
+def test_rpa_callback_rejects_stale_run_no(app, tmp_path):
+ """旧 run_no 回调不得覆盖当前任务库存轮次。"""
+ inventory_drop = tmp_path / "drop"
+ inventory_drop.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop)
+ sample = inventory_drop / "inventory_stale_run.xlsx"
+ with open(sample, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-STALE-RUN",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory(rpa_callback_payload(
+ task,
+ sample,
+ run_no="RUN-OLD",
+ ))
+ assert result["status"] == "failed"
+ assert (result.get("data") or {}).get("run_no_error") == "run_no_mismatch"
+
+
+@pytest.mark.inventory_source_gate
+def test_scheduled_batch_unknown_source_creates_no_ready_snapshot(app, tmp_path):
+ """未知/禁用 source 的定时批量回调不得创建 ready 快照。"""
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "scheduled.xlsx"
+ with open(sample, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-UNKNOWN-SRC",
+ "trigger_type": "scheduled",
+ "results": [{
+ "source_code": "UNKNOWN_SOURCE",
+ "warehouse_id": "AWSDU",
+ "status": "success",
+ "success": True,
+ "file_path": str(sample),
+ }],
+ })
+ after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
+
+ assert result["status"] == "ok"
+ assert result["result_status"] == "failed"
+ assert after == before
+ assert result["data"]["failed"][0]["error"] == "unknown_or_disabled_source"
+
+
+@pytest.mark.inventory_source_gate
+def test_manual_upload_csv_preserves_suffix_and_passes_identity(app, tmp_path):
+ """CSV 上传应保留 .csv 后缀并通过 Warehouse ID 身份校验。"""
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-UPLOAD-CSV",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ db.session.add(task)
+ db.session.commit()
+
+ result = upload_inventory_file(
+ task.task_no,
+ _FakeUpload(inventory_csv_with_warehouse("AWSDU"), filename="inventory.csv"),
+ )
+ assert result["status"] != "failed"
+ csv_files = list((tmp_path / "shipping").rglob("inventory.csv"))
+ assert len(csv_files) == 1
+ assert ShippingInventoryFile.query.count() == 1
+
+
+@pytest.mark.inventory_source_gate
+def test_manual_upload_rejects_xls_extension(app, tmp_path):
+ """.xls 上传应在入口明确拒绝,而非误报 Warehouse 缺失。"""
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-UPLOAD-XLS",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ db.session.add(task)
+ db.session.commit()
+
+ result = upload_inventory_file(
+ task.task_no,
+ _FakeUpload(_minimal_inventory_xlsx(), filename="inventory.xls"),
+ )
+ assert result["status"] == "failed"
+ assert ShippingInventoryFile.query.count() == 0
+
+
+@pytest.mark.inventory_source_gate
+def test_rpa_success_rejected_without_active_trigger(app, tmp_path):
+ """无 inventory_rpa_triggered 事件时,成功回调不得入库。"""
+ inventory_drop = tmp_path / "drop"
+ inventory_drop.mkdir()
+ app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop)
+ sample = inventory_drop / "no_trigger.xlsx"
+ with open(sample, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-NO-TRIGGER",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ db.session.add(task)
+ db.session.commit()
+ before = ShippingInventoryFile.query.count()
+
+ result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-FAKE"))
+ after = ShippingInventoryFile.query.count()
+
+ assert result["status"] == "failed"
+ assert (result.get("data") or {}).get("run_no_error") == "no_active_trigger"
+ assert after == before
+
+
+@pytest.mark.inventory_source_gate
+def test_rpa_failed_rejected_stale_run_no(app, tmp_path):
+ """旧 run_no 的 failed 回调不得覆盖当前等待轮次。"""
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-STALE-FAIL",
+ source_type="pdf",
+ process_status="waiting_inventory",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1}],
+ )
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT-FAIL")
+ db.session.add(task)
+ db.session.commit()
+
+ result = rpa_report_inventory({
+ "task_id": task.task_no,
+ "status": "failed",
+ "success": False,
+ "run_no": "RUN-OLD-FAIL",
+ "error_message": "stale callback",
+ })
+ db.session.refresh(task)
+
+ assert result["status"] == "failed"
+ assert (result.get("data") or {}).get("run_no_error") == "run_no_mismatch"
+ assert task.error_message is None
+
+
+@pytest.mark.inventory_source_gate
+def test_scheduled_crane_batch_accepts_dynamic_warehouse(app, tmp_path):
+ """CRANE 动态库位定时回调应接受 Worker 回传的 TZR/TZR2/TZR3。"""
+ from app.models import ShippingInventoryFile
+ from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
+ from tests.conftest import scheduled_rpa_batch_item
+
+ drop_dir = tmp_path / "drop"
+ drop_dir.mkdir()
+ app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
+ sample = drop_dir / "crane_tzr2.xlsx"
+ with open(sample, "wb") as handle:
+ handle.write(inventory_xlsx_with_warehouse("TZR2").getvalue())
+
+ with app.app_context():
+ before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
+ result = rpa_report_inventory_batch({
+ "run_no": "RUN-CRANE-TZR2",
+ "trigger_type": "scheduled",
+ "results": [scheduled_rpa_batch_item(
+ "CRANE",
+ warehouse_id="TZR2",
+ success=True,
+ file_path=str(sample),
+ )],
+ })
+ after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
+
+ assert result["status"] == "ok"
+ assert result["success_count"] == 1
+ created = (result.get("data") or {}).get("created") or []
+ assert created and created[0].get("warehouse_id") == "TZR2"
+ assert after == before + 1
+ snap = ShippingInventoryFile.query.filter_by(
+ rpa_run_no="RUN-CRANE-TZR2",
+ source_code="CRANE",
+ warehouse_id="TZR2",
+ ).first()
+ assert snap is not None
+ assert snap.site_id == "CRANE"
+
+
+@pytest.mark.inventory_source_gate
+def test_inventory_header_skips_single_cell_warehouse_title(app, tmp_path):
+ """仅含 Warehouse 标题的单单元格行不得被误判为表头。"""
+ from io import BytesIO
+
+ from openpyxl import Workbook
+
+ from app.services.shipping_notice.inventory_file_identity import (
+ extract_warehouse_ids_from_inventory_excel,
+ )
+
+ buf = BytesIO()
+ wb = Workbook()
+ ws = wb.active
+ ws.append(["Warehouse"])
+ ws.append(["Warehouse ID", "SKU", "Qty"])
+ ws.append(["TZR2", "A001", 1])
+ wb.save(buf)
+ buf.seek(0)
+
+ path = tmp_path / "title_then_header.xlsx"
+ path.write_bytes(buf.getvalue())
+ found = extract_warehouse_ids_from_inventory_excel(path)
+ assert found == {"TZR2"}
+
+
+@pytest.mark.inventory_source_gate
+def test_conflicted_inventory_source_status_persists(app):
+ """自动裁决 conflicted 状态须能写入数据库,不被 CHECK 约束拒绝。"""
+ from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
+ from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication
+
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-GATE-CONFLICTED",
+ process_status="pending_review",
+ customer_code="TEST",
+ )
+ db.session.add(task)
+ db.session.flush()
+ apply_inventory_source_adjudication(
+ task,
+ InventorySourceAdjudication(
+ status="conflicted",
+ config_version="v1",
+ routing_fingerprint="fp-conflict",
+ candidates=[],
+ conflicts=["matched_conflicting_rules"],
+ reason="matched_conflicting_rules",
+ ),
+ )
+ db.session.commit()
+ db.session.refresh(task)
+ assert task.inventory_source_status == "conflicted"
+
+
+@pytest.mark.inventory_source_gate
+def test_csv_inventory_parse_reads_beyond_preview_limit(app, tmp_path):
+ """CSV 全量解析不得静默截断为 10,000 行。"""
+ from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel
+
+ path = tmp_path / "large.csv"
+ lines = ["Warehouse ID,SKU,Qty Available"]
+ lines.extend(f"AWSDU,SKU-{i},1" for i in range(10_050))
+ path.write_text("\n".join(lines), encoding="utf-8")
+
+ with app.app_context():
+ rows = parse_inventory_excel(path)
+ assert len(rows) == 10_050
diff --git a/backend/tests/test_shipping_notice_inventory_sources_config.py b/backend/tests/test_shipping_notice_inventory_sources_config.py
index 78c00085..d8fe37f7 100644
--- a/backend/tests/test_shipping_notice_inventory_sources_config.py
+++ b/backend/tests/test_shipping_notice_inventory_sources_config.py
@@ -21,7 +21,7 @@ def test_inventory_sources_yaml_loads(app):
assert source is not None
assert source["source_type"] == "dsv360"
assert source["site_id"] == "AWSDU"
- assert source["warehouse_id"] == ""
+ assert source["warehouse_id"] == "AWSDU"
assert source["query"]["program_label"]
@@ -100,15 +100,40 @@ sources:
reload_inventory_sources_config()
-def test_build_rpa_inventory_source_crane_has_no_site_or_warehouse_requirement(app):
- """Crane 源不要求配置 site_id/warehouse_id,导出走 Schedule Report 异步下载。"""
+def test_dsv_source_requires_warehouse_id(app, tmp_path):
+ """DSV 源必须显式配置 warehouse_id。"""
+ bad = tmp_path / "bad_sources.yaml"
+ bad.write_text(
+ """
+version: 1
+sources:
+- source_code: DSV360_BAD
+ enabled: true
+ source_type: dsv360
+ site_id: AWSBI
+ entry_url: http://x
+ navigation: {}
+ parameters: []
+ """,
+ encoding="utf-8",
+ )
+ app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad)
+ with app.app_context():
+ with pytest.raises(InventorySourceConfigError, match="warehouse_id is required"):
+ reload_inventory_sources_config()
+
+
+def test_build_rpa_inventory_source_crane_has_site_and_alias_resolution(app):
+ """Crane 源须配置 site_id 与 match_aliases,库位由订单别名解析。"""
with app.app_context():
reload_inventory_sources_config()
payload = build_rpa_inventory_source("CRANE")
assert payload is not None
assert payload["source_type"] == "crane_footprint"
- assert payload["site_id"] == ""
+ assert payload["site_id"] == "CRANE"
assert payload["warehouse_id"] == ""
+ assert payload["warehouse_resolution"] == "alias_match"
+ assert payload.get("allowed_warehouse_ids") == ["TZR", "TZR2", "TZR3"]
assert payload["parameters"] == []
assert payload["navigation"]["download_mode"] == "scheduled_report"
@@ -123,3 +148,46 @@ def test_match_aliases_available_via_list(app):
assert "CRANE" in codes
awsbi_count = sum(1 for item in list_inventory_sources() if str(item.get("source_code", "")).startswith("DSV360_AWSBI_"))
assert awsbi_count == 25
+
+
+def test_inventory_sources_cache_refreshes_when_content_changes_with_same_mtime(app, tmp_path, monkeypatch):
+ """配置内容变化但 mtime 不变时,缓存仍须刷新。"""
+ import os
+
+ from app.services.shipping_notice import inventory_sources as mod
+
+ cfg = tmp_path / "sources.yaml"
+ cfg.write_text(
+ """
+version: 1
+sources:
+- source_code: CACHE_TEST
+ enabled: true
+ source_type: dsv360
+ site_id: S1
+ warehouse_id: W1
+ entry_url: http://example.com
+ navigation: {}
+ parameters: []
+ """,
+ encoding="utf-8",
+ )
+ fixed_mtime = 1_700_000_000.0
+ os.utime(cfg, (fixed_mtime, fixed_mtime))
+ app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(cfg)
+
+ with app.app_context():
+ mod._CONFIG_CACHE = None
+ mod._CONFIG_PATH = None
+ mod._CONFIG_RAW_DIGEST = None
+ first = mod.reload_inventory_sources_config()
+ assert first["sources"]["CACHE_TEST"]["warehouse_id"] == "W1"
+
+ cfg.write_text(
+ cfg.read_text(encoding="utf-8").replace("warehouse_id: W1", "warehouse_id: W2"),
+ encoding="utf-8",
+ )
+ os.utime(cfg, (fixed_mtime, fixed_mtime))
+ second = mod.reload_inventory_sources_config()
+ assert second["sources"]["CACHE_TEST"]["warehouse_id"] == "W2"
+ assert second is not first
diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py
index c69fb56e..4e149be9 100644
--- a/backend/tests/test_shipping_notice_tools.py
+++ b/backend/tests/test_shipping_notice_tools.py
@@ -6,6 +6,7 @@ import pytest
from app import db
from app.models import ChatLog, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.match import match_notice_lines
+from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source
def _tool_headers(app):
@@ -17,6 +18,23 @@ def _tool_headers(app):
}
+def _parse_notice_for_stable_inventory_source(client, headers, task_id: str) -> None:
+ """测试辅助:写入 Dublin 目的地以触发稳定库存源裁决,供库存阶段 Tool 测试使用。"""
+ client.post(
+ "/api/shipping-notice/tools/parse_notice",
+ headers=headers,
+ json={
+ "task_id": task_id,
+ "structured": {
+ "customer_name": "AWS",
+ "ship_to": "Dublin",
+ "lines": [{"sku": "A001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
+ "confidence": 0.95,
+ },
+ },
+ )
+
+
def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client):
with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret"
@@ -389,6 +407,7 @@ def test_openapi_spec_public(app, client):
map_json_schema = apply_mapping["properties"]["map_json"]
assert map_json_schema["type"] == "string"
assert "JSON 字符串" in map_json_schema["description"]
+ assert "/tools/confirm_inventory_source" in spec["paths"]
submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"]
assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"]
spec_text = str(spec)
@@ -410,6 +429,30 @@ def test_openapi_spec_public(app, client):
assert "按钮由 HXOPS 前端渲染" in submit_desc
+def test_confirm_inventory_source_route_returns_json(app, client):
+ """confirm_inventory_source HTTP 路由必须存在且可调用。"""
+ headers = _tool_headers(app)
+ with app.app_context():
+ task = ShippingTask(
+ task_no="SN-HTTP-CONFIRM-SRC",
+ source_type="manual",
+ process_status="pending_review",
+ pending_human_reason="inventory_source_unresolved",
+ ship_to="Dublin",
+ lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
+ )
+ db.session.add(task)
+ db.session.commit()
+
+ res = client.post(
+ "/api/shipping-notice/tools/confirm_inventory_source",
+ headers=headers,
+ json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
+ )
+ assert res.status_code == 200
+ assert res.get_json()["status"] in {"ok", "needs_human", "running"}
+
+
def test_static_openapi_snapshot_contains_shipping_contract_keywords():
"""静态 OpenAPI 快照应同步最新推进约束,避免 Dify 导入旧版说明。"""
spec_path = Path(__file__).resolve().parents[2] / "docs" / "openapi" / "shipping_notice_tools.dify.json"
@@ -495,6 +538,7 @@ def test_parse_inventory_empty_needs_human(app, client):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
+ _parse_notice_for_stable_inventory_source(client, headers, task_id)
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
@@ -620,11 +664,16 @@ def test_match_inventory_requires_reservation_id(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
- "lines": [{"sku": "A001", "qty": 1, "uom": "EA"}],
+ "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
+ with app.app_context():
+ task = ShippingTask.query.filter_by(task_no=task_id).first()
+ assert task is not None
+ task.lines_json = [{"sku": "A001", "qty": 1, "uom": "EA"}]
+ db.session.commit()
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
@@ -704,20 +753,38 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
)
task_id = create_res.get_json()["task_id"]
+ from app import db
+ from tests.conftest import seed_task_inventory_source
+
+ with app.app_context():
+ task = ShippingTask.query.filter_by(task_no=task_id).first()
+ assert task is not None
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ seed_rpa_inventory_trigger(task, run_no="RUN-TOOLS-CB")
+ db.session.commit()
+
from openpyxl import Workbook
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
- ws.append(["料号", "可用数量"])
- ws.append(["A001", 20])
+ ws.append(["Warehouse ID", "料号", "可用数量"])
+ ws.append(["AWSDU", "A001", 20])
wb.save(inv_file)
wb.close()
cb_res = client.post(
"/api/shipping-notice/rpa/inventory-ready",
headers=headers,
- json={"task_no": task_id, "success": True, "file_path": str(inv_file)},
+ json={
+ "task_no": task_id,
+ "success": True,
+ "file_path": str(inv_file),
+ "run_no": "RUN-TOOLS-CB",
+ "source_code": "DSV360_AWSDU",
+ "site_id": "AWSDU",
+ "warehouse_id": "AWSDU",
+ },
)
assert cb_res.status_code == 200
data = cb_res.get_json()
@@ -890,8 +957,8 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
buf = BytesIO()
wb = Workbook()
ws = wb.active
- ws.append(["AWS Sku", "COM ID", "Qty Available"])
- ws.append(["10-40594-001", "AWS-311", 5])
+ ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
+ ws.append(["AWSDU", "10-40594-001", "AWS-311", 5])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -909,7 +976,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "map_infer"
preview = upload_data["data"]["schema_preview"]
- assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
+ assert preview["headers"] == ["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
apply_res = client.post(
@@ -941,6 +1008,7 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
from app.models import ShippingBatch, ShippingTaskInventoryLink
from app.services.shipping_notice import inventory_file_store
+ from tests.conftest import seed_task_inventory_source
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
@@ -976,15 +1044,16 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
batch_index=2,
batch_total=2,
)
+ seed_task_inventory_source(pending, source_code="DSV360_AWSDU")
db.session.add_all([batch, completed, pending])
db.session.commit()
buf = BytesIO()
wb = Workbook()
ws = wb.active
- ws.append(["SKU", "Reservation ID", "Available Qty"])
- ws.append(["A001", "R-1", 10])
- ws.append(["A002", "R-2", 10])
+ ws.append(["Warehouse ID", "SKU", "Reservation ID", "Available Qty"])
+ ws.append(["AWSDU", "A001", "R-1", 10])
+ ws.append(["AWSDU", "A002", "R-2", 10])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -1019,6 +1088,7 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
+ _parse_notice_for_stable_inventory_source(client, headers, task_id)
from io import BytesIO
@@ -1026,8 +1096,8 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
wb = Workbook()
ws = wb.active
- ws.append(["AWS Sku", "COM ID", "Qty Available"])
- ws.append(["504-010213-001", "1000140351", 5])
+ ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
+ ws.append(["AWSDU", "504-010213-001", "1000140351", 5])
buf = BytesIO()
wb.save(buf)
buf.seek(0)
@@ -1067,6 +1137,7 @@ def test_get_inventory_schema_preview(app, client, tmp_path):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
+ _parse_notice_for_stable_inventory_source(client, headers, task_id)
missing = client.post(
"/api/shipping-notice/tools/get_inventory_schema_preview",
@@ -1086,6 +1157,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
+ _parse_notice_for_stable_inventory_source(client, headers, task_id)
from io import BytesIO
@@ -1094,8 +1166,8 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
buf = BytesIO()
wb = Workbook()
ws = wb.active
- ws.append(["Part No", "Resv", "On Hand"])
- ws.append(["SKU-99", "R-1", 12])
+ ws.append(["Warehouse ID", "Part No", "Resv", "On Hand"])
+ ws.append(["AWSDU", "SKU-99", "R-1", 12])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -1143,7 +1215,8 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
- "lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
+ "ship_to": "Dublin",
+ "lines": [{"sku": "504-010213-001", "reservation_id": "R-1", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1437,7 +1510,11 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
@pytest.mark.auto_rpa
-def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp_path):
+def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp_path, monkeypatch):
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
+ lambda *args, **kwargs: None,
+ )
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
inventory_drop = tmp_path / "inventory_drop"
@@ -1478,6 +1555,8 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ task.process_status = "parsed"
db.session.commit()
retry_res = client.post(
@@ -1544,6 +1623,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(
ShippingTaskEvent(
task_id=task.id,
@@ -1568,7 +1648,11 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
@pytest.mark.auto_rpa
-def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path):
+def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path, monkeypatch):
+ monkeypatch.setattr(
+ "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
+ lambda *args, **kwargs: None,
+ )
from datetime import datetime, timedelta
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
@@ -1602,6 +1686,8 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
+ task.process_status = "parsed"
base_time = datetime.utcnow() - timedelta(minutes=5)
for idx in range(3):
db.session.add(
@@ -1681,6 +1767,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
+ seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(
ShippingTaskEvent(
task_id=task.id,
@@ -1849,6 +1936,7 @@ def test_parse_inventory_rejects_oversized_text(app, client):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
+ _parse_notice_for_stable_inventory_source(client, headers, task_id)
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
diff --git a/docker-compose.yml b/docker-compose.yml
index 7247e9c7..dbb41cd8 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -49,7 +49,9 @@ services:
- EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice}
# LibreOffice 单次格式转换超时(秒)
- EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-600}
-
+ # 固资履历:必须注入 LOCAL_ROOT,避免只加载 .env.shared 时回退到 Linux 不可达的 UNC
+ - FIXED_ASSET_HISTORY_LOCAL_ROOT=${FIXED_ASSET_HISTORY_LOCAL_ROOT:-}
+ - FIXED_ASSET_HISTORY_SHARE_ROOT=${FIXED_ASSET_HISTORY_SHARE_ROOT:-}
# 允许容器访问宿主机服务 (如数据库)
extra_hosts:
- "host.docker.internal:host-gateway"
@@ -59,6 +61,10 @@ services:
volumes:
- ./oracle_client:/app/oracle_client:ro
- hxops_runtime_data:/app/data
+ # 固资履历:宿主机先 CIFS 挂载(scripts/mount_fixed_asset_history.sh),再 bind 进容器只读。
+ # test/prod 的 FIXED_ASSET_HISTORY_LOCAL_ROOT 分别指向对应路径;未使用的一侧为空目录无影响。
+ - /mnt/hxops-fixed-asset-history-test:/mnt/hxops-fixed-asset-history-test:ro
+ - /mnt/hxops-fixed-asset-history-prod:/mnt/hxops-fixed-asset-history-prod:ro
networks:
- ai-platform
diff --git a/docs/demand.md b/docs/demand.md
index b4a2ae36..f7cd38d1 100644
--- a/docs/demand.md
+++ b/docs/demand.md
@@ -47,6 +47,22 @@
- **可靠性要求**:单次同步必须设置超时;超时或短时失败后,每隔 30 分钟自动重试 1 次,累计最多重试 3 次;若全部失败,继续保留上一版快照对外服务。
- **查询要求**:用户在 `固资管理` Agent 中发起查询时,优先查询本地快照;字段级条件优先匹配,`备注` 作为模糊检索补充;极少数无法覆盖的复杂场景可再回退实时 ERP 查询。
+### 3.x 货代发货通知库存源补充需求
+
+- **核心目标**:在订单解析阶段即确定库存查询来源(`source_code`),避免 RPA 抓错库存池;用户仅需确认来源编码,站点与仓库由系统配置生成。
+- **自动匹配**:根据发货通知目的地/港口/仓库线索与 `shipping_inventory_sources.yaml` 规则自动 adjudicate;唯一命中则 `resolved` 并继续流程。
+- **人工确认**:无法唯一命中时进入 `inventory_source_review` 检查点,用户在聊天区选择或输入线索确认 `source_code`。
+- **硬阻断**:库存源未稳定(`resolved` / `user_confirmed`)时,RPA、库存匹配、Excel 生成、货代上传均不得执行。
+- **身份校验**:关联库存快照时校验 `source_code`、`site_id`、`warehouse_id` 与任务一致。
+- 技术方案见 [docs/features/shipping-notice/inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。
+
+### 3.x 货代发货通知建单防重复(第一阶段)
+
+- **同请求去重**:上传接入阶段按源文件 SHA-256 去重,相同内容只抽取、建任务一次。
+- **建单幂等**:`ShippingBatch.create_idempotency_key` 防止双击、重试与并发重复建批;数据库唯一约束 `(user_id, create_idempotency_key)` 提供最终保护。
+- **内容指纹**:`ShippingTask.source_content_hash` 记录完整文件哈希,支持跨请求精确重复检测。
+- **语义分离**:货代上传幂等仍使用 `ShippingTask.idempotency_key`,不与建单幂等键混用。
+
### 3.1 本期范围
- 查询员工本人假期余额
diff --git a/docs/features/README.md b/docs/features/README.md
index 84e2bf4b..7f0914ae 100644
--- a/docs/features/README.md
+++ b/docs/features/README.md
@@ -6,7 +6,7 @@
| --- | --- | --- |
| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) |
| [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) |
-| [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) |
+| [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) · [履历挂载命令](fixed-assets/history-share-mount.md) |
**平台级**设计(跨域)见 [platform/](../platform/README.md)。
diff --git a/docs/features/file-check/technical.md b/docs/features/file-check/technical.md
index 1db9e0ce..b052fe95 100644
--- a/docs/features/file-check/technical.md
+++ b/docs/features/file-check/technical.md
@@ -901,8 +901,8 @@ flask db current # 应包含 e2f3a4b5c6d7
| 1 | Start(`用户输入`)**删除** `task_id`、`hxops_turn_id` 等 HXOPS 业务变量 |
| 2 | Start **新增/保留** `agent_runtime_context`(Paragraph / Long Text);`query` 继续绑定 `sys.query` |
| 3 | Start 与 LLM 之间 **新增** [§3.1A Code:解析运行态上下文](#31a-code解析运行态上下文) |
-| 4 | 原引用 `用户输入.task_id` 的节点改为 `解析运行态上下文.task_id` |
-| 5 | RUN_FILE_CHECK(§3.8)入参绑定 `解析运行态上下文.task_id` 与 `解析运行态上下文.hxops_turn_id` |
+| 4 | 原引用 `用户输入.task_id` 的 **Tool** 节点改为 `解析运行态上下文.task_id_int`(Number);**LLM / Code** 改为 `解析运行态上下文.task_id`(String) |
+| 5 | RUN_FILE_CHECK(§3.8)入参:`task_id` → `解析运行态上下文.task_id_int`;`hxops_turn_id` → `解析运行态上下文.hxops_turn_id` |
| 6 | (可选)导入 `docs/openapi/agent_runtime_context_tools.dify.json`,用 Tool `parse_agent_runtime_context` 替代 Code 节点 |
| 7 | Dify 直连调试时,Start 的 `agent_runtime_context` 手工填含 `refs` 的 JSON(见 §3.1A 示例) |
@@ -1209,10 +1209,22 @@ Layer 2 — 成功出口 → Code(仅 HTTP 200 且 JSON 已到)
| --- | --- |
| **String** | 文本、JSON 字符串(`run_json` / `runs_json`)、ID、错误码 |
| **Boolean** | `ok`、各类是否判断 |
-| **Number** | `confidence`(意图识别) |
+| **Number** | `confidence`(意图识别)、`task_id_int`(检核任务 ID 整数,**Tool API 专用**) |
| **Secret** | 历史 HTTP 方案曾在 Start 使用 `hxops_tool_api_token`;**当前 Tool 方案由 OpenAPI 工具 Credential 托管,Start 勿配** |
| **Array[Object]** | Tool 节点 `json` 出参;历史检索 Tool 响应(§3.25) |
+#### 3.0.0 `task_id` 类型约定(最终版,勿混用)
+
+| 层级 | 类型 | 说明 |
+| --- | --- | --- |
+| **HXOPS 后端**(`ScheduleTask.id`、`bound_schedule_task_id`、`chat_tool_runs.schedule_task_id`) | **integer** | 数据库与 API 内部一律整型 |
+| **OpenAPI Tool API**(`run_file_check`、`get_latest_file_check_run`、`list_file_check_runs`、`search_file_check_history` 等) | **integer** | `docs/openapi/file_check_tools_openapi.json` 中 `task_id` 均为 `integer` |
+| **Dify `解析运行态上下文` 出参** | `task_id_int` · **Number**;`task_id` · String | Tool 节点 Integer 参数 **只绑 `task_id_int`**;LLM Prompt / Code 文本逻辑用 `task_id` 字符串 |
+| **Dify `提取查询参数` 出参** | 同上 | 查询分支 Tool 绑 `提取查询参数.task_id_int` |
+| **Dify Start / 意图识别** | **勿用** | 不在 Start 配顶层 `task_id`;`意图识别.task_id` 常为空,禁止绑 Tool |
+
+> `agent_runtime_context.refs.schedule_task_id` 在 JSON 中可能是字符串 `"3"` 或数字 `3`,§3.1A Code 负责归一化为 `task_id_int=3`。
+
#### 3.0.1 Code 节点入参 / 出参总表
**Tool 响应解析共用 helper**(各 Code 节点可复制到 `main` 上方):
@@ -1241,7 +1253,7 @@ def _load_tool_json(tool_json, tool_text):
| 节点名 | 入参(名 · Dify 类型 · 必填 · 绑定) | 出参(名 · Dify 类型 · 说明) |
| --- | --- | --- |
| `解析启动检核响应` | `tool_json` · **Array[Object]** 或 **Object** · 是 · `Tool:启动检核.json`;`tool_text` · **String** · 否 · 同上 `.text` | `ok` · **Boolean**;`error_code` / `message` / `run_id` / `run_no` / `run_status` / `task_name` / `started_at` · **String** |
-| `提取查询参数` | `user_query` / `intent_run_id` / `intent_task_id` / `task_id` · **String** · `user_query` 与 `task_id` 是,其余否 · 见 §3.14 | `query_mode` · **String** · `by_run_id`/`latest_by_task`/`all_runs`/`missing`;`run_id` / `task_id` · **String** |
+| `提取查询参数` | `user_query` / `intent_run_id` / `intent_task_id` / `task_id` · **String** · `user_query` 与 `task_id` 是,其余否 · 见 §3.14 | `query_mode` · **String**;`run_id` / `task_id` · **String**;`task_id_int` · **Number**(Tool 绑此字段) |
| `解析指定检核查询响应` | `tool_json` / `tool_text` · 是/否 · `Tool:查询指定检核.json` / `.text` | `ok` · **Boolean**;`error_code` / `message` · **String**;`run_json` · **String** |
| `解析最近检核查询响应` | `tool_json` / `tool_text` · 是/否 · `Tool:查询最近检核.json` / `.text` | 同上 |
| `解析所有检核批次响应` | `tool_json` / `tool_text` · 是/否 · `Tool:查询所有检核批次.json` / `.text` | `ok` · **Boolean**;`error_code` / `message` / `runs_json` / `count` · **String** |
@@ -1284,7 +1296,7 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输
| 节点名 | 入参(名 · Dify 类型 · 必填 · 绑定) | 出参(名 · Dify 类型 · 说明) |
| --- | --- | --- |
-| `检索历史检核报告` | Tool · `task_id` · **Integer** · 是 · `解析运行态上下文.task_id`;`query` · **String** · 是 · `用户输入.query` | `json` · **Object**;`text` · **String** |
+| `检索历史检核报告` | Tool · `task_id` · **Integer** · 是 · `解析运行态上下文.task_id_int`;`query` · **String** · 是 · `用户输入.query` | `json` · **Object**;`text` · **String** |
| `解析历史检索响应` | `tool_json` · **Object** · 是 · `检索历史检核报告.json`;`tool_text` · **String** · 否 | `count` · **Number**;`segments_text` · **String** |
| `生成历史报告回答` | Prompt · `用户输入.query`;`解析历史检索响应.segments_text` | `text` · **String** |
@@ -1352,7 +1364,8 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输
| 输出名 | Dify 类型 | 说明 |
| --- | --- | --- |
-| `task_id` | String | 检核任务 ID(`ScheduleTask.id`),供下游 Tool / LLM 复用 |
+| `task_id` | String | 检核任务 ID 字符串,供 LLM Prompt / Code 节点复用 |
+| `task_id_int` | **Number** | 与 `task_id` 同值整数;**所有 OpenAPI Tool 的 Integer task_id 参数绑此字段** |
| `schedule_task_id` | String | 与 `task_id` 相同,显式命名便于对照平台协议 |
| `hxops_turn_id` | String | 本轮对话唯一标识;RUN_FILE_CHECK **必须**回传 |
@@ -1374,11 +1387,20 @@ def main(agent_runtime_context: str) -> dict:
pass
refs = ctx.get("refs") if isinstance(ctx.get("refs"), dict) else {}
- schedule_task_id = str(refs.get("schedule_task_id") or "").strip()
+ raw_task_id = refs.get("schedule_task_id")
+ schedule_task_id = str(raw_task_id or "").strip()
hxops_turn_id = str(refs.get("hxops_turn_id") or "").strip()
+ task_id_int = None
+ try:
+ if raw_task_id is not None and str(raw_task_id).strip() != "":
+ task_id_int = int(raw_task_id)
+ except (TypeError, ValueError):
+ task_id_int = None
+
return {
"task_id": schedule_task_id,
+ "task_id_int": task_id_int,
"schedule_task_id": schedule_task_id,
"hxops_turn_id": hxops_turn_id,
}
@@ -1389,7 +1411,7 @@ def main(agent_runtime_context: str) -> dict:
- 导入 `docs/openapi/agent_runtime_context_tools.dify.json`
- 节点名建议 `Tool 解析运行态上下文`;调用 `parse_agent_runtime_context`
- 推荐 paths:`refs.schedule_task_id`、`refs.hxops_turn_id`、`platform.session_id`
-- 将 Tool 输出映射为与本节相同的 `task_id` / `hxops_turn_id` 变量名,供 §3.8 使用
+- 将 Tool 输出映射为与本节相同的 `task_id` / `task_id_int` / `hxops_turn_id` 变量名,供 §3.8 使用
---
@@ -1518,7 +1540,7 @@ def main(agent_runtime_context: str) -> dict:
错误类型:{{#检索历史检核报告.error_type#}}
错误信息:{{#检索历史检核报告.error_message#}}
-常见原因:Tool 鉴权失败(401)、检核任务/批次不存在(404)、参数非法(400)、HXOPS 或 Dify 检索服务不可用(503)、网络超时。
+常见原因:Tool 鉴权失败(401)、检核任务/批次不存在(404)、参数非法(400)、检核数据源不可用(503 / data_source_unavailable)、HXOPS 或 Dify 检索服务不可用(503)、网络超时。
若为历史查询,请确认排程已启用 kb_sync 且知识库 Dataset 已绑定;若为发起/查询检核,请确认 Agent 已配置 schedule_task_id。
```
@@ -1547,7 +1569,7 @@ def main(agent_runtime_context: str) -> dict:
| 参数 | 类型 | 绑定 / 固定值 |
| --- | --- | --- |
-| `task_id` | Number | `解析运行态上下文.task_id` |
+| `task_id` | **Number** | `解析运行态上下文.task_id_int`(**勿绑** `task_id` 字符串或 `意图识别.task_id`) |
| `hxops_turn_id` | String | `解析运行态上下文.hxops_turn_id` |
| `trigger_source` | String | 固定 `dify_chatflow` |
| `conversation_id` | String | `sys.conversation_id`(系统变量) |
@@ -1560,7 +1582,7 @@ def main(agent_runtime_context: str) -> dict:
```json
{
- "task_id": "<解析运行态上下文.task_id>",
+ "task_id": "<解析运行态上下文.task_id_int>",
"hxops_turn_id": "<解析运行态上下文.hxops_turn_id>",
"conversation_id": "{{#sys.conversation_id#}}",
"trigger_source": "dify_chatflow",
@@ -1855,13 +1877,33 @@ def main(tool_json, tool_text: str = "") -> dict:
| --- | --- | --- |
| `query_mode` | String | `by_run_id` / `latest_by_task` / `all_runs` / `missing` |
| `run_id` | String | 检核批次 ID;非 by_run_id 时为 `""` |
-| `task_id` | String | 检核任务 ID |
+| `task_id` | String | 检核任务 ID 字符串,供 IF / LLM |
+| `task_id_int` | **Number** | 检核任务 ID 整数;§3.17 / §3.17A Tool 绑此字段 |
**完整 Python 代码**
```python
import re
+
+def _to_task_id_int(tid: str):
+ """将 task_id 字符串转为整数;非法或空时返回 None(Dify Number 出参可为 null)。"""
+ normalized = str(tid or "").strip()
+ if not normalized.isdigit():
+ return None
+ return int(normalized)
+
+
+def _pack_query_result(query_mode: str, run_id: str = "", task_id: str = "") -> dict:
+ tid = str(task_id or "").strip()
+ return {
+ "query_mode": query_mode,
+ "run_id": str(run_id or "").strip(),
+ "task_id": tid,
+ "task_id_int": _to_task_id_int(tid),
+ }
+
+
def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
q = str(user_query or "")
run_id = str(intent_run_id or "").strip()
@@ -1869,7 +1911,7 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
all_keywords = ["所有", "全部", "全量", "列表", "历史记录", "执行记录", "所有文件检核结果", "全部文件检核结果", "all"]
if any(k in q for k in all_keywords):
tid = str(intent_task_id or task_id or "").strip()
- return {"query_mode": "all_runs", "run_id": "", "task_id": tid}
+ return _pack_query_result("all_runs", task_id=tid)
if not run_id:
m = re.search(r'(?:批次\s*ID|run[_\s-]*id|run_id)\s*[::]?\s*(\d+)', q, re.I)
@@ -1881,19 +1923,19 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
run_id = m.group(1)
if run_id:
- return {"query_mode": "by_run_id", "run_id": run_id, "task_id": ""}
+ return _pack_query_result("by_run_id", run_id=run_id)
latest_keywords = ["最新", "最近", "上一次", "上次", "latest"]
if any(k in q for k in latest_keywords):
tid = str(intent_task_id or task_id or "").strip()
if tid:
- return {"query_mode": "latest_by_task", "run_id": "", "task_id": tid}
+ return _pack_query_result("latest_by_task", task_id=tid)
tid = str(intent_task_id or task_id or "").strip()
if tid:
- return {"query_mode": "latest_by_task", "run_id": "", "task_id": tid}
+ return _pack_query_result("latest_by_task", task_id=tid)
- return {"query_mode": "missing", "run_id": "", "task_id": ""}
+ return _pack_query_result("missing")
```
**下游**:→ [§3.15 IF:查询方式](#315-if查询方式)
@@ -1941,7 +1983,7 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
| 参数 | 类型 | 绑定 |
| --- | --- | --- |
-| `task_id` | Number | `提取查询参数.task_id` |
+| `task_id` | Number | `提取查询参数.task_id_int` |
**下游**:→ [§3.18.2 Code:解析最近检核查询响应](#318-code解析检核查询响应两个节点)
@@ -1957,7 +1999,7 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
| 参数 | 类型 | 绑定 / 固定值 |
| --- | --- | --- |
-| `task_id` | Number | `提取查询参数.task_id` |
+| `task_id` | Number | `提取查询参数.task_id_int` |
| `limit` | Number | 固定 `50` |
**下游**:→ [§3.18.3 Code:解析所有检核批次响应](#3183-code解析所有检核批次响应)
@@ -2322,7 +2364,7 @@ def main(tool_json, tool_text) -> dict:
| 配置项 | 绑定 |
| --- | --- |
| 工具 | OpenAPI 自定义工具 `search_file_check_history` |
-| `task_id` | `{{#解析运行态上下文.task_id#}}` |
+| `task_id` | `{{#解析运行态上下文.task_id_int#}}` |
| `query` | `{{#用户输入.query#}}` |
| `top_k`(可选) | 默认 5,可不填 |
| 异常处理 | **Fail Branch** → §3.7 |
@@ -2511,6 +2553,7 @@ def main(tool_json: dict, tool_text: str) -> dict:
| `kb_not_configured` | 400 | 排程未启用 kb_sync 或未绑 kb_group | Tool 异常分支 → §3.7 |
| `kb_dataset_not_bound` | 400 | 知识库分组未绑定 dify_dataset_id | Tool 异常分支 → §3.7 |
| `dify_retrieve_failed` | 503 | Dify 检索 API 失败或未配置 | Tool 异常分支 → §3.7 |
+| `data_source_unavailable` | 503 | 启动检核预检时 ODBC/SQL Server 连接失败或 SRM 未配置 | Tool 异常分支 → §3.7(RUN_FILE_CHECK) |
| `check_running` | 200 | 检核进行中(body,非 HTTP 失败) | Tool **成功出口** → [§3.9](#39-code解析启动检核响应) → [§3.10](#310-if启动业务分支) → §3.12 |
| `excel_not_ready` | 409 | 报告未生成 | 查询分支 LLM 说明时提及 |
| `invalid_response` | — | Tool HTTP 成功但 Code 无法解析 JSON | [§3.24](#324-answer错误兜底启动检核-body)(启动)或历史 LLM 兜底 |
@@ -2607,11 +2650,13 @@ limit 20;
| 指定/最近查询共用一个 Code | 分支汇入变量来源混乱 | 复制为两个 Code 节点 |
| 历史报告改走 Knowledge Retrieval | 无法按 task_id 动态选 Dataset | 历史走 §3.25 Tool API |
| OpenAPI Server URL 错误 | 工具调用超时 / 404 | 确认与 `HXOPS_TOOLS_API_BASE` 一致 |
+| RUN_FILE_CHECK 绑定 `意图识别.task_id` 或 `task_id` 字符串 | 解析节点有 `task_id_int:3`,Tool 入参却是 `null` | Tool 的 Integer `task_id` **只绑** `解析运行态上下文.task_id_int`(或 `提取查询参数.task_id_int`) |
+| RUN_FILE_CHECK 仍显示 `task_no` | 入参含废弃字段 `task_no:null` | 重新 URL 导入 OpenAPI(§1.4),删除 `task_no` 绑定 |
### E.3 迁移后画布检查
- [ ] Start **仅**含 `agent_runtime_context`(及 `query`);无顶层 `task_id` / `hxops_turn_id`
-- [ ] 存在 §3.1A `解析运行态上下文` 节点,且 RUN_FILE_CHECK 绑定其 `task_id` / `hxops_turn_id`
+- [ ] 存在 §3.1A `解析运行态上下文` 节点,且 **所有 Tool** 的 Integer `task_id` 绑 `task_id_int`(RUN_FILE_CHECK / 历史检索绑 `解析运行态上下文.task_id_int`;查询分支绑 `提取查询参数.task_id_int`)
- [ ] 不存在调用 `/api/file-check/tools/*` 的 HTTP Request 节点
- [ ] 不存在手写 `Authorization` Header
- [ ] Start 无 Tool API token / base URL
diff --git a/docs/features/fixed-assets/README.md b/docs/features/fixed-assets/README.md
index 79de74c6..aaae3634 100644
--- a/docs/features/fixed-assets/README.md
+++ b/docs/features/fixed-assets/README.md
@@ -3,5 +3,6 @@
| 文档 | 读者 | 路径 |
| --- | --- | --- |
| **技术方案** | 研发 | [technical.md](technical.md) |
+| **履历共享盘挂载命令**(test/prod) | 运维 | [history-share-mount.md](history-share-mount.md) |
**代码**:`backend/app/services/text2sql.py`(查询)、固资快照同步任务 · **状态**:见 [funclist.md](../../funclist.md)(固资管理)
diff --git a/docs/features/fixed-assets/history-share-mount.md b/docs/features/fixed-assets/history-share-mount.md
new file mode 100644
index 00000000..b59c4a1d
--- /dev/null
+++ b/docs/features/fixed-assets/history-share-mount.md
@@ -0,0 +1,197 @@
+# 固资履历共享盘挂载(Linux 运维命令)
+
+> 适用:Linux 宿主机 + Docker Compose 部署的 hxops-backend。
+> 已在 test 环境验证:`smbclient` 可达后,用「CIFS 挂共享根 + bind 履历子目录」方式成功。
+> **不要使用** `subdir=履历`(部分内核会报 `mount error(22): Invalid argument`)。
+
+## 1. 背景
+
+| 项 | 值 |
+| --- | --- |
+| Windows 源路径 | `\\192.168.100.130\设备履历记录\履历` |
+| 业务变量 | `FIXED_ASSET_HISTORY_LOCAL_ROOT`(优先于 UNC) |
+| test 本地根 | `/mnt/hxops-fixed-asset-history-test` |
+| prod 本地根 | `/mnt/hxops-fixed-asset-history-prod` |
+| 共享根挂载点 | test: `/mnt/hxops-fixed-asset-history-test-share`
prod: `/mnt/hxops-fixed-asset-history-prod-share` |
+
+挂载顺序:
+
+1. CIFS 挂载共享根 `设备履历记录` → `*-share`
+2. `mount --bind` 把其中的 `履历` 挂到 `FIXED_ASSET_HISTORY_LOCAL_ROOT`
+3. 重建 `hxops-backend`,使容器内能看到该目录
+
+---
+
+## 2. 公共准备(test / prod 各做一次即可)
+
+```bash
+# 安装工具
+sudo apt update
+sudo apt install -y cifs-utils smbclient
+
+# 凭据文件(密码与 .env.shared / .env. 中 FIXED_ASSET_HISTORY_SHARE_* 一致)
+sudo mkdir -p /etc/smbcredentials
+sudo tee /etc/smbcredentials/hxops-fixed-asset-history >/dev/null <<'EOF'
+username=SBLL00001
+password=这里填真实密码
+domain=WORKGROUP
+EOF
+sudo chmod 600 /etc/smbcredentials/hxops-fixed-asset-history
+
+# 连通性探测(应能列出目录)
+smbclient //192.168.100.130/设备履历记录 -A /etc/smbcredentials/hxops-fixed-asset-history -c "ls"
+```
+
+`uid/gid` 默认按 `1001`;不一致时先执行 `id`,替换下面命令中的数值。
+
+若 `vers=3.0` 报 `Invalid argument`,将命令中的 `vers=3.0` 改为 `vers=2.1` 再试。
+
+---
+
+## 3. Test 环境命令(已验证)
+
+在 hxops 仓库所在宿主机执行:
+
+```bash
+# 1) 挂共享根
+sudo mkdir -p /mnt/hxops-fixed-asset-history-test-share
+sudo mount -t cifs //192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-test-share \
+ -o credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro
+
+# 2) 确认有「履历」
+ls /mnt/hxops-fixed-asset-history-test-share
+
+# 3) bind 履历 -> LOCAL_ROOT
+sudo mkdir -p /mnt/hxops-fixed-asset-history-test
+sudo mount --bind /mnt/hxops-fixed-asset-history-test-share/履历 /mnt/hxops-fixed-asset-history-test
+
+# 4) 确认履历文件可见
+ls /mnt/hxops-fixed-asset-history-test | head
+
+# 5) 重建后端并检查容器内路径(必须带 COMPOSE_ENV_BASENAME,否则读不到 LOCAL_ROOT)
+cd /path/to/hxops # 换成实际部署目录,例如 ~/ai/platform/hxops
+export COMPOSE_SHARED_ENV_BASENAME=.env.shared
+export COMPOSE_ENV_BASENAME=.env.test
+docker compose --env-file .env.test up -d hxops-backend
+docker exec hxops-backend printenv | grep FIXED_ASSET_HISTORY
+docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-test
+```
+
+### Test 开机自动挂载(可选,写入 /etc/fstab)
+
+```bash
+echo '//192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-test-share cifs credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro,nofail,_netdev 0 0' | sudo tee -a /etc/fstab
+
+echo '/mnt/hxops-fixed-asset-history-test-share/履历 /mnt/hxops-fixed-asset-history-test none bind,nofail 0 0' | sudo tee -a /etc/fstab
+
+# 验证 fstab(勿在已挂载时盲目 umount 生产业务目录)
+sudo mount -a
+findmnt /mnt/hxops-fixed-asset-history-test
+```
+
+---
+
+## 4. Prod 环境命令
+
+与 test 相同,仅路径与 compose env 不同:
+
+```bash
+# 1) 挂共享根
+sudo mkdir -p /mnt/hxops-fixed-asset-history-prod-share
+sudo mount -t cifs //192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-prod-share \
+ -o credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro
+
+# 2) 确认有「履历」
+ls /mnt/hxops-fixed-asset-history-prod-share
+
+# 3) bind 履历 -> LOCAL_ROOT
+sudo mkdir -p /mnt/hxops-fixed-asset-history-prod
+sudo mount --bind /mnt/hxops-fixed-asset-history-prod-share/履历 /mnt/hxops-fixed-asset-history-prod
+
+# 4) 确认履历文件可见
+ls /mnt/hxops-fixed-asset-history-prod | head
+
+# 5) 重建后端并检查容器内路径(必须带 COMPOSE_ENV_BASENAME,否则读不到 LOCAL_ROOT)
+cd /path/to/hxops
+export COMPOSE_SHARED_ENV_BASENAME=.env.shared
+export COMPOSE_ENV_BASENAME=.env.prod
+docker compose --env-file .env.prod up -d hxops-backend
+docker exec hxops-backend printenv | grep FIXED_ASSET_HISTORY
+docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-prod
+```
+
+### Prod 开机自动挂载(可选,写入 /etc/fstab)
+
+```bash
+echo '//192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-prod-share cifs credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro,nofail,_netdev 0 0' | sudo tee -a /etc/fstab
+
+echo '/mnt/hxops-fixed-asset-history-prod-share/履历 /mnt/hxops-fixed-asset-history-prod none bind,nofail 0 0' | sudo tee -a /etc/fstab
+
+sudo mount -a
+findmnt /mnt/hxops-fixed-asset-history-prod
+```
+
+---
+
+## 5. 卸载(需要时)
+
+先卸 bind,再卸共享根:
+
+```bash
+# test
+sudo umount /mnt/hxops-fixed-asset-history-test
+sudo umount /mnt/hxops-fixed-asset-history-test-share
+
+# prod
+sudo umount /mnt/hxops-fixed-asset-history-prod
+sudo umount /mnt/hxops-fixed-asset-history-prod-share
+```
+
+---
+
+## 6. 排障
+
+| 现象 | 处理 |
+| --- | --- |
+| `asset history share is unreachable` | 宿主机 `LOCAL_ROOT` 未挂载,或容器未 recreate / compose 未 bind 该路径 |
+| `mount error(22): Invalid argument` | 勿用 `subdir=`;或改 `vers=2.1` / `vers=2.0` |
+| `smbclient` 失败 | 查网络、账号密码、Windows 共享权限 |
+| 宿主机有文件、容器内没有 | `docker compose --env-file .env. up -d hxops-backend` 重建后再 `docker exec ... ls` |
+| 容器 `ls` 正常但仍 503 `unreachable` | 应用未读到 `FIXED_ASSET_HISTORY_LOCAL_ROOT`,回退到 UNC。执行 `docker exec hxops-backend printenv \| grep FIXED_ASSET`;重建时必须带上 env:见下方「重建后端」 |
+| 目录存在但为空 | 可能 Docker 先创建了空目录;先 `umount`/清错挂,再按本文重新 mount |
+
+### 重建后端(重要)
+
+compose 默认 `env_file` 指向 `.env.dev`(无 LOCAL_ROOT)。手动重建时请显式指定:
+
+```bash
+cd /path/to/hxops
+export COMPOSE_SHARED_ENV_BASENAME=.env.shared
+export COMPOSE_ENV_BASENAME=.env.test # prod 改成 .env.prod
+docker compose --env-file .env.test up -d hxops-backend
+
+# 确认容器内已注入 LOCAL_ROOT(不应为空,且不是 UNC)
+docker exec hxops-backend printenv | grep FIXED_ASSET_HISTORY
+```
+
+期望类似:
+
+```text
+FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
+FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
+```
+
+
+相关配置:
+
+- `.env.test` / `.env.prod`:`FIXED_ASSET_HISTORY_LOCAL_ROOT`
+- `docker-compose.yml`:已把 test/prod 两个 `LOCAL_ROOT` 只读挂进 `hxops-backend`
+- 可选脚本:`scripts/mount_fixed_asset_history.sh`(封装同上逻辑)
+
+---
+
+## 7. 验收
+
+1. 宿主机:`ls $LOCAL_ROOT` 能看到履历文件
+2. 容器:`docker exec hxops-backend ls $LOCAL_ROOT` 同样可见
+3. 前端:聊天页点击资产编号,不再出现 503 / `asset history share is unreachable`
diff --git a/docs/features/fixed-assets/technical.md b/docs/features/fixed-assets/technical.md
index 9cb66534..6e56a191 100644
--- a/docs/features/fixed-assets/technical.md
+++ b/docs/features/fixed-assets/technical.md
@@ -257,6 +257,29 @@ backend/data/fixed_assets/
这样可避免同步失败导致固资查询整体不可用。
+### 7.4 资产履历共享盘访问约定
+
+固资聊天结果中的“资产编号”点击后,会走 `backend/app/services/fixed_asset_history.py` 检索履历文件,并经 `api/chat.py` 的预览代理读取二进制内容。为兼容不同部署环境,履历目录访问遵循以下约定:
+
+- **Windows 本地开发环境**:可直接使用 `FIXED_ASSET_HISTORY_SHARE_ROOT=\\\\server\\share\\...` 访问 UNC 共享盘。
+- **Linux 测试/生产环境**:应先由宿主机把 SMB 共享盘挂载到本地目录,再配置 `FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/...`;运行时优先使用 `LOCAL_ROOT`,不依赖 `net use`。
+- **预览安全限制**:`/api/chat/preview-file-raw` 只允许读取 `PLM_PREVIEW_SHARE_ROOT`、`FIXED_ASSET_HISTORY_SHARE_ROOT`、`FIXED_ASSET_HISTORY_LOCAL_ROOT` 这三类受信根目录下的文件路径,避免任意本地文件被前端透传读取。
+
+#### 7.4.1 Linux 宿主机挂载
+
+**权威运维命令(含 test / prod 完整步骤)**:见 [history-share-mount.md](history-share-mount.md)。
+
+要点:先 CIFS 挂共享根 `设备履历记录`,再 `mount --bind` 子目录 `履历` 到 `FIXED_ASSET_HISTORY_LOCAL_ROOT`;**不要**使用 `subdir=`(易触发 `mount error(22)`)。
+
+可选封装脚本:`scripts/mount_fixed_asset_history.sh`。
+
+`docker-compose.yml` 已将 test/prod 的 `LOCAL_ROOT` 只读 bind 进 `hxops-backend`;宿主机挂载成功后需:
+
+```bash
+docker compose --env-file .env. up -d hxops-backend
+docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-
+```
+
---
## 8. 定时任务设计
diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md
index 3c9501e4..84b791bd 100644
--- a/docs/features/shipping-notice/business.md
+++ b/docs/features/shipping-notice/business.md
@@ -102,7 +102,7 @@ SN-20260529-A1B2C3D4
| 顺序 | 资料 | 格式 | 用途 |
|------|------|------|------|
| 1 | **发货通知 / 订单** | PDF、Word,或邮件/微信正文 | 解析客户、SKU、数量、Reservation ID、单价、金额等 |
-| 2 | **库存快照** | Excel(.xlsx / .xls / .csv) | 与订单行核对可用库存;大表请直接上传文件,不要整表粘贴到聊天框 |
+| 2 | **库存快照** | Excel(.xlsx / .csv) | 与订单行核对可用库存;大表请直接上传文件,不要整表粘贴到聊天框 |
| 3 | (可选)**货代发货模板** | 由 IT 配置 | 生成最终上传货代用的 Excel |
**顺序要求**:须先完成发货通知解析并确认,再上传库存。若尚未有任务编号就上传库存 Excel,系统会提示您先提交发货通知。
diff --git a/docs/features/shipping-notice/inventory_source_plan.md b/docs/features/shipping-notice/inventory_source_plan.md
index 57d8ab5f..cd142568 100644
--- a/docs/features/shipping-notice/inventory_source_plan.md
+++ b/docs/features/shipping-notice/inventory_source_plan.md
@@ -1,36 +1,66 @@
-# 发货通知库存源路由与 RPA Driver 方案
+# 发货通知库存源路由方案(订单解析阶段判定)
## 背景
-发货通知的库存导出不能再假设只有一个 RPA 地址或一种页面流程。不同目的地、出货港口或仓库线索可能对应不同货代系统入口,例如 DSV 360 的不同 Program,或 Crane FootPrint Portal 的不同 Warehouse。若选错库存源,后续库存匹配和出货 Excel 会建立在错误库存池上,风险高于“未查到库存”。
+发货通知的库存导出不能再假设只有一个 RPA 地址或一种页面流程。不同目的地、出货港口或仓库线索可能对应不同货代系统入口,例如 DSV 360 的不同 Program,或 Crane FootPrint Portal 的不同 Warehouse。若选错库存源,后续库存匹配和出货 Excel 会建立在错误库存池上,风险高于「未查到库存」。
+
+历史上 `site_id`(如 `AWSBI`)与 `warehouse_id`(如 `BYAWSATL01`)曾被混用,导致发货 Excel 与 RPA 查询参数不一致。本方案将库存源判定前移到**订单解析阶段**,并以独立数据库字段持久化业务决策。
## 设计原则
-- Dify LLM 负责从非结构化发货通知和用户对话中抽取候选字段,不负责最终 RPA URL 决策。
-- HXOPS 负责标准化、规则匹配、唯一性判断、权限校验、人工确认和审计。
+- Dify LLM 负责从非结构化发货通知和用户对话中抽取候选字段(目的地、港口、仓库线索等),**不负责**最终 RPA URL / source_code 决策。
+- HXOPS 在 `parse_notice` 阶段根据 YAML 配置做标准化、规则匹配、唯一性判断;唯一命中写入任务独立字段。
+- 用户人工确认时**只确认 `source_code`**;`site_id`、`warehouse_id` 由配置自动生成,禁止前端或 LLM 直写。
+- RPA、库存准备、匹配、Excel 生成、上传等后续步骤均通过 **inventory source gate** 硬阻断,未稳定(`resolved` / `user_confirmed`)不得继续。
- RPA 只消费 HXOPS 给出的 `rpa_inventory_source` 参数,按 `source_type` 分发到不同 Driver。
-- 通用化范围是 trigger 协议、状态机、超时重试、回调、库存标准化;页面操作逻辑由不同 Driver 独立实现。
-- 用户对话可以做当前任务级临时覆盖;全局规则变更只能作为建议,需审核后生效。
-## MVP 范围
+## 判定时机与状态机
-第一版不改数据库结构,规则和源配置先放代码中,任务级上下文写入 `ShippingTask.step_payload_json`。
+### 何时判定
-MVP 包含:
+1. **`parse_notice`**:解析结构化订单后,立即调用 `adjudicate_inventory_source()` 抽取/写入库存源**线索与候选**(不抢解析人工确认)。
+2. **低置信度**:先进入 `checkpoint=parse_review`(确认 / 重新解析 / 驳回);解析通过后再看库存源是否稳定。
+3. **高置信度且唯一命中且配置完整** → `inventory_source_status=resolved`,任务可进入 `parsed`。
+4. **解析已接受但未命中 / 多命中 / 配置无效 / 路由指纹变更** → `pending_review`,`checkpoint=inventory_source_review`,`pending_human_reason=inventory_source_unresolved`。
+5. 用户在聊天区确认 `source_code` → `confirm_inventory_source` → `inventory_source_status=user_confirmed`,再推进至 `parsed` 并允许 RPA。
-- 解析 Dify 输出的目的地候选字段,并保存到任务 step payload。
-- 根据目的地/港口/仓库线索解析库存源。
-- 唯一命中时自动写入 `rpa_inventory_source`。
-- 无法命中或多命中时进入 `inventory_source_review` 人工检查点。
-- RPA trigger JSON 增加 `rpa_inventory_source`。
-- 后端测试覆盖 DSV 与 Crane 的基本路由。
+### 稳定状态
-暂不包含:
+| status | 含义 |
+| --- | --- |
+| `resolved` | 规则自动唯一命中 |
+| `user_confirmed` | 用户已确认 source_code |
-- 后台规则管理页面。
-- 数据库规则表。
-- 批次级对话覆盖。
-- 全局规则建议审核流。
+其余状态(`unresolved`、`ambiguous`、`invalid`、`conflicted`)均视为不稳定,gate 阻断。
+
+## 独立数据库字段(`shipping_tasks`)
+
+| 字段 | 说明 |
+| --- | --- |
+| `destination_*` | 目的地候选(城市、国家、港口等),供规则匹配 |
+| `inventory_source_code` | 正式库存源编码,如 `DSV360_AWSDU` |
+| `inventory_source_type` | `dsv360` / `crane_footprint` |
+| `inventory_site_id` | DSV Program / Site(如 `AWSDU`) |
+| `inventory_warehouse_id` | 具体仓库(如需要) |
+| `inventory_source_status` | 判定状态 |
+| `inventory_source_method` | `auto` / `user` |
+| `inventory_source_config_version` | YAML 配置版本指纹 |
+| `inventory_routing_fingerprint` | 路由输入指纹,变更时要求重确认 |
+
+`step_payload_json.inventory_source_resolution` 仅保留候选列表与诊断信息,**不作为** gate 真相源。
+
+## 配置文件
+
+路径:`backend/config/shipping_inventory_sources.yaml`(环境变量 `SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG`)
+
+每个 source 含:
+
+- `source_code`、`source_type`、`site_id`、`warehouse_id`
+- `navigation`、`parameters`(RPA 填表)
+- `match_aliases`:目的地/港口/仓库别名
+- `match`:加权评分规则(可选)
+
+新增 Warehouse **只改 YAML**,不改 Python。
## Trigger 协议
@@ -69,19 +99,63 @@ Crane 示例:
}
```
-## 初始路由规则
+## Gate 规则(硬阻断)
-- `BISON`, `AWSBI` -> `DSV360_AWSBI`
-- `CINCINNATI`, `CVG`, `AWSCV` -> `DSV360_AWSCV`
-- `DUB`, `DUBLIN` -> `DSV360_AWSDU`
-- `MOERDIJK`, `AMS`, `AWSAMS` -> `DSV360_AWSAMS`
-- `USLCK`, `SALT LAKE CITY` -> `DSV360_AWSSL`
-- `SINGAPORE`, `SG` -> `DSV360_AWSSG`
-- `TZR`, `THAILAND` -> `CRANE_TZR`
+以下步骤执行前调用 `assert_inventory_source_gate(task)`:
+
+- RPA 触发 / 重试
+- 库存快照 link / 映射 / 匹配
+- 发货 Excel 生成
+- 货代上传
+
+库存快照 link 时额外做 **identity check**:`source_code`、`site_id`、`warehouse_id` 与任务字段一致,否则 `SHIPPING.INVENTORY_IDENTITY_MISMATCH`。
+
+## 错误码(API)
+
+| code | 场景 |
+| --- | --- |
+| `SHIPPING.INVENTORY_SOURCE_UNRESOLVED` | 无法判定 |
+| `SHIPPING.INVENTORY_SOURCE_AMBIGUOUS` | 多候选 |
+| `SHIPPING.INVENTORY_SOURCE_INVALID` | 配置无效 |
+| `SHIPPING.INVENTORY_SOURCE_CONFLICTED` | 判定冲突 |
+| `SHIPPING.INVENTORY_SOURCE_CONFIRMATION_REQUIRED` | 需人工确认 |
+| `SHIPPING.INVENTORY_SOURCE_CHANGED` | 路由变更需重确认 |
+| `SHIPPING.INVENTORY_IDENTITY_MISMATCH` | 快照与任务不一致 |
+| `SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED` | 通用 gate 阻断 |
+
+前端 i18n:`errors.codes.SHIPPING_INVENTORY_SOURCE_*`(点号转下划线)。
+
+## 聊天区交互
+
+- 检查点 `inventory_source_review` 展示候选按钮(携带 `source_code`)。
+- 用户可直接输入目的地线索(如 `Dublin`、`AWSDU`),前端匹配唯一候选后调用 `confirm_inventory_source`。
+- 动作:`confirm_inventory_source`、`retry_resolve_inventory_source`。
+
+## 初始路由规则(示例)
+
+- `BISON`, `AWSBI` → `DSV360_AWSBI`
+- `CINCINNATI`, `CVG`, `AWSCV` → `DSV360_AWSCV`
+- `DUB`, `DUBLIN` → `DSV360_AWSDU`
+- `MOERDIJK`, `AMS`, `AWSAMS` → `DSV360_AWSAMS`
+- `USLCK`, `SALT LAKE CITY` → `DSV360_AWSSL`
+- `SINGAPORE`, `SG` → `DSV360_AWSSG`
+- `TZR`, `THAILAND` → `CRANE_TZR`
+
+完整列表以 YAML 为准。
+
+## 相关代码
+
+| 模块 | 路径 |
+| --- | --- |
+| 规则与指纹 | `services/shipping_notice/inventory_source_rules.py` |
+| Gate | `services/shipping_notice/inventory_source_gate.py` |
+| 解析集成 | `services/shipping_notice/task_workflow.py` |
+| 确认 Tool | `services/shipping_notice/inventory_rpa_workflow.py` |
+| 配置加载 | `services/shipping_notice/inventory_sources.py` |
+| 迁移 | `migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py` |
## 后续演进
-- 将代码配置迁移到可维护规则表。
-- 增加管理员审核的规则变更建议。
-- RPA 侧实现 `dsv360` 与 `crane_footprint` Driver。
-- 导入库存时校验 source_code、warehouse/program 与任务期望是否一致。
+- 后台规则管理页面与审核流。
+- 批次级对话覆盖(当前仅任务级)。
+- 全局规则变更建议与审计。
diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md
index 8bb1e0a7..a92795aa 100644
--- a/docs/features/shipping-notice/technical.md
+++ b/docs/features/shipping-notice/technical.md
@@ -8,6 +8,132 @@
Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、OpenAPI、多文件批次解析、自动上传与 Agent 指令合集。
+### 第三阶段:业务去重与任务版本(实现摘要)
+
+- **文件哈希去重**(FileAsset / notice `content_hash`)与 **业务指纹去重**(`shipping-v1`:客户码/PO/Reservation/行 digest)分层独立;建单幂等键、货代上传幂等键语义不变。
+- Intake 预解析完成后写入 `business_summary`、指纹与 `duplicate_status`;与 `parse_status` 正交。
+- 阻断型重复须先 `POST .../intakes/{intake_no}/duplicate-resolution`(`open_existing` / `create_revision` / `force_create`),再确认建单;建单事务内重校检测结果。
+- 修订创建新 `ShippingTask`:`supersedes_task_id` + `document_version+1`;已 `uploaded` 任务禁止原地覆盖;`force_create` 需 `admin` 或 `shipping_notice_force_create` 与原因,审计事件走 `ShippingTaskEvent`。
+
+### 附件资产化与订单候选(阶段二)
+
+> 本阶段在阶段一文本抽取之上,把附件升级为派生 FileAsset + Document,并识别订单 Candidate;**仍不**正式创建多个 Task。
+
+| 项 | 说明 |
+| --- | --- |
+| 派生资产 | EML 根 `FileAsset` → 子资产(`parent_asset_id` / `asset_role=derived_attachment`);SHA-256 幂等;`source_attachment_key` 为首次来源键(复用不覆盖),当前来源以 Document.attachment_key 为准 |
+| 引用计数 | Document↔派生资产按关联边原子 `±1`;多 Document 共用同一子资产可正确归零回收;`cancel_intake` 行锁幂等清理并剥离摘要投影 |
+| 锁顺序 | 解析成功/失败清理、重复刷新、重试入队均先 `FOR UPDATE` Intake,再碰 Document/资产,与 cancel 同序防死锁;阶段二+parsed+去重同事务 |
+| 重试入队 | 仅复用 `queued` Job(不复用 `running`);`enqueue(commit=False)` 与 Intake.queued/`parse_job_id` 同事务提交 |
+| 去重降级 | 阶段二先落 Document/Candidate 基础行;Candidate+Intake 重复检测在 SAVEPOINT;异常清空为 `unchecked`,不打挂阶段二 |
+| 失败清空 | 阶段二失败清理复用 `clear_duplicate_state_to_unchecked`,去掉 matches/指纹/决策残留 |
+| 资产缺失 | 领取后失败统一 `fail_intake_with_stage2_cleanup`;Job `retryable=False` 且不再抛出,外层仅 `running` 才 fail |
+| 超时回收 | `FOR UPDATE SKIP LOCKED` + `status/attempts` 条件 UPDATE;同事务清空 `parse_lease` 并 `parsing→queued/parse_failed`;替代者须 `FOR UPDATE`:仅 `queued`,或 running 且 Intake 已持精确 `parse_job_id+parse_lease`,禁止向未接管的 running 伪造 lease |
+| 失败收口 | `fail_job` requeue 清空 `started_at`;claim 刷新 `started_at`;终态 failed/cancelled 同步 Intake 离开 `parsing`;唯一冲突窗口消失时保持 running 而非强行 failed |
+| 创建终态 | `cancelled`/`expired`(含 `expires_at` 到期)拒绝再次创建,与 `retry_intake_parse` 一致;仅 `created`/`parse_failed` 可重投;重投仅复用 `queued` Job |
+| 执行代次 | Intake `parse_lease="{job_id}:{attempts}"`;Job `finish/fail` 条件 UPDATE(禁止 Session 缓存判断拥有权) |
+| 原子入队 | 初次创建与重试均 `enqueue(commit=False)`,同事务提交 Intake/`parse_job_id`/Job,禁止半绑定窗口 |
+| 创建幂等 | Intake 创建 FOR UPDATE + SAVEPOINT/IntegrityError 回落;`enqueue` 仅在 SAVEPOINT 内 `add+flush`,避免冲突毒化外层事务 |
+| queued 唯一 | `shipping_notice_parse` 仅允许一条 queued;旧 running 失败/超时回收撞唯一时→`cancelled` 并重指 Intake,禁止永久卡 `running` |
+| 软删除唯一 | `(parent_asset_id, content_hash)` 为 **partial unique**(`deleted_at IS NULL`);清理后同哈希可复活/重建;迁移去重行转 `orphan_cleanup` 供 MinIO 回收 |
+| 重复刷新 | `refresh_intake_duplicate_detection` 逐 Candidate 重检再聚合 Intake;避免仅更新概览导致候选状态陈旧 |
+| Document | `ShippingNoticeDocument`:`body` + 各附件一行;详情/轮询经 Intake 序列化返回 |
+| Candidate | 仅附件/单文件在抽到真实 PO/Reservation/行项目时生成;**正文永不生成 Candidate**(`email_context`) |
+| 分类 | 无业务信号的 PDF 等为 `supporting` Document,禁止伪造 PO/SKU |
+| 失败与重试 | 阶段二持久化失败 → `parse_failed`(可重试);与文本抽取成功解耦后不再静默 `parsed` |
+| 并发 | Job 原子领取 `parsing`;派生资产部分唯一 + IntegrityError 回查;补偿删 MinIO 失败写 `orphan_cleanup` 行供定时回收 |
+| 重复隔离 | 候选 A 重复只阻断 A;Intake 概览可为 `partial_duplicate` |
+| 重试幂等 | `(parent, content_hash)` / `(intake, attachment_key)` / `(intake, primary_document_id)`;失效 Candidate 按本轮主文档集清理 |
+| 解析器版本 | 默认 `SHIPPING_NOTICE_PARSER_VERSION=v6`(相对 v5:落库 Document/Candidate/派生资产) |
+| 建单 | `ShippingTask.source_candidate_id` 预留;本阶段结束仍不按 Candidate 建 Task |
+
+实现入口:`document_candidate_persist.persist_documents_and_candidates` ← `intake_parse_workflow.run_intake_parse`;派生创建:`file_assets.service.create_derived_file_asset_from_bytes`。
+
+### EML 附件提取(阶段一)
+
+> 本阶段只保证「能看到并解析附件」,**不**把多附件拆成多个 Task。
+
+#### 能力边界
+
+| 项 | 说明 |
+| --- | --- |
+| 邮件元数据 | `message_id` / `subject` / `from` / `to` / `date`(ISO) |
+| 正文 | 优先 `text/plain`,否则清洗后的 `text/html`(去 script/style/标签,**不执行**脚本) |
+| 真实附件 | `Content-Disposition: attachment`、带文件名的非正文部件;对 PDF/DOCX/CSV/图片/文本等复用 `extract_notice_text` |
+| 内嵌资源 | 仅跳过 **图片** 类 `inline` / `Content-ID` / 文件名像 logo·signature 的图片;`inline` PDF 等仍视为真实附件 |
+| 嵌套邮件 | 支持 `message/rfc822`、**.eml 文件附件**与 **disposition=attachment 的 multipart/***(如 `bundle.mime`):共享 attachments/限额/哈希;深度从当前层累加;成功容器须登记独立附件行;`multipart/mixed` 内独立 plain/html 段全部保留,`multipart/alternative` 仍 plain 优先;外层 `body_text` **不穿透** rfc822 / 附件型 multipart;**总大小计费**:顶层容器计入配额,展开子内容不计费;超限/超深登记 `skipped` 行 |
+| 文本附件 | 带 `filename`/`name=` 的 `text/plain|html` 视为附件,不当作正文丢弃 |
+| 字符集 | 优先 `Content-Type charset`,回退 utf-8/GB/latin-1 |
+| HTML 正文 | 保留 `tr/td/th` 行列边界(`\n`+`\t`);`html.unescape` 解码实体 |
+| 安全 | 仅 MIME 解码 + 文本抽取;不执行宏、OLE 脚本或嵌入可执行内容 |
+| 失败隔离 | 单附件损坏 → `parse_status=failed|empty`,其余附件继续;**前后端** incomplete 门禁阻断建批(含文本预算耗尽、`eml_attachment_text_truncated`、`notice_text_truncated`);不完整时可重试解析 |
+| 持久化 | DB 保留附件全文(单附件 + **全部附件合计预算**);预算耗尽写入 `eml_attachment_text_budget_exhausted` 并视为不完整;状态轮询瘦身,详情接口按需返回全文 |
+| 计数 | `attachment_count`=发现总数(含超限未登记);`attachment_registered_count`/`attachments[]`=已登记项 |
+| 解析器版本 | 默认见阶段二(当前 `v6`);阶段一语义在 v5 已对齐(mixed HTML / 附件型 alternative) |
+| 建批门禁 | `create_shipping_batch_from_intakes` 除要求 `parse_status=parsed` 外,须通过 `attachment_integrity`;前端 `shippingNoticeAttachmentIntegrity.ts` 与后端 `BLOCKING_WARNING_PREFIXES` 契约一致(测试双向校验) |
+| 重试解析 | 允许 `parse_failed`,或 `parsed` 但附件不完整;UI 对两类均展示重试按钮 |
+
+#### 配置项(`settings.py`)
+
+| 环境变量 | 默认 | 含义 |
+| --- | --- | --- |
+| `SHIPPING_NOTICE_EML_MAX_ATTACHMENTS` | `20` | 单封邮件最多登记的真实附件数 |
+| `SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES` | `20971520`(20MB) | 单附件大小上限 |
+| `SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES` | `52428800`(50MB) | 全部附件合计大小上限 |
+| `SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH` | `3` | `message/rfc822` / 嵌套 eml 最大深度 |
+| `SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS` | `500000` | 全部附件 `extracted_text` 写入 structured_result_json 的合计字符上限 |
+
+#### 警告码(`parse_warnings` / meta.warnings)
+
+| 码 | 含义 |
+| --- | --- |
+| `eml_inline_resources_skipped:N` | 跳过了 N 个内嵌/签名资源 |
+| `eml_attachment_limit_exceeded:N:discovered=M` | 登记上限为 N,实际发现 M 个真实附件 |
+| `eml_attachment_too_large:filename:size` | 单附件过大被跳过 |
+| `eml_total_attachment_size_exceeded:N` | 附件总大小超限 |
+| `eml_nesting_depth_exceeded:N` | 嵌套深度超限 |
+| `eml_attachment_duplicate:filename` | 同信内内容哈希重复 |
+| `eml_attachment_extract_failed:filename` | 附件文本抽取失败 |
+| `eml_attachment_text_truncated:N` / `eml_body_text_truncated:N` | **N=截断上限字符数**;另见 `text_length`/`stored_text_length`。其中 **`eml_attachment_text_truncated` 为建批阻断项**(`eml_body_text_truncated` 暂不阻断) |
+| `eml_attachment_text_budget_exhausted:N` | 全部附件落库文本合计超过 `SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS`(建批阻断) |
+| `notice_text_truncated:N` | 扁平 `extracted_text` 超 `NOTICE_TEXT_MAX_CHARS`(建批阻断) |
+| `eml_nested_message_unreadable` | 嵌套 rfc822 无法解析(建批阻断) |
+
+#### Intake 结构化结果(节选)
+
+预解析写入 DB 的 `structured_result_json`(含附件全文,截断后);状态轮询返回瘦身摘要:
+
+```json
+{
+ "email": {
+ "message_id": "",
+ "subject": "PO 4510039227, 4510039228, 4510039229",
+ "from": "laszlo.fussy@example.com",
+ "body_text_length": 1200,
+ "stored_body_text_length": 1200
+ },
+ "attachment_count": 3,
+ "attachment_registered_count": 3,
+ "attachments": [
+ {
+ "attachment_key": "att-001",
+ "filename": "4510039227.pdf",
+ "mime_type": "application/pdf",
+ "content_hash": "...",
+ "parse_status": "parsed",
+ "text_length": 1234,
+ "stored_text_length": 1234
+ }
+ ]
+}
+```
+
+`GET /shipping-notice/intakes/{intake_no}` 详情另含 `email.body_text` 与 `attachments[].extracted_text`。
+
+聊天输入栏在「解析完成」后展示 `附件 ok/total`(悬停 title 含各附件文件名与状态)。
+
+实现入口:`eml_parse.parse_eml_bytes` ← `notice_upload.extract_notice_text`;摘要组装:`intake_parse_workflow.intake_result_to_structured_summary`。
+
> **实现策略(强制)**:根据行业最佳实践,优先在 Dify 中实现适合由 AI 编排层承接的能力,包括但不限于 Chatflow / Workflow、Agent、LLM 节点、Code 节点、Tool 节点、If-Else 分流,以及人工确认节点所需的解释、建议与交互编排。对于任务/批次持久化、主状态机、后台续跑、失败恢复、审计留痕、二进制文件处理、RPA/上传回执及外部系统集成等生产级业务职责,统一由 hxops 后端承担。本方案的判断标准不是“Dify 是否能实现”,而是“该能力是否适合由 AI 编排层承接,还是应由业务后端作为真相源与主调度层承接”。
**Tool API 基路径**:`/api/shipping-notice`\
@@ -86,6 +212,12 @@ FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# 建单后延后 parse_notice 到 Dify 画布(默认 true,符合 Dify 编排优先)
# SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY=true
+# EML 附件提取安全上限(阶段一)
+# SHIPPING_NOTICE_EML_MAX_ATTACHMENTS=20
+# SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES=20971520
+# SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES=52428800
+# SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH=3
+
# 批次后台调度:每个批次最多同时派发几张票(默认 3)
# SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY=3
@@ -292,12 +424,60 @@ $env:FREIGHT_RPA_LOG_BACKUP_COUNT = "5"
$env:FREIGHT_RPA_DSV_USERNAME = "请替换为DSV账号"
$env:FREIGHT_RPA_DSV_PASSWORD = "请替换为DSV密码"
-# 如需 Crane:
-# $env:FREIGHT_RPA_CRANE_USERNAME = "请替换为Crane账号"
-# $env:FREIGHT_RPA_CRANE_PASSWORD = "请替换为Crane密码"
+$env:FREIGHT_RPA_CRANE_USERNAME = "请替换为Crane账号"
+$env:FREIGHT_RPA_CRANE_PASSWORD = "请替换为Crane密码"
+
+# 心跳与共享 scope(test/prod 必填;与 Ubuntu SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID 一致)
+$env:FREIGHT_RPA_ENVIRONMENT = "test"
+$env:FREIGHT_RPA_SHARED_SCOPE_ID = "hxops-rpa-test-data"
+$env:FREIGHT_RPA_HEARTBEAT_SECONDS = "20"
```
-正式环境测试时,将 `C:\HxopsRpaTest` 改为 `C:\HxopsRpaProd`,并把 `HXOPS_API_BASE`、`SHIPPING_NOTICE_TOOL_API_KEY` 改为正式后端对应值。
+正式环境测试时,将 `C:\HxopsRpaTest` 改为 `C:\HxopsRpaProd`,`FREIGHT_RPA_ENVIRONMENT` 改为 `prod`,`FREIGHT_RPA_SHARED_SCOPE_ID` 改为 `hxops-rpa-prod-data`,并把 `HXOPS_API_BASE`、`SHIPPING_NOTICE_TOOL_API_KEY` 改为正式后端对应值。
+
+也可使用仓库脚本一次性写入用户级永久变量(推荐):
+
+```powershell
+cd C:\HxopsRpaTest
+.\scripts\rpa\set_rpa_worker_env.ps1 -Environment test -ApiBase "http://测试后端:端口" -ToolApiKey "<与后端一致的密钥>"
+```
+
+#### 1.5.5a RPA Worker 心跳、共享 scope 与哨兵
+
+test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是否匹配、共享目录是否有效。Windows Worker 需周期性 `POST /api/shipping-notice/rpa/heartbeat`,并在**库存 trigger 共享目录**(`FREIGHT_RPA_INVENTORY_TRIGGER_DIR`,如 `...\inventory_triggers`)写入哨兵文件 `.hxops_rpa_shared_mount`(默认文件名,可由 `SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME` 覆盖)。
+
+| 侧 | 变量 | 测试示例 | 正式示例 |
+| --- | --- | --- | --- |
+| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` |
+| Windows RPA | `FREIGHT_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` |
+| Windows RPA | `FREIGHT_RPA_ENVIRONMENT` | `test` | `prod` |
+| Windows RPA | `FREIGHT_RPA_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 |
+| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS` | `90`(默认) | `90` |
+| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` | 逗号分隔 HXOPS 用户名(**部署前建议显式填写**) | 同左 |
+| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` |
+| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS` | `120`(企微发送中短锁,失败后可重试) | `120` |
+
+**告警接收人部署检查**:`SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` 留空时,仅当存在 `role=admin` 且已绑定 `wecom_userid` 的用户才会真正收到企微通知;否则只写 warning。上线前请二选一:填写运维用户名,或确认至少一名 admin 已完成企微绑定。
+
+**多进程去重**:告警冷却状态以 `app_settings` 为权威源,Redis 仅作缓存同步;DB 不可读写时才回退 Redis/进程内内存 claim。
+
+**为何必须显式配置 scope**:Windows 标准路径 `C:\HxopsRpaTest\data\...` 不含 `hxops-rpa-test-data` 字样,后端无法从路径推导 scope;漏配 `FREIGHT_RPA_SHARED_SCOPE_ID` 时 Worker 不写哨兵,就绪检查报 `shared_sentinel_missing`。
+
+Worker 启动后验证哨兵(测试环境示例):
+
+```powershell
+Get-Content C:\HxopsRpaTest\data\inventory_triggers\.hxops_rpa_shared_mount
+```
+
+应包含 `scope_id=hxops-rpa-test-data`。Ubuntu 对应路径:
+
+```bash
+cat /mnt/hxops-rpa-test-data/inventory_triggers/.hxops_rpa_shared_mount
+```
+
+管理端 `GET /api/admin/rpa-workers/status` 可查看最后心跳;Worker 离线时触发库存 RPA 会立即失败(fail-fast),不再空等 900s。
+
+心跳存储:test/prod 默认要求 **Redis**(`SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true`)。Redis 不可用时触发与排程会报 `RPA.HEARTBEAT_STORAGE_UNAVAILABLE`,调度器会按冷却发送企微「心跳存储异常」告警。
先验证 DSV 登录:
@@ -317,6 +497,27 @@ SUCCESS — DSV session ready
python scripts\rpa\dsv_export_smoke.py DSV360_AWSBI_BYAWSCMH01
```
+可选:验证 DSV **批量**导出链路(一次登录连续多仓,不回调后端):
+
+```powershell
+python scripts\rpa\dsv_export_batch_smoke.py warehouse
+python scripts\rpa\dsv_export_batch_smoke.py source_code
+python scripts\rpa\dsv_export_batch_smoke.py all
+```
+
+batch smoke **默认语义**:链路跑完即通过(退出码 0),**全 skipped(确认无库存、未导出 Excel)也算通过**。
+
+若 CI 或联调需要“至少真实导出一个 Excel”,启用严格模式:
+
+```powershell
+$env:FREIGHT_RPA_SMOKE_REQUIRE_EXPORT = "true"
+python scripts\rpa\dsv_export_batch_smoke.py warehouse
+```
+
+| 环境变量 | 默认值 | 说明 |
+| --- | --- | --- |
+| `FREIGHT_RPA_SMOKE_REQUIRE_EXPORT` | `false` | 为 `true` 时要求至少一条 `success` 导出;全 skipped 时退出码 **2** |
+
如果登录或导出失败,先排查 Windows 主机是否能手工打开 DSV/Crane、账号密码是否正确、是否需要 MFA/验证码/SSO、公司代理和证书是否正常。
#### 1.5.6 Ubuntu 后端主机:安装 SMB 工具并测试共享
@@ -461,6 +662,15 @@ FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
+
+# Worker 心跳与共享 scope(与 Windows FREIGHT_RPA_SHARED_SCOPE_ID 一致)
+SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
+SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
+SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true
+# 逗号分隔已绑企微的 HXOPS 用户名;留空且 FALLBACK_ADMIN=true 时通知 admin
+SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
+SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
+SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
```
正式环境只把路径改为 `/mnt/hxops-rpa-prod-data/...`,并使用正式环境的 `SHIPPING_NOTICE_TOOL_API_KEY`。
@@ -505,15 +715,29 @@ volumes:
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_DSV_USERNAME", "请替换为DSV账号", "User")
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_DSV_PASSWORD", "请替换为DSV密码", "User")
+
+# 心跳与共享 scope(test 示例;正式改为 prod + hxops-rpa-prod-data + C:\HxopsRpaProd\...)
+[Environment]::SetEnvironmentVariable("FREIGHT_RPA_ENVIRONMENT", "test", "User")
+[Environment]::SetEnvironmentVariable("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data", "User")
+[Environment]::SetEnvironmentVariable("FREIGHT_RPA_HEARTBEAT_SECONDS", "20", "User")
```
-以上写法适合只常驻一个 worker。若同一台 Windows 主机要同时常驻测试与正式,建议不要依赖用户级环境变量,而是分别准备两个启动脚本或任务计划,确保每个任务内显式设置各自的目录、API Base 与 Key。
+或使用脚本(参数按实际后端地址与密钥填写):
+
+```powershell
+cd C:\HxopsRpaTest
+.\scripts\rpa\set_rpa_worker_env.ps1 -Environment test -ApiBase "http://192.168.1.20:8890" -ToolApiKey "<密钥>"
+```
+
+以上写法适合只常驻一个 worker。若同一台 Windows 主机要同时常驻测试与正式,建议不要依赖用户级环境变量,而是分别准备两个启动脚本或任务计划,确保每个任务内显式设置各自的目录、API Base、scope 与 Key。
关闭并重新打开 PowerShell 后检查:
```powershell
echo $env:HXOPS_API_BASE
echo $env:FREIGHT_RPA_INVENTORY_TRIGGER_DIR
+echo $env:FREIGHT_RPA_SHARED_SCOPE_ID
+echo $env:FREIGHT_RPA_ENVIRONMENT
```
确认 worker 可手动启动:
@@ -564,11 +788,13 @@ Register-ScheduledTask `
3. Windows 执行 `python scripts\rpa\dsv_export_smoke.py DSV360_AWSBI_BYAWSATL01`。
4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\inventory_triggers` 能看到。
5. Windows 启动 `python scripts\rpa\freight_rpa_worker.py`。
-6. HXOPS 页面或排程触发库存 RPA 导出。
-7. Ubuntu 查看 trigger:`ls -lt /mnt/hxops-rpa-test-data/inventory_triggers`。
-8. Windows 查看 worker 输出;成功后 trigger 会进入 `C:\HxopsRpaTest\data\inventory_triggers\processed`。
-9. Excel 会落到 `C:\HxopsRpaTest\data\inventory_drop`,随后由后端回调流程入库为库存快照。
-10. HXOPS 任务应进入库存字段映射/库存匹配阶段;定时排程 run 应由 `awaiting_rpa_callback` 终态化为 `success` / `failed` / `partial_failed`。
+6. 确认哨兵:`Get-Content C:\HxopsRpaTest\data\inventory_triggers\.hxops_rpa_shared_mount` 含正确 `scope_id`。
+7. HXOPS 管理端或 `GET /api/admin/rpa-workers/status` 显示 Worker 在线。
+8. HXOPS 页面或排程触发库存 RPA 导出。
+9. Ubuntu 查看 trigger:`ls -lt /mnt/hxops-rpa-test-data/inventory_triggers`。
+10. Windows 查看 worker 输出;成功后 trigger 会进入 `C:\HxopsRpaTest\data\inventory_triggers\processed`。
+11. Excel 会落到 `C:\HxopsRpaTest\data\inventory_drop`,随后由后端回调流程入库为库存快照。
+12. HXOPS 任务应进入库存字段映射/库存匹配阶段;定时排程 run 应由 `awaiting_rpa_callback` 终态化为 `success` / `failed` / `partial_failed`。
#### 1.5.12 常见问题
@@ -1346,7 +1572,7 @@ def main(normalized_query: str = "", intent_hint: str = "", sys_files=None):
text = str(normalized_query or "").strip()
if files:
lower_names = " ".join(_file_name(f) for f in files)
- if any(ext in lower_names for ext in [".xlsx", ".xls", ".csv"]):
+ if any(ext in lower_names for ext in [".xlsx", ".csv"]):
return {"route_key": "inventory_path", "reason": "inventory_file"}
return {"route_key": "direct_answer", "reason": "notice_files_managed_by_hxops"}
if intent_hint in {
@@ -2841,7 +3067,7 @@ Agent 状态输入标准化 -> 货代续办 Agent
| 确认 / 驳回 / 重匹配直连 | `确认` / `驳回` / `重新匹配` / `rematch` | `submit_decision` | 是,直连决策 Tool | 当前任务或显式 `SN-...` | 按状态机推进;`rematch` 清理 shortage 并重新入队当前任务 | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_contract_submit_decision_rematch_is_direct_recovery_entry` |
| shortage 阻断 | shortage review 后输入 `继续` 或自动续跑 | `match_inventory` / `submit_decision` 返回门禁 | 是,命中状态机门禁后停止 | 当前任务 | `status=needs_human`;禁止 `generate_shipment_excel` / `upload_to_freight`;不生成 Excel | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_shipping_notice_match_shortage_needs_human` |
| 多任务只推进 focus task | 多票批次中输入 `继续处理` | `get_batch_status` + 当前 focus 的 `get_task_status` | 是,先读状态再决定 | `batch.current_focus_task_no` | 每轮只围绕一个 focus task;读批次状态不循环推进整批 | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_contract_batch_status_keeps_single_focus_without_advancing_other_tasks` |
-| 库存上传链路 | 上传 `.xlsx/.xls/.csv` | `get_inventory_schema_preview` → 映射 LLM → `apply_inventory_mapping` | 否,进入库存专用分支,不走自由 Agent | 当前任务 / 所属批次库存快照 | 生成 schema preview;应用映射后进入 `align_review` 或后端续跑 | 待实测 |
+| 库存上传链路 | 上传 `.xlsx/.csv` | `get_inventory_schema_preview` → 映射 LLM → `apply_inventory_mapping` | 否,进入库存专用分支,不走自由 Agent | 当前任务 / 所属批次库存快照 | 生成 schema preview;应用映射后进入 `align_review` 或后端续跑 | 待实测 |
| 字段对齐人工门 | `apply_inventory_mapping` 返回 `align_review` 后输入 `确认` | `submit_decision(decision=confirm_inventory_mapping)` | 是,直连决策 Tool | 当前任务 | 停住等待确认;确认后交由 hxops worker 续跑匹配 / 导出 / 上传 | 待实测 |
| Tool 人工门收口 | 任一 Tool 返回 `needs_human` 或 `stop_agent_turn=true` | 工具结果标准化 | 是,硬停止本轮 | 当前任务 | 本轮不再继续调用后续 Tool | 待实测 |
| forbidden_next_tools 门禁 | Tool 返回 `forbidden_next_tools` | 工具结果标准化 | 是,硬门禁 | 当前任务 | 画布不调用被禁止 Tool | 待实测 |
@@ -2905,7 +3131,10 @@ Agent 状态输入标准化 -> 货代续办 Agent
| `upload_status` | 上传子状态 |
| `upload_mode` | 上传模式 |
| `upload_attempt` | 上传重试次数 |
-| `idempotency_key` | 上传幂等键 |
+| `idempotency_key` | **货代上传**幂等键(与建单幂等分离) |
+| `source_content_hash` | 源文件 SHA-256(小写十六进制,基于原始字节) |
+
+`ShippingBatch` 另含 `create_idempotency_key`:**建单**幂等键;唯一约束 `(user_id, create_idempotency_key)` 防止双击/重试/并发重复建批。Chat Turn 与 Workspace API 经 `batch_from_notices.create_shipping_batch_from_notice_items()` 共用该逻辑。
常见 `process_status` / 子状态:
@@ -3155,7 +3384,9 @@ API 层
| `backend/app/services/shipping_notice/state_machine.py` | checkpoint / action\_buttons / 人工节点规则 |
| `backend/app/services/shipping_notice/user_facing_status.py` | Tool 投影字段裁剪、用户可见阶段文案 |
| `backend/app/services/shipping_notice/openapi_spec.py` | Dify 使用的 OpenAPI 生成 |
-| `backend/app/services/shipping_notice/inventory_upload.py` | 库存文件上传与读取 |
+| `backend/app/services/shipping_notice/notice_upload.py` | 通知附件接入、文本抽取、截断;EML 委托 `eml_parse` |
+| `backend/app/services/shipping_notice/eml_parse.py` | EML 结构化解析(元数据/正文/真实附件/嵌套 rfc822) |
+| `backend/app/services/shipping_notice/intake_parse_workflow.py` | Intake 预解析;EML meta 写入 `structured_result_json` |
| `backend/app/services/shipping_notice/export.py` | 发货 Excel 生成 |
| `backend/app/services/shipping_notice/rpa.py` | RPA 触发文件写入(低层 I/O) |
@@ -3197,7 +3428,7 @@ API 层
### 5.2 快照复用规则
-1. `ensure_inventory(mode=auto)` 在解析库存源后,优先 `find_latest_ready_snapshot(source_code, warehouse_id)`
+1. `ensure_inventory(mode=auto)` 在库存源**已稳定**后,优先 `find_latest_ready_snapshot(source_code, site_id, warehouse_id)`
2. 未过期快照 → `link_snapshot_to_task(reason=reuse_latest)` → 映射/匹配
3. 过期或缺失 → 触发 RPA(单 task trigger 或定时 batch trigger)
4. `retry_rpa` **强制跳过**快照缓存
@@ -3212,11 +3443,25 @@ API 层
- **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值)
- Worker:`scripts/rpa/freight_rpa_worker.py` → `_handle_inventory_batch_trigger`
- 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready`
+- **回调响应语义**(2026-07):`status` 恒为 `ok`(payload 合法且回调处理完成);**业务成败**看顶层 `result_status` 或 `data.result_status`(`success` / `partial_failed` / `failed`),全失败回调也是 `status=ok` + `result_status=failed`。**排程场景**(含 `schedule_run_id` 且 finalize 成功)时 `result_status` 与 `ScheduleRun.status` 一致;`data.callback_result_status` 保留仅按回调 results 计算的原始结果。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。
- 定时排程:`schedule_type=platform_job`,`platform_api_path=shipping-inventory-rpa`,`data_source_type=null`;建议 cron `0 3 * * *`(Asia/Shanghai)
- 排程语义:`data_source_type` 仅用于 `schedule_type=data_pipeline`(`database` | `external_api`);平台任务通过 Job Registry 注册,由 `platform_api_path` 引用 job key
### 5.4 审计字段
-- `shipping_inventory_files`:`warehouse_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id`
-- `shipping_task_inventory_links`:`link_reason`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json`
+- `shipping_inventory_files`:`warehouse_id`、`site_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id`、`identity_status`
+- `shipping_task_inventory_links`:`link_reason`、`matched_source_code`、`matched_site_id`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json`、身份校验字段
+
+### 5.5 订单解析阶段库存源判定(2026-07)
+
+> 详细方案见 [`inventory_source_plan.md`](./inventory_source_plan.md)。
+
+1. **`parse_notice` 内 adjudicate**:读取任务 `destination_*` 与 YAML `match`/`match_aliases`,产出 `InventorySourceAdjudication`(写入线索/候选)。
+2. **先解析复核,再定库存源**:低置信度先 `checkpoint=parse_review`(含重新解析);解析通过(人工确认或高置信度自动过)后,若源未稳定再进 `inventory_source_review`。RPA 等后续步骤仍要求 `inventory_source_status ∈ {resolved, user_confirmed}`。
+ - **问题清单**:`ui_state.summary.issues` 汇总当前检查点原因 + parse warnings;解析复核阶段可提示「确认后再选库存源」;存量 `pending_parse_review_after_source` 仍兼容旧顺序。
+3. **独立字段为真相源**:`inventory_source_code`、`inventory_site_id`、`inventory_warehouse_id` 等存于 `shipping_tasks` 列,gate 不读 `step_payload_json`。
+4. **用户只确认 source_code**:`confirm_inventory_source` 根据编码回填 site/warehouse;路由指纹变更时要求重确认(`SHIPPING.INVENTORY_SOURCE_CHANGED`)。
+5. **硬 Gate**:`inventory_rpa_workflow`、`inventory_workflow`、`fulfillment_workflow`、`progress_workflow` 入口均调用 `assert_inventory_source_gate`。
+6. **快照复用键**:`find_latest_ready_snapshot(source_code, site_id, warehouse_id)`;link 时做 identity check。
+7. **迁移**:`b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields`。
diff --git a/docs/funclist.md b/docs/funclist.md
index 6c6ca713..0e2cb309 100644
--- a/docs/funclist.md
+++ b/docs/funclist.md
@@ -58,10 +58,18 @@
| --- | --- | --- |
| 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) |
| 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) |
+| 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 |
+| EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 |
+| 附件资产化与订单候选(阶段二) | 已实现 | EML 附件派生 FileAsset;Document 关联边引用计数;partial unique + 软删复活;cancel 释放 Document/Candidate;MinIO 补偿失败记 orphan_cleanup;候选去重在 SAVEPOINT;失败/资产缺失统一阶段二清理;预解析 Job 超时回收同步 Intake + parse_lease 代次隔离;入队原子绑定 parse_job_id;Intake 创建 FOR UPDATE/IntegrityError 幂等,cancelled/expired 禁止复活;enqueue 仅 SAVEPOINT 内插入;替代 Job FOR UPDATE,仅 queued 或已持精确 lease 的 running 可 supersede;parser v6;暂不按候选建 Task;见技术手册「附件资产化与订单候选」 |
| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML |
+| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` |
+| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings |
+| 库存源人工确认与 Gate | 已实现 | `confirm_inventory_source`;RPA/匹配/Excel/上传硬阻断;独立 DB 字段持久化 |
+| 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 |
| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 |
| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` |
| 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` |
+| 建单防重复(第一阶段) | 已实现 | 批次 `create_idempotency_key`、任务 `source_content_hash`、同请求去重、幂等重放 |
| 产品原型 | 已文档化 | 见 [docs/prototype/shipping_notice_agent_prototype.md](prototype/shipping_notice_agent_prototype.md) |
### 排程平台任务契约中心(schedule)
@@ -113,7 +121,7 @@
| 固资本地快照查询 | 已实现 | `固资管理` Agent 优先查询 SQLite 最新快照,减少实时 ERP 压力 |
| 固资导出文件 | 已实现 | 同步成功后生成 `FixedAssets_latest.xlsx`,供人工核查与留档 |
| 固资快照技术方案 | 已文档化 | 见 [docs/features/fixed-assets/technical.md](features/fixed-assets/technical.md) |
-| 固资履历查看 | 已实现 | 聊天结果中的 `资产编号` 支持点击后检索共享盘履历文件,并复用现有预览弹窗查看 |
+| 固资履历查看 | 已实现 | 聊天结果中的 `资产编号` 支持点击后检索共享盘履历文件,并复用现有预览弹窗查看;Windows 本地可直接访问 UNC 共享盘,Linux 测试/生产通过 `scripts/mount_fixed_asset_history.sh` 挂载后由 `FIXED_ASSET_HISTORY_LOCAL_ROOT` 读取(compose 已 bind 进 backend) |
### F-01 本人假期查询
@@ -451,14 +459,24 @@
---
-## 7. 移动端适配功能清单
+## 7. 管理端功能清单
-### 7.1 功能总览
+| 功能项 | 说明 | 状态 | 优先级 |
+| --- | --- | --- | --- |
+| 管理端使用分析 | 管理控制台「数据报表」首项由原始用户表替换为「使用分析」,展示对话总量、活跃用户/应用、按日趋势、应用/用户排行、低使用应用与异常高峰提醒,并保留聊天明细追溯与导出 | 已实现 | P1 |
+| 管理端应用运营报表 | 「数据报表 > 应用」由 agents 配置表替换为应用运营看板:按应用聚合对话/用户/最近活跃/授权/待审/均分,支持时间范围与状态筛选、Excel 导出,并可下钻聊天日志与权限申请 | 已实现 | P1 |
+
+---
+
+## 8. 移动端适配功能清单
+
+### 8.1 功能总览
| 功能项 | 说明 | 状态 | 优先级 |
| --- | --- | --- | --- |
| 移动端自动识别 | 屏幕高度>宽度时判定为手机端,实时响应方向变化 | 已完成 | P0 |
| 手机端登录流程 | 未登录仍进入登录页,登录表单移动端可用 | 已完成 | P0 |
+| 登录页记住我 | 登录页支持“记住我(记住登录状态 + 记住账号密码)”方案;勾选后优先保持 30 天登录态,用户回到登录页时自动回填账号和密码,可直接点击登录进入系统;取消勾选后自动清除本地回填信息 | 已实现 | P1 |
| 登录后默认进 Chat | 已登录访问根路径自动跳转 `/chat/16` | 已完成 | P0 |
| 受保护页面认证守卫 | 未登录访问受保护页面重定向到登录页 | 已完成 | P0 |
| PC 侧边栏移动端隐藏 | ChatView/WorkspaceView 侧边栏在手机端不渲染 | 已完成 | P0 |
@@ -466,10 +484,13 @@
| 右上角个人设置按钮 | UserCircle 图标按钮,点击进入 /profile | 已完成 | P0 |
| ProfileView 移动端返回 | 返回按钮手机端回 Chat,PC 端回 Workspace | 已完成 | P1 |
-### 7.2 验收清单
+### 8.2 验收清单
- 手机竖屏访问时自动进入适配布局
- 未登录时正确显示登录页
+- 勾选“记住我”后,登录态有效时可直接进入系统;用户回到登录页时可自动回填账号和密码
+- 取消“记住我”后,下次进入登录页不再自动回填账号和密码
+- 登录页本地 remember 数据可被清理,不影响正常密码登录与企微登录
- 登录后默认跳转到 Chat 页面
- 移动端不显示 PC 端左侧导航/侧边栏
- 移动端右上角可见个人设置图标按钮
diff --git a/docs/openapi/file_check_tools_openapi.json b/docs/openapi/file_check_tools_openapi.json
index b413d781..a176c6f2 100644
--- a/docs/openapi/file_check_tools_openapi.json
+++ b/docs/openapi/file_check_tools_openapi.json
@@ -7,7 +7,7 @@
},
"servers": [
{
- "url": "http://127.0.0.1:5052",
+ "url": "http://192.168.100.192:8890",
"description": "HXOPS_TOOLS_API_BASE"
}
],
@@ -108,6 +108,9 @@
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
+ },
+ "503": {
+ "$ref": "#/components/responses/DataSourceUnavailable"
}
}
}
@@ -533,7 +536,8 @@
"properties": {
"task_id": {
"type": "integer",
- "example": 12
+ "example": 12,
+ "description": "检核任务 ID(ScheduleTask.id);绑定 解析运行态上下文.task_id_int(Number),勿绑意图识别.task_id"
},
"trigger_source": {
"type": "string",
@@ -561,7 +565,7 @@
"required": [
"task_id"
],
- "description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
+ "description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
},
"RunCheckSuccessResponse": {
"type": "object",
diff --git a/docs/openapi/shipping_notice_tools.dify.json b/docs/openapi/shipping_notice_tools.dify.json
index b321e0a7..12ef9266 100644
--- a/docs/openapi/shipping_notice_tools.dify.json
+++ b/docs/openapi/shipping_notice_tools.dify.json
@@ -346,6 +346,50 @@
}
}
},
+ "/tools/confirm_inventory_source": {
+ "post": {
+ "operationId": "confirm_inventory_source",
+ "summary": "在库存源人工检查点确认正式库存查询来源(仅提交 source_code)",
+ "description": "库存源门禁:稳定身份须同时具备 source_code、source_type、site_id、warehouse_id,且 routing_fingerprint 与当前配置版本一致。Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。若返回 needs_human,说明身份未完整解析或需先完成解析确认。",
+ "parameters": [],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "task_id": {
+ "type": "string",
+ "description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
+ },
+ "source_code": {
+ "type": "string",
+ "description": "启用配置中的库存源编码,如 DSV360_AWSDU、CRANE;站点 site_id 与库位 warehouse_id 由后端根据配置与订单路由解析,禁止前端直传"
+ }
+ },
+ "required": [
+ "task_id",
+ "source_code"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/tools/submit_decision": {
"post": {
"operationId": "submit_decision",
@@ -411,8 +455,8 @@
"/tools/get_task_status": {
"post": {
"operationId": "get_task_status",
- "summary": "查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
- "description": "查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
+ "summary": "查询任务当前状态与 human_options;响应含 inventory_source_* 独立字段与候选结构",
+ "description": "返回 inventory_source_code、inventory_source_type、inventory_site_id、inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|user_confirmed|invalid|conflicted)、inventory_source_method、inventory_source_config_version、inventory_routing_fingerprint、inventory_source_confirmed_by、inventory_source_confirmed_at,以及 step_payload.inventory_source_resolution.candidates。",
"parameters": [],
"requestBody": {
"required": true,
@@ -488,4 +532,4 @@
}
}
}
-}
+}
\ No newline at end of file
diff --git a/docs/release_note/W29-V26.7.1.txt b/docs/release_note/W29-V26.7.1.txt
new file mode 100644
index 00000000..dde97286
--- /dev/null
+++ b/docs/release_note/W29-V26.7.1.txt
@@ -0,0 +1,42 @@
+版本:V26.7.1
+更新周期:2026-06-23 ~ 2026-07-14
+
+————————————————————
+【面向用户】
+————————————————————
+
+本次更新亮点:
+
+1. 员工培训 Agent:新增新人入职与员工培训闭环,可在对话中进入培训/考试工作区,支持学习、答题、交卷结算;管理员与 HR 可查看培训相关统计。
+
+2. 设备维保助手 Agent:新增设备维保智能助手,可识别维保相关意图,协助查询设备与维保信息。
+
+3. 固资管理 Agent:支持资产履历直达预览与下载,Excel 预览体验优化,连续查询更稳定。
+
+4. 货代发货 Agent:支持重新上传发货通知、批量自动处理与任务重试;新增库存快照与导出能力,批次任务跟踪更清晰。
+
+5. 其它优化:开启语音输入;意见反馈可同步通知企业微信;文件检核进度展示更直观;知识库上传与 PDF(含图文 OCR)同步更可靠;页面加载与后台管理体验持续优化。
+
+————————————————————
+【面向开发者】
+————————————————————
+
+本次更新亮点:
+
+1. 员工培训:完成培训闭环与管理配置;培训工作区考试流转(交卷后再结算);角色化常见问题;透传账号角色到 Dify;HR 统计问答兜底与布局交互修复;试题 PDF 导入判断题解析修复
+
+2. 设备维保:新增维保助手相关能力、意图识别、上下文设备解析及 Tool Key 配置
+
+3. 固资管理:对接 Dify 查询;支持资产履历预览与下载权限;修复连续问答、宽泛查询空字段与首轮会话中断等问题;快照同步增加账套字段与自动清理
+
+4. 货代发货:批量自动处理与任务重试;重新上传发货通知;库存快照管理与 RPA 批量导出;发货消息与轻量工作台逻辑优化;排程增加库存源描述与站点 ID、平台任务参数契约与动态选项
+
+5. 文件检核:进度卡片展示合格/不合格/人工判定笔数;持久化 chat_tool_runs;统一 agent_runtime_context 注入;增强可靠性元信息与错误分类
+
+6. 知识库:手册/设计类 PDF 保留图片并 OCR 写入 Markdown 再同步;上传提示与页面样式优化;清洗超时与 job 队列重构;旧 KB 任务入队兼容
+
+7. 聊天与交互:开启语音输入;源文件解析不阻塞 SSE;修复生产源文件名兜底问题;智能体支持分级显示与聚合应用配置;意见反馈通知企业微信群
+
+8. 管理后台:Admin 列表排序过滤;聊天日志与应用权限优化;知识库配置布局调整
+
+9. 工程与基建:后端 core/基础设施迁移与 models 拆分;admin/schedule 重构;push 前校验 migration multiple head;文件检核与货代相关单测补充
diff --git a/docs/tec.md b/docs/tec.md
index 6f94d2f2..c5ffe3cf 100644
--- a/docs/tec.md
+++ b/docs/tec.md
@@ -24,6 +24,8 @@
- 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。
- 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。
- `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。
+- **库存源判定前移至订单解析**:`parse_notice` 根据 `shipping_inventory_sources.yaml` 与目的地字段自动 adjudicate;仅 `inventory_source_status` 为 `resolved` 或 `user_confirmed` 时允许 RPA 与后续步骤;`site_id` 与 `warehouse_id` 由配置生成,用户只确认 `source_code`。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。
+- **建单防重复(第一阶段)**:`ShippingBatch.create_idempotency_key` + `(user_id, create_idempotency_key)` 唯一约束提供并发保护;`ShippingTask.source_content_hash` 记录源文件 SHA-256;Chat Turn 与 Workspace API 共用 `batch_from_notices` 幂等逻辑;与货代上传 `ShippingTask.idempotency_key` 语义分离。
### 2.1 已有聊天路由能力
@@ -765,6 +767,31 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth;
- 路由守卫对 `/workspace` 等直接访问不做拦截,PC 端行为不变
- PC 端侧边栏、导航栏、布局结构无任何 CSS 或 DOM 变更
+### 16.6 登录页“记住我”方案补充
+
+- **产品口径**:按当前业务确认,登录页采用“记住我(记住登录状态 + 记住账号密码)”方案;用户勾选后,回到登录页时应自动回填账号和密码,允许直接点击【登录】进入系统。
+- **现有基础**:前端认证工具 `shared/utils/auth.ts` 已支持:
+ - 勾选时将登录态持久化到 `localStorage`
+ - 未勾选时仅保存在 `sessionStorage`
+ - `hxops_user` 本地持久化有效期 30 天
+ - 登录页现已补齐“记住我”勾选框、remembered username/password 回填与浏览器密码自动填充兼容属性
+- **推荐交互**:
+ - 勾选“记住我”并登录成功后:持久化登录态,并额外记住用户名和密码
+ - 下次进入登录页时:若登录态仍有效,则直接进入系统;若用户因登出或登录态失效回到登录页,则自动回填账号和密码
+ - 用户取消勾选后:清除 remembered username/password、remember flag 与本地持久登录态
+- **本地存储建议**:
+ - 认证数据继续沿用现有 `hxops_user`
+ - 登录页偏好建议独立存储,如 `hxops_login_remember`、`hxops_login_profile`
+ - `hxops_login_profile` 保存 `username`、本地可恢复的 `password_ciphertext` 与更新时间,用于登录页自动回填
+- **浏览器密码兼容**:
+ - 用户名输入框补 `autocomplete="username"`
+ - 密码输入框补 `autocomplete="current-password"`
+ - 浏览器若支持密码管理器,可继续辅助自动填充;当前主能力仍以前端 remember 存储为准
+- **实现边界**:
+ - 本方案不新增后端接口,仍复用现有密码登录与 refresh token 机制
+ - remembered password 仅用于登录页自动回填,不参与后端持久化
+ - 用户取消勾选后,必须同步清理本地 remembered password,避免后续误填
+
---
diff --git a/docs/test_plan_matrix.md b/docs/test_plan_matrix.md
index efe03e6a..9d52be2f 100644
--- a/docs/test_plan_matrix.md
+++ b/docs/test_plan_matrix.md
@@ -33,4 +33,7 @@
| **个性化** | **常用问题** | 用户添加/删除自定义的常用问题 (Quick Questions)。 | 模拟 User POST/DELETE `/api/user/quick-questions`。 | `{ "title": "日报", "question": "写一份日报", "agent_id": 1 }` | HTTP 201 Created; 再次查询列表能看到该问题。 |
| **报表监控** | **仪表盘** | 管理员查看系统概览 (Agent 数、用户数、对话总数)。 | 模拟 Admin GET `/api/admin/dashboard` (或各统计接口)。 | Header: `X-Role: admin` | HTTP 200 OK; 返回 `{ "total_agents": 10, "total_users": 50 ... }`。 |
| **报表监控** | **数据导出** | 管理员导出用户、日志等数据为 Excel/CSV。 | 模拟 Admin GET `/api/admin/database/{table_name}`。 | URL Path: `/api/admin/database/chat_logs` | HTTP 200 OK; 返回完整数据列表。 |
+| **发货通知** | **建单幂等** | 相同 `create_idempotency_key` 重复请求返回同一批次,不重复启动 orchestrator。 | `test_shipping_notice_batches.py`:Workspace API 双次 POST;断言 `idempotent_replay`、任务数、orchestrator 调用次数。 | Header `Idempotency-Key` + 相同 notice 文件 | 第二次 `batch_no` 相同;`idempotent_replay=true`;DB 仅 1 批次。 |
+| **发货通知** | **同请求文件去重** | 同一次上传中内容相同文件只建 1 个任务。 | `test_notice_intake.py` / `test_shipping_notice_batches.py`:2 个同字节不同文件名。 | 2× 相同内容 PDF | `duplicate_count=1`;`tasks` 长度 1。 |
+| **发货通知** | **双击/重试前端锁** | 建批提交中重复发送被消费,幂等键在重试间保持稳定。 | `useChatShippingUploadHandler.spec.ts` / `useChatShippingSendHandler.spec.ts` | 连续点击发送 | `startChatTurn` 仅 1 次;失败重试复用同一 `idempotency_key`。 |
diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts
index d83a43a5..c97ee905 100644
--- a/frontend/src/features/admin/api/admin.api.ts
+++ b/frontend/src/features/admin/api/admin.api.ts
@@ -7,7 +7,14 @@ import { requestJson } from '@/shared/api/client';
import type { AdminUserRow } from '../types/admin.types';
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
import type { PaginatedResult } from '@/shared/types/pagination.types';
-import type { UsageReport, UsageRangeKey } from '../types/report.types';
+import type {
+ ApplicationReport,
+ ApplicationSortKey,
+ ApplicationStatusFilter,
+ ApplicationUsageFilter,
+ UsageReport,
+ UsageRangeKey,
+} from '../types/report.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
@@ -275,6 +282,39 @@ export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
auth(),
);
};
+
+export interface AdminApplicationReportParams {
+ range?: UsageRangeKey;
+ status?: ApplicationStatusFilter;
+ usage?: ApplicationUsageFilter;
+ q?: string;
+ sort?: ApplicationSortKey;
+ order?: 'asc' | 'desc';
+ page?: number;
+ page_size?: number;
+}
+
+/**
+ * 拉取应用运营报表(按应用聚合使用 / 权限 / 评分)。
+ * @param params - 时间范围、状态、使用筛选、搜索与排序分页
+ */
+export const getAdminApplicationReport = (params: AdminApplicationReportParams = {}) => {
+ const qs = new URLSearchParams();
+ if (params.range) qs.set('range', params.range);
+ if (params.status && params.status !== 'all') qs.set('status', params.status);
+ if (params.usage && params.usage !== 'all') qs.set('usage', params.usage);
+ if (params.q?.trim()) qs.set('q', params.q.trim());
+ if (params.sort) qs.set('sort', params.sort);
+ if (params.order) qs.set('order', params.order);
+ if (params.page != null) qs.set('page', String(params.page));
+ if (params.page_size != null) qs.set('page_size', String(params.page_size));
+ const query = qs.toString();
+ return requestJson(
+ `/api/admin/reports/applications${query ? `?${query}` : ''}`,
+ auth(),
+ );
+};
+
export const getAdminFeedbackReport = () => requestJson('/api/admin/reports/feedback', auth());
export const getAdminReportTable = (url: string) => requestJson(url, auth());
export const getAdminReportTableCount = (url: string) => requestJson<{ total: number }>(url, auth());
diff --git a/frontend/src/features/admin/api/schedule.api.ts b/frontend/src/features/admin/api/schedule.api.ts
index b8e6a642..36eefa61 100644
--- a/frontend/src/features/admin/api/schedule.api.ts
+++ b/frontend/src/features/admin/api/schedule.api.ts
@@ -156,4 +156,42 @@ export const listAdminScheduleRuns = (taskId: number, params?: { status?: string
export const adminRunExcelUrl = (runId: number) => `/api/admin/schedule-runs/${runId}/excel`;
+export const adminRunInventoryRawZipUrl = (runId: number) =>
+ `/api/admin/schedule-runs/${runId}/inventory-raw-zip`;
+
+export interface RpaWorkerHeartbeatWorker {
+ worker_id?: string;
+ hostname?: string;
+ environment?: string;
+ status?: string;
+ capabilities?: string[];
+ trigger_dir?: string;
+ drop_dir?: string;
+ shared_scope_id?: string;
+ version?: string;
+ online?: boolean;
+ eligible?: boolean;
+ ineligible_reasons?: string[];
+ age_seconds?: number | null;
+ received_at?: string;
+ timestamp?: string;
+}
+
+export interface RpaWorkerHeartbeatSummary {
+ ready: boolean;
+ message: string;
+ detail_message?: string;
+ checked_at: string;
+ heartbeat_ttl_seconds: number;
+ backend_environment: string;
+ shared_scope_id?: string;
+ shared_sentinel_name?: string;
+ trigger_dir: string;
+ reasons: string[];
+ workers: RpaWorkerHeartbeatWorker[];
+}
+
+export const getAdminRpaWorkersStatus = () =>
+ getJson('/api/admin/rpa-workers/status');
+
export type { DifyExecutionSnapshot, ScheduleRun, ScheduleTask, StepLog, TestScheduleRunResult, TestScheduleSqlResult };
diff --git a/frontend/src/features/admin/components/AdminNav.vue b/frontend/src/features/admin/components/AdminNav.vue
index 220c5493..e8b708a9 100644
--- a/frontend/src/features/admin/components/AdminNav.vue
+++ b/frontend/src/features/admin/components/AdminNav.vue
@@ -1,9 +1,11 @@
/**
* features/admin/components/AdminNav.vue
* 管理后台左侧导航,使用子路由跳转。
+ * 依赖:admin-nav.store、modules 常量、vue-router。
+ * 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开以便看到激活项。
*/
diff --git a/frontend/src/features/admin/constants/modules.ts b/frontend/src/features/admin/constants/modules.ts
index 027ced55..4c2e3788 100644
--- a/frontend/src/features/admin/constants/modules.ts
+++ b/frontend/src/features/admin/constants/modules.ts
@@ -35,9 +35,9 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
];
export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
- 'users',
- 'agents',
+ 'usage_analysis',
'chat_logs',
+ 'agents',
'permission_requests',
'general_feedbacks',
'feedbacks',
diff --git a/frontend/src/features/admin/modules/agents/AgentsPage.vue b/frontend/src/features/admin/modules/agents/AgentsPage.vue
index 50dec8b7..9321ff1e 100644
--- a/frontend/src/features/admin/modules/agents/AgentsPage.vue
+++ b/frontend/src/features/admin/modules/agents/AgentsPage.vue
@@ -232,8 +232,12 @@ onMounted(() => {
{{ agent.name }}
-
- {{ agent.description || '—' }}
+
+ {{ agent.description }}
|
diff --git a/frontend/src/features/admin/modules/reports/ReportsPage.vue b/frontend/src/features/admin/modules/reports/ReportsPage.vue
index c6175954..6cf4f0f8 100644
--- a/frontend/src/features/admin/modules/reports/ReportsPage.vue
+++ b/frontend/src/features/admin/modules/reports/ReportsPage.vue
@@ -1,32 +1,80 @@
/**
* features/admin/modules/reports/ReportsPage.vue
- * 用途:管理后台报表独立页面(多表浏览、列筛选、聊天日志批量操作)。
- * 依赖:useReportsAdmin、DeleteConfirmDialog。
- * 逻辑:路由 /admin/reports/:table?;列宽由 composable 默认值与本地偏好控制。
+ * 用途:管理后台报表独立页面(使用分析、应用运营、多表浏览与聊天日志批量操作)。
+ * 依赖:useReportsAdmin、DeleteConfirmDialog、PaginationBar、lucide 图标。
+ * 逻辑:路由 /admin/reports/:table?;分页统一复用 shared/PaginationBar。
*/
@@ -116,13 +244,17 @@ onMounted(() => {
{{ t('admin.report.totalRows', { total: chatLogsTotal }) }}
-
+
+ {{ t('admin.report.totalRows', { total: applicationTotal }) }}
+
+
{{ t('admin.report.showingRange', { start: reportRangeStart, end: reportRangeEnd, total: reportTotalRows }) }}
-
+
+
+
+
+
{{ t('admin.report.usage') }}
+
{{ t('admin.report.usageIntro') }}
+
+
+
+
+
+
+
+
{{ t('admin.report.usageTotalSessions') }}
+
+
+
{{ usageReport.total }}
+
+
+
+ {{ t('admin.report.usageActiveUsers') }}
+
+
+
{{ usageUserTotal }}
+
{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}
+
+
+
+ {{ t('admin.report.usageActiveAgents') }}
+
+
+
{{ usageActiveAgentCount }}
+
+
+
+
+
+
+
{{ t('admin.report.usageTrend') }}
+
+
+
+
+
+
{{ formatUsageDayLabel(day.date) }}
+
+
+
{{ t('admin.report.usageTrendEmpty') }}
+
+
+
+
+
{{ t('admin.report.usageInsights') }}
+
+
+
+
+
+
{{ t('admin.report.usageLowAgents') }}
+
+
+
+ {{ t('admin.report.usageLowAgentsHint', { max: usageLowAgentMaxChats, limit: usageLowAgentListLimit }) }}
+
+
+
+
+
+ {{ item.agent }}
+ {{ item.count }}
+
+
+
{{ t('admin.report.usageLowAgentsEmpty') }}
+
+
+
+
{{ t('admin.report.usageSpikeDays') }}
+
+
+
+ {{ t('admin.report.usageSpikeDaysHint', {
+ min: usageSpikeDayMinChats,
+ multiplier: usageSpikeDayAvgMultiplier,
+ limit: usageSpikeDayListLimit,
+ }) }}
+
+
+
+
+
+ {{ item.date }}
+ {{ item.count }}
+
+
+
{{ t('admin.report.usageSpikeDaysEmpty') }}
+
+
+
+
+
+
+
+
+
{{ t('admin.report.byAgent') }}
+
{{ t('admin.report.usageByAgentHint') }}
+
+
+
+ {{ a.agent }}
+ {{ a.count }}
+
+
+ {{ t('admin.report.usageByAgentEmpty') }}
+
+
+
+
+
+
+
{{ t('admin.report.byUser') }}
+
{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}
+
+
+
+ {{ formatUsageUserLabel(u) }}
+ {{ u.count }}
+
+
+ {{ t('admin.report.usageByUserEmpty') }}
+
+
+
+
+
+
+
+
+
+
+
{{ t('admin.report.appOps.title') }}
+
{{ t('admin.report.appOps.intro') }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{{ t('admin.report.appOps.summaryPending') }}
+
{{ applicationSummary.pending_permission_total }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+ |
+ {{ t('admin.report.appOps.columns.category') }} |
+ {{ t('admin.report.appOps.columns.is_active') }} |
+ {{ t('admin.report.appOps.columns.actions') }} |
+
+
+
+
+ |
+ {{ t('admin.report.appOps.empty') }}
+ |
+
+
+ | {{ row.name }} |
+ {{ row.chat_count }} |
+ {{ row.unique_users }} |
+
+ {{ row.last_active_at ? formatLocalDateTime(row.last_active_at) : '-' }}
+ |
+ {{ row.authorized_users }} |
+ {{ row.pending_requests }} |
+
+ {{ row.avg_score == null ? '-' : row.avg_score }}
+ ({{ row.feedback_count }})
+ |
+ {{ row.category || '-' }} |
+
+
+ {{ row.is_active ? t('admin.report.appOps.statusActive') : t('admin.report.appOps.statusInactive') }}
+
+ |
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
@@ -245,7 +715,7 @@ onMounted(() => {
-
+
{{ t('admin.report.noData', { table: getReportTableLabel(currentTable) }) }}
@@ -327,147 +797,15 @@ onMounted(() => {
-
-
- {{ t('admin.report.paginationSummary', { total: reportTotalRows, page: reportCurrentPage, pages: reportTotalPages }) }}
-
-
-
-
-
-
-
-
-
-
-
-
-
{{ t('admin.report.usage') }}
-
-
-
-
-
{{ t('admin.report.byAgent') }}
-
-
- {{ a.agent }}
- {{ a.count }}
-
-
-
-
-
-
{{ t('admin.report.byUser') }}
-
{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}
-
-
-
- {{ u.username }}
- {{ u.count }}
-
-
- {{ t('admin.report.usageByUserEmpty') }}
-
-
-
-
- {{ t('admin.report.paginationSummary', { total: usageUserTotal, page: usageUserPage, pages: usageUserTotalPages }) }}
-
-
-
-
-
-
-
-
-
-
-
+
diff --git a/frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts b/frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts
index e2e195d2..dfcf4960 100644
--- a/frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts
+++ b/frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts
@@ -1,15 +1,17 @@
/**
* features/admin/modules/reports/composables/useReportsAdmin.ts
- * 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除与带时间范围的用量图表)。
- * 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime。
- * 逻辑:ReportsPage 调用本 composable;使用分析默认近一月,可切换 7d/30d/90d/180d/365d。
+ * 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除、使用分析与应用运营看板)。
+ * 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime、vue-router。
+ * 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,均复用 PaginationBar;
+ * 低使用应用优先消费后端 low_agents(含零使用启用应用),与应用运营口径对齐。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
-import { useRoute } from 'vue-router';
+import { useRoute, useRouter } from 'vue-router';
import * as XLSX from 'xlsx';
import {
batchDeleteAdminChatLogs,
+ getAdminApplicationReport,
getAdminReportTable,
getAdminReportTableCount,
getAdminUsageReport,
@@ -20,6 +22,11 @@ import { useMessage } from '@/shared/composables/useMessage';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { ADMIN_REPORT_TABLES } from '@/features/admin/constants/modules';
import type {
+ ApplicationReport,
+ ApplicationReportItem,
+ ApplicationSortKey,
+ ApplicationStatusFilter,
+ ApplicationUsageFilter,
ChatLogsLayoutPref,
ReportColumnConfig,
SortRule,
@@ -72,6 +79,7 @@ export function useReportsAdmin() {
const { t, locale } = useI18n();
const msg = useMessage();
const route = useRoute();
+ const router = useRouter();
const usageReport = ref
(null);
const usageUserPage = ref(1);
@@ -81,6 +89,24 @@ export function useReportsAdmin() {
const usageRange = ref('30d');
const usageRangeOptions: UsageRangeKey[] = ['7d', '30d', '90d', '180d', '365d'];
+ /** 按应用统计:前端分页(后端已返回范围内全部应用) */
+ const usageAgentPage = ref(1);
+ const usageAgentPageSize = ref(10);
+ const usageAgentPageSizeOptions = [5, 10, 20, 50];
+
+ /** 应用运营看板状态(替换原 agents 配置表浏览) */
+ const applicationReport = ref(null);
+ const applicationRange = ref('30d');
+ const applicationStatus = ref('all');
+ const applicationUsage = ref('all');
+ const applicationQuery = ref('');
+ const applicationSort = ref('chat_count');
+ const applicationOrder = ref<'asc' | 'desc'>('desc');
+ const applicationPage = ref(1);
+ const applicationPageSize = ref(20);
+ const applicationPageSizeOptions = [10, 20, 50, 100];
+ let applicationSearchTimer: ReturnType | null = null;
+
const loadUsageReport = async (): Promise => {
try {
usageReport.value = await getAdminUsageReport({
@@ -97,9 +123,193 @@ export function useReportsAdmin() {
}
};
+ /**
+ * 加载应用运营报表。
+ * 核心逻辑:调用 /reports/applications,按当前筛选与排序拉取分页数据。
+ */
+ const loadApplicationReport = async (): Promise => {
+ try {
+ applicationReport.value = await getAdminApplicationReport({
+ range: applicationRange.value,
+ status: applicationStatus.value,
+ usage: applicationUsage.value,
+ q: applicationQuery.value,
+ sort: applicationSort.value,
+ order: applicationOrder.value,
+ page: applicationPage.value,
+ page_size: applicationPageSize.value,
+ });
+ const pages = applicationReport.value?.pages ?? 1;
+ if (applicationPage.value > pages) {
+ applicationPage.value = pages;
+ }
+ } catch (e) {
+ console.error('Error loading application report:', e);
+ applicationReport.value = null;
+ }
+ };
+
+ const applicationSummary = computed(() => applicationReport.value?.summary ?? null);
+ const applicationItems = computed(() => applicationReport.value?.items ?? []);
+ const applicationTotal = computed(() => applicationReport.value?.total ?? 0);
+ const applicationTotalPages = computed(() => Math.max(1, applicationReport.value?.pages ?? 1));
+ const applicationPageButtons = computed(() =>
+ buildOffsetPageButtons(applicationPage.value, applicationTotalPages.value),
+ );
+
+ const goToApplicationPage = (page: number): void => {
+ applicationPage.value = Math.min(Math.max(1, page), applicationTotalPages.value);
+ void loadApplicationReport();
+ };
+ const prevApplicationPage = () => goToApplicationPage(applicationPage.value - 1);
+ const nextApplicationPage = () => goToApplicationPage(applicationPage.value + 1);
+
+ /**
+ * 切换应用运营表头排序;同列再次点击翻转升降序。
+ * @param key - 可排序字段
+ */
+ const onApplicationSortClick = (key: ApplicationSortKey): void => {
+ if (applicationSort.value === key) {
+ applicationOrder.value = applicationOrder.value === 'asc' ? 'desc' : 'asc';
+ } else {
+ applicationSort.value = key;
+ applicationOrder.value = key === 'name' ? 'asc' : 'desc';
+ }
+ applicationPage.value = 1;
+ void loadApplicationReport();
+ };
+
+ const getApplicationSortMark = (key: ApplicationSortKey): string => {
+ if (applicationSort.value !== key) return '';
+ return applicationOrder.value === 'asc' ? '^' : 'v';
+ };
+
+ /**
+ * 应用名称搜索防抖,避免输入过程中频繁打接口。
+ */
+ const handleApplicationSearchChange = (): void => {
+ if (applicationSearchTimer) clearTimeout(applicationSearchTimer);
+ applicationSearchTimer = setTimeout(() => {
+ applicationPage.value = 1;
+ void loadApplicationReport();
+ }, 400);
+ };
+
+ /**
+ * 下钻到聊天日志,按 agent_id 精确过滤。
+ * @param row - 应用运营行
+ */
+ const openApplicationChatLogs = (row: ApplicationReportItem): void => {
+ void router.push({
+ name: 'AdminReports',
+ params: { table: 'chat_logs' },
+ query: { agent_id: String(row.agent_id), agent_name: row.name },
+ });
+ };
+
+ /**
+ * 下钻到权限申请列表,按 agent_id 精确过滤。
+ * @param row - 应用运营行
+ */
+ const openApplicationPermissionRequests = (row: ApplicationReportItem): void => {
+ void router.push({
+ name: 'AdminReports',
+ params: { table: 'permission_requests' },
+ query: { agent_id: String(row.agent_id) },
+ });
+ };
+
+ /**
+ * 导出应用运营报表 Excel(仅运营字段)。
+ */
+ const exportApplicationReport = (): void => {
+ const items = applicationItems.value;
+ if (items.length === 0) return;
+ const rows = items.map((row) => ({
+ [t('admin.report.appOps.columns.name')]: row.name,
+ [t('admin.report.appOps.columns.is_active')]: row.is_active
+ ? t('admin.report.appOps.statusActive')
+ : t('admin.report.appOps.statusInactive'),
+ [t('admin.report.appOps.columns.category')]: row.category || '-',
+ [t('admin.report.appOps.columns.chat_count')]: row.chat_count,
+ [t('admin.report.appOps.columns.unique_users')]: row.unique_users,
+ [t('admin.report.appOps.columns.last_active_at')]: row.last_active_at
+ ? formatLocalDateTime(row.last_active_at)
+ : '-',
+ [t('admin.report.appOps.columns.authorized_users')]: row.authorized_users,
+ [t('admin.report.appOps.columns.pending_requests')]: row.pending_requests,
+ [t('admin.report.appOps.columns.avg_score')]: row.avg_score ?? '-',
+ [t('admin.report.appOps.columns.feedback_count')]: row.feedback_count,
+ [t('admin.report.appOps.columns.tokens_used')]: row.tokens_used,
+ }));
+ const ws = XLSX.utils.json_to_sheet(rows);
+ const wb = XLSX.utils.book_new();
+ XLSX.utils.book_append_sheet(wb, ws, 'applications');
+ XLSX.writeFile(wb, `applications_ops_${new Date().toISOString().split('T')[0]}.xlsx`);
+ };
+
const usageUserTotalPages = computed(() => Math.max(1, usageReport.value?.user_pages ?? 1));
const usageUserTotal = computed(() => usageReport.value?.user_total ?? 0);
const usageUserTopLimit = computed(() => usageReport.value?.user_top_limit ?? 50);
+ const usageActiveAgentCount = computed(() => usageReport.value?.by_agent.length ?? 0);
+ const usageTrendMax = computed(() => Math.max(1, ...(usageReport.value?.by_day || []).map((item) => item.count)));
+ /** 低使用应用:范围内对话次数 ≤ 该阈值(兜底;优先用后端返回值) */
+ const USAGE_LOW_AGENT_MAX_CHATS = 2;
+ /** 低使用应用提醒最多展示条数(兜底;优先用后端返回值) */
+ const USAGE_LOW_AGENT_LIST_LIMIT = 5;
+ /** 异常高峰:单日对话量下限(与日均倍数取较大者) */
+ const USAGE_SPIKE_DAY_MIN_CHATS = 5;
+ /** 异常高峰:相对日均的倍数阈值 */
+ const USAGE_SPIKE_DAY_AVG_MULTIPLIER = 2;
+ /** 异常高峰日期最多展示条数 */
+ const USAGE_SPIKE_DAY_LIST_LIMIT = 3;
+ const usageLowAgentMaxChats = computed(
+ () => usageReport.value?.low_agent_max_chats ?? USAGE_LOW_AGENT_MAX_CHATS,
+ );
+ const usageLowAgentListLimit = computed(
+ () => usageReport.value?.low_agent_list_limit ?? USAGE_LOW_AGENT_LIST_LIMIT,
+ );
+ /**
+ * 低使用应用列表:优先用后端 low_agents(含零使用启用应用);
+ * 旧接口无该字段时回退到 by_agent 过滤(不含零使用)。
+ */
+ const usageLowAgentItems = computed(() => {
+ const fromApi = usageReport.value?.low_agents;
+ if (Array.isArray(fromApi)) {
+ return fromApi;
+ }
+ return [...(usageReport.value?.by_agent || [])]
+ .filter((item) => item.count <= usageLowAgentMaxChats.value)
+ .sort((a, b) => a.count - b.count || a.agent.localeCompare(b.agent))
+ .slice(0, usageLowAgentListLimit.value);
+ });
+ const usageSpikeDayItems = computed(() => {
+ const days = usageReport.value?.by_day || [];
+ if (days.length === 0) return [];
+ const average = days.reduce((sum, item) => sum + item.count, 0) / days.length;
+ // 高峰阈值:不低于下限,且不低于日均 × 倍数
+ const threshold = Math.max(USAGE_SPIKE_DAY_MIN_CHATS, average * USAGE_SPIKE_DAY_AVG_MULTIPLIER);
+ return days
+ .filter((item) => item.count >= threshold)
+ .sort((a, b) => b.count - a.count)
+ .slice(0, USAGE_SPIKE_DAY_LIST_LIMIT);
+ });
+ const usageTopUserItems = computed(() => usageReport.value?.by_user ?? []);
+ const usageAgentTotal = computed(() => usageReport.value?.by_agent.length ?? 0);
+ const usageAgentTotalPages = computed(() => {
+ const size = Math.max(1, Number(usageAgentPageSize.value) || 10);
+ return Math.max(1, Math.ceil(usageAgentTotal.value / size));
+ });
+ /**
+ * 按应用统计当前页数据(对话量降序全集上的偏移分页)。
+ */
+ const usageTopAgentItems = computed(() => {
+ const list = usageReport.value?.by_agent ?? [];
+ const size = Math.max(1, Number(usageAgentPageSize.value) || 10);
+ const page = Math.min(Math.max(1, usageAgentPage.value), usageAgentTotalPages.value);
+ const start = (page - 1) * size;
+ return list.slice(start, start + size);
+ });
const usageUserPageButtons = computed(() =>
buildOffsetPageButtons(usageUserPage.value, usageUserTotalPages.value),
);
@@ -111,6 +321,14 @@ export function useReportsAdmin() {
const prevUsageUserPage = () => goToUsageUserPage(usageUserPage.value - 1);
const nextUsageUserPage = () => goToUsageUserPage(usageUserPage.value + 1);
+ /**
+ * 跳转按应用统计分页(纯前端切片,无需重新请求)。
+ * @param page - 目标页码
+ */
+ const goToUsageAgentPage = (page: number): void => {
+ usageAgentPage.value = Math.min(Math.max(1, page), usageAgentTotalPages.value);
+ };
+
const loadReports = async (): Promise => {
await loadUsageReport();
};
@@ -145,7 +363,7 @@ export function useReportsAdmin() {
if (typeof table === 'string' && (ADMIN_REPORT_TABLES as readonly string[]).includes(table)) {
return table as AdminReportTableId;
}
- return 'users';
+ return 'usage_analysis';
};
const currentTable = ref(resolveTableFromRoute());
@@ -180,26 +398,55 @@ const resizingColumnKey = ref(null);
let resizeStartX = 0;
let resizeStartWidth = 0;
+/** 使用分析 / 应用运营是菜单层虚拟页,明细表仍复用对应数据源。 */
+const dataSourceTable = computed>(() => {
+ if (currentTable.value === 'usage_analysis') return 'chat_logs';
+ return currentTable.value as Exclude;
+});
+
+/**
+ * 从路由 query 灌入列筛选(用于应用运营下钻到聊天日志 / 权限申请)。
+ */
+const applyRouteQueryFilters = (): void => {
+ const next: Record = {};
+ for (const [key, value] of Object.entries(route.query)) {
+ if (typeof value === 'string' && value.trim()) {
+ next[key] = value.trim();
+ }
+ }
+ columnFilters.value = next;
+};
+
const loadTableData = async () => {
+ // 应用运营页不走通用配置表
+ if (currentTable.value === 'agents') {
+ tableData.value = [];
+ selectedReportRowIds.value = [];
+ chatLogsColumns.value = [];
+ await loadApplicationReport();
+ return;
+ }
+
const params = new URLSearchParams();
for (const [key, value] of Object.entries(columnFilters.value)) {
if (value) params.append(key, value);
}
- const url = currentTable.value === 'general_feedbacks'
+ const table = dataSourceTable.value;
+ const url = table === 'general_feedbacks'
? `/api/admin/reports/general-feedbacks?${params.toString()}`
- : `/api/admin/database/${currentTable.value}?${params.toString()}`;
+ : `/api/admin/database/${table}?${params.toString()}`;
try {
tableData.value = await getAdminReportTable(url);
if (tableData.value.length > 0) {
const rowKeys = Object.keys(tableData.value[0] || {});
- const columnKeys = currentTable.value === 'chat_logs'
+ const columnKeys = dataSourceTable.value === 'chat_logs'
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
: rowKeys;
initChatLogsColumns(columnKeys);
}
- if (currentTable.value === 'chat_logs') {
+ if (dataSourceTable.value === 'chat_logs') {
const validIds = new Set(
tableData.value
.map((row: any) => Number(row?.id))
@@ -229,7 +476,7 @@ const saveChatLogsColumns = () => {
const initChatLogsColumns = (keys: string[]) => {
chatLogsWrapEnabled.value = false;
chatLogsWrapMaxHeight.value = 120;
- const hideByDefault = currentTable.value === 'chat_logs' && keys.includes('id');
+ const hideByDefault = dataSourceTable.value === 'chat_logs' && keys.includes('id');
const defaults: ReportColumnConfig[] = keys.map((k) => ({
key: k,
visible: hideByDefault ? k !== 'id' : true,
@@ -246,7 +493,7 @@ const initChatLogsColumns = (keys: string[]) => {
const missing = keys.filter((k) => !order.includes(k));
merged = [...order, ...missing].map((k) => ({
key: k,
- visible: savedMap.get(k)?.visible ?? (currentTable.value === 'chat_logs' && k === 'id' ? false : true),
+ visible: savedMap.get(k)?.visible ?? (dataSourceTable.value === 'chat_logs' && k === 'id' ? false : true),
width: savedMap.get(k)?.width ?? defaultChatLogsColumnWidth(k),
}));
if (!Array.isArray(parsed)) {
@@ -272,7 +519,7 @@ const resetChatLogsColumns = () => {
chatLogsSortRules.value = [];
reportHeaderSort.value = null;
const rowKeys = Object.keys(tableData.value[0] || {});
- const columnKeys = currentTable.value === 'chat_logs'
+ const columnKeys = dataSourceTable.value === 'chat_logs'
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
: rowKeys;
initChatLogsColumns(columnKeys);
@@ -353,6 +600,10 @@ const loadTableCount = async (table: string) => {
};
const exportToExcel = () => {
+ if (currentTable.value === 'agents') {
+ exportApplicationReport();
+ return;
+ }
if (tableData.value.length === 0) return;
const keys = visibleReportKeys.value;
const rows = tableData.value.map((row) => {
@@ -377,10 +628,14 @@ const handleFilterChange = () => {
}, 500);
};
-const isChatLogsTable = computed(() => currentTable.value === 'chat_logs');
-/** 列已初始化后(含筛选无结果)仍展示表头与筛选框,避免用户无法修改条件 */
+const isUsageAnalysisTable = computed(() => currentTable.value === 'usage_analysis');
+const isApplicationOpsTable = computed(() => currentTable.value === 'agents');
+const isChatLogsTable = computed(() => dataSourceTable.value === 'chat_logs');
+/** 列已初始化后(含筛选无结果)仍展示表头与筛选框;应用运营页用专用看板,不展示通用表 */
const showReportTable = computed(
- () => tableData.value.length > 0 || chatLogsColumns.value.length > 0,
+ () =>
+ !isApplicationOpsTable.value
+ && (tableData.value.length > 0 || chatLogsColumns.value.length > 0),
);
const visibleReportKeys = computed(() => {
let keys: string[];
@@ -406,7 +661,7 @@ const visibleReportKeys = computed(() => {
return feedbackFixedOrder.filter((k) => available.has(k));
}
- if (currentTable.value === 'chat_logs') {
+ if (dataSourceTable.value === 'chat_logs') {
const available = new Set(keys);
return CHAT_LOGS_REPORT_KEYS.filter((k) => available.has(k));
}
@@ -819,7 +1074,7 @@ const batchDeleteChatLogs = async () => {
};
watch(currentTable, async () => {
- columnFilters.value = {}; // Reset filters on table change
+ applyRouteQueryFilters();
chatLogsColumns.value = [];
selectedReportRowIds.value = [];
showChatLogsColumnPanel.value = false;
@@ -827,7 +1082,7 @@ watch(currentTable, async () => {
reportCurrentPage.value = 1;
await loadTableData();
reportHeaderSort.value = null;
- if (currentTable.value === 'chat_logs') {
+ if (dataSourceTable.value === 'chat_logs' && !isApplicationOpsTable.value) {
chatLogsTotal.value = await loadTableCount('chat_logs');
}
});
@@ -862,9 +1117,27 @@ watch(usageUserPageSize, () => {
watch(usageRange, () => {
usageUserPage.value = 1;
+ usageAgentPage.value = 1;
void loadUsageReport();
});
+watch(usageAgentPageSize, () => {
+ usageAgentPage.value = 1;
+});
+
+watch(usageAgentTotalPages, (pages) => {
+ if (usageAgentPage.value > pages) {
+ usageAgentPage.value = pages;
+ }
+});
+
+watch([applicationRange, applicationStatus, applicationUsage, applicationPageSize], () => {
+ applicationPage.value = 1;
+ if (isApplicationOpsTable.value) {
+ void loadApplicationReport();
+ }
+});
+
watch([reportPageSize, sortedTableData], () => {
if (reportCurrentPage.value > reportTotalPages.value) {
reportCurrentPage.value = reportTotalPages.value;
@@ -877,14 +1150,14 @@ watch([reportPageSize, sortedTableData], () => {
const loadAll = async (): Promise => {
isLoading.value = true;
await loadReports();
- columnFilters.value = {};
+ applyRouteQueryFilters();
selectedReportRowIds.value = [];
showChatLogsColumnPanel.value = false;
showChatLogsSelection.value = false;
reportCurrentPage.value = 1;
reportHeaderSort.value = null;
await loadTableData();
- if (currentTable.value === 'chat_logs') {
+ if (dataSourceTable.value === 'chat_logs' && !isApplicationOpsTable.value) {
chatLogsTotal.value = await loadTableCount('chat_logs');
} else {
showChatLogsSelection.value = false;
@@ -902,10 +1175,50 @@ watch([reportPageSize, sortedTableData], () => {
usageUserTotal,
usageUserTotalPages,
usageUserTopLimit,
+ usageActiveAgentCount,
+ usageTrendMax,
+ usageLowAgentMaxChats,
+ usageLowAgentListLimit,
+ usageSpikeDayMinChats: USAGE_SPIKE_DAY_MIN_CHATS,
+ usageSpikeDayAvgMultiplier: USAGE_SPIKE_DAY_AVG_MULTIPLIER,
+ usageSpikeDayListLimit: USAGE_SPIKE_DAY_LIST_LIMIT,
+ usageLowAgentItems,
+ usageSpikeDayItems,
+ usageTopUserItems,
+ usageTopAgentItems,
+ usageAgentPage,
+ usageAgentPageSize,
+ usageAgentPageSizeOptions,
+ usageAgentTotal,
+ usageAgentTotalPages,
+ goToUsageAgentPage,
usageUserPageButtons,
goToUsageUserPage,
prevUsageUserPage,
nextUsageUserPage,
+ applicationReport,
+ applicationRange,
+ applicationStatus,
+ applicationUsage,
+ applicationQuery,
+ applicationSort,
+ applicationOrder,
+ applicationPage,
+ applicationPageSize,
+ applicationPageSizeOptions,
+ applicationSummary,
+ applicationItems,
+ applicationTotal,
+ applicationTotalPages,
+ applicationPageButtons,
+ goToApplicationPage,
+ prevApplicationPage,
+ nextApplicationPage,
+ onApplicationSortClick,
+ getApplicationSortMark,
+ handleApplicationSearchChange,
+ openApplicationChatLogs,
+ openApplicationPermissionRequests,
isLoading,
currentTable,
tableData,
@@ -925,6 +1238,8 @@ watch([reportPageSize, sortedTableData], () => {
chatLogsSortRules,
reportHeaderSort,
draggingColumnKey,
+ isUsageAnalysisTable,
+ isApplicationOpsTable,
isChatLogsTable,
showReportTable,
visibleReportKeys,
diff --git a/frontend/src/features/admin/modules/schedules/SchedulesPage.vue b/frontend/src/features/admin/modules/schedules/SchedulesPage.vue
index a3456868..f770f58c 100644
--- a/frontend/src/features/admin/modules/schedules/SchedulesPage.vue
+++ b/frontend/src/features/admin/modules/schedules/SchedulesPage.vue
@@ -18,7 +18,10 @@ const admin = reactive(adminApi) as SchedulesAdminContextProvided;
provide(SCHEDULES_ADMIN_KEY, admin);
/** 弹窗 v-if 须绑定原始 ref,避免 reactive 属性赋值破坏 ref 链接 */
provide(SCHEDULE_CREATE_MODAL_OPEN_KEY, adminApi.showScheduleCreateModal);
-onMounted(() => { void admin.loadAll(); });
+onMounted(async () => {
+ await admin.loadAll();
+ await admin.applyFromRouteQuery();
+});
diff --git a/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.spec.ts b/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.spec.ts
new file mode 100644
index 00000000..b8d032b1
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.spec.ts
@@ -0,0 +1,23 @@
+/**
+ * features/admin/modules/schedules/components/ScheduleWorkbenchPanel.spec.ts
+ * 用途:断言执行记录页不默认展示原始库存下载;仅企微深链 raw_zip=1 时突出下载入口。
+ */
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+describe('ScheduleWorkbenchPanel run table actions', () => {
+ it('does not render raw inventory zip download in the run table column', () => {
+ const panelPath = resolve(__dirname, 'ScheduleWorkbenchPanel.vue');
+ const content = readFileSync(panelPath, 'utf8');
+ expect(content).not.toMatch(/downloadScheduleInventoryRawZip\(r\.id\)/);
+ });
+
+ it('only shows raw inventory download when wecom deep link prompt is active', () => {
+ const panelPath = resolve(__dirname, 'ScheduleWorkbenchPanel.vue');
+ const content = readFileSync(panelPath, 'utf8');
+ expect(content).toMatch(/wecomRawZipPromptRunId/);
+ expect(content).not.toMatch(/v-if="admin\.expandedScheduleRun\.inventory_raw_zip_available"/);
+ expect(content).toMatch(/admin\.wecomRawZipPromptRunId === admin\.expandedScheduleRun\.id/);
+ });
+});
diff --git a/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.vue b/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.vue
index aefd1570..00605f68 100644
--- a/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.vue
+++ b/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.vue
@@ -15,7 +15,7 @@ const admin = useSchedulesAdminContext();
-
+
{{ admin.selectedSchedule?.name || $t('admin.schedule.noSelection') }}
{{ $t('admin.schedule.selectedHint', { time: admin.selectedScheduleLatestRunAt }) }}
@@ -32,6 +32,10 @@ const admin = useSchedulesAdminContext();
{{ admin.selectedScheduleRunMetrics.success }}
{{ $t('admin.schedule.totalSuccess') }}
+
+
{{ admin.selectedScheduleRunMetrics.skipped }}
+
{{ $t('admin.schedule.totalSkipped') }}
+
{{ admin.selectedScheduleRunMetrics.failed }}
{{ $t('admin.schedule.totalFailed') }}
@@ -126,6 +130,35 @@ const admin = useSchedulesAdminContext();
{{ $t('admin.schedule.recordsTitle', { name: admin.selectedSchedule.name }) }}
{{ $t('admin.schedule.recordsSubtitle') }}
+
+ {{ $t('admin.schedule.rpaWorker.title') }}
+
+ {{ $t('admin.schedule.rpaWorker.loading') }}
+
+
+ {{ admin.rpaWorkerStatus?.ready ? $t('admin.schedule.rpaWorker.online') : $t('admin.schedule.rpaWorker.offline') }}
+
+
+ {{ $t('admin.schedule.rpaWorker.lastHeartbeat', { time: admin.rpaWorkerLastHeartbeatAt }) }}
+
+
+ {{ admin.rpaWorkerStatus.detail_message }}
+
+
@@ -186,10 +219,10 @@ const admin = useSchedulesAdminContext();
- | {{ $t('admin.schedule.queryingRuns') }} |
+ {{ $t('admin.schedule.queryingRuns') }} |
- | {{ $t('admin.schedule.noRunRecords') }} |
+ {{ $t('admin.schedule.noRunRecords') }} |
| {{ r.total_count }} |
{{ r.success_count }} |
+ {{ r.skipped_count ?? 0 }} |
{{ r.failed_count }}
-
|
- |
@@ -260,8 +294,22 @@ const admin = useSchedulesAdminContext();
v-if="admin.expandedScheduleRun"
:key="'expanded-' + admin.expandedScheduleRunId"
>
- |
+ |
+
+ {{ $t('admin.schedule.rawInventoryZipWecomHint') }}
+
+
{{ $t('admin.schedule.difySnapshot.notEnabledRun') }}
-
+
{{ $t('admin.schedule.runLogs') }}
{{ $t('admin.schedule.stepsCount', { count: admin.expandedScheduleRun.step_logs?.length || 0 }) }}
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/schedule-admin.state.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/schedule-admin.state.ts
index 2ed305eb..42ceb8a2 100644
--- a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/schedule-admin.state.ts
+++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/schedule-admin.state.ts
@@ -3,7 +3,7 @@
* 定时任务管理页共享 ref 与删除确认弹窗状态。
*/
import { ref } from 'vue';
-import type { PlatformJobOption, PlatformTaskDefinition, ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/features/admin/api/schedule.api';
+import type { PlatformJobOption, PlatformTaskDefinition, RpaWorkerHeartbeatSummary, ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/features/admin/api/schedule.api';
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
import type { KbGroup } from '@/features/kb/api/kb.api';
import {
@@ -55,6 +55,8 @@ export function createScheduleAdminState() {
const schedulesLoaded = ref(false);
void schedulesLoaded;
const selectedScheduleRuns = ref ([]);
+ const rpaWorkerStatus = ref(null);
+ const rpaWorkerStatusLoading = ref(false);
const scheduleLoading = ref(false);
const scheduleRunsLoading = ref(false);
const selectedScheduleId = ref(null);
@@ -68,6 +70,7 @@ export function createScheduleAdminState() {
{ key: 'status', label: '', width: 130, min: 50 },
{ key: 'total_count', label: '', width: 70, min: 40 },
{ key: 'success_count', label: '', width: 70, min: 40 },
+ { key: 'skipped_count', label: '', width: 70, min: 40 },
{ key: 'failed_count', label: '', width: 70, min: 40 },
{ key: 'wecom_notified', label: '', width: 100, min: 80 },
{ key: 'detail', label: '', width: 100, min: 80 },
@@ -83,6 +86,8 @@ export function createScheduleAdminState() {
const scheduleConfigCollapsed = ref(true);
const expandedScheduleRunId = ref(null);
+ /** 企微深链 raw_zip=1 进入时待手动下载的执行记录 ID;普通列表浏览不展示原始库存下载入口。 */
+ const wecomRawZipPromptRunId = ref(null);
const showTestRunDialog = ref(false);
const testRunSchedule = ref(null);
@@ -122,6 +127,8 @@ export function createScheduleAdminState() {
schedules,
schedulesLoaded,
selectedScheduleRuns,
+ rpaWorkerStatus,
+ rpaWorkerStatusLoading,
scheduleLoading,
scheduleRunsLoading,
selectedScheduleId,
@@ -137,6 +144,7 @@ export function createScheduleAdminState() {
scheduleCreateForm,
scheduleConfigCollapsed,
expandedScheduleRunId,
+ wecomRawZipPromptRunId,
showTestRunDialog,
testRunSchedule,
testRunWhere,
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts
new file mode 100644
index 00000000..8dc3b6ec
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts
@@ -0,0 +1,65 @@
+/**
+ * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts
+ * 用途:解析企微深链 query,定位排程执行记录并在登录后自动下载原始库存包。
+ * 依赖:vue-router、schedule-admin.state、useScheduleAdminRuns。
+ * 逻辑:SchedulesPage onMounted 在 loadAll 后调用;消费 task_id/run_id/raw_zip/download,自动下载失败时保留手动入口。
+ */
+import { useRoute, useRouter } from 'vue-router';
+import type { ScheduleAdminState } from './schedule-admin.state';
+import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
+
+function parsePositiveInt(raw: unknown): number | null {
+ const value = Number(raw);
+ if (!Number.isFinite(value) || value <= 0) return null;
+ return Math.trunc(value);
+}
+
+/**
+ * 根据路由 query 打开工作台执行记录;raw_zip=1 时展开 run 并保留手动下载按钮。
+ * 核心逻辑:download=inventory_raw_zip 时登录后自动下载一次;若企微内置浏览器拦截,用户仍可点醒目按钮重试。
+ */
+export function useScheduleAdminDeepLink(
+ state: ScheduleAdminState,
+ runs: Pick,
+) {
+ const route = useRoute();
+ const router = useRouter();
+
+ const applyFromRouteQuery = async (): Promise => {
+ const taskId = parsePositiveInt(route.query.task_id);
+ if (!taskId) return;
+
+ const runId = parsePositiveInt(route.query.run_id);
+ const rawZipPrompt = String(route.query.raw_zip || '') === '1';
+ const shouldAutoDownloadRawZip = rawZipPrompt && String(route.query.download || '') === 'inventory_raw_zip';
+
+ state.scheduleViewMode.value = 'workbench';
+ state.selectedScheduleId.value = taskId;
+ state.wecomRawZipPromptRunId.value = null;
+ await runs.viewScheduleRuns(taskId);
+
+ if (runId) {
+ state.expandedScheduleRunId.value = runId;
+ if (rawZipPrompt) {
+ const target = state.selectedScheduleRuns.value.find((item) => item.id === runId);
+ if (target?.inventory_raw_zip_available) {
+ state.wecomRawZipPromptRunId.value = runId;
+ if (shouldAutoDownloadRawZip) {
+ await runs.downloadScheduleInventoryRawZip(runId);
+ }
+ }
+ }
+ }
+
+ const nextQuery = { ...route.query };
+ delete nextQuery.task_id;
+ delete nextQuery.run_id;
+ delete nextQuery.raw_zip;
+ delete nextQuery.download;
+ await router.replace({ path: route.path, query: nextQuery });
+ };
+
+ return { applyFromRouteQuery };
+}
+
+export type ScheduleAdminDeepLink = ReturnType;
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts
index 2d2a24b2..22b39afc 100644
--- a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts
+++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts
@@ -4,7 +4,7 @@
*/
import { computed, watch, type Ref } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
-import { listAdminScheduleRuns } from '@/features/admin/api/schedule.api';
+import { listAdminScheduleRuns, adminRunInventoryRawZipUrl, getAdminRpaWorkersStatus } from '@/features/admin/api/schedule.api';
import { useMessage } from '@/shared/composables/useMessage';
import { getAuthHeaders } from '@/shared/utils/auth';
import { formatDateTime } from '../../utils/schedule-format.utils';
@@ -25,6 +25,8 @@ export function useScheduleAdminRuns(
selectedScheduleRuns,
scheduleRunsLoading,
selectedScheduleId,
+ rpaWorkerStatus,
+ rpaWorkerStatusLoading,
scheduleRunStatusFilter,
scheduleRunStartedAfter,
scheduleRunStartedBefore,
@@ -41,6 +43,7 @@ export function useScheduleAdminRuns(
status: 'status',
total_count: 'totalCount',
success_count: 'successCount',
+ skipped_count: 'skippedCount',
failed_count: 'failedCount',
wecom_notified: 'wecomNotified',
detail: 'detail',
@@ -132,10 +135,11 @@ export function useScheduleAdminRuns(
(acc, item) => {
acc.total += item.total_count || 0;
acc.success += item.success_count || 0;
+ acc.skipped += item.skipped_count || 0;
acc.failed += item.failed_count || 0;
return acc;
},
- { total: 0, success: 0, failed: 0 },
+ { total: 0, success: 0, skipped: 0, failed: 0 },
);
});
@@ -144,6 +148,35 @@ export function useScheduleAdminRuns(
return raw ? formatDateTime(raw) : '-';
});
+ const isInventoryRpaSchedule = computed(
+ () => selectedSchedule.value?.platform_api_path === 'shipping-inventory-rpa',
+ );
+
+ const rpaWorkerLastHeartbeatAt = computed(() => {
+ const workers = rpaWorkerStatus.value?.workers || [];
+ const latest = workers
+ .map((item) => item.received_at || item.timestamp)
+ .filter(Boolean)
+ .sort()
+ .pop();
+ return latest ? formatDateTime(String(latest)) : '-';
+ });
+
+ const refreshRpaWorkerStatus = async () => {
+ if (!isInventoryRpaSchedule.value) {
+ rpaWorkerStatus.value = null;
+ return;
+ }
+ rpaWorkerStatusLoading.value = true;
+ try {
+ rpaWorkerStatus.value = await getAdminRpaWorkersStatus();
+ } catch {
+ rpaWorkerStatus.value = null;
+ } finally {
+ rpaWorkerStatusLoading.value = false;
+ }
+ };
+
const todayStart = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`;
@@ -175,6 +208,7 @@ export function useScheduleAdminRuns(
params.started_before = new Date(scheduleRunStartedBefore.value).toISOString();
}
selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
+ await refreshRpaWorkerStatus();
} finally {
scheduleRunsLoading.value = false;
}
@@ -198,6 +232,24 @@ export function useScheduleAdminRuns(
URL.revokeObjectURL(url);
};
+ const downloadScheduleInventoryRawZip = async (runId: number) => {
+ const res = await fetch(adminRunInventoryRawZipUrl(runId), { headers: getAuthHeaders() });
+ if (!res.ok) {
+ msg.error(t('admin.schedule.msg.downloadInventoryRawZipFailed'));
+ return;
+ }
+ const blob = await res.blob();
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ const disposition = res.headers.get('content-disposition');
+ a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'inventory-rpa-raw.zip';
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ };
+
const getScheduleRunFailedCountTitle = (run: (typeof selectedScheduleRuns.value)[number]) =>
buildScheduleRunFailedCountTitle(run, t('admin.schedule.excelExportFailedHint'));
@@ -211,9 +263,13 @@ export function useScheduleAdminRuns(
stepStatusMap,
selectedScheduleRunMetrics,
selectedScheduleLatestRunAt,
+ isInventoryRpaSchedule,
+ rpaWorkerLastHeartbeatAt,
+ refreshRpaWorkerStatus,
resetScheduleRunFilters,
viewScheduleRuns,
downloadScheduleExcel,
+ downloadScheduleInventoryRawZip,
startScheduleColResize,
formatDateTime,
isScheduleRunExcelExportFailed,
diff --git a/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts b/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts
index 73d5c6cc..b7bf0127 100644
--- a/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts
+++ b/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts
@@ -9,6 +9,7 @@ import { useScheduleAdminList } from './schedule-admin/useScheduleAdminList';
import { useScheduleAdminLookups } from './schedule-admin/useScheduleAdminLookups';
import { useScheduleAdminRuns } from './schedule-admin/useScheduleAdminRuns';
import { useScheduleAdminTestRun } from './schedule-admin/useScheduleAdminTestRun';
+import { useScheduleAdminDeepLink } from './schedule-admin/useScheduleAdminDeepLink';
export function useSchedulesAdmin() {
const { t, locale } = useI18n();
@@ -16,6 +17,7 @@ export function useSchedulesAdmin() {
const lookups = useScheduleAdminLookups(state);
const runs = useScheduleAdminRuns(state, t, locale);
const list = useScheduleAdminList(state, runs, t);
+ const deepLink = useScheduleAdminDeepLink(state, runs);
const form = useScheduleAdminForm(state, lookups, list, runs, t);
const testRun = useScheduleAdminTestRun(state, list, runs, t);
@@ -24,6 +26,7 @@ export function useSchedulesAdmin() {
...lookups,
...runs,
...list,
+ ...deepLink,
...form,
...testRun,
};
diff --git a/frontend/src/features/admin/stores/admin-nav.store.ts b/frontend/src/features/admin/stores/admin-nav.store.ts
index 87fd4155..31b54d05 100644
--- a/frontend/src/features/admin/stores/admin-nav.store.ts
+++ b/frontend/src/features/admin/stores/admin-nav.store.ts
@@ -1,9 +1,10 @@
/**
* features/admin/stores/admin-nav.store.ts
- * 管理后台导航 UI 状态(侧栏折叠、报表展开、角标)。
+ * 管理后台导航 UI 状态(侧栏折叠、报表/企微子菜单展开、角标)。
*
* 角标数据来自 GET /api/admin/dashboard/badges,在 store 内做 TTL 缓存与 in-flight 去重,
* 避免切换 admin 子路由时重复请求(AdminLayout 挂载一次即可)。
+ * 报表与企业微信子菜单默认折叠,进入对应模块时由 AdminNav 展开。
*/
import { defineStore } from 'pinia';
import { ref } from 'vue';
@@ -15,8 +16,10 @@ const BADGE_CACHE_TTL_MS = 60_000;
export const useAdminNavStore = defineStore('adminNav', () => {
const sidebarCollapsed = ref(false);
- const reportsExpanded = ref(true);
- const wecomExpanded = ref(true);
+ /** 数据报表子菜单:默认折叠 */
+ const reportsExpanded = ref(false);
+ /** 企业微信子菜单:默认折叠 */
+ const wecomExpanded = ref(false);
/** 「用户审批」导航角标:pending 注册用户数 */
const pendingApprovalsCount = ref(0);
/** 「权限申请」导航角标:pending 权限申请数 */
diff --git a/frontend/src/features/admin/types/admin.types.ts b/frontend/src/features/admin/types/admin.types.ts
index 8d2f93a0..26b2cf7e 100644
--- a/frontend/src/features/admin/types/admin.types.ts
+++ b/frontend/src/features/admin/types/admin.types.ts
@@ -20,6 +20,7 @@ export type AdminModuleId =
| 'reports';
export type AdminReportTableId =
+ | 'usage_analysis'
| 'users'
| 'agents'
| 'chat_logs'
diff --git a/frontend/src/features/admin/types/report.types.ts b/frontend/src/features/admin/types/report.types.ts
index 39c8f218..c1c0cd5c 100644
--- a/frontend/src/features/admin/types/report.types.ts
+++ b/frontend/src/features/admin/types/report.types.ts
@@ -1,6 +1,6 @@
/**
* features/admin/types/report.types.ts
- * 用途:报表模块类型(使用分析、列配置、排序规则)。
+ * 用途:报表模块类型(使用分析、应用运营、列配置、排序规则)。
* 依赖:无。
* 逻辑:useReportsAdmin / admin.api 共用。
*/
@@ -12,9 +12,19 @@ export interface UsageReport {
total: number;
/** 当前统计时间范围 */
range?: UsageRangeKey;
- by_user: { username: string; count: number }[];
+ by_user: { username: string; real_name?: string; count: number }[];
by_agent: { agent: string; count: number }[];
+ /** 当前范围内按自然日聚合的对话趋势,用于使用分析柱状图。 */
by_day?: { date: string; count: number }[];
+ /**
+ * 运营提醒:启用应用中范围内对话次数 ≤ low_agent_max_chats 的列表(含零使用)。
+ * 由后端以 Agent 主表左连接统计,与应用运营「零使用」口径对齐。
+ */
+ low_agents?: { agent: string; count: number }[];
+ /** 低使用对话次数上限(后端常量) */
+ low_agent_max_chats?: number;
+ /** 低使用列表条数上限(后端常量) */
+ low_agent_list_limit?: number;
user_total: number;
user_page: number;
user_page_size: number;
@@ -22,6 +32,62 @@ export interface UsageReport {
user_top_limit: number;
}
+/** 应用运营报表:启用状态筛选 */
+export type ApplicationStatusFilter = 'all' | 'active' | 'inactive';
+
+/** 应用运营报表:是否有使用筛选 */
+export type ApplicationUsageFilter = 'all' | 'used' | 'unused';
+
+/** 应用运营报表可排序字段 */
+export type ApplicationSortKey =
+ | 'name'
+ | 'chat_count'
+ | 'unique_users'
+ | 'last_active_at'
+ | 'authorized_users'
+ | 'pending_requests'
+ | 'avg_score'
+ | 'tokens_used';
+
+export interface ApplicationReportItem {
+ agent_id: number;
+ name: string;
+ is_active: boolean;
+ category: string;
+ chat_count: number;
+ unique_users: number;
+ last_active_at: string | null;
+ authorized_users: number;
+ pending_requests: number;
+ avg_score: number | null;
+ feedback_count: number;
+ tokens_used: number;
+ avg_latency_ms: number | null;
+}
+
+export interface ApplicationReportSummary {
+ agent_total: number;
+ active_agents: number;
+ used_agents: number;
+ unused_agents: number;
+ pending_permission_total: number;
+}
+
+export interface ApplicationReport {
+ range: UsageRangeKey;
+ status: ApplicationStatusFilter;
+ usage: ApplicationUsageFilter;
+ q: string;
+ sort: ApplicationSortKey;
+ order: 'asc' | 'desc';
+ summary: ApplicationReportSummary;
+ items: ApplicationReportItem[];
+ total: number;
+ page: number;
+ page_size: number;
+ pages: number;
+}
+
export interface ReportColumnConfig {
key: string;
visible: boolean;
diff --git a/frontend/src/features/auth/components/LoginPage.vue b/frontend/src/features/auth/components/LoginPage.vue
index f146a8db..875cbf94 100644
--- a/frontend/src/features/auth/components/LoginPage.vue
+++ b/frontend/src/features/auth/components/LoginPage.vue
@@ -1,7 +1,10 @@
+
+
+
+
+
+ {{ t('chat.shippingNoticeDuplicateTitle') }}
+
+ {{ statusLabel }}
+
+ {{ attachment.originalFilename }}
+
+
+
+ {{ t('chat.shippingNoticeDuplicateMatchTask', { taskNo: match.taskNo }) }}
+
+ {{ t('chat.shippingNoticeDuplicateMatchStatus', { status: match.processStatus }) }}
+ · v{{ match.documentVersion }}
+
+
+ {{ t('chat.shippingNoticeDuplicateMatchFields', { fields: match.matchedFields.join(', ') }) }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ localError }}
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/chat/composables/useChatAssetHistory.ts b/frontend/src/features/chat/composables/useChatAssetHistory.ts
index 5c2cae10..fcecb63d 100644
--- a/frontend/src/features/chat/composables/useChatAssetHistory.ts
+++ b/frontend/src/features/chat/composables/useChatAssetHistory.ts
@@ -28,6 +28,12 @@ function normalizeAssetHistoryErrorMessage(message: string): string {
if (lowerCaseMessage.includes('asset history share is not configured')) {
return '当前系统暂未配置资产履历文件目录,暂时无法查看履历,请联系管理员处理。';
}
+ if (lowerCaseMessage.includes('asset history share is unreachable')) {
+ return '当前环境暂时无法访问资产履历共享盘,请联系管理员检查测试环境共享盘挂载或访问权限。';
+ }
+ if (lowerCaseMessage.includes('asset history share is invalid')) {
+ return '当前环境的资产履历目录配置无效,请联系管理员检查共享盘目录配置。';
+ }
return normalizedMessage || '检索资产履历失败';
}
diff --git a/frontend/src/features/chat/composables/useChatAssetImage.ts b/frontend/src/features/chat/composables/useChatAssetImage.ts
index b75f5767..53da1537 100644
--- a/frontend/src/features/chat/composables/useChatAssetImage.ts
+++ b/frontend/src/features/chat/composables/useChatAssetImage.ts
@@ -27,12 +27,16 @@ function normalizeAssetImageErrorMessage(message: string): string {
if (lowerCaseMessage.includes('固定资产图片文档库未配置')) {
return '当前系统暂未配置固定资产图片文档库,暂时无法查看图片,请联系管理员处理。';
}
+ if (lowerCaseMessage.includes('请求的资源不存在')) {
+ return '设备管理员还未上传照片~';
+ }
if (lowerCaseMessage.includes('未找到资产')) {
return normalizedMessage;
}
return normalizedMessage || '检索固定资产图片失败';
}
+
export function useChatAssetImage(options: UseChatAssetImageOptions) {
const loading = ref(false);
@@ -76,7 +80,11 @@ export function useChatAssetImage(options: UseChatAssetImageOptions) {
} catch (err: unknown) {
const rawMessage = err instanceof Error ? err.message : '检索固定资产图片失败';
const message = normalizeAssetImageErrorMessage(rawMessage);
- options.warn(`图片查询失败:${message}`);
+ if (message === '设备管理员还未上传照片~') {
+ options.warn(message);
+ } else {
+ options.warn(`图片查询失败:${message}`);
+ }
} finally {
loading.value = false;
}
diff --git a/frontend/src/features/chat/composables/useChatPage.ts b/frontend/src/features/chat/composables/useChatPage.ts
index e027b28d..a8dd879e 100644
--- a/frontend/src/features/chat/composables/useChatPage.ts
+++ b/frontend/src/features/chat/composables/useChatPage.ts
@@ -31,6 +31,7 @@ import { useChatStore } from '../stores/chat.store';
import { useTrainingWorkspace } from './useTrainingWorkspace';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
+import { clearPendingNoticeBatchRetry } from '../shipping/useChatShippingUploadHandler';
import {
createChatPageConversationApi,
createChatPageLocalMessageApi,
@@ -337,6 +338,7 @@ export function useChatPage() {
isThinking,
loadConversationState,
createNewChatView,
+ clearPendingNoticeBatchRetry,
onConversationIdChanging: shipping.onConversationIdChanging,
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
onConversationLoadFailed: shipping.onConversationLoadFailed,
@@ -536,6 +538,26 @@ export function useChatPage() {
showGuideSidebar: chatGuides.showSidebar,
openGuideModal: chatGuides.openModal,
...attachmentApi,
+ handleLocalFilesSelected: (event: Event) => {
+ if (shipping.handleShippingLocalFilesSelected(event)) return;
+ attachmentApi.handleLocalFilesSelected(event);
+ },
+ removeAttachment: (id: string) => {
+ const target = attachmentApi.attachments.value.find((item) => item.id === id);
+ if (target?.kind === 'shipping_notice') {
+ void shipping.removeShippingNoticeAttachment(id);
+ return;
+ }
+ attachmentApi.removeAttachment(id);
+ },
+ retryShippingNoticeAttachment: shipping.retryShippingNoticeAttachment,
+ showShippingDuplicateDialog: shipping.showShippingDuplicateDialog,
+ shippingDuplicateAttachment: shipping.shippingDuplicateAttachment,
+ canForceCreateShippingDuplicate: shipping.canForceCreateShippingDuplicate,
+ openShippingDuplicateDialog: shipping.openShippingDuplicateDialog,
+ resolveShippingDuplicateDialog: shipping.resolveShippingDuplicateDialog,
+ removeShippingDuplicateDialogAttachment: shipping.removeShippingDuplicateDialogAttachment,
+ closeShippingDuplicateDialog: shipping.closeShippingDuplicateDialog,
filePreviewVisible,
previewFile,
previewFiles,
diff --git a/frontend/src/features/chat/composables/useChatShipping.ts b/frontend/src/features/chat/composables/useChatShipping.ts
index 7658dad3..55207142 100644
--- a/frontend/src/features/chat/composables/useChatShipping.ts
+++ b/frontend/src/features/chat/composables/useChatShipping.ts
@@ -14,10 +14,12 @@ import {
type ComputedRef,
type Ref,
} from 'vue';
+import { useAuthStore } from '@/features/auth/stores/auth.store';
import { agentUsesWorkspaceStepperProgress, isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
+import { useShippingNoticeIntakes } from '../shipping/useShippingNoticeIntakes';
import {
createShippingActionsRefresher,
createShippingConversationHelpers,
@@ -27,6 +29,7 @@ import {
createShippingParseReviewHandlers,
createShippingSendHandlers,
createShippingUploadHandlers,
+ onNoticeBatchConversationChanging,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
@@ -39,6 +42,8 @@ import {
shippingActionButtonClass,
} from '../shipping';
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
+import { classifyShippingUploadFile } from '../shipping/shippingUploadPrompt';
+import { extractExt } from '../constants/shipping';
import {
getWorkspaceShippingConversationBatches,
getWorkspaceShippingBatch,
@@ -656,6 +661,75 @@ export function useChatShipping(options: UseChatShippingOptions) {
msg,
});
+ const shippingIntakes = useShippingNoticeIntakes({
+ attachments,
+ conversationId,
+ msg,
+ t,
+ });
+
+ const showShippingDuplicateDialog = ref(false);
+ const shippingDuplicateAttachmentId = ref(null);
+ const shippingDuplicateAttachment = computed(() => {
+ const id = shippingDuplicateAttachmentId.value;
+ if (!id) return null;
+ return shippingIntakes.noticeAttachments.value.find((item) => item.id === id) || null;
+ });
+ const canForceCreateShippingDuplicate = computed(() => {
+ const user = useAuthStore().user;
+ if (!user) return false;
+ if (String(user.role || '') === 'admin') return true;
+ return Boolean(user.feature_permissions?.shipping_notice_force_create);
+ });
+
+ /**
+ * 打开首个(或指定)阻断型重复附件的处理弹窗。
+ */
+ const openShippingDuplicateDialog = (attachmentId?: string) => {
+ const targetId =
+ attachmentId
+ || shippingIntakes.noticeAttachments.value.find(
+ (item) => item.duplicate?.blocking && !item.duplicateResolution?.action,
+ )?.id
+ || null;
+ if (!targetId) {
+ msg.warning(t('chat.shippingNoticeDuplicateNeedsResolution'));
+ return;
+ }
+ shippingDuplicateAttachmentId.value = targetId;
+ showShippingDuplicateDialog.value = true;
+ };
+
+ /**
+ * 提交重复决策并写回附件状态。
+ */
+ const resolveShippingDuplicateDialog = async (payload: {
+ action: import('../types/shipping.types').ShippingDuplicateAction;
+ targetTaskNo?: string;
+ reason?: string;
+ }) => {
+ const id = shippingDuplicateAttachmentId.value;
+ if (!id) return;
+ try {
+ await shippingIntakes.resolveDuplicateAttachment(
+ id,
+ payload.action,
+ payload.targetTaskNo,
+ payload.reason,
+ );
+ msg.success(t('chat.shippingNoticeDuplicateResolved'));
+ } catch (e: unknown) {
+ msg.warning(e instanceof Error ? e.message : t('chat.shippingNoticeDuplicateResolveFailed'));
+ }
+ };
+
+ const removeShippingDuplicateDialogAttachment = async () => {
+ const id = shippingDuplicateAttachmentId.value;
+ if (!id) return;
+ await shippingIntakes.removeNoticeAttachment(id);
+ shippingDuplicateAttachmentId.value = null;
+ };
+
const {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
@@ -666,6 +740,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
+ isShippingNoticeBatchSubmitting,
} = createShippingUploadHandlers({
conversationId,
currentAgentId,
@@ -687,6 +762,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
getActiveShippingTaskId,
startChatTurn,
refreshShippingActions,
+ getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
+ clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
msg,
t,
});
@@ -738,6 +815,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
handleShippingMenuAction,
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
+ isShippingNoticeBatchSubmitting,
+ hasBlockingNoticeIntake: () => shippingIntakes.hasBlockingUploadOrParse.value,
+ hasNoticeIntakeFailures: () => shippingIntakes.hasParseFailures.value,
+ hasBlockingNoticeDuplicates: () => shippingIntakes.hasBlockingDuplicates.value,
+ openShippingDuplicateDialog,
+ getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
refreshShippingActions,
shippingSuggestedPrompt,
isShippingShortageQueryIntent,
@@ -778,6 +861,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
+ onNoticeBatchConversationChanging(nextId, prevId);
+ shippingIntakes.stopPolling();
+ if (nextId && nextId !== prevId) {
+ void shippingIntakes.restoreForConversation(nextId);
+ }
if (prevId !== nextId) {
resolvedShippingTaskId.value = '';
if (!shippingBatchNoFromQuery.value) {
@@ -851,6 +939,33 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
};
+ const handleShippingLocalFilesSelected = (event: Event): boolean => {
+ if (!isShippingNoticeAgent.value) return false;
+ const inputEl = event.target as HTMLInputElement | null;
+ const files = inputEl?.files ? Array.from(inputEl.files) : [];
+ if (!files.length) return false;
+ const noticeFiles = files.filter((file) => classifyShippingUploadFile(file, extractExt) === 'notice');
+ const otherFiles = files.filter((file) => classifyShippingUploadFile(file, extractExt) !== 'notice');
+ if (noticeFiles.length) {
+ void shippingIntakes.enqueueNoticeFiles(noticeFiles);
+ }
+ // 同一次选择中的库存/其他文件直接落入本地附件,避免清空 input 后通用 handler 丢失 FileList
+ for (const file of otherFiles) {
+ const kind = classifyShippingUploadFile(file, extractExt);
+ attachments.value = [
+ ...attachments.value,
+ {
+ id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
+ kind: 'local',
+ file,
+ type: kind === 'inventory' ? 'document' : 'document',
+ },
+ ];
+ }
+ if (inputEl) inputEl.value = '';
+ return true;
+ };
+
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
const nextQuery: Record = { task_id: shippingTaskIdFromQuery.value };
@@ -1013,6 +1128,19 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingActionButtonClass,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
+ enqueueShippingNoticeFiles: shippingIntakes.enqueueNoticeFiles,
+ handleShippingLocalFilesSelected,
+ removeShippingNoticeAttachment: shippingIntakes.removeNoticeAttachment,
+ retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
+ showShippingDuplicateDialog,
+ shippingDuplicateAttachment,
+ canForceCreateShippingDuplicate,
+ openShippingDuplicateDialog,
+ resolveShippingDuplicateDialog,
+ removeShippingDuplicateDialogAttachment,
+ closeShippingDuplicateDialog: () => {
+ showShippingDuplicateDialog.value = false;
+ },
tryHandleShippingAttachmentAutoFlow,
tryHandleShippingSend,
onConversationIdChanging,
diff --git a/frontend/src/features/chat/page/useChatPageConversation.spec.ts b/frontend/src/features/chat/page/useChatPageConversation.spec.ts
new file mode 100644
index 00000000..b442be38
--- /dev/null
+++ b/frontend/src/features/chat/page/useChatPageConversation.spec.ts
@@ -0,0 +1,166 @@
+/**
+ * features/chat/page/useChatPageConversation.spec.ts
+ * 用途:验证新建聊天与 Agent 切换时清理发货通知待重试建批幂等状态。
+ * 依赖:vitest、vue refs/computed、useChatPageConversation、useChatShippingUploadHandler。
+ * 逻辑:覆盖 createNewChatView 不经 onConversationIdChanging 时仍生成新幂等键的回归场景。
+ */
+import { computed, ref } from 'vue';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createChatPageConversationApi } from './useChatPageConversation';
+import {
+ clearPendingNoticeBatchRetry,
+ createShippingUploadHandlers,
+ resetShippingNoticeBatchSubmitStateForTests,
+ type ShippingUploadHandlerContext,
+} from '../shipping/useChatShippingUploadHandler';
+
+const { listChatMessages } = vi.hoisted(() => ({
+ listChatMessages: vi.fn(),
+}));
+
+const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
+ computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => {
+ const content = await files[0]?.text();
+ return `fp-${content || 'empty'}`;
+ }),
+}));
+
+vi.mock('../api/chat.api', () => ({
+ listChatMessages,
+}));
+
+vi.mock('../shipping/shippingNoticeBatchIdempotency', () => ({
+ computeNoticeFilesContentFingerprint,
+}));
+
+const createConversationContext = () => {
+ const conversationId = ref('conv-a');
+ const messages = ref([]);
+ const createNewChatView = vi.fn(() => {
+ conversationId.value = null;
+ messages.value = [];
+ });
+
+ return {
+ conversationId,
+ messages,
+ createNewChatView,
+ api: createChatPageConversationApi({
+ deps: { t: (key: string) => key, msg: { warning: vi.fn() } },
+ route: { path: '/chat/42', query: {} } as never,
+ router: { replace: vi.fn() } as never,
+ currentAgentId: computed(() => 42),
+ conversationId,
+ activeRunId: ref(null),
+ messages,
+ isThinking: ref(false),
+ loadConversationState: vi.fn(),
+ createNewChatView,
+ clearPendingNoticeBatchRetry,
+ onConversationIdChanging: vi.fn(),
+ onConversationLoadedEmpty: vi.fn(async () => undefined),
+ onConversationLoadFailed: vi.fn(async () => undefined),
+ isShippingNoticeAgent: computed(() => true),
+ shippingTaskIdFromQuery: computed(() => ''),
+ shippingBatchNoFromQuery: computed(() => ''),
+ clearHistory: vi.fn(),
+ clearAttachments: vi.fn(),
+ input: ref(''),
+ resetCurrentAgent: vi.fn(),
+ copiedIndex: ref(null),
+ resetPeripheralState: vi.fn(),
+ filePreviewVisible: ref(false),
+ previewFile: ref(null),
+ previewFiles: ref([]),
+ currentPreviewIndex: ref(0),
+ }),
+ };
+};
+
+const createUploadContext = (
+ conversationId: ReturnType>,
+ startChatTurn: ReturnType,
+): ShippingUploadHandlerContext => ({
+ conversationId,
+ currentAgentId: computed(() => 42),
+ attachments: ref([]),
+ input: ref(''),
+ shippingAutoFlowRequested: ref(false),
+ shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
+ shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
+ pendingShippingUploadTaskId: ref(''),
+ pendingShippingNoticeTaskId: ref(''),
+ pendingShippingInventoryFile: ref(null),
+ resolvedShippingTaskId: ref(''),
+ resolvedShippingBatchNo: ref(''),
+ shippingBatchSummary: ref(null),
+ shippingBatchTasks: ref([]),
+ shippingInventorySelectionActive: ref(false),
+ shippingInventorySelectionTaskId: ref(''),
+ shippingInventorySchemaPreviewCache: ref({}),
+ getActiveShippingTaskId: () => '',
+ startChatTurn,
+ refreshShippingActions: vi.fn(async () => undefined),
+ msg: { warning: vi.fn() },
+ t: (key: string) => key,
+});
+
+describe('useChatPageConversation', () => {
+ beforeEach(() => {
+ listChatMessages.mockReset();
+ computeNoticeFilesContentFingerprint.mockReset();
+ computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
+ const content = await files[0]?.text();
+ return `fp-${content || 'empty'}`;
+ });
+ resetShippingNoticeBatchSubmitStateForTests();
+ });
+
+ it('startNewChat clears pending notice batch retry and next upload uses a new idempotency key', async () => {
+ const startChatTurn = vi.fn(async () => false);
+ const { conversationId, createNewChatView, api } = createConversationContext();
+ const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
+ createUploadContext(conversationId, startChatTurn),
+ );
+ const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ api.startNewChat();
+
+ expect(createNewChatView).toHaveBeenCalledTimes(1);
+ expect(conversationId.value).toBeNull();
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ expect(firstKey).toBeTruthy();
+ expect(secondKey).toBeTruthy();
+ expect(secondKey).not.toBe(firstKey);
+ });
+
+ it('resetChatStateForAgentChange clears pending notice batch retry and next upload uses a new idempotency key', async () => {
+ const startChatTurn = vi.fn(async () => false);
+ const { conversationId, createNewChatView, api } = createConversationContext();
+ const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
+ createUploadContext(conversationId, startChatTurn),
+ );
+ const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ api.resetChatStateForAgentChange();
+
+ expect(createNewChatView).toHaveBeenCalledTimes(1);
+ expect(conversationId.value).toBeNull();
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ expect(firstKey).toBeTruthy();
+ expect(secondKey).toBeTruthy();
+ expect(secondKey).not.toBe(firstKey);
+ });
+});
diff --git a/frontend/src/features/chat/page/useChatPageConversation.ts b/frontend/src/features/chat/page/useChatPageConversation.ts
index 65687944..c8b4984b 100644
--- a/frontend/src/features/chat/page/useChatPageConversation.ts
+++ b/frontend/src/features/chat/page/useChatPageConversation.ts
@@ -17,6 +17,7 @@ export interface ChatPageConversationContext {
isThinking: Ref;
loadConversationState: (id: string, loaded: ChatMessage[]) => void;
createNewChatView: () => void;
+ clearPendingNoticeBatchRetry: () => void;
onConversationIdChanging: (nextId: string, prevId: string | null | undefined) => void;
onConversationLoadedEmpty: () => Promise;
onConversationLoadFailed: () => Promise;
@@ -71,6 +72,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
};
const startNewChat = () => {
+ ctx.clearPendingNoticeBatchRetry();
ctx.createNewChatView();
ctx.clearAttachments();
ctx.input.value = '';
@@ -84,6 +86,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
};
const resetChatStateForAgentChange = () => {
+ ctx.clearPendingNoticeBatchRetry();
ctx.createNewChatView();
ctx.clearHistory();
ctx.clearAttachments();
diff --git a/frontend/src/features/chat/page/useChatPageMarkdown.ts b/frontend/src/features/chat/page/useChatPageMarkdown.ts
index c7c4c839..ff0d6ec9 100644
--- a/frontend/src/features/chat/page/useChatPageMarkdown.ts
+++ b/frontend/src/features/chat/page/useChatPageMarkdown.ts
@@ -6,10 +6,16 @@
*/
import { computed } from 'vue';
import { marked } from 'marked';
+import { useMessage } from '@/shared/composables/useMessage';
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../types/chat.types';
import type { ShippingMatchResultPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
+import {
+ downloadFileCheckExcelByRunId,
+ parseFileCheckExcelRunId,
+ rewriteFileCheckExcelLinksForDisplay,
+} from '../utils/fileCheckExcelDownload';
marked.setOptions({ gfm: true, breaks: true });
@@ -330,6 +336,8 @@ function enhanceAssetHistoryTableLinks(html: string): string {
}
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
+ const message = useMessage();
+
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
if (msgItem?.role === 'user') return true;
if (msgItem?.type === 'shipping-parse-review') return false;
@@ -378,26 +386,6 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const target = event.target as HTMLElement | null;
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
const rawHref = anchor?.getAttribute('href') || '';
- // #region debug-point A:asset-history-anchor-click
- if (rawHref.startsWith('#asset-history?')) {
- fetch('http://127.0.0.1:7777/event', {
- method: 'POST',
- body: JSON.stringify({
- sessionId: 'asset-history-click',
- runId: 'pre-fix',
- hypothesisId: 'A',
- location: 'frontend/useChatPageMarkdown.ts',
- msg: '[DEBUG] asset history anchor clicked',
- data: {
- href: rawHref,
- tagName: target?.tagName || '',
- anchorText: String(anchor?.textContent || '').trim(),
- },
- ts: Date.now(),
- }),
- }).catch(() => {});
- }
- // #endregion
if (rawHref.startsWith('#asset-history?')) {
event.preventDefault();
const params = new URLSearchParams(rawHref.slice('#asset-history?'.length));
@@ -416,6 +404,15 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
void ctx.openPreview(preview);
return;
}
+ const fileCheckRunId = parseFileCheckExcelRunId(rawHref);
+ if (fileCheckRunId) {
+ event.preventDefault();
+ void downloadFileCheckExcelByRunId(fileCheckRunId).catch((error: unknown) => {
+ const text = error instanceof Error ? error.message : '下载 Excel 失败';
+ message.error(text);
+ });
+ return;
+ }
ctx.handleLeaveMarkdownClick(event);
};
@@ -428,7 +425,9 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const renderMarkdown = (text: string) => {
if (!text) return '';
const extracted = safeExtractInlineDownloadFiles(text);
- const displayText = ctx.prepareMarkdownDisplayText(extracted.cleanedText);
+ const displayText = rewriteFileCheckExcelLinksForDisplay(
+ ctx.prepareMarkdownDisplayText(extracted.cleanedText),
+ );
try {
const rendered = marked.parse(displayText);
const html = typeof rendered === 'string' ? rendered : displayText;
diff --git a/frontend/src/features/chat/shipping/shippingNoticeAttachmentIntegrity.spec.ts b/frontend/src/features/chat/shipping/shippingNoticeAttachmentIntegrity.spec.ts
new file mode 100644
index 00000000..0dbdc7c4
--- /dev/null
+++ b/frontend/src/features/chat/shipping/shippingNoticeAttachmentIntegrity.spec.ts
@@ -0,0 +1,56 @@
+/**
+ * features/chat/shipping/shippingNoticeAttachmentIntegrity.spec.ts
+ * 用途:附件完整性门禁单测;阻断码与截断路径须能阻止建单判定。
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ BLOCKING_WARNING_PREFIXES,
+ isShippingNoticeAttachmentParseIncomplete,
+} from './shippingNoticeAttachmentIntegrity';
+
+describe('shippingNoticeAttachmentIntegrity', () => {
+ it('treats each blocking warning prefix as incomplete', () => {
+ for (const prefix of BLOCKING_WARNING_PREFIXES) {
+ expect(
+ isShippingNoticeAttachmentParseIncomplete({
+ warnings: [`${prefix}demo`],
+ attachments: [],
+ }),
+ ).toBe(true);
+ }
+ });
+
+ it('treats per-attachment text truncation as incomplete', () => {
+ expect(
+ isShippingNoticeAttachmentParseIncomplete({
+ attachment_count: 1,
+ attachments: [
+ {
+ parse_status: 'parsed',
+ warnings: ['eml_attachment_text_truncated:10'],
+ },
+ ],
+ warnings: [],
+ }),
+ ).toBe(true);
+ });
+
+ it('treats notice_text_truncated as incomplete', () => {
+ expect(
+ isShippingNoticeAttachmentParseIncomplete({
+ warnings: ['notice_text_truncated:200000'],
+ attachments: [],
+ }),
+ ).toBe(true);
+ });
+
+ it('allows clean parsed summary', () => {
+ expect(
+ isShippingNoticeAttachmentParseIncomplete({
+ attachment_count: 1,
+ attachments: [{ parse_status: 'parsed', warnings: [] }],
+ warnings: [],
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/frontend/src/features/chat/shipping/shippingNoticeAttachmentIntegrity.ts b/frontend/src/features/chat/shipping/shippingNoticeAttachmentIntegrity.ts
new file mode 100644
index 00000000..8465dc56
--- /dev/null
+++ b/frontend/src/features/chat/shipping/shippingNoticeAttachmentIntegrity.ts
@@ -0,0 +1,54 @@
+/**
+ * features/chat/shipping/shippingNoticeAttachmentIntegrity.ts
+ * 用途:发货通知附件完整性门禁契约(阻断 warning 前缀与 incomplete 判定)。
+ * 依赖:shipping.types(ParseSummary 形状)。
+ * 逻辑:与后端 attachment_integrity.BLOCKING_WARNING_PREFIXES /
+ * is_attachment_parse_incomplete 保持一致;契约测试校验两端前缀集合。
+ */
+
+import type { ShippingNoticeParseSummary } from '../types/shipping.types';
+
+/** 阻断 warning 前缀;须与 backend BLOCKING_WARNING_PREFIXES 完全一致(顺序可不同)。 */
+export const BLOCKING_WARNING_PREFIXES = [
+ 'eml_nesting_depth_exceeded:',
+ 'eml_attachment_limit_exceeded:',
+ 'eml_total_attachment_size_exceeded:',
+ 'eml_nested_message_unreadable',
+ 'eml_attachment_text_budget_exhausted:',
+ 'eml_attachment_text_truncated:',
+ 'notice_text_truncated:',
+] as const;
+
+const INCOMPLETE_ATTACHMENT_STATUSES = new Set(['failed', 'empty', 'skipped']);
+
+/**
+ * 判定单条 warning 是否为完整性阻断项。
+ */
+export function isBlockingWarning(text: string): boolean {
+ const normalized = String(text || '');
+ return BLOCKING_WARNING_PREFIXES.some((prefix) => normalized.startsWith(prefix));
+}
+
+/**
+ * 判定 EML 等 intake 是否存在未完整解析的附件(含超深/超限/截断警告)。
+ * 核心逻辑:阻断警告、登记数少于发现数、或 failed/empty/skipped 均视为不完整;
+ * duplicate 仅为去重,不阻断建单。
+ */
+export function isShippingNoticeAttachmentParseIncomplete(
+ summary?: ShippingNoticeParseSummary | null,
+): boolean {
+ if (!summary) return false;
+ const warnings = summary.warnings || [];
+ if (warnings.some((item) => isBlockingWarning(String(item || '')))) {
+ return true;
+ }
+ const rows = summary.attachments || [];
+ const total = Number(summary.attachment_count || 0);
+ if (total > rows.length) return true;
+ return rows.some((item) => {
+ if (INCOMPLETE_ATTACHMENT_STATUSES.has(String(item.parse_status || ''))) {
+ return true;
+ }
+ return (item.warnings || []).some((w) => isBlockingWarning(String(w || '')));
+ });
+}
diff --git a/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts b/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts
new file mode 100644
index 00000000..62cc7603
--- /dev/null
+++ b/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts
@@ -0,0 +1,23 @@
+/**
+ * features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts
+ * 用途:验证前端文件集合指纹与后端 compute_notice_items_content_fingerprint 对齐。
+ */
+import { describe, expect, it } from 'vitest';
+import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdempotency';
+
+describe('shippingNoticeBatchIdempotency', () => {
+ it('treats duplicate files as one content set', async () => {
+ const content = 'same-notice-content';
+ const single = new File([content], 'a.txt', { type: 'text/plain' });
+ const duplicatePair = [
+ new File([content], 'a.txt', { type: 'text/plain' }),
+ new File([content], 'b.txt', { type: 'text/plain' }),
+ ];
+
+ const singleFp = await computeNoticeFilesContentFingerprint([single]);
+ const duplicateFp = await computeNoticeFilesContentFingerprint(duplicatePair);
+
+ expect(singleFp).toBeTruthy();
+ expect(duplicateFp).toBe(singleFp);
+ });
+});
diff --git a/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.ts b/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.ts
new file mode 100644
index 00000000..7181513f
--- /dev/null
+++ b/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.ts
@@ -0,0 +1,38 @@
+/**
+ * features/chat/shipping/shippingNoticeBatchIdempotency.ts
+ * 用途:发货通知建批幂等键与文件集合指纹计算。
+ * 依赖:浏览器 Web Crypto API。
+ * 逻辑:useChatShippingUploadHandler 在重试时绑定「幂等键 + 文件指纹」,文件变化时生成新键。
+ */
+
+/**
+ * 将 File 列表转为与后端 notice_items 对齐的内容指纹(排序哈希后二次 SHA-256)。
+ */
+export async function computeNoticeFilesContentFingerprint(files: File[]): Promise {
+ const hashes: string[] = [];
+ for (const file of files) {
+ if (!file) continue;
+ const buffer = await file.arrayBuffer();
+ const digest = await crypto.subtle.digest('SHA-256', buffer);
+ const hex = Array.from(new Uint8Array(digest))
+ .map((byte) => byte.toString(16).padStart(2, '0'))
+ .join('');
+ hashes.push(hex.toLowerCase());
+ }
+ const uniqueHashes = [...new Set(hashes)].sort();
+ if (!uniqueHashes.length) return '';
+ const joined = uniqueHashes.join('|');
+ const encoded = new TextEncoder().encode(joined);
+ const fingerprintDigest = await crypto.subtle.digest('SHA-256', encoded);
+ return Array.from(new Uint8Array(fingerprintDigest))
+ .map((byte) => byte.toString(16).padStart(2, '0'))
+ .join('')
+ .toLowerCase();
+}
+
+/**
+ * 将 intake 编号列表转为建批重试指纹(排序去重后拼接)。
+ */
+export function computeNoticeIntakeNosFingerprint(intakeNos: string[]): string {
+ return [...new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean))].sort().join('|');
+}
diff --git a/frontend/src/features/chat/shipping/shippingStepper.ts b/frontend/src/features/chat/shipping/shippingStepper.ts
index 5537db73..c65fd1b2 100644
--- a/frontend/src/features/chat/shipping/shippingStepper.ts
+++ b/frontend/src/features/chat/shipping/shippingStepper.ts
@@ -130,6 +130,7 @@ function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined):
|| reviewStatus === 'rsv_required'
|| pendingReason === 'low_confidence'
|| pendingReason === 'rsv_required'
+ || pendingReason === 'inventory_source_unresolved'
) {
return 1;
}
@@ -159,7 +160,12 @@ export function buildShippingWorkflowSteps(
}
if (
- (index === 1 && (reviewStatus === 'parse_review' || pendingReason === 'low_confidence' || pendingReason === 'rsv_required'))
+ (index === 1 && (
+ reviewStatus === 'parse_review'
+ || pendingReason === 'low_confidence'
+ || pendingReason === 'rsv_required'
+ || pendingReason === 'inventory_source_unresolved'
+ ))
|| (index === 2 && (pendingReason === 'inv_unavail' || pendingReason === 'rpa_exhausted'))
|| (index === 3 && (reviewStatus === 'align_review' || pendingReason === 'align_review'))
|| (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage'))
diff --git a/frontend/src/features/chat/shipping/shippingTurnActions.spec.ts b/frontend/src/features/chat/shipping/shippingTurnActions.spec.ts
new file mode 100644
index 00000000..97bd5886
--- /dev/null
+++ b/frontend/src/features/chat/shipping/shippingTurnActions.spec.ts
@@ -0,0 +1,22 @@
+/**
+ * features/chat/shipping/shippingTurnActions.spec.ts
+ * 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
+ */
+import { describe, expect, it } from 'vitest';
+import { buildShippingCreateBatchTurn } from './shippingTurnActions';
+
+describe('shippingTurnActions', () => {
+ it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
+ const files = [
+ new File(['notice-a'], 'notice-a.txt', { type: 'text/plain' }),
+ new File(['notice-b'], 'notice-b.txt', { type: 'text/plain' }),
+ ];
+ const turn = buildShippingCreateBatchTurn(files, 'conv-001', 'idem-key-001');
+
+ expect(turn.actionType).toBe('shipping.create_batch_from_notices');
+ expect(turn.payload.conversation_id).toBe('conv-001');
+ expect(turn.payload.file_count).toBe(2);
+ expect(turn.payload.idempotency_key).toBe('idem-key-001');
+ expect(turn.files).toEqual(files);
+ });
+});
diff --git a/frontend/src/features/chat/shipping/shippingTurnActions.ts b/frontend/src/features/chat/shipping/shippingTurnActions.ts
index e577f05d..8a263873 100644
--- a/frontend/src/features/chat/shipping/shippingTurnActions.ts
+++ b/frontend/src/features/chat/shipping/shippingTurnActions.ts
@@ -78,6 +78,7 @@ export function buildShippingSubmitDecisionTurn(
export function buildShippingCreateBatchTurn(
files: File[],
conversationId?: string | null,
+ idempotencyKey?: string,
): { actionType: string; displayText: string; payload: Record; files: File[] } {
const count = files.length;
const displayText = count === 1
@@ -89,11 +90,35 @@ export function buildShippingCreateBatchTurn(
payload: {
conversation_id: conversationId || undefined,
file_count: count,
+ idempotency_key: idempotencyKey,
},
files,
};
}
+/**
+ * 构造发货通知建批 Chat Turn(基于已解析 intake,不再携带 files)。
+ */
+export function buildShippingCreateBatchFromIntakesTurn(
+ intakeNos: string[],
+ conversationId?: string | null,
+ idempotencyKey?: string,
+): { actionType: string; displayText: string; payload: Record } {
+ const count = intakeNos.length;
+ const displayText = count === 1
+ ? `确认建单:${intakeNos[0]}`
+ : `确认建单:${count} 份发货通知`;
+ return {
+ actionType: 'shipping.create_batch_from_intakes',
+ displayText,
+ payload: {
+ intake_nos: intakeNos,
+ conversation_id: conversationId || undefined,
+ idempotency_key: idempotencyKey,
+ },
+ };
+}
+
/**
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
*/
diff --git a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts
index 3089489d..6cfe191d 100644
--- a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts
+++ b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts
@@ -32,7 +32,7 @@ export interface ShippingMenuHandlerContext {
refreshShippingActions: () => Promise;
startChatTurn: (options: StartChatTurnOptions) => Promise;
msg: { warning: (text: string) => void; info: (text: string) => void };
- t: (key: string) => string;
+ t: (key: string, ...args: unknown[]) => string;
}
export interface HandleShippingMenuActionOptions {
@@ -97,8 +97,8 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
if (!turnSpec) return false;
const displayBase = String(action.message || actionId || '操作').trim();
const displayText = actionId === 'confirm_inventory_source'
- ? `${displayBase}\n任务编号:${taskId}`
- : `${displayBase}(任务编号:${taskId})`;
+ ? ctx.t('chat.shippingNoticeUi.inventorySource.confirmWithTask', { taskId })
+ : ctx.t('chat.shippingNoticeUi.inventorySource.actionWithTask', { message: displayBase, taskId });
await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
@@ -168,7 +168,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
}
if (!sourceCode) {
- ctx.msg.warning('请直接输入要使用的库存源线索,例如 AWSDU、Dublin 或 Singapore。');
+ ctx.msg.warning(ctx.t('chat.shippingNoticeUi.inventorySource.inputHint'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
@@ -179,7 +179,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
}
const label = String(('label' in action ? action.label : '') || sourceCode).trim();
const displayMessage = action.id === 'confirm_inventory_source'
- ? `确认库存查询来源:${label || sourceCode}`
+ ? ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label: label || sourceCode })
: action.message;
await runShippingActionTurn(
{ ...action, message: displayMessage },
@@ -195,7 +195,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
if (action.id === 'retry_resolve_inventory_source') {
await ctx.refreshShippingActions();
- ctx.msg.info('已重新刷新库存源状态');
+ ctx.msg.info(ctx.t('chat.shippingNoticeUi.inventorySource.retryResolveDone'));
return;
}
if (action.id === 'edit_inventory_mapping') {
diff --git a/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts
new file mode 100644
index 00000000..39ca0142
--- /dev/null
+++ b/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts
@@ -0,0 +1,74 @@
+/**
+ * features/chat/shipping/useChatShippingSendHandler.spec.ts
+ * 用途:验证建批提交中发送拦截不会回退到普通聊天发送。
+ */
+import { computed, ref } from 'vue';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createShippingSendHandlers, type ShippingSendHandlerContext } from './useChatShippingSendHandler';
+
+const isShippingNoticeBatchSubmitting = vi.hoisted(() => vi.fn(() => false));
+
+vi.mock('./useChatShippingUploadHandler', () => ({
+ isShippingNoticeBatchSubmitting,
+}));
+
+const createContext = (
+ overrides: Partial = {},
+): ShippingSendHandlerContext => ({
+ isShippingNoticeAgent: computed(() => true),
+ isThinking: ref(false),
+ isUploadingAttachments: ref(false),
+ messages: ref([]),
+ conversationId: ref('conv-send'),
+ history: ref([]),
+ input: ref(''),
+ attachments: ref([{ kind: 'local', file: new File(['notice'], 'notice.txt', { type: 'text/plain' }) }]),
+ shippingAutoFlowRequested: ref(true),
+ resolvedShippingTaskId: ref(''),
+ getActiveShippingBatchNo: () => '',
+ currentAgentId: computed(() => 1),
+ selectedKb: ref(''),
+ attachmentPolicy: computed(() => ({ anyEnabled: true })),
+ getActiveShippingTaskId: () => '',
+ lastAssistantMessageContent: () => '',
+ lastAssistantShippingActions: () => [],
+ sendMessage: vi.fn(async () => undefined),
+ buildFileSpecsForSend: vi.fn(async () => []),
+ loadHistory: vi.fn(async () => undefined),
+ sendShippingMenuMessage: vi.fn(async () => undefined),
+ startChatTurn: vi.fn(async () => true),
+ openShippingInventoryPicker: vi.fn(() => true),
+ executeShippingDecision: vi.fn(async () => true),
+ executeShippingManualUpload: vi.fn(async () => true),
+ handleShippingMenuAction: vi.fn(async () => undefined),
+ handleShippingAutoUploadFile: vi.fn(async () => undefined),
+ handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
+ isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
+ refreshShippingActions: vi.fn(async () => undefined),
+ shippingSuggestedPrompt: computed(() => ''),
+ isShippingShortageQueryIntent: () => false,
+ queryShippingShortageDetails: vi.fn(async () => true),
+ msg: { warning: vi.fn(), info: vi.fn() },
+ t: (key: string) => key,
+ ...overrides,
+});
+
+describe('useChatShippingSendHandler', () => {
+ beforeEach(() => {
+ isShippingNoticeBatchSubmitting.mockReset();
+ isShippingNoticeBatchSubmitting.mockReturnValue(false);
+ });
+
+ it('consumes send while notice batch is submitting and does not call sendMessage', async () => {
+ isShippingNoticeBatchSubmitting.mockReturnValue(true);
+ const ctx = createContext();
+ const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
+
+ const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
+
+ expect(consumed).toBe(true);
+ expect(ctx.sendMessage).not.toHaveBeenCalled();
+ expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
+ expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
+ });
+});
diff --git a/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts b/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts
index 786414c7..e024e8db 100644
--- a/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts
+++ b/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts
@@ -61,12 +61,18 @@ export interface ShippingSendHandlerContext {
handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise;
handleShippingAutoUploadFile: (file: File) => Promise;
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise;
+ isShippingNoticeBatchSubmitting?: () => boolean;
+ hasBlockingNoticeIntake?: () => boolean;
+ hasNoticeIntakeFailures?: () => boolean;
+ hasBlockingNoticeDuplicates?: () => boolean;
+ openShippingDuplicateDialog?: (attachmentId?: string) => void;
+ getParsedIntakeNos?: () => string[];
refreshShippingActions: () => Promise;
shippingSuggestedPrompt: ComputedRef;
isShippingShortageQueryIntent: (text: string) => boolean;
queryShippingShortageDetails: (taskNo?: string, displayText?: string) => Promise;
msg: { warning: (text: string) => void; info: (text: string) => void };
- t: (key: string) => string;
+ t: (key: string, ...args: unknown[]) => string;
}
/**
@@ -114,13 +120,13 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
const label = String(hit?.display_name || sourceCode).trim();
await ctx.handleShippingMenuAction({
id: 'confirm_inventory_source',
- message: `确认库存查询来源:${label}`,
+ message: ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label }),
label,
source_code: sourceCode,
});
return true;
} catch (e: unknown) {
- const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
+ const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUi.inventorySource.confirmFailed');
ctx.msg.warning(errorMessage);
return true;
}
@@ -186,9 +192,42 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
_content: string,
trimmed: string,
): Promise => {
+ if (!ctx.isShippingNoticeAgent.value) return false;
+ const noticeItems = ctx.attachments.value.filter((item) => item.kind === 'shipping_notice');
+ if (noticeItems.length > 0) {
+ if (ctx.hasBlockingNoticeIntake?.()) {
+ ctx.msg.info(ctx.t('chat.shippingNoticeWaitingForParse'));
+ return true;
+ }
+ if (ctx.hasNoticeIntakeFailures?.()) {
+ ctx.msg.warning(ctx.t('chat.shippingNoticeParseFailedHint'));
+ return true;
+ }
+ if (ctx.hasBlockingNoticeDuplicates?.()) {
+ ctx.openShippingDuplicateDialog?.();
+ ctx.msg.warning(ctx.t('chat.shippingNoticeDuplicateNeedsResolution'));
+ return true;
+ }
+ const intakeNos = ctx.getParsedIntakeNos?.() || [];
+ if (intakeNos.length && (!trimmed || ctx.shippingAutoFlowRequested.value)) {
+ ctx.shippingAutoFlowRequested.value = false;
+ if (typeof textOrEvent !== 'string') ctx.input.value = '';
+ try {
+ await ctx.handleShippingAutoUploadNoticeBatch([]);
+ } catch (e: unknown) {
+ const errorMessage = e instanceof Error ? e.message : '文件处理失败';
+ ctx.msg.warning(errorMessage);
+ }
+ return true;
+ }
+ }
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
+ if (ctx.isShippingNoticeBatchSubmitting?.()) {
+ ctx.msg.info(ctx.t('chat.shippingNoticeBatchSubmitting'));
+ return true;
+ }
const requestedAutoFlow = ctx.shippingAutoFlowRequested.value;
ctx.shippingAutoFlowRequested.value = false;
const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array>;
diff --git a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts
index 7b4f8213..6d9c6914 100644
--- a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts
+++ b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts
@@ -7,7 +7,10 @@
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ clearPendingNoticeBatchRetry,
createShippingUploadHandlers,
+ onNoticeBatchConversationChanging,
+ resetShippingNoticeBatchSubmitStateForTests,
type ShippingUploadHandlerContext,
} from './useChatShippingUploadHandler';
@@ -15,10 +18,21 @@ const { createWorkspaceShippingTask } = vi.hoisted(() => ({
createWorkspaceShippingTask: vi.fn(),
}));
+const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
+ computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => {
+ const content = await files[0]?.text();
+ return `fp-${content || 'empty'}`;
+ }),
+}));
+
vi.mock('@/features/chat/api/shipping.api', () => ({
createWorkspaceShippingTask,
}));
+vi.mock('./shippingNoticeBatchIdempotency', () => ({
+ computeNoticeFilesContentFingerprint,
+}));
+
const createContext = (
overrides: Partial = {},
): ShippingUploadHandlerContext => ({
@@ -50,6 +64,12 @@ const createContext = (
describe('useChatShippingUploadHandler', () => {
beforeEach(() => {
createWorkspaceShippingTask.mockReset();
+ computeNoticeFilesContentFingerprint.mockReset();
+ computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
+ const content = await files[0]?.text();
+ return `fp-${content || 'empty'}`;
+ });
+ resetShippingNoticeBatchSubmitStateForTests();
});
it('opens inventory picker for explicit taskId instead of current active task', () => {
@@ -103,6 +123,186 @@ describe('useChatShippingUploadHandler', () => {
);
});
+ it('double click only calls startChatTurn once and keeps stable idempotency key', async () => {
+ const startChatTurn = vi.fn(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ return true;
+ });
+ const ctx = createContext({
+ getActiveShippingTaskId: () => '',
+ startChatTurn,
+ });
+ const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
+ const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
+
+ const first = handleShippingAutoUploadNoticeBatch([file]);
+ const second = handleShippingAutoUploadNoticeBatch([file]);
+ await Promise.all([first, second]);
+
+ expect(startChatTurn).toHaveBeenCalledTimes(1);
+ const payload = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload;
+ expect(payload?.idempotency_key).toBeTruthy();
+ });
+
+ it('reuses idempotency key on retry and generates new key after success', async () => {
+ let attempt = 0;
+ const startChatTurn = vi.fn(async () => {
+ attempt += 1;
+ return attempt >= 2;
+ });
+ const ctx = createContext({
+ getActiveShippingTaskId: () => '',
+ startChatTurn,
+ });
+ const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
+ const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const thirdKey = (startChatTurn.mock.calls[2]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ expect(firstKey).toBe(secondKey);
+ expect(thirdKey).not.toBe(secondKey);
+ });
+
+ it('generates new idempotency key when files change after a failed attempt', async () => {
+ const startChatTurn = vi.fn(async () => false);
+ const ctx = createContext({
+ getActiveShippingTaskId: () => '',
+ startChatTurn,
+ });
+ const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
+ const firstFile = new File(['notice-a'], 'notice-a.pdf', { type: 'application/pdf' });
+ const secondFile = new File(['notice-b'], 'notice-b.pdf', { type: 'application/pdf' });
+
+ await handleShippingAutoUploadNoticeBatch([firstFile]);
+ const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+ await handleShippingAutoUploadNoticeBatch([secondFile]);
+ const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ expect(firstKey).toBeTruthy();
+ expect(secondKey).toBeTruthy();
+ expect(secondKey).not.toBe(firstKey);
+ });
+
+ it('reuses idempotency key when conversation upgrades from empty to server-assigned after network failure', async () => {
+ const conversationId = ref(null);
+ const startChatTurn = vi.fn(async () => {
+ conversationId.value = 'conv-server-new';
+ return false;
+ });
+ const ctx = createContext({
+ conversationId,
+ getActiveShippingTaskId: () => '',
+ startChatTurn,
+ });
+ const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
+ const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ expect(firstKey).toBeTruthy();
+ expect(secondKey).toBe(firstKey);
+ });
+
+ it('generates new idempotency key when switching from new chat to historical session', async () => {
+ const startChatTurn = vi.fn(async () => false);
+ const conversationId = ref(null);
+ const ctx = createContext({
+ conversationId,
+ getActiveShippingTaskId: () => '',
+ startChatTurn,
+ });
+ const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
+ const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ onNoticeBatchConversationChanging('conv-history', '');
+ conversationId.value = 'conv-history';
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ expect(firstKey).toBeTruthy();
+ expect(secondKey).toBeTruthy();
+ expect(secondKey).not.toBe(firstKey);
+ });
+
+ it('generates new idempotency key after explicit clearPendingNoticeBatchRetry', async () => {
+ const startChatTurn = vi.fn(async () => false);
+ const conversationId = ref('conv-a');
+ const ctx = createContext({
+ conversationId,
+ getActiveShippingTaskId: () => '',
+ startChatTurn,
+ });
+ const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
+ const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ clearPendingNoticeBatchRetry();
+ conversationId.value = null;
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ expect(firstKey).toBeTruthy();
+ expect(secondKey).toBeTruthy();
+ expect(secondKey).not.toBe(firstKey);
+ });
+
+ it('generates new idempotency key when conversation changes after a failed attempt', async () => {
+ const startChatTurn = vi.fn(async () => false);
+ const conversationId = ref('conv-a');
+ const ctx = createContext({
+ conversationId,
+ getActiveShippingTaskId: () => '',
+ startChatTurn,
+ });
+ const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
+ const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
+
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ onNoticeBatchConversationChanging('conv-b', 'conv-a');
+ conversationId.value = 'conv-b';
+ await handleShippingAutoUploadNoticeBatch([file]);
+ const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key;
+
+ expect(firstKey).toBeTruthy();
+ expect(secondKey).toBeTruthy();
+ expect(secondKey).not.toBe(firstKey);
+ });
+
+ it('releases submit lock when fingerprint computation fails', async () => {
+ computeNoticeFilesContentFingerprint.mockRejectedValueOnce(new Error('digest failed'));
+ const startChatTurn = vi.fn(async () => true);
+ const ctx = createContext({
+ getActiveShippingTaskId: () => '',
+ startChatTurn,
+ });
+ const { handleShippingAutoUploadNoticeBatch, isShippingNoticeBatchSubmitting } = createShippingUploadHandlers(ctx);
+ const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
+
+ await expect(handleShippingAutoUploadNoticeBatch([file])).rejects.toThrow('digest failed');
+ expect(startChatTurn).not.toHaveBeenCalled();
+ expect(isShippingNoticeBatchSubmitting()).toBe(false);
+
+ computeNoticeFilesContentFingerprint.mockResolvedValueOnce('fp-notice');
+ await handleShippingAutoUploadNoticeBatch([file]);
+ expect(startChatTurn).toHaveBeenCalledTimes(1);
+ });
+
it('does not open notice picker when both explicit taskId and active task are missing', () => {
const noticeClick = vi.fn();
const warning = vi.fn();
diff --git a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts
index a2079861..11a96409 100644
--- a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts
+++ b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts
@@ -2,7 +2,7 @@
* features/chat/shipping/useChatShippingUploadHandler.ts
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
* 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。
- * 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE。
+ * 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE;待重试幂等键绑定 conversation_id。
*/
import { computed } from 'vue';
import {
@@ -10,13 +10,92 @@ import {
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import { extractExt } from '../constants/shipping';
-import { buildShippingCreateBatchTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
+import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
+import { computeNoticeFilesContentFingerprint, computeNoticeIntakeNosFingerprint } from './shippingNoticeBatchIdempotency';
import { classifyShippingUploadFile } from './shippingUploadPrompt';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { PendingAttachment } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
+let noticeBatchSubmitting = false;
+
+interface PendingNoticeBatchRetryState {
+ conversationId: string;
+ idempotencyKey: string;
+ fileFingerprint: string;
+}
+
+let pendingNoticeBatchRetry: PendingNoticeBatchRetryState | null = null;
+
+function normalizeConversationId(conversationId: string | null | undefined): string {
+ return String(conversationId || '').trim();
+}
+
+function clearPendingNoticeBatchRetryState(): void {
+ pendingNoticeBatchRetry = null;
+}
+
+/**
+ * 显式清理待重试建批幂等状态(新建聊天、切换 Agent 等不经 onConversationIdChanging 的路径)。
+ */
+export function clearPendingNoticeBatchRetry(): void {
+ clearPendingNoticeBatchRetryState();
+}
+
+/**
+ * 判断待重试状态是否应绑定到当前会话。
+ * 核心逻辑:允许「尚未分配会话」升级绑定服务端新 ID;两个非空且不同、或旧非空而新为空时清理。
+ */
+function reconcilePendingNoticeBatchConversation(
+ pending: PendingNoticeBatchRetryState,
+ conversationKey: string,
+): void {
+ const pendingKey = pending.conversationId;
+ if (pendingKey === conversationKey) {
+ return;
+ }
+ if (!pendingKey && conversationKey) {
+ pending.conversationId = conversationKey;
+ return;
+ }
+ if (pendingKey && !conversationKey) {
+ clearPendingNoticeBatchRetryState();
+ return;
+ }
+ if (pendingKey && conversationKey && pendingKey !== conversationKey) {
+ clearPendingNoticeBatchRetryState();
+ }
+}
+
+/**
+ * 用户主动切换会话时清理待重试建批状态,避免跨会话复用幂等键。
+ * 仅由 onConversationIdChanging 调用;SSE 自动分配 conversation_id 不经过此函数。
+ */
+export function onNoticeBatchConversationChanging(
+ nextId: string,
+ prevId?: string | null,
+): void {
+ const next = normalizeConversationId(nextId);
+ const prev = normalizeConversationId(prevId);
+ if (next !== prev) {
+ clearPendingNoticeBatchRetryState();
+ }
+}
+
+/**
+ * 查询发货通知建批是否正在提交中(供发送拦截器消费重复点击)。
+ */
+export function isShippingNoticeBatchSubmitting(): boolean {
+ return noticeBatchSubmitting;
+}
+
+/** 单测重置模块级建批提交状态。 */
+export function resetShippingNoticeBatchSubmitStateForTests(): void {
+ noticeBatchSubmitting = false;
+ clearPendingNoticeBatchRetry();
+}
+
export interface ShippingUploadHandlerContext {
conversationId: Ref;
currentAgentId: ComputedRef;
@@ -40,6 +119,8 @@ export interface ShippingUploadHandlerContext {
refreshShippingActions: () => Promise;
msg: { warning: (text: string) => void };
t: (key: string, params?: Record) => string;
+ getParsedIntakeNos?: () => string[];
+ clearConsumedNoticeAttachments?: () => void;
}
/**
@@ -135,25 +216,58 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
};
const runNoticeBatchChatTurn = async (files: File[]) => {
- const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value);
- const ok = await ctx.startChatTurn({
- agentId: ctx.currentAgentId.value,
- inputType: 'upload_followup',
- displayText: turn.displayText,
- actionType: turn.actionType,
- payload: turn.payload,
- files: turn.files,
- hooks: {
- onAssistantMessageFinished: async (assistantMsg) => {
- syncBatchContextFromTurnMessage(assistantMsg);
- void ctx.refreshShippingActions();
+ if (noticeBatchSubmitting) {
+ return true;
+ }
+ noticeBatchSubmitting = true;
+ try {
+ const conversationKey = normalizeConversationId(ctx.conversationId.value);
+ const fileFingerprint = await computeNoticeFilesContentFingerprint(files);
+ if (pendingNoticeBatchRetry) {
+ reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
+ }
+ if (
+ pendingNoticeBatchRetry
+ && pendingNoticeBatchRetry.fileFingerprint !== fileFingerprint
+ ) {
+ clearPendingNoticeBatchRetryState();
+ }
+ if (!pendingNoticeBatchRetry) {
+ pendingNoticeBatchRetry = {
+ conversationId: conversationKey,
+ idempotencyKey: crypto.randomUUID(),
+ fileFingerprint,
+ };
+ } else {
+ pendingNoticeBatchRetry.fileFingerprint = fileFingerprint;
+ }
+ const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
+ const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value, idempotencyKey);
+ const ok = await ctx.startChatTurn({
+ agentId: ctx.currentAgentId.value,
+ inputType: 'upload_followup',
+ displayText: turn.displayText,
+ actionType: turn.actionType,
+ payload: turn.payload,
+ files: turn.files,
+ hooks: {
+ onAssistantMessageFinished: async (assistantMsg) => {
+ syncBatchContextFromTurnMessage(assistantMsg);
+ void ctx.refreshShippingActions();
+ },
},
- },
- });
- if (!ok) {
- ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
+ });
+ if (ok) {
+ if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
+ clearPendingNoticeBatchRetryState();
+ }
+ } else {
+ ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
+ }
+ return ok;
+ } finally {
+ noticeBatchSubmitting = false;
}
- return ok;
};
const syncBatchContextFromNoticeResponse = (result: Record | null | undefined) => {
@@ -196,6 +310,61 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return ok;
};
+ const runNoticeBatchFromIntakes = async (intakeNos: string[]) => {
+ if (noticeBatchSubmitting) {
+ return true;
+ }
+ noticeBatchSubmitting = true;
+ try {
+ const conversationKey = normalizeConversationId(ctx.conversationId.value);
+ const intakeFingerprint = computeNoticeIntakeNosFingerprint(intakeNos);
+ if (pendingNoticeBatchRetry) {
+ reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
+ }
+ if (
+ pendingNoticeBatchRetry
+ && pendingNoticeBatchRetry.fileFingerprint !== intakeFingerprint
+ ) {
+ clearPendingNoticeBatchRetryState();
+ }
+ if (!pendingNoticeBatchRetry) {
+ pendingNoticeBatchRetry = {
+ conversationId: conversationKey,
+ idempotencyKey: crypto.randomUUID(),
+ fileFingerprint: intakeFingerprint,
+ };
+ } else {
+ pendingNoticeBatchRetry.fileFingerprint = intakeFingerprint;
+ }
+ const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
+ const turn = buildShippingCreateBatchFromIntakesTurn(intakeNos, ctx.conversationId.value, idempotencyKey);
+ const ok = await ctx.startChatTurn({
+ agentId: ctx.currentAgentId.value,
+ inputType: 'upload_followup',
+ displayText: turn.displayText,
+ actionType: turn.actionType,
+ payload: turn.payload,
+ hooks: {
+ onAssistantMessageFinished: async (assistantMsg) => {
+ syncBatchContextFromTurnMessage(assistantMsg);
+ void ctx.refreshShippingActions();
+ },
+ },
+ });
+ if (ok) {
+ if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
+ clearPendingNoticeBatchRetryState();
+ }
+ ctx.clearConsumedNoticeAttachments?.();
+ } else {
+ ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
+ }
+ return ok;
+ } finally {
+ noticeBatchSubmitting = false;
+ }
+ };
+
const handleReplaceNoticeForCurrentTask = async (taskId: string, file: File) => {
ctx.resolvedShippingTaskId.value = taskId;
await runReplaceNoticeChatTurn(taskId, file);
@@ -232,6 +401,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
const noticeFiles = files.filter(Boolean);
+ const intakeNos = ctx.getParsedIntakeNos?.() || [];
+ if (!noticeFiles.length && intakeNos.length) {
+ await runNoticeBatchFromIntakes(intakeNos);
+ return;
+ }
if (!noticeFiles.length) return;
const pendingNoticeTaskId = String(ctx.pendingShippingNoticeTaskId.value || '').trim().toUpperCase();
ctx.pendingShippingNoticeTaskId.value = '';
@@ -317,5 +491,6 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
+ isShippingNoticeBatchSubmitting,
};
}
diff --git a/frontend/src/features/chat/shipping/useShippingNoticeIntakes.ts b/frontend/src/features/chat/shipping/useShippingNoticeIntakes.ts
new file mode 100644
index 00000000..0b7d5495
--- /dev/null
+++ b/frontend/src/features/chat/shipping/useShippingNoticeIntakes.ts
@@ -0,0 +1,372 @@
+/**
+ * features/chat/shipping/useShippingNoticeIntakes.ts
+ * 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。
+ * 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity。
+ * 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件;
+ * 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐)。
+ */
+import { computed, onBeforeUnmount, ref, type Ref } from 'vue';
+import { uploadFileAsset } from '@/shared/api/file-assets.api';
+import type {
+ PendingAttachment,
+ ShippingDuplicateAction,
+ ShippingDuplicateResult,
+ ShippingNoticeParseSummary,
+ ShippingNoticePendingAttachment,
+} from '../types/shipping.types';
+import type { ShippingNoticeIntakeResponse } from '../types/shipping.api.types';
+import {
+ cancelShippingNoticeIntake,
+ createShippingNoticeIntake,
+ getShippingNoticeIntakeStatuses,
+ listActiveShippingNoticeIntakes,
+ resolveShippingNoticeDuplicate,
+ retryShippingNoticeIntake,
+} from '@/features/chat/api/shipping.api';
+import { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity';
+
+export { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity';
+
+const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed', 'cancelled', 'expired']);
+const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']);
+
+function mapServerParseStatus(status: string): ShippingNoticePendingAttachment['parseStatus'] {
+ const normalized = String(status || '').trim().toLowerCase();
+ if (normalized === 'parsed') return 'parsed';
+ if (normalized === 'queued' || normalized === 'created') return 'queued';
+ if (normalized === 'parsing') return 'parsing';
+ if (normalized === 'parse_failed') return 'failed';
+ if (normalized === 'consumed') return 'consumed';
+ if (normalized === 'cancelled') return 'cancelled';
+ if (normalized === 'expired') return 'expired';
+ return 'waiting';
+}
+
+/**
+ * 将服务端 duplicate 结果映射为前端附件状态。
+ */
+function mapServerDuplicate(remote: ShippingNoticeIntakeResponse): {
+ duplicate?: ShippingDuplicateResult;
+ duplicateResolution?: ShippingNoticePendingAttachment['duplicateResolution'];
+} {
+ const dup = remote.duplicate;
+ if (!dup) return {};
+ const duplicate: ShippingDuplicateResult = {
+ status: dup.status,
+ blocking: Boolean(dup.blocking),
+ fingerprintStrength: dup.fingerprint_strength,
+ matches: (dup.matches || []).map((item) => ({
+ taskNo: item.task_no,
+ processStatus: item.process_status,
+ documentVersion: Number(item.document_version || 1),
+ matchType: item.match_type,
+ matchedFields: listSafe(item.matched_fields),
+ createdAt: item.created_at,
+ })),
+ allowedActions: (dup.allowed_actions || []) as ShippingDuplicateAction[],
+ };
+ const resolution = remote.duplicate_resolution;
+ return {
+ duplicate,
+ duplicateResolution: resolution
+ ? {
+ action: resolution.action,
+ targetTaskNo: resolution.target_task_no || undefined,
+ reason: resolution.reason || undefined,
+ }
+ : undefined,
+ };
+}
+
+function listSafe(value: unknown): string[] {
+ return Array.isArray(value) ? value.map((item) => String(item)) : [];
+}
+
+function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
+ return {
+ id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
+ kind: 'shipping_notice',
+ file,
+ type: 'document',
+ uploadStatus: 'waiting',
+ parseStatus: 'waiting',
+ uploadProgress: 0,
+ originalFilename: file.name,
+ fileSize: file.size,
+ };
+}
+
+export interface UseShippingNoticeIntakesOptions {
+ attachments: Ref;
+ conversationId: Ref;
+ msg: { warning: (text: string) => void };
+ t: (key: string, params?: Record) => string;
+}
+
+export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOptions) {
+ const pollTimer = ref | null>(null);
+ const pollRound = ref(0);
+
+ const noticeAttachments = computed(() =>
+ options.attachments.value.filter(
+ (item): item is ShippingNoticePendingAttachment => item.kind === 'shipping_notice',
+ ),
+ );
+
+ const hasBlockingUploadOrParse = computed(() =>
+ noticeAttachments.value.some((item) =>
+ item.uploadStatus === 'uploading'
+ || item.uploadStatus === 'waiting'
+ || ACTIVE_PARSE.has(item.parseStatus)
+ || item.parseStatus === 'queued'
+ || item.parseStatus === 'parsing',
+ ),
+ );
+
+ const hasParseFailures = computed(() =>
+ noticeAttachments.value.some(
+ (item) =>
+ item.parseStatus === 'failed'
+ || isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
+ ),
+ );
+
+ const allParsedReady = computed(() =>
+ noticeAttachments.value.length > 0
+ && noticeAttachments.value.every(
+ (item) =>
+ item.parseStatus === 'parsed'
+ && !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
+ ),
+ );
+
+ const hasBlockingDuplicates = computed(() =>
+ noticeAttachments.value.some(
+ (item) => item.duplicate?.blocking && !item.duplicateResolution?.action,
+ ),
+ );
+
+ const allReadyForConfirmation = computed(() =>
+ allParsedReady.value && !hasBlockingDuplicates.value && !hasParseFailures.value,
+ );
+
+ const stopPolling = () => {
+ if (pollTimer.value) {
+ clearTimeout(pollTimer.value);
+ pollTimer.value = null;
+ }
+ pollRound.value = 0;
+ };
+
+ const schedulePoll = () => {
+ stopPolling();
+ const intakeNos = noticeAttachments.value
+ .map((item) => item.intakeNo)
+ .filter((item): item is string => Boolean(item));
+ if (!intakeNos.length) return;
+ if (intakeNos.every((no) => {
+ const item = noticeAttachments.value.find((entry) => entry.intakeNo === no);
+ return item != null && TERMINAL_PARSE.has(item.parseStatus);
+ })) {
+ return;
+ }
+ const delayMs = pollRound.value >= 8 ? 5000 : 2000;
+ pollTimer.value = setTimeout(() => {
+ void refreshStatuses().finally(() => {
+ pollRound.value += 1;
+ schedulePoll();
+ });
+ }, delayMs);
+ };
+
+ const patchAttachment = (id: string, patch: Partial) => {
+ options.attachments.value = options.attachments.value.map((item) =>
+ item.id === id && item.kind === 'shipping_notice'
+ ? { ...item, ...patch }
+ : item,
+ );
+ };
+
+ const refreshStatuses = async () => {
+ const intakeNos = noticeAttachments.value
+ .map((item) => item.intakeNo)
+ .filter((item): item is string => Boolean(item));
+ if (!intakeNos.length) return;
+ const { items } = await getShippingNoticeIntakeStatuses(intakeNos);
+ for (const remote of items) {
+ const local = noticeAttachments.value.find((item) => item.intakeNo === remote.intake_no);
+ if (!local) continue;
+ patchAttachment(local.id, {
+ parseStatus: mapServerParseStatus(remote.parse_status),
+ parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
+ errorCode: remote.error_code || undefined,
+ errorMessage: remote.error_message || undefined,
+ expiresAt: remote.expires_at || undefined,
+ assetNo: remote.asset_no || local.assetNo,
+ ...mapServerDuplicate(remote),
+ });
+ }
+ };
+
+ const processSingleFile = async (attachment: ShippingNoticePendingAttachment) => {
+ if (!attachment.file) return;
+ patchAttachment(attachment.id, { uploadStatus: 'uploading', uploadProgress: 10 });
+ try {
+ const asset = await uploadFileAsset(attachment.file);
+ patchAttachment(attachment.id, {
+ assetNo: asset.asset_no,
+ uploadStatus: 'uploaded',
+ uploadProgress: 100,
+ parseStatus: 'queued',
+ });
+ const intake = await createShippingNoticeIntake(
+ asset.asset_no,
+ options.conversationId.value,
+ );
+ patchAttachment(attachment.id, {
+ intakeNo: intake.intake_no,
+ parseStatus: mapServerParseStatus(intake.parse_status),
+ parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
+ errorCode: intake.error_code || undefined,
+ errorMessage: intake.error_message || undefined,
+ expiresAt: intake.expires_at || undefined,
+ });
+ schedulePoll();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : options.t('chat.shippingNoticeUploadFailed');
+ patchAttachment(attachment.id, {
+ uploadStatus: 'failed',
+ parseStatus: 'failed',
+ errorMessage: message,
+ });
+ options.msg.warning(message);
+ }
+ };
+
+ const enqueueNoticeFiles = async (files: File[]) => {
+ for (const file of files) {
+ const attachment = createPendingAttachment(file);
+ options.attachments.value = [...options.attachments.value, attachment];
+ await processSingleFile(attachment);
+ }
+ };
+
+ /**
+ * 移除待建单附件:先从 UI 删除,再取消后端未消费的 intake(含已 parsed)。
+ * @param id - 本地附件临时 ID
+ */
+ const removeNoticeAttachment = async (id: string) => {
+ const target = noticeAttachments.value.find((item) => item.id === id);
+ options.attachments.value = options.attachments.value.filter((item) => item.id !== id);
+ // parsed 且未建单的 intake 也应取消,否则刷新后会经 listActive 再次出现
+ if (target?.intakeNo && target.parseStatus !== 'consumed') {
+ try {
+ await cancelShippingNoticeIntake(target.intakeNo);
+ } catch {
+ // 移除 UI 优先,取消失败由后端 TTL 兜底
+ }
+ }
+ if (!noticeAttachments.value.length) stopPolling();
+ };
+
+ const retryNoticeAttachment = async (id: string) => {
+ const target = noticeAttachments.value.find((item) => item.id === id);
+ if (!target?.intakeNo) return;
+ patchAttachment(id, { parseStatus: 'queued', errorCode: undefined, errorMessage: undefined });
+ const intake = await retryShippingNoticeIntake(target.intakeNo);
+ patchAttachment(id, {
+ parseStatus: mapServerParseStatus(intake.parse_status),
+ parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
+ errorCode: intake.error_code || undefined,
+ errorMessage: intake.error_message || undefined,
+ });
+ schedulePoll();
+ };
+
+ const getParsedIntakeNos = () =>
+ noticeAttachments.value
+ .filter(
+ (item) =>
+ item.parseStatus === 'parsed'
+ && item.intakeNo
+ && !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
+ )
+ .map((item) => String(item.intakeNo));
+
+ const clearConsumedAttachments = () => {
+ options.attachments.value = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
+ stopPolling();
+ };
+
+ const restoreForConversation = async (conversationId?: string | null) => {
+ const { items } = await listActiveShippingNoticeIntakes(conversationId);
+ const restored: ShippingNoticePendingAttachment[] = items
+ .filter((item) => !TERMINAL_PARSE.has(String(item.parse_status || '').toLowerCase()) || item.parse_status === 'parsed')
+ .filter((item) => item.parse_status !== 'consumed')
+ .map((item) => ({
+ id: `restored_${item.intake_no}`,
+ kind: 'shipping_notice' as const,
+ type: 'document' as const,
+ assetNo: item.asset_no || undefined,
+ intakeNo: item.intake_no,
+ uploadStatus: 'uploaded' as const,
+ parseStatus: mapServerParseStatus(item.parse_status),
+ uploadProgress: 100,
+ originalFilename: item.original_filename || item.intake_no,
+ fileSize: Number(item.file_size || 0),
+ parseSummary: (item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
+ errorCode: item.error_code || undefined,
+ errorMessage: item.error_message || undefined,
+ expiresAt: item.expires_at || undefined,
+ ...mapServerDuplicate(item),
+ }));
+ const nonNotice = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
+ options.attachments.value = [...nonNotice, ...restored];
+ if (restored.some((item) => item.parseStatus === 'queued' || item.parseStatus === 'parsing')) {
+ schedulePoll();
+ }
+ };
+
+ const resolveDuplicateAttachment = async (
+ id: string,
+ action: ShippingDuplicateAction,
+ targetTaskNo?: string,
+ reason?: string,
+ ) => {
+ const target = noticeAttachments.value.find((item) => item.id === id);
+ if (!target?.intakeNo) return;
+ const intake = await resolveShippingNoticeDuplicate(
+ target.intakeNo,
+ action,
+ targetTaskNo,
+ reason,
+ );
+ patchAttachment(target.id, {
+ parseStatus: mapServerParseStatus(intake.parse_status),
+ ...mapServerDuplicate(intake),
+ });
+ };
+
+ onBeforeUnmount(() => {
+ stopPolling();
+ });
+
+ return {
+ noticeAttachments,
+ hasBlockingUploadOrParse,
+ hasParseFailures,
+ allParsedReady,
+ hasBlockingDuplicates,
+ allReadyForConfirmation,
+ enqueueNoticeFiles,
+ removeNoticeAttachment,
+ retryNoticeAttachment,
+ resolveDuplicateAttachment,
+ getParsedIntakeNos,
+ clearConsumedAttachments,
+ restoreForConversation,
+ stopPolling,
+ };
+}
+
+export type ShippingNoticeIntakesApi = ReturnType;
diff --git a/frontend/src/features/chat/types/shipping.api.types.ts b/frontend/src/features/chat/types/shipping.api.types.ts
index ccd26dc2..6376b99f 100644
--- a/frontend/src/features/chat/types/shipping.api.types.ts
+++ b/frontend/src/features/chat/types/shipping.api.types.ts
@@ -4,6 +4,42 @@
* 依赖:无(纯类型模块)。
* 逻辑:shipping.api.ts 与 Chat/工作台组件统一引用本文件 DTO 类型。
*/
+export type InventorySourceStatus =
+ | 'unresolved'
+ | 'ambiguous'
+ | 'resolved'
+ | 'user_confirmed'
+ | 'invalid'
+ | 'conflicted';
+
+export type InventorySourceMethod =
+ | 'rule_exact'
+ | 'rule_combined'
+ | 'user_confirmed'
+ | 'legacy_migrated';
+
+export interface ShippingInventorySourceCandidate {
+ source_code: string;
+ display_name?: string | null;
+ site_id?: string | null;
+ warehouse_id?: string | null;
+ source_type?: string | null;
+ match_score?: number | null;
+ matched_by?: string | null;
+}
+
+export interface ShippingInventorySourceResolution {
+ status?: InventorySourceStatus | null;
+ method?: InventorySourceMethod | null;
+ reason?: string | null;
+ candidates?: ShippingInventorySourceCandidate[];
+ destination_candidates?: string[];
+ evidence?: Record[];
+ conflicts?: string[];
+ config_version?: string | null;
+ routing_fingerprint?: string | null;
+}
+
export interface ShippingInventorySnapshot {
inventory_file_no?: string | null;
source_code?: string | null;
@@ -48,11 +84,34 @@ export interface ShippingTaskSummary {
};
rpa_runtime?: ShippingRpaRuntime | null;
rpa_inventory_source?: Record | null;
- inventory_source_resolution?: Record | null;
+ inventory_source_resolution?: ShippingInventorySourceResolution | null;
+ destination_code?: string | null;
+ destination_city?: string | null;
+ destination_country?: string | null;
+ warehouse_hint?: string | null;
+ inventory_source_code?: string | null;
+ inventory_source_type?: string | null;
+ inventory_site_id?: string | null;
+ inventory_warehouse_id?: string | null;
+ inventory_source_status?: InventorySourceStatus | null;
+ inventory_source_method?: InventorySourceMethod | null;
+ inventory_source_config_version?: string | null;
+ inventory_routing_fingerprint?: string | null;
+ inventory_source_confirmed_at?: string | null;
+ inventory_source_confirmed_by?: number | null;
inventory_snapshot?: ShippingInventorySnapshot | null;
created_at?: string | null;
updated_at?: string | null;
ui_state?: ShippingTaskUiState;
+ /** 业务版本号;修订建单时递增 */
+ document_version?: number;
+ supersedes_task_no?: string | null;
+ superseded_by_task_no?: string | null;
+ duplicate_source_task_no?: string | null;
+ duplicate_resolution_type?: string | null;
+ duplicate_override_reason?: string | null;
+ business_fingerprint?: string | null;
+ fingerprint_version?: string | null;
}
export interface ShippingTaskEvent {
@@ -155,6 +214,8 @@ export interface ShippingTaskUiState {
title?: string | null;
message?: string | null;
error_message?: string | null;
+ /** 文件解析阶段汇总的全部待处理问题(库存源 + 解析 warnings 等) */
+ issues?: string[] | null;
};
action_buttons: ShippingChatAction[];
updated_at?: string | null;
@@ -222,12 +283,28 @@ export interface ShippingTaskCreateResponse {
data?: Record;
}
+export interface ShippingNoticeFileSummary {
+ total_files: number;
+ accepted_count: number;
+ rejected_count: number;
+ duplicate_count: number;
+ accepted_files?: Array>;
+ rejected_files?: Array>;
+ duplicate_files?: Array<{
+ filename: string;
+ duplicate_of: string;
+ content_hash?: string;
+ }>;
+}
+
export interface ShippingNoticeUploadResponse {
status: string;
message?: string;
task_id?: string;
batch_no?: string;
checkpoint?: string;
+ idempotent_replay?: boolean;
+ file_summary?: ShippingNoticeFileSummary;
data?: Record & {
batch?: ShippingBatchSummary;
focus_task?: ShippingTaskSummary | null;
@@ -237,6 +314,69 @@ export interface ShippingNoticeUploadResponse {
human_options?: string[];
}
+export interface ShippingNoticeIntakeResponse {
+ intake_no: string;
+ asset_no?: string | null;
+ conversation_id?: string | null;
+ parse_status: string;
+ parser_version?: string;
+ parse_summary?: Record | null;
+ business_summary?: Record | null;
+ business_fingerprint?: string | null;
+ fingerprint_strength?: ShippingDuplicateFingerprintStrength | null;
+ fingerprint_version?: string | null;
+ duplicate?: ShippingDuplicateResult | null;
+ duplicate_resolution?: {
+ action: ShippingDuplicateAction;
+ reason?: string | null;
+ resolved_by_id?: number | null;
+ resolved_at?: string | null;
+ target_task_no?: string | null;
+ } | null;
+ warnings?: string[];
+ error_code?: string | null;
+ error_message?: string | null;
+ expires_at?: string | null;
+ consumed_at?: string | null;
+ created_at?: string | null;
+ updated_at?: string | null;
+ original_filename?: string;
+ file_size?: number;
+ content_hash?: string;
+}
+
+export type ShippingDuplicateStatus =
+ | 'unchecked'
+ | 'none'
+ | 'exact_file'
+ | 'same_active_task'
+ | 'same_completed_task'
+ | 'possible_duplicate';
+
+export type ShippingDuplicateAction = 'open_existing' | 'create_revision' | 'force_create';
+
+export type ShippingDuplicateFingerprintStrength = 'strong' | 'medium' | 'weak' | 'unavailable';
+
+export interface ShippingDuplicateMatch {
+ task_no: string;
+ process_status: string;
+ document_version: number;
+ match_type: string;
+ matched_fields: string[];
+ lifecycle?: string;
+ created_at?: string;
+}
+
+export interface ShippingDuplicateResult {
+ status: ShippingDuplicateStatus;
+ blocking: boolean;
+ fingerprint_strength: ShippingDuplicateFingerprintStrength;
+ matches: ShippingDuplicateMatch[];
+ allowed_actions: ShippingDuplicateAction[];
+}
+
+export interface ShippingCreateBatchFromIntakesResponse extends ShippingNoticeUploadResponse {}
+
export interface ShippingDecisionResponse {
status: string;
message?: string;
diff --git a/frontend/src/features/chat/types/shipping.types.ts b/frontend/src/features/chat/types/shipping.types.ts
index d0585d6b..0312555d 100644
--- a/frontend/src/features/chat/types/shipping.types.ts
+++ b/frontend/src/features/chat/types/shipping.types.ts
@@ -11,10 +11,120 @@ export type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' |
export type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
-/** 待发送附件(本地文件或远程 URL) */
+export type ShippingNoticeUploadStatus = 'waiting' | 'uploading' | 'uploaded' | 'failed';
+export type ShippingNoticeParseStatus =
+ | 'waiting'
+ | 'queued'
+ | 'parsing'
+ | 'parsed'
+ | 'failed'
+ | 'consumed'
+ | 'cancelled'
+ | 'expired';
+
+export type ShippingDuplicateAction = 'open_existing' | 'create_revision' | 'force_create';
+
+export type ShippingDuplicateFingerprintStrength = 'strong' | 'medium' | 'weak' | 'unavailable';
+
+export type ShippingDuplicateStatus =
+ | 'unchecked'
+ | 'none'
+ | 'exact_file'
+ | 'same_active_task'
+ | 'same_completed_task'
+ | 'possible_duplicate';
+
+export interface ShippingDuplicateMatch {
+ taskNo: string;
+ processStatus: string;
+ documentVersion: number;
+ matchType: string;
+ matchedFields: string[];
+ createdAt?: string;
+}
+
+export interface ShippingDuplicateResult {
+ status: ShippingDuplicateStatus;
+ blocking: boolean;
+ fingerprintStrength: ShippingDuplicateFingerprintStrength;
+ matches: ShippingDuplicateMatch[];
+ allowedActions: ShippingDuplicateAction[];
+}
+
+export interface ShippingDuplicateResolution {
+ action: ShippingDuplicateAction;
+ targetTaskNo?: string;
+ reason?: string;
+}
+
+export interface ShippingNoticeParseAttachmentSummary {
+ attachment_key?: string;
+ filename?: string;
+ mime_type?: string;
+ size?: number;
+ content_hash?: string;
+ parse_status?: string;
+ /** 详情接口才有;状态轮询为瘦身摘要不含全文 */
+ extracted_text?: string;
+ /** 原始解析文本长度 */
+ text_length?: number;
+ /** 落库/截断后长度 */
+ stored_text_length?: number;
+ warnings?: string[];
+}
+
+export interface ShippingNoticeParseEmailMeta {
+ message_id?: string;
+ subject?: string;
+ from?: string;
+ to?: string;
+ date?: string;
+ /** 详情接口才有完整正文;状态轮询通常省略 */
+ body_text?: string;
+ body_text_length?: number;
+ stored_body_text_length?: number;
+}
+
+export interface ShippingNoticeParseSummary {
+ filename?: string;
+ source_type?: string;
+ text_length?: number;
+ line_count?: number;
+ warnings?: string[];
+ parser_version?: string;
+ email?: ShippingNoticeParseEmailMeta;
+ /** 发现的真实附件总数(含因上限未登记的) */
+ attachment_count?: number;
+ /** 实际登记到 attachments[] 的数量 */
+ attachment_registered_count?: number;
+ attachments?: ShippingNoticeParseAttachmentSummary[];
+}
+
+export type ShippingNoticePendingAttachment = {
+ id: string;
+ kind: 'shipping_notice';
+ file?: File;
+ type: 'document';
+ assetNo?: string;
+ intakeNo?: string;
+ uploadStatus: ShippingNoticeUploadStatus;
+ parseStatus: ShippingNoticeParseStatus;
+ uploadProgress: number;
+ originalFilename: string;
+ fileSize: number;
+ parseSummary?: ShippingNoticeParseSummary;
+ errorCode?: string;
+ errorMessage?: string;
+ expiresAt?: string;
+ duplicate?: ShippingDuplicateResult;
+ duplicateResolution?: ShippingDuplicateResolution;
+};
+
+/** 待发送附件(本地文件、远程 URL 或货代通知预解析) */
export type PendingAttachment =
| { id: string; kind: 'local'; file: File; type: ChatUploadFileType }
- | { id: string; kind: 'remote'; url: string; type: ChatUploadFileType };
+ | { id: string; kind: 'remote'; url: string; type: ChatUploadFileType }
+ | ShippingNoticePendingAttachment;
export type ChatUploadFileSpec =
| { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string }
diff --git a/frontend/src/features/chat/utils/fileCheckExcelDownload.spec.ts b/frontend/src/features/chat/utils/fileCheckExcelDownload.spec.ts
new file mode 100644
index 00000000..2af815b1
--- /dev/null
+++ b/frontend/src/features/chat/utils/fileCheckExcelDownload.spec.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import {
+ parseFileCheckExcelRunId,
+ rewriteFileCheckExcelLinksForDisplay,
+} from './fileCheckExcelDownload';
+
+describe('fileCheckExcelDownload', () => {
+ it('parses tool api excel link with token', () => {
+ expect(parseFileCheckExcelRunId(
+ 'http://192.168.100.230:8890/api/file-check/tools/runs/187/excel?token=abc',
+ )).toBe(187);
+ });
+
+ it('parses workspace excel link', () => {
+ expect(parseFileCheckExcelRunId('/api/workspace/file-check/runs/42/excel')).toBe(42);
+ });
+
+ it('rewrites tool api links to workspace paths for display', () => {
+ const input = '下载:[链接](http://ai.example.com/api/file-check/tools/runs/9/excel?token=xyz)';
+ expect(rewriteFileCheckExcelLinksForDisplay(input)).toBe(
+ '下载:[链接](/api/workspace/file-check/runs/9/excel)',
+ );
+ });
+});
diff --git a/frontend/src/features/chat/utils/fileCheckExcelDownload.ts b/frontend/src/features/chat/utils/fileCheckExcelDownload.ts
new file mode 100644
index 00000000..fb3f5c1a
--- /dev/null
+++ b/frontend/src/features/chat/utils/fileCheckExcelDownload.ts
@@ -0,0 +1,106 @@
+/**
+ * features/chat/utils/fileCheckExcelDownload.ts
+ * 用途:解析文件检核 Excel 下载链接,并通过 Workspace 会话鉴权下载(不依赖短期 JWT)。
+ * 依赖:getAuthHeaders。
+ * 逻辑:ChatMessageBubble 点击 Dify 返回的 Tool API 链接时,改走 workspace 下载接口以支持历史对话。
+ */
+
+import { getAuthHeaders } from '@/shared/utils/auth';
+
+const FILE_CHECK_TOOL_EXCEL_PATH_RE = /\/api\/file-check\/tools\/runs\/(\d+)\/excel(?:\?.*)?$/i;
+const FILE_CHECK_WORKSPACE_EXCEL_PATH_RE = /\/api\/workspace\/file-check\/runs\/(\d+)\/excel(?:\?.*)?$/i;
+
+/**
+ * 从 Tool API 或 Workspace 下载链中解析检核批次 ID。
+ * @param href - 原始链接(可为绝对或相对路径)。
+ * @returns 批次 ID;无法解析时返回 null。
+ */
+export function parseFileCheckExcelRunId(href: string): number | null {
+ const normalized = String(href || '').trim();
+ if (!normalized) return null;
+
+ let pathname = normalized;
+ try {
+ if (/^https?:\/\//i.test(normalized)) {
+ pathname = new URL(normalized).pathname;
+ } else {
+ pathname = normalized.split('?')[0] || normalized;
+ }
+ } catch {
+ pathname = normalized.split('?')[0] || normalized;
+ }
+
+ const match = pathname.match(FILE_CHECK_TOOL_EXCEL_PATH_RE)
+ || pathname.match(FILE_CHECK_WORKSPACE_EXCEL_PATH_RE);
+ if (!match?.[1]) return null;
+
+ const runId = Number(match[1]);
+ return Number.isFinite(runId) && runId > 0 ? runId : null;
+}
+
+/**
+ * 将 Dify Tool API 的 Excel 下载链改写为 Workspace 相对路径,供 Markdown 展示。
+ * @param text - 原始聊天文本。
+ * @returns 改写后的文本。
+ */
+export function rewriteFileCheckExcelLinksForDisplay(text: string): string {
+ const source = String(text || '');
+ if (!source) return '';
+
+ return source
+ .replace(
+ /https?:\/\/[^\s)\]]+\/api\/file-check\/tools\/runs\/(\d+)\/excel(?:\?[^\s)\]]*)?/gi,
+ '/api/workspace/file-check/runs/$1/excel',
+ )
+ .replace(
+ /\/api\/file-check\/tools\/runs\/(\d+)\/excel(?:\?[^\s)\]]*)?/gi,
+ '/api/workspace/file-check/runs/$1/excel',
+ );
+}
+
+const parseDownloadFilename = (disposition: string | null, fallback: string) => {
+ const value = disposition || '';
+ const utf8Match = value.match(/filename\*=UTF-8''([^;]+)/i);
+ const raw = utf8Match?.[1] || value.match(/filename="?([^";]+)"?/i)?.[1] || fallback;
+ try {
+ return decodeURIComponent(raw);
+ } catch {
+ return raw;
+ }
+};
+
+/**
+ * 通过 Workspace 接口下载检核 Excel(使用登录态,不依赖 Tool API 短期 token)。
+ * @param runId - 检核批次 ID。
+ * @param fallbackName - 默认文件名。
+ */
+export async function downloadFileCheckExcelByRunId(
+ runId: number,
+ fallbackName = `file-check-run-${runId}.xlsx`,
+): Promise {
+ const url = `/api/workspace/file-check/runs/${encodeURIComponent(String(runId))}/excel`;
+ const res = await fetch(url, { headers: getAuthHeaders() });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ const message = typeof body?.message === 'string'
+ ? body.message
+ : typeof body?.error?.message === 'string'
+ ? body.error.message
+ : `下载失败:${res.status}`;
+ throw new Error(message);
+ }
+
+ const blob = await res.blob();
+ const filename = parseDownloadFilename(
+ res.headers.get('content-disposition'),
+ fallbackName,
+ );
+ const objectUrl = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = objectUrl;
+ link.download = filename;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(objectUrl);
+}
diff --git a/frontend/src/features/kb/utils/kb-display.utils.ts b/frontend/src/features/kb/utils/kb-display.utils.ts
index a7f7b319..0c7105b8 100644
--- a/frontend/src/features/kb/utils/kb-display.utils.ts
+++ b/frontend/src/features/kb/utils/kb-display.utils.ts
@@ -1,16 +1,23 @@
/**
* features/kb/utils/kb-display.utils.ts
- * 文档标题、时间、文件大小与状态徽标等纯展示工具。
+ * 用途:文档标题、时间、文件大小与状态徽标等纯展示工具。
+ * 依赖:kb.api 类型、kb-i18n.types、shared/utils/dateTime(UTC 时间戳本地化)。
+ * 逻辑:KbWorkspace / KbAdminPanel 等调用;时间统一走 formatLocalDateTime,避免无时区后缀被当成本地时间导致差 8 小时。
*/
+import { formatLocalDateTime } from '@/shared/utils/dateTime';
import type { KbDocumentItem } from '../api/kb.api';
import type { KbTranslateFn } from './kb-i18n.types';
+/**
+ * 格式化知识库时间戳为本地时区 `YYYY-MM-DD HH:mm:ss`。
+ * 核心逻辑:委托 formatLocalDateTime;后端 isoformat() 常无 Z,按 UTC 解析后再转浏览器本地时区。
+ * @param value - API 返回的时间字符串
+ * @returns 本地展示文案;空值返回 `--`
+ */
export const formatDateTime = (value?: string | null) => {
if (!value) return '--';
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) return value;
- const pad = (n: number) => String(n).padStart(2, '0');
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
+ const formatted = formatLocalDateTime(value);
+ return formatted === '-' ? '--' : formatted;
};
export const formatFileSize = (value?: number | null) => {
diff --git a/frontend/src/features/workspace/views/ShippingNoticeView.vue b/frontend/src/features/workspace/views/ShippingNoticeView.vue
index d4d94a5d..62ecdda2 100644
--- a/frontend/src/features/workspace/views/ShippingNoticeView.vue
+++ b/frontend/src/features/workspace/views/ShippingNoticeView.vue
@@ -141,6 +141,31 @@ const inventorySnapshotLabel = (triggerType?: string | null) => {
return map[key] || map.on_demand;
};
+const inventorySourceStatusLabel = (status?: string | null) => {
+ const key = String(status || '').trim();
+ if (!key) return '—';
+ const i18nKey = `workspace.shippingNotice.inventorySource.statusLabels.${key}`;
+ return te(i18nKey) ? t(i18nKey) : key;
+};
+
+const inventorySourceMethodLabel = (method?: string | null) => {
+ const key = String(method || '').trim();
+ if (!key) return '—';
+ const i18nKey = `workspace.shippingNotice.inventorySource.methodLabels.${key}`;
+ return te(i18nKey) ? t(i18nKey) : key;
+};
+
+const hasInventorySourceFields = computed(() => {
+ const item = detail.value;
+ if (!item) return false;
+ return !!(
+ item.inventory_source_code
+ || item.inventory_site_id
+ || item.inventory_warehouse_id
+ || item.inventory_source_status
+ );
+});
+
const loadCases = async () => {
loading.value = true;
try {
@@ -388,6 +413,45 @@ onMounted(async () => {
{{ $t('workspace.shippingNotice.fields.freightRef') }}{{ detail.freight_ref_no || '—' }}
+
+
+ {{ $t('workspace.shippingNotice.inventorySource.title') }}
+
+
+
+ - {{ $t('workspace.shippingNotice.inventorySource.sourceCode') }}
+ - {{ detail.inventory_source_code || '—' }}
+
+
+ - {{ $t('workspace.shippingNotice.inventorySource.status') }}
+ - {{ inventorySourceStatusLabel(detail.inventory_source_status) }}
+
+
+ - {{ $t('workspace.shippingNotice.inventorySource.siteId') }}
+ - {{ detail.inventory_site_id || '—' }}
+
+
+ - {{ $t('workspace.shippingNotice.inventorySource.warehouseId') }}
+ - {{ detail.inventory_warehouse_id || '—' }}
+
+
+ - {{ $t('workspace.shippingNotice.inventorySource.method') }}
+ - {{ inventorySourceMethodLabel(detail.inventory_source_method) }}
+
+
+ - {{ $t('workspace.shippingNotice.inventorySource.configVersion') }}
+ - {{ detail.inventory_source_config_version || '—' }}
+
+
+ - {{ $t('workspace.shippingNotice.inventorySource.confirmedBy') }}
+ - {{ detail.inventory_source_confirmed_by ?? '—' }}
+
+
+
+
{
+ const form = new FormData();
+ form.append('file', file);
+ return requestJson ('/api/files/assets', {
+ method: 'POST',
+ body: form,
+ });
+}
+
+/**
+ * 查询文件资产元数据。
+ */
+export function getFileAsset(assetNo: string) {
+ return requestJson(`/api/files/assets/${encodeURIComponent(assetNo)}`);
+}
+
+/**
+ * 删除未引用的临时资产。
+ */
+export function deleteFileAsset(assetNo: string) {
+ return requestJson<{ deleted: boolean }>(`/api/files/assets/${encodeURIComponent(assetNo)}`, {
+ method: 'DELETE',
+ });
+}
diff --git a/frontend/src/shared/components/AgentCategoryList.vue b/frontend/src/shared/components/AgentCategoryList.vue
index 4f4dd4a1..7b324596 100644
--- a/frontend/src/shared/components/AgentCategoryList.vue
+++ b/frontend/src/shared/components/AgentCategoryList.vue
@@ -24,7 +24,7 @@ const props = withDefaults(defineProps<{
activeAgentId: null,
compact: false,
showSearch: true,
- defaultExpanded: true,
+ defaultExpanded: false,
});
const emit = defineEmits<{
@@ -64,7 +64,7 @@ const matchesQuery = (agent: AgentWithCategory, query: string) => {
const filteredAgents = computed(() => {
const q = searchQuery.value.trim();
return props.agents.filter((agent) => {
- if (directoryMemberIds.value.has(agent.id)) return false;
+ if (directoryMemberIds.value.has(agent.id) && !isAggregateAgent(agent)) return false;
return matchesQuery(agent, q);
});
});
@@ -134,18 +134,29 @@ const onSelect = (agent: AgentWithCategory) => {
/**
* 统一 Agent 行的激活/默认样式类。
+ * 核心逻辑:选中态用浅蓝底 + 品牌色文字,比实心 brand-600 更轻,与侧栏历史选中风格一致。
* @param active - 是否为当前选中项
* @param dense - 是否为目录成员等更紧凑的行
*/
const agentRowClass = (active: boolean, dense = false) => {
const base = dense
- ? 'group relative flex w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[11px] font-medium transition-all duration-150'
- : 'group relative flex w-full min-w-0 items-center gap-2 rounded-xl px-2.5 py-2 text-left text-xs font-medium transition-all duration-150';
+ ? 'group relative flex w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[11px] font-medium transition-colors duration-150'
+ : 'group relative flex w-full min-w-0 items-center gap-2 rounded-xl px-2.5 py-2 text-left text-xs font-medium transition-colors duration-150';
if (active) {
- return `${base} cursor-default bg-brand-50 text-brand-700 shadow-sm ring-1 ring-brand-100/80 dark:bg-brand-900/25 dark:text-brand-300 dark:ring-brand-800/40`;
+ return `${base} cursor-default bg-brand-50 text-brand-700`;
}
- return `${base} text-secondary hover:bg-surface hover:text-primary hover:shadow-sm`;
+ return `${base} text-secondary hover:bg-surface hover:text-primary`;
};
+
+/**
+ * 聚合应用作为一级入口时选中态需要更强,避免与浅色未选中卡片混在一起。
+ * 核心逻辑:浅蓝底 + 浅品牌描边表达选中,不用实心深蓝。
+ */
+const aggregateCardClass = (active: boolean) => (
+ active
+ ? 'border-brand-200 bg-brand-50 text-brand-700'
+ : 'border-subtle bg-surface'
+);
@@ -170,12 +181,16 @@ const agentRowClass = (active: boolean, dense = false) => {
-
+
-
+
+
+
+ {{ member.name.charAt(0) }}
+
+ {{ member.name }}
+
+
diff --git a/frontend/src/shared/styles/components-ds.css b/frontend/src/shared/styles/components-ds.css
index 588a39bd..059a10fa 100644
--- a/frontend/src/shared/styles/components-ds.css
+++ b/frontend/src/shared/styles/components-ds.css
@@ -467,6 +467,24 @@
@apply text-left transition-colors text-secondary hover:text-brand-600;
}
+ /* 应用运营表:取消 uppercase/tracking;表头与单元格统一左对齐,排序箭头不挤占文案起点 */
+ .admin-report-table--app-ops thead {
+ @apply normal-case tracking-normal;
+ }
+
+ .admin-report-table--app-ops thead th,
+ .admin-report-table--app-ops tbody td {
+ @apply align-middle text-left;
+ }
+
+ .admin-report-app-ops-sort-btn {
+ @apply inline-flex max-w-full items-center justify-start gap-0.5 text-left text-xs font-semibold text-secondary transition-colors hover:text-brand-600;
+ }
+
+ .admin-report-app-ops-sort-mark {
+ @apply inline-block w-2.5 shrink-0 text-left text-[10px] leading-none text-brand-500;
+ }
+
.admin-report-page-btn {
@apply rounded-lg border border-default px-2.5 py-1.5 text-xs text-secondary transition-colors;
}
diff --git a/frontend/src/shared/types/schedule.types.ts b/frontend/src/shared/types/schedule.types.ts
index 423d9cae..1958b317 100644
--- a/frontend/src/shared/types/schedule.types.ts
+++ b/frontend/src/shared/types/schedule.types.ts
@@ -41,6 +41,7 @@ export interface ScheduleRun {
status: string;
total_count: number;
success_count: number;
+ skipped_count: number;
failed_count: number;
api_request_json?: Record | null;
api_response_json?: Record | null;
@@ -50,6 +51,7 @@ export interface ScheduleRun {
error_message?: string | null;
excel_file_name?: string | null;
excel_file_size?: number | null;
+ inventory_raw_zip_available?: boolean;
kb_sync_status?: string | null;
kb_group_id?: number | null;
kb_document_id?: number | null;
diff --git a/frontend/src/shared/utils/agent-category.utils.ts b/frontend/src/shared/utils/agent-category.utils.ts
index 7754bcba..2b30d73a 100644
--- a/frontend/src/shared/utils/agent-category.utils.ts
+++ b/frontend/src/shared/utils/agent-category.utils.ts
@@ -27,6 +27,8 @@ export interface AgentDirectoryMemberRef extends AgentCategoryFields {
description?: string | null;
agent_code?: string | null;
dify_app_id?: string | null;
+ is_aggregate?: boolean;
+ directory_members?: AgentDirectoryMemberRef[];
}
export interface AgentCategorySubGroup {
diff --git a/frontend/src/shared/utils/auth.test.ts b/frontend/src/shared/utils/auth.test.ts
new file mode 100644
index 00000000..e3498123
--- /dev/null
+++ b/frontend/src/shared/utils/auth.test.ts
@@ -0,0 +1,113 @@
+/**
+ * shared/utils/auth.test.ts
+ *
+ * 用途:覆盖认证本地存储的关键约束,避免“记住我”回归时把过期登录态或 remembered username/password 逻辑改坏。
+ * 依赖:vitest、shared/utils/auth。
+ * 逻辑:重点验证 remember payload 过期清理、remembered username/password 的存取,以及不勾选时不会生成本地持久登录态。
+ */
+import { beforeEach, describe, expect, it } from 'vitest';
+import {
+ clearRememberedLoginProfile,
+ getRememberedLoginPreference,
+ getRememberedLoginProfile,
+ getStoredAuthUser,
+ saveAuthUser,
+ saveRememberedLoginPreference,
+ saveRememberedLoginProfile,
+} from './auth';
+
+class MemoryStorage implements Storage {
+ private store = new Map();
+
+ get length(): number {
+ return this.store.size;
+ }
+
+ clear(): void {
+ this.store.clear();
+ }
+
+ getItem(key: string): string | null {
+ return this.store.has(key) ? this.store.get(key) ?? null : null;
+ }
+
+ key(index: number): string | null {
+ return Array.from(this.store.keys())[index] ?? null;
+ }
+
+ removeItem(key: string): void {
+ this.store.delete(key);
+ }
+
+ setItem(key: string, value: string): void {
+ this.store.set(key, value);
+ }
+}
+
+Object.defineProperty(globalThis, 'localStorage', {
+ value: new MemoryStorage(),
+ writable: true,
+});
+
+Object.defineProperty(globalThis, 'sessionStorage', {
+ value: new MemoryStorage(),
+ writable: true,
+});
+
+describe('shared/utils/auth remember me helpers', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ });
+
+ it('stores remembered username and password for auto-fill', () => {
+ saveRememberedLoginPreference(true);
+ saveRememberedLoginProfile('26040006', 'Hxit@54321');
+
+ expect(getRememberedLoginPreference()).toBe(true);
+ expect(getRememberedLoginProfile()).toMatchObject({
+ username: '26040006',
+ password: 'Hxit@54321',
+ });
+ expect(localStorage.getItem('hxops_login_profile')).not.toContain('Hxit@54321');
+ });
+
+ it('clears expired remember login payload automatically', () => {
+ localStorage.setItem('hxops_user', JSON.stringify({
+ user: {
+ username: 'remembered_user',
+ role: 'admin',
+ access_token: 'expired-token',
+ },
+ expiry: Date.now() - 1000,
+ }));
+
+ expect(getStoredAuthUser()).toBeNull();
+ expect(localStorage.getItem('hxops_user')).toBeNull();
+ });
+
+ it('stores non-remembered login state in session storage only', () => {
+ saveAuthUser({
+ username: 'session_only_user',
+ role: 'user',
+ access_token: 'session-token',
+ }, false);
+
+ expect(getStoredAuthUser()).toMatchObject({
+ username: 'session_only_user',
+ role: 'user',
+ });
+ expect(sessionStorage.getItem('hxops_user')).toContain('session_only_user');
+ expect(localStorage.getItem('hxops_user')).toBeNull();
+ });
+
+ it('removes remembered login preference when user cancels remember me', () => {
+ saveRememberedLoginPreference(true);
+ saveRememberedLoginProfile('26040006', 'Hxit@54321');
+
+ clearRememberedLoginProfile();
+
+ expect(getRememberedLoginPreference()).toBe(false);
+ expect(getRememberedLoginProfile()).toBeNull();
+ });
+});
diff --git a/frontend/src/shared/utils/auth.ts b/frontend/src/shared/utils/auth.ts
index 6d0615a8..de54825e 100644
--- a/frontend/src/shared/utils/auth.ts
+++ b/frontend/src/shared/utils/auth.ts
@@ -1,6 +1,8 @@
/**
* shared/utils/auth.ts
- * 认证 token / 用户读写、logout、跨标签同步。
+ * 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步等认证相关本地存储能力。
+ * 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。
+ * 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理,既支持 30 天免登录,也支持按业务确认方案回填账号密码。
*/
export interface AuthUser {
id?: number;
@@ -19,18 +21,87 @@ export interface AuthUser {
token_expires_at?: number;
}
+interface StoredAuthPayload {
+ user?: AuthUser;
+ expiry?: number;
+}
+
+export interface RememberedLoginProfile {
+ username: string;
+ password: string;
+ updated_at: number;
+}
+
+interface StoredRememberedLoginProfile {
+ username?: string;
+ password_ciphertext?: string;
+ updated_at?: number;
+}
+
+const AUTH_USER_KEY = 'hxops_user';
+const LOGIN_REMEMBER_KEY = 'hxops_login_remember';
+const LOGIN_PROFILE_KEY = 'hxops_login_profile';
+
+/**
+ * 对登录页 remember password 做轻量编码,避免在本地存储中直接裸露原始密码文本。
+ * AI 触发时机:当业务明确要求自动回填密码时使用;这里只做本地编码,不改变“浏览器端可恢复”的事实。
+ */
+const encodeRememberedSecret = (value: string): string => {
+ const text = String(value || '');
+ if (!text) return '';
+ const bytes = new TextEncoder().encode(text);
+ let binary = '';
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+ return globalThis.btoa(binary);
+};
+
+/**
+ * 解码本地 remember password。
+ * AI 触发时机:登录页初始化需要回填密码时使用;解码失败时返回空串并清理坏数据。
+ */
+const decodeRememberedSecret = (value: string): string => {
+ const text = String(value || '');
+ if (!text) return '';
+ const binary = globalThis.atob(text);
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
+ return new TextDecoder().decode(bytes);
+};
+
+/**
+ * 解析认证存储载荷,并在 remember payload 过期时自动清理。
+ * AI 触发时机:当登录页或请求拦截器需要读取当前登录态时,必须先经过这里判断 30 天免登录是否仍有效,
+ * 避免 localStorage 中残留的旧 token 被误认为是有效登录态。
+ */
+const readStoredAuthPayload = (storage: Storage, key: string): StoredAuthPayload | null => {
+ const stored = storage.getItem(key);
+ if (!stored) return null;
+ try {
+ const data = JSON.parse(stored) as StoredAuthPayload | AuthUser;
+ const payload = (data && typeof data === 'object' && ('user' in data || 'expiry' in data))
+ ? data as StoredAuthPayload
+ : { user: data as AuthUser };
+ if (payload.expiry && payload.expiry <= Date.now()) {
+ storage.removeItem(key);
+ return null;
+ }
+ return payload;
+ } catch {
+ storage.removeItem(key);
+ return null;
+ }
+};
+
export const getStoredAuthUser = (): AuthUser | null => {
- const candidates = [
- sessionStorage.getItem('hxops_user'),
- localStorage.getItem('hxops_user'),
+ const candidates: Array<[Storage, string]> = [
+ [sessionStorage, AUTH_USER_KEY],
+ [localStorage, AUTH_USER_KEY],
];
- for (const stored of candidates) {
- if (!stored) continue;
- try {
- const data = JSON.parse(stored);
- return (data.user || data) as AuthUser;
- } catch {
- continue;
+ for (const [storage, key] of candidates) {
+ const payload = readStoredAuthPayload(storage, key);
+ if (payload?.user) {
+ return payload.user;
}
}
return null;
@@ -58,11 +129,11 @@ export const saveAuthUser = (user: AuthUser, remember = false): void => {
? { user: next, expiry: Date.now() + 30 * 24 * 60 * 60 * 1000 }
: { user: next };
if (remember) {
- localStorage.setItem('hxops_user', JSON.stringify(payload));
- sessionStorage.removeItem('hxops_user');
+ localStorage.setItem(AUTH_USER_KEY, JSON.stringify(payload));
+ sessionStorage.removeItem(AUTH_USER_KEY);
} else {
- sessionStorage.setItem('hxops_user', JSON.stringify(payload));
- localStorage.removeItem('hxops_user');
+ sessionStorage.setItem(AUTH_USER_KEY, JSON.stringify(payload));
+ localStorage.removeItem(AUTH_USER_KEY);
}
};
@@ -73,12 +144,100 @@ let _authBroadcast: BroadcastChannel | null = null;
let _authSyncInitialized = false;
const clearAuthStorage = (): void => {
- localStorage.removeItem('hxops_user');
- sessionStorage.removeItem('hxops_user');
+ localStorage.removeItem(AUTH_USER_KEY);
+ sessionStorage.removeItem(AUTH_USER_KEY);
sessionStorage.removeItem('hxops_wecom_state');
sessionStorage.removeItem('hxops_casdoor_state');
};
+/**
+ * 读取登录页“记住我”偏好。
+ * AI 触发时机:进入登录页时,需要先判断用户是否曾选择记住我,再决定是否回填 remembered username/password。
+ */
+export const getRememberedLoginPreference = (): boolean => {
+ try {
+ const stored = localStorage.getItem(LOGIN_REMEMBER_KEY);
+ if (!stored) return false;
+ const data = JSON.parse(stored) as { remember?: boolean };
+ return Boolean(data?.remember);
+ } catch {
+ localStorage.removeItem(LOGIN_REMEMBER_KEY);
+ return false;
+ }
+};
+
+/**
+ * 保存登录页“记住我”偏好。
+ * AI 触发时机:用户勾选或取消“记住我”时,应只调整登录偏好,不要误写密码或覆盖业务 token。
+ */
+export const saveRememberedLoginPreference = (remember: boolean): void => {
+ if (!remember) {
+ localStorage.removeItem(LOGIN_REMEMBER_KEY);
+ return;
+ }
+ localStorage.setItem(LOGIN_REMEMBER_KEY, JSON.stringify({ remember: true }));
+};
+
+/**
+ * 读取 remembered username/password。
+ * AI 触发时机:登录页初始化且 remember=true 时,用于回填上次成功登录的账号和密码,减少重复输入。
+ */
+export const getRememberedLoginProfile = (): RememberedLoginProfile | null => {
+ try {
+ const stored = localStorage.getItem(LOGIN_PROFILE_KEY);
+ if (!stored) return null;
+ const data = JSON.parse(stored) as StoredRememberedLoginProfile;
+ const username = String(data?.username || '').trim();
+ const password = decodeRememberedSecret(String(data?.password_ciphertext || ''));
+ if (!username) {
+ localStorage.removeItem(LOGIN_PROFILE_KEY);
+ return null;
+ }
+ if (!password) {
+ localStorage.removeItem(LOGIN_PROFILE_KEY);
+ return null;
+ }
+ return {
+ username,
+ password,
+ updated_at: Number(data?.updated_at || Date.now()),
+ };
+ } catch {
+ localStorage.removeItem(LOGIN_PROFILE_KEY);
+ return null;
+ }
+};
+
+/**
+ * 保存 remembered username/password。
+ * AI 触发时机:仅当密码登录成功且用户明确勾选“记住我”后保存,用于下次回到登录页时直接回填并允许用户直接点登录。
+ */
+export const saveRememberedLoginProfile = (username: string, password: string): void => {
+ const normalizedUsername = String(username || '').trim();
+ const normalizedPassword = String(password || '');
+ if (!normalizedUsername || !normalizedPassword) {
+ localStorage.removeItem(LOGIN_PROFILE_KEY);
+ return;
+ }
+ localStorage.setItem(
+ LOGIN_PROFILE_KEY,
+ JSON.stringify({
+ username: normalizedUsername,
+ password_ciphertext: encodeRememberedSecret(normalizedPassword),
+ updated_at: Date.now(),
+ } satisfies StoredRememberedLoginProfile),
+ );
+};
+
+/**
+ * 清理登录页 remember 偏好和 remembered username/password。
+ * AI 触发时机:用户取消“记住我”时,必须同步清理自动回填账号密码所需的数据,避免下次进入登录页仍残留旧凭据。
+ */
+export const clearRememberedLoginProfile = (): void => {
+ localStorage.removeItem(LOGIN_REMEMBER_KEY);
+ localStorage.removeItem(LOGIN_PROFILE_KEY);
+};
+
const broadcastLogout = (): void => {
try {
localStorage.setItem(AUTH_LOGOUT_KEY, String(Date.now()));
@@ -123,7 +282,7 @@ export const initAuthSync = (): void => {
_authSyncInitialized = true;
window.addEventListener('storage', (event: StorageEvent) => {
- if (event.key === 'hxops_user' && event.newValue === null && event.oldValue != null) {
+ if (event.key === AUTH_USER_KEY && event.newValue === null && event.oldValue != null) {
handleRemoteLogout();
return;
}
@@ -166,7 +325,7 @@ export const refreshAccessToken = async (): Promise => {
const data = await res.json();
if (!data?.access_token) return null;
// Preserve existing profile fields while replacing rotated token material.
- saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem('hxops_user')));
+ saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem(AUTH_USER_KEY)));
return String(data.access_token);
} catch {
return null;
diff --git a/scripts/mount_fixed_asset_history.sh b/scripts/mount_fixed_asset_history.sh
new file mode 100644
index 00000000..dfd3a864
--- /dev/null
+++ b/scripts/mount_fixed_asset_history.sh
@@ -0,0 +1,341 @@
+#!/usr/bin/env bash
+#
+# scripts/mount_fixed_asset_history.sh
+# 用途:在 Linux 宿主机将 Windows 固资履历 SMB 共享挂载到本地目录,供 hxops-backend 容器只读访问。
+# 依赖:cifs-utils、smbclient(可选连通性探测)、sudo;仓库内 .env.shared / .env. 或已有凭据文件。
+# 逻辑:按 test/prod 选择挂载点 → 从 env 读账号密码写入 /etc/smbcredentials → mount.cifs → 可选写入 fstab。
+# 用法(在仓库根目录,最简):
+# sudo ./scripts/mount_fixed_asset_history.sh test --fstab
+# sudo ./scripts/mount_fixed_asset_history.sh prod --fstab
+# sudo ./scripts/mount_fixed_asset_history.sh test --status
+# sudo ./scripts/mount_fixed_asset_history.sh prod --umount
+#
+set -euo pipefail
+
+ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+
+ENV_NAME="${1:-}"
+ACTION="mount"
+if [[ "${2:-}" == "--fstab" ]]; then
+ ACTION="mount_fstab"
+elif [[ "${2:-}" == "--umount" ]]; then
+ ACTION="umount"
+elif [[ "${2:-}" == "--status" ]]; then
+ ACTION="status"
+elif [[ -n "${2:-}" ]]; then
+ echo "Unknown option: ${2}"
+ echo "Usage: $0 [--fstab|--umount|--status]"
+ exit 1
+fi
+
+if [[ "${ENV_NAME}" != "test" && "${ENV_NAME}" != "prod" ]]; then
+ echo "Usage: $0 [--fstab|--umount|--status]"
+ exit 1
+fi
+
+if [[ "$(id -u)" -ne 0 ]]; then
+ echo "Please run as root (sudo)."
+ echo "Example: sudo $0 ${ENV_NAME:-test} --fstab"
+ exit 1
+fi
+
+#
+# 从仓库 env 文件读取 KEY=VALUE(仅导出 FIXED_ASSET_HISTORY_*,避免 source 整份 .env)。
+# 核心逻辑:先读 .env.shared,再读 .env. 覆盖;密码等特殊字符用 printf -v 赋值。
+#
+load_env_key() {
+ local key="$1"
+ local file="$2"
+ local override="${3:-0}"
+ local line value
+ [[ -f "${file}" ]] || return 0
+ line="$(grep -E "^${key}=" "${file}" | tail -n 1 || true)"
+ [[ -n "${line}" ]] || return 0
+ value="${line#*=}"
+ value="${value%$'\r'}"
+ if [[ "${value}" == \"*\" && "${value}" == *\" ]]; then
+ value="${value:1:${#value}-2}"
+ elif [[ "${value}" == \'*\' && "${value}" == *\' ]]; then
+ value="${value:1:${#value}-2}"
+ fi
+ if [[ "${override}" == "1" || -z "${!key:-}" ]]; then
+ printf -v "${key}" '%s' "${value}"
+ export "${key}"
+ fi
+}
+
+load_fixed_asset_history_env() {
+ local shared_env="${ROOT_DIR}/.env.shared"
+ local env_file="${ROOT_DIR}/.env.${ENV_NAME}"
+ local keys=(
+ FIXED_ASSET_HISTORY_SHARE_USERNAME
+ FIXED_ASSET_HISTORY_SHARE_PASSWORD
+ FIXED_ASSET_HISTORY_LOCAL_ROOT
+ FIXED_ASSET_HISTORY_SMB_SERVER
+ FIXED_ASSET_HISTORY_SMB_SHARE
+ FIXED_ASSET_HISTORY_SMB_SUBDIR
+ FIXED_ASSET_HISTORY_SMB_DOMAIN
+ FIXED_ASSET_HISTORY_MOUNT_UID
+ FIXED_ASSET_HISTORY_MOUNT_GID
+ FIXED_ASSET_HISTORY_CIFS_VERS
+ )
+ local key
+ for key in "${keys[@]}"; do
+ load_env_key "${key}" "${shared_env}" 0
+ load_env_key "${key}" "${env_file}" 1
+ done
+ echo "[env] loaded FIXED_ASSET_HISTORY_* from .env.shared + .env.${ENV_NAME}"
+}
+
+load_fixed_asset_history_env
+
+# Windows UNC: \\192.168.100.130\设备履历记录\履历
+# 说明:部分内核不支持 mount.cifs 的 subdir= 选项(会报 Invalid argument / 22),
+# 因此改为:先挂共享根目录,再把「履历」子目录 bind 到 LOCAL_ROOT。
+SMB_SERVER="${FIXED_ASSET_HISTORY_SMB_SERVER:-192.168.100.130}"
+SMB_SHARE="${FIXED_ASSET_HISTORY_SMB_SHARE:-设备履历记录}"
+SMB_SUBDIR="${FIXED_ASSET_HISTORY_SMB_SUBDIR:-履历}"
+SMB_DOMAIN="${FIXED_ASSET_HISTORY_SMB_DOMAIN:-WORKGROUP}"
+CREDENTIALS_FILE="${FIXED_ASSET_HISTORY_CREDENTIALS_FILE:-/etc/smbcredentials/hxops-fixed-asset-history}"
+MOUNT_UID="${FIXED_ASSET_HISTORY_MOUNT_UID:-1001}"
+MOUNT_GID="${FIXED_ASSET_HISTORY_MOUNT_GID:-1001}"
+CIFS_VERS="${FIXED_ASSET_HISTORY_CIFS_VERS:-3.0}"
+
+if [[ -n "${FIXED_ASSET_HISTORY_LOCAL_ROOT:-}" ]]; then
+ MOUNT_POINT="${FIXED_ASSET_HISTORY_LOCAL_ROOT}"
+elif [[ "${ENV_NAME}" == "test" ]]; then
+ MOUNT_POINT="/mnt/hxops-fixed-asset-history-test"
+else
+ MOUNT_POINT="/mnt/hxops-fixed-asset-history-prod"
+fi
+
+SHARE_MOUNT_POINT="${FIXED_ASSET_HISTORY_SHARE_MOUNT_POINT:-${MOUNT_POINT}-share}"
+
+# [STEP 1] 组装 CIFS 远端路径与挂载选项(不含 subdir,兼容旧内核)
+REMOTE="//${SMB_SERVER}/${SMB_SHARE}"
+CIFS_OPTS_BASE="credentials=${CREDENTIALS_FILE},iocharset=utf8,uid=${MOUNT_UID},gid=${MOUNT_GID},file_mode=0755,dir_mode=0755,ro"
+MOUNT_OPTS="${CIFS_OPTS_BASE},vers=${CIFS_VERS}"
+FSTAB_CIFS_LINE="${REMOTE} ${SHARE_MOUNT_POINT} cifs ${MOUNT_OPTS},nofail,_netdev 0 0"
+FSTAB_BIND_LINE="${SHARE_MOUNT_POINT}/${SMB_SUBDIR} ${MOUNT_POINT} none bind,nofail 0 0"
+
+ensure_packages() {
+ if ! command -v mount.cifs >/dev/null 2>&1; then
+ echo "[pkg] installing cifs-utils..."
+ apt-get update -y
+ apt-get install -y cifs-utils
+ fi
+ if ! command -v smbclient >/dev/null 2>&1; then
+ echo "[pkg] installing smbclient (optional probe)..."
+ apt-get install -y smbclient || true
+ fi
+}
+
+#
+# 确保凭据文件存在;优先复用已有文件,否则从环境变量写入。
+# 核心逻辑:绝不把密码写进仓库脚本;仅写入 chmod 600 的宿主机凭据文件。
+#
+ensure_credentials() {
+ mkdir -p "$(dirname "${CREDENTIALS_FILE}")"
+ if [[ -f "${CREDENTIALS_FILE}" ]]; then
+ chmod 600 "${CREDENTIALS_FILE}"
+ echo "[cred] using existing ${CREDENTIALS_FILE}"
+ return 0
+ fi
+
+ local username="${FIXED_ASSET_HISTORY_SHARE_USERNAME:-}"
+ local password="${FIXED_ASSET_HISTORY_SHARE_PASSWORD:-}"
+ if [[ -z "${username}" || -z "${password}" ]]; then
+ echo "[cred] missing ${CREDENTIALS_FILE}"
+ echo "Create it manually:"
+ echo " sudo mkdir -p /etc/smbcredentials"
+ echo " sudo tee ${CREDENTIALS_FILE} >/dev/null <<'EOF'"
+ echo "username=YOUR_USER"
+ echo "password=YOUR_PASSWORD"
+ echo "domain=${SMB_DOMAIN}"
+ echo "EOF"
+ echo " sudo chmod 600 ${CREDENTIALS_FILE}"
+ echo "Or export FIXED_ASSET_HISTORY_SHARE_USERNAME / FIXED_ASSET_HISTORY_SHARE_PASSWORD then re-run."
+ exit 1
+ fi
+
+ umask 077
+ cat >"${CREDENTIALS_FILE}" </dev/null; then
+ echo "[status] share_mounted=yes"
+ findmnt -n -o SOURCE,TARGET,FSTYPE,OPTIONS "${SHARE_MOUNT_POINT}" || true
+ else
+ echo "[status] share_mounted=no"
+ fi
+ if mountpoint -q "${MOUNT_POINT}" 2>/dev/null; then
+ echo "[status] local_root_mounted=yes"
+ findmnt -n -o SOURCE,TARGET,FSTYPE,OPTIONS "${MOUNT_POINT}" || true
+ echo "[status] sample entries:"
+ ls -la "${MOUNT_POINT}" | head -n 20
+ else
+ echo "[status] local_root_mounted=no"
+ if [[ -d "${MOUNT_POINT}" ]]; then
+ echo "[status] local_root directory exists but is not mounted"
+ else
+ echo "[status] local_root directory missing"
+ fi
+ fi
+}
+
+do_umount() {
+ if mountpoint -q "${MOUNT_POINT}" 2>/dev/null; then
+ umount "${MOUNT_POINT}"
+ echo "[umount] ${MOUNT_POINT}"
+ else
+ echo "[umount] ${MOUNT_POINT} is not mounted"
+ fi
+ if mountpoint -q "${SHARE_MOUNT_POINT}" 2>/dev/null; then
+ umount "${SHARE_MOUNT_POINT}"
+ echo "[umount] ${SHARE_MOUNT_POINT}"
+ else
+ echo "[umount] ${SHARE_MOUNT_POINT} is not mounted"
+ fi
+}
+
+#
+# 尝试多种 SMB 版本挂载共享根目录(避免单一 vers 导致 Invalid argument)。
+#
+mount_cifs_share_root() {
+ local vers candidate_opts
+ local versions=("${CIFS_VERS}" "3.0" "2.1" "2.0" "1.0")
+ local tried=()
+ local vers_item
+
+ for vers_item in "${versions[@]}"; do
+ local skip=0
+ local t
+ for t in "${tried[@]:-}"; do
+ if [[ "${t}" == "${vers_item}" ]]; then
+ skip=1
+ break
+ fi
+ done
+ [[ "${skip}" -eq 1 ]] && continue
+ tried+=("${vers_item}")
+
+ candidate_opts="${CIFS_OPTS_BASE},vers=${vers_item}"
+ echo "[mount] try cifs vers=${vers_item}: ${REMOTE} -> ${SHARE_MOUNT_POINT}"
+ if mount -t cifs "${REMOTE}" "${SHARE_MOUNT_POINT}" -o "${candidate_opts}"; then
+ MOUNT_OPTS="${candidate_opts}"
+ FSTAB_CIFS_LINE="${REMOTE} ${SHARE_MOUNT_POINT} cifs ${MOUNT_OPTS},nofail,_netdev 0 0"
+ echo "[mount] cifs ok with vers=${vers_item}"
+ return 0
+ fi
+ done
+ echo "[mount] all cifs version attempts failed; check: dmesg | tail -n 30"
+ return 1
+}
+
+#
+# 执行挂载:共享根目录 CIFS + 「履历」子目录 bind 到 LOCAL_ROOT。
+#
+do_mount() {
+ ensure_packages
+ ensure_credentials
+ mkdir -p "${SHARE_MOUNT_POINT}" "${MOUNT_POINT}"
+
+ if mountpoint -q "${MOUNT_POINT}" 2>/dev/null && mountpoint -q "${SHARE_MOUNT_POINT}" 2>/dev/null; then
+ echo "[mount] already mounted"
+ show_status
+ return 0
+ fi
+
+ # [STEP 2] 可选:用 smbclient 探测共享是否可达(失败不阻断,仅提示)
+ if command -v smbclient >/dev/null 2>&1; then
+ local user
+ user="$(awk -F= '/^username=/{print $2; exit}' "${CREDENTIALS_FILE}")"
+ echo "[probe] smbclient //${SMB_SERVER}/${SMB_SHARE} -U ${user} ..."
+ if ! smbclient "//${SMB_SERVER}/${SMB_SHARE}" -A "${CREDENTIALS_FILE}" -c "ls" >/tmp/hxops-asset-history-smb-probe.log 2>&1; then
+ echo "[probe] warning: smbclient probe failed; see /tmp/hxops-asset-history-smb-probe.log"
+ echo "[probe] continue to mount.cifs anyway"
+ else
+ echo "[probe] smbclient ok"
+ fi
+ fi
+
+ # [STEP 3] 挂载共享根(不使用 subdir=,避免 error 22)
+ if ! mountpoint -q "${SHARE_MOUNT_POINT}" 2>/dev/null; then
+ mount_cifs_share_root
+ else
+ echo "[mount] share root already mounted: ${SHARE_MOUNT_POINT}"
+ fi
+
+ local subdir_path="${SHARE_MOUNT_POINT}/${SMB_SUBDIR}"
+ if [[ ! -d "${subdir_path}" ]]; then
+ echo "[mount] subdir not found: ${subdir_path}"
+ echo "[mount] share root contents:"
+ ls -la "${SHARE_MOUNT_POINT}" | head -n 30
+ exit 1
+ fi
+
+ # [STEP 4] 把「履历」bind 到 FIXED_ASSET_HISTORY_LOCAL_ROOT
+ if ! mountpoint -q "${MOUNT_POINT}" 2>/dev/null; then
+ echo "[mount] bind ${subdir_path} -> ${MOUNT_POINT}"
+ mount --bind "${subdir_path}" "${MOUNT_POINT}"
+ else
+ echo "[mount] local_root already mounted: ${MOUNT_POINT}"
+ fi
+
+ show_status
+}
+
+#
+# 将 fstab 行幂等追加(CIFS 共享根 + bind 子目录),保证开机自动挂载。
+#
+ensure_fstab() {
+ touch /etc/fstab
+ if ! grep -Fqs "${SHARE_MOUNT_POINT}" /etc/fstab; then
+ echo "${FSTAB_CIFS_LINE}" >>/etc/fstab
+ echo "[fstab] appended cifs:"
+ echo " ${FSTAB_CIFS_LINE}"
+ else
+ echo "[fstab] cifs entry for ${SHARE_MOUNT_POINT} already exists"
+ fi
+ if ! grep -Fqs "${MOUNT_POINT}" /etc/fstab; then
+ echo "${FSTAB_BIND_LINE}" >>/etc/fstab
+ echo "[fstab] appended bind:"
+ echo " ${FSTAB_BIND_LINE}"
+ else
+ echo "[fstab] bind entry for ${MOUNT_POINT} already exists; review /etc/fstab if options changed"
+ fi
+ echo "[fstab] verify with: sudo mount -a && findmnt ${MOUNT_POINT}"
+}
+
+case "${ACTION}" in
+ status)
+ show_status
+ ;;
+ umount)
+ do_umount
+ ;;
+ mount)
+ do_mount
+ ;;
+ mount_fstab)
+ do_mount
+ ensure_fstab
+ ;;
+esac
+
+echo
+echo "Next: recreate backend so the bind mount is visible inside the container:"
+echo " docker compose --env-file .env.${ENV_NAME} up -d hxops-backend"
+echo " docker exec hxops-backend ls -la ${MOUNT_POINT}"
diff --git a/scripts/nginx.conf b/scripts/nginx.conf
index aeecc4ea..5f1feda7 100644
--- a/scripts/nginx.conf
+++ b/scripts/nginx.conf
@@ -23,6 +23,13 @@ server {
location /api/ {
# 转发到 Gunicorn (Gevent)
proxy_pass http://127.0.0.1:5000;
+
+ # 请求体上限(主要约束上传;库存 ZIP 下载靠下方超时)
+ # 按业务估算:几十个大 Excel 打包约 100–300MB,预留 200m;若单批更大可改 500m
+ client_max_body_size 200m;
+ # 大文件响应超时(库存 ZIP 下载关键项)
+ proxy_send_timeout 300s;
+ send_timeout 300s;
# 关键配置:关闭缓冲以支持 SSE 流式输出
proxy_buffering off;
diff --git a/scripts/rpa/README.md b/scripts/rpa/README.md
index 5103967c..39dd7888 100644
--- a/scripts/rpa/README.md
+++ b/scripts/rpa/README.md
@@ -26,6 +26,11 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
| `FREIGHT_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest |
| `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` |
| `FREIGHT_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel |
+| `FREIGHT_RPA_SHARED_SCOPE_ID` | 与后端 `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` 一致;Worker 在 **inventory_triggers** 目录写哨兵 `.hxops_rpa_shared_mount` |
+| `FREIGHT_RPA_ENVIRONMENT` | `test` / `prod`,须与后端 `ENV_NAME` 一致 |
+| `FREIGHT_RPA_HEARTBEAT_SECONDS` | 心跳间隔(默认 20s),test/prod 触发前检查依赖在线心跳 |
+
+Windows test/prod 部署脚本:`scripts/rpa/set_rpa_worker_env.ps1`(详见 `docs/features/shipping-notice/technical.md` §1.5.5a)。
## 开发环境 Mock
@@ -121,6 +126,14 @@ Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,DSV
库存源定义见 `backend/config/shipping_inventory_sources.yaml`(新增 Warehouse 只改 YAML)。
+### 本地 batch smoke(`dsv_export_batch_smoke.py`)
+
+联调 DSV 批量导出链路,不回调后端。默认语义:**链路跑完即通过**(全 skipped 无库存也退出码 0)。
+
+| 环境变量 | 默认值 | 用途 |
+|---------|--------|------|
+| `FREIGHT_RPA_SMOKE_REQUIRE_EXPORT` | `false` | 为 `true` 时要求至少真实导出一个 Excel;全 skipped 将退出码 2(CI 严格模式) |
+
页面控件如果默认可见文本无法稳定点击,可通过环境变量覆盖 selector:
| 环境变量 | 用途 |
diff --git a/scripts/rpa/dsv_export_batch_smoke.py b/scripts/rpa/dsv_export_batch_smoke.py
index 3d247a2a..2193df07 100644
--- a/scripts/rpa/dsv_export_batch_smoke.py
+++ b/scripts/rpa/dsv_export_batch_smoke.py
@@ -1,10 +1,15 @@
"""
scripts/rpa/dsv_export_batch_smoke.py
-用途:本地验证 DSV 360 同一浏览器 session 内连续导出 3 份库存 Excel。
+用途:本地验证 DSV 360 同一浏览器 session 内连续批量导出库存(smoke / 联调)。
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、shipping_inventory_sources.yaml、freight_rpa_worker。
逻辑:复用 worker 批量导出循环(一次登录 + reset 入口),不依赖 HXOPS callback。
+Smoke 语义(团队约定):
+ - 验证目标:**批量导出链路能跑完**(登录 → 导航 → 填参 → View Report → 导出/跳过判定)。
+ - **不保证**至少导出一个 Excel;全仓无库存(全 skipped)也算通过(退出码 0)。
+ - 若需“至少真实导出一个 Excel”,设置 FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true。
+
场景:
warehouse — 同一 source_code / 同一 3lv 报表,仅 Warehouse 参数变化
source_code — 三个不同 source_code(YAML 中独立配置项)
@@ -13,6 +18,10 @@ scripts/rpa/dsv_export_batch_smoke.py
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py warehouse
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py source_code
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py all
+
+退出码:
+ 0 — summary.status=success(含全 skipped;或至少一条 success)
+ 2 — 无结果、partial_failed、failed;或 REQUIRE_EXPORT=true 且无 success 导出
"""
from __future__ import annotations
@@ -134,18 +143,34 @@ def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]]
{
"source_code": code,
"warehouse_id": wh,
+ "status": "success",
"success": True,
"file_path": str(out_file),
"size_kb": round(size_kb, 1),
}
)
print(f"[batch-smoke] OK {code}/{wh} -> {out_file.name} ({size_kb:.1f} KB)")
+ except worker.NoInventoryDataError as exc:
+ results.append(
+ {
+ "source_code": code,
+ "warehouse_id": wh,
+ "status": "skipped",
+ "success": False,
+ "skipped": True,
+ "skip_reason": "no_inventory_data",
+ "message": str(exc),
+ }
+ )
+ print(f"[batch-smoke] SKIP {code}/{wh}: {exc}")
except Exception as exc:
results.append(
{
"source_code": code,
"warehouse_id": wh,
+ "status": "failed",
"success": False,
+ "error_code": "rpa_export_failed",
"error_message": str(exc),
}
)
@@ -161,14 +186,36 @@ def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]]
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
elapsed_s = int(time.monotonic() - started)
- ok = sum(1 for item in results if item.get("success"))
+ summary = worker._summarize_inventory_batch_results(results)
print(
- f"[batch-smoke] scenario={scenario} done success={ok}/{len(results)} "
+ f"[batch-smoke] scenario={scenario} done status={summary['status']} "
+ f"success={summary['success_count']} skipped={summary['skipped_count']} "
+ f"failed={summary['failed_count']}/{len(results)} "
f"elapsed={elapsed_s}s drop_dir={drop_dir}"
)
return results
+def _resolve_smoke_scenario_exit_code(
+ *,
+ results: list[dict[str, Any]],
+ summary: dict[str, Any],
+ require_export: bool,
+) -> int:
+ """
+ 根据 batch summary 与 FREIGHT_RPA_SMOKE_REQUIRE_EXPORT 计算 smoke 退出码。
+
+ 核心逻辑:默认 status=success 即 0(含全 skipped);require_export 且无 Excel 导出时返回 2。
+ """
+ if not results:
+ return 2
+ if summary.get("status") in {"failed", "partial_failed"}:
+ return 2
+ if require_export and not summary.get("has_success"):
+ return 2
+ return 0
+
+
def _run_scenario(worker: Any, scenario: str) -> int:
if scenario == "warehouse":
sources = _build_warehouse_scenario_sources()
@@ -187,9 +234,19 @@ def _run_scenario(worker: Any, scenario: str) -> int:
)
results = _run_batch_exports(worker, scenario, sources, drop_dir)
- if not results or not all(item.get("success") for item in results):
- return 2
- return 0
+ summary = worker._summarize_inventory_batch_results(results)
+ require_export = worker._env("FREIGHT_RPA_SMOKE_REQUIRE_EXPORT", "false").lower() == "true"
+ exit_code = _resolve_smoke_scenario_exit_code(
+ results=results,
+ summary=summary,
+ require_export=require_export,
+ )
+ if exit_code == 2 and require_export and not summary.get("has_success") and results:
+ print(
+ "[batch-smoke] FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 但未导出任何 Excel",
+ file=sys.stderr,
+ )
+ return exit_code
def main() -> int:
diff --git a/scripts/rpa/dsv_report_export.py b/scripts/rpa/dsv_report_export.py
index ecc80090..c7b75236 100644
--- a/scripts/rpa/dsv_report_export.py
+++ b/scripts/rpa/dsv_report_export.py
@@ -42,10 +42,20 @@ from dsv_session import (
goto_dsv_entry_url as _goto_dsv_entry_url,
has_dsv_portal_shell as _has_dsv_portal_shell,
is_dsv_home_ready as _is_dsv_home_ready,
+ is_dsv_in_report_navigation_context as _is_dsv_in_report_navigation_context,
maybe_auto_login_dsv as _maybe_auto_login_dsv,
wait_for_dsv_home_ready as _wait_for_dsv_home_ready,
)
+
+class NoInventoryDataError(RuntimeError):
+ """
+ DSV 报表结果区无库存明细行。
+
+ 核心逻辑:表示业务上「已查询但无库存」,供 worker 映射为 skipped 而非 failed。
+ """
+
+
def _click_dsv_export_excel(page: Any) -> None:
"""
触发 DSV SSRS ReportViewer 的 Excel 导出。
@@ -661,47 +671,167 @@ def _wait_dsv_report_ready(page: Any, *, timeout_ms: int) -> None:
_wait_for_dsv_report_result_ready(page, timeout_ms)
+_DSV_INVENTORY_DATA_ROWS_PROBE_JS = """
+() => {
+ const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
+
+ const PARAMETER_ROOT_SELECTORS = [
+ '#ReportViewerMain_ctl08',
+ '#ParameterTable_ReportViewerMain_ctl08',
+ '#ParametersGridReportViewerMain_ctl08',
+ '[id$="_divDropDown"]',
+ ].join(', ');
+
+ const REPORT_ROOT_SELECTORS = [
+ '#Report_table',
+ 'span#Report_table',
+ '#VisibleReportContentReportViewerMain_ctl13',
+ '#ReportViewerMain_ctl13_ReportArea',
+ '#ReportViewerMain_ctl13',
+ ].join(', ');
+
+ const isInsideParameterArea = (node) => {
+ if (!node || !node.closest) return false;
+ return !!node.closest(PARAMETER_ROOT_SELECTORS);
+ };
+
+ const directBodyRows = (table) => {
+ const tbodies = Array.from(table.tBodies || []);
+ const rows = [];
+ for (const tbody of tbodies) {
+ if (tbody.parentElement !== table) continue;
+ rows.push(...Array.from(tbody.children).filter((node) => node.tagName === 'TR'));
+ }
+ return rows;
+ };
+
+ const isHiddenRow = (row) => {
+ const heightAttr = String(row.getAttribute('height') || '').trim().toLowerCase();
+ if (heightAttr === '0' || heightAttr === '0px') return true;
+ try {
+ const style = window.getComputedStyle(row);
+ if (style.display === 'none' || style.visibility === 'hidden') return true;
+ if (row.offsetHeight === 0 && parseFloat(style.height || '0') === 0) return true;
+ } catch (_err) {
+ return false;
+ }
+ return false;
+ };
+
+ const isInventoryHeaderRow = (row) => {
+ const line = normalize(row.innerText || '');
+ return (
+ line.includes('Supplier ID') &&
+ line.includes('AWS Sku') &&
+ (line.includes('Qty Available') || /\\bQty\\b/.test(line))
+ );
+ };
+
+ const isReportMetadataRow = (row) => {
+ const line = normalize(row.innerText || '');
+ if (!line) return true;
+ if (/created\\s+.+(by|rsviewer)/i.test(line)) return true;
+ if (/rsviewer\\s+v\\d/i.test(line)) return true;
+ if (/^aws on hand inventory by location$/i.test(line)) return true;
+ return false;
+ };
+
+ const isWarehouseCodeOnly = (texts) => {
+ if (!texts.length) return true;
+ return texts.every((value) => /^BYAWS[A-Z0-9]+$/i.test(value));
+ };
+
+ const isInventoryDetailRow = (row) => {
+ if (isHiddenRow(row) || isInventoryHeaderRow(row) || isReportMetadataRow(row)) {
+ return false;
+ }
+ const cells = Array.from(row.querySelectorAll(':scope > td, :scope > th'));
+ if (!cells.length) return false;
+ const texts = cells.map((cell) => normalize(cell.innerText || '')).filter(Boolean);
+ if (!texts.length || isWarehouseCodeOnly(texts)) return false;
+
+ const hasAwsSku = texts.some((value) => /^B0[A-Z0-9]{8,}$/i.test(value));
+ const hasSupplierId = texts.some((value) => /^\\d{6,}$/.test(value.replace(/,/g, '')));
+ const hasQtyLike = texts.some((value) => /^-?\\d+(\\.\\d+)?$/.test(value.replace(/,/g, '')));
+ const hasMeaningfulSku = texts.some(
+ (value) =>
+ /^[A-Z0-9][A-Z0-9._-]{3,}$/i.test(value) &&
+ !/^(supplier|location|carton|pallet|uom|owner|putawayzone|warehouse)$/i.test(value) &&
+ !/^BYAWS[A-Z0-9]+$/i.test(value),
+ );
+
+ return hasAwsSku || (hasSupplierId && hasQtyLike) || (hasMeaningfulSku && hasQtyLike);
+ };
+
+ const tableHasInventoryDetailRows = (table) => {
+ if (isInsideParameterArea(table)) return false;
+ const text = normalize(table.innerText || '');
+ const isInventoryTable =
+ text.includes('Supplier ID') &&
+ text.includes('AWS Sku') &&
+ (text.includes('Qty Available') || /\\bQty\\b/.test(text));
+ if (!isInventoryTable) return false;
+
+ const rows = directBodyRows(table).filter((row) => !isHiddenRow(row));
+ const headerIdx = rows.findIndex(isInventoryHeaderRow);
+ if (headerIdx >= 0) {
+ return rows.slice(headerIdx + 1).some(isInventoryDetailRow);
+ }
+ return rows.some(isInventoryDetailRow);
+ };
+
+ const collectCandidateTables = () => {
+ const seen = new Set();
+ const tables = [];
+ const push = (table) => {
+ if (!table || seen.has(table) || isInsideParameterArea(table)) return;
+ seen.add(table);
+ tables.push(table);
+ };
+
+ document
+ .querySelectorAll('#Report_table table, span#Report_table > table')
+ .forEach(push);
+
+ if (tables.length > 0) return tables;
+
+ for (const root of document.querySelectorAll(REPORT_ROOT_SELECTORS)) {
+ if (isInsideParameterArea(root)) continue;
+ root.querySelectorAll('table').forEach((table) => {
+ if (isInsideParameterArea(table)) return;
+ const text = normalize(table.innerText || '');
+ if (
+ text.includes('Supplier ID') &&
+ text.includes('AWS Sku') &&
+ (text.includes('Qty Available') || /\\bQty\\b/.test(text))
+ ) {
+ push(table);
+ }
+ });
+ }
+ return tables;
+ };
+
+ return collectCandidateTables().some(tableHasInventoryDetailRows);
+}
+"""
+
+
def _dsv_report_has_inventory_data_rows(page: Any) -> bool:
"""
判断 DSV 库存报表结果页是否存在真实库存明细行。
- 核心逻辑:只检查包含库存表头的 SSRS 明细表,不统计整页 `tr`。
- 当前报表无数据时该表通常只有 3 行;有数据时第 4 行开始出现明细行。
+ 核心逻辑:仅扫描 SSRS 结果区(`#Report_table` / `#ReportViewerMain_ctl13`),
+ 排除参数区 `#ReportViewerMain_ctl08` 及其下拉表格;只统计目标 table 的直接
+ `tbody > tr`;忽略 `height=0`、列头行与 rsviewer 元数据行;明细行须含 AWS Sku
+ 或 Supplier ID + Qty 组合,避免 PutawayZone 的 BBU/DAMAGE 被误判为库存。
"""
selected = _find_dsv_report_result_frame(page)
if selected is None:
return False
_frame_index, frame, _state = selected
try:
- return bool(
- frame.evaluate(
- """
- () => {
- const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
- const tables = Array.from(document.querySelectorAll('table'));
- for (const table of tables) {
- const text = normalize(table.innerText);
- const isInventoryTable =
- text.includes('Supplier ID') &&
- text.includes('AWS Sku') &&
- text.includes('Qty Available');
- if (!isInventoryTable) continue;
-
- const rows = Array.from(table.querySelectorAll('tbody > tr'));
- if (rows.length <= 3) return false;
-
- const dataRows = rows.slice(3).filter((row) => {
- const cells = Array.from(row.querySelectorAll('td'));
- const line = normalize(cells.map((cell) => cell.innerText || '').join(' '));
- return line.length > 0;
- });
- return dataRows.length > 0;
- }
- return false;
- }
- """
- )
- )
+ return bool(frame.evaluate(_DSV_INVENTORY_DATA_ROWS_PROBE_JS))
except Exception as exc:
print(f"[dsv-report] inventory data row probe failed: {exc}", file=sys.stderr)
return False
@@ -878,29 +1008,51 @@ def _is_dsv_session_active(page: Any, entry_url: str) -> bool:
def _ensure_dsv_session(page: Any, entry_url: str) -> None:
- """DSV 360 一次登录并等待首页/Reports 导航就绪。"""
+ """
+ DSV 360 一次登录并等待首页/Reports 导航就绪。
+
+ 核心逻辑:登录后 home-not-ready 时,若 session 已在 entry 站点,回 entry 首页重试一次。
+ """
if _is_dsv_session_active(page, entry_url):
print("[dsv] session already active on entry site, skip login")
+ if _is_dsv_in_report_navigation_context(page):
+ print("[dsv] session active but still in report context, goto entry portal home")
+ _goto_dsv_entry_url(page, entry_url)
_wait_for_dsv_home_ready(page, timeout_ms=30_000)
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
return
+
_goto_dsv_entry_url(page, entry_url)
- _maybe_auto_login_dsv(page)
- _wait_for_dsv_home_ready(page, timeout_ms=60_000)
+ home_not_ready_after_login = False
+ try:
+ _maybe_auto_login_dsv(page)
+ except RuntimeError as exc:
+ if "home page was not ready" not in str(exc):
+ raise
+ home_not_ready_after_login = True
+ print("[dsv] home not ready after login, retry entry reset once", file=sys.stderr)
+
+ if home_not_ready_after_login:
+ if not _is_dsv_on_entry_site(page, entry_url):
+ raise RuntimeError("DSV home page was not ready after login")
+ _goto_dsv_entry_url(page, entry_url)
+
+ home_timeout_ms = 30_000 if home_not_ready_after_login else 60_000
+ _wait_for_dsv_home_ready(page, timeout_ms=home_timeout_ms)
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
def _reset_dsv_export_entry(page: Any, entry_url: str) -> None:
"""
批量导出中 navigation 变化时回到 portal 首页。
- 核心逻辑:同 entry_url 且 session 仍有效时不重复登录,仅回首页待命;
+ 核心逻辑:同 entry_url 且 session 仍有效时不重复登录,但始终 goto entry 离开报表 iframe;
同 navigation 连续导出请改用 _return_to_dsv_report_parameters。
"""
print("[dsv] reset export entry before next source")
if _is_dsv_session_active(page, entry_url):
print("[dsv] same entry_url session active, skip re-login")
- if not _is_dsv_home_ready(page):
- _goto_dsv_entry_url(page, entry_url)
+ print("[dsv] goto entry portal home for navigation change")
+ _goto_dsv_entry_url(page, entry_url)
_wait_for_dsv_home_ready(page, timeout_ms=30_000)
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
return
@@ -991,15 +1143,19 @@ def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
_click_dsv_reports_menu(page)
_wait_for_dsv_reports_open(page, timeout_ms=10_000)
+ program_group = str(query.get("program_group") or navigation.get("program_group") or "").strip()
+ program_label = str(query.get("program_label") or navigation.get("program_label") or "").strip()
+ report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
+
program_selector = _env("FREIGHT_RPA_DSV_PROGRAM_SELECTOR")
- program_label = str(query.get("program_label") or navigation.get("program_label") or "")
if program_selector:
page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
else:
- _click_dsv_menu_item(page, program_label, next_text=str(query.get("report_group") or navigation.get("report_group") or "Inventory"))
+ if program_group and program_group != program_label:
+ _click_dsv_menu_item(page, program_group, next_text=program_label)
+ _click_dsv_menu_item(page, program_label, next_text=report_group)
report_group_selector = _env("FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR")
- report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
if report_group_selector:
page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms())
else:
@@ -1025,7 +1181,7 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
pass
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
if not _dsv_report_has_inventory_data_rows(page):
- raise RuntimeError("DSV report has no inventory data")
+ raise NoInventoryDataError("DSV report has no inventory data")
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
_click_dsv_export_excel(page)
return download_info.value
diff --git a/scripts/rpa/dsv_session.py b/scripts/rpa/dsv_session.py
index 5ff26fce..27d1399c 100644
--- a/scripts/rpa/dsv_session.py
+++ b/scripts/rpa/dsv_session.py
@@ -62,6 +62,38 @@ def _has_dsv_report_nav_usable(page: Any) -> bool:
pass
return _has_dsv_report_nav_attached(page)
+def _is_dsv_in_report_navigation_context(page: Any) -> bool:
+ """
+ 判断当前是否仍处于报表 iframe / SSRS 上下文,而非 portal 首页。
+
+ 核心逻辑:报表 frame URL 与 portal 首页一样会渲染 Home/Favorites 侧栏与 Reports 顶栏;
+ 仅探测 Reports 导航不足以区分,必须结合顶层 URL 与 report-frame 是否仍挂载。
+ """
+ try:
+ current_url = str(page.url or "").lower()
+ except Exception:
+ current_url = ""
+ if "/main/portal/frame/reports/" in current_url:
+ return True
+ if "/s360reports/" in current_url:
+ return True
+ for frame in getattr(page, "frames", []):
+ try:
+ frame_url = str(frame.url or "").lower()
+ except Exception:
+ frame_url = ""
+ if "/s360reports/reports/default.aspx" in frame_url:
+ return True
+ if "/s360reports/ssrs/" in frame_url:
+ return True
+ try:
+ if frame.locator("#ReportViewerMain").count() > 0:
+ return True
+ except Exception:
+ continue
+ return False
+
+
def _is_dsv_on_portal_home(page: Any) -> bool:
"""URL 已在 portal 且主页面已出现 Home/Favorites/Recent Reports 等内容。"""
try:
@@ -72,6 +104,8 @@ def _is_dsv_on_portal_home(page: Any) -> bool:
return False
if "s360.dbschenker.com" not in current_url:
return False
+ if _is_dsv_in_report_navigation_context(page):
+ return False
try:
body = str(page.locator("body").inner_text(timeout=1_000) or "").lower()
except Exception:
@@ -219,11 +253,13 @@ def _is_dsv_home_ready(page: Any) -> bool:
"""
判断 DSV 是否已经稳定进入首页导航态。
- 核心逻辑:必须离开认证域名,且 Reports 导航已可用(跨 frame 探测);
- 用户肉眼已在 portal 首页时,不再仅依赖顶层 #report-mega-legacy 计数。
+ 核心逻辑:必须离开认证域名与报表 iframe 上下文,且 Reports 导航已可用;
+ 停留在 `/main/portal/frame/reports/` 时即使顶栏可见,也不应视为 home-ready。
"""
if "auth.dbschenker.com" in page.url:
return False
+ if _is_dsv_in_report_navigation_context(page):
+ return False
return _has_dsv_report_nav_usable(page)
def _wait_for_dsv_home_ready(
@@ -235,8 +271,8 @@ def _wait_for_dsv_home_ready(
"""
等待 DSV 首页真正稳定可操作。
- 核心逻辑:登录和升级提示都可能导致页面短暂回跳;这里统一要求首页导航稳定出现,
- 失败则直接在“首页阶段”报错,避免主流程跳步到 Reports/View Report。
+ 核心逻辑:登录和升级提示都可能导致页面短暂回跳;这里统一要求首页导航稳定出现。
+ app wait 超时但 portal 壳层已可见时,追加 grace wait;仍失败则在首页阶段报错。
"""
import dsv_auth
@@ -281,6 +317,20 @@ def _wait_for_dsv_home_ready(
)
# #endregion
return
+ if _wait_for_dsv_report_nav_grace(
+ page,
+ timeout_ms=30_000,
+ on_portal_shell_seen=on_portal_shell_seen,
+ ):
+ # #region debug-point A:home-ready-after-grace
+ _report_debug_event(
+ "A",
+ "freight_rpa_worker.py:_wait_for_dsv_home_ready:ready_after_grace",
+ "[DEBUG] dsv home became ready during portal grace wait",
+ {"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
+ )
+ # #endregion
+ return
_debug_dsv_stage(page, "home-not-ready", target_text="Reports")
# #region debug-point A:home-not-ready
_report_debug_event(
@@ -292,6 +342,44 @@ def _wait_for_dsv_home_ready(
# #endregion
raise RuntimeError("DSV home page was not ready after login")
+
+def _wait_for_dsv_report_nav_grace(
+ page: Any,
+ *,
+ timeout_ms: int = 30_000,
+ on_portal_shell_seen: Callable[[], None] | None = None,
+) -> bool:
+ """
+ Portal 首屏已出现但 Reports 导航尚未 visible 时的额外等待。
+
+ 核心逻辑:SSO/合规页较慢时,portal 壳层(Home/Favorites)常先于顶栏 Reports 可点击;
+ 在判定 home-not-ready 前给导航一次 grace 窗口,降低首条 batch 误失败概率。
+
+ Returns:
+ bool: grace 窗口内首页变为 ready 则 True,否则 False。
+ """
+ import dsv_auth
+
+ if not _is_dsv_on_portal_home(page):
+ return False
+ print(
+ "[dsv-home] portal shell visible, grace wait for Reports nav "
+ f"timeoutMs={timeout_ms} report_nav_attached={_has_dsv_report_nav_attached(page)} "
+ f"url={page.url!r}"
+ )
+ deadline = time.monotonic() + (timeout_ms / 1000)
+ while time.monotonic() < deadline:
+ if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
+ dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
+ if _is_dsv_home_ready(page):
+ if on_portal_shell_seen is not None:
+ on_portal_shell_seen()
+ _debug_dsv_stage(page, "home-ready-after-grace", target_text="Reports")
+ return True
+ time.sleep(0.5)
+ return False
+
+
def _goto_dsv_entry_url(page: Any, entry_url: str) -> None:
"""
打开 DSV entry_url;domcontentloaded 超时时若已跳转到 auth/portal 则继续。
@@ -324,10 +412,12 @@ has_dsv_portal_shell = _has_dsv_portal_shell
has_dsv_report_nav_attached = _has_dsv_report_nav_attached
has_dsv_report_nav_usable = _has_dsv_report_nav_usable
is_dsv_home_ready = _is_dsv_home_ready
+is_dsv_in_report_navigation_context = _is_dsv_in_report_navigation_context
is_dsv_on_portal_home = _is_dsv_on_portal_home
iter_dsv_report_nav_locators = _iter_dsv_report_nav_locators
wait_for_dsv_app_after_login = _wait_for_dsv_app_after_login
wait_for_dsv_home_ready = _wait_for_dsv_home_ready
+wait_for_dsv_report_nav_grace = _wait_for_dsv_report_nav_grace
# 向后兼容:登录 API 仍可从 dsv_session 引用
from dsv_auth import ( # noqa: E402
diff --git a/scripts/rpa/freight_rpa_heartbeat.py b/scripts/rpa/freight_rpa_heartbeat.py
new file mode 100644
index 00000000..ac5a062b
--- /dev/null
+++ b/scripts/rpa/freight_rpa_heartbeat.py
@@ -0,0 +1,201 @@
+"""
+scripts/rpa/freight_rpa_heartbeat.py
+
+用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
+依赖:rpa_common.env、urllib、socket。
+逻辑:由 freight_rpa_worker 主循环按 FREIGHT_RPA_HEARTBEAT_SECONDS 周期调用;同步写入共享目录哨兵文件。
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import socket
+import sys
+import time
+import urllib.error
+import urllib.request
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from rpa_common import env as _env
+
+_RUNTIME_STATUS = "idle"
+_LAST_HEARTBEAT_MONO = 0.0
+_DEFAULT_SENTINEL_NAME = ".hxops_rpa_shared_mount"
+
+
+def set_worker_runtime_status(status: str) -> None:
+ """更新 worker 运行态(idle / busy),供心跳上报。"""
+ global _RUNTIME_STATUS
+ normalized = str(status or "idle").strip().lower()
+ _RUNTIME_STATUS = normalized if normalized in {"idle", "busy"} else "idle"
+
+
+def get_worker_runtime_status() -> str:
+ return _RUNTIME_STATUS
+
+
+def _resolve_worker_environment() -> str:
+ raw = (
+ _env("FREIGHT_RPA_ENVIRONMENT")
+ or _env("ENV_NAME")
+ or _env("HXOPS_ENV")
+ or "dev"
+ )
+ value = str(raw or "dev").strip().lower()
+ if value in {"development", ""}:
+ return "dev"
+ if value in {"testing"}:
+ return "test"
+ if value in {"production"}:
+ return "prod"
+ return value
+
+
+def _resolve_shared_scope_id() -> str:
+ raw = (
+ _env("FREIGHT_RPA_SHARED_SCOPE_ID")
+ or _env("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID")
+ or ""
+ )
+ value = str(raw or "").strip()
+ if value:
+ return value
+ trigger = str(_env("FREIGHT_RPA_INVENTORY_TRIGGER_DIR") or "").replace("\\", "/").lower()
+ for token in ("hxops-rpa-test-data", "hxops-rpa-prod-data"):
+ if token in trigger:
+ return token
+ return ""
+
+
+def _resolve_sentinel_name() -> str:
+ return str(
+ _env("FREIGHT_RPA_SHARED_SENTINEL_NAME")
+ or _env("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME")
+ or _DEFAULT_SENTINEL_NAME
+ ).strip() or _DEFAULT_SENTINEL_NAME
+
+
+def _resolve_worker_id(hostname: str) -> str:
+ explicit = str(_env("FREIGHT_RPA_WORKER_ID") or "").strip()
+ if explicit:
+ return explicit
+ pid = os.getpid()
+ return f"{hostname}-{pid}"
+
+
+def write_shared_mount_sentinel(*, trigger_dir: str | Path, hostname: str | None = None) -> None:
+ """
+ 在 trigger 共享目录写入哨兵文件,供 Ubuntu 后端校验 CIFS 挂载与 scope 一致。
+ 核心逻辑:不创建 trigger 根目录,仅更新已存在目录下的哨兵文件。
+ """
+ scope_id = _resolve_shared_scope_id()
+ if not scope_id:
+ return
+ root = Path(trigger_dir)
+ if not root.is_dir():
+ return
+ host = hostname or socket.gethostname()
+ body = "\n".join([
+ f"scope_id={scope_id}",
+ f"updated_at={datetime.now(UTC).replace(tzinfo=None).isoformat()}",
+ f"host={host}",
+ f"worker_id={_resolve_worker_id(host)}",
+ ])
+ sentinel_path = root / _resolve_sentinel_name()
+ sentinel_path.write_text(body + "\n", encoding="utf-8")
+
+
+def build_heartbeat_payload(
+ *,
+ trigger_dir: str | Path,
+ drop_dir: str | Path,
+ status: str | None = None,
+) -> dict[str, Any]:
+ """
+ 组装心跳 payload。
+ 核心逻辑:capabilities 固定包含 inventory_export;shared_scope_id 用于跨平台路径对齐。
+ """
+ hostname = socket.gethostname()
+ return {
+ "worker_id": _resolve_worker_id(hostname),
+ "hostname": hostname,
+ "environment": _resolve_worker_environment(),
+ "capabilities": ["inventory_export"],
+ "status": status or get_worker_runtime_status(),
+ "trigger_dir": str(trigger_dir),
+ "drop_dir": str(drop_dir),
+ "shared_scope_id": _resolve_shared_scope_id(),
+ "version": str(_env("FREIGHT_RPA_WORKER_VERSION", "rpa-poc") or "rpa-poc"),
+ "timestamp": datetime.now(UTC).replace(tzinfo=None).isoformat(),
+ }
+
+
+def post_heartbeat(payload: dict[str, Any]) -> bool:
+ """
+ 向后端上报心跳。
+ Returns:
+ bool: HTTP 2xx 时 True,否则 False(不中断 worker 主循环)。
+ """
+ base = str(_env("HXOPS_API_BASE", "http://127.0.0.1:5052") or "http://127.0.0.1:5052").rstrip("/")
+ key = (
+ _env("SHIPPING_NOTICE_TOOL_API_KEY")
+ or _env("INTEGRATION_API_KEY")
+ or _env("HXOPS_TOOLS_API_KEY")
+ )
+ if not key:
+ print("[heartbeat] skipped: missing SHIPPING_NOTICE_TOOL_API_KEY", file=sys.stderr)
+ return False
+
+ url = f"{base}/api/shipping-notice/rpa/heartbeat"
+ data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+ req = urllib.request.Request(
+ url,
+ data=data,
+ headers={
+ "Content-Type": "application/json",
+ "X-Integration-Key": key,
+ "X-Shipping-Tool-Key": key,
+ },
+ method="POST",
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=8) as resp:
+ return 200 <= int(resp.status) < 300
+ except urllib.error.HTTPError as exc:
+ body = ""
+ try:
+ body = exc.read().decode("utf-8", errors="replace")[:500]
+ except Exception:
+ body = ""
+ print(f"[heartbeat] HTTP {exc.code} {body}", file=sys.stderr)
+ return False
+ except Exception as exc:
+ print(f"[heartbeat] failed: {exc}", file=sys.stderr)
+ return False
+
+
+def maybe_send_heartbeat(
+ *,
+ trigger_dir: str | Path,
+ drop_dir: str | Path,
+ last_sent_mono: float,
+ force: bool = False,
+) -> float:
+ """
+ 按 FREIGHT_RPA_HEARTBEAT_SECONDS 节流发送心跳。
+ Returns:
+ float: 最近一次尝试后的 monotonic 时间戳(成功或失败均更新节流时钟)。
+ """
+ global _LAST_HEARTBEAT_MONO
+ interval = max(15, int(_env("FREIGHT_RPA_HEARTBEAT_SECONDS", "20") or "20"))
+ now = time.monotonic()
+ if not force and last_sent_mono and (now - last_sent_mono) < interval:
+ return last_sent_mono
+ write_shared_mount_sentinel(trigger_dir=trigger_dir)
+ payload = build_heartbeat_payload(trigger_dir=trigger_dir, drop_dir=drop_dir)
+ post_heartbeat(payload)
+ _LAST_HEARTBEAT_MONO = now
+ return now
diff --git a/scripts/rpa/freight_rpa_worker.py b/scripts/rpa/freight_rpa_worker.py
index d0fdd93c..c4473612 100644
--- a/scripts/rpa/freight_rpa_worker.py
+++ b/scripts/rpa/freight_rpa_worker.py
@@ -39,7 +39,7 @@ import tempfile
import time
import urllib.error
import urllib.request
-from datetime import datetime
+from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Callable, TextIO
@@ -59,7 +59,9 @@ import dsv_debug # noqa: E402
import dsv_driver # noqa: E402
import dsv_navigation # noqa: E402
import dsv_report_export # noqa: E402
+from dsv_report_export import NoInventoryDataError # noqa: E402
import dsv_session # noqa: E402
+import freight_rpa_heartbeat # noqa: E402
# 测试与 smoke 向后兼容 re-export
_maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv
@@ -126,26 +128,55 @@ def _env(name: str, default: str = "") -> str:
return value
+def _log_line_timestamp() -> str:
+ """
+ 生成 worker 日志行首时间戳(本地时区)。
+
+ 核心逻辑:RPA 批量导出常跨 1+ 小时,行级时间便于对照 DSV 页面卡顿与超时点。
+
+ Returns:
+ str: `YYYY-MM-DD HH:MM:SS` 格式字符串。
+ """
+ return datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S")
+
+
class _TeeStream:
"""
同时写入控制台与日志文件的轻量 stream。
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
- 文件 flush 采用行级同步,RPA 异常退出时尽量保留最后几行排障信息。
+ 每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量
+ 保留最后几行排障信息。
"""
def __init__(self, console: TextIO, log_file: TextIO) -> None:
self._console = console
self._log_file = log_file
+ self._pending = ""
self.encoding = getattr(console, "encoding", "utf-8")
+ def _emit_line(self, line: str, *, newline: bool) -> None:
+ """将单行(可含时间戳前缀)写入控制台与日志文件。"""
+ if line:
+ stamped = f"{_log_line_timestamp()} {line}"
+ self._console.write(stamped)
+ self._log_file.write(stamped)
+ if newline:
+ self._console.write("\n")
+ self._log_file.write("\n")
+
def write(self, text: str) -> int:
- self._console.write(text)
- written = self._log_file.write(text)
+ self._pending += text
+ while "\n" in self._pending:
+ line, self._pending = self._pending.split("\n", 1)
+ self._emit_line(line, newline=True)
self.flush()
- return written
+ return len(text)
def flush(self) -> None:
+ if self._pending:
+ self._emit_line(self._pending, newline=False)
+ self._pending = ""
self._console.flush()
self._log_file.flush()
@@ -158,7 +189,8 @@ def _configure_file_logging() -> Path | None:
按 FREIGHT_RPA_LOG_FILE 启用 worker 文件日志。
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
- 让所有 print/stdout/stderr 同时落盘,便于排查登录、下载、回调失败。
+ 让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
+ 登录、下载、回调失败与长批次耗时。
Returns:
Path | None: 已启用的日志路径;未配置时返回 None。
@@ -323,7 +355,28 @@ def _browser_profile_root() -> Path:
return _resolve_backend_relative_path(profile, default=default)
+def _mask_secret(value: str) -> str:
+ """
+ 对 API Key 等敏感字符串做首尾保留脱敏,供 callback 请求日志打印。
+
+ Args:
+ value: 原始密钥字符串。
+
+ Returns:
+ str: 长度 ≤8 时返回 `***`;否则保留前 4 与后 4 字符。
+ """
+ value = str(value or "")
+ if len(value) <= 8:
+ return "***"
+ return f"{value[:4]}...{value[-4:]}"
+
+
def _post_callback(path: str, payload: dict) -> None:
+ """
+ 向 HXOPS 货代 Tool API 发送 JSON 回调。
+
+ 核心逻辑:组装 URL 与双 Header 密钥 → 打印脱敏请求日志 → POST;HTTP 错误时打印响应体摘要。
+ """
base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
key = (
_env("SHIPPING_NOTICE_TOOL_API_KEY")
@@ -342,6 +395,14 @@ def _post_callback(path: str, payload: dict) -> None:
url = f"{base}{path}"
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+ print(
+ "[callback-request] "
+ f"POST {url} "
+ f"headers={{'Content-Type': 'application/json', "
+ f"'X-Integration-Key': '{_mask_secret(key)}', "
+ f"'X-Shipping-Tool-Key': '{_mask_secret(key)}'}} "
+ f"payload={data.decode('utf-8', errors='replace')[:4000]}"
+ )
req = urllib.request.Request(
url,
data=data,
@@ -358,6 +419,11 @@ def _post_callback(path: str, payload: dict) -> None:
print(f"[callback] {path} -> {resp.status} {body[:200]}")
except urllib.error.HTTPError as exc:
err = exc.read().decode("utf-8", errors="replace")
+ print(
+ "[callback-response] "
+ f"POST {url} -> HTTP {exc.code} {err[:1000]}",
+ file=sys.stderr,
+ )
raise RuntimeError(f"callback {path} HTTP {exc.code}: {err[:300]}") from exc
@@ -718,6 +784,67 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
+def _normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
+ """
+ batch 明细状态归一化(比单任务更严格:缺省字段不算 success)。
+
+ 核心逻辑:worker 自生成 results 均带 status/success;空 dict 或缺字段归为 failed,
+ 避免 batch summary 误计成功。
+ """
+ raw_status = str(item.get("status") or "").strip().lower()
+ if raw_status in {"success", "skipped", "failed"}:
+ return raw_status
+ if item.get("skipped"):
+ return "skipped"
+ if item.get("success") is True:
+ return "success"
+ return "failed"
+
+
+def _summarize_inventory_batch_results(results: list[dict[str, Any]]) -> dict[str, Any]:
+ """
+ 汇总 batch 回调顶层状态。
+
+ 核心逻辑:
+ - status:新监控用,区分 success / partial_failed / failed;
+ - success(legacy):与旧 any(item.success) 兼容,有 success 或 skipped 即为 true;
+ - has_success:是否至少有一条实际导出成功。
+ """
+ zero = {
+ "status": "failed",
+ "success": False,
+ "has_success": False,
+ "success_count": 0,
+ "skipped_count": 0,
+ "failed_count": 0,
+ }
+ statuses = [
+ _normalize_inventory_batch_item_status(item)
+ for item in results
+ if isinstance(item, dict)
+ ]
+ if not statuses:
+ return dict(zero)
+
+ success_count = sum(1 for status in statuses if status == "success")
+ skipped_count = sum(1 for status in statuses if status == "skipped")
+ failed_count = sum(1 for status in statuses if status == "failed")
+ if failed_count == 0:
+ top_status = "success"
+ elif success_count == 0 and skipped_count == 0:
+ top_status = "failed"
+ else:
+ top_status = "partial_failed"
+ return {
+ "status": top_status,
+ "success": (success_count + skipped_count) > 0,
+ "has_success": success_count > 0,
+ "success_count": success_count,
+ "skipped_count": skipped_count,
+ "failed_count": failed_count,
+ }
+
+
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
run_no = str(body.get("run_no") or trigger_path.stem).strip()
@@ -742,6 +869,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
"source_code": source.get("source_code"),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
+ "status": "success",
"success": True,
"file_path": str(out_file),
"task_no": task_no or None,
@@ -769,7 +897,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
"source_code": source.get("source_code"),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
+ "status": "failed",
"success": False,
+ "error_code": "unsupported_source_type",
"error_message": f"unsupported source_type: {site}",
})
continue
@@ -799,17 +929,32 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
"source_code": code,
"site_id": source.get("site_id"),
"warehouse_id": wh,
+ "status": "success",
"success": True,
"file_path": str(out_file),
"task_no": task_no or None,
})
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
+ except NoInventoryDataError as exc:
+ results.append({
+ "source_code": code,
+ "site_id": source.get("site_id"),
+ "warehouse_id": wh,
+ "status": "skipped",
+ "success": False,
+ "skipped": True,
+ "skip_reason": "no_inventory_data",
+ "message": str(exc),
+ })
+ print(f"[inventory-batch] {site} export skipped {code}/{wh}: {exc}")
except Exception as exc:
results.append({
"source_code": code,
"site_id": source.get("site_id"),
"warehouse_id": wh,
+ "status": "failed",
"success": False,
+ "error_code": "rpa_export_failed",
"error_message": str(exc),
})
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
@@ -822,16 +967,28 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
try:
+ batch_summary = _summarize_inventory_batch_results(results)
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
"run_no": run_no,
- "success": any(item.get("success") for item in results),
+ "status": batch_summary["status"],
+ "success": batch_summary["success"],
+ "has_success": batch_summary["has_success"],
+ "success_count": batch_summary["success_count"],
+ "skipped_count": batch_summary["skipped_count"],
+ "failed_count": batch_summary["failed_count"],
"rpa_mode": mode,
"trigger_type": body.get("trigger_type"),
"schedule_run_id": body.get("schedule_run_id"),
"results": results,
})
_move_trigger(trigger_path, processed_dir, "processed")
- print(f"[inventory-batch] callback done run={run_no} success={sum(1 for r in results if r.get('success'))}/{len(results)}")
+ print(
+ f"[inventory-batch] callback done run={run_no} "
+ f"status={batch_summary['status']} "
+ f"success={batch_summary['success_count']} "
+ f"skipped={batch_summary['skipped_count']} "
+ f"failed={batch_summary['failed_count']}/{len(results)}"
+ )
except Exception as callback_exc:
_report_callback_failure(trigger_path, failed_dir, callback_exc)
@@ -855,6 +1012,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir)
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
+ "status": "success",
"success": True,
"file_path": str(out_file),
"rpa_mode": mode,
@@ -862,11 +1020,34 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
})
_move_trigger(trigger_path, processed_dir, "processed")
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
+ except NoInventoryDataError as exc:
+ try:
+ _post_callback("/api/shipping-notice/rpa/inventory-ready", {
+ "task_no": task_no,
+ "status": "skipped",
+ "success": False,
+ "skipped": True,
+ "skip_reason": "no_inventory_data",
+ "message": str(exc),
+ "rpa_mode": mode,
+ "source_code": (
+ (body.get("rpa_inventory_source") or {}).get("source_code")
+ if isinstance(body.get("rpa_inventory_source"), dict)
+ else None
+ ),
+ })
+ if trigger_path.exists():
+ trigger_path.unlink(missing_ok=True)
+ print(f"[inventory] {mode} export skipped for {task_no}: {exc}")
+ except Exception as callback_exc:
+ _report_callback_failure(trigger_path, failed_dir, callback_exc)
except Exception as exc:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
+ "status": "failed",
"success": False,
+ "skipped": False,
"rpa_mode": mode,
"error_message": str(exc),
})
@@ -921,10 +1102,13 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
for path in sorted(trigger_dir.glob("*.json")):
if not path.is_file():
continue
+ freight_rpa_heartbeat.set_worker_runtime_status("busy")
try:
handler(path, *extra_args)
except Exception as exc:
print(f"[error] {path.name}: {exc}", file=sys.stderr)
+ finally:
+ freight_rpa_heartbeat.set_worker_runtime_status("idle")
def main() -> None:
@@ -945,7 +1129,20 @@ def main() -> None:
print(f" drop={drop_dir}")
print(f" queue={upload_queue_dir}")
+ last_heartbeat_mono = 0.0
+ last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
+ trigger_dir=inv_trigger_dir,
+ drop_dir=drop_dir,
+ last_sent_mono=last_heartbeat_mono,
+ force=True,
+ )
+
while True:
+ last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
+ trigger_dir=inv_trigger_dir,
+ drop_dir=drop_dir,
+ last_sent_mono=last_heartbeat_mono,
+ )
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
time.sleep(poll)
diff --git a/scripts/rpa/set_rpa_worker_env.ps1 b/scripts/rpa/set_rpa_worker_env.ps1
new file mode 100644
index 00000000..1fa37064
--- /dev/null
+++ b/scripts/rpa/set_rpa_worker_env.ps1
@@ -0,0 +1,123 @@
+<#
+.SYNOPSIS
+ 为货代库存 RPA Worker 写入 Windows 用户级永久环境变量(含共享 scope 与心跳)。
+
+.DESCRIPTION
+ test/prod 部署时必须配置 FREIGHT_RPA_SHARED_SCOPE_ID,与 Ubuntu 后端
+ SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID 一致,否则 Worker 不会写哨兵文件,
+ 后端就绪检查将报 shared_sentinel_missing。
+
+ 用法(以管理员或 RPA 专用账号登录后执行一次):
+ .\scripts\rpa\set_rpa_worker_env.ps1 -Environment test -ApiBase "http://192.168.1.20:8890" -ToolApiKey "<密钥>"
+ .\scripts\rpa\set_rpa_worker_env.ps1 -Environment prod -ApiBase "http://生产地址:端口" -ToolApiKey "<密钥>"
+
+ 执行后请关闭并重新打开 PowerShell,再运行 freight_rpa_worker.py。
+ 完整说明见 docs/features/shipping-notice/technical.md §1.5.5a / §1.5.10。
+#>
+param(
+ [Parameter(Mandatory = $true)]
+ [ValidateSet("test", "prod")]
+ [string]$Environment,
+
+ [Parameter(Mandatory = $true)]
+ [string]$ApiBase,
+
+ [Parameter(Mandatory = $true)]
+ [string]$ToolApiKey,
+
+ [string]$DsvUsername = "",
+ [string]$DsvPassword = "",
+ [string]$CraneUsername = "",
+ [string]$CranePassword = ""
+)
+
+$ErrorActionPreference = "Stop"
+
+if ($Environment -eq "test") {
+ $Root = "C:\HxopsRpaTest"
+ $ScopeId = "hxops-rpa-test-data"
+} else {
+ $Root = "C:\HxopsRpaProd"
+ $ScopeId = "hxops-rpa-prod-data"
+}
+
+$DataRoot = Join-Path $Root "data"
+$Vars = [ordered]@{
+ "HXOPS_API_BASE" = $ApiBase
+ "SHIPPING_NOTICE_TOOL_API_KEY" = $ToolApiKey
+ "FREIGHT_RPA_ENVIRONMENT" = $Environment
+ "FREIGHT_RPA_SHARED_SCOPE_ID" = $ScopeId
+ "FREIGHT_RPA_HEARTBEAT_SECONDS" = "20"
+ "FREIGHT_RPA_MOCK" = "false"
+ "FREIGHT_RPA_HEADLESS" = "false"
+ "FREIGHT_RPA_BROWSER_CHANNEL" = "msedge"
+ "FREIGHT_RPA_POLL_SECONDS" = "3"
+ "FREIGHT_RPA_INVENTORY_TRIGGER_DIR" = Join-Path $DataRoot "inventory_triggers"
+ "FREIGHT_INVENTORY_DROP_DIR" = Join-Path $DataRoot "inventory_drop"
+ "FREIGHT_RPA_UPLOAD_TRIGGER_DIR" = Join-Path $DataRoot "upload_triggers"
+ "FREIGHT_UPLOAD_QUEUE_DIR" = Join-Path $DataRoot "upload_queue"
+ "FREIGHT_RPA_BROWSER_PROFILE_DIR" = Join-Path $DataRoot "browser_profile"
+ "FREIGHT_RPA_LOG_FILE" = Join-Path $DataRoot "logs\worker.log"
+ "FREIGHT_RPA_LOG_MAX_BYTES" = "10485760"
+ "FREIGHT_RPA_LOG_BACKUP_COUNT" = "5"
+}
+
+if ($DsvUsername) { $Vars["FREIGHT_RPA_DSV_USERNAME"] = $DsvUsername }
+if ($DsvPassword) { $Vars["FREIGHT_RPA_DSV_PASSWORD"] = $DsvPassword }
+if ($CraneUsername) { $Vars["FREIGHT_RPA_CRANE_USERNAME"] = $CraneUsername }
+if ($CranePassword) { $Vars["FREIGHT_RPA_CRANE_PASSWORD"] = $CranePassword }
+
+$SensitiveKeys = @(
+ "SHIPPING_NOTICE_TOOL_API_KEY",
+ "FREIGHT_RPA_DSV_PASSWORD",
+ "FREIGHT_RPA_CRANE_PASSWORD"
+)
+
+$UsernameKeys = @(
+ "FREIGHT_RPA_DSV_USERNAME",
+ "FREIGHT_RPA_CRANE_USERNAME"
+)
+
+function Get-MaskedUsername {
+ param([string]$Value)
+ if (-not $Value) { return $Value }
+ if ($Value -match '^([^@]+)@(.+)$') {
+ $local = $Matches[1]
+ $domain = $Matches[2]
+ if ($local.Length -le 3) {
+ return "***@$domain"
+ }
+ return ($local.Substring(0, 3) + "***@" + $domain)
+ }
+ if ($Value.Length -le 3) {
+ return "***"
+ }
+ return ($Value.Substring(0, 3) + "***")
+}
+
+function Get-DisplayValue {
+ param(
+ [string]$Key,
+ [string]$Value
+ )
+ if ($SensitiveKeys -contains $Key -and $Value) {
+ return "******"
+ }
+ if ($UsernameKeys -contains $Key -and $Value) {
+ return Get-MaskedUsername -Value $Value
+ }
+ return $Value
+}
+
+foreach ($entry in $Vars.GetEnumerator()) {
+ [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, "User")
+ $display = Get-DisplayValue -Key $entry.Key -Value ([string]$entry.Value)
+ Write-Host ("[ok] {0}={1}" -f $entry.Key, $display)
+}
+
+Write-Host ""
+Write-Host "Environment=$Environment scope_id=$ScopeId root=$Root"
+Write-Host "请关闭并重新打开 PowerShell,然后验证:"
+Write-Host " echo `$env:FREIGHT_RPA_SHARED_SCOPE_ID"
+Write-Host " cd $Root"
+Write-Host " python scripts\rpa\freight_rpa_worker.py"
|