refactor(chat/shipping): 重构发货通知模块为统一UI State驱动模式

- 重构发货通知的状态与动作获取逻辑:移除从聊天文本解析HXOPS_SHIPPING_ACTIONS注释的旧逻辑,改为统一从后端shipping_ui_state获取任务状态、动作按钮与工作流步骤
- 新增SSE实时推送shipping_ui_state事件,支持前端即时更新聊天气泡与工作台的状态与按钮
- 优化路由与登录流程:调整根路径重定向逻辑,退出登录时跳转到登录页;移除chat路由不必要的props传参;将原路由守卫中的根路径判断迁移到路由配置中
- 完善库存RPA与本地导入流程:新增本地库存文件托管接口,优化RPA回调的文件落盘与任务关联逻辑
- 新增多组单元测试覆盖焦点切换、决策处理、SSE同步等核心场景
- 修复多语言显示逻辑,使用te方法判断翻译key是否存在,避免缺失翻译时的渲染异常
- 新增reparse_inventory菜单动作,支持静默重新解析库存且不追加额外聊天消息
- 重构工作流步骤渲染函数,优先使用后端返回的步骤数据, fallback到本地推导的旧逻辑
- 清理后端旧的chat-actions API接口,将相关逻辑迁移到统一的ui_state接口中
This commit is contained in:
hugo committed 2026-07-02 01:55:19 +08:00
commit 9c036c825b
39 files changed
+3114 -456

No files matched your search

+75
View File
@@ -1309,6 +1309,77 @@ def chat_completions():
known_provider_conversation_id = session.external_conversation_id known_provider_conversation_id = session.external_conversation_id
known_status = session.status known_status = session.status
is_shipping_stream = str(getattr(agent_proxy, 'name', '') or '').strip() == SHIPPING_NOTICE_AGENT_NAME
emitted_shipping_state_keys: set[str] = set()
def build_shipping_ui_state_event() -> dict | None:
"""
构造发货通知专属 UI State SSE 事件。
核心逻辑:优先使用前端显式 task_id,其次按 batch 焦点任务补齐;事件只携带状态机读模型,
不依赖 Dify 文本,供前端即时渲染按钮和步骤。
"""
if not is_shipping_stream:
return None
try:
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
task = get_task_by_ref(shipping_task_id)
batch = get_batch_by_no(shipping_batch_no)
if task is None and batch is not None:
focus_task_no = str(batch.current_focus_task_no or '').strip()
if focus_task_no:
candidate = get_task_by_ref(focus_task_no)
if candidate is not None and candidate.batch_id == batch.id:
task = candidate
if task is not None:
return {
'event': 'shipping_ui_state',
'conversation_id': session.session_id,
'task_no': task.task_no,
'batch_no': task.batch.batch_no if task.batch is not None else None,
'ui_state': build_task_ui_state(task),
}
if batch is not None:
return {
'event': 'shipping_ui_state',
'conversation_id': session.session_id,
'batch_no': batch.batch_no,
'batch_ui_state': build_batch_ui_state(batch),
}
except Exception:
current_app.logger.exception(
'[chat-api] build shipping_ui_state failed request_id=%s session_id=%s task_id=%s batch_no=%s',
request_id,
session.session_id,
shipping_task_id,
shipping_batch_no,
)
return None
def maybe_emit_shipping_ui_state() -> str | None:
event = build_shipping_ui_state_event()
if not event:
return None
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {}
focus_state = batch_ui_state.get('focus_task_ui_state') if isinstance(batch_ui_state.get('focus_task_ui_state'), dict) else {}
checkpoint = ui_state.get('checkpoint') or focus_state.get('checkpoint')
key = json.dumps({
'task_no': event.get('task_no'),
'batch_no': event.get('batch_no'),
'checkpoint': checkpoint,
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
}, ensure_ascii=False, sort_keys=True)
if key in emitted_shipping_state_keys:
return None
emitted_shipping_state_keys.add(key)
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
initial_shipping_state = maybe_emit_shipping_ui_state()
if initial_shipping_state:
yield initial_shipping_state
try: try:
for chunk in generator: for chunk in generator:
@@ -1369,6 +1440,10 @@ def chat_completions():
'total_relay_ms': relay_total_ms, 'total_relay_ms': relay_total_ms,
} }
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n" yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
if event_name in ('message_end', 'workflow_finished'):
shipping_state = maybe_emit_shipping_ui_state()
if shipping_state:
yield shipping_state
except Exception as exc: except Exception as exc:
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id) current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'} payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
+183 -79
View File
@@ -2,18 +2,21 @@
api/workspace_shipping_notice.py api/workspace_shipping_notice.py
用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。 用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload。 依赖:app.core.auth.jwt / context、app.core.errors / response、shipping_notice.query_service / tools / notice_upload。
逻辑:薄路由层做鉴权与参数校验(统一 raise AppError);业务编排下沉 shipping_notice service。 逻辑:薄路由层做鉴权与参数校验(统一 raise AppError);业务编排下沉 shipping_notice service。
""" """
from __future__ import annotations from __future__ import annotations
from flask import Blueprint, jsonify, request, send_file import uuid
from flask import Blueprint, g, request, send_file
from app import db from app import db
from app.core.auth.context import get_request_id
from app.core.auth.jwt import get_current_user from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.models import ShippingBatch, ShippingTask from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import ( from app.services.shipping_notice.constants import (
AUTO_CHAIN_FALLBACK, AUTO_CHAIN_FALLBACK,
CP_EXPORT_GENERATED, CP_EXPORT_GENERATED,
@@ -35,10 +38,39 @@ from app.services.shipping_notice.query_service import (
serialize_task_summary, serialize_task_summary,
task_export_error_message, task_export_error_message,
) )
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__) workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
def _workspace_request_id() -> str:
"""
返回当前 workspace 请求的唯一 request_id。
核心逻辑:优先复用上游链路注入的 request_id;若不存在则在当前请求上下文中生成并缓存,供临时目录和 success envelope 共用同一 ID。
Returns:
str: 当前请求唯一 ID。
"""
existing = str(get_request_id() or getattr(g, 'workspace_request_id', '') or '').strip()
if existing:
g.workspace_request_id = existing
return existing
generated = uuid.uuid4().hex[:12]
g.workspace_request_id = generated
return generated
def _ok(data):
"""
构造 workspace 路由专用成功 envelope。
核心逻辑:优先复用请求上下文 request_id,无上游注入时生成一个兜底值,保证前端始终能拿到追踪字段。
Args:
data: 需要放入 success envelope 的业务数据。
Returns:
Flask Response: `{ success, data, request_id, timestamp }` 结构的 JSON 响应。
"""
return ok(data, request_id=_workspace_request_id())
def _require_user(): def _require_user():
""" """
校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。 校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。
@@ -60,14 +92,14 @@ def workspace_shipping_tasks():
batch_no = str(request.args.get('batch_no') or '').strip() or None batch_no = str(request.args.get('batch_no') or '').strip() or None
process_status = str(request.args.get('process_status') or '').strip() or None process_status = str(request.args.get('process_status') or '').strip() or None
limit = int(request.args.get('limit') or 100) limit = int(request.args.get('limit') or 100)
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit)) return _ok(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
def workspace_shipping_batches(): def workspace_shipping_batches():
"""列出当前用户的发货批次摘要。""" """列出当前用户的发货批次摘要。"""
user = _require_user() user = _require_user()
limit = int(request.args.get('limit') or 100) limit = int(request.args.get('limit') or 100)
return jsonify(list_batches_for_user(user.id, limit=limit)) return _ok(list_batches_for_user(user.id, limit=limit))
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
def workspace_shipping_conversation_batch_workspace(conversation_id: str): def workspace_shipping_conversation_batch_workspace(conversation_id: str):
@@ -76,11 +108,14 @@ def workspace_shipping_conversation_batch_workspace(conversation_id: str):
batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter( batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter(
(ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None)) (ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None))
).all() ).all()
return jsonify(get_conversation_batch_workspace(conversation_id, user.id)) return _ok(get_conversation_batch_workspace(conversation_id, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
def workspace_create_shipping_batch_from_notices(): def workspace_create_shipping_batch_from_notices():
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。""" """
接收多份发货通知附件,按文件级抽取结果创建批次并交给后台编排器逐票推进。
核心逻辑:先逐文件抽取文本,只有拿到可解析文本的文件才会进入 create_batch_tasks;失败/空文本文件仅回传摘要,不创建空任务。
"""
user = _require_user() user = _require_user()
uploads = request.files.getlist('files') uploads = request.files.getlist('files')
if not uploads: if not uploads:
@@ -90,50 +125,111 @@ def workspace_create_shipping_batch_from_notices():
if not uploads: if not uploads:
raise ValidationError('files is required') raise ValidationError('files is required')
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload from app.services.shipping_notice.notice_upload import (
cleanup_temp_notice_uploads,
extract_notice_text,
guess_source_type,
max_notice_chars,
save_temp_notice_upload,
)
conversation_id = str(request.form.get('conversation_id') or '').strip() conversation_id = str(request.form.get('conversation_id') or '').strip()
request_id = _workspace_request_id()
notice_items: list[dict] = [] notice_items: list[dict] = []
for upload in uploads: accepted_files: list[dict] = []
raw = upload.read() or b'' rejected_files: list[dict] = []
filename = upload.filename or 'notice' try:
source_type = guess_source_type(filename) for index, upload in enumerate(uploads, start=1):
text = '' raw = upload.read() or b''
warnings: list[str] = [] filename = upload.filename or 'notice'
try: source_type = guess_source_type(filename)
temp_task_no = f'TMP-{len(notice_items) + 1}' source_file_type = str(getattr(upload, 'mimetype', '') or '').strip() or None
saved_path = save_task_notice_upload(temp_task_no, filename, raw) text = ''
text, meta = extract_notice_text(saved_path) warnings: list[str] = []
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] meta: dict = {}
except Exception as exc: try:
warnings = [f'notice_extract_failed:{exc}'] # [STEP 1] 使用请求级唯一临时目录做文件级抽取,避免并发请求串文件且方便 finally 整体清理。
if text: saved_path = save_temp_notice_upload(request_id, index, filename, raw)
limit = max_notice_chars() text, meta = extract_notice_text(saved_path)
if len(text) > limit: warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
text = text[:limit] except Exception as exc:
warnings.append(f'notice_text_truncated:{limit}') warnings = [f'notice_extract_failed:{exc}']
notice_items.append({'source_type': source_type, 'source_file_name': filename, 'source_file_type': str(getattr(upload, 'mimetype', '') or '').strip() or None, 'raw_text': text, 'warnings': warnings}) rejected_files.append({
payload = {'user_id': user.id, 'conversation_id': conversation_id or None, 'file_count': len(notice_items), 'notice_items': notice_items, 'defer_parse': True} 'filename': filename,
created = shipping_tools.create_batch_tasks(payload) 'source_type': source_type,
data = created.get('data') if isinstance(created, dict) else None 'source_file_type': source_file_type,
batch_data = data.get('batch') if isinstance(data, dict) else None 'reason': 'extract_failed',
tasks_data = data.get('tasks') if isinstance(data, dict) else None 'message': 'notice extraction failed',
batch_no = str(created.get('batch_no') or (batch_data or {}).get('batch_no') or '').strip() 'warnings': warnings,
orchestrator_started = False })
if batch_no: continue
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator text = str(text or '').strip()
orchestrator_started = start_batch_orchestrator(batch_no) if text:
if isinstance(data, dict) and batch_no: limit = max_notice_chars()
focus_task = get_focus_task_for_batch(batch_no, user.id) if len(text) > limit:
if focus_task: text = text[:limit]
data['focus_task'] = serialize_task_summary(focus_task) warnings.append(f'notice_text_truncated:{limit}')
if isinstance(tasks_data, list): notice_items.append({
data['tasks'] = tasks_data 'source_type': source_type,
data['orchestrator_started'] = orchestrator_started 'source_file_name': filename,
if isinstance(created, dict): 'source_file_type': source_file_type,
base_message = str(created.get('message') or '').strip() 'raw_text': text,
if orchestrator_started: 'warnings': warnings,
created['message'] = f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。' })
return jsonify(created) accepted_files.append({
'filename': filename,
'source_type': source_type,
'source_file_type': source_file_type,
'text_length': len(text),
'warnings': warnings,
})
continue
rejected_files.append({
'filename': filename,
'source_type': source_type,
'source_file_type': source_file_type,
'reason': 'empty_text',
'message': 'notice text is empty after extraction',
'warnings': warnings,
})
file_summary = {
'total_files': len(uploads),
'accepted_count': len(accepted_files),
'rejected_count': len(rejected_files),
'accepted_files': accepted_files,
'rejected_files': rejected_files,
}
if not notice_items:
raise ValidationError(
'all uploaded files failed extraction or contained no parseable text',
details={'rejected_files': rejected_files, 'file_summary': file_summary},
)
payload = {'user_id': user.id, 'conversation_id': conversation_id or None, 'file_count': len(notice_items), 'notice_items': notice_items, 'defer_parse': True}
# [STEP 2] 仅将 accepted 文件交给建批逻辑,保证 batch/task 数量与可解析附件完全一致。
created = shipping_tools.create_batch_tasks(payload)
data = created.get('data') if isinstance(created, dict) else None
batch_data = data.get('batch') if isinstance(data, dict) else None
tasks_data = data.get('tasks') if isinstance(data, dict) else None
batch_no = str(created.get('batch_no') or (batch_data or {}).get('batch_no') or '').strip()
orchestrator_started = False
if batch_no:
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
orchestrator_started = start_batch_orchestrator(batch_no)
if isinstance(data, dict) and batch_no:
focus_task = get_focus_task_for_batch(batch_no, user.id)
if focus_task:
data['focus_task'] = serialize_task_summary(focus_task)
if isinstance(tasks_data, list):
data['tasks'] = tasks_data
data['orchestrator_started'] = orchestrator_started
if isinstance(created, dict):
base_message = str(created.get('message') or '').strip()
if orchestrator_started:
created['message'] = f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。'
created['file_summary'] = file_summary
# [STEP 3] workspace 成功响应统一 envelope;原 tool 结果整体保留在 data 内,前端可渐进迁移。
return _ok(created)
finally:
cleanup_temp_notice_uploads(request_id)
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
def workspace_shipping_batch_detail(batch_no: str): def workspace_shipping_batch_detail(batch_no: str):
@@ -142,8 +238,16 @@ def workspace_shipping_batch_detail(batch_no: str):
batch = get_batch_for_user(batch_no, user.id) batch = get_batch_for_user(batch_no, user.id)
if not batch: if not batch:
raise NotFoundError('Not found') raise NotFoundError('Not found')
focus_task = get_focus_task_for_batch(batch_no, user.id) return _ok(build_batch_ui_state(batch))
return jsonify({**serialize_batch_summary(batch), 'tasks': list_tasks_for_batch(batch_no, user.id), 'focus_task': serialize_task_summary(focus_task) if focus_task else None})
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
def workspace_shipping_batch_ui_state(batch_no: str):
"""返回批次级 UI State,供工作台、步骤条和任务卡片共用同一状态来源。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return _ok(build_batch_ui_state(batch))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
def workspace_shipping_batch_tasks(batch_no: str): def workspace_shipping_batch_tasks(batch_no: str):
@@ -152,7 +256,7 @@ def workspace_shipping_batch_tasks(batch_no: str):
batch = get_batch_for_user(batch_no, user.id) batch = get_batch_for_user(batch_no, user.id)
if not batch: if not batch:
raise NotFoundError('Not found') raise NotFoundError('Not found')
return jsonify(list_tasks_for_batch(batch_no, user.id)) return _ok(list_tasks_for_batch(batch_no, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
def workspace_shipping_batch_focus_task(batch_no: str): def workspace_shipping_batch_focus_task(batch_no: str):
@@ -164,7 +268,7 @@ def workspace_shipping_batch_focus_task(batch_no: str):
focus_task = get_focus_task_for_batch(batch_no, user.id) focus_task = get_focus_task_for_batch(batch_no, user.id)
if not focus_task: if not focus_task:
raise NotFoundError('Focus task not found') raise NotFoundError('Focus task not found')
return jsonify(serialize_task_summary(focus_task)) return _ok(serialize_task_summary(focus_task))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
def workspace_switch_shipping_batch_focus_task(batch_no: str): def workspace_switch_shipping_batch_focus_task(batch_no: str):
@@ -182,7 +286,7 @@ def workspace_switch_shipping_batch_focus_task(batch_no: str):
raise NotFoundError('Task not found in batch') raise NotFoundError('Task not found in batch')
batch.current_focus_task_no = task.task_no batch.current_focus_task_no = task.task_no
db.session.commit() db.session.commit()
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}) return _ok({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
def workspace_create_shipping_task(): def workspace_create_shipping_task():
@@ -200,7 +304,7 @@ def workspace_create_shipping_task():
if raw_content: if raw_content:
payload['raw_content'] = raw_content payload['raw_content'] = raw_content
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.create_task(payload)) return _ok(shipping_tools.create_task(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
def workspace_create_shipping_task_from_notice(): def workspace_create_shipping_task_from_notice():
@@ -225,7 +329,7 @@ def workspace_create_shipping_task_from_notice():
text, meta = extract_notice_text(saved_path) text, meta = extract_notice_text(saved_path)
if not text: if not text:
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': {'filename': upload.filename or '', **meta}}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)}) return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': {'filename': upload.filename or '', **meta}}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
if text: if text:
limit = max_notice_chars() limit = max_notice_chars()
if len(text) > limit: if len(text) > limit:
@@ -242,7 +346,7 @@ def workspace_create_shipping_task_from_notice():
db.session.commit() db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id) orchestrator_started = start_task_orchestrator(task_id)
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
def workspace_replace_shipping_task_notice(task_no: str): def workspace_replace_shipping_task_notice(task_no: str):
@@ -277,7 +381,7 @@ def workspace_replace_shipping_task_notice(task_no: str):
data = result.setdefault('data', {}) data = result.setdefault('data', {})
if isinstance(data, dict): if isinstance(data, dict):
data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})} data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})}
return jsonify(result) return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
def workspace_shipping_task_detail(task_no: str): def workspace_shipping_task_detail(task_no: str):
@@ -286,16 +390,16 @@ def workspace_shipping_task_detail(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
return jsonify(serialize_task_detail(task)) return _ok({**serialize_task_detail(task), 'ui_state': build_task_ui_state(task)})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
def workspace_shipping_task_chat_actions(task_no: str): def workspace_shipping_task_ui_state(task_no: str):
"""返回聊天气泡侧所需的动作按钮与检查点信息。""" """返回单票任务 UI State;后续 Chat 按钮、顶部步骤条统一消费本接口。"""
user = _require_user() user = _require_user()
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
return jsonify(build_chat_actions_payload(task)) return _ok(build_task_ui_state(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
def workspace_retry_shipping_task(task_no: str): def workspace_retry_shipping_task(task_no: str):
@@ -310,7 +414,7 @@ def workspace_retry_shipping_task(task_no: str):
comment = str(data.get('comment') or '').strip() comment = str(data.get('comment') or '').strip()
if comment: if comment:
payload['comment'] = comment payload['comment'] = comment
return jsonify(shipping_tools.retry_task(payload)) return _ok(shipping_tools.retry_task(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
def workspace_upload_shipping_inventory(task_no: str): def workspace_upload_shipping_inventory(task_no: str):
@@ -321,7 +425,7 @@ def workspace_upload_shipping_inventory(task_no: str):
raise NotFoundError('Not found') raise NotFoundError('Not found')
upload = request.files.get('file') upload = request.files.get('file')
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload)) return _ok(shipping_tools.upload_inventory_file(task.task_no, upload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
def workspace_confirm_shipping_inventory_source(task_no: str): def workspace_confirm_shipping_inventory_source(task_no: str):
@@ -335,7 +439,7 @@ def workspace_confirm_shipping_inventory_source(task_no: str):
if not source_code: if not source_code:
raise ValidationError('source_code is required') raise ValidationError('source_code is required')
from app.services.shipping_notice import tools as shipping_tools 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 _ok(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code}))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
def workspace_apply_inventory_mapping(task_no: str): def workspace_apply_inventory_mapping(task_no: str):
@@ -351,7 +455,7 @@ def workspace_apply_inventory_mapping(task_no: str):
raise ValidationError(f'{MAP_JSON} is required') raise ValidationError(f'{MAP_JSON} is required')
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True} payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
return jsonify(shipping_tools.apply_inventory_mapping(payload)) return _ok(shipping_tools.apply_inventory_mapping(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
def workspace_submit_shipping_decision(task_no: str): def workspace_submit_shipping_decision(task_no: str):
@@ -369,7 +473,7 @@ def workspace_submit_shipping_decision(task_no: str):
comment = str(data.get('comment') or '').strip() comment = str(data.get('comment') or '').strip()
if comment: if comment:
payload['comment'] = comment payload['comment'] = comment
return jsonify(shipping_tools.submit_decision(payload)) return _ok(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
def workspace_update_shipping_notice_fields(task_no: str): def workspace_update_shipping_notice_fields(task_no: str):
@@ -387,7 +491,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
comment = str(data.get('comment') or '').strip() comment = str(data.get('comment') or '').strip()
if comment: if comment:
payload['comment'] = comment payload['comment'] = comment
return jsonify(shipping_tools.update_notice_fields(payload)) return _ok(shipping_tools.update_notice_fields(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
def workspace_update_shipping_notice_line(task_no: str): def workspace_update_shipping_notice_line(task_no: str):
@@ -409,7 +513,7 @@ def workspace_update_shipping_notice_line(task_no: str):
comment = str(data.get('comment') or '').strip() comment = str(data.get('comment') or '').strip()
if comment: if comment:
payload['comment'] = comment payload['comment'] = comment
return jsonify(shipping_tools.update_notice_line(payload)) return _ok(shipping_tools.update_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST'])
def workspace_add_shipping_notice_line(task_no: str): def workspace_add_shipping_notice_line(task_no: str):
@@ -427,7 +531,7 @@ def workspace_add_shipping_notice_line(task_no: str):
comment = str(data.get('comment') or '').strip() comment = str(data.get('comment') or '').strip()
if comment: if comment:
payload['comment'] = comment payload['comment'] = comment
return jsonify(shipping_tools.add_notice_line(payload)) return _ok(shipping_tools.add_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
def workspace_remove_shipping_notice_line(task_no: str): def workspace_remove_shipping_notice_line(task_no: str):
@@ -446,7 +550,7 @@ def workspace_remove_shipping_notice_line(task_no: str):
comment = str(data.get('comment') or '').strip() comment = str(data.get('comment') or '').strip()
if comment: if comment:
payload['comment'] = comment payload['comment'] = comment
return jsonify(shipping_tools.remove_notice_line(payload)) return _ok(shipping_tools.remove_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
def workspace_auto_progress_shipping_task(task_no: str): def workspace_auto_progress_shipping_task(task_no: str):
@@ -468,7 +572,7 @@ def workspace_auto_progress_shipping_task(task_no: str):
if isinstance(gen_data, dict) and gen_data.get('export_file_path'): if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'} gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
result = {**result, 'data': gen_data} result = {**result, 'data': gen_data}
return jsonify(result) return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
def workspace_match_shipping_inventory(task_no: str): def workspace_match_shipping_inventory(task_no: str):
@@ -481,7 +585,7 @@ def workspace_match_shipping_inventory(task_no: str):
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True}) matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
if not isinstance(matched, dict): if not isinstance(matched, dict):
return jsonify(matched) return _ok(matched)
data = matched.get('data') data = matched.get('data')
if isinstance(data, dict) and data.get('export_file_path'): if isinstance(data, dict) and data.get('export_file_path'):
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}} matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
@@ -496,7 +600,7 @@ def workspace_match_shipping_inventory(task_no: str):
buttons = action_buttons_for_checkpoint(checkpoint) buttons = action_buttons_for_checkpoint(checkpoint)
if buttons: if buttons:
matched['action_buttons'] = buttons matched['action_buttons'] = buttons
return jsonify(matched) return _ok(matched)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
def workspace_mark_manual_uploaded(task_no: str): def workspace_mark_manual_uploaded(task_no: str):
@@ -506,7 +610,7 @@ def workspace_mark_manual_uploaded(task_no: str):
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'})) return _ok(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
def workspace_retry_shipping_upload(task_no: str): def workspace_retry_shipping_upload(task_no: str):
@@ -516,7 +620,7 @@ def workspace_retry_shipping_upload(task_no: str):
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'})) return _ok(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'}))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
def workspace_generate_shipping_excel(task_no: str): def workspace_generate_shipping_excel(task_no: str):
@@ -533,7 +637,7 @@ def workspace_generate_shipping_excel(task_no: str):
data = {} data = {}
result['data'] = data result['data'] = data
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export' data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
return jsonify(result) return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
def workspace_shipping_task_export(task_no: str): def workspace_shipping_task_export(task_no: str):
@@ -556,4 +660,4 @@ def workspace_retry_shipping_batch_pending(batch_no: str):
if not batch: if not batch:
raise NotFoundError('Not found') raise NotFoundError('Not found')
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
return jsonify(retry_batch_pending_tasks(batch.batch_no)) return _ok(retry_batch_pending_tasks(batch.batch_no))
@@ -1,9 +1,9 @@
""" """
services/shipping_notice/chat_actions.py services/shipping_notice/chat_actions.py
用途:chat-actions 相关符号的向后兼容 re-export 入口。 用途:发货通知状态机旧模块名的向后兼容 re-export 入口。
依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)。 依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)。
逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py。 逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py,不再暴露已删除的 /chat-actions 读模型。
""" """
from app.services.shipping_notice.state_machine import ( from app.services.shipping_notice.state_machine import (
@@ -16,10 +16,8 @@ from app.services.shipping_notice.state_machine import (
action_buttons_for_checkpoint, action_buttons_for_checkpoint,
apply_task_transition, apply_task_transition,
build_action_buttons, build_action_buttons,
build_chat_actions_payload,
build_checkpoint_catalog, build_checkpoint_catalog,
checkpoint_for_task, checkpoint_for_task,
format_actions_directive,
human_options_for_checkpoint, human_options_for_checkpoint,
human_options_for_task, human_options_for_task,
human_options_for_task_or_checkpoint, human_options_for_task_or_checkpoint,
@@ -43,10 +41,8 @@ __all__ = [
"action_buttons_for_checkpoint", "action_buttons_for_checkpoint",
"apply_task_transition", "apply_task_transition",
"build_action_buttons", "build_action_buttons",
"build_chat_actions_payload",
"build_checkpoint_catalog", "build_checkpoint_catalog",
"checkpoint_for_task", "checkpoint_for_task",
"format_actions_directive",
"human_options_for_checkpoint", "human_options_for_checkpoint",
"human_options_for_task", "human_options_for_task",
"human_options_for_task_or_checkpoint", "human_options_for_task_or_checkpoint",
@@ -9,6 +9,7 @@ services/shipping_notice/inventory_file_store.py
from __future__ import annotations from __future__ import annotations
import re import re
import shutil
import uuid import uuid
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
@@ -109,6 +110,57 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
return inv_file return inv_file
def save_task_inventory_file_from_local_path(
task: ShippingTask,
source_path: str | Path,
*,
source_file_name: str | None = None,
) -> ShippingInventoryFile:
"""
将本地已有库存文件纳入统一库存快照模型,并为当前任务建立 active link。
【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 ShippingInventoryFile 记录时调用。
核心逻辑:复制本地文件到 inventory_file_no 对应标准目录,生成 schema preview,
再创建 task_only 的 ShippingInventoryFile 与 active ShippingTaskInventoryLink。
Args:
task: 当前发货任务,用于绑定 user/batch 与 active link。
source_path: 本地库存文件路径,必须存在。
source_file_name: 展示给用户/审计的原始文件名;为空时回退源文件名。
Returns:
ShippingInventoryFile: 已持久化的库存快照对象。
Raises:
FileNotFoundError: 源文件不存在时抛出。
"""
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
inventory_file_no = generate_inventory_file_no()
path = inventory_file_upload_path(inventory_file_no)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, path)
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = str(source_file_name or source.name or path.name).strip() or path.name
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
batch_id=task.batch_id,
user_id=task.user_id,
source_file_name=str(source_file_name or source.name or path.name).strip() or path.name,
storage_path=str(path),
schema_preview_json=preview,
share_mode="task_only",
line_count=0,
)
db.session.add(inv_file)
db.session.flush()
replace_task_inventory_link(task, inv_file, role="owner")
return inv_file
def replace_task_inventory_link( def replace_task_inventory_link(
task: ShippingTask, task: ShippingTask,
inv_file: ShippingInventoryFile, inv_file: ShippingInventoryFile,
@@ -16,6 +16,8 @@ from app import db
from app.models import ShippingTask, ShippingTaskEvent 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.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
from app.services.shipping_notice.inventory_file_store import save_task_inventory_file_from_local_path
from app.services.shipping_notice.inventory_upload import save_task_inventory_local_file
from app.services.shipping_notice.inventory_source_rules import ( from app.services.shipping_notice.inventory_source_rules import (
mark_inventory_source_review, mark_inventory_source_review,
resolve_inventory_source, resolve_inventory_source,
@@ -427,14 +429,20 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task), data=serialize_task_for_tool(task),
) )
# [STEP 2] 成功回调后读取实际库存文件并交给统一的 inventory_loaded_response。 # [STEP 2] 成功回调后先把 RPA 文件正式纳入系统库存目录,再交给统一 ingest。
# 这样回调路径与人工上传路径在后续字段对齐/自动串联上保持一致。 # 这样 inventory_uploads 会保留任务级正式附件,回调路径也能与人工上传共享同一托管约定。
file_path = str(payload.get("file_path") or "").strip() file_path = str(payload.get("file_path") or "").strip()
path = Path(file_path) if file_path else find_latest_inventory_file() path = Path(file_path) if file_path else find_latest_inventory_file()
if not path or not path.is_file(): if not path or not path.is_file():
return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在") return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在")
processed = inventory_processed_dir() processed = inventory_processed_dir()
managed_path = save_task_inventory_local_file(task.task_no, path)
inv_file = save_task_inventory_file_from_local_path(
task,
managed_path,
source_file_name=path.name,
)
lines, column_meta = ingest_inventory_file(path, move_to=processed) lines, column_meta = ingest_inventory_file(path, move_to=processed)
set_task_step_progress( set_task_step_progress(
task, task,
@@ -443,7 +451,18 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
status="running", status="running",
message="RPA 库存文件已返回,正在读取库存快照", message="RPA 库存文件已返回,正在读取库存快照",
progress_percent=85, progress_percent=85,
detail=f"正在读取 {path.name}", detail=f"正在读取 {managed_path.name}",
)
log_task_event(
task,
"inventory_uploaded",
{
"source": "rpa_callback",
"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( return inventory_loaded_response(
task, task,
@@ -9,6 +9,7 @@ services/shipping_notice/inventory_upload.py
from __future__ import annotations from __future__ import annotations
import re import re
import shutil
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
@@ -44,6 +45,33 @@ def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
return path return path
def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Path:
"""
保存本地已存在的库存文件到任务标准库存目录。
【AI 触发时机】:当 RPA 或其他后台流程已经拿到本地 Excel,需要把它正式纳入系统托管目录时调用。
核心逻辑:校验 source_path 存在后,统一复制到 inventory_uploads/{task_no}/inventory.xlsx,
让 RPA 下载与人工上传共用同一套任务级库存附件路径。
Args:
task_no: 发货任务号,禁止为空。
source_path: 本地现有库存文件路径,必须指向真实文件。
Returns:
Path: 系统托管后的任务库存文件路径。
Raises:
FileNotFoundError: 源文件不存在时抛出。
"""
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
def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]: def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]:
"""读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。""" """读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。"""
path = task_inventory_upload_path(task_no) path = task_inventory_upload_path(task_no)
@@ -3,13 +3,14 @@ services/shipping_notice/notice_upload.py
用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。 用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。
依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。 依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。
逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow。 逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow;批量上传的预检临时文件也在这里统一落盘和清理。
""" """
from __future__ import annotations from __future__ import annotations
import base64 import base64
import re import re
import shutil
from email import policy from email import policy
from email.parser import BytesParser from email.parser import BytesParser
from pathlib import Path from pathlib import Path
@@ -30,6 +31,19 @@ def task_notice_upload_path(task_no: str, filename: str) -> Path:
return _storage_root() / "notice_uploads" / safe_task / safe_name return _storage_root() / "notice_uploads" / safe_task / safe_name
def temp_notice_upload_dir(request_id: str) -> Path:
"""
返回批量上传预检使用的请求级临时目录。
核心逻辑:将同一请求下的临时文件收敛到 `_tmp/{request_id}`,便于 finally 阶段整目录清理。
Args:
request_id: 当前请求唯一 ID。
Returns:
Path: 临时目录路径。
"""
safe_request = re.sub(r"[^\w\-]+", "_", str(request_id or "").strip()) or "unknown"
return _storage_root() / "notice_uploads" / "_tmp" / safe_request
def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path: def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path:
"""保存发货通知附件字节流并返回落盘路径。""" """保存发货通知附件字节流并返回落盘路径。"""
path = task_notice_upload_path(task_no, filename) path = task_notice_upload_path(task_no, filename)
@@ -38,6 +52,42 @@ def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path:
return path return path
def save_temp_notice_upload(request_id: str, index: int, filename: str, data: bytes) -> Path:
"""
保存批量上传预检阶段的临时附件。
核心逻辑:以请求 ID 作为一级目录、文件序号作为二级目录,避免同请求内同名文件互相覆盖。
Args:
request_id: 当前请求唯一 ID。
index: 当前文件在请求内的顺序号。
filename: 原始文件名。
data: 文件字节流。
Returns:
Path: 临时落盘路径。
"""
name = str(filename or "").strip() or "notice"
safe_name = re.sub(r"[^\w\-.]+", "_", name)[:120] or "notice"
safe_index = max(int(index or 0), 1)
path = temp_notice_upload_dir(request_id) / str(safe_index) / safe_name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
def cleanup_temp_notice_uploads(request_id: str) -> None:
"""
清理指定请求的临时上传目录。
【AI 触发时机】:仅在批量上传预检完成后调用;正式任务附件目录禁止使用本函数清理。
Args:
request_id: 当前请求唯一 ID。
"""
path = temp_notice_upload_dir(request_id)
if path.exists():
shutil.rmtree(path, ignore_errors=True)
parent = path.parent
if parent.exists() and not any(parent.iterdir()):
parent.rmdir()
def _decode_text(data: bytes) -> str: def _decode_text(data: bytes) -> str:
if not data: if not data:
return "" return ""
@@ -3,7 +3,7 @@ services/shipping_notice/state_machine.py
用途:发货通知人工节点(checkpoint)与动作按钮的单一注册表,负责任务 DB 字段与 UI 状态的映射。 用途:发货通知人工节点(checkpoint)与动作按钮的单一注册表,负责任务 DB 字段与 UI 状态的映射。
依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts。 依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts。
逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;chat_actions 与前端 chat-actions API 读本模块生成按钮与 ui_state;新增人工节点时仅改本文件与测试。 逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;ui_state.py 与历史兼容模块都从本文件读取按钮/状态;新增人工节点时仅改本文件与测试。
扩展说明(开发者): 扩展说明(开发者):
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt` - checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
@@ -13,7 +13,6 @@ services/shipping_notice/state_machine.py
from __future__ import annotations from __future__ import annotations
import json
from dataclasses import dataclass from dataclasses import dataclass
from enum import StrEnum from enum import StrEnum
from typing import Any from typing import Any
@@ -223,19 +222,10 @@ def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
def action_buttons_for_checkpoint(checkpoint: str | None) -> list[dict[str, str]]: def action_buttons_for_checkpoint(checkpoint: str | None) -> list[dict[str, str]]:
"""checkpoint → action_buttons 的便捷封装(tool_response 与 Dify fallback 用)。""" """checkpoint → action_buttons 的便捷封装(状态机 UI payload 用)。"""
return build_action_buttons(human_options_for_checkpoint(checkpoint)) return build_action_buttons(human_options_for_checkpoint(checkpoint))
def format_actions_directive(option_ids: list[str] | None) -> str:
"""将 action_buttons 序列化为 HTML 注释指令,嵌入 Agent 回复供前端解析。"""
buttons = build_action_buttons(option_ids)
if not buttons:
return ""
body = json.dumps(buttons, ensure_ascii=False)
return f"<!-- HXOPS_SHIPPING_ACTIONS: {body} -->"
def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState: def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
"""无 DB 任务时,仅按 checkpoint id 构造 TaskUiState(Tool 早停响应用)。""" """无 DB 任务时,仅按 checkpoint id 构造 TaskUiState(Tool 早停响应用)。"""
options = human_options_for_checkpoint(checkpoint) options = human_options_for_checkpoint(checkpoint)
@@ -271,7 +261,7 @@ def human_options_for_task_or_checkpoint(
def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
""" """
将 ShippingTask DB 字段映射为 checkpoint + human_options(/chat-actions 核心)。 将 ShippingTask DB 字段映射为 checkpoint + human_options,供统一 UI State 读模型消费。
核心逻辑:终态 → 正向流程节点 → pending_human_reason 分支 → 默认 None。 核心逻辑:终态 → 正向流程节点 → pending_human_reason 分支 → 默认 None。
""" """
@@ -399,29 +389,6 @@ def human_options_for_task(task: ShippingTask) -> list[str] | None:
return resolve_task_ui_state(task).human_options return resolve_task_ui_state(task).human_options
def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
"""
组装 /chat-actions API 响应体,供前端渲染步骤条与动作按钮。
Returns:
dict: 含 task_no、checkpoint、process_status、action_buttons 等字段。
"""
ui = resolve_task_ui_state(task)
action_buttons = (
inventory_source_action_buttons(task)
if ui.checkpoint == CP_INVENTORY_SOURCE_REVIEW
else ui.action_buttons
)
return {
"task_no": task.task_no,
"checkpoint": ui.checkpoint,
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"action_buttons": action_buttons,
}
def build_checkpoint_catalog() -> dict[str, Any]: def build_checkpoint_catalog() -> dict[str, Any]:
"""导出 checkpoint 注册表供文档/CI 校验(不接入 Dify 画布)。""" """导出 checkpoint 注册表供文档/CI 校验(不接入 Dify 画布)。"""
checkpoints = [] checkpoints = []
@@ -0,0 +1,250 @@
"""
services/shipping_notice/ui_state.py
用途:发货通知任务/批次 UI 状态读模型,作为 Chat 按钮、步骤条与工作台的统一状态来源。
依赖:models.ShippingTask/ShippingBatch、state_machine、query_service。
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/action_buttons,再补充七步流程与用户可读摘要。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_COMPLETED,
CP_EXPORT_READY,
CP_INVENTORY_PENDING,
CP_INVENTORY_SOURCE_REVIEW,
CP_MAP_INFER,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_PARSE_REVIEW,
CP_READY_EXPORT,
CP_READY_MATCH,
CP_REJECTED,
CP_RSV_REQ,
CP_UPLOADED,
CP_UPLOAD_FAILED,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_INV_UNAVAIL,
PH_MAP_INFER,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_RSV_REQ,
PH_SHORTAGE,
PH_UPLOAD_RPA_PENDING,
RS_ALIGN_REVIEW,
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.query_service import (
compute_batch_process_summary,
list_sorted_batch_tasks,
serialize_batch_summary,
serialize_task_summary,
)
from app.services.shipping_notice.state_machine import (
inventory_source_action_buttons,
resolve_task_ui_state,
)
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
{"id": "shipping-step-1", "code": "notice_submit", "label": "提交通知"},
{"id": "shipping-step-2", "code": "parse_confirm", "label": "确认解析"},
{"id": "shipping-step-3", "code": "inventory_prepare", "label": "获取库存"},
{"id": "shipping-step-4", "code": "align_confirm", "label": "确认字段对齐"},
{"id": "shipping-step-5", "code": "match_inventory", "label": "匹配库存"},
{"id": "shipping-step-6", "code": "generate_file", "label": "生成发货文件"},
{"id": "shipping-step-7", "code": "upload_freight", "label": "上传货代"},
)
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
"step1_notice_submit": 0,
"step2_parse_confirm": 1,
"step3_inventory_prepare": 2,
"step2_inventory_prepare": 2,
"step4_align_confirm": 3,
"step5_match_inventory": 4,
"step3_inventory_match": 4,
"step4_shortage_review": 4,
"step6_generate_file": 5,
"step5_export_excel": 5,
"step7_upload_freight": 6,
"step6_upload_freight": 6,
"step7_finish": 6,
}
_TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"}
_BLOCKED_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
CP_ALIGN_REVIEW,
RS_SHORTAGE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_UPLOAD_FAILED,
}
def _derive_current_step_index(task: ShippingTask) -> int:
"""
根据任务字段推导七步流程当前索引。
核心逻辑:优先使用 current_step 精准定位;缺失时按 process/review/pending 状态兜底,
保持与前端旧 stepper 的语义一致,后续前端可直接消费后端 step。
"""
current_step = str(task.current_step or "").strip()
if current_step in _CURRENT_STEP_INDEX_MAP:
return _CURRENT_STEP_INDEX_MAP[current_step]
process_status = str(task.process_status or "").strip()
review_status = str(task.review_status or "").strip()
pending_reason = str(task.pending_human_reason or "").strip()
match_status = str(task.match_status or "").strip()
has_export = bool(str(task.export_file_name or "").strip() or str(task.export_file_path or "").strip())
if process_status in _TERMINAL_PROCESS_STATUSES:
return 6
if process_status in {"waiting_upload", "upload_failed"} or has_export:
return 5
if process_status == "matched":
return 4
if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE:
return 4
if review_status == RS_ALIGN_REVIEW or pending_reason == CP_ALIGN_REVIEW:
return 3
if process_status == "inventory_ready" or match_status:
return 4
if process_status == "waiting_inventory" or pending_reason in {
PH_MAP_INFER,
PH_RPA_PENDING,
PH_INV_UNAVAIL,
PH_RPA_EXHAUSTED,
}:
return 2
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}:
return 1
return 0
def build_shipping_workflow_steps(task: ShippingTask, checkpoint: str | None) -> list[dict[str, str]]:
"""
构造七步流程状态。
Returns:
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
"""
current_index = _derive_current_step_index(task)
process_status = str(task.process_status or "").strip()
checkpoint_value = str(checkpoint or "").strip()
steps: list[dict[str, str]] = []
for index, step in enumerate(WORKFLOW_STEPS):
if process_status in _TERMINAL_PROCESS_STATUSES:
status = "completed"
elif index < current_index:
status = "completed"
elif index == current_index:
status = "current"
else:
status = "pending"
if index == current_index and checkpoint_value in _BLOCKED_CHECKPOINTS:
status = "blocked"
steps.append({**step, "status": status})
return steps
def _action_buttons_for_task(task: ShippingTask) -> list[dict[str, str]]:
"""从状态机解析当前任务可用动作按钮,库存源确认场景补充 source_code。"""
ui = resolve_task_ui_state(task)
if ui.checkpoint == CP_INVENTORY_SOURCE_REVIEW:
return inventory_source_action_buttons(task)
return ui.action_buttons
def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, str | None]:
"""输出用户可读任务摘要,供 Chat 文案与工作台卡片复用。"""
title = user_facing_task_stage(task)
message_by_checkpoint: dict[str, str] = {
CP_PARSE_REVIEW: "解析结果需要人工确认后才能继续。",
CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。",
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
CP_INVENTORY_SOURCE_REVIEW: "库存查询来源不明确,需要先确认。",
CP_MAP_INFER: "库存列映射需要确认或重新选择。",
CP_ALIGN_REVIEW: "库存字段对齐需要人工确认。",
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
CP_READY_MATCH: "库存已就绪,可以继续执行匹配。",
CP_READY_EXPORT: "库存匹配已满足发货条件,可以生成发货文件。",
CP_EXPORT_READY: "发货文件已生成,可以下载或确认上传。",
CP_WAITING_UPLOAD: "系统正在等待货代上传结果。",
CP_UPLOAD_FAILED: "货代上传失败,需要重试或手工确认。",
CP_REJECTED: "任务已驳回,无需继续处理。",
CP_UPLOADED: "任务已完成上传。",
CP_COMPLETED: "任务已关闭。",
}
return {
"title": title,
"message": message_by_checkpoint.get(str(checkpoint or ""), title),
"error_message": task.error_message or task.upload_error_message,
}
def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
"""
构建单票任务 UI State。
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/action_buttons/step,避免 Chat、顶部步骤条、
右侧工作台分别推导状态导致不一致。
"""
ui = resolve_task_ui_state(task)
action_buttons = _action_buttons_for_task(task)
steps = build_shipping_workflow_steps(task, ui.checkpoint)
current_index = _derive_current_step_index(task)
current_step = steps[current_index] if 0 <= current_index < len(steps) else None
return {
"task_no": task.task_no,
"batch_no": task.batch.batch_no if task.batch is not None else None,
"checkpoint": ui.checkpoint,
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"match_status": task.match_status,
"current_step": current_step,
"steps": steps,
"summary": _build_task_summary(task, ui.checkpoint),
"action_buttons": action_buttons,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
}
def build_batch_ui_state(batch: ShippingBatch) -> dict[str, Any]:
"""
构建批次级 UI State。
核心逻辑:批次摘要、焦点任务、任务卡片均包含同源 task ui_state,供右侧工作台统一消费。
"""
tasks = list_sorted_batch_tasks(batch)
focus_task_no = str(batch.current_focus_task_no or "").strip()
focus_task = next((task for task in tasks if task.task_no == focus_task_no), None)
if focus_task is None and tasks:
focus_task = tasks[0]
task_states = [
{
**serialize_task_summary(task),
"ui_state": build_task_ui_state(task),
}
for task in tasks
]
return {
**serialize_batch_summary(batch),
"process_summary": batch.process_summary_json or compute_batch_process_summary(tasks),
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
"focus_task_ui_state": build_task_ui_state(focus_task) if focus_task else None,
"tasks": task_states,
}
+389 -3
View File
@@ -41,7 +41,6 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
/ "shipping_notice" / "shipping_notice"
/ "freight_rpa" / "freight_rpa"
/ "inventory_triggers" / "inventory_triggers"
/ "failed"
/ "inventory_export_SN-20260629-2EDADC77.json" / "inventory_export_SN-20260629-2EDADC77.json"
) )
trigger_dir = tmp_path / "inventory_triggers" trigger_dir = tmp_path / "inventory_triggers"
@@ -104,7 +103,6 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
/ "shipping_notice" / "shipping_notice"
/ "freight_rpa" / "freight_rpa"
/ "inventory_triggers" / "inventory_triggers"
/ "failed"
/ "inventory_export_SN-20260629-2EDADC77.json" / "inventory_export_SN-20260629-2EDADC77.json"
) )
trigger_dir = tmp_path / "inventory_triggers" trigger_dir = tmp_path / "inventory_triggers"
@@ -195,6 +193,395 @@ def test_open_browser_uses_configured_browser_channel(monkeypatch, tmp_path):
} }
def test_is_dsv_username_page_ignores_login_method_page_text():
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
worker = _load_freight_rpa_worker()
class _FakeLocator:
def __init__(self, text: str) -> None:
self._text = text
def inner_text(self, timeout: int | None = None) -> str:
return self._text
class _FakeFrame:
def __init__(self, text: str) -> None:
self._text = text
def locator(self, selector: str) -> _FakeLocator:
assert selector == "body"
return _FakeLocator(self._text)
class _FakePage:
def __init__(self, texts: list[str]) -> None:
self.frames = [_FakeFrame(text) for text in texts]
page = _FakePage(
[
"登录 电子邮箱或SIMS ID或手机号 继续 选择登录方法 密码 输入您的密码并登录。",
]
)
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)
monkeypatch.setattr(worker, "_fill_dsv_username", lambda current_page, username: 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: 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_click_dsv_password_method_reads_device_list_sibling_form(monkeypatch):
"""DSV 第二步的密码选项在 .device-list 中,mfaForm 仅作为提交表单存在。"""
worker = _load_freight_rpa_worker()
evaluated_scripts: list[str] = []
submitted = {"value": False}
class _FakeFrame:
def evaluate(self, script: str, *args, **kwargs):
evaluated_scripts.append(script)
if "fromDeviceList" in script:
assert '.device-list li.mb-2' in script
assert 'form[name="mfaForm"] li.mb-2' not in script
return ["密码 输入您的密码并登录。"]
if "passwordIcon" in script and "document.forms.mfaForm" in script:
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)
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()
evaluated_scripts: list[str] = []
class _FakeLocator:
first = None
def __init__(self) -> None:
self.first = self
def wait_for(self, *args, **kwargs) -> None:
raise RuntimeError("not a method row")
def all(self):
return []
class _FakeFrame:
def locator(self, selector: str) -> _FakeLocator:
return _FakeLocator()
def evaluate(self, script: str, *args, **kwargs):
evaluated_scripts.append(script)
if "fromDeviceList" in script:
return ["Forgot password?", "忘记密码"]
if "isPasswordMethod" in script:
return False
return False
class _FakePage:
frames = [_FakeFrame()]
url = "https://auth.dbschenker.com/mock-password-page"
def locator(self, selector: str) -> _FakeLocator:
return _FakeLocator()
monkeypatch.setattr(worker, "_debug_report", lambda *args, **kwargs: None)
monkeypatch.setattr(worker.time, "sleep", lambda seconds: None)
monkeypatch.setattr(worker.time, "monotonic", iter([0, 11]).__next__)
monkeypatch.setattr(worker, "_wait_for_visible_selector", lambda *args, **kwargs: None)
assert worker._click_dsv_password_method(_FakePage()) is False
assert any("forgot password" in script.lower() for script in evaluated_scripts)
def test_submit_dsv_password_form_supports_vue_type_button_and_hidden_password():
"""第三步密码页使用 Vue type=button 登录按钮,并通过隐藏 pf.pass 提交密码。"""
worker = _load_freight_rpa_worker()
submitted = {"value": False}
class _FakeLocator:
def wait_for(self, state: str, timeout: int | None = None) -> None:
raise RuntimeError("force script fallback")
class _FakeFrame:
def locator(self, selector: str) -> _FakeLocator:
return _FakeLocator()
def evaluate(self, script: str, timeout: int | None = None) -> bool:
assert 'input#password[name="pf.pass"]' in script
assert 'input[name="pf.ok"]' in script
assert 'button[name="login"]' in script
assert "pointerdown" in script
submitted["value"] = True
return True
class _FakePage:
frames = [_FakeFrame()]
assert worker._submit_dsv_password_form(_FakePage()) is True
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}
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:
def locator(self, selector: str) -> _FakeLocator:
return _FakeLocator(selector)
worker._click_dsv_reports_menu(_FakePage())
assert clicked["value"] is True
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 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 "pointerdown" in script
clicked_selectors.append(self.selector)
class _FakePage:
url = "https://auth.dbschenker.com/mock-passkey"
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_click_dsv_view_report_uses_reportviewer_button_id():
"""库存报表页 View Report 按钮来自 SSRS ReportViewer 的固定控件 ID。"""
worker = _load_freight_rpa_worker()
clicked_selectors: list[str] = []
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 != "#ReportViewerMain_ctl08_ctl00":
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_selectors.append(self.selector)
class _FakeFrame:
def locator(self, selector: str) -> _FakeLocator:
return _FakeLocator(selector)
class _FakePage:
frames = [_FakeFrame()]
worker._click_dsv_view_report(_FakePage())
assert clicked_selectors == ["#ReportViewerMain_ctl08_ctl00"]
def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
"""Owner 参数未配置 selector 时,默认使用源码中的 ReportViewer Owner 文本框。"""
worker = _load_freight_rpa_worker()
filled: dict[str, str] = {}
class _FakeText:
first = None
def __init__(self) -> None:
self.first = self
def is_visible(self, timeout: int | None = None) -> bool:
return False
class _FakeFrame:
def evaluate(self, script: str, payload: dict[str, str], timeout: int | None = None) -> bool:
assert "disabled = false" in script
filled[payload["selector"]] = payload["value"]
return True
class _FakePage:
frames = [_FakeFrame()]
def get_by_text(self, text: str, exact: bool = False) -> _FakeText:
return _FakeText()
worker._fill_dsv_filter_if_needed(
_FakePage(),
"FREIGHT_RPA_DSV_OWNER_SELECTOR",
"Owner",
"CADU-0000000100",
)
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_validate_inventory_excel_accepts_real_report_shape(tmp_path):
"""下载完成后必须能打开 Excel,并包含库存报表标题和关键表头。"""
worker = _load_freight_rpa_worker()
path = tmp_path / "inventory.xlsx"
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "LognetAWSOnHandInventoryLoc3lv"
ws.append(["AWS DUB On Hand Inventory by Location"])
ws.append(["Supplier ID", "Supplier", "AWS Sku", "Sku Description"])
for index in range(120):
ws.append(["CADU-0000000100", "Well Trust Precision Technology", f"504-006043-{index:03d}", "Frame"])
wb.save(path)
worker._validate_inventory_excel(path)
def test_validate_inventory_excel_rejects_invalid_download(tmp_path):
"""下载文件太小或不是有效 Excel 时不能回调 success。"""
worker = _load_freight_rpa_worker()
path = tmp_path / "inventory.xlsx"
path.write_bytes(b"not a complete excel")
with pytest.raises(RuntimeError, match="too small|valid Excel"):
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 == []
@pytest.mark.rpa_e2e @pytest.mark.rpa_e2e
def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_path): def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_path):
""" """
@@ -217,7 +604,6 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
/ "shipping_notice" / "shipping_notice"
/ "freight_rpa" / "freight_rpa"
/ "inventory_triggers" / "inventory_triggers"
/ "failed"
/ "inventory_export_SN-20260629-2EDADC77.json" / "inventory_export_SN-20260629-2EDADC77.json"
) )
trigger = json.loads(source_trigger.read_text(encoding="utf-8")) trigger = json.loads(source_trigger.read_text(encoding="utf-8"))
+294 -27
View File
@@ -4,7 +4,7 @@
1. 单/多通知可通过 create_batch 一次建批并生成多 task。 1. 单/多通知可通过 create_batch 一次建批并生成多 task。
2. get_batch_status 返回 focus task 与任务列表。 2. get_batch_status 返回 focus task 与任务列表。
3. switch_focus_task 可在同批次内切换当前任务。 3. switch_focus_task 可在同批次内切换当前任务。
4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。 4. 工作台批量上传通知时仅为可解析文件建任务,并返回 envelope + 文件级摘要。
""" """
from datetime import datetime, timedelta from datetime import datetime, timedelta
@@ -46,6 +46,15 @@ def _workspace_headers(app):
} }
def _unwrap_ok(res):
"""解包 workspace 成功 envelope,减少断言噪音。"""
payload = res.get_json()
assert payload["success"] is True
assert payload["request_id"]
assert payload["timestamp"]
return payload["data"]
def test_create_batch_tasks_and_switch_focus(app, client): def test_create_batch_tasks_and_switch_focus(app, client):
"""验证 batch 建单、状态查询、focus task 切换主流程。""" """验证 batch 建单、状态查询、focus task 切换主流程。"""
headers = _tool_headers(app) headers = _tool_headers(app)
@@ -190,7 +199,7 @@ def test_create_batch_defers_parse_without_structured(app, client):
def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client): def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
"""聊天/工作台批量上传通知时应仅落 raw_text,首轮解析延后到 Dify。""" """聊天/工作台批量上传通知时应返回 envelope,并仅落 raw_text,首轮解析延后到 Dify。"""
headers = _workspace_headers(app) headers = _workspace_headers(app)
res = client.post( res = client.post(
@@ -203,15 +212,30 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
content_type="multipart/form-data", content_type="multipart/form-data",
) )
assert res.status_code == 200 assert res.status_code == 200
data = res.get_json() result = _unwrap_ok(res)
assert data["status"] == "ok" assert result["status"] == "ok"
assert data["batch_no"].startswith("SB-") assert result["batch_no"].startswith("SB-")
assert data["data"]["batch"]["batch_no"] == data["batch_no"] assert result["data"]["batch"]["batch_no"] == result["batch_no"]
assert data["data"]["tasks"][0]["parse_status"] == "deferred" assert result["data"]["tasks"][0]["parse_status"] == "deferred"
assert data["data"]["focus_task"]["task_no"] == data["data"]["tasks"][0]["task_id"] 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": [],
}
with app.app_context(): with app.app_context():
task = ShippingTask.query.filter_by(task_no=data["data"]["tasks"][0]["task_id"]).first() task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).first()
assert task is not None assert task is not None
assert task.raw_content assert task.raw_content
assert task.process_status == "created" assert task.process_status == "created"
@@ -242,10 +266,131 @@ def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(ap
content_type="multipart/form-data", content_type="multipart/form-data",
) )
assert res.status_code == 200 assert res.status_code == 200
data = res.get_json() result = _unwrap_ok(res)
assert data["status"] == "ok" assert result["status"] == "ok"
assert data["data"]["orchestrator_started"] is True assert result["data"]["orchestrator_started"] is True
assert started == [data["batch_no"]] assert started == [result["batch_no"]]
def test_workspace_create_batch_from_notices_skips_failed_files_and_keeps_batch_non_empty(app, client, monkeypatch, tmp_path):
"""部分文件抽取失败时,只为成功文件建任务,并回传 rejected_files 摘要。"""
from app.services.shipping_notice import notice_upload
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
with app.app_context():
batch_count_before = ShippingBatch.query.count()
task_count_before = ShippingTask.query.count()
def fake_extract_notice_text(saved_path: str):
name = str(saved_path).replace("\\", "/")
if name.endswith("/notice-a.txt"):
return "客户:ACME\nA001 x 10", {"warnings": []}
if name.endswith("/notice-b.pdf"):
return "", {"warnings": ["ocr_empty"]}
raise AssertionError(f"unexpected saved_path: {saved_path}")
monkeypatch.setattr(notice_upload, "extract_notice_text", fake_extract_notice_text)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": [
(BytesIO("ok".encode("utf-8")), "notice-a.txt"),
(BytesIO(b"%PDF-1.4"), "notice-b.pdf"),
],
"conversation_id": "conv-workspace-batch-partial",
},
content_type="multipart/form-data",
)
assert res.status_code == 200
result = _unwrap_ok(res)
assert result["status"] == "ok"
assert result["file_summary"]["accepted_count"] == 1
assert result["file_summary"]["rejected_count"] == 1
assert len(result["data"]["tasks"]) == 1
assert result["file_summary"]["accepted_files"][0]["filename"] == "notice-a.txt"
assert result["file_summary"]["rejected_files"] == [
{
"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"],
}
]
with app.app_context():
assert ShippingBatch.query.count() == batch_count_before + 1
assert ShippingTask.query.count() == task_count_before + 1
batch = ShippingBatch.query.filter_by(batch_no=result["batch_no"]).one()
task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).one()
assert batch.file_count == 1
assert batch.current_focus_task_no == task.task_no
assert task.source_file_name == "notice-a.txt"
assert not (tmp_path / "notice_uploads" / "_tmp").exists()
def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_creating_batch(app, client, monkeypatch, tmp_path):
"""全部文件失败或空文本时,应直接报 ValidationError,且不创建空 batch/task。"""
from app.services.shipping_notice import notice_upload
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
with app.app_context():
batch_count_before = ShippingBatch.query.count()
task_count_before = ShippingTask.query.count()
monkeypatch.setattr(
notice_upload,
"extract_notice_text",
lambda saved_path: ("", {"warnings": ["ocr_empty"]}),
)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": [
(BytesIO(b"%PDF-1.4"), "notice-a.pdf"),
(BytesIO(b"%PDF-1.4"), "notice-b.pdf"),
],
"conversation_id": "conv-workspace-batch-all-failed",
},
content_type="multipart/form-data",
)
assert res.status_code == 400
payload = res.get_json()
assert payload["success"] is False
assert payload["error"]["message"] == "all uploaded files failed extraction or contained no parseable text"
assert payload["error"]["details"]["rejected_files"] == [
{
"filename": "notice-a.pdf",
"source_type": "pdf",
"source_file_type": "application/pdf",
"reason": "empty_text",
"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
with app.app_context():
assert ShippingBatch.query.count() == batch_count_before
assert ShippingTask.query.count() == task_count_before
assert not (tmp_path / "notice_uploads" / "_tmp").exists()
def test_parse_notice_empty_result_requires_reupload_instead_of_review(app): def test_parse_notice_empty_result_requires_reupload_instead_of_review(app):
@@ -324,7 +469,7 @@ def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app,
) )
assert res.status_code == 200 assert res.status_code == 200
data = res.get_json() data = _unwrap_ok(res)
assert data["status"] in {"ok", "running"} assert data["status"] in {"ok", "running"}
assert data["data"]["task_no"] == "SN-REPLACE-NOTICE-001" assert data["data"]["task_no"] == "SN-REPLACE-NOTICE-001"
with app.app_context(): with app.app_context():
@@ -426,7 +571,7 @@ def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, cli
res = client.get("/api/workspace/shipping-tasks/SN-RPA-RECHECK-001", headers=headers) res = client.get("/api/workspace/shipping-tasks/SN-RPA-RECHECK-001", headers=headers)
assert res.status_code == 200 assert res.status_code == 200
data = res.get_json() data = _unwrap_ok(res)
assert data["process_status"] == "waiting_inventory" assert data["process_status"] == "waiting_inventory"
assert data["pending_human_reason"] == "rpa_pending" assert data["pending_human_reason"] == "rpa_pending"
with app.app_context(): with app.app_context():
@@ -537,8 +682,8 @@ def test_auto_progress_unknown_destination_requires_inventory_source_review(app)
def test_inventory_source_review_chat_actions_return_source_buttons(app): def test_inventory_source_review_chat_actions_return_source_buttons(app):
"""库存源待确认且只有一个候选时,聊天按钮才携带具体 source_code。""" """库存源待确认且只有一个候选时,统一 UI State 会携带具体 source_code。"""
from app.services.shipping_notice.state_machine import build_chat_actions_payload from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context(): with app.app_context():
task = ShippingTask( task = ShippingTask(
@@ -559,18 +704,19 @@ def test_inventory_source_review_chat_actions_return_source_buttons(app):
}, },
) )
payload = build_chat_actions_payload(task) ui_state = build_task_ui_state(task)
assert payload["checkpoint"] == "inventory_source_review" assert ui_state["checkpoint"] == "inventory_source_review"
first = payload["action_buttons"][0] first = ui_state["action_buttons"][0]
assert first["id"] == "confirm_inventory_source" assert first["id"] == "confirm_inventory_source"
assert first["source_code"] == "DSV360_AWSDU" assert first["source_code"] == "DSV360_AWSDU"
assert first["label"] == "确认:DSV 360 / Dublin / AWSDU - Prod (JDA)" assert first["label"] == "确认:DSV 360 / Dublin / AWSDU - Prod (JDA)"
assert ui_state["current_step"]["code"] == "inventory_prepare"
def test_inventory_source_review_chat_actions_do_not_list_all_sources(app): def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
"""库存源候选很多时,不应把全部数据源铺成按钮。""" """库存源候选很多时,统一 UI State 不应把全部数据源铺成按钮。"""
from app.services.shipping_notice.state_machine import build_chat_actions_payload from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context(): with app.app_context():
task = ShippingTask( task = ShippingTask(
@@ -595,20 +741,141 @@ def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
}, },
) )
payload = build_chat_actions_payload(task) ui_state = build_task_ui_state(task)
source_buttons = [ source_buttons = [
item for item in payload["action_buttons"] item for item in ui_state["action_buttons"]
if item["id"] == "confirm_inventory_source" and item.get("source_code") if item["id"] == "confirm_inventory_source" and item.get("source_code")
] ]
assert source_buttons == [] assert source_buttons == []
assert [item["id"] for item in payload["action_buttons"]] == [ assert [item["id"] for item in ui_state["action_buttons"]] == [
"confirm_inventory_source", "confirm_inventory_source",
"retry_resolve_inventory_source", "retry_resolve_inventory_source",
"upload_inventory_file", "upload_inventory_file",
] ]
def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client):
"""任务/批次工作台读接口直接返回 UI State,Chat 和工作台不再各自推导状态。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch = ShippingBatch(
batch_no="SB-UI-STATE-001",
user_id=user.id,
current_focus_task_no="SN-UI-STATE-001",
file_count=1,
)
task = ShippingTask(
task_no="SN-UI-STATE-001",
source_type="pdf",
user_id=user.id,
batch=batch,
batch_index=1,
batch_total=1,
process_status="pending_review",
review_status="shortage_review",
pending_human_reason="shortage",
)
db.session.add_all([batch, task])
db.session.commit()
task_state_res = client.get("/api/workspace/shipping-tasks/SN-UI-STATE-001/ui-state", headers=headers)
task_detail_res = client.get("/api/workspace/shipping-tasks/SN-UI-STATE-001", headers=headers)
batch_detail_res = client.get("/api/workspace/shipping-batches/SB-UI-STATE-001", headers=headers)
batch_state_res = client.get("/api/workspace/shipping-batches/SB-UI-STATE-001/ui-state", headers=headers)
assert task_state_res.status_code == 200
assert task_detail_res.status_code == 200
assert batch_detail_res.status_code == 200
assert batch_state_res.status_code == 200
task_state = _unwrap_ok(task_state_res)
task_detail = _unwrap_ok(task_detail_res)
batch_detail = _unwrap_ok(batch_detail_res)
batch_state = _unwrap_ok(batch_state_res)
assert task_state["checkpoint"] == "shortage_review"
assert task_detail["ui_state"]["action_buttons"] == task_state["action_buttons"]
assert task_state["current_step"]["status"] == "blocked"
assert batch_detail["focus_task_ui_state"]["task_no"] == "SN-UI-STATE-001"
assert batch_state["focus_task_ui_state"]["task_no"] == "SN-UI-STATE-001"
assert batch_state["tasks"][0]["ui_state"]["action_buttons"] == task_state["action_buttons"]
def test_chat_completions_streams_shipping_ui_state(app, client, monkeypatch):
"""发货通知聊天流应先下发状态机 UI State,前端无需等待 Dify 正文结束才显示按钮。"""
from app.services import dify as dify_module
with app.app_context():
user = User(
username="shipping_stream_user",
email="shipping_stream_user@example.com",
role="user",
status="active",
)
user.set_password("password")
agent = Agent(
name="货代发货通知 Agent",
dify_api_key="test-dify-key",
api_base_url="http://dify.example/v1",
type="api",
is_active=True,
)
user.agents.append(agent)
batch = ShippingBatch(
batch_no="SB-STREAM-UI-STATE",
user_id=user.id,
conversation_id="conv-stream-ui-state",
current_focus_task_no="SN-STREAM-UI-STATE",
file_count=1,
)
task = ShippingTask(
task_no="SN-STREAM-UI-STATE",
batch=batch,
user_id=user.id,
conversation_id="conv-stream-ui-state",
source_type="pdf",
process_status="pending_review",
review_status="shortage_review",
pending_human_reason="shortage",
)
db.session.add_all([user, agent, batch, task])
db.session.commit()
user_id = user.id
agent_id = agent.id
def fake_stream_chat(*args, **kwargs):
yield 'data: {"event":"message","answer":"当前库存不足。"}\n\n'
yield 'data: {"event":"message_end","answer":"","conversation_id":"dify-conv"}\n\n'
monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat))
res = client.post(
"/api/chat/completions",
headers={
"X-User-Id": str(user_id),
"X-Username": "shipping_stream_user",
"X-Role": "user",
"Content-Type": "application/json",
},
json={
"agent_id": agent_id,
"query": "继续处理当前任务",
"conversation_id": "conv-stream-ui-state",
"task_id": "SN-STREAM-UI-STATE",
"batch_no": "SB-STREAM-UI-STATE",
},
)
body = res.get_data(as_text=True)
assert res.status_code == 200
assert '"event": "shipping_ui_state"' in body
assert '"task_no": "SN-STREAM-UI-STATE"' in body
assert '"checkpoint": "shortage_review"' in body
assert '"action_buttons"' in body
def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client): def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client):
"""同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。""" """同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。"""
headers = _workspace_headers(app) headers = _workspace_headers(app)
@@ -698,7 +965,7 @@ def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app,
headers=headers, headers=headers,
) )
assert res.status_code == 200 assert res.status_code == 200
data = res.get_json() data = _unwrap_ok(res)
assert data["conversation_id"] == "conv-workspace-multi" assert data["conversation_id"] == "conv-workspace-multi"
assert data["summary"] == { assert data["summary"] == {
"batch_count": 2, "batch_count": 2,
@@ -767,7 +1034,7 @@ def test_workspace_conversation_batch_workspace_filters_by_user(app, client):
headers=headers, headers=headers,
) )
assert res.status_code == 200 assert res.status_code == 200
data = res.get_json() data = _unwrap_ok(res)
assert data["summary"]["batch_count"] == 1 assert data["summary"]["batch_count"] == 1
assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-OWN"] assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-OWN"]
@@ -2,10 +2,12 @@
覆盖 RPA 库存子模块与 inventory_workflow 的委托边界: 覆盖 RPA 库存子模块与 inventory_workflow 的委托边界:
1. ensure_inventory(mode=auto) 触发 running 并写入 trigger 事件。 1. ensure_inventory(mode=auto) 触发 running 并写入 trigger 事件。
2. rpa_report_inventory 回调落盘后进入字段映射确认。 2. rpa_report_inventory 回调会把文件正式落到 inventory_uploads,并进入字段映射确认。
""" """
from app.models import ShippingTask, ShippingTaskEvent from pathlib import Path
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
def _tool_headers(): def _tool_headers():
@@ -69,6 +71,7 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
drop = tmp_path / "drop" drop = tmp_path / "drop"
drop.mkdir() drop.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop) app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key" app.config["INTEGRATION_API_KEY"] = "test-integration-key"
@@ -104,6 +107,17 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
task = ShippingTask.query.filter_by(task_no=task_id).first() task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None assert task is not None
assert task.process_status == "inventory_ready" assert task.process_status == "inventory_ready"
stored = Path(app.config["SHIPPING_NOTICE_STORAGE_ROOT"]) / "inventory_uploads" / task_id / "inventory.xlsx"
assert 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"
assert Path(inv_file.storage_path).is_file()
assert inv_file.source_file_name == "stock.xlsx"
active_link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).first()
assert active_link is not None
assert active_link.inventory_file_id == inv_file.id
assert task.inventory_snapshot_id == inv_file.id
def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path): def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
+5 -4
View File
@@ -1736,7 +1736,8 @@ def test_parse_inventory_rejects_oversized_text(app, client):
def test_chat_actions_empty_when_task_rejected(app): def test_chat_actions_empty_when_task_rejected(app):
from app.services.shipping_notice.chat_actions import build_chat_actions_payload, human_options_for_task from app.services.shipping_notice.chat_actions import human_options_for_task
from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context(): with app.app_context():
task = ShippingTask( task = ShippingTask(
@@ -1746,7 +1747,7 @@ def test_chat_actions_empty_when_task_rejected(app):
review_status="rejected", review_status="rejected",
) )
assert human_options_for_task(task) == [] assert human_options_for_task(task) == []
payload = build_chat_actions_payload(task) ui_state = build_task_ui_state(task)
assert payload["checkpoint"] == "rejected" assert ui_state["checkpoint"] == "rejected"
assert payload["action_buttons"] == [] assert ui_state["action_buttons"] == []
+1 -10
View File
@@ -6,7 +6,7 @@ import type { Router } from 'vue-router';
import { config } from '@/config'; import { config } from '@/config';
import { adminModulePath } from '@/features/admin/constants/modules'; import { adminModulePath } from '@/features/admin/constants/modules';
import { useAuthStore } from '@/features/auth/stores/auth.store'; import { useAuthStore } from '@/features/auth/stores/auth.store';
import { DEFAULT_CHAT_AGENT_ID, isPublicPath } from '@/shared/constants/routes'; import { isPublicPath } from '@/shared/constants/routes';
export function setupRouterGuards(router: Router): void { export function setupRouterGuards(router: Router): void {
router.beforeEach((to, _from, next) => { router.beforeEach((to, _from, next) => {
@@ -25,15 +25,6 @@ export function setupRouterGuards(router: Router): void {
} }
} }
if (to.path === '/') {
if (auth.isLoggedIn) {
next(`/chat/${DEFAULT_CHAT_AGENT_ID}`);
return;
}
next('/login');
return;
}
if (to.path === '/login' && auth.isLoggedIn) { if (to.path === '/login' && auth.isLoggedIn) {
next('/workspace/applications'); next('/workspace/applications');
return; return;
@@ -9,6 +9,5 @@ export const chatRoutes: RouteRecordRaw[] = [
path: '/chat/:agentId', path: '/chat/:agentId',
name: 'Chat', name: 'Chat',
component: () => import('@/features/chat/views/ChatView.vue'), component: () => import('@/features/chat/views/ChatView.vue'),
props: true,
}, },
]; ];
+10
View File
@@ -8,8 +8,18 @@ import { authRoutes } from './auth.routes';
import { chatRoutes } from './chat.routes'; import { chatRoutes } from './chat.routes';
import { kbRoutes } from './kb.routes'; import { kbRoutes } from './kb.routes';
import { workspaceRoutes } from './workspace.routes'; import { workspaceRoutes } from './workspace.routes';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { DEFAULT_CHAT_AGENT_ID } from '@/shared/constants/routes';
export const appRoutes: RouteRecordRaw[] = [ export const appRoutes: RouteRecordRaw[] = [
{
path: '/',
redirect: () => {
const auth = useAuthStore();
auth.syncFromStorage();
return auth.isLoggedIn ? `/chat/${DEFAULT_CHAT_AGENT_ID}` : '/login';
},
},
...authRoutes, ...authRoutes,
...workspaceRoutes, ...workspaceRoutes,
...chatRoutes, ...chatRoutes,
+16 -9
View File
@@ -7,7 +7,7 @@
import { BusinessError, requestJson } from '@/shared/api/client'; import { BusinessError, requestJson } from '@/shared/api/client';
import type { import type {
ShippingBatchSummary, ShippingBatchSummary,
ShippingChatActionsResponse, ShippingBatchUiState,
ShippingConversationWorkspace, ShippingConversationWorkspace,
ShippingDecisionResponse, ShippingDecisionResponse,
ShippingInventoryUploadResponse, ShippingInventoryUploadResponse,
@@ -17,6 +17,7 @@ import type {
ShippingTaskCreateResponse, ShippingTaskCreateResponse,
ShippingTaskDetail, ShippingTaskDetail,
ShippingTaskSummary, ShippingTaskSummary,
ShippingTaskUiState,
} from '../types/shipping.api.types'; } from '../types/shipping.api.types';
type ShippingApiStatusPayload = { type ShippingApiStatusPayload = {
@@ -75,10 +76,16 @@ export const listShippingChatAgents = () => requestJson<ShippingChatAgentOption[
/** 获取批次详情、批次任务列表与当前焦点任务。 */ /** 获取批次详情、批次任务列表与当前焦点任务。 */
export const getWorkspaceShippingBatch = (batchNo: string) => export const getWorkspaceShippingBatch = (batchNo: string) =>
requestJson<ShippingBatchSummary & { tasks?: ShippingTaskSummary[]; focus_task?: ShippingTaskSummary | null }>( requestJson<ShippingBatchUiState>(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}`, `/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}`,
); );
/** 获取批次级 UI State,供工作台、步骤条和任务卡片统一消费。 */
export const getWorkspaceShippingBatchUiState = (batchNo: string) =>
requestJson<ShippingBatchUiState>(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/ui-state`,
);
/** 获取一个 Agent 会话下的多批次执行工作台快照。 */ /** 获取一个 Agent 会话下的多批次执行工作台快照。 */
export const getWorkspaceShippingConversationBatches = (conversationId: string) => export const getWorkspaceShippingConversationBatches = (conversationId: string) =>
requestJson<ShippingConversationWorkspace>( requestJson<ShippingConversationWorkspace>(
@@ -95,16 +102,14 @@ export const getWorkspaceShippingBatchFocusTask = (batchNo: string) =>
export const getWorkspaceShippingTask = (taskNo: string) => export const getWorkspaceShippingTask = (taskNo: string) =>
requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`); requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
/** 获取单票任务 UI State,后续 Chat 按钮与顶部步骤条统一读取此状态。 */
export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
requestJson<ShippingTaskUiState>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/ui-state`);
/** 生成任务导出文件的前端下载 URL。 */ /** 生成任务导出文件的前端下载 URL。 */
export const workspaceShippingExportUrl = (taskNo: string) => export const workspaceShippingExportUrl = (taskNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`; `/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
/** 获取聊天气泡动作按钮、检查点和 human options。 */
export const getShippingChatActions = (taskNo: string) =>
requestJson<ShippingChatActionsResponse>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/chat-actions`,
);
/** /**
* 上传库存 Excel,并由后端完成解析与 schema preview 生成。 * 上传库存 Excel,并由后端完成解析与 schema preview 生成。
* @param taskNo - 发货任务编号 * @param taskNo - 发货任务编号
@@ -425,8 +430,8 @@ export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent';
export type { export type {
ShippingBatchSummary, ShippingBatchSummary,
ShippingBatchUiState,
ShippingChatAction, ShippingChatAction,
ShippingChatActionsResponse,
ShippingConversationBatch, ShippingConversationBatch,
ShippingConversationWorkspace, ShippingConversationWorkspace,
ShippingConversationWorkspaceSummary, ShippingConversationWorkspaceSummary,
@@ -440,4 +445,6 @@ export type {
ShippingTaskCreateResponse, ShippingTaskCreateResponse,
ShippingTaskDetail, ShippingTaskDetail,
ShippingTaskSummary, ShippingTaskSummary,
ShippingTaskUiState,
ShippingWorkflowStep,
} from '../types/shipping.api.types'; } from '../types/shipping.api.types';
@@ -10,7 +10,7 @@ import { AlertTriangle, List, RefreshCw } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api'; import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
import { useMessage } from '@/shared/composables/useMessage'; import { useMessage } from '@/shared/composables/useMessage';
import { buildShippingWorkflowSteps } from '@/features/chat/shipping'; import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
import type { import type {
ShippingBatchSummary, ShippingBatchSummary,
ShippingConversationWorkspace, ShippingConversationWorkspace,
@@ -102,7 +102,9 @@ const executionStateMeta = computed(() => {
}; };
}); });
const activeTaskSteps = computed(() => buildShippingWorkflowSteps(props.activeTaskDetail)); const activeTaskSteps = computed(() => (
resolveShippingWorkflowSteps(props.activeTaskDetail)
));
const activeStepIndex = computed(() => { const activeStepIndex = computed(() => {
const index = activeTaskSteps.value.findIndex((step) => step.status === 'current' || step.status === 'blocked'); const index = activeTaskSteps.value.findIndex((step) => step.status === 'current' || step.status === 'blocked');
return index >= 0 ? index : Math.max(0, activeTaskSteps.value.length - 1); return index >= 0 ? index : Math.max(0, activeTaskSteps.value.length - 1);
@@ -112,7 +114,7 @@ const activeStepLabel = computed(() => {
return step ? t('chat.shippingNoticeUi.stepHeadline', { return step ? t('chat.shippingNoticeUi.stepHeadline', {
current: activeStepIndex.value + 1, current: activeStepIndex.value + 1,
total: activeTaskSteps.value.length, total: activeTaskSteps.value.length,
label: t(step.label), label: step.label.startsWith('chat.') ? t(step.label) : step.label,
}) : '--'; }) : '--';
}); });
@@ -8,7 +8,7 @@
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { RefreshCw, Target, X } from 'lucide-vue-next'; import { RefreshCw, Target, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { buildShippingWorkflowSteps, type ShippingWorkflowStepItem } from '@/features/chat/shipping'; import { resolveShippingWorkflowSteps, type ShippingWorkflowStepItem } from '@/features/chat/shipping';
import { hasShortageLines } from '@/features/chat/shipping/shippingShortageDetails'; import { hasShortageLines } from '@/features/chat/shipping/shippingShortageDetails';
import type { import type {
ShippingBatchSummary, ShippingBatchSummary,
@@ -126,17 +126,21 @@ const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail) =>
return { text: t('chat.shippingNoticeUi.runningState'), className: 'border-sky-100 bg-sky-50 text-brand-700' }; return { text: t('chat.shippingNoticeUi.runningState'), className: 'border-sky-100 bg-sky-50 text-brand-700' };
}; };
const taskWorkflowSteps = (task: ShippingTaskSummary | ShippingTaskDetail) => (
resolveShippingWorkflowSteps(task)
);
const taskStepNumber = (task: ShippingTaskSummary | ShippingTaskDetail) => const taskStepNumber = (task: ShippingTaskSummary | ShippingTaskDetail) =>
resolveActiveStep(buildShippingWorkflowSteps(task)) + 1; resolveActiveStep(taskWorkflowSteps(task)) + 1;
const taskStepHeadline = (task: ShippingTaskSummary | ShippingTaskDetail) => { const taskStepHeadline = (task: ShippingTaskSummary | ShippingTaskDetail) => {
const steps = buildShippingWorkflowSteps(task); const steps = taskWorkflowSteps(task);
const index = resolveActiveStep(steps); const index = resolveActiveStep(steps);
const step = steps[index]; const step = steps[index];
return step ? t('chat.shippingNoticeUi.stepHeadline', { return step ? t('chat.shippingNoticeUi.stepHeadline', {
current: index + 1, current: index + 1,
total: steps.length, total: steps.length,
label: t(step.label), label: step.label.startsWith('chat.') ? t(step.label) : step.label,
}) : t('chat.shippingNoticeUi.stepFraction', { current: index + 1, total: steps.length }); }) : t('chat.shippingNoticeUi.stepFraction', { current: index + 1, total: steps.length });
}; };
@@ -144,6 +148,13 @@ const currentStepProgress = (task: ShippingTaskSummary | ShippingTaskDetail) =>
task.step_payload?.current_step_progress || null; task.step_payload?.current_step_progress || null;
const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => { const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => {
const uiSummary = task.ui_state?.summary;
if (uiSummary?.title || uiSummary?.message || uiSummary?.error_message) {
return {
title: uiSummary.error_message || uiSummary.title || t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step: taskStepNumber(task) }),
advice: uiSummary.message || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
};
}
const reason = String(task.pending_human_reason || '').trim(); const reason = String(task.pending_human_reason || '').trim();
const reviewStatus = String(task.review_status || '').trim(); const reviewStatus = String(task.review_status || '').trim();
const processStatus = String(task.process_status || '').trim(); const processStatus = String(task.process_status || '').trim();
@@ -226,6 +237,9 @@ const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) =>
}; };
const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail) => { const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail) => {
if (task.ui_state?.action_buttons?.length) {
return task.ui_state.action_buttons.map((action) => action.label).join(' / ');
}
const reason = String(task.pending_human_reason || '').trim(); const reason = String(task.pending_human_reason || '').trim();
const reviewStatus = String(task.review_status || '').trim(); const reviewStatus = String(task.review_status || '').trim();
if (hasShortageLines(task) || reason === 'shortage' || reviewStatus === 'shortage_review') { if (hasShortageLines(task) || reason === 'shortage' || reviewStatus === 'shortage_review') {
@@ -246,7 +260,7 @@ const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail)
return t('chat.shippingNoticeUi.suggestContinue'); return t('chat.shippingNoticeUi.suggestContinue');
}; };
const resolveActiveStep = (steps: ShippingWorkflowStepItem[]) => { const resolveActiveStep = (steps: Array<ShippingWorkflowStepItem | { status: string }>) => {
const activeIndex = steps.findIndex((step) => step.status === 'current' || step.status === 'blocked'); const activeIndex = steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
return activeIndex >= 0 ? activeIndex : Math.max(0, steps.length - 1); return activeIndex >= 0 ? activeIndex : Math.max(0, steps.length - 1);
}; };
@@ -413,7 +427,7 @@ const handleSwitchBatch = (batchNo: string) => {
<div class="my-3"> <div class="my-3">
<div class="scheme-stepper"> <div class="scheme-stepper">
<template v-for="(step, index) in buildShippingWorkflowSteps(task)" :key="step.id"> <template v-for="(step, index) in taskWorkflowSteps(task)" :key="step.id">
<div <div
class="scheme-step-node" class="scheme-step-node"
:class="{ :class="{
@@ -428,7 +442,7 @@ const handleSwitchBatch = (batchNo: string) => {
<span v-else-if="step.status === 'blocked'">!</span> <span v-else-if="step.status === 'blocked'">!</span>
<span v-else>{{ index + 1 }}</span> <span v-else>{{ index + 1 }}</span>
</div> </div>
<div class="scheme-step-label">{{ t(step.label) }}</div> <div class="scheme-step-label">{{ step.label.startsWith('chat.') ? t(step.label) : step.label }}</div>
</div> </div>
</template> </template>
</div> </div>
@@ -13,7 +13,8 @@ defineProps<{
compact?: boolean; compact?: boolean;
}>(); }>();
const { t } = useI18n(); const { t, te } = useI18n();
const displayLabel = (label: string) => (te(label) ? t(label) : label);
const stepClass = (status: ShippingWorkflowStepItem['status']) => { const stepClass = (status: ShippingWorkflowStepItem['status']) => {
if (status === 'completed') return 'border-emerald-200 bg-emerald-50 text-emerald-700'; if (status === 'completed') return 'border-emerald-200 bg-emerald-50 text-emerald-700';
if (status === 'current') return 'border-brand-300 bg-brand-50 text-brand-700'; if (status === 'current') return 'border-brand-300 bg-brand-50 text-brand-700';
@@ -43,7 +44,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
<span class="inline-flex h-5 min-w-5 items-center justify-center rounded-full text-[11px] font-semibold text-white" :class="dotClass(step.status)"> <span class="inline-flex h-5 min-w-5 items-center justify-center rounded-full text-[11px] font-semibold text-white" :class="dotClass(step.status)">
{{ index + 1 }} {{ index + 1 }}
</span> </span>
<span class="text-xs font-semibold">{{ t(step.label) }}</span> <span class="text-xs font-semibold">{{ displayLabel(step.label) }}</span>
</div> </div>
</div> </div>
</div> </div>
@@ -192,26 +192,38 @@ const downloadExcel = async () => {
<span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span> <span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span>
</div> </div>
<div class="grid grid-cols-2 gap-2 md:grid-cols-5"> <div class="grid grid-cols-2 gap-1.5 sm:grid-cols-4 lg:grid-cols-8">
<div class="rounded-xl bg-white/80 px-3 py-2"> <div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="text-xs text-slate-500">总数</div> <div class="whitespace-nowrap text-xs text-slate-500">总数</div>
<div class="text-lg font-bold text-slate-800">{{ run.total_count }}</div> <div class="text-base font-bold text-slate-800">{{ run.total_count }}</div>
</div> </div>
<div class="rounded-xl bg-white/80 px-3 py-2"> <div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="text-xs text-slate-500">已处理</div> <div class="whitespace-nowrap text-xs text-slate-500">已处理</div>
<div class="text-lg font-bold text-sky-700">{{ run.processed_count }}</div> <div class="text-base font-bold text-sky-700">{{ run.processed_count }}</div>
</div> </div>
<div class="rounded-xl bg-white/80 px-3 py-2"> <div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="text-xs text-slate-500">成功</div> <div class="whitespace-nowrap text-xs text-slate-500">成功</div>
<div class="text-lg font-bold text-emerald-700">{{ run.success_count }}</div> <div class="text-base font-bold text-emerald-700">{{ run.success_count }}</div>
</div> </div>
<div class="rounded-xl bg-white/80 px-3 py-2"> <div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="text-xs text-slate-500">失败</div> <div class="whitespace-nowrap text-xs text-slate-500">失败</div>
<div class="text-lg font-bold text-rose-700">{{ run.failed_count }}</div> <div class="text-base font-bold text-rose-700">{{ run.failed_count }}</div>
</div> </div>
<div class="rounded-xl bg-white/80 px-3 py-2"> <div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="text-xs text-slate-500">跳过</div> <div class="whitespace-nowrap text-xs text-slate-500">跳过</div>
<div class="text-lg font-bold text-amber-700">{{ run.skipped_count }}</div> <div class="text-base font-bold text-amber-700">{{ run.skipped_count }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">合格笔数</div>
<div class="text-base font-bold text-emerald-700">{{ run.judgement?.qualified_count ?? 0 }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">不合格笔数</div>
<div class="text-base font-bold text-rose-700">{{ run.judgement?.unqualified_count ?? 0 }}</div>
</div>
<div class="rounded-lg bg-white/80 px-2 py-1.5">
<div class="whitespace-nowrap text-xs text-slate-500">人工判定笔数</div>
<div class="text-base font-bold text-amber-700">{{ run.judgement?.manual_count ?? 0 }}</div>
</div> </div>
</div> </div>
@@ -0,0 +1,99 @@
/**
* features/chat/composables/useChat.spec.ts
* 用途:验证聊天流对发货通知 UI State SSE 事件的消息级回写行为。
* 依赖:vitest、useChat 导出的纯函数、chat.types。
* 逻辑:覆盖 batch_ui_state 到 focus_task_ui_state 的投影、focus 切换时按钮跟随更新,以及已消费按钮消息的防回挂保护。
*/
import { describe, expect, it } from 'vitest';
import { applyShippingUiStateToMessage } from './useChat';
import type { ChatMessage } from '../types/chat.types';
const buildBatchUiStateEvent = (
taskNo: string,
batchNo: string,
actionId: string,
checkpoint = 'ready_export',
) => ({
event: 'shipping_ui_state',
batch_no: batchNo,
batch_ui_state: {
batch_no: batchNo,
current_focus_task_no: taskNo,
tasks: [],
focus_task_ui_state: {
task_no: taskNo,
batch_no: batchNo,
checkpoint,
process_status: 'matched',
review_status: null,
pending_human_reason: null,
match_status: 'fulfillable',
current_step: null,
steps: [],
summary: {
title: '可生成发货文件',
message: '库存匹配已满足发货条件,可以生成发货文件。',
error_message: null,
},
action_buttons: [
{
id: actionId,
label: `动作-${actionId}`,
message: `执行 ${actionId}`,
variant: 'primary' as const,
},
],
updated_at: '2026-07-01T10:00:00+08:00',
},
},
});
describe('useChat shipping_ui_state SSE', () => {
it('hydrates focus task ui state from batch payload and does not reattach used actions', () => {
const message: ChatMessage = {
role: 'assistant',
content: '当前正在处理批次任务',
type: 'shipping-match-result',
payload: { action_buttons: [] },
};
const batchEvent = buildBatchUiStateEvent('SN-UNIT-001', 'SB-UNIT-001', 'generate_excel');
applyShippingUiStateToMessage(message, batchEvent);
expect(message.shipping_ui_state?.task_no).toBe('SN-UNIT-001');
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toHaveLength(1);
expect((message.payload as { shipping_batch_ui_state?: { batch_no?: string } }).shipping_batch_ui_state?.batch_no).toBe('SB-UNIT-001');
message.shipping_actions_used = true;
message.shipping_actions = undefined;
(message.payload as { action_buttons?: unknown[] }).action_buttons = [];
applyShippingUiStateToMessage(message, batchEvent);
expect(message.shipping_ui_state?.checkpoint).toBe('ready_export');
expect(message.shipping_actions).toBeUndefined();
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toEqual([]);
});
it('switches buttons when batch focus task changes from A to B', () => {
const message: ChatMessage = {
role: 'assistant',
content: '请继续处理当前批次',
payload: { action_buttons: [] },
};
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-A', 'SB-FOCUS-001', 'generate_excel'));
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-A');
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-B', 'SB-FOCUS-001', 'retry_upload'));
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['retry_upload']);
expect((message.payload as { shipping_batch_ui_state?: { current_focus_task_no?: string } }).shipping_batch_ui_state?.current_focus_task_no)
.toBe('SN-FOCUS-B');
});
});
@@ -7,6 +7,7 @@ import { useI18n } from 'vue-i18n';
import { getAuthHeaders } from '@/shared/utils/auth'; import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage'; import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types'; import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
export interface SendMessageLifecycleHooks { export interface SendMessageLifecycleHooks {
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>; onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
@@ -77,6 +78,63 @@ const addAttributionParts = (msg: ChatMessage, value: unknown) => {
} }
}; };
/**
* 解析发货通知 SSE 事件中的统一 UI State 载荷。
*
* 核心逻辑:优先读取单票 `ui_state`,批次事件则下钻 `batch_ui_state.focus_task_ui_state`;
* 同时保留批次态原文,供右侧工作台和后续兼容逻辑继续消费。
* @param data - SSE 事件 JSON
* @returns 提炼后的单票 UI State 与原始批次 UI State
*/
export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
uiState?: ShippingTaskUiState;
batchUiState?: ShippingBatchUiState;
} => {
const rawUiState = data.ui_state;
const uiState = rawUiState && typeof rawUiState === 'object'
? rawUiState as ShippingTaskUiState
: undefined;
const rawBatchUiState = data.batch_ui_state;
const batchUiState = rawBatchUiState && typeof rawBatchUiState === 'object'
? rawBatchUiState as ShippingBatchUiState
: undefined;
const focusTaskUiState = batchUiState?.focus_task_ui_state && typeof batchUiState.focus_task_ui_state === 'object'
? batchUiState.focus_task_ui_state
: undefined;
return {
uiState: uiState || focusTaskUiState,
batchUiState,
};
};
/**
* 将发货通知状态机事件同步到当前助手消息。
*
* 说明:shipping_ui_state 是 HXOPS 自有 SSE 事件,不依赖 Dify 正文;收到后立即挂按钮,
* 让用户无需等待 `message_end` 才拿到状态机结果。若该消息按钮已被消费,则只更新状态快照,
* 不重新挂出可点击按钮,避免首帧旧状态覆盖。
*/
export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
const { uiState, batchUiState } = resolveShippingUiStatePayload(data);
if (!uiState) return;
const nextActions = Array.isArray(uiState.action_buttons) && uiState.action_buttons.length
? uiState.action_buttons
: undefined;
msg.shipping_ui_state = uiState;
if (!msg.shipping_actions_used) {
msg.shipping_actions = nextActions;
}
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object' && !msg.shipping_actions_used) {
(msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons = nextActions;
}
msg.payload = {
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
shipping_ui_state: uiState,
...(batchUiState ? { shipping_batch_ui_state: batchUiState } : {}),
};
};
/** /**
* 把 SSE 事件附带的元数据同步到当前消息对象。 * 把 SSE 事件附带的元数据同步到当前消息对象。
* *
@@ -360,9 +418,6 @@ export function useChat() {
while (true) { while (true) {
const { done, value } = await reader.read(); const { done, value } = await reader.read();
if (done) break; if (done) break;
if (ignoreFurtherStreamEvents) {
continue;
}
clearLikelyCompletedStreamTimer(); clearLikelyCompletedStreamTimer();
buffer += decoder.decode(value, { stream: true }); buffer += decoder.decode(value, { stream: true });
@@ -400,7 +455,14 @@ export function useChat() {
} }
const eventName = String(data.event || ''); const eventName = String(data.event || '');
if (eventName === 'message' || eventName === 'agent_message') { if (ignoreFurtherStreamEvents && eventName !== 'shipping_ui_state') {
continue;
}
if (eventName === 'shipping_ui_state') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyShippingUiStateToMessage(botMsg, data);
} else if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) { if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage(); const botMsg = ensureBotMessage();
if (!botMsg) continue; if (!botMsg) continue;
@@ -0,0 +1,64 @@
/**
* features/chat/composables/useChatShipping.spec.ts
* 用途:验证发货批次切换后的默认焦点解析,避免右侧工作台沿用旧批次的 focused task。
* 依赖:vitest、useChatShipping 纯函数导出。
* 逻辑:覆盖 current focus、process summary 回退、首票回退与无任务时清空焦点原因四种路径。
*/
import { describe, expect, it } from 'vitest';
import { resolveShippingBatchFocusState } from './useChatShipping';
describe('useChatShipping batch focus sync', () => {
it('prefers batch current focus task and keeps default reason', () => {
expect(resolveShippingBatchFocusState(
{
current_focus_task_no: 'SN-BATCH-B2',
process_summary: { current_task_no: 'SN-BATCH-B1' },
},
[{ task_no: 'SN-BATCH-B0' }],
'当前聚焦任务',
)).toEqual({
taskNo: 'SN-BATCH-B2',
focusReason: '当前聚焦任务',
});
});
it('falls back to process summary and first task when current focus is absent', () => {
expect(resolveShippingBatchFocusState(
{
current_focus_task_no: '',
process_summary: { current_task_no: 'SN-BATCH-C1' },
},
[{ task_no: 'SN-BATCH-C0' }],
'当前聚焦任务',
)).toEqual({
taskNo: 'SN-BATCH-C1',
focusReason: '当前聚焦任务',
});
expect(resolveShippingBatchFocusState(
{
current_focus_task_no: '',
process_summary: { current_task_no: '' },
},
[{ task_no: 'SN-BATCH-D0' }],
'当前聚焦任务',
)).toEqual({
taskNo: 'SN-BATCH-D0',
focusReason: '当前聚焦任务',
});
});
it('clears focus state when the new batch has no resolvable task', () => {
expect(resolveShippingBatchFocusState(
{
current_focus_task_no: '',
process_summary: { current_task_no: '' },
},
[],
'当前聚焦任务',
)).toEqual({
taskNo: '',
focusReason: '',
});
});
});
@@ -25,7 +25,6 @@ import {
createShippingParseReviewHandlers, createShippingParseReviewHandlers,
createShippingSendHandlers, createShippingSendHandlers,
createShippingUploadHandlers, createShippingUploadHandlers,
extractShippingActionsDirective,
findHistorySessionForShippingTask, findHistorySessionForShippingTask,
findLatestShippingTaskId, findLatestShippingTaskId,
getShippingInventoryMappingPayload, getShippingInventoryMappingPayload,
@@ -42,6 +41,7 @@ import {
getWorkspaceShippingBatch, getWorkspaceShippingBatch,
getWorkspaceShippingTask, getWorkspaceShippingTask,
switchWorkspaceShippingBatchFocusTask, switchWorkspaceShippingBatchFocusTask,
type ShippingBatchUiState,
type ShippingBatchSummary, type ShippingBatchSummary,
type ShippingConversationWorkspace, type ShippingConversationWorkspace,
type ShippingTaskDetail, type ShippingTaskDetail,
@@ -90,6 +90,34 @@ export interface UseChatShippingOptions {
createNewChatView: () => void; createNewChatView: () => void;
} }
/**
* 解析批次切换后的默认焦点状态。
* 核心逻辑:优先取状态机记录的 current focus,其次回退到 process summary 当前任务,再回退到任务列表首票;只有拿到 task_no 才回填默认聚焦原因。
* @param batchSummary - 当前批次摘要
* @param batchTasks - 当前批次任务列表
* @param defaultReason - 批次切换后写入输入栏提示的默认焦点原因
* @returns 供步骤条、按钮与右侧工作台共用的 focus 状态;取不到 task 时返回空焦点
*/
export const resolveShippingBatchFocusState = (
batchSummary: {
current_focus_task_no?: string | null;
process_summary?: { current_task_no?: string | null } | null;
} | null | undefined,
batchTasks: Array<{ task_no?: string | null }> | null | undefined,
defaultReason: string,
) => {
const taskNo = String(
batchSummary?.current_focus_task_no
|| batchSummary?.process_summary?.current_task_no
|| batchTasks?.[0]?.task_no
|| '',
).trim();
return {
taskNo,
focusReason: taskNo ? defaultReason : '',
};
};
/** /**
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。 * 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
* *
@@ -142,8 +170,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
const shippingInventorySelectionTaskId = ref(''); const shippingInventorySelectionTaskId = ref('');
const prepareMarkdownDisplayText = (text: string) => { const prepareMarkdownDisplayText = (text: string) => {
const stripped = isShippingNoticeAgent.value ? extractShippingActionsDirective(text).cleanedText : text; return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value);
return sanitizeShippingConversationText(stripReasoningPrelude(stripped), isShippingNoticeAgent.value);
}; };
// ── 任务编号状态 ────────────────────────────────────────── // ── 任务编号状态 ──────────────────────────────────────────
@@ -172,7 +199,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null; let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
const applyShippingBatchDetail = ( const applyShippingBatchDetail = (
detail: ShippingBatchSummary & { tasks?: ShippingTaskSummary[]; focus_task?: ShippingTaskSummary | null }, detail: ShippingBatchUiState,
fallbackBatchNo: string, fallbackBatchNo: string,
) => { ) => {
const normalizedBatchNo = detail.batch_no || fallbackBatchNo; const normalizedBatchNo = detail.batch_no || fallbackBatchNo;
@@ -200,6 +227,15 @@ export function useChatShipping(options: UseChatShippingOptions) {
if (preferredTaskNo) { if (preferredTaskNo) {
resolvedShippingTaskId.value = preferredTaskNo; resolvedShippingTaskId.value = preferredTaskNo;
} }
if (detail.focus_task && detail.focus_task_ui_state) {
activeShippingTaskDetail.value = {
...(activeShippingTaskDetail.value || {}),
...detail.focus_task,
lines: activeShippingTaskDetail.value?.lines || [],
events: activeShippingTaskDetail.value?.events || [],
ui_state: detail.focus_task_ui_state,
} as ShippingTaskDetail;
}
}; };
const syncShippingBatchSummary = async (batchNo: string) => { const syncShippingBatchSummary = async (batchNo: string) => {
@@ -282,12 +318,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
} else { } else {
await syncShippingBatchSummary(normalizedBatchNo); await syncShippingBatchSummary(normalizedBatchNo);
} }
const nextTaskNo = String( const nextFocusState = resolveShippingBatchFocusState(
shippingBatchSummary.value?.current_focus_task_no shippingBatchSummary.value,
|| shippingBatchSummary.value?.process_summary?.current_task_no shippingBatchTasks.value,
|| shippingBatchTasks.value[0]?.task_no t('chat.shippingNoticeUi.currentFocusDefaultReason'),
|| '', );
).trim(); const nextTaskNo = nextFocusState.taskNo;
focusedShippingTaskNo.value = nextFocusState.taskNo;
shippingFocusReason.value = nextFocusState.focusReason;
if (nextTaskNo) { if (nextTaskNo) {
resolvedShippingTaskId.value = nextTaskNo; resolvedShippingTaskId.value = nextTaskNo;
await syncActiveShippingTaskDetail(nextTaskNo); await syncActiveShippingTaskDetail(nextTaskNo);
@@ -1,4 +1,4 @@
/** /**
* 对话页:当前登录用户展示名、工号与登出/管理入口。 * 对话页:当前登录用户展示名、工号与登出/管理入口。
*/ */
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
@@ -33,7 +33,7 @@ export function useChatPageUser(router: Router) {
const handleLogout = () => { const handleLogout = () => {
logoutAuth(); logoutAuth();
onAuthLogout(); onAuthLogout();
router.push('/'); router.push('/login');
}; };
const goToAdmin = () => { const goToAdmin = () => {
@@ -1,10 +1,9 @@
/** /**
* features/chat/shipping/shippingMenu.ts * features/chat/shipping/shippingMenu.ts
* 用途:发货聊天数字菜单解析、动作按钮合并与决策文本识别(纯函数)。 * 用途:发货聊天数字菜单解析、动作按钮合并与决策文本识别(纯函数)。
* 依赖:shippingText.extractShippingActionsDirective、types/shipping.types。 * 依赖:types/shipping.types。
* 逻辑:useChatShippingSendHandler 在发送前调用;按钮只来自 API 或结构化 HTML 指令,不从自然语言正文猜测。 * 逻辑:useChatShippingSendHandler 在发送前调用;按钮只来自后端状态机 UI State,不从自然语言正文猜测。
*/ */
import { extractShippingActionsDirective, stripShippingActionListByButtons } from './shippingText';
import type { ShippingActionButton, ShippingMenuAction } from '../types/shipping.types'; import type { ShippingActionButton, ShippingMenuAction } from '../types/shipping.types';
/** /**
@@ -76,32 +75,6 @@ export function normalizeApiShippingButtons(
})); }));
} }
/**
* 合并 API 按钮与 HTML 指令,得到最终 action_buttons 与 cleanedText。
*/
export function resolveShippingActionButtons(
content: string,
apiButtons: Array<{ id: string; label: string; message: string; variant?: string; source_code?: string }> | null,
opts?: { apiResolved?: boolean },
) {
const directive = extractShippingActionsDirective(String(content || ''));
if (opts?.apiResolved) {
const buttons = normalizeApiShippingButtons(apiButtons);
return {
buttons,
cleanedText: stripShippingActionListByButtons(directive.cleanedText, buttons),
fromDirective: false,
};
}
if (directive.buttons.length) {
return { buttons: directive.buttons, cleanedText: directive.cleanedText, fromDirective: true };
}
if (apiButtons?.length) {
return { buttons: normalizeApiShippingButtons(apiButtons), cleanedText: directive.cleanedText, fromDirective: false };
}
return { buttons: [], cleanedText: directive.cleanedText, fromDirective: false };
}
/** /**
* 从用户文本与助手上下文识别 submit_decision 所需的 action id。 * 从用户文本与助手上下文识别 submit_decision 所需的 action id。
*/ */
@@ -19,6 +19,13 @@ export interface ShippingWorkflowStepItem {
status: 'completed' | 'current' | 'pending' | 'blocked'; status: 'completed' | 'current' | 'pending' | 'blocked';
} }
type ShippingWorkflowStepSource = {
id?: string | null;
code?: string | null;
label?: string | null;
status?: string | null;
};
export const SHIPPING_WORKFLOW_STEP_LABELS = [ export const SHIPPING_WORKFLOW_STEP_LABELS = [
'chat.shippingNoticeUi.stepper.noticeSubmit', 'chat.shippingNoticeUi.stepper.noticeSubmit',
'chat.shippingNoticeUi.stepper.parseConfirm', 'chat.shippingNoticeUi.stepper.parseConfirm',
@@ -46,6 +53,44 @@ const CURRENT_STEP_INDEX_MAP: Record<string, number> = {
}; };
const TERMINAL_PROCESS_STATUSES = new Set(['uploaded', 'closed']); const TERMINAL_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
const WORKFLOW_STEP_STATUSES = new Set<ShippingWorkflowStepItem['status']>([
'completed',
'current',
'pending',
'blocked',
]);
/**
* 将后端 UI State steps 收窄为 Stepper 可渲染的前端结构。
*/
export function normalizeShippingWorkflowSteps(
steps: ShippingWorkflowStepSource[] | null | undefined,
): ShippingWorkflowStepItem[] {
if (!Array.isArray(steps)) return [];
return steps
.map((step, index) => {
const status = String(step?.status || '').trim();
if (!WORKFLOW_STEP_STATUSES.has(status as ShippingWorkflowStepItem['status'])) {
return null;
}
return {
id: String(step?.id || step?.code || `shipping-step-${index + 1}`),
label: String(step?.label || SHIPPING_WORKFLOW_STEP_LABELS[index] || ''),
status: status as ShippingWorkflowStepItem['status'],
};
})
.filter((step): step is ShippingWorkflowStepItem => !!step);
}
/**
* 优先消费后端状态机 UI State steps;没有时按 task 状态本地推导。
*/
export function resolveShippingWorkflowSteps(
task: (ShippingTaskStepperSource & { ui_state?: { steps?: ShippingWorkflowStepSource[] | null } | null }) | null | undefined,
): ShippingWorkflowStepItem[] {
const uiStateSteps = normalizeShippingWorkflowSteps(task?.ui_state?.steps);
return uiStateSteps.length ? uiStateSteps : buildShippingWorkflowSteps(task);
}
function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number { function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number {
const currentStep = String(task?.current_step || '').trim(); const currentStep = String(task?.current_step || '').trim();
@@ -1,11 +1,11 @@
/** /**
* features/chat/shipping/shippingText.ts * features/chat/shipping/shippingText.ts
* 用途:发货聊天消息文本净化与 HTML 动作指令解析(纯函数,无 Vue 依赖)。 * 用途:发货聊天消息文本净化(纯函数,无 Vue 依赖)。
* 依赖:constants/shippingNoticeActions、types/shipping.types。 * 依赖:constants/shippingNoticeActions、types/shipping.types。
* 逻辑:ChatView 渲染前 sanitize;shippingMenu 解析 <!-- HXOPS_SHIPPING_ACTIONS --> 注释块。 * 逻辑:ChatView 渲染前 sanitize;动作按钮统一来自后端 shipping_ui_state。
*/ */
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET } from '@/constants/shippingNoticeActions'; import { SHIPPING_INTERNAL_STATUS_TOKENS } from '@/constants/shippingNoticeActions';
import type { ShippingActionButton, ShippingActionVariant } from '../types/shipping.types'; import type { ShippingActionButton } from '../types/shipping.types';
/** /**
* 文本归一化用于判断 Agent 正文编号项是否重复描述了结构化按钮。 * 文本归一化用于判断 Agent 正文编号项是否重复描述了结构化按钮。
@@ -249,49 +249,16 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
result = result.replace(quoted, ''); result = result.replace(quoted, '');
result = result.replace(new RegExp(`\`${token}\``, 'gi'), ''); result = result.replace(new RegExp(`\`${token}\``, 'gi'), '');
} }
return stripShippingPlainActionMenu(stripShippingRedundantNumberedActionList(result.replace(/\n{3,}/g, '\n\n').trim())); return stripShippingPlainActionMenu(stripShippingRedundantNumberedActionList(stripShippingActionsDirectiveComment(result).replace(/\n{3,}/g, '\n\n').trim()));
} }
/** /**
* 解析消息中的 HXOPS_SHIPPING_ACTIONS HTML 注释,提取 action_buttons 并返回净化后文本。 * 移除历史 HXOPS_SHIPPING_ACTIONS HTML 注释。
*
* 按钮已经切换为后端状态机 shipping_ui_state,正文注释只作为脏文本清理,不再产生 action_buttons。
*/ */
export function extractShippingActionsDirective(rawText: string): { export function stripShippingActionsDirectiveComment(rawText: string): string {
cleanedText: string; return String(rawText || '').replace(/<!--\s*HXOPS_SHIPPING_ACTIONS\s*:\s*[\s\S]*?\s*-->/gi, '').trim();
buttons: ShippingActionButton[];
} {
const text = String(rawText || '');
const re = /<!--\s*HXOPS_SHIPPING_ACTIONS\s*:\s*([\s\S]*?)\s*-->/gi;
const buttons: ShippingActionButton[] = [];
for (;;) {
const m = re.exec(text);
if (!m) break;
const body = String(m[1] || '').trim();
if (!body) continue;
try {
const parsed = JSON.parse(body);
if (Array.isArray(parsed)) {
for (const item of parsed) {
if (!item || typeof item !== 'object') continue;
const id = String((item as Record<string, unknown>).id || '').trim();
const label = String((item as Record<string, unknown>).label || '').trim();
const message = String((item as Record<string, unknown>).message || '').trim();
const variantRaw = String((item as Record<string, unknown>).variant || '').trim();
const variant: ShippingActionVariant | undefined = (variantRaw === 'primary' || variantRaw === 'secondary' || variantRaw === 'danger')
? (variantRaw as ShippingActionVariant)
: undefined;
if (!id || !label || !message) continue;
if (!SHIPPING_KNOWN_ACTION_ID_SET.has(id)) {
console.warn(`[shipping] unknown action id in HXOPS_SHIPPING_ACTIONS: ${id}`);
}
buttons.push({ id, label, message, variant });
}
}
} catch {
// ignore malformed directive
}
}
const cleaned = text.replace(re, '').trim();
return { cleanedText: cleaned, buttons };
} }
/** /**
@@ -0,0 +1,84 @@
/**
* features/chat/shipping/useChatShippingDecision.spec.ts
* 用途:验证发货通知决策处理器的 silent 模式,避免纯 UI 操作追加本地聊天气泡。
* 依赖:vitest、vue refs、shipping.api、useChatShippingDecision。
* 逻辑:分别覆盖 silent 与普通决策路径,确保 silent 仅更新状态,不写入本地消息或后端消息存档。
*/
import { computed, ref } from 'vue';
import { describe, expect, it, vi } from 'vitest';
import { createShippingDecisionHandlers, type ShippingDecisionContext } from './useChatShippingDecision';
const {
autoProgressWorkspaceShippingTask,
markWorkspaceShippingManualUploaded,
submitWorkspaceShippingDecision,
} = vi.hoisted(() => ({
autoProgressWorkspaceShippingTask: vi.fn(),
markWorkspaceShippingManualUploaded: vi.fn(),
submitWorkspaceShippingDecision: vi.fn(),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
autoProgressWorkspaceShippingTask,
markWorkspaceShippingManualUploaded,
submitWorkspaceShippingDecision,
}));
const createContext = (
overrides: Partial<ShippingDecisionContext> = {},
): ShippingDecisionContext => ({
messages: ref([]),
conversationId: ref('conv-001'),
history: ref([{ conversation_id: 'conv-001' }]),
isShippingNoticeAgent: computed(() => true),
shippingInventorySchemaPreviewCache: ref({}),
getActiveShippingTaskId: () => 'SN-FOCUS-001',
newLocalMessageId: vi.fn((prefix: string) => `${prefix}-local-id`),
saveLocalMessageToBackend: vi.fn(async () => undefined),
loadHistory: vi.fn(async () => undefined),
openShippingInventoryMappingFormForTask: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
msg: {
warning: vi.fn(),
success: vi.fn(),
},
t: (key: string) => key,
...overrides,
});
describe('useChatShippingDecision', () => {
it('does not append local chat messages when decision runs in silent mode', async () => {
submitWorkspaceShippingDecision.mockResolvedValue({
message: '已清除库存快照,请重新上传库存。',
data: {},
});
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('reparse_inventory', '重新上传库存', { silent: true });
expect(ok).toBe(true);
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-FOCUS-001', 'reparse_inventory');
expect(ctx.messages.value).toEqual([]);
expect(ctx.saveLocalMessageToBackend).not.toHaveBeenCalled();
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('keeps appending local chat messages for normal decisions', async () => {
submitWorkspaceShippingDecision.mockResolvedValue({
message: '已确认,请继续下一步。',
data: {},
});
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('confirm', '确认');
expect(ok).toBe(true);
expect(ctx.messages.value).toHaveLength(2);
expect(ctx.messages.value[0]?.role).toBe('user');
expect(ctx.messages.value[1]?.role).toBe('assistant');
expect(ctx.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
});
@@ -29,10 +29,14 @@ export interface ShippingDecisionContext {
t: (key: string, params?: Record<string, unknown>) => string; t: (key: string, params?: Record<string, unknown>) => string;
} }
export interface ExecuteShippingDecisionOptions {
silent?: boolean;
}
/** /**
* 创建发货通知决策处理器。 * 创建发货通知决策处理器。
* *
* 核心逻辑:根据决策类型调用对应后端接口,同步本地用户/助手消息,并在需要时刷新历史与动作按钮。 * 核心逻辑:根据决策类型调用对应后端接口;默认同步本地用户/助手消息,也支持 silent 模式仅更新状态机与按钮。
* @param ctx - 决策处理上下文 * @param ctx - 决策处理上下文
* @returns 人工决策与手工上传确认处理函数 * @returns 人工决策与手工上传确认处理函数
*/ */
@@ -48,7 +52,19 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
} }
}; };
const executeShippingDecision = async (decision: string, displayText?: string) => { /**
* 提交发货人工决策,并按需把结果落为本地聊天消息。
* 核心逻辑:先基于 taskId 调后端决策接口,再根据 silent 选项决定是否写入本地 user/assistant 气泡。
* @param decision - 决策动作 ID,如 confirm、reparse_inventory
* @param displayText - 用户侧展示文案;未传时回退为 decision
* @param options.silent - 为 true 时只更新状态与按钮,不追加本地聊天消息
* @returns 是否成功提交决策
*/
const executeShippingDecision = async (
decision: string,
displayText?: string,
options?: ExecuteShippingDecisionOptions,
) => {
const taskId = ctx.getActiveShippingTaskId(); const taskId = ctx.getActiveShippingTaskId();
if (!taskId) { if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId')); ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
@@ -76,27 +92,29 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
taskId, taskId,
ctx.t('chat.shippingNoticeDecisionDone'), ctx.t('chat.shippingNoticeDecisionDone'),
); );
const userMsg: ChatMessage = { if (!options?.silent) {
role: 'user', const userMsg: ChatMessage = {
type: 'text', role: 'user',
content: `${userText}\n任务编号:${taskId}`, type: 'text',
local_id: ctx.newLocalMessageId('shipping-user'), content: `${userText}\n任务编号:${taskId}`,
local_only: true, local_id: ctx.newLocalMessageId('shipping-user'),
}; local_only: true,
const assistantMsg: ChatMessage = { };
role: 'assistant', const assistantMsg: ChatMessage = {
type: 'text', role: 'assistant',
content: assistantContent, type: 'text',
local_id: ctx.newLocalMessageId('shipping-assistant'), content: assistantContent,
local_only: true, local_id: ctx.newLocalMessageId('shipping-assistant'),
}; local_only: true,
ctx.messages.value.push(userMsg, assistantMsg); };
await ctx.saveLocalMessageToBackend(userMsg, userText); ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(assistantMsg); await ctx.saveLocalMessageToBackend(userMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg);
await syncHistoryIfNeeded();
}
if (result.message && !ctx.isShippingNoticeAgent.value) { if (result.message && !ctx.isShippingNoticeAgent.value) {
ctx.msg.success(result.message); ctx.msg.success(result.message);
} }
await syncHistoryIfNeeded();
void ctx.refreshShippingActions(); void ctx.refreshShippingActions();
if (decision === 'correct_inventory_mapping') { if (decision === 'correct_inventory_mapping') {
await ctx.openShippingInventoryMappingFormForTask(taskId); await ctx.openShippingInventoryMappingFormForTask(taskId);
@@ -0,0 +1,93 @@
/**
* features/chat/shipping/useChatShippingMenuHandler.spec.ts
* 用途:验证发货通知聊天菜单动作分流,避免 UI 按钮误走普通对话链路。
* 依赖:vitest、vue refs、useChatShippingMenuHandler。
* 逻辑:直接调用 createShippingMenuHandlers,覆盖 reparse_inventory 的 silent 决策提交、缺少 task 提示与上传器打开条件。
*/
import { ref } from 'vue';
import { describe, expect, it, vi } from 'vitest';
import { createShippingMenuHandlers, type ShippingMenuHandlerContext } from './useChatShippingMenuHandler';
import type { ChatMessage } from '../types/chat.types';
const createContext = (
overrides: Partial<ShippingMenuHandlerContext> = {},
): ShippingMenuHandlerContext => ({
isThinking: ref(false),
getActiveShippingTaskId: () => 'SN-FOCUS-001',
messages: ref([]),
newLocalMessageId: vi.fn(() => 'local-id'),
saveLocalMessageToBackend: vi.fn(async () => undefined),
sendShippingMenuMessage: vi.fn(async () => undefined),
openShippingInventoryMappingFormForTask: vi.fn(async () => true),
openShippingInventoryPicker: vi.fn(() => true),
openShippingNoticePicker: vi.fn(() => true),
executeShippingDecision: vi.fn(async () => true),
executeShippingManualUpload: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
msg: {
warning: vi.fn(),
info: vi.fn(),
},
t: (key: string) => key,
...overrides,
});
describe('useChatShippingMenuHandler', () => {
it('clears inventory state and opens picker for reparse_inventory without sending chat text', async () => {
const ctx = createContext();
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
const chatMsg = { role: 'assistant', content: '请重新上传库存' } as ChatMessage & { shipping_actions_used?: boolean };
await handleShippingMenuAction(
{ id: 'reparse_inventory', message: '重新上传库存' },
chatMsg,
);
expect(chatMsg.shipping_actions_used).toBe(true);
expect(ctx.executeShippingDecision).toHaveBeenCalledTimes(1);
expect(ctx.executeShippingDecision).toHaveBeenCalledWith('reparse_inventory', '重新上传库存', { silent: true });
expect(ctx.openShippingInventoryPicker).toHaveBeenCalledTimes(1);
expect(ctx.sendShippingMenuMessage).not.toHaveBeenCalled();
});
it('keeps existing missing task warning when reparse_inventory has no active task', async () => {
const ctx = createContext({
getActiveShippingTaskId: () => '',
});
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
await handleShippingMenuAction({ id: 'reparse_inventory', message: '重新上传库存' });
expect(ctx.msg.warning).toHaveBeenCalledWith('chat.shippingNoticeMissingTaskId');
expect(ctx.executeShippingDecision).not.toHaveBeenCalled();
expect(ctx.openShippingInventoryPicker).not.toHaveBeenCalled();
expect(ctx.sendShippingMenuMessage).not.toHaveBeenCalled();
});
it('does not open picker when reparse_inventory decision fails', async () => {
const ctx = createContext({
executeShippingDecision: vi.fn(async () => false),
});
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
await handleShippingMenuAction({ id: 'reparse_inventory', message: '重新上传库存' });
expect(ctx.executeShippingDecision).toHaveBeenCalledWith('reparse_inventory', '重新上传库存', { silent: true });
expect(ctx.openShippingInventoryPicker).not.toHaveBeenCalled();
expect(ctx.sendShippingMenuMessage).not.toHaveBeenCalled();
});
it('does not mark button used when reparse_inventory has no active task', async () => {
const ctx = createContext({
getActiveShippingTaskId: () => '',
});
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
const chatMsg = { role: 'assistant', content: '请重新上传库存' } as ChatMessage & { shipping_actions_used?: boolean };
await handleShippingMenuAction({ id: 'reparse_inventory', message: '重新上传库存' }, chatMsg);
expect(chatMsg.shipping_actions_used).toBeUndefined();
expect(ctx.executeShippingDecision).not.toHaveBeenCalled();
expect(ctx.openShippingInventoryPicker).not.toHaveBeenCalled();
});
});
@@ -29,7 +29,11 @@ export interface ShippingMenuHandlerContext {
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>; openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
openShippingInventoryPicker: () => boolean; openShippingInventoryPicker: () => boolean;
openShippingNoticePicker: () => boolean; openShippingNoticePicker: () => boolean;
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>; executeShippingDecision: (
decision: string,
displayText?: string,
options?: { silent?: boolean },
) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>; executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
refreshShippingActions: () => Promise<void>; refreshShippingActions: () => Promise<void>;
msg: { warning: (text: string) => void; info: (text: string) => void }; msg: { warning: (text: string) => void; info: (text: string) => void };
@@ -330,6 +334,18 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint')); ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
return; return;
} }
if (action.id === 'reparse_inventory') {
if (chatMsg?.shipping_actions_used) return;
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
if (chatMsg) chatMsg.shipping_actions_used = true;
const ok = await ctx.executeShippingDecision('reparse_inventory', action.message, { silent: true });
if (ok) ctx.openShippingInventoryPicker();
return;
}
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) { if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
if (chatMsg?.shipping_actions_used) return; if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true; if (chatMsg) chatMsg.shipping_actions_used = true;
@@ -1,13 +1,26 @@
/** /**
* useChatShippingRefresh.spec.ts * useChatShippingRefresh.spec.ts
* 用途:验证发货动作按钮刷新时的任务定位优先级,避免按 conversation 猜任务导致按钮绑错票。 * 用途:验证发货动作按钮刷新时的任务定位优先级与 focus 切换刷新保护。
* 依赖:vitest、useChatShippingRefresh 纯函数导出。 * 依赖:vitest、vue refs、useChatShippingRefresh 纯函数导出。
* 逻辑:只覆盖任务编号解析优先级,不触碰 Vue 组件或网络请求。 * 逻辑:覆盖任务编号解析优先级,以及批次 focus 变化后应先锁定新 task 再拉取按钮。
*/ */
import { describe, expect, it } from 'vitest'; import { computed, ref } from 'vue';
import { resolvePreferredShippingTaskId } from './useChatShippingRefresh'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createShippingActionsRefresher, resolvePreferredShippingTaskId } from './useChatShippingRefresh';
const { getWorkspaceShippingTaskUiState } = vi.hoisted(() => ({
getWorkspaceShippingTaskUiState: vi.fn(),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
getWorkspaceShippingTaskUiState,
}));
describe('useChatShippingRefresh', () => { describe('useChatShippingRefresh', () => {
beforeEach(() => {
getWorkspaceShippingTaskUiState.mockReset();
});
it('prefers current batch focus task over message and history fallbacks', () => { it('prefers current batch focus task over message and history fallbacks', () => {
expect(resolvePreferredShippingTaskId({ expect(resolvePreferredShippingTaskId({
batchTaskId: 'sn-batch-001', batchTaskId: 'sn-batch-001',
@@ -27,4 +40,66 @@ describe('useChatShippingRefresh', () => {
historyTaskId: '', historyTaskId: '',
})).toBe(''); })).toBe('');
}); });
it('locks onto the latest focus task before refreshing chat buttons', async () => {
getWorkspaceShippingTaskUiState.mockResolvedValue({
task_no: 'SN-FOCUS-B',
batch_no: 'SB-FOCUS-001',
checkpoint: 'ready_export',
process_status: 'matched',
review_status: null,
pending_human_reason: null,
match_status: 'fulfillable',
current_step: null,
steps: [],
summary: {
title: '可生成发货文件',
message: '库存匹配已满足发货条件,可以生成发货文件。',
error_message: null,
},
action_buttons: [
{
id: 'generate_excel',
label: '生成发货文件',
message: '请生成发货文件',
variant: 'primary',
},
],
updated_at: '2026-07-01T10:00:00+08:00',
});
const messages = ref([
{
role: 'assistant' as const,
content: '请继续处理当前批次',
shipping_actions: [
{
id: 'old-action',
label: '旧动作',
message: '旧动作',
variant: 'secondary' as const,
},
],
},
]);
const resolvedShippingTaskId = ref('SN-FOCUS-A');
const { refreshShippingActions } = createShippingActionsRefresher({
isShippingNoticeAgent: computed(() => true),
messages,
conversationId: ref('conv-focus-switch'),
isThinking: ref(false),
history: ref([]),
resolvedShippingTaskId,
shippingTaskIdFromQuery: computed(() => ''),
getActiveBatchTaskId: () => 'SN-FOCUS-B',
});
await refreshShippingActions();
expect(resolvedShippingTaskId.value).toBe('SN-FOCUS-B');
expect(getWorkspaceShippingTaskUiState).toHaveBeenCalledTimes(1);
expect(getWorkspaceShippingTaskUiState).toHaveBeenCalledWith('SN-FOCUS-B');
expect(messages.value[0].shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
expect(messages.value[0].shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
});
}); });
@@ -1,17 +1,17 @@
/** /**
* features/chat/shipping/useChatShippingRefresh.ts * features/chat/shipping/useChatShippingRefresh.ts
* 用途:刷新聊天区发货通知动作按钮,把后端 checkpoint/action_buttons 同步到消息气泡。 * 用途:刷新聊天区发货通知 UI State,把后端状态机 action_buttons 同步到消息气泡。
* 依赖:shipping.api、shippingMenu、shippingTaskId、shippingNoticeActions 常量、chat.types。 * 依赖:shipping.api、shippingTaskId、shippingNoticeActions 常量、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件根据当前 taskId 拉取动作配置并回写到 messages[].shipping_actions。 * 逻辑:由 useChatShipping 调用本文件;本文件只读取后端 /ui-state,不再从 Dify 正文解析按钮。
*/ */
import { getShippingChatActions } from '@/features/chat/api/shipping.api'; import { getWorkspaceShippingTaskUiState } from '@/features/chat/api/shipping.api';
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions'; import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
import { SHIPPING_TASK_ID_RE } from '../constants/shipping'; import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
import { findLatestShippingTaskId } from './shippingTaskId'; import { findLatestShippingTaskId } from './shippingTaskId';
import { resolveShippingActionButtons } from './shippingMenu';
import { stripShippingPlainActionMenu } from './shippingText'; import { stripShippingPlainActionMenu } from './shippingText';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types'; import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ShippingActionButton } from '../types/shipping.types'; import type { ShippingActionButton } from '../types/shipping.types';
import type { ShippingTaskUiState } from '../types/shipping.api.types';
import type { ComputedRef, Ref } from 'vue'; import type { ComputedRef, Ref } from 'vue';
export interface ShippingRefreshContext { export interface ShippingRefreshContext {
@@ -63,7 +63,7 @@ export function assistantMessageHasLaterUserReply(msgs: Array<{ role?: string }>
/** /**
* 创建发货通知动作按钮刷新器。 * 创建发货通知动作按钮刷新器。
* *
* 核心逻辑:优先按 taskId 拉取后端 action_buttons,失败时回退到消息文本指令解析,并在终态 checkpoint 清空旧按钮。 * 核心逻辑:按 taskId 拉取后端 ui_state/action_buttons,并在终态 checkpoint 清空旧按钮。
* @param ctx - 发货通知聊天上下文 * @param ctx - 发货通知聊天上下文
* @returns 动作刷新函数 * @returns 动作刷新函数
*/ */
@@ -108,35 +108,34 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
} }
const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex; const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex;
if (targetAssistantIndex >= 0) { if (targetAssistantIndex >= 0) {
const target = msgs[targetAssistantIndex] as ChatMessage & { shipping_actions?: ShippingActionButton[] }; const target = msgs[targetAssistantIndex] as ChatMessage;
const resolved = resolveShippingActionButtons(String(target.content || ''), null); const cleanedText = stripShippingPlainActionMenu(String(target.content || ''));
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
if (cleanedText !== String(target.content || '').trim()) { if (cleanedText !== String(target.content || '').trim()) {
target.content = cleanedText; target.content = cleanedText;
} }
} }
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null; let apiState: ShippingTaskUiState | null = null;
let apiCheckpoint: string | null = null;
let apiResolved = false; let apiResolved = false;
if (taskId) { if (taskId) {
const seq = ++shippingActionsRequestSeq; const seq = ++shippingActionsRequestSeq;
try { try {
const data = await getShippingChatActions(taskId); const data = await getWorkspaceShippingTaskUiState(taskId);
if (seq === shippingActionsRequestSeq) { if (seq === shippingActionsRequestSeq) {
apiResolved = true; apiResolved = true;
apiCheckpoint = data.checkpoint ? String(data.checkpoint) : null; apiState = data;
apiButtons = data.action_buttons?.length ? data.action_buttons : null;
} }
} catch { } catch {
// keep structured directive buttons if present // keep existing SSE-delivered ui_state if present
} }
} }
const apiCheckpoint = apiState?.checkpoint ? String(apiState.checkpoint) : null;
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) { if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
msgs.forEach((rawMsg) => { msgs.forEach((rawMsg) => {
const m = rawMsg as ChatMessage & { shipping_actions?: unknown }; const m = rawMsg as ChatMessage;
if (m.role === 'assistant') { if (m.role === 'assistant') {
m.shipping_actions = undefined; m.shipping_actions = undefined;
m.shipping_ui_state = apiState || undefined;
} }
}); });
return; return;
@@ -159,23 +158,16 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
} }
let buttons: ShippingActionButton[] = []; let buttons: ShippingActionButton[] = [];
if (index === targetAssistantIndex) { if (index === targetAssistantIndex) {
const resolved = resolveShippingActionButtons( const cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
String(chatMsg.content || ''), if (cleanedText !== String(chatMsg.content || '').trim()) {
apiResolved ? (apiButtons ?? []) : null,
{ apiResolved },
);
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
if (resolved.fromDirective || cleanedText !== String(chatMsg.content || '').trim()) {
chatMsg.content = cleanedText; chatMsg.content = cleanedText;
} }
buttons = resolved.buttons; if (apiState?.action_buttons?.length) {
} else if (!apiResolved) { buttons = apiState.action_buttons;
const resolved = resolveShippingActionButtons(String(chatMsg.content || ''), null); chatMsg.shipping_ui_state = apiState;
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText); } else if (!apiResolved && chatMsg.shipping_ui_state?.action_buttons?.length) {
if (resolved.fromDirective || cleanedText !== String(chatMsg.content || '').trim()) { buttons = chatMsg.shipping_ui_state.action_buttons;
chatMsg.content = cleanedText;
} }
buttons = resolved.buttons;
} else { } else {
chatMsg.content = stripShippingPlainActionMenu(String(chatMsg.content || '')); chatMsg.content = stripShippingPlainActionMenu(String(chatMsg.content || ''));
} }
@@ -5,6 +5,7 @@
* 逻辑:作为 features/chat 域的类型中枢,向上提供页面编排约束,向下约束消息渲染与交互结构。 * 逻辑:作为 features/chat 域的类型中枢,向上提供页面编排约束,向下约束消息渲染与交互结构。
*/ */
import type { LeaveAgentOption } from './leave.types'; import type { LeaveAgentOption } from './leave.types';
import type { ShippingTaskUiState } from './shipping.api.types';
export type { LeaveAgentOption }; export type { LeaveAgentOption };
@@ -35,7 +36,9 @@ export interface ChatMessage {
label: string; label: string;
message: string; message: string;
variant?: 'primary' | 'secondary' | 'danger'; variant?: 'primary' | 'secondary' | 'danger';
source_code?: string;
}>; }>;
shipping_ui_state?: ShippingTaskUiState;
shipping_actions_used?: boolean; shipping_actions_used?: boolean;
/** 流式对话是否因网络/上游中断而附带错误提示 */ /** 流式对话是否因网络/上游中断而附带错误提示 */
stream_error?: boolean; stream_error?: boolean;
@@ -35,6 +35,7 @@ export interface ShippingTaskSummary {
inventory_source_resolution?: Record<string, unknown> | null; inventory_source_resolution?: Record<string, unknown> | null;
created_at?: string | null; created_at?: string | null;
updated_at?: string | null; updated_at?: string | null;
ui_state?: ShippingTaskUiState;
} }
export interface ShippingTaskEvent { export interface ShippingTaskEvent {
@@ -99,6 +100,7 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
parse_confidence?: number | null; parse_confidence?: number | null;
error_message?: string | null; error_message?: string | null;
events: ShippingTaskEvent[]; events: ShippingTaskEvent[];
ui_state?: ShippingTaskUiState;
} }
export interface ShippingChatAction { export interface ShippingChatAction {
@@ -109,13 +111,30 @@ export interface ShippingChatAction {
source_code?: string; source_code?: string;
} }
export interface ShippingChatActionsResponse { export interface ShippingWorkflowStep {
id: string;
code: string;
label: string;
status: 'completed' | 'current' | 'pending' | 'blocked' | string;
}
export interface ShippingTaskUiState {
task_no: string; task_no: string;
batch_no?: string | null;
checkpoint?: string | null; checkpoint?: string | null;
process_status: string; process_status: string;
review_status?: string | null; review_status?: string | null;
pending_human_reason?: string | null; pending_human_reason?: string | null;
match_status?: string | null;
current_step?: ShippingWorkflowStep | null;
steps: ShippingWorkflowStep[];
summary: {
title?: string | null;
message?: string | null;
error_message?: string | null;
};
action_buttons: ShippingChatAction[]; action_buttons: ShippingChatAction[];
updated_at?: string | null;
} }
export interface ShippingBatchSummary { export interface ShippingBatchSummary {
@@ -137,6 +156,12 @@ export interface ShippingBatchSummary {
updated_at?: string | null; updated_at?: string | null;
} }
export interface ShippingBatchUiState extends ShippingBatchSummary {
focus_task?: ShippingTaskSummary | null;
focus_task_ui_state?: ShippingTaskUiState | null;
tasks: ShippingTaskSummary[];
}
export interface ShippingConversationWorkspaceSummary { export interface ShippingConversationWorkspaceSummary {
batch_count: number; batch_count: number;
total: number; total: number;
@@ -23,7 +23,7 @@ import {
type ShippingTaskSummary, type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api'; } from '@/features/chat/api/shipping.api';
import { getAuthHeaders } from '@/shared/utils/auth'; import { getAuthHeaders } from '@/shared/utils/auth';
import { buildShippingWorkflowSteps } from '@/features/chat/shipping'; import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
const props = defineProps<{ const props = defineProps<{
embedded?: boolean; embedded?: boolean;
@@ -108,7 +108,9 @@ const eventLabel = (eventType: string) => {
return te(key) ? t(key) : t('workspace.shippingNotice.eventTypes.system'); return te(key) ? t(key) : t('workspace.shippingNotice.eventTypes.system');
}; };
const detailWorkflowSteps = computed(() => buildShippingWorkflowSteps(detail.value)); const detailWorkflowSteps = computed(() => (
resolveShippingWorkflowSteps(detail.value)
));
const detailStepProgress = computed<ShippingCurrentStepProgress | null>(() => { const detailStepProgress = computed<ShippingCurrentStepProgress | null>(() => {
const payload = detail.value?.step_payload; const payload = detail.value?.step_payload;
if (!payload || typeof payload !== 'object') return null; if (!payload || typeof payload !== 'object') return null;
File diff suppressed because it is too large. Load diff