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_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'}
+183 -79
View File
@@ -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,
}