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))
|
||||
Reference in new issue
Block a user