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:
commit
9c036c825b
39 files changed
+3114
-456
No files matched your search
@@ -1309,6 +1309,77 @@ def chat_completions():
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
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:
|
||||
for chunk in generator:
|
||||
@@ -1369,6 +1440,10 @@ def chat_completions():
|
||||
'total_relay_ms': relay_total_ms,
|
||||
}
|
||||
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:
|
||||
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'}
|
||||
|
||||
@@ -2,18 +2,21 @@
|
||||
api/workspace_shipping_notice.py
|
||||
|
||||
用途:提供 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。
|
||||
"""
|
||||
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.core.auth.context import get_request_id
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
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 (
|
||||
AUTO_CHAIN_FALLBACK,
|
||||
CP_EXPORT_GENERATED,
|
||||
@@ -35,10 +38,39 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task_summary,
|
||||
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__)
|
||||
|
||||
|
||||
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():
|
||||
"""
|
||||
校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。
|
||||
@@ -60,14 +92,14 @@ def workspace_shipping_tasks():
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||
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'])
|
||||
def workspace_shipping_batches():
|
||||
"""列出当前用户的发货批次摘要。"""
|
||||
user = _require_user()
|
||||
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'])
|
||||
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(
|
||||
(ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None))
|
||||
).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'])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
"""
|
||||
接收多份发货通知附件,按文件级抽取结果创建批次并交给后台编排器逐票推进。
|
||||
核心逻辑:先逐文件抽取文本,只有拿到可解析文本的文件才会进入 create_batch_tasks;失败/空文本文件仅回传摘要,不创建空任务。
|
||||
"""
|
||||
user = _require_user()
|
||||
uploads = request.files.getlist('files')
|
||||
if not uploads:
|
||||
@@ -90,50 +125,111 @@ def workspace_create_shipping_batch_from_notices():
|
||||
if not uploads:
|
||||
raise ValidationError('files is required')
|
||||
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()
|
||||
request_id = _workspace_request_id()
|
||||
notice_items: list[dict] = []
|
||||
for upload in uploads:
|
||||
raw = upload.read() or b''
|
||||
filename = upload.filename or 'notice'
|
||||
source_type = guess_source_type(filename)
|
||||
text = ''
|
||||
warnings: list[str] = []
|
||||
try:
|
||||
temp_task_no = f'TMP-{len(notice_items) + 1}'
|
||||
saved_path = save_task_notice_upload(temp_task_no, filename, raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
|
||||
except Exception as exc:
|
||||
warnings = [f'notice_extract_failed:{exc}']
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
warnings.append(f'notice_text_truncated:{limit}')
|
||||
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})
|
||||
payload = {'user_id': user.id, 'conversation_id': conversation_id or None, 'file_count': len(notice_items), 'notice_items': notice_items, 'defer_parse': True}
|
||||
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 '后台已开始逐票处理。'
|
||||
return jsonify(created)
|
||||
accepted_files: list[dict] = []
|
||||
rejected_files: list[dict] = []
|
||||
try:
|
||||
for index, upload in enumerate(uploads, start=1):
|
||||
raw = upload.read() or b''
|
||||
filename = upload.filename or 'notice'
|
||||
source_type = guess_source_type(filename)
|
||||
source_file_type = str(getattr(upload, 'mimetype', '') or '').strip() or None
|
||||
text = ''
|
||||
warnings: list[str] = []
|
||||
meta: dict = {}
|
||||
try:
|
||||
# [STEP 1] 使用请求级唯一临时目录做文件级抽取,避免并发请求串文件且方便 finally 整体清理。
|
||||
saved_path = save_temp_notice_upload(request_id, index, filename, raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
|
||||
except Exception as exc:
|
||||
warnings = [f'notice_extract_failed:{exc}']
|
||||
rejected_files.append({
|
||||
'filename': filename,
|
||||
'source_type': source_type,
|
||||
'source_file_type': source_file_type,
|
||||
'reason': 'extract_failed',
|
||||
'message': 'notice extraction failed',
|
||||
'warnings': warnings,
|
||||
})
|
||||
continue
|
||||
text = str(text or '').strip()
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
warnings.append(f'notice_text_truncated:{limit}')
|
||||
notice_items.append({
|
||||
'source_type': source_type,
|
||||
'source_file_name': filename,
|
||||
'source_file_type': source_file_type,
|
||||
'raw_text': text,
|
||||
'warnings': warnings,
|
||||
})
|
||||
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'])
|
||||
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)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
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})
|
||||
return _ok(build_batch_ui_state(batch))
|
||||
|
||||
@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'])
|
||||
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)
|
||||
if not batch:
|
||||
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'])
|
||||
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)
|
||||
if not focus_task:
|
||||
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'])
|
||||
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')
|
||||
batch.current_focus_task_no = task.task_no
|
||||
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'])
|
||||
def workspace_create_shipping_task():
|
||||
@@ -200,7 +304,7 @@ def workspace_create_shipping_task():
|
||||
if raw_content:
|
||||
payload['raw_content'] = raw_content
|
||||
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'])
|
||||
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)
|
||||
if not text:
|
||||
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:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
@@ -242,7 +346,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
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'])
|
||||
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', {})
|
||||
if isinstance(data, dict):
|
||||
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'])
|
||||
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)
|
||||
if not task:
|
||||
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'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_task_ui_state(task_no: str):
|
||||
"""返回单票任务 UI State;后续 Chat 按钮、顶部步骤条统一消费本接口。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
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'])
|
||||
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()
|
||||
if 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'])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
@@ -321,7 +425,7 @@ def workspace_upload_shipping_inventory(task_no: str):
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
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'])
|
||||
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:
|
||||
raise ValidationError('source_code is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code}))
|
||||
return _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'])
|
||||
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')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
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'])
|
||||
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()
|
||||
if 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'])
|
||||
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()
|
||||
if 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'])
|
||||
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()
|
||||
if 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'])
|
||||
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()
|
||||
if 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'])
|
||||
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()
|
||||
if 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'])
|
||||
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'):
|
||||
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
|
||||
result = {**result, 'data': gen_data}
|
||||
return jsonify(result)
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||
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
|
||||
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
return _ok(matched)
|
||||
data = matched.get('data')
|
||||
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'}}
|
||||
@@ -496,7 +600,7 @@ def workspace_match_shipping_inventory(task_no: str):
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if 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'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
@@ -506,7 +610,7 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
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'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
@@ -516,7 +620,7 @@ def workspace_retry_shipping_upload(task_no: str):
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
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'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
@@ -533,7 +637,7 @@ def workspace_generate_shipping_excel(task_no: str):
|
||||
data = {}
|
||||
result['data'] = data
|
||||
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'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
@@ -556,4 +660,4 @@ def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
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
|
||||
|
||||
用途:chat-actions 相关符号的向后兼容 re-export 入口。
|
||||
用途:发货通知状态机旧模块名的向后兼容 re-export 入口。
|
||||
依赖: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 (
|
||||
@@ -16,10 +16,8 @@ from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
apply_task_transition,
|
||||
build_action_buttons,
|
||||
build_chat_actions_payload,
|
||||
build_checkpoint_catalog,
|
||||
checkpoint_for_task,
|
||||
format_actions_directive,
|
||||
human_options_for_checkpoint,
|
||||
human_options_for_task,
|
||||
human_options_for_task_or_checkpoint,
|
||||
@@ -43,10 +41,8 @@ __all__ = [
|
||||
"action_buttons_for_checkpoint",
|
||||
"apply_task_transition",
|
||||
"build_action_buttons",
|
||||
"build_chat_actions_payload",
|
||||
"build_checkpoint_catalog",
|
||||
"checkpoint_for_task",
|
||||
"format_actions_directive",
|
||||
"human_options_for_checkpoint",
|
||||
"human_options_for_task",
|
||||
"human_options_for_task_or_checkpoint",
|
||||
|
||||
@@ -9,6 +9,7 @@ services/shipping_notice/inventory_file_store.py
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -109,6 +110,57 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
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(
|
||||
task: ShippingTask,
|
||||
inv_file: ShippingInventoryFile,
|
||||
|
||||
@@ -16,6 +16,8 @@ from app import db
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.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 (
|
||||
mark_inventory_source_review,
|
||||
resolve_inventory_source,
|
||||
@@ -427,14 +429,20 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
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()
|
||||
path = Path(file_path) if file_path else find_latest_inventory_file()
|
||||
if not path or not path.is_file():
|
||||
return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在")
|
||||
|
||||
processed = inventory_processed_dir()
|
||||
managed_path = save_task_inventory_local_file(task.task_no, path)
|
||||
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)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
@@ -443,7 +451,18 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
status="running",
|
||||
message="RPA 库存文件已返回,正在读取库存快照",
|
||||
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(
|
||||
task,
|
||||
|
||||
@@ -9,6 +9,7 @@ services/shipping_notice/inventory_upload.py
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -44,6 +45,33 @@ def save_task_inventory_upload(task_no: str, upload: FileStorage) -> 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]:
|
||||
"""读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。"""
|
||||
path = task_inventory_upload_path(task_no)
|
||||
|
||||
@@ -3,13 +3,14 @@ services/shipping_notice/notice_upload.py
|
||||
|
||||
用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。
|
||||
依赖: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
|
||||
|
||||
import base64
|
||||
import re
|
||||
import shutil
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
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
|
||||
|
||||
|
||||
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:
|
||||
"""保存发货通知附件字节流并返回落盘路径。"""
|
||||
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
|
||||
|
||||
|
||||
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:
|
||||
if not data:
|
||||
return ""
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/state_machine.py
|
||||
|
||||
用途:发货通知人工节点(checkpoint)与动作按钮的单一注册表,负责任务 DB 字段与 UI 状态的映射。
|
||||
依赖: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`
|
||||
@@ -13,7 +13,6 @@ services/shipping_notice/state_machine.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
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]]:
|
||||
"""checkpoint → action_buttons 的便捷封装(tool_response 与 Dify fallback 用)。"""
|
||||
"""checkpoint → action_buttons 的便捷封装(状态机 UI payload 用)。"""
|
||||
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:
|
||||
"""无 DB 任务时,仅按 checkpoint id 构造 TaskUiState(Tool 早停响应用)。"""
|
||||
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:
|
||||
"""
|
||||
将 ShippingTask DB 字段映射为 checkpoint + human_options(/chat-actions 核心)。
|
||||
将 ShippingTask DB 字段映射为 checkpoint + human_options,供统一 UI State 读模型消费。
|
||||
|
||||
核心逻辑:终态 → 正向流程节点 → 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
|
||||
|
||||
|
||||
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]:
|
||||
"""导出 checkpoint 注册表供文档/CI 校验(不接入 Dify 画布)。"""
|
||||
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,
|
||||
}
|
||||
@@ -41,7 +41,6 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
/ "shipping_notice"
|
||||
/ "freight_rpa"
|
||||
/ "inventory_triggers"
|
||||
/ "failed"
|
||||
/ "inventory_export_SN-20260629-2EDADC77.json"
|
||||
)
|
||||
trigger_dir = tmp_path / "inventory_triggers"
|
||||
@@ -104,7 +103,6 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
/ "shipping_notice"
|
||||
/ "freight_rpa"
|
||||
/ "inventory_triggers"
|
||||
/ "failed"
|
||||
/ "inventory_export_SN-20260629-2EDADC77.json"
|
||||
)
|
||||
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
|
||||
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"
|
||||
/ "freight_rpa"
|
||||
/ "inventory_triggers"
|
||||
/ "failed"
|
||||
/ "inventory_export_SN-20260629-2EDADC77.json"
|
||||
)
|
||||
trigger = json.loads(source_trigger.read_text(encoding="utf-8"))
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
1. 单/多通知可通过 create_batch 一次建批并生成多 task。
|
||||
2. get_batch_status 返回 focus task 与任务列表。
|
||||
3. switch_focus_task 可在同批次内切换当前任务。
|
||||
4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。
|
||||
4. 工作台批量上传通知时仅为可解析文件建任务,并返回 envelope + 文件级摘要。
|
||||
"""
|
||||
|
||||
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):
|
||||
"""验证 batch 建单、状态查询、focus task 切换主流程。"""
|
||||
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):
|
||||
"""聊天/工作台批量上传通知时应仅落 raw_text,首轮解析延后到 Dify。"""
|
||||
"""聊天/工作台批量上传通知时应返回 envelope,并仅落 raw_text,首轮解析延后到 Dify。"""
|
||||
headers = _workspace_headers(app)
|
||||
|
||||
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",
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data["status"] == "ok"
|
||||
assert data["batch_no"].startswith("SB-")
|
||||
assert data["data"]["batch"]["batch_no"] == data["batch_no"]
|
||||
assert data["data"]["tasks"][0]["parse_status"] == "deferred"
|
||||
assert data["data"]["focus_task"]["task_no"] == data["data"]["tasks"][0]["task_id"]
|
||||
result = _unwrap_ok(res)
|
||||
assert result["status"] == "ok"
|
||||
assert result["batch_no"].startswith("SB-")
|
||||
assert result["data"]["batch"]["batch_no"] == result["batch_no"]
|
||||
assert result["data"]["tasks"][0]["parse_status"] == "deferred"
|
||||
assert result["data"]["focus_task"]["task_no"] == result["data"]["tasks"][0]["task_id"]
|
||||
assert result["file_summary"] == {
|
||||
"total_files": 1,
|
||||
"accepted_count": 1,
|
||||
"rejected_count": 0,
|
||||
"accepted_files": [
|
||||
{
|
||||
"filename": "notice-a.txt",
|
||||
"source_type": "manual",
|
||||
"source_file_type": "text/plain",
|
||||
"text_length": len("客户:ACME\nA001 x 10"),
|
||||
"warnings": [],
|
||||
}
|
||||
],
|
||||
"rejected_files": [],
|
||||
}
|
||||
|
||||
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.raw_content
|
||||
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",
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data["status"] == "ok"
|
||||
assert data["data"]["orchestrator_started"] is True
|
||||
assert started == [data["batch_no"]]
|
||||
result = _unwrap_ok(res)
|
||||
assert result["status"] == "ok"
|
||||
assert result["data"]["orchestrator_started"] is True
|
||||
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):
|
||||
@@ -324,7 +469,7 @@ def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app,
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
data = _unwrap_ok(res)
|
||||
assert data["status"] in {"ok", "running"}
|
||||
assert data["data"]["task_no"] == "SN-REPLACE-NOTICE-001"
|
||||
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)
|
||||
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
data = _unwrap_ok(res)
|
||||
assert data["process_status"] == "waiting_inventory"
|
||||
assert data["pending_human_reason"] == "rpa_pending"
|
||||
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):
|
||||
"""库存源待确认且只有一个候选时,聊天按钮才携带具体 source_code。"""
|
||||
from app.services.shipping_notice.state_machine import build_chat_actions_payload
|
||||
"""库存源待确认且只有一个候选时,统一 UI State 会携带具体 source_code。"""
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
with app.app_context():
|
||||
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"
|
||||
first = payload["action_buttons"][0]
|
||||
assert ui_state["checkpoint"] == "inventory_source_review"
|
||||
first = ui_state["action_buttons"][0]
|
||||
assert first["id"] == "confirm_inventory_source"
|
||||
assert first["source_code"] == "DSV360_AWSDU"
|
||||
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):
|
||||
"""库存源候选很多时,不应把全部数据源铺成按钮。"""
|
||||
from app.services.shipping_notice.state_machine import build_chat_actions_payload
|
||||
"""库存源候选很多时,统一 UI State 不应把全部数据源铺成按钮。"""
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
with app.app_context():
|
||||
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 = [
|
||||
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")
|
||||
]
|
||||
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",
|
||||
"retry_resolve_inventory_source",
|
||||
"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):
|
||||
"""同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。"""
|
||||
headers = _workspace_headers(app)
|
||||
@@ -698,7 +965,7 @@ def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app,
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
data = _unwrap_ok(res)
|
||||
assert data["conversation_id"] == "conv-workspace-multi"
|
||||
assert data["summary"] == {
|
||||
"batch_count": 2,
|
||||
@@ -767,7 +1034,7 @@ def test_workspace_conversation_batch_workspace_filters_by_user(app, client):
|
||||
headers=headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
data = _unwrap_ok(res)
|
||||
assert data["summary"]["batch_count"] == 1
|
||||
assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-OWN"]
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
覆盖 RPA 库存子模块与 inventory_workflow 的委托边界:
|
||||
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():
|
||||
@@ -69,6 +71,7 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
|
||||
drop = tmp_path / "drop"
|
||||
drop.mkdir()
|
||||
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["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()
|
||||
assert task is not None
|
||||
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):
|
||||
|
||||
@@ -1736,7 +1736,8 @@ def test_parse_inventory_rejects_oversized_text(app, client):
|
||||
|
||||
|
||||
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():
|
||||
task = ShippingTask(
|
||||
@@ -1746,7 +1747,7 @@ def test_chat_actions_empty_when_task_rejected(app):
|
||||
review_status="rejected",
|
||||
)
|
||||
assert human_options_for_task(task) == []
|
||||
payload = build_chat_actions_payload(task)
|
||||
assert payload["checkpoint"] == "rejected"
|
||||
assert payload["action_buttons"] == []
|
||||
ui_state = build_task_ui_state(task)
|
||||
assert ui_state["checkpoint"] == "rejected"
|
||||
assert ui_state["action_buttons"] == []
|
||||
|
||||
Reference in new issue
Block a user