Merge branch 'dev' into hugo-shipping-notice
# Conflicts: # backend/app/jobs/queue.py
This commit is contained in:
commit
ce80867d09
89 files changed
+10328
-4126
No files matched your search
+50
-8
@@ -38,6 +38,7 @@ from app.core.errors import (
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||
SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent'
|
||||
|
||||
|
||||
def _can_use_leave_feature(agent_proxy) -> bool:
|
||||
@@ -52,6 +53,28 @@ def _session_title_from_text(text: str) -> str:
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
|
||||
def _user_facing_chat_query(text: str, agent_name: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_name: 当前 Agent 名称,仅对发货通知 Agent 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_name or '').strip() != SHIPPING_NOTICE_AGENT_NAME:
|
||||
return value
|
||||
import re
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
@@ -909,9 +932,23 @@ def get_chat_messages():
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_name = str(getattr(g.current_agent, 'name', '') or '').strip()
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_name)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
if (
|
||||
log.query
|
||||
and log.answer == log.query
|
||||
and (not log.message_type or log.message_type == 'text')
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
@@ -940,10 +977,14 @@ def save_local_message():
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
data = request.get_json() or {}
|
||||
conversation_id = (data.get('conversation_id') or '').strip()
|
||||
role = (data.get('role') or 'assistant').strip()
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
if role == 'user':
|
||||
user_query = user_query or content
|
||||
content = ''
|
||||
|
||||
if not message_type:
|
||||
raise ValidationError('type is required')
|
||||
@@ -1074,6 +1115,7 @@ def chat_completions():
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
query = data.get('query')
|
||||
display_query = str(data.get('display_query') or query or '').strip()
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
@@ -1117,7 +1159,7 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
existing_session.session_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
@@ -1126,13 +1168,13 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
external_conversation_id=conversation_id,
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
else:
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running')
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
|
||||
|
||||
normalized_files: list[dict] | None = None
|
||||
if files is not None:
|
||||
@@ -1199,7 +1241,7 @@ def chat_completions():
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
dify_inputs: dict[str, str] | None = None
|
||||
dify_inputs: dict[str, object] | None = None
|
||||
hxops_turn_id: str | None = None
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
@@ -1230,12 +1272,11 @@ def chat_completions():
|
||||
elif is_shipping_agent:
|
||||
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
|
||||
dify_inputs = build_shipping_notice_dify_inputs(
|
||||
external_conversation_id or session.session_id,
|
||||
session.session_id,
|
||||
task_id=shipping_task_id,
|
||||
batch_no=shipping_batch_no,
|
||||
entry_mode="user_chat",
|
||||
user_message=query,
|
||||
trigger_source="frontend_chat",
|
||||
request_id=request_id,
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
@@ -1247,6 +1288,7 @@ def chat_completions():
|
||||
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
display_query=display_query,
|
||||
)
|
||||
|
||||
def relay_stream():
|
||||
|
||||
@@ -122,7 +122,7 @@ def openapi_dify_yaml():
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。
|
||||
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
@@ -130,7 +130,7 @@ def tool_create_task():
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
|
||||
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
if isinstance(payload.get('notice_items'), list) and payload.get('notice_items'):
|
||||
@@ -222,7 +222,7 @@ def tool_apply_inventory_mapping():
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
|
||||
@@ -230,7 +230,7 @@ def tool_ensure_inventory():
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。
|
||||
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
@@ -238,7 +238,7 @@ def tool_auto_progress():
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
|
||||
@@ -254,7 +254,7 @@ def tool_submit_decision():
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
|
||||
@@ -262,7 +262,7 @@ def tool_generate_shipment_excel():
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
@@ -294,7 +294,7 @@ def tool_get_batch_status():
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
|
||||
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
|
||||
@@ -23,6 +23,7 @@ from app.services.shipping_notice.constants import (
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_for_user,
|
||||
get_conversation_batch_workspace,
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
@@ -51,6 +52,28 @@ def _require_user():
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _maybe_recheck_inventory_rpa_wait(task: ShippingTask | None) -> None:
|
||||
"""
|
||||
工作台查询兜底复查库存 RPA 等待态。
|
||||
|
||||
常规超时/重试由 shipping worker 执行;这里仅在用户查询时发现已超时仍未推进的任务,补偿触发一次幂等复查。
|
||||
"""
|
||||
if not task:
|
||||
return
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait
|
||||
|
||||
maybe_recheck_inventory_rpa_wait(task, source="workspace_query")
|
||||
|
||||
|
||||
def _maybe_recheck_batch_inventory_rpa_wait(batch: ShippingBatch | None) -> None:
|
||||
"""对批次下任务执行工作台查询兜底复查,避免 worker 异常时页面长期停在等待结果。"""
|
||||
if not batch:
|
||||
return
|
||||
for task in batch.tasks or []:
|
||||
_maybe_recheck_inventory_rpa_wait(task)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
@@ -67,6 +90,17 @@ def workspace_shipping_batches():
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(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):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||
user = _require_user()
|
||||
batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter(
|
||||
(ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None))
|
||||
).all()
|
||||
for batch in batches:
|
||||
_maybe_recheck_batch_inventory_rpa_wait(batch)
|
||||
return jsonify(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():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
@@ -131,6 +165,7 @@ def workspace_shipping_batch_detail(batch_no: str):
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
_maybe_recheck_batch_inventory_rpa_wait(batch)
|
||||
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})
|
||||
|
||||
@@ -141,6 +176,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')
|
||||
_maybe_recheck_batch_inventory_rpa_wait(batch)
|
||||
return jsonify(list_tasks_for_batch(batch_no, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||
@@ -150,6 +186,7 @@ def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
_maybe_recheck_batch_inventory_rpa_wait(batch)
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if not focus_task:
|
||||
raise NotFoundError('Focus task not found')
|
||||
@@ -233,6 +270,41 @@ def workspace_create_shipping_task_from_notice():
|
||||
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}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
"""重新上传发货通知并覆盖当前任务,不新建批次/任务。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import task_workflow
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
|
||||
raw = upload.read() or b''
|
||||
filename = upload.filename or 'notice'
|
||||
saved_path = save_task_notice_upload(task.task_no, filename, raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
warnings.append(f'notice_text_truncated:{limit}')
|
||||
task.source_type = guess_source_type(filename) or task.source_type
|
||||
result = task_workflow.replace_task_notice(
|
||||
task,
|
||||
raw_text=text,
|
||||
source_file_name=filename,
|
||||
source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(),
|
||||
warnings=warnings,
|
||||
)
|
||||
data = result.setdefault('data', {})
|
||||
if isinstance(data, dict):
|
||||
data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})}
|
||||
return jsonify(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
"""返回指定任务的详情快照。"""
|
||||
@@ -240,6 +312,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_maybe_recheck_inventory_rpa_wait(task)
|
||||
return jsonify(serialize_task_detail(task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
@@ -277,6 +350,20 @@ def workspace_upload_shipping_inventory(task_no: str):
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(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):
|
||||
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
source_code = str(data.get('source_code') or '').strip()
|
||||
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}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
@@ -448,6 +535,16 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
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'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""用户态重试上传货代系统,直接触发既有 RPA 上传链路。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
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'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
@@ -486,4 +583,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 jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
@@ -160,7 +160,7 @@ class Config:
|
||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||
'shipment_{task_no}_{ts}.xlsx',
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'true').lower() == 'true'
|
||||
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||
@@ -175,13 +175,17 @@ class Config:
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path("FREIGHT_INVENTORY_DROP_DIR", "freight_rpa", "inventory_drop")
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path(
|
||||
"FREIGHT_INVENTORY_DROP_DIR", "shipping_notice", "freight_rpa", "inventory_drop"
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "freight_rpa", "inventory_triggers"
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "shipping_notice", "freight_rpa", "inventory_triggers"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path(
|
||||
"FREIGHT_UPLOAD_QUEUE_DIR", "shipping_notice", "freight_rpa", "upload_queue"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path("FREIGHT_UPLOAD_QUEUE_DIR", "freight_rpa", "upload_queue")
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "freight_rpa", "upload_triggers"
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
|
||||
+244
-44
@@ -1,15 +1,39 @@
|
||||
"""
|
||||
backend/app/jobs/queue.py
|
||||
|
||||
用途:任务入队 API(Wave 2:adapter 至 KbJob + 域内 enqueue 函数)。
|
||||
逻辑:API / services 在创建 KbJob 后调用 enqueue;sync 模式仍由域内函数同步执行。
|
||||
用途:通用后台任务入队、领取与完成状态管理。
|
||||
依赖:models.Job、jobs.types、Flask app.config。
|
||||
逻辑:业务服务调用 enqueue 写入 jobs;worker 调用 claim/finish/fail 完成执行闭环。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app import db
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
ACTIVE_STATUSES = ("queued", "running")
|
||||
TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled")
|
||||
|
||||
|
||||
def _normalize_job_type(job_type: JobType | str) -> str:
|
||||
"""把 JobType 或字符串统一成数据库保存值。"""
|
||||
return str(getattr(job_type, "value", job_type) or "").strip()
|
||||
|
||||
|
||||
def _worker_id() -> str:
|
||||
"""生成当前 worker 标识,用于锁记录和排障。"""
|
||||
try:
|
||||
host = socket.gethostname()
|
||||
except Exception:
|
||||
host = "unknown-host"
|
||||
return f"{host}:{id(db.session)}"
|
||||
|
||||
|
||||
def _find_shipping_notice_job_id(task_no: str) -> int | None:
|
||||
@@ -42,59 +66,59 @@ def _find_shipping_notice_job_id(task_no: str) -> int | None:
|
||||
|
||||
|
||||
def enqueue(
|
||||
job_type: JobType,
|
||||
job_type: JobType | str,
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
domain: str = "default",
|
||||
business_ref: str | None = None,
|
||||
created_by_id: int | None = None,
|
||||
priority: int = 0,
|
||||
max_attempts: int = 3,
|
||||
message: str | None = None,
|
||||
dedupe_active: bool = True,
|
||||
correlation_id: str | None = None,
|
||||
scheduled_at: Any = None,
|
||||
) -> int:
|
||||
"""
|
||||
将任务提交执行并返回 job id(Wave 2 要求 payload 含已持久化的 KbJob id 或发货参数)。
|
||||
核心逻辑:KB/发货任务委托既有 queue_service;未创建 KbJob 的调用方须先写库再 enqueue。
|
||||
将任务写入通用 jobs 队列并返回 job id。
|
||||
|
||||
Args:
|
||||
job_type: 任务类型。
|
||||
payload: 任务参数;KB 类须含 job_id,发货类须含 task_no。
|
||||
correlation_id: 关联业务 id(预留,当前未写入 KbJob)。
|
||||
scheduled_at: 延迟执行时间(预留)。
|
||||
Returns:
|
||||
KbJob 主键。
|
||||
Raises:
|
||||
ValidationError: 参数缺失或域 enqueue 失败。
|
||||
payload: JSON payload。
|
||||
domain: 业务域,如 shipping_notice。
|
||||
business_ref: 业务幂等锚点,如发货任务号。
|
||||
created_by_id: 创建人。
|
||||
priority: 优先级,数值越大越先执行。
|
||||
max_attempts: 最大尝试次数。
|
||||
message: 初始状态说明。
|
||||
dedupe_active: 是否复用 active 状态的同业务任务。
|
||||
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
|
||||
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
|
||||
"""
|
||||
_ = correlation_id, scheduled_at # Wave 4 通用 Job 表再使用
|
||||
normalized_type = _normalize_job_type(job_type)
|
||||
normalized_domain = str(domain or "").strip() or "default"
|
||||
normalized_ref = str(business_ref or correlation_id or "").strip() or None
|
||||
if not normalized_type:
|
||||
raise ValueError("job_type is required")
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("payload must be a dict")
|
||||
|
||||
if job_type in (JobType.KB_CLEAN, JobType.KB_DIFY_SYNC):
|
||||
job_id = payload.get('job_id')
|
||||
if not job_id:
|
||||
raise ValidationError('enqueue KB job 须在 payload 中提供 job_id(先创建 KbJob)')
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job
|
||||
|
||||
ok, msg = enqueue_kb_job(int(job_id))
|
||||
if not ok:
|
||||
raise ValidationError(f'KB job enqueue failed: {msg}')
|
||||
return int(job_id)
|
||||
|
||||
if job_type == JobType.SHIPPING_NOTICE_RUN:
|
||||
task_no = str(payload.get('task_no') or '').strip()
|
||||
if not task_no:
|
||||
raise ValidationError('enqueue shipping job 须在 payload 中提供 task_no')
|
||||
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||
|
||||
ok, msg = enqueue_shipping_notice_job(
|
||||
task_no=task_no,
|
||||
created_by_id=payload.get('created_by_id'),
|
||||
batch_no=payload.get('batch_no'),
|
||||
if dedupe_active and normalized_ref:
|
||||
existing = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == normalized_domain,
|
||||
Job.job_type == normalized_type,
|
||||
Job.business_ref == normalized_ref,
|
||||
Job.status.in_(ACTIVE_STATUSES),
|
||||
)
|
||||
.order_by(Job.created_at.desc(), Job.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not ok:
|
||||
raise ValidationError(f'shipping job enqueue failed: {msg}')
|
||||
# sync/worker/already_queued 均需按 task_no 精确回查,避免返回其他发货任务的 id。
|
||||
if payload.get('job_id'):
|
||||
return int(payload['job_id'])
|
||||
job_id = _find_shipping_notice_job_id(task_no)
|
||||
if job_id:
|
||||
return job_id
|
||||
raise ValidationError(f'shipping job enqueue ambiguous: {msg}')
|
||||
if existing:
|
||||
return int(existing.id)
|
||||
|
||||
<<<<<<< HEAD
|
||||
raise ValidationError(f'JobType {job_type} enqueue not implemented in Wave 2')
|
||||
|
||||
|
||||
@@ -145,3 +169,179 @@ def enqueue_shipping_notice_job(
|
||||
created_by_id=created_by_id,
|
||||
batch_no=batch_no,
|
||||
)
|
||||
=======
|
||||
now = datetime.utcnow()
|
||||
queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now
|
||||
job = Job(
|
||||
domain=normalized_domain,
|
||||
job_type=normalized_type,
|
||||
status="queued",
|
||||
priority=int(priority or 0),
|
||||
business_ref=normalized_ref,
|
||||
payload_json=payload,
|
||||
progress=0,
|
||||
message=message or "等待后台处理",
|
||||
attempts=0,
|
||||
max_attempts=max(1, int(max_attempts or 1)),
|
||||
created_by_id=created_by_id,
|
||||
created_at=queue_at,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
return int(job.id)
|
||||
|
||||
|
||||
def recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int:
|
||||
"""回收指定业务域内超时 running 的通用任务。"""
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=float(timeout_seconds))
|
||||
query = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == domain,
|
||||
Job.status == "running",
|
||||
Job.started_at.isnot(None),
|
||||
Job.started_at < cutoff,
|
||||
)
|
||||
)
|
||||
normalized_type = _normalize_job_type(job_type) if job_type else ""
|
||||
if normalized_type:
|
||||
query = query.filter(Job.job_type == normalized_type)
|
||||
stale_jobs = query.order_by(Job.started_at.asc(), Job.id.asc()).all()
|
||||
if not stale_jobs:
|
||||
return 0
|
||||
|
||||
now = datetime.utcnow()
|
||||
for job in stale_jobs:
|
||||
if int(job.attempts or 0) < int(job.max_attempts or 1):
|
||||
job.status = "queued"
|
||||
job.message = "任务执行超时,已回收等待重试"
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.started_at = None
|
||||
job.updated_at = now
|
||||
continue
|
||||
job.status = "failed"
|
||||
job.error_message = f"任务执行超时(超过 {int(timeout_seconds)}s)"
|
||||
job.message = job.error_message
|
||||
job.progress = 100
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.finished_at = now
|
||||
job.updated_at = now
|
||||
db.session.commit()
|
||||
return len(stale_jobs)
|
||||
|
||||
|
||||
def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
|
||||
"""原子领取指定业务域下一条 queued 任务。"""
|
||||
normalized_types = [_normalize_job_type(item) for item in (job_types or []) if _normalize_job_type(item)]
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
query = db.session.query(Job).filter(
|
||||
Job.domain == domain,
|
||||
Job.status == "queued",
|
||||
Job.created_at <= now,
|
||||
)
|
||||
if normalized_types:
|
||||
query = query.filter(Job.job_type.in_(normalized_types))
|
||||
job = (
|
||||
query.order_by(Job.priority.desc(), Job.created_at.asc(), Job.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.first()
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
|
||||
if not job:
|
||||
db.session.rollback()
|
||||
return None
|
||||
|
||||
job.status = "running"
|
||||
job.started_at = job.started_at or now
|
||||
job.locked_at = now
|
||||
job.locked_by = worker_id or _worker_id()
|
||||
job.attempts = int(job.attempts or 0) + 1
|
||||
job.progress = max(int(job.progress or 0), 1)
|
||||
job.message = "worker 已领取任务"
|
||||
job.updated_at = now
|
||||
db.session.commit()
|
||||
return job
|
||||
|
||||
|
||||
def finish_job(job: Job, *, result: dict[str, Any] | None = None, message: str | None = None) -> None:
|
||||
"""标记任务成功完成。"""
|
||||
now = datetime.utcnow()
|
||||
job.status = "success"
|
||||
job.progress = 100
|
||||
job.result_json = result or {}
|
||||
job.message = message or "任务处理完成"
|
||||
job.error_message = None
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.finished_at = now
|
||||
job.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None:
|
||||
"""标记任务失败;retryable 且未达上限时重新排队。"""
|
||||
now = datetime.utcnow()
|
||||
can_retry = retryable and int(job.attempts or 0) < int(job.max_attempts or 1)
|
||||
job.status = "queued" if can_retry else "failed"
|
||||
job.progress = 0 if can_retry else 100
|
||||
job.result_json = result or {}
|
||||
job.error_message = str(error or "job failed")[:1000]
|
||||
job.message = "任务失败,等待重试" if can_retry else job.error_message
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.finished_at = None if can_retry else now
|
||||
job.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def process_next_job(
|
||||
*,
|
||||
ctx: Any,
|
||||
domain: str,
|
||||
job_types: list[str | JobType] | None = None,
|
||||
timeout_config_key: str | None = None,
|
||||
default_timeout_seconds: float = 300,
|
||||
) -> tuple[bool, str]:
|
||||
"""领取并分发一条通用任务。"""
|
||||
import app.jobs.handlers # noqa: F401
|
||||
from app.jobs.registry import get_handler
|
||||
|
||||
timeout_seconds = float(
|
||||
current_app.config.get(timeout_config_key, default_timeout_seconds)
|
||||
if timeout_config_key
|
||||
else default_timeout_seconds
|
||||
)
|
||||
recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
|
||||
job = claim_next_job(domain=domain, job_types=job_types)
|
||||
if not job:
|
||||
return False, "no_job"
|
||||
|
||||
job_id = int(job.id)
|
||||
job_type_value = str(job.job_type or "").strip()
|
||||
payload = dict(job.payload_json or {})
|
||||
payload.setdefault("job_id", job_id)
|
||||
handler = get_handler(JobType(job_type_value))
|
||||
if handler is None:
|
||||
fail_job(job, error=f"no handler registered for {job.job_type}")
|
||||
return True, "missing_handler"
|
||||
|
||||
try:
|
||||
handler(ctx, payload)
|
||||
refreshed = db.session.get(Job, job_id)
|
||||
if refreshed and refreshed.status == "running":
|
||||
finish_job(refreshed, message="任务处理完成")
|
||||
return True, job_type_value
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
refreshed = db.session.get(Job, job_id)
|
||||
if refreshed:
|
||||
fail_job(refreshed, error=str(exc), retryable=True)
|
||||
raise
|
||||
>>>>>>> hugo-shipping-notice
|
||||
@@ -11,14 +11,17 @@ from app.models.base import Base, user_agent_permissions
|
||||
from app.models.chat import ChatLog, ChatSession, Feedback, GeneralFeedback
|
||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||
from app.models.department import Department
|
||||
from app.models.job import Job
|
||||
from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob
|
||||
from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.models.settings import AppSetting
|
||||
from app.models.shipping import (
|
||||
ShippingBatch,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryMapping,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
@@ -48,6 +51,7 @@ __all__ = [
|
||||
'KbDocument',
|
||||
'KbDocumentVersion',
|
||||
'KbJob',
|
||||
'Job',
|
||||
'KbDifySyncRecord',
|
||||
'WecomCallbackAudit',
|
||||
'ScheduleTask',
|
||||
@@ -56,6 +60,8 @@ __all__ = [
|
||||
'ShippingBatch',
|
||||
'ShippingTask',
|
||||
'ShippingTaskEvent',
|
||||
'ShippingInventoryFile',
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingInventoryMapping',
|
||||
'AgentGuide',
|
||||
]
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
backend/app/models/job.py
|
||||
|
||||
用途:通用后台任务模型,承载跨业务域的异步任务执行状态。
|
||||
依赖:models.base.Base。
|
||||
逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Job(Base):
|
||||
"""
|
||||
通用后台任务
|
||||
用途:承载非知识库专属的后台任务队列与执行记录
|
||||
"""
|
||||
|
||||
__tablename__ = 'jobs'
|
||||
__table_args__ = (
|
||||
Index('ix_jobs_domain_status_created', 'domain', 'status', 'created_at'),
|
||||
Index('ix_jobs_type_status_created', 'job_type', 'status', 'created_at'),
|
||||
Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'),
|
||||
Index('ix_jobs_locked_at', 'locked_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
domain: Mapped[str] = mapped_column(String(64), index=True)
|
||||
job_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
priority: Mapped[int] = mapped_column(Integer, default=0, index=True)
|
||||
business_ref: Mapped[Optional[str]] = mapped_column(String(128))
|
||||
payload_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
result_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
progress: Mapped[int] = mapped_column(Integer, default=0)
|
||||
message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
attempts: Mapped[int] = mapped_column(Integer, default=0)
|
||||
max_attempts: Mapped[int] = mapped_column(Integer, default=3)
|
||||
locked_by: Mapped[Optional[str]] = mapped_column(String(128))
|
||||
locked_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
created_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[created_by_id])
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/models/shipping.py
|
||||
|
||||
用途:货代发货通知批次、任务、事件与库存映射模型。
|
||||
用途:货代发货通知批次、任务、事件、库存文件与库存映射模型。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import DateTime, Float, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
@@ -136,6 +136,65 @@ class ShippingTaskEvent(Base):
|
||||
task: Mapped['ShippingTask'] = relationship('ShippingTask', back_populates='events')
|
||||
|
||||
|
||||
class ShippingInventoryFile(Base):
|
||||
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_files'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_inventory_files_batch_created', 'batch_id', 'created_at'),
|
||||
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
line_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
batch: Mapped[Optional['ShippingBatch']] = relationship('ShippingBatch', foreign_keys=[batch_id])
|
||||
links: Mapped[List['ShippingTaskInventoryLink']] = relationship(
|
||||
'ShippingTaskInventoryLink',
|
||||
back_populates='inventory_file',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingTaskInventoryLink(Base):
|
||||
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
|
||||
|
||||
__tablename__ = 'shipping_task_inventory_links'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
|
||||
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
|
||||
link_role: Mapped[str] = mapped_column(String(32), default='member')
|
||||
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
|
||||
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped['ShippingTask'] = relationship('ShippingTask', foreign_keys=[task_id])
|
||||
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
|
||||
'ShippingInventoryFile',
|
||||
back_populates='links',
|
||||
foreign_keys=[inventory_file_id],
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryMapping(Base):
|
||||
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
backend/app/services/chat/hxops_context.py
|
||||
|
||||
用途:构建 HXOPS -> Dify 的平台统一上下文注入协议。
|
||||
依赖:无业务域依赖,仅提供平台级上下文结构与 refs 规范化工具。
|
||||
逻辑:由聊天入口、后台编排器或各 Agent 适配层调用本模块,统一生成 hxops_context,
|
||||
避免各业务目录重复定义 Dify Start 输入协议。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
HXOPS_CONTEXT_INPUT = "hxops_context"
|
||||
HXOPS_CONTEXT_SCHEMA_VERSION = "1"
|
||||
|
||||
|
||||
def build_ref(field: str, value: str | None) -> dict[str, str] | None:
|
||||
"""构建单个业务对象引用;缺值时返回 None。"""
|
||||
normalized_field = str(field or "").strip()
|
||||
normalized_value = str(value or "").strip()
|
||||
if not normalized_field or not normalized_value:
|
||||
return None
|
||||
return {"field": normalized_field, "value": normalized_value}
|
||||
|
||||
|
||||
def build_hxops_context(
|
||||
*,
|
||||
session_id: str,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
locale: str | None = None,
|
||||
refs: list[dict[str, str] | None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建平台统一的 hxops_context。
|
||||
|
||||
设计约束:
|
||||
- 只注入平台基础信息与当前已知对象锚点
|
||||
- 不注入 query/files 等 Dify 原生输入
|
||||
- 不注入 checkpoint/stage 等运行态状态
|
||||
"""
|
||||
normalized_session_id = str(session_id or "").strip()
|
||||
if not normalized_session_id:
|
||||
return {}
|
||||
|
||||
request_payload: dict[str, str] = {}
|
||||
normalized_request_id = str(request_id or "").strip()
|
||||
normalized_trigger_source = str(trigger_source or "").strip()
|
||||
normalized_locale = str(locale or "").strip()
|
||||
if normalized_request_id:
|
||||
request_payload["id"] = normalized_request_id
|
||||
if normalized_trigger_source:
|
||||
request_payload["trigger_source"] = normalized_trigger_source
|
||||
if normalized_locale:
|
||||
request_payload["locale"] = normalized_locale
|
||||
|
||||
normalized_refs: list[dict[str, str]] = []
|
||||
seen_fields: set[str] = set()
|
||||
for item in refs or []:
|
||||
if not item:
|
||||
continue
|
||||
field = str(item.get("field") or "").strip()
|
||||
value = str(item.get("value") or "").strip()
|
||||
if not field or not value or field in seen_fields:
|
||||
continue
|
||||
normalized_refs.append({"field": field, "value": value})
|
||||
seen_fields.add(field)
|
||||
|
||||
return {
|
||||
"schema_version": HXOPS_CONTEXT_SCHEMA_VERSION,
|
||||
"session": {"id": normalized_session_id},
|
||||
"request": request_payload,
|
||||
"refs": normalized_refs,
|
||||
}
|
||||
|
||||
@@ -513,6 +513,8 @@ class DifyService:
|
||||
hxops_turn_id: str | None = None,
|
||||
files: list[dict[str, Any]] | None = None,
|
||||
inputs: dict[str, Any] | None = None,
|
||||
persist_chat_log: bool = True,
|
||||
display_query: str | None = None,
|
||||
):
|
||||
"""
|
||||
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
|
||||
@@ -537,6 +539,7 @@ class DifyService:
|
||||
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
||||
url = DifyService._build_chat_messages_url(base_url)
|
||||
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
|
||||
visible_query = str(display_query or query or '').strip()
|
||||
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
@@ -593,6 +596,8 @@ class DifyService:
|
||||
return None
|
||||
|
||||
def persist_stream_chat(data: dict, event_name: str) -> None:
|
||||
if not persist_chat_log:
|
||||
return
|
||||
result = persist_stream_chat_async(data, event_name)
|
||||
if isinstance(result, dict):
|
||||
if result.get("chat_log_id") is not None:
|
||||
@@ -645,7 +650,7 @@ class DifyService:
|
||||
session_id=session_id,
|
||||
hxops_turn_id=hxops_turn_id,
|
||||
normalized_conversation_id=normalized_conversation_id,
|
||||
query=query,
|
||||
query=visible_query,
|
||||
answer_text=answer_snapshot,
|
||||
latency=latency_snapshot,
|
||||
retriever_resources=resources_snapshot,
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/batch_orchestrator.py
|
||||
|
||||
用途:发货通知批次/单票后台编排器。
|
||||
依赖:query_service、task_workflow、dify_executor、shipping_notice.tools、tool_common。
|
||||
逻辑:工作台上传后由后端主导单票调度;批次线程只做任务派发,created 票通过 Dify 完成 AI 解析,其余确定性步骤由后端 auto_progress 推进。
|
||||
逻辑:工作台上传后由后端主导单票调度;批次线程只做任务派发,created 票通过 Dify 完成单票 AI 解析,其余确定性步骤由后端 auto_progress 推进。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,12 +14,17 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
<<<<<<< HEAD
|
||||
from app.jobs import enqueue_shipping_notice_job
|
||||
=======
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||
>>>>>>> hugo-shipping-notice
|
||||
from app.services.shipping_notice.dify_executor import run_shipping_parse_via_dify
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks
|
||||
from app.services.shipping_notice.task_workflow import recompute_batch_summary
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, cfg_bool, cfg_int, log_task_event
|
||||
from app.services.shipping_notice.tools import auto_progress
|
||||
from app.services.shipping_notice.tools import auto_progress, submit_decision
|
||||
|
||||
_RUNNING_BATCHES: set[str] = set()
|
||||
_RUNNING_TASKS: set[str] = set()
|
||||
@@ -59,10 +64,17 @@ def _unmark_running(bucket: set[str], key: str) -> None:
|
||||
|
||||
def _should_orchestrate_task(task: Any) -> bool:
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason in {"", PH_RPA_PENDING}
|
||||
):
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
if process_status in {"waiting_inventory", "waiting_upload", "upload_failed"}:
|
||||
@@ -73,10 +85,13 @@ def _should_orchestrate_task(task: Any) -> bool:
|
||||
def _is_retryable_task(task: Any) -> bool:
|
||||
"""判断任务是否允许由批次重试入口重新派发。"""
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if process_status == "waiting_inventory" and pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}:
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
return True
|
||||
@@ -95,7 +110,8 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
"""
|
||||
后台执行单票任务的一轮推进。
|
||||
|
||||
`created` 先由 Dify 做单票解析,其余状态尝试走 auto_progress;进入人工检查点时自然返回。
|
||||
`created` 先由 Dify 做单票解析;解析完成后和其他可续跑状态统一交给后端 auto_progress。
|
||||
一旦进入人工检查点或等待外部回执状态,本轮自动停止,等待用户或外部系统回写。
|
||||
"""
|
||||
normalized_task_no = _normalize_ref(task_no)
|
||||
if not normalized_task_no:
|
||||
@@ -110,7 +126,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
if not _should_orchestrate_task(task):
|
||||
return {
|
||||
"status": "skipped",
|
||||
"message": f"skip process_status={task.process_status or ''}",
|
||||
"message": (
|
||||
f"skip process_status={task.process_status or ''}"
|
||||
f" pending_human_reason={task.pending_human_reason or ''}"
|
||||
f" review_status={task.review_status or ''}"
|
||||
),
|
||||
}
|
||||
|
||||
_refresh_batch_focus(task.task_no)
|
||||
@@ -124,8 +144,27 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
db.session.commit()
|
||||
|
||||
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
|
||||
if str(task.process_status or "").strip().lower() == "created":
|
||||
process_status = str(task.process_status or "").strip().lower()
|
||||
pending_reason = str(task.pending_human_reason or "").strip().lower()
|
||||
if (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason in {"", PH_RPA_PENDING}
|
||||
):
|
||||
payload["mode"] = "auto"
|
||||
result = auto_progress(payload)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
|
||||
task.task_no,
|
||||
result.get("status"),
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
elif process_status == "created":
|
||||
result = run_shipping_parse_via_dify(task.task_no)
|
||||
# Dify 会通过 Tool API 在独立请求中提交 parse_notice;当前 worker session
|
||||
# 可能仍缓存 created 旧对象,必须重新读库后才能决定是否继续 auto_progress。
|
||||
db.session.expire_all()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] dify-parse result task_no=%s status=%s process_status_before=%s provider_conversation_id=%s message=%s",
|
||||
@@ -306,7 +345,7 @@ def start_batch_orchestrator(batch_no: str | None) -> bool:
|
||||
|
||||
|
||||
def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
"""重试批次中仍可自动推进的任务,跳过已终态和人工阻断任务。"""
|
||||
"""重试批次中可恢复的任务;RPA 耗尽态会手动开启新一轮库存导出。"""
|
||||
normalized_batch_no = _normalize_ref(batch_no)
|
||||
if not normalized_batch_no:
|
||||
return {"status": "failed", "message": "batch_no is required"}
|
||||
@@ -320,6 +359,24 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
if not _is_retryable_task(task):
|
||||
skipped += 1
|
||||
continue
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING:
|
||||
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_EXHAUSTED:
|
||||
result = submit_decision({"task_id": task.task_no, "decision": "retry_rpa"})
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if start_task_orchestrator(task.task_no):
|
||||
started += 1
|
||||
else:
|
||||
|
||||
@@ -14,7 +14,7 @@ from typing import Any
|
||||
MAP_JSON = "map_json"
|
||||
SUGGEST_OK = "suggest_ok"
|
||||
AUTO_MAP = "auto_map"
|
||||
# Workspace / Hxops chat fallback only — Dify Agent 主路径应调 auto_progress,勿在画布 HTTP 传此字段
|
||||
# Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑
|
||||
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
|
||||
|
||||
# Legacy request field names (read-only compat)
|
||||
@@ -38,6 +38,7 @@ CP_READY_MATCH = "ready_to_match"
|
||||
CP_READY_EXPORT = "ready_to_export"
|
||||
CP_EXPORT_READY = "export_ready"
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
|
||||
CP_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
|
||||
CP_EXPORT_GENERATED = "export_generated"
|
||||
CP_UPLOADED = "uploaded"
|
||||
CP_COMPLETED = "completed"
|
||||
@@ -59,6 +60,8 @@ PH_SHORTAGE = "shortage"
|
||||
PH_RPA_EXHAUSTED = "rpa_exhausted"
|
||||
PH_RPA_PENDING = "rpa_pending"
|
||||
PH_INV_UNAVAIL = "inv_unavail"
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
|
||||
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
|
||||
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
|
||||
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/decision_workflow.py
|
||||
|
||||
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配、重解析和映射修正。
|
||||
依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调 auto_progress 或 parse_notice。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,12 +28,18 @@ from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
inventory_mapping_checkpoint_response,
|
||||
latest_inventory_column_meta,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
linked_task_nos_for_inventory_file,
|
||||
start_inventory_file_linked_tasks,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_upload import (
|
||||
has_uploaded_task_inventory,
|
||||
read_task_inventory_schema_preview,
|
||||
task_inventory_upload_path,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
@@ -44,6 +50,13 @@ from app.services.shipping_notice.tool_common import (
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
|
||||
def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
|
||||
|
||||
return _start(task_no)
|
||||
|
||||
|
||||
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
|
||||
@@ -60,14 +73,12 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
message=(
|
||||
"未找到任务。用户说「确认/重新解析/驳回」时禁止 create_task。"
|
||||
"请先 get_task_status(conversation_id=...) 或 submit_decision 带上任务编号。"
|
||||
),
|
||||
message=t("workflow.decision.task_not_found", lang="zh"),
|
||||
)
|
||||
|
||||
decision = str(payload.get("decision") or "").strip().lower()
|
||||
comment = str(payload.get("comment") or "").strip()
|
||||
lang = resolve_lang(payload)
|
||||
|
||||
# [STEP 1] 先处理终止型决策。
|
||||
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
|
||||
@@ -78,7 +89,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message="已驳回该发货任务。",
|
||||
message=t("workflow.decision.rejected", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -89,7 +100,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message="已关闭该发货任务(可在同一会话重新开新单)。",
|
||||
message=t("workflow.decision.closed", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -100,7 +111,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。",
|
||||
message=t("workflow.decision.shortage_confirm_blocked", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -120,23 +131,23 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
log_task_event(task, "parse_confirmed", {"comment": comment})
|
||||
db.session.commit()
|
||||
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
|
||||
next_payload = merge_tool_payload(task, payload, extra={"mode": "auto"})
|
||||
if payload_wants_auto_chain_fallback(payload):
|
||||
from app.services.shipping_notice.task_workflow import auto_progress
|
||||
|
||||
return auto_progress(next_payload)
|
||||
return ensure_inventory(next_payload)
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=t("workflow.decision.parse_confirmed_running", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_PARSE_OK,
|
||||
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
|
||||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=(
|
||||
"发货通知已确认。"
|
||||
"请先处理库存(ensure_inventory / parse_inventory → confirm_inventory_mapping → match_inventory)。"
|
||||
"禁止跳过匹配直接 generate_shipment_excel。"
|
||||
),
|
||||
message=t("workflow.decision.parse_confirmed_next", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_PARSE_OK,
|
||||
next_required_action="ensure_inventory 或 parse_inventory",
|
||||
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
|
||||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
@@ -147,59 +158,76 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message="已确认,可继续生成 Excel 并上传货代系统。",
|
||||
message=t("workflow.decision.matched_confirmed", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if task.process_status == "waiting_inventory" or (
|
||||
task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json
|
||||
):
|
||||
follow_payload = merge_tool_payload(task, payload, extra={"mode": "auto"})
|
||||
if payload_wants_auto_chain_fallback(payload):
|
||||
from app.services.shipping_notice.task_workflow import auto_progress
|
||||
|
||||
return auto_progress(follow_payload)
|
||||
return ensure_inventory(follow_payload)
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=t("workflow.decision.inventory_preparing", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if awaiting_inventory_mapping_confirm(task):
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
return inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||||
|
||||
if task.inventory_lines_json or task.process_status == "inventory_ready":
|
||||
follow_payload = merge_tool_payload(task, payload)
|
||||
if payload_wants_auto_chain_fallback(payload):
|
||||
from app.services.shipping_notice.task_workflow import auto_progress
|
||||
|
||||
return auto_progress(follow_payload)
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message="发货通知已确认,当前任务已进入库存处理阶段,请按当前按钮继续。",
|
||||
message=t("workflow.decision.fulfillment_running", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
|
||||
message=t("workflow.decision.confirm_invalid_state", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
# [STEP 3] 处理重算型决策。
|
||||
# rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
|
||||
# retry_rpa / rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
|
||||
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
|
||||
if decision == "retry_rpa":
|
||||
log_task_event(task, "decision_retry_rpa", {"comment": comment})
|
||||
task.error_message = None
|
||||
db.session.flush()
|
||||
retry_payload = merge_tool_payload(
|
||||
task,
|
||||
payload,
|
||||
extra={"mode": "retry_rpa", "manual_retry_round": True},
|
||||
)
|
||||
return ensure_inventory(retry_payload)
|
||||
|
||||
if decision == "rematch":
|
||||
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
log_task_event(task, "decision_rematch", {"comment": comment})
|
||||
db.session.commit()
|
||||
rematch_payload = merge_tool_payload(task, payload)
|
||||
return match_inventory(rematch_payload)
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=t("workflow.decision.rematch_running", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if decision == "confirm_inventory_mapping":
|
||||
if not awaiting_inventory_mapping_confirm(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="当前无需确认库存字段对齐。",
|
||||
message=t("workflow.decision.mapping_not_needed", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
meta = latest_inventory_column_meta(task) or {}
|
||||
@@ -216,8 +244,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
column_meta=meta,
|
||||
extra_data={
|
||||
"warnings": [
|
||||
"库存表必须包含 Reservation ID 列标题(该列允许为空值)。"
|
||||
"请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。"
|
||||
t("workflow.decision.mapping_missing_reservation_warning", lang=lang),
|
||||
],
|
||||
},
|
||||
lang=lang or None,
|
||||
@@ -234,17 +261,58 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()},
|
||||
)
|
||||
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
|
||||
log_task_event(task, "inventory_mapping_confirmed", {"comment": comment})
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
linked_task_nos = [task.task_no]
|
||||
if inv_file:
|
||||
inv_file.mapping_confirmed = True
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_mapping_confirmed",
|
||||
{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
)
|
||||
for link in inv_file.links or []:
|
||||
linked_task = link.task
|
||||
if not link.is_active or not linked_task:
|
||||
continue
|
||||
linked_task_nos.append(linked_task.task_no)
|
||||
if awaiting_inventory_mapping_confirm(linked_task):
|
||||
apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED)
|
||||
log_task_event(
|
||||
linked_task,
|
||||
"inventory_mapping_confirmed",
|
||||
{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
)
|
||||
else:
|
||||
log_task_event(task, "inventory_mapping_confirmed", {"comment": comment})
|
||||
db.session.commit()
|
||||
next_payload = merge_tool_payload(task, payload)
|
||||
return match_inventory(next_payload)
|
||||
orchestrator_started = (
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
if inv_file
|
||||
else start_task_orchestrator(task.task_no)
|
||||
)
|
||||
if inv_file:
|
||||
linked_task_nos = linked_task_nos_for_inventory_file(inv_file)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=t("workflow.decision.mapping_confirmed_running", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "linked_task_nos": linked_task_nos},
|
||||
)
|
||||
|
||||
if decision == "correct_inventory_mapping":
|
||||
if not awaiting_inventory_mapping_confirm(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="当前不在库存字段对齐确认步骤,无法更正映射。",
|
||||
message=t("workflow.decision.mapping_correction_invalid_state", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
task.inventory_lines_json = None
|
||||
@@ -259,7 +327,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=f"读取库存表头失败: {exc}",
|
||||
message=t("workflow.decision.read_inventory_preview_failed", lang=lang).format(error=exc),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
else:
|
||||
@@ -268,18 +336,15 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"headers": meta.get("headers") or [],
|
||||
"sample_rows": [],
|
||||
"suggested_mapping": meta.get("field_mapping") or {},
|
||||
"note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。",
|
||||
"note": t("workflow.decision.mapping_preview_note", lang=lang),
|
||||
}
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=(
|
||||
"已回到列映射步骤。请根据 schema_preview 提供新的 map_json,"
|
||||
"再调用 apply_inventory_mapping。"
|
||||
),
|
||||
message=t("workflow.decision.mapping_correction_needed", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "schema_preview": preview},
|
||||
checkpoint=CP_MAP_INFER,
|
||||
next_required_action="apply_inventory_mapping(map_json=...)",
|
||||
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
@@ -301,15 +366,38 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message="已清除库存快照,请重新上传或粘贴库存后调用 parse_inventory。",
|
||||
message=t("workflow.decision.inventory_cleared", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
# [STEP 4] 最后处理整单重新解析。
|
||||
# 该分支会复用已有任务号和原始文本,避免产生重复任务。
|
||||
# 整单重解析必须回到 created 并交给后台 Dify 编排,避免启发式兜底直接覆盖 AI 解析。
|
||||
if decision == "reparse":
|
||||
from app.services.shipping_notice.task_workflow import parse_notice
|
||||
task.process_status = "created"
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
task.lines_json = []
|
||||
task.parse_confidence = None
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
task.inventory_lines_json = None
|
||||
task.error_message = None
|
||||
log_task_event(task, "notice_reparse_requested", {"comment": comment, "source": "dify_required"})
|
||||
db.session.commit()
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=f"已提交重新解析任务 {task.task_no},后台将通过 Dify 重新抽取发货通知。",
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
return parse_notice({"task_id": task.task_no, "raw_text": task.raw_content or ""})
|
||||
|
||||
return tool_response(status="failed", task_id=task.task_no, message=f"未知 decision: {decision}")
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.decision.unknown", lang=lang).format(decision=decision),
|
||||
)
|
||||
@@ -25,24 +25,12 @@ from app.services.shipping_notice.tool_common import cfg_int
|
||||
|
||||
|
||||
def build_single_task_parse_prompt(task_no: str, *, batch_no: str | None = None) -> str:
|
||||
"""构造后台排程器发给 Dify 的单票解析指令。"""
|
||||
pieces = [
|
||||
"你正在处理货代发货通知任务。",
|
||||
f"当前任务编号:{task_no}。",
|
||||
]
|
||||
if batch_no:
|
||||
pieces.append(f"所属批次:{batch_no}。")
|
||||
pieces.extend(
|
||||
[
|
||||
"只允许处理当前这一票,禁止切换任务、禁止整批循环、禁止调用 switch_focus_task。",
|
||||
"先调用 get_task_status 获取当前任务状态和 raw_text。",
|
||||
"如果当前任务已经不是待解析状态,或已经进入人工确认/下游阶段,请直接总结当前状态并结束。",
|
||||
"如果当前任务仍待解析,请基于 raw_text 用 LLM 抽取结构化字段,并调用 parse_notice(structured=...) 落库。",
|
||||
"禁止再次询问用户“是否开始解析”。",
|
||||
"完成后只返回当前票的简短解析结果摘要。",
|
||||
]
|
||||
)
|
||||
return "".join(pieces)
|
||||
"""
|
||||
构造后台排程器发给 Dify 的用户意图短句。
|
||||
|
||||
后台任务号与批次号通过 hxops_context.refs 注入,不能拼入 query,避免 Dify 预处理把 SB-/流程指令误判为切换任务。
|
||||
"""
|
||||
return "解析当前发货通知任务"
|
||||
|
||||
|
||||
def _ensure_chat_session_for_task(task: Any, agent_id: int, title: str) -> ChatSession | None:
|
||||
@@ -86,29 +74,6 @@ def _ensure_chat_session_for_task(task: Any, agent_id: int, title: str) -> ChatS
|
||||
return session
|
||||
|
||||
|
||||
def _update_chat_session_after_stream(
|
||||
session: ChatSession | None,
|
||||
*,
|
||||
provider_conversation_id: str | None,
|
||||
status: str,
|
||||
) -> None:
|
||||
if not session:
|
||||
return
|
||||
provider_id = str(provider_conversation_id or "").strip() or None
|
||||
changed = False
|
||||
if provider_id and session.external_conversation_id != provider_id:
|
||||
session.external_conversation_id = provider_id
|
||||
changed = True
|
||||
if status and session.status != status:
|
||||
session.status = status
|
||||
changed = True
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
changed = True
|
||||
if changed:
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _log_executor_context(
|
||||
*,
|
||||
task: Any,
|
||||
@@ -160,18 +125,16 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
or str(getattr(task, "conversation_id", "") or "").strip()
|
||||
or task.task_no
|
||||
)
|
||||
provider_conversation_id = (
|
||||
str(getattr(session, "external_conversation_id", "") or "").strip() or None
|
||||
)
|
||||
# 后台编排每票都从新的 Dify provider conversation 开始,避免多票复用前端会话导致上下文串单。
|
||||
provider_conversation_id = None
|
||||
request_id = f"shipping-orch-{task.task_no}"
|
||||
inputs = build_dify_chat_inputs(
|
||||
local_conversation_id,
|
||||
task_id=task.task_no,
|
||||
batch_no=batch_no,
|
||||
entry_mode="orchestrator_parse",
|
||||
user_message="",
|
||||
trigger_source="backend_orchestrator",
|
||||
request_id=request_id,
|
||||
)
|
||||
request_id = f"shipping-orch-{task.task_no}"
|
||||
started_at = time.perf_counter()
|
||||
total_timeout_seconds = _parse_total_timeout_seconds()
|
||||
|
||||
@@ -210,6 +173,7 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
request_id=request_id,
|
||||
session_id=local_conversation_id,
|
||||
inputs=inputs,
|
||||
persist_chat_log=False,
|
||||
)
|
||||
for chunk in stream:
|
||||
if time.perf_counter() - started_at > total_timeout_seconds:
|
||||
@@ -260,11 +224,6 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
break
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_update_chat_session_after_stream(
|
||||
session,
|
||||
provider_conversation_id=provider_conversation_id,
|
||||
status="error",
|
||||
)
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
"[shipping-dify-executor] exception request_id=%s task_no=%s provider_conversation_id=%s",
|
||||
@@ -274,11 +233,6 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
)
|
||||
return {"status": "failed", "message": str(exc)[:500] or "dify execution failed"}
|
||||
|
||||
_update_chat_session_after_stream(
|
||||
session,
|
||||
provider_conversation_id=provider_conversation_id,
|
||||
status=terminal_status,
|
||||
)
|
||||
refreshed = get_task_by_ref(task.task_no)
|
||||
process_status = str(getattr(refreshed, "process_status", "") or "").strip() if refreshed else ""
|
||||
review_status = str(getattr(refreshed, "review_status", "") or "").strip() if refreshed else ""
|
||||
|
||||
@@ -2,27 +2,27 @@
|
||||
services/shipping_notice/dify_inputs.py
|
||||
|
||||
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
|
||||
依赖:agent_resolver、models.ShippingBatch/ShippingTask。
|
||||
依赖:agent_resolver、models.ShippingBatch/ShippingTask、chat.hxops_context。
|
||||
逻辑:由 api/chat 在调用 DifyService.stream_chat 前引用;本模块按会话号解析当前批次/任务焦点,
|
||||
把 Dify 画布需要的 conversation_id、current_batch_no、current_task_no 注入 Start 节点变量。
|
||||
仅补充货代发货场景可识别的 refs,再委托平台级上下文构造器生成 hxops_context。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
|
||||
from typing import Any
|
||||
|
||||
SHIPPING_CONVERSATION_ID_INPUT = "conversation_id"
|
||||
SHIPPING_CURRENT_BATCH_NO_INPUT = "current_batch_no"
|
||||
SHIPPING_CURRENT_TASK_NO_INPUT = "current_task_no"
|
||||
SHIPPING_ENTRY_MODE_INPUT = "entry_mode"
|
||||
SHIPPING_USER_MESSAGE_INPUT = "user_message"
|
||||
SHIPPING_TRIGGER_SOURCE_INPUT = "trigger_source"
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.chat.hxops_context import HXOPS_CONTEXT_INPUT, build_hxops_context, build_ref
|
||||
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
|
||||
|
||||
|
||||
def is_shipping_notice_chat_agent(agent) -> bool:
|
||||
"""判断 Agent 记录是否为发货通知聊天 Agent。"""
|
||||
return getattr(agent, "name", None) == CHAT_AGENT_NAME
|
||||
agent_name = str(getattr(agent, "name", None) or "").strip()
|
||||
if agent_name == CHAT_AGENT_NAME:
|
||||
return True
|
||||
normalized_name = agent_name.replace(" ", "")
|
||||
return "发货通知" in normalized_name and "Agent" in normalized_name
|
||||
|
||||
|
||||
def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None:
|
||||
@@ -50,53 +50,63 @@ def _latest_task_for_conversation(conversation_id: str) -> ShippingTask | None:
|
||||
)
|
||||
|
||||
|
||||
def _build_hxops_refs(*, task: str, batch: str) -> list[dict[str, str]]:
|
||||
"""构建货代发货 Agent 当前已知业务对象锚点。"""
|
||||
return [
|
||||
build_ref("task", task),
|
||||
build_ref("batch", batch),
|
||||
]
|
||||
|
||||
|
||||
def build_dify_chat_inputs(
|
||||
conversation_id: str | None = None,
|
||||
*,
|
||||
task_id: str | None = None,
|
||||
batch_no: str | None = None,
|
||||
entry_mode: str | None = None,
|
||||
user_message: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
request_id: str | None = None,
|
||||
locale: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建发货通知 Dify Chatflow inputs。
|
||||
|
||||
OpenAPI 工具已在 Dify 侧配置 Server URL 与 Authorization / X-Integration-Key,
|
||||
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布稳定读取当前 task/batch。
|
||||
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布通过 refs 稳定定位当前 task/batch。
|
||||
"""
|
||||
conv_id = str(conversation_id or "").strip()
|
||||
if not conv_id:
|
||||
return {}
|
||||
|
||||
explicit_task_no = str(task_id or "").strip().upper()
|
||||
explicit_batch_no = str(batch_no or "").strip().upper()
|
||||
explicit_task = str(task_id or "").strip().upper()
|
||||
explicit_batch = str(batch_no or "").strip().upper()
|
||||
|
||||
batch = _latest_batch_for_conversation(conv_id)
|
||||
task = _latest_task_for_conversation(conv_id)
|
||||
|
||||
current_task_no = explicit_task_no
|
||||
if not current_task_no and batch and batch.current_focus_task_no:
|
||||
current_task_no = str(batch.current_focus_task_no or "").strip().upper()
|
||||
elif not current_task_no and task and task.task_no:
|
||||
current_task_no = str(task.task_no or "").strip().upper()
|
||||
focus_task = explicit_task
|
||||
if not focus_task and batch and batch.current_focus_task_no:
|
||||
focus_task = str(batch.current_focus_task_no or "").strip().upper()
|
||||
elif not focus_task and task and task.task_no:
|
||||
focus_task = str(task.task_no or "").strip().upper()
|
||||
|
||||
current_batch_no = explicit_batch_no
|
||||
if not current_batch_no and batch and batch.batch_no:
|
||||
current_batch_no = str(batch.batch_no or "").strip().upper()
|
||||
focus_batch = explicit_batch
|
||||
if not focus_batch and batch and batch.batch_no:
|
||||
focus_batch = str(batch.batch_no or "").strip().upper()
|
||||
elif (
|
||||
not current_batch_no
|
||||
not focus_batch
|
||||
and task
|
||||
and getattr(task, "batch", None) is not None
|
||||
and getattr(task.batch, "batch_no", None)
|
||||
):
|
||||
current_batch_no = str(task.batch.batch_no or "").strip().upper()
|
||||
focus_batch = str(task.batch.batch_no or "").strip().upper()
|
||||
|
||||
return {
|
||||
SHIPPING_ENTRY_MODE_INPUT: str(entry_mode or "").strip(),
|
||||
SHIPPING_CONVERSATION_ID_INPUT: conv_id,
|
||||
SHIPPING_CURRENT_BATCH_NO_INPUT: current_batch_no,
|
||||
SHIPPING_CURRENT_TASK_NO_INPUT: current_task_no,
|
||||
SHIPPING_USER_MESSAGE_INPUT: str(user_message or "").strip(),
|
||||
SHIPPING_TRIGGER_SOURCE_INPUT: str(trigger_source or "").strip(),
|
||||
}
|
||||
hxops_context = build_hxops_context(
|
||||
session_id=conv_id,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
refs=_build_hxops_refs(task=focus_task, batch=focus_batch),
|
||||
)
|
||||
if not hxops_context:
|
||||
return {}
|
||||
return {HXOPS_CONTEXT_INPUT: hxops_context}
|
||||
@@ -21,6 +21,7 @@ from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
awaiting_inventory_mapping_confirm,
|
||||
inventory_mapping_checkpoint_response,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
from app.services.shipping_notice.inventory_workflow import (
|
||||
ensure_inventory,
|
||||
parse_inventory_lines,
|
||||
@@ -31,6 +32,7 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task_for_tool,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.reservation_id import extract_reservation_id
|
||||
from app.services.shipping_notice.rpa import write_upload_trigger
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
@@ -109,7 +111,7 @@ def excel_gate_error(task: ShippingTask) -> str | None:
|
||||
if task.process_status == "uploaded" and task.export_file_path:
|
||||
return None
|
||||
if not match_completed(task):
|
||||
return "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。"
|
||||
return "workflow.fulfillment.excel_gate_unmatched"
|
||||
return None
|
||||
|
||||
|
||||
@@ -124,10 +126,14 @@ def latest_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | Non
|
||||
.first()
|
||||
)
|
||||
def should_auto_chain_after_match(payload: dict[str, Any] | None) -> bool:
|
||||
"""是否应在 match 成功后自动串联 generate_excel / upload_to_freight(Hxops fallback 链)。"""
|
||||
"""是否应在 match 成功后自动串联低风险履约步骤。
|
||||
|
||||
fulfillable 后生成 Excel 是幂等、可审计的低风险步骤,应由后端默认推进;
|
||||
auto_chain_fallback 仅保留为兼容旧聊天 fallback 链的显式触发信号。
|
||||
"""
|
||||
from app.services.shipping_notice.tool_common import payload_wants_auto_chain_fallback
|
||||
|
||||
return payload_wants_auto_chain_fallback(payload)
|
||||
return _auto_generate_excel_enabled() or payload_wants_auto_chain_fallback(payload)
|
||||
|
||||
|
||||
def try_auto_chain_after_match(
|
||||
@@ -137,10 +143,10 @@ def try_auto_chain_after_match(
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
匹配成功后按配置自动串联 Excel 导出与 RPA 上传(Hxops chat fallback 链)。
|
||||
匹配成功后自动串联 Excel 导出与货代上传(Hxops chat fallback 链)。
|
||||
|
||||
核心逻辑:仅在 payload 含 auto_chain_fallback 且 match_result 为 ok 时触发;
|
||||
依次调用 generate_excel、upload_to_freight,并将消息 prepend 合并返回。
|
||||
核心逻辑:match_result 为 ok 后默认自动生成 Excel;若自动上传开关开启,
|
||||
继续触发 RPA 上传。失败、超时或缺少 RPA 配置时转人工接管。
|
||||
|
||||
Args:
|
||||
task: 当前 ShippingTask。
|
||||
@@ -195,9 +201,10 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
Returns:
|
||||
dict[str, Any]: Tool 标准响应;status 可为 ok / needs_human / failed。
|
||||
"""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
|
||||
# [STEP 1] 先确认字段对齐与库存快照是否已经就绪。
|
||||
# 若还停在映射确认阶段或完全没有库存,就不能直接进入匹配计算。
|
||||
@@ -208,7 +215,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
inventory_lines = parse_inventory_lines(payload)
|
||||
if inventory_lines:
|
||||
task.inventory_lines_json = inventory_lines
|
||||
elif not task.inventory_lines_json:
|
||||
else:
|
||||
inventory_lines = active_inventory_lines_for_task(task)
|
||||
if not inventory_lines:
|
||||
inv_payload: dict[str, Any] = {"task_id": task.task_no}
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
if lang:
|
||||
@@ -221,11 +230,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_key="step5_match_inventory",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message="正在执行库存匹配",
|
||||
message=t("workflow.fulfillment.match_running", lang=lang),
|
||||
progress_percent=10,
|
||||
current=0,
|
||||
total=total_notice_lines or None,
|
||||
detail="按 SKU + Reservation ID 逐行比对需求与库存",
|
||||
detail=t("workflow.fulfillment.match_running_detail", lang=lang),
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
@@ -238,7 +247,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
]
|
||||
inv_missing_count = sum(
|
||||
1
|
||||
for row in (task.inventory_lines_json or [])
|
||||
for row in (inventory_lines or [])
|
||||
if not extract_reservation_id((row or {}).get("reservation_id"))
|
||||
)
|
||||
if order_missing:
|
||||
@@ -255,11 +264,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=(
|
||||
"当前匹配规则要求发货需求(订单)必须提供 Reservation ID。"
|
||||
f"订单缺少 Reservation ID:{len(order_missing)} 行。"
|
||||
"请重新解析发货通知后再匹配。"
|
||||
),
|
||||
message=t("workflow.fulfillment.reservation_required", lang=lang).format(count=len(order_missing)),
|
||||
data={**serialize_task_for_tool(task), "reservation_id_required": detail},
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||||
@@ -274,18 +279,18 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_key="step5_match_inventory",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message="正在执行库存匹配",
|
||||
message=t("workflow.fulfillment.match_running", lang=lang),
|
||||
progress_percent=percent,
|
||||
current=processed,
|
||||
total=total,
|
||||
detail=f"已匹配 {processed}/{total} 行",
|
||||
detail=t("workflow.fulfillment.match_progress_detail", lang=lang).format(processed=processed, total=total),
|
||||
)
|
||||
if processed == total or processed % 50 == 0:
|
||||
db.session.flush()
|
||||
|
||||
match_status, line_results, shortage = match_notice_lines(
|
||||
notice_lines,
|
||||
task.inventory_lines_json or [],
|
||||
inventory_lines or [],
|
||||
progress_callback=_on_match_progress,
|
||||
)
|
||||
if inv_missing_count and isinstance(shortage, dict):
|
||||
@@ -298,18 +303,16 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_key="step5_match_inventory",
|
||||
step_title="匹配库存",
|
||||
status="needs_human" if match_status != "fulfillable" else "completed",
|
||||
message="库存匹配已完成",
|
||||
message=t("workflow.fulfillment.match_completed", lang=lang),
|
||||
progress_percent=100,
|
||||
current=len(line_results),
|
||||
total=len(line_results),
|
||||
detail=(
|
||||
f"已匹配 {len(line_results)}/{len(line_results)} 行,全部订单行库存满足"
|
||||
t("workflow.fulfillment.match_completed_ok_detail", lang=lang).format(count=len(line_results))
|
||||
if match_status == "fulfillable"
|
||||
else f"已匹配 {len(line_results)}/{len(line_results)} 行,存在缺口,需人工处理"
|
||||
else t("workflow.fulfillment.match_completed_shortage_detail", lang=lang).format(count=len(line_results))
|
||||
),
|
||||
)
|
||||
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() or None
|
||||
match_summary = format_match_summary(
|
||||
match_status,
|
||||
line_results,
|
||||
@@ -353,9 +356,10 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
Returns:
|
||||
dict[str, Any]: 含 download_hint 的 Tool 响应;门禁失败时 forbidden_next_tools 含 upload_to_freight。
|
||||
"""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
|
||||
# [STEP 1] 若任务已有可下载的导出文件,则直接返回成功,保证重复点击“生成 Excel”幂等。
|
||||
# 这里不重复生成文件,避免任务已进入 waiting_upload 后再次点击却被旧门禁误判为“未完成匹配”。
|
||||
@@ -363,7 +367,9 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message=f"发货 Excel 已生成:{task.export_file_name or task.export_file_path}",
|
||||
message=t("workflow.fulfillment.excel_exists", lang=lang).format(
|
||||
file=task.export_file_name or task.export_file_path
|
||||
),
|
||||
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
|
||||
)
|
||||
|
||||
@@ -374,19 +380,19 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=gate_error,
|
||||
message=t(gate_error, lang=lang) if gate_error.startswith("workflow.") else gate_error,
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
next_required_action="match_inventory(须先完成库存上传与字段对齐确认)",
|
||||
next_required_action=t("workflow.fulfillment.match_first", lang=lang),
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step6_generate_file",
|
||||
step_title="生成发货文件",
|
||||
status="running",
|
||||
message="正在生成发货 Excel",
|
||||
message=t("workflow.fulfillment.generate_running", lang=lang),
|
||||
progress_percent=60,
|
||||
detail="正在按货代模板填充全部应发行",
|
||||
detail=t("workflow.fulfillment.generate_running_detail", lang=lang),
|
||||
)
|
||||
|
||||
# [STEP 3] 生成文件并把任务推进到等待上传阶段。
|
||||
@@ -400,7 +406,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_key="step6_generate_file",
|
||||
step_title="生成发货文件",
|
||||
status="completed",
|
||||
message="发货 Excel 已生成",
|
||||
message=t("workflow.fulfillment.generate_completed", lang=lang),
|
||||
progress_percent=100,
|
||||
detail=filename,
|
||||
)
|
||||
@@ -409,7 +415,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message=f"已生成发货 Excel:{filename}",
|
||||
message=t("workflow.fulfillment.generate_done", lang=lang).format(file=filename),
|
||||
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
|
||||
)
|
||||
|
||||
@@ -427,9 +433,10 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
Returns:
|
||||
dict[str, Any]: status 可为 ok / running / needs_human / failed。
|
||||
"""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
|
||||
# [STEP 1] 先确保上传所需的 Excel 已经存在。
|
||||
# 调用方可能直接请求 upload,此时需要自动补齐 generate_excel 前置步骤。
|
||||
@@ -447,7 +454,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
status="ok",
|
||||
task=task,
|
||||
task_id=task.task_no,
|
||||
message=f"任务 {task.task_no} 已标记为完成,无需重复操作。",
|
||||
message=t("workflow.fulfillment.manual_already_done", lang=lang).format(task_no=task.task_no),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED,
|
||||
human_options=[],
|
||||
@@ -459,9 +466,9 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_key="step7_upload_freight",
|
||||
step_title="上传货代",
|
||||
status="completed",
|
||||
message="已确认手工上传货代完成",
|
||||
message=t("workflow.fulfillment.manual_confirmed", lang=lang),
|
||||
progress_percent=100,
|
||||
detail="任务已完成",
|
||||
detail=t("workflow.fulfillment.task_completed", lang=lang),
|
||||
)
|
||||
# [STEP 2.1] 手工上传确认属于任务终态写路径,需要同步刷新批次汇总,
|
||||
# 否则聊天顶部批次卡片仍会读取旧的 process_summary_json,显示成未完成。
|
||||
@@ -477,10 +484,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
status="ok",
|
||||
task=task,
|
||||
task_id=task.task_no,
|
||||
message=(
|
||||
f"已标记为手工上传货代系统完成。任务 {task.task_no} 已全部处理完毕,"
|
||||
"无需再进行任何操作。"
|
||||
),
|
||||
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED,
|
||||
human_options=[],
|
||||
@@ -506,10 +510,12 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=(
|
||||
f"RPA 上传进行中(第 {max(attempts, 1)}/{max_attempts} 次)。"
|
||||
f"已等待 {elapsed}s / 超时 {timeout_seconds}s。"
|
||||
f"请稍后再试(建议 {remaining}s 后)。"
|
||||
message=t("workflow.fulfillment.upload_running", lang=lang).format(
|
||||
attempt=max(attempts, 1),
|
||||
max_attempts=max_attempts,
|
||||
elapsed=elapsed,
|
||||
timeout=timeout_seconds,
|
||||
remaining=remaining,
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
@@ -524,7 +530,9 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
last_failed = latest_event(task, "upload_rpa_failed")
|
||||
if not last_failed or (last_failed.created_at < last_trigger.created_at):
|
||||
task.error_message = f"RPA 上传超时(>{timeout_seconds}s)"
|
||||
task.error_message = t("workflow.fulfillment.upload_timeout_error", lang=lang).format(
|
||||
timeout=timeout_seconds
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"upload_rpa_failed",
|
||||
@@ -535,7 +543,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
attempts = upload_rpa_attempts(task)
|
||||
if attempts >= max_attempts:
|
||||
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
|
||||
task.error_message = f"已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。"
|
||||
task.error_message = t("workflow.fulfillment.upload_exhausted", lang=lang).format(attempts=attempts)
|
||||
log_task_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
@@ -555,10 +563,13 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_key="step7_upload_freight",
|
||||
step_title="上传货代",
|
||||
status="running",
|
||||
message="已触发 RPA 上传货代,等待回执",
|
||||
message=t("workflow.fulfillment.upload_triggered_wait", lang=lang),
|
||||
current=attempt_no,
|
||||
total=max_attempts,
|
||||
detail=f"第 {attempt_no}/{max_attempts} 次上传尝试",
|
||||
detail=t("workflow.fulfillment.upload_triggered_detail", lang=lang).format(
|
||||
attempt=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
),
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
@@ -575,9 +586,10 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=(
|
||||
f"已触发 RPA 上传货代(第 {attempt_no}/{max_attempts} 次)。"
|
||||
f"若 {timeout_seconds}s 内无回调,可重试;超过最大次数将转手工上传。"
|
||||
message=t("workflow.fulfillment.upload_triggered_message", lang=lang).format(
|
||||
attempt=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
timeout=timeout_seconds,
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
@@ -592,17 +604,17 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_key="step7_upload_freight",
|
||||
step_title="上传货代",
|
||||
status="needs_human",
|
||||
message="RPA 自动上传失败,请人工接管",
|
||||
message=t("workflow.fulfillment.upload_takeover", lang=lang),
|
||||
progress_percent=100,
|
||||
detail="请下载 Excel 手工上传后确认完成",
|
||||
detail=t("workflow.fulfillment.upload_takeover_detail", lang=lang),
|
||||
)
|
||||
task.error_message = "RPA 上传目录未配置或触发失败"
|
||||
task.error_message = t("workflow.fulfillment.upload_trigger_failed", lang=lang)
|
||||
log_task_event(task, "upload_rpa_pending", {})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="RPA 自动上传失败或未配置。请下载 Excel 在货代系统手工上传,完成后告知我。",
|
||||
message=t("workflow.fulfillment.upload_takeover_message", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -620,9 +632,10 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
Returns:
|
||||
dict[str, Any]: 成功时 checkpoint=uploaded;失败时 needs_human 并附带 error_message。
|
||||
"""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
|
||||
success = bool(payload.get("success", True))
|
||||
if success:
|
||||
@@ -633,9 +646,9 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_key="step7_upload_freight",
|
||||
step_title="上传货代",
|
||||
status="completed",
|
||||
message="RPA 已成功上传货代系统",
|
||||
message=t("workflow.fulfillment.rpa_uploaded", lang=lang),
|
||||
progress_percent=100,
|
||||
detail="任务已完成",
|
||||
detail=t("workflow.fulfillment.task_completed", lang=lang),
|
||||
)
|
||||
task.freight_ref_no = str(payload.get("freight_ref_no") or "").strip() or None
|
||||
log_task_event(task, "upload_rpa_success", {"freight_ref_no": task.freight_ref_no})
|
||||
@@ -644,7 +657,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
status="ok",
|
||||
task=task,
|
||||
task_id=task.task_no,
|
||||
message="RPA 已成功上传货代系统,任务已全部处理完毕。",
|
||||
message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED,
|
||||
human_options=[],
|
||||
@@ -657,9 +670,9 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_key="step7_upload_freight",
|
||||
step_title="上传货代",
|
||||
status="needs_human",
|
||||
message="货代上传失败,等待人工处理",
|
||||
message=t("workflow.fulfillment.upload_failed_wait_manual", lang=lang),
|
||||
progress_percent=100,
|
||||
detail="可重试上传或改为手工上传",
|
||||
detail=t("workflow.fulfillment.upload_failed_detail", lang=lang),
|
||||
)
|
||||
task.error_message = str(payload.get("error_message") or "RPA upload failed")[:500]
|
||||
log_task_event(task, "upload_rpa_failed", {"error": task.error_message})
|
||||
@@ -667,7 +680,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
attempts = upload_rpa_attempts(task)
|
||||
max_attempts = max_rpa_upload_attempts()
|
||||
if attempts >= max_attempts:
|
||||
task.error_message = f"已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。"
|
||||
task.error_message = t("workflow.fulfillment.upload_exhausted", lang=lang).format(attempts=attempts)
|
||||
log_task_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
|
||||
@@ -20,7 +20,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"parse.no_lines": "未解析到订单明细行,请重新上传或重新解析。",
|
||||
"parse.low_conf": "解析置信度较低,请重点核对料号、预订单号、数量、单价与金额。",
|
||||
"parse.confirm": "请确认以上信息是否正确?",
|
||||
"parse.hint": "回复「确认」进入库存检查;「重新解析」重试;「驳回」终止本任务。",
|
||||
"parse.hint": "请核对信息后使用下方按钮继续。",
|
||||
"parse.hint_btn": "",
|
||||
"align.title": "【库存字段对齐确认 — 确认后再匹配】任务编号:{task_no}",
|
||||
"align.match_rule": "匹配规则:{rule}{note}",
|
||||
@@ -35,7 +35,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"align.source.fallback": "(后端动态兜底)",
|
||||
"align.source.other": "({source})",
|
||||
"align.confirm": "请确认以上字段对齐是否正确。",
|
||||
"align.hint": "回复「确认」进入匹配;「更正映射」重选列;「重新上传」换库存文件;「驳回」终止本任务。",
|
||||
"align.hint": "请核对字段对齐后使用下方按钮继续。",
|
||||
"align.hint_btn": "",
|
||||
"common.tips": "提示:",
|
||||
"table.field": "字段",
|
||||
@@ -67,13 +67,95 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"match.conclusion.unfulfillable": "**结论**:库存均不足,无法发货。请补库存或返回修订后重新匹配。",
|
||||
"match.conclusion.other": "**结论**:match_status={status}",
|
||||
"match.no_lines": "无订单明细,无法比对数量。",
|
||||
"workflow.parse.auto_continued": "解析完成,后台已开始继续处理后续步骤。",
|
||||
"workflow.parse.check_later": "解析完成,请稍后继续查看任务状态。",
|
||||
"workflow.decision.parse_confirmed_running": "发货通知已确认,后台已开始继续处理库存与后续步骤。",
|
||||
"workflow.decision.inventory_preparing": "已确认,后台继续处理库存准备步骤。",
|
||||
"workflow.decision.fulfillment_running": "发货通知已确认,后台继续处理库存与后续步骤。",
|
||||
"workflow.decision.rematch_running": "已提交重新匹配请求,后台继续处理。",
|
||||
"workflow.decision.mapping_confirmed_running": "库存字段对齐已确认,后台继续处理匹配与后续步骤。",
|
||||
"workflow.decision.task_not_found": "未找到任务。用户说「确认/重新解析/驳回」时禁止 create_task。请先 get_task_status(conversation_id=...) 或 submit_decision 带上任务编号。",
|
||||
"workflow.decision.rejected": "已驳回该发货任务。",
|
||||
"workflow.decision.closed": "已关闭该发货任务(可在同一会话重新开新单)。",
|
||||
"workflow.decision.shortage_confirm_blocked": "库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。",
|
||||
"workflow.decision.parse_confirmed_next": "发货通知已确认。请继续在当前任务中补充库存或等待后端继续处理,并稍后刷新任务状态。",
|
||||
"workflow.decision.parse_confirmed_wait": "等待后台继续处理或稍后刷新任务状态",
|
||||
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory 或 parse_inventory",
|
||||
"workflow.decision.matched_confirmed": "已确认,可继续生成 Excel 并上传货代系统。",
|
||||
"workflow.decision.confirm_invalid_state": "当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
|
||||
"workflow.decision.mapping_not_needed": "当前无需确认库存字段对齐。",
|
||||
"workflow.decision.mapping_missing_reservation_warning": "库存表必须包含 Reservation ID 列标题(该列允许为空值)。请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。",
|
||||
"workflow.decision.mapping_correction_invalid_state": "当前不在库存字段对齐确认步骤,无法更正映射。",
|
||||
"workflow.decision.read_inventory_preview_failed": "读取库存表头失败: {error}",
|
||||
"workflow.decision.mapping_preview_note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。",
|
||||
"workflow.decision.mapping_correction_needed": "已回到列映射步骤。请根据 schema_preview 提供新的 map_json,再调用 apply_inventory_mapping。",
|
||||
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.decision.inventory_cleared": "已清除库存快照。请重新上传或粘贴库存,后续继续在当前任务中处理。",
|
||||
"workflow.decision.unknown": "未知 decision: {decision}",
|
||||
"workflow.inventory.task_not_found": "未找到任务编号",
|
||||
"workflow.inventory.uploaded_file_missing": "未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
|
||||
"workflow.inventory.text_too_large": "库存文本过大({chars} 字符,上限 {max_chars})。请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 POST /tools/upload_inventory_file 上传,再 parse_inventory(use_uploaded_file=true)。",
|
||||
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
|
||||
"workflow.inventory.parse_failed": "未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
|
||||
"workflow.inventory.preview_read_failed": "读取库存表头失败: {error}",
|
||||
"workflow.inventory.preview_ready": "已读取库存表头与样例行。请根据 schema_preview 推断列映射,调用 apply_inventory_mapping(map_json=...)。",
|
||||
"workflow.inventory.preview_next": "根据 data.schema_preview.headers 与 sample_rows 推断 JSON:{\"sku\":\"<列名>\",\"reservation_id\":\"<列名>\",\"available_qty\":\"<列名>\"},再调用 apply_inventory_mapping",
|
||||
"workflow.inventory.uploaded_file_missing_short": "未找到已上传的库存文件。请先 upload_inventory_file。",
|
||||
"workflow.inventory.mapping_invalid": "map_json 无效或不完整。需要提供 {\"sku\":\"列名\",\"reservation_id\":\"列名\",\"available_qty\":\"列名\"}。(库存的 Reservation ID 列允许为空值,但必须有该列标题)",
|
||||
"workflow.inventory.mapping_header_mismatch": "列映射与 Excel 表头不匹配。(表头在第 {row} 行){errors} 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。",
|
||||
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
|
||||
"workflow.inventory.file_missing": "未收到 file 字段",
|
||||
"workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .xls / .csv 库存文件",
|
||||
"workflow.inventory.uploading": "正在上传并解析库存文件",
|
||||
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
|
||||
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
|
||||
"workflow.inventory.completed_task_locked": "该任务已完成,不能再重新上传库存。请切换到仍待处理的任务后再上传库存文件。",
|
||||
"workflow.inventory.uploaded": "库存文件已上传。",
|
||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。",
|
||||
"workflow.inventory.uploaded_need_llm": " 请由画布 LLM 推断列映射后 apply_inventory_mapping。",
|
||||
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.inventory.ready_for_match": "已有库存快照且字段对齐已确认,可调用 match_inventory。",
|
||||
"workflow.inventory.unavailable": "暂无可用库存数据。请重试 RPA 自动导出,或手动上传货代库存 Excel。",
|
||||
"workflow.fulfillment.task_not_found": "未找到任务编号",
|
||||
"workflow.fulfillment.match_running": "正在执行库存匹配",
|
||||
"workflow.fulfillment.match_running_detail": "按 SKU + Reservation ID 逐行比对需求与库存",
|
||||
"workflow.fulfillment.match_progress_detail": "已匹配 {processed}/{total} 行",
|
||||
"workflow.fulfillment.match_completed": "库存匹配已完成",
|
||||
"workflow.fulfillment.match_completed_ok_detail": "已匹配 {count}/{count} 行,全部订单行库存满足",
|
||||
"workflow.fulfillment.match_completed_shortage_detail": "已匹配 {count}/{count} 行,存在缺口,需人工处理",
|
||||
"workflow.fulfillment.reservation_required": "当前匹配规则要求发货需求(订单)必须提供 Reservation ID。订单缺少 Reservation ID:{count} 行。请重新解析发货通知后再匹配。",
|
||||
"workflow.fulfillment.excel_gate_unmatched": "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。",
|
||||
"workflow.fulfillment.excel_exists": "发货 Excel 已生成:{file}",
|
||||
"workflow.fulfillment.match_first": "match_inventory(须先完成库存上传与字段对齐确认)",
|
||||
"workflow.fulfillment.generate_running": "正在生成发货 Excel",
|
||||
"workflow.fulfillment.generate_running_detail": "正在按货代模板填充全部应发行",
|
||||
"workflow.fulfillment.generate_completed": "发货 Excel 已生成",
|
||||
"workflow.fulfillment.generate_done": "已生成发货 Excel:{file}",
|
||||
"workflow.fulfillment.manual_already_done": "任务 {task_no} 已标记为完成,无需重复操作。",
|
||||
"workflow.fulfillment.manual_confirmed": "已确认手工上传货代完成",
|
||||
"workflow.fulfillment.task_completed": "任务已完成",
|
||||
"workflow.fulfillment.manual_done_message": "好的,任务 {task_no} 已确认完成,无需再处理。",
|
||||
"workflow.fulfillment.upload_running": "RPA 上传进行中(第 {attempt}/{max_attempts} 次)。已等待 {elapsed}s / 超时 {timeout}s。请稍后再试(建议 {remaining}s 后)。",
|
||||
"workflow.fulfillment.upload_timeout_error": "RPA 上传超时(>{timeout}s)",
|
||||
"workflow.fulfillment.upload_exhausted": "已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。",
|
||||
"workflow.fulfillment.upload_triggered_wait": "已触发 RPA 上传货代,等待回执",
|
||||
"workflow.fulfillment.upload_triggered_detail": "第 {attempt}/{max_attempts} 次上传尝试",
|
||||
"workflow.fulfillment.upload_triggered_message": "已触发 RPA 上传货代(第 {attempt}/{max_attempts} 次)。若 {timeout}s 内无回调,可重试;超过最大次数将转手工上传。",
|
||||
"workflow.fulfillment.upload_takeover": "RPA 自动上传失败,请人工接管",
|
||||
"workflow.fulfillment.upload_takeover_detail": "请下载 Excel 手工上传后确认完成",
|
||||
"workflow.fulfillment.upload_trigger_failed": "RPA 上传目录未配置或触发失败",
|
||||
"workflow.fulfillment.upload_takeover_message": "RPA 自动上传失败或未配置。请下载 Excel 在货代系统手工上传,完成后告知我。",
|
||||
"workflow.fulfillment.rpa_uploaded": "RPA 已成功上传货代系统",
|
||||
"workflow.fulfillment.rpa_uploaded_done": "RPA 已成功上传货代系统,任务已全部处理完毕。",
|
||||
"workflow.fulfillment.upload_failed_wait_manual": "货代上传失败,等待人工处理",
|
||||
"workflow.fulfillment.upload_failed_detail": "可重试上传或改为手工上传",
|
||||
},
|
||||
"en": {
|
||||
"parse.title": "[Shipping notice parsed] Task: {task_no}",
|
||||
"parse.no_lines": "No order lines found. Please re-upload or re-parse.",
|
||||
"parse.low_conf": "Low confidence. Please double-check SKU, Qty, Reservation ID, Unit Price and Amount.",
|
||||
"parse.confirm": "Please confirm the above information.",
|
||||
"parse.hint": 'Reply "Confirm" to proceed; "Re-parse" to retry; "Reject" to stop this task.',
|
||||
"parse.hint": "Review the information, then use the buttons below to continue.",
|
||||
"parse.hint_btn": "",
|
||||
"align.title": "[Inventory mapping confirmation] Task: {task_no}",
|
||||
"align.match_rule": "Match rule: {rule}{note}",
|
||||
@@ -88,7 +170,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"align.source.fallback": " (backend fallback)",
|
||||
"align.source.other": " ({source})",
|
||||
"align.confirm": "Please confirm the field alignment above.",
|
||||
"align.hint": 'Reply "Confirm" to match; "Fix mapping" to reselect columns; "Re-upload" to change the inventory file; "Reject" to stop.',
|
||||
"align.hint": "Review the field alignment, then use the buttons below to continue.",
|
||||
"align.hint_btn": "",
|
||||
"common.tips": "Notes:",
|
||||
"table.field": "Field",
|
||||
@@ -120,13 +202,95 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"match.conclusion.unfulfillable": "**Result**: Insufficient inventory for all lines. Shipment blocked until inventory is replenished.",
|
||||
"match.conclusion.other": "**Result**: match_status={status}",
|
||||
"match.no_lines": "No order lines to compare.",
|
||||
"workflow.parse.auto_continued": "Parsing is complete. The backend has started the remaining steps.",
|
||||
"workflow.parse.check_later": "Parsing is complete. Please check the task status again later.",
|
||||
"workflow.decision.parse_confirmed_running": "The shipping notice is confirmed. The backend has started inventory handling and the remaining steps.",
|
||||
"workflow.decision.inventory_preparing": "Confirmed. The backend is continuing the inventory preparation steps.",
|
||||
"workflow.decision.fulfillment_running": "The shipping notice is confirmed. The backend is continuing inventory handling and the remaining steps.",
|
||||
"workflow.decision.rematch_running": "The rematch request has been submitted. The backend is continuing processing.",
|
||||
"workflow.decision.mapping_confirmed_running": "The inventory mapping is confirmed. The backend is continuing matching and the remaining steps.",
|
||||
"workflow.decision.task_not_found": "Task not found. When the user says confirm / re-parse / reject, do not call create_task. Please call get_task_status(conversation_id=...) first or pass the task ID to submit_decision.",
|
||||
"workflow.decision.rejected": "The shipping task has been rejected.",
|
||||
"workflow.decision.closed": "The shipping task has been closed. You may start a new one in the same conversation.",
|
||||
"workflow.decision.shortage_confirm_blocked": "Inventory is insufficient. You cannot use confirm for the whole task. Please use reparse_inventory, rematch, or reject.",
|
||||
"workflow.decision.parse_confirmed_next": "The shipping notice is confirmed. Please continue with inventory for the current task or wait for the backend to continue, then refresh the task status later.",
|
||||
"workflow.decision.parse_confirmed_wait": "Wait for backend processing or refresh the task status later.",
|
||||
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory or parse_inventory",
|
||||
"workflow.decision.matched_confirmed": "Confirmed. You may continue to generate the Excel and upload to the freight system.",
|
||||
"workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Please complete inventory matching first, or use confirm_inventory_mapping / reparse.",
|
||||
"workflow.decision.mapping_not_needed": "Inventory field alignment confirmation is not needed right now.",
|
||||
"workflow.decision.mapping_missing_reservation_warning": "The inventory sheet must contain a Reservation ID column header (the values in that column may be empty). Please use Fix Mapping to choose the Reservation ID column again, or re-upload an inventory Excel that contains that column.",
|
||||
"workflow.decision.mapping_correction_invalid_state": "The task is not currently in the inventory field alignment confirmation step, so the mapping cannot be corrected.",
|
||||
"workflow.decision.read_inventory_preview_failed": "Failed to read inventory headers: {error}",
|
||||
"workflow.decision.mapping_preview_note": "No uploaded Excel was found. Please paste a small inventory table or re-upload, then call apply_inventory_mapping / parse_inventory.",
|
||||
"workflow.decision.mapping_correction_needed": "The task has returned to the mapping step. Please provide a new map_json based on schema_preview, then call apply_inventory_mapping.",
|
||||
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.decision.inventory_cleared": "The inventory snapshot has been cleared. Please re-upload or paste inventory data, then continue in the current task.",
|
||||
"workflow.decision.unknown": "Unknown decision: {decision}",
|
||||
"workflow.inventory.task_not_found": "Task ID not found.",
|
||||
"workflow.inventory.uploaded_file_missing": "No uploaded inventory file was found. Please POST /tools/upload_inventory_file to upload the Excel file first.",
|
||||
"workflow.inventory.text_too_large": "The inventory text is too large ({chars} characters, limit {max_chars}). Do not send the full Excel content to the LLM. Please call POST /tools/upload_inventory_file first, then parse_inventory(use_uploaded_file=true).",
|
||||
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
|
||||
"workflow.inventory.parse_failed": "Inventory lines could not be parsed. For large Excel files, use upload_inventory_file; for small tables, paste the content; if inventory is unavailable, use RPA.",
|
||||
"workflow.inventory.preview_read_failed": "Failed to read inventory headers: {error}",
|
||||
"workflow.inventory.preview_ready": "Inventory headers and sample rows have been loaded. Please infer the column mapping from schema_preview and call apply_inventory_mapping(map_json=...).",
|
||||
"workflow.inventory.preview_next": "Infer JSON from data.schema_preview.headers and sample_rows: {\"sku\":\"<column>\",\"reservation_id\":\"<column>\",\"available_qty\":\"<column>\"}, then call apply_inventory_mapping",
|
||||
"workflow.inventory.uploaded_file_missing_short": "No uploaded inventory file was found. Please call upload_inventory_file first.",
|
||||
"workflow.inventory.mapping_invalid": "map_json is invalid or incomplete. You must provide {\"sku\":\"column\",\"reservation_id\":\"column\",\"available_qty\":\"column\"}. The Reservation ID column may contain empty values, but the column header itself must exist.",
|
||||
"workflow.inventory.mapping_header_mismatch": "The column mapping does not match the Excel headers. (The header row is row {row}) {errors} Please call apply_inventory_mapping again using schema_preview.headers.",
|
||||
"workflow.inventory.parse_failed_detail": "Failed to parse inventory: {error}",
|
||||
"workflow.inventory.file_missing": "The file field was not received.",
|
||||
"workflow.inventory.file_type_unsupported": "Only .xlsx / .xls / .csv inventory files are supported.",
|
||||
"workflow.inventory.uploading": "Uploading and parsing the inventory file.",
|
||||
"workflow.inventory.uploading_detail": "Processing inventory file {filename}",
|
||||
"workflow.inventory.save_failed": "Failed to save inventory file: {error}",
|
||||
"workflow.inventory.completed_task_locked": "This task is already completed, so inventory cannot be uploaded again. Please switch to a task that still needs processing.",
|
||||
"workflow.inventory.uploaded": "The inventory file has been uploaded.",
|
||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping is complete, so the canvas can call apply_inventory_mapping directly without using the LLM.",
|
||||
"workflow.inventory.uploaded_need_llm": " Please let the canvas LLM infer the column mapping and then call apply_inventory_mapping.",
|
||||
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.inventory.ready_for_match": "An inventory snapshot already exists and the field alignment has been confirmed. You may call match_inventory.",
|
||||
"workflow.inventory.unavailable": "No usable inventory data is available yet. Please retry the RPA export or upload the freight inventory Excel manually.",
|
||||
"workflow.fulfillment.task_not_found": "Task ID not found.",
|
||||
"workflow.fulfillment.match_running": "Running inventory matching.",
|
||||
"workflow.fulfillment.match_running_detail": "Comparing demand and inventory line by line using SKU + Reservation ID",
|
||||
"workflow.fulfillment.match_progress_detail": "Matched {processed}/{total} lines",
|
||||
"workflow.fulfillment.match_completed": "Inventory matching is complete.",
|
||||
"workflow.fulfillment.match_completed_ok_detail": "Matched {count}/{count} lines. All order lines are fulfillable.",
|
||||
"workflow.fulfillment.match_completed_shortage_detail": "Matched {count}/{count} lines. Shortage exists and manual handling is required.",
|
||||
"workflow.fulfillment.reservation_required": "The current matching rule requires Reservation ID on the order side. {count} order lines are missing Reservation ID. Please re-parse the shipping notice before matching again.",
|
||||
"workflow.fulfillment.excel_gate_unmatched": "Inventory matching is not complete yet. Please upload inventory, confirm field alignment, and call match_inventory first.",
|
||||
"workflow.fulfillment.excel_exists": "Shipment Excel already exists: {file}",
|
||||
"workflow.fulfillment.match_first": "match_inventory (inventory upload and field alignment confirmation are required first)",
|
||||
"workflow.fulfillment.generate_running": "Generating shipment Excel.",
|
||||
"workflow.fulfillment.generate_running_detail": "Filling all shippable lines into the freight template",
|
||||
"workflow.fulfillment.generate_completed": "Shipment Excel has been generated.",
|
||||
"workflow.fulfillment.generate_done": "Shipment Excel generated: {file}",
|
||||
"workflow.fulfillment.manual_already_done": "Task {task_no} is already marked complete. No further action is needed.",
|
||||
"workflow.fulfillment.manual_confirmed": "Manual freight upload has been confirmed.",
|
||||
"workflow.fulfillment.task_completed": "Task completed.",
|
||||
"workflow.fulfillment.manual_done_message": "Done. Task {task_no} is confirmed complete. No further action is needed.",
|
||||
"workflow.fulfillment.upload_running": "RPA upload is in progress (attempt {attempt}/{max_attempts}). Waited {elapsed}s / timeout {timeout}s. Please try again later (recommended after {remaining}s).",
|
||||
"workflow.fulfillment.upload_timeout_error": "RPA upload timed out (>{timeout}s)",
|
||||
"workflow.fulfillment.upload_exhausted": "RPA upload failed after {attempts} attempts. Please download the Excel and upload it manually.",
|
||||
"workflow.fulfillment.upload_triggered_wait": "RPA upload to freight has been triggered. Waiting for callback.",
|
||||
"workflow.fulfillment.upload_triggered_detail": "Upload attempt {attempt}/{max_attempts}",
|
||||
"workflow.fulfillment.upload_triggered_message": "RPA upload to freight has been triggered (attempt {attempt}/{max_attempts}). If no callback arrives within {timeout}s, you may retry. After the max attempts, the flow will fall back to manual upload.",
|
||||
"workflow.fulfillment.upload_takeover": "RPA auto-upload failed. Manual takeover is required.",
|
||||
"workflow.fulfillment.upload_takeover_detail": "Please download the Excel, upload it manually, then confirm completion.",
|
||||
"workflow.fulfillment.upload_trigger_failed": "The RPA upload directory is not configured or triggering failed.",
|
||||
"workflow.fulfillment.upload_takeover_message": "RPA auto-upload failed or is not configured. Please download the Excel and upload it manually in the freight system, then let me know when it is done.",
|
||||
"workflow.fulfillment.rpa_uploaded": "RPA has uploaded to the freight system successfully.",
|
||||
"workflow.fulfillment.rpa_uploaded_done": "RPA uploaded to the freight system successfully. The task is fully completed.",
|
||||
"workflow.fulfillment.upload_failed_wait_manual": "Freight upload failed. Waiting for manual handling.",
|
||||
"workflow.fulfillment.upload_failed_detail": "You may retry the upload or switch to manual upload.",
|
||||
},
|
||||
"th": {
|
||||
"parse.title": "【ยืนยันการแยกใบแจ้งส่งสินค้า】งาน: {task_no}",
|
||||
"parse.no_lines": "ไม่พบบรรทัดรายการสั่งซื้อ กรุณาอัปโหลดใหม่หรือแยกใหม่อีกครั้ง",
|
||||
"parse.low_conf": "ความมั่นใจต่ำ กรุณาตรวจสอบ SKU, จำนวน, Reservation ID, ราคาต่อหน่วย และจำนวนเงิน",
|
||||
"parse.confirm": "กรุณายืนยันว่าข้อมูลด้านบนถูกต้องหรือไม่",
|
||||
"parse.hint": 'พิมพ์ "ยืนยัน" เพื่อไปต่อ; "แยกใหม่" เพื่อลองใหม่; "ปฏิเสธ" เพื่อยุติงานนี้',
|
||||
"parse.hint": "ตรวจสอบข้อมูลแล้วใช้ปุ่มด้านล่างเพื่อดำเนินการต่อ",
|
||||
"parse.hint_btn": "",
|
||||
"align.title": "【ยืนยันการจับคู่คอลัมน์สต็อก】งาน: {task_no}",
|
||||
"align.match_rule": "กฎการจับคู่: {rule}{note}",
|
||||
@@ -141,7 +305,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"align.source.fallback": " (สำรองโดยระบบ)",
|
||||
"align.source.other": " ({source})",
|
||||
"align.confirm": "กรุณายืนยันว่าการจับคู่ฟิลด์ด้านบนถูกต้อง",
|
||||
"align.hint": 'พิมพ์ "ยืนยัน" เพื่อจับคู่; "แก้ไขการจับคู่" เพื่อเลือกคอลัมน์ใหม่; "อัปโหลดใหม่" เพื่อเปลี่ยนไฟล์สต็อก; "ปฏิเสธ" เพื่อยุติ',
|
||||
"align.hint": "ตรวจสอบการจับคู่ฟิลด์แล้วใช้ปุ่มด้านล่างเพื่อดำเนินการต่อ",
|
||||
"align.hint_btn": "",
|
||||
"common.tips": "หมายเหตุ:",
|
||||
"table.field": "ฟิลด์",
|
||||
@@ -173,6 +337,88 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"match.conclusion.unfulfillable": "**สรุป**: สต็อกไม่เพียงพอทั้งหมด ไม่สามารถจัดส่งได้ กรุณาเติมสต็อกหรือแก้ไขแล้วจับคู่ใหม่",
|
||||
"match.conclusion.other": "**สรุป**: match_status={status}",
|
||||
"match.no_lines": "ไม่มีรายการสั่งซื้อสำหรับเปรียบเทียบ",
|
||||
"workflow.parse.auto_continued": "แยกข้อมูลเสร็จแล้ว ระบบหลังบ้านได้เริ่มดำเนินขั้นตอนถัดไปต่อแล้ว",
|
||||
"workflow.parse.check_later": "แยกข้อมูลเสร็จแล้ว กรุณากลับมาตรวจสอบสถานะงานอีกครั้งภายหลัง",
|
||||
"workflow.decision.parse_confirmed_running": "ยืนยันใบแจ้งส่งสินค้าแล้ว ระบบหลังบ้านได้เริ่มจัดการสต็อกและขั้นตอนถัดไปต่อแล้ว",
|
||||
"workflow.decision.inventory_preparing": "ยืนยันแล้ว ระบบหลังบ้านกำลังดำเนินขั้นตอนเตรียมสต็อกต่อ",
|
||||
"workflow.decision.fulfillment_running": "ยืนยันใบแจ้งส่งสินค้าแล้ว ระบบหลังบ้านกำลังดำเนินการสต็อกและขั้นตอนถัดไปต่อ",
|
||||
"workflow.decision.rematch_running": "ส่งคำขอจับคู่ใหม่แล้ว ระบบหลังบ้านกำลังดำเนินการต่อ",
|
||||
"workflow.decision.mapping_confirmed_running": "ยืนยันการจับคู่คอลัมน์สต็อกแล้ว ระบบหลังบ้านกำลังดำเนินการจับคู่และขั้นตอนถัดไปต่อ",
|
||||
"workflow.decision.task_not_found": "ไม่พบงาน เมื่อผู้ใช้พูดว่ายืนยัน / แยกใหม่ / ปฏิเสธ ห้ามเรียก create_task โปรดเรียก get_task_status(conversation_id=...) ก่อน หรือส่ง task ID ให้ submit_decision",
|
||||
"workflow.decision.rejected": "ปฏิเสธงานจัดส่งนี้แล้ว",
|
||||
"workflow.decision.closed": "ปิดงานจัดส่งนี้แล้ว และสามารถเริ่มงานใหม่ในบทสนทนาเดิมได้",
|
||||
"workflow.decision.shortage_confirm_blocked": "สต็อกไม่เพียงพอ จึงไม่สามารถใช้ confirm เพื่อยืนยันทั้งงานได้ โปรดใช้ reparse_inventory, rematch หรือ reject",
|
||||
"workflow.decision.parse_confirmed_next": "ยืนยันใบแจ้งส่งสินค้าแล้ว โปรดดำเนินการเรื่องสต็อกในงานปัจจุบันต่อ หรือรอให้ระบบหลังบ้านทำต่อ แล้วค่อยรีเฟรชสถานะงาน",
|
||||
"workflow.decision.parse_confirmed_wait": "รอให้ระบบหลังบ้านดำเนินการต่อ หรือกลับมาตรวจสอบสถานะงานภายหลัง",
|
||||
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory หรือ parse_inventory",
|
||||
"workflow.decision.matched_confirmed": "ยืนยันแล้ว สามารถดำเนินการสร้างไฟล์ Excel และอัปโหลดไปยังระบบขนส่งต่อได้",
|
||||
"workflow.decision.confirm_invalid_state": "ไม่สามารถใช้ confirm ในสถานะปัจจุบันได้ โปรดทำ inventory matching ให้เสร็จก่อน หรือใช้ confirm_inventory_mapping / reparse",
|
||||
"workflow.decision.mapping_not_needed": "ขณะนี้ยังไม่ต้องยืนยันการจับคู่คอลัมน์สต็อก",
|
||||
"workflow.decision.mapping_missing_reservation_warning": "ไฟล์สต็อกต้องมีหัวคอลัมน์ Reservation ID (ค่าภายในคอลัมน์นี้สามารถเว้นว่างได้) โปรดใช้ Fix Mapping เพื่อเลือกคอลัมน์ Reservation ID ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกที่มีคอลัมน์นี้อีกครั้ง",
|
||||
"workflow.decision.mapping_correction_invalid_state": "ขณะนี้งานไม่ได้อยู่ในขั้นตอนยืนยันการจับคู่คอลัมน์สต็อก จึงไม่สามารถแก้ไข mapping ได้",
|
||||
"workflow.decision.read_inventory_preview_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}",
|
||||
"workflow.decision.mapping_preview_note": "ไม่พบไฟล์ Excel ที่อัปโหลดไว้ โปรดวางตารางสต็อกขนาดเล็กหรืออัปโหลดใหม่ แล้วจึงเรียก apply_inventory_mapping / parse_inventory",
|
||||
"workflow.decision.mapping_correction_needed": "งานได้ย้อนกลับมาที่ขั้นตอนจับคู่คอลัมน์แล้ว โปรดส่ง map_json ใหม่ตาม schema_preview แล้วเรียก apply_inventory_mapping",
|
||||
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.decision.inventory_cleared": "ล้าง snapshot สต็อกแล้ว โปรดอัปโหลดใหม่หรือวางข้อมูลสต็อก แล้วดำเนินการต่อในงานปัจจุบัน",
|
||||
"workflow.decision.unknown": "ไม่รู้จัก decision: {decision}",
|
||||
"workflow.inventory.task_not_found": "ไม่พบรหัสงาน",
|
||||
"workflow.inventory.uploaded_file_missing": "ไม่พบไฟล์สต็อกที่อัปโหลดไว้ โปรดอัปโหลดไฟล์ Excel ผ่าน POST /tools/upload_inventory_file ก่อน",
|
||||
"workflow.inventory.text_too_large": "ข้อความสต็อกมีขนาดใหญ่เกินไป ({chars} ตัวอักษร, จำกัด {max_chars}) โปรดอย่าส่งเนื้อหา Excel ทั้งหมดเข้า LLM ให้เรียก POST /tools/upload_inventory_file ก่อน แล้วจึงใช้ parse_inventory(use_uploaded_file=true)",
|
||||
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
|
||||
"workflow.inventory.parse_failed": "ไม่สามารถแยกรายการสต็อกได้ สำหรับไฟล์ Excel ขนาดใหญ่ให้ใช้ upload_inventory_file; สำหรับตารางเล็กสามารถวางข้อความได้; หากไม่มีสต็อกให้ใช้ RPA",
|
||||
"workflow.inventory.preview_read_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}",
|
||||
"workflow.inventory.preview_ready": "อ่านหัวตารางและแถวตัวอย่างของสต็อกแล้ว โปรดอนุมานการจับคู่คอลัมน์จาก schema_preview แล้วเรียก apply_inventory_mapping(map_json=...)",
|
||||
"workflow.inventory.preview_next": "อนุมาน JSON จาก data.schema_preview.headers และ sample_rows: {\"sku\":\"<คอลัมน์>\",\"reservation_id\":\"<คอลัมน์>\",\"available_qty\":\"<คอลัมน์>\"} แล้วจึงเรียก apply_inventory_mapping",
|
||||
"workflow.inventory.uploaded_file_missing_short": "ไม่พบไฟล์สต็อกที่อัปโหลดไว้ โปรดเรียก upload_inventory_file ก่อน",
|
||||
"workflow.inventory.mapping_invalid": "map_json ไม่ถูกต้องหรือไม่ครบ ต้องระบุ {\"sku\":\"ชื่อคอลัมน์\",\"reservation_id\":\"ชื่อคอลัมน์\",\"available_qty\":\"ชื่อคอลัมน์\"} โดยคอลัมน์ Reservation ID สามารถมีค่าว่างได้ แต่ต้องมีหัวคอลัมน์นี้",
|
||||
"workflow.inventory.mapping_header_mismatch": "การจับคู่คอลัมน์ไม่ตรงกับหัวตาราง Excel (หัวตารางอยู่ที่แถว {row}) {errors} โปรดเรียก apply_inventory_mapping ใหม่โดยอ้างอิง schema_preview.headers",
|
||||
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
|
||||
"workflow.inventory.file_missing": "ไม่ได้รับฟิลด์ file",
|
||||
"workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .xls / .csv",
|
||||
"workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
|
||||
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
|
||||
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
|
||||
"workflow.inventory.completed_task_locked": "งานนี้เสร็จสิ้นแล้ว จึงไม่สามารถอัปโหลดสต็อกซ้ำได้ โปรดสลับไปยังงานที่ยังต้องดำเนินการ",
|
||||
"workflow.inventory.uploaded": "อัปโหลดไฟล์สต็อกแล้ว",
|
||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping ครบแล้ว จึงสามารถเรียก apply_inventory_mapping ได้ตรงจาก canvas โดยไม่ต้องผ่าน LLM",
|
||||
"workflow.inventory.uploaded_need_llm": " โปรดให้ LLM บน canvas อนุมานการจับคู่คอลัมน์ แล้วจึงเรียก apply_inventory_mapping",
|
||||
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.inventory.ready_for_match": "มี inventory snapshot อยู่แล้วและยืนยันการจับคู่คอลัมน์แล้ว สามารถเรียก match_inventory ได้",
|
||||
"workflow.inventory.unavailable": "ยังไม่มีข้อมูลสต็อกที่ใช้งานได้ โปรดลองส่งออกผ่าน RPA ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกของผู้ให้บริการขนส่งด้วยตนเอง",
|
||||
"workflow.fulfillment.task_not_found": "ไม่พบรหัสงาน",
|
||||
"workflow.fulfillment.match_running": "กำลังจับคู่สต็อก",
|
||||
"workflow.fulfillment.match_running_detail": "กำลังเทียบความต้องการกับสต็อกทีละบรรทัดด้วย SKU + Reservation ID",
|
||||
"workflow.fulfillment.match_progress_detail": "จับคู่แล้ว {processed}/{total} รายการ",
|
||||
"workflow.fulfillment.match_completed": "จับคู่สต็อกเสร็จแล้ว",
|
||||
"workflow.fulfillment.match_completed_ok_detail": "จับคู่แล้ว {count}/{count} รายการ และทุกรายการมีสต็อกเพียงพอ",
|
||||
"workflow.fulfillment.match_completed_shortage_detail": "จับคู่แล้ว {count}/{count} รายการ แต่ยังมีของขาดและต้องให้คนจัดการต่อ",
|
||||
"workflow.fulfillment.reservation_required": "กฎการจับคู่ปัจจุบันกำหนดให้ฝั่งคำสั่งซื้อมี Reservation ID ขณะนี้มี {count} รายการที่ขาด Reservation ID โปรดแยกใบแจ้งส่งสินค้าใหม่ก่อนแล้วค่อยจับคู่",
|
||||
"workflow.fulfillment.excel_gate_unmatched": "ยังจับคู่สต็อกไม่เสร็จ โปรดอัปโหลดสต็อก ยืนยันการจับคู่คอลัมน์ แล้วเรียก match_inventory ก่อน",
|
||||
"workflow.fulfillment.excel_exists": "สร้างไฟล์ Shipment Excel แล้ว: {file}",
|
||||
"workflow.fulfillment.match_first": "match_inventory (ต้องอัปโหลดสต็อกและยืนยันการจับคู่คอลัมน์ก่อน)",
|
||||
"workflow.fulfillment.generate_running": "กำลังสร้าง Shipment Excel",
|
||||
"workflow.fulfillment.generate_running_detail": "กำลังเติมรายการที่สามารถจัดส่งได้ลงในเทมเพลตของผู้ให้บริการขนส่ง",
|
||||
"workflow.fulfillment.generate_completed": "สร้าง Shipment Excel แล้ว",
|
||||
"workflow.fulfillment.generate_done": "สร้าง Shipment Excel แล้ว: {file}",
|
||||
"workflow.fulfillment.manual_already_done": "งาน {task_no} ถูกทำเครื่องหมายว่าเสร็จแล้ว จึงไม่ต้องดำเนินการซ้ำ",
|
||||
"workflow.fulfillment.manual_confirmed": "ยืนยันการอัปโหลดเข้าระบบขนส่งด้วยตนเองแล้ว",
|
||||
"workflow.fulfillment.task_completed": "งานเสร็จสิ้นแล้ว",
|
||||
"workflow.fulfillment.manual_done_message": "เรียบร้อย งาน {task_no} ยืนยันว่าเสร็จแล้ว ไม่ต้องดำเนินการต่อ",
|
||||
"workflow.fulfillment.upload_running": "RPA กำลังอัปโหลดอยู่ (ครั้งที่ {attempt}/{max_attempts}) รอแล้ว {elapsed}s / หมดเวลา {timeout}s โปรดลองอีกครั้งภายหลัง (แนะนำหลัง {remaining}s)",
|
||||
"workflow.fulfillment.upload_timeout_error": "RPA อัปโหลดหมดเวลา (>{timeout}s)",
|
||||
"workflow.fulfillment.upload_exhausted": "พยายามอัปโหลดผ่าน RPA มาแล้ว {attempts} ครั้งแต่ยังไม่สำเร็จ โปรดดาวน์โหลด Excel แล้วอัปโหลดด้วยตนเอง",
|
||||
"workflow.fulfillment.upload_triggered_wait": "ทริกเกอร์ RPA ให้อัปโหลดเข้าระบบขนส่งแล้ว กำลังรอผลตอบกลับ",
|
||||
"workflow.fulfillment.upload_triggered_detail": "พยายามอัปโหลดครั้งที่ {attempt}/{max_attempts}",
|
||||
"workflow.fulfillment.upload_triggered_message": "ทริกเกอร์ RPA ให้อัปโหลดเข้าระบบขนส่งแล้ว (ครั้งที่ {attempt}/{max_attempts}) หากไม่มี callback ภายใน {timeout}s สามารถลองใหม่ได้ และถ้าเกินจำนวนครั้งสูงสุดจะเปลี่ยนเป็นอัปโหลดด้วยตนเอง",
|
||||
"workflow.fulfillment.upload_takeover": "RPA อัปโหลดอัตโนมัติไม่สำเร็จ ต้องให้คนรับช่วงต่อ",
|
||||
"workflow.fulfillment.upload_takeover_detail": "โปรดดาวน์โหลด Excel แล้วอัปโหลดด้วยตนเอง จากนั้นค่อยยืนยันว่าเสร็จแล้ว",
|
||||
"workflow.fulfillment.upload_trigger_failed": "ไม่ได้ตั้งค่าไดเรกทอรีอัปโหลดของ RPA หรือการทริกเกอร์ล้มเหลว",
|
||||
"workflow.fulfillment.upload_takeover_message": "RPA อัปโหลดอัตโนมัติล้มเหลวหรือยังไม่ได้ตั้งค่า โปรดดาวน์โหลด Excel แล้วอัปโหลดด้วยตนเองในระบบขนส่ง จากนั้นแจ้งฉันเมื่อเสร็จแล้ว",
|
||||
"workflow.fulfillment.rpa_uploaded": "RPA อัปโหลดเข้าระบบขนส่งสำเร็จแล้ว",
|
||||
"workflow.fulfillment.rpa_uploaded_done": "RPA อัปโหลดเข้าระบบขนส่งสำเร็จแล้ว และงานเสร็จสมบูรณ์",
|
||||
"workflow.fulfillment.upload_failed_wait_manual": "อัปโหลดเข้าระบบขนส่งล้มเหลว กำลังรอให้คนจัดการต่อ",
|
||||
"workflow.fulfillment.upload_failed_detail": "สามารถลองอัปโหลดใหม่หรือเปลี่ยนเป็นอัปโหลดด้วยตนเองได้",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_file_store.py
|
||||
|
||||
用途:管理货代发货批次级库存快照文件、任务 link 与解析结果投影。
|
||||
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
|
||||
逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_snapshot import (
|
||||
parse_inventory_excel_with_meta,
|
||||
read_inventory_schema_preview,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
|
||||
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def _can_relink_inventory(task: ShippingTask) -> bool:
|
||||
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
|
||||
return str(task.process_status or "").strip().lower() not in _TERMINAL_PROCESS_STATUSES
|
||||
|
||||
|
||||
def _safe_ref(value: str) -> str:
|
||||
return re.sub(r"[^\w\-]+", "_", str(value or "").strip()) or "unknown"
|
||||
|
||||
|
||||
def generate_inventory_file_no() -> str:
|
||||
"""生成库存快照外部编号。"""
|
||||
from datetime import datetime
|
||||
|
||||
return f"SIF-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def inventory_file_upload_path(inventory_file_no: str) -> Path:
|
||||
"""库存快照文件标准落盘路径(inventory_uploads/{inventory_file_no}/inventory.xlsx)。"""
|
||||
return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / "inventory.xlsx"
|
||||
|
||||
|
||||
def active_inventory_file_for_task(task: ShippingTask) -> ShippingInventoryFile | None:
|
||||
"""读取任务当前 active link 指向的库存快照。"""
|
||||
if task.id is None:
|
||||
return None
|
||||
link = (
|
||||
ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True)
|
||||
.order_by(ShippingTaskInventoryLink.id.desc())
|
||||
.first()
|
||||
)
|
||||
return link.inventory_file if link else None
|
||||
|
||||
|
||||
def active_inventory_lines_for_task(task: ShippingTask) -> list[dict[str, Any]]:
|
||||
"""解析任务可用于匹配的库存行;批次库存快照优先,单票任务回退到任务投影字段。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file and isinstance(inv_file.inventory_lines_json, list):
|
||||
return [row for row in inv_file.inventory_lines_json if isinstance(row, dict)]
|
||||
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
|
||||
|
||||
def has_uploaded_inventory_file(task: ShippingTask) -> bool:
|
||||
"""任务是否已有可读取的库存上传文件。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file:
|
||||
return Path(inv_file.storage_path).is_file()
|
||||
return False
|
||||
|
||||
|
||||
def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> ShippingInventoryFile:
|
||||
"""
|
||||
保存库存 Excel 并创建批次级库存快照。
|
||||
|
||||
【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。
|
||||
"""
|
||||
inventory_file_no = generate_inventory_file_no()
|
||||
path = inventory_file_upload_path(inventory_file_no)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
upload.save(str(path))
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = str(upload.filename or path.name)
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
batch_id=task.batch_id,
|
||||
user_id=task.user_id,
|
||||
source_file_name=str(upload.filename or "").strip() or path.name,
|
||||
storage_path=str(path),
|
||||
schema_preview_json=preview,
|
||||
share_mode="batch_all" if task.batch_id else "task_only",
|
||||
line_count=0,
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
|
||||
candidates = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task]
|
||||
linked_tasks = [item for item in candidates if _can_relink_inventory(item)]
|
||||
for item in linked_tasks:
|
||||
replace_task_inventory_link(item, inv_file, role="owner" if item.id == task.id else "member")
|
||||
return inv_file
|
||||
|
||||
|
||||
def replace_task_inventory_link(
|
||||
task: ShippingTask,
|
||||
inv_file: ShippingInventoryFile,
|
||||
*,
|
||||
role: str = "member",
|
||||
) -> ShippingTaskInventoryLink:
|
||||
"""替换任务 active 库存 link,保留历史 link 审计。"""
|
||||
if task.id is None:
|
||||
db.session.flush()
|
||||
existing = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all()
|
||||
for link in existing:
|
||||
link.is_active = False
|
||||
new_link = ShippingTaskInventoryLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inv_file.id,
|
||||
link_role=role,
|
||||
access_mode="readonly",
|
||||
linked_by_user_id=inv_file.user_id,
|
||||
)
|
||||
db.session.add(new_link)
|
||||
db.session.add(
|
||||
ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type="inventory_file_linked",
|
||||
detail_json={
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"role": role,
|
||||
"share_mode": inv_file.share_mode,
|
||||
},
|
||||
)
|
||||
)
|
||||
return new_link
|
||||
|
||||
|
||||
def read_linked_inventory_schema_preview(task: ShippingTask) -> dict[str, Any]:
|
||||
"""读取任务 active 库存快照的 schema preview。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if not inv_file:
|
||||
raise FileNotFoundError(f"未找到任务 {task.task_no} 的库存快照")
|
||||
if inv_file.schema_preview_json:
|
||||
return dict(inv_file.schema_preview_json)
|
||||
path = Path(inv_file.storage_path)
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = inv_file.source_file_name or path.name
|
||||
inv_file.schema_preview_json = preview
|
||||
return preview
|
||||
|
||||
|
||||
def parse_linked_inventory_file(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
header_row_index: int | None = None,
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any], Path, ShippingInventoryFile]:
|
||||
"""解析任务 active 库存快照 Excel,并返回解析行、列元数据、文件路径和快照对象。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if not inv_file:
|
||||
raise FileNotFoundError(f"未找到任务 {task.task_no} 的库存快照")
|
||||
path = Path(inv_file.storage_path)
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
|
||||
lines, column_meta = parse_inventory_excel_with_meta(
|
||||
path,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=header_row_index,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
return lines, column_meta, path, inv_file
|
||||
|
||||
|
||||
def apply_inventory_parse_result_to_linked_tasks(
|
||||
inv_file: ShippingInventoryFile,
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str | None = None,
|
||||
mapping_confirmed: bool = False,
|
||||
) -> list[ShippingTask]:
|
||||
"""把库存快照解析结果写到文件层,并同步投影到所有 active link 任务。"""
|
||||
inv_file.inventory_lines_json = inventory_lines
|
||||
inv_file.line_count = len(inventory_lines)
|
||||
if field_mapping:
|
||||
inv_file.field_mapping_json = field_mapping
|
||||
if mapping_source:
|
||||
inv_file.mapping_source = mapping_source
|
||||
inv_file.mapping_confirmed = bool(mapping_confirmed)
|
||||
|
||||
linked_tasks: list[ShippingTask] = []
|
||||
for link in inv_file.links or []:
|
||||
if not link.is_active or not link.task:
|
||||
continue
|
||||
if not _can_relink_inventory(link.task):
|
||||
continue
|
||||
link.task.inventory_snapshot_id = inv_file.id
|
||||
link.task.inventory_lines_json = inventory_lines
|
||||
linked_tasks.append(link.task)
|
||||
return linked_tasks
|
||||
|
||||
|
||||
def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) -> list[str]:
|
||||
"""返回库存快照当前 active link 关联的任务编号列表。"""
|
||||
if not inv_file:
|
||||
return []
|
||||
task_nos: list[str] = []
|
||||
for link in inv_file.links or []:
|
||||
if link.is_active and link.task and link.task.task_no:
|
||||
task_nos.append(link.task.task_no)
|
||||
return sorted(set(task_nos))
|
||||
|
||||
|
||||
def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> bool:
|
||||
"""
|
||||
按库存快照关联任务批量入队续跑。
|
||||
|
||||
【AI 触发时机】:库存快照完成解析或字段映射确认后由内部调用;不暴露给 Agent。
|
||||
"""
|
||||
task_nos = [
|
||||
task_no
|
||||
for task_no in linked_task_nos_for_inventory_file(inv_file)
|
||||
if inv_file
|
||||
and any(
|
||||
link.is_active
|
||||
and link.task
|
||||
and link.task.task_no == task_no
|
||||
and _can_relink_inventory(link.task)
|
||||
for link in inv_file.links or []
|
||||
)
|
||||
]
|
||||
if not task_nos:
|
||||
return False
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
from app.services.shipping_notice.tool_common import set_task_step_progress
|
||||
|
||||
started = False
|
||||
for link in inv_file.links or []:
|
||||
task = link.task
|
||||
if not link.is_active or not task:
|
||||
continue
|
||||
if task.task_no in task_nos and task.process_status in {"inventory_ready", "parsed", "waiting_inventory"}:
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message="本批库存快照已确认,等待匹配库存",
|
||||
progress_percent=5,
|
||||
detail="后端已按批次将任务加入库存匹配队列",
|
||||
)
|
||||
db.session.commit()
|
||||
for task_no in task_nos:
|
||||
started = start_task_orchestrator(task_no) or started
|
||||
return started
|
||||
@@ -16,6 +16,11 @@ from flask import current_app
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
apply_inventory_parse_result_to_linked_tasks,
|
||||
start_inventory_file_linked_tasks,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping import mapping_is_complete
|
||||
from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping
|
||||
from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview
|
||||
@@ -213,7 +218,27 @@ def maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool:
|
||||
field_alignment = field_alignment_for_task(task)
|
||||
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
|
||||
log_task_event(task, "inventory_mapping_auto_confirmed", {"field_alignment": field_alignment})
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file:
|
||||
inv_file.mapping_confirmed = True
|
||||
for link in inv_file.links or []:
|
||||
linked_task = link.task
|
||||
if not link.is_active or not linked_task or linked_task.id == task.id:
|
||||
continue
|
||||
if awaiting_inventory_mapping_confirm(linked_task):
|
||||
apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED)
|
||||
log_task_event(
|
||||
linked_task,
|
||||
"inventory_mapping_auto_confirmed",
|
||||
{
|
||||
"field_alignment": field_alignment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
if inv_file:
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
return True
|
||||
|
||||
|
||||
@@ -255,6 +280,8 @@ def inventory_loaded_response(
|
||||
require_mapping_review: bool,
|
||||
event_type: str,
|
||||
chain_payload: dict[str, Any] | None = None,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
库存载入后的统一响应编排:写 inventory_lines → 映射复核或 inventory_ready → 可选 auto-chain。
|
||||
@@ -265,7 +292,18 @@ def inventory_loaded_response(
|
||||
"""
|
||||
# [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。
|
||||
# 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。
|
||||
task.inventory_lines_json = inventory_lines
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
linked_tasks: list[ShippingTask] = []
|
||||
if inv_file:
|
||||
linked_tasks = apply_inventory_parse_result_to_linked_tasks(
|
||||
inv_file,
|
||||
inventory_lines,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
mapping_confirmed=False,
|
||||
)
|
||||
else:
|
||||
task.inventory_lines_json = inventory_lines
|
||||
field_alignment = field_alignment_for_task(task, column_meta)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
@@ -292,8 +330,27 @@ def inventory_loaded_response(
|
||||
"source": source,
|
||||
"mapping_review": True,
|
||||
"column_meta": column_meta,
|
||||
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
|
||||
"linked_task_nos": [item.task_no for item in linked_tasks],
|
||||
},
|
||||
)
|
||||
for linked_task in linked_tasks:
|
||||
if linked_task.id == task.id:
|
||||
continue
|
||||
apply_task_transition(linked_task, TaskTransition.INVENTORY_ALIGN_REVIEW)
|
||||
log_task_event(
|
||||
linked_task,
|
||||
event_type,
|
||||
{
|
||||
"row_count": len(inventory_lines),
|
||||
"warnings": warnings or [],
|
||||
"source": source,
|
||||
"mapping_review": True,
|
||||
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
|
||||
"owner_task_no": task.task_no,
|
||||
"column_meta": column_meta,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
|
||||
if chained is not None:
|
||||
@@ -319,6 +376,9 @@ def inventory_loaded_response(
|
||||
# [STEP 3] 无需映射复核时,直接推进到 inventory_ready。
|
||||
# 这条路径主要服务于明确结构化库存输入,尽快把任务交给后续匹配阶段。
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_READY)
|
||||
for linked_task in linked_tasks:
|
||||
if linked_task.id != task.id:
|
||||
apply_task_transition(linked_task, TaskTransition.INVENTORY_READY)
|
||||
log_task_event(
|
||||
task,
|
||||
event_type,
|
||||
@@ -327,9 +387,13 @@ def inventory_loaded_response(
|
||||
"warnings": warnings or [],
|
||||
"source": source,
|
||||
"column_meta": column_meta,
|
||||
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
|
||||
"linked_task_nos": [item.task_no for item in linked_tasks],
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
if inv_file:
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
|
||||
@@ -8,14 +8,21 @@ services/shipping_notice/inventory_rpa_workflow.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
mark_inventory_source_review,
|
||||
resolve_inventory_source,
|
||||
save_task_rpa_inventory_source,
|
||||
task_rpa_inventory_source,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
|
||||
from app.services.shipping_notice.query_service import (
|
||||
resolve_task_from_payload,
|
||||
serialize_task_for_tool,
|
||||
@@ -49,9 +56,160 @@ def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent
|
||||
)
|
||||
|
||||
|
||||
def inventory_rpa_wait_seconds(task: ShippingTask) -> tuple[int | None, int | None, int | None]:
|
||||
"""
|
||||
返回库存 RPA 当前等待耗时、超时时间和剩余秒数。
|
||||
【AI 触发时机】:需要判断库存 RPA 是否还应等待、是否该调度复查或兜底推进时调用。
|
||||
|
||||
Args:
|
||||
task: 当前发货通知任务,必须已经进入 RPA 库存等待态。
|
||||
|
||||
Returns:
|
||||
tuple[int | None, int | None, int | None]: (elapsed_seconds, timeout_seconds, remaining_seconds)。
|
||||
"""
|
||||
if (
|
||||
task.pending_human_reason != PH_RPA_PENDING
|
||||
or task.process_status != "waiting_inventory"
|
||||
or task.inventory_lines_json
|
||||
):
|
||||
return None, None, None
|
||||
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
|
||||
if not last_trigger or not isinstance(last_trigger.created_at, datetime):
|
||||
return None, None, None
|
||||
timeout_seconds = rpa_inventory_timeout_seconds()
|
||||
elapsed = max(int((datetime.utcnow() - last_trigger.created_at).total_seconds()), 0)
|
||||
remaining = max(timeout_seconds - elapsed, 0)
|
||||
return elapsed, timeout_seconds, remaining
|
||||
|
||||
|
||||
def next_inventory_rpa_recheck_at(task: ShippingTask) -> datetime | None:
|
||||
"""
|
||||
计算库存 RPA 下一次复查时间点。
|
||||
【AI 触发时机】:worker 给等待外部 RPA 回执的任务创建延迟复查 job 时调用。
|
||||
"""
|
||||
elapsed, timeout_seconds, remaining = inventory_rpa_wait_seconds(task)
|
||||
if elapsed is None or timeout_seconds is None or remaining is None:
|
||||
return None
|
||||
return datetime.utcnow() + timedelta(seconds=max(remaining, 1))
|
||||
|
||||
|
||||
def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "workspace_fallback") -> dict[str, Any] | None:
|
||||
"""
|
||||
对已超时的库存 RPA 等待态做一次幂等复查。
|
||||
【AI 触发时机】:工作台查询发现任务仍卡在 RPA 等待且已超过超时时间时调用;常规链路仍由 worker 调度。
|
||||
|
||||
核心逻辑:未超时立即返回 None;已超时则复用 ensure_inventory_via_rpa,让既有状态机负责失败事件、自动重试和耗尽转人工。
|
||||
Args:
|
||||
task: 当前发货通知任务。
|
||||
source: 复查来源,用于审计排障。
|
||||
|
||||
Returns:
|
||||
dict | None: 实际触发复查时返回 Tool 响应;未触发时返回 None。
|
||||
"""
|
||||
elapsed, timeout_seconds, remaining = inventory_rpa_wait_seconds(task)
|
||||
if elapsed is None or timeout_seconds is None or remaining is None:
|
||||
return None
|
||||
if remaining > 0:
|
||||
return None
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_wait_rechecked",
|
||||
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
|
||||
)
|
||||
db.session.flush()
|
||||
return ensure_inventory_via_rpa(task, mode="auto")
|
||||
|
||||
|
||||
def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
确认当前任务的库存 RPA 来源,并继续触发库存导出。
|
||||
【AI 触发时机】:当用户在库存源确认检查点选择一个 source_code 后调用;禁止用自然语言中的任意 URL 直接写入。
|
||||
"""
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
source_code = str(payload.get("source_code") or "").strip().upper()
|
||||
source = build_rpa_inventory_source(source_code)
|
||||
if not source:
|
||||
return tool_response(status="failed", task=task, message="库存源不存在或未启用")
|
||||
|
||||
save_task_rpa_inventory_source(task, source)
|
||||
task.pending_human_reason = None
|
||||
task.review_status = None
|
||||
task.error_message = None
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_confirmed",
|
||||
{
|
||||
"source_code": source.get("source_code"),
|
||||
"source_type": source.get("source_type"),
|
||||
"confirmed_by": "user",
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
return ensure_inventory_via_rpa(task, mode=str(payload.get("mode") or "auto"))
|
||||
|
||||
|
||||
def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]:
|
||||
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
manual_retry_round = mode == "retry_rpa"
|
||||
|
||||
# [STEP 0] 库存 RPA 必须先确定唯一库存源;Dify 只给目的地线索,HXOPS 规则负责最终裁决。
|
||||
rpa_source = task_rpa_inventory_source(task)
|
||||
if not rpa_source:
|
||||
resolution = resolve_inventory_source(task)
|
||||
if resolution.status == "resolved" and resolution.source:
|
||||
rpa_source = resolution.source
|
||||
save_task_rpa_inventory_source(task, rpa_source, resolution=resolution)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_resolved",
|
||||
{
|
||||
"source_code": rpa_source.get("source_code"),
|
||||
"source_type": rpa_source.get("source_type"),
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
else:
|
||||
mark_inventory_source_review(task, resolution)
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
|
||||
task.error_message = "无法根据发货通知唯一确定库存查询来源"
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="库存查询来源待确认",
|
||||
progress_percent=30,
|
||||
current=len(resolution.candidates),
|
||||
total=len(resolution.candidates),
|
||||
detail="请确认本票应使用哪个 RPA 库存来源后继续。",
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_review_required",
|
||||
{
|
||||
"status": resolution.status,
|
||||
"reason": resolution.reason,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
"candidate_source_codes": [item.get("source_code") for item in resolution.candidates],
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="无法根据发货通知唯一确定库存查询来源,请选择库存源后继续 RPA 获取库存。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"inventory_source_candidates": resolution.candidates,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
|
||||
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
|
||||
@@ -137,21 +295,44 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
|
||||
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
|
||||
attempt_no = attempts + 1
|
||||
trigger = write_inventory_export_trigger(task.task_no, {"mode": mode, "attempt": attempt_no})
|
||||
trigger = write_inventory_export_trigger(
|
||||
task.task_no,
|
||||
{
|
||||
"mode": mode,
|
||||
"attempt": attempt_no,
|
||||
"rpa_inventory_source": rpa_source,
|
||||
},
|
||||
)
|
||||
if trigger:
|
||||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
||||
task.error_message = None
|
||||
progress_message = (
|
||||
"已手动重新触发 RPA 库存导出,等待结果"
|
||||
if manual_retry_round
|
||||
else "已触发 RPA 库存导出,等待结果"
|
||||
)
|
||||
progress_detail = (
|
||||
f"新一轮第 {attempt_no}/{max_attempts} 次尝试"
|
||||
if manual_retry_round
|
||||
else f"第 {attempt_no}/{max_attempts} 次尝试"
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="已触发 RPA 库存导出,等待结果",
|
||||
message=progress_message,
|
||||
progress_percent=60,
|
||||
current=attempt_no,
|
||||
total=max_attempts,
|
||||
detail=f"第 {attempt_no}/{max_attempts} 次尝试",
|
||||
detail=progress_detail,
|
||||
extra={"manual_retry_round": manual_retry_round} if manual_retry_round else None,
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_triggered",
|
||||
{"trigger": trigger, "attempt": attempt_no, "manual_retry_round": manual_retry_round},
|
||||
)
|
||||
log_task_event(task, "inventory_rpa_triggered", {"trigger": trigger, "attempt": attempt_no})
|
||||
|
||||
if attempt_no >= max_attempts and not task.inventory_lines_json:
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
@@ -165,14 +346,16 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
response_prefix = (
|
||||
f"已手动重新触发 RPA 库存导出(新一轮第 {attempt_no}/{max_attempts} 次)。"
|
||||
if manual_retry_round
|
||||
else f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=(
|
||||
f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
|
||||
f"若 {timeout_seconds}s 内无回调/无落盘文件,可继续重试;超过最大次数将转人工上传。"
|
||||
),
|
||||
message=f"{response_prefix}若 {timeout_seconds}s 内无回调/无落盘文件,可继续重试;超过最大次数将转人工上传。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"rpa": {
|
||||
@@ -183,7 +366,20 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
},
|
||||
)
|
||||
|
||||
log_task_event(task, "inventory_rpa_retry_requested", {})
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = "RPA 库存目录未配置或触发失败"
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="RPA 库存触发失败",
|
||||
progress_percent=100,
|
||||
current=0,
|
||||
total=max_attempts,
|
||||
detail="请重试 RPA 自动导出,或手动上传货代库存 Excel。",
|
||||
)
|
||||
log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_rules.py
|
||||
|
||||
用途:根据发货通知目的地/港口/仓库线索解析应使用的库存 RPA 源。
|
||||
依赖:inventory_sources、ShippingTask step_payload_json/单头/订单行。
|
||||
逻辑:Dify 只提供候选字段;本模块负责标准化、规则命中、唯一性判断和写入任务上下文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
|
||||
|
||||
|
||||
ROUTE_RULES: tuple[dict[str, Any], ...] = (
|
||||
{"source_code": "DSV360_AWSBI", "aliases": ("BISON", "AWSBI")},
|
||||
{"source_code": "DSV360_AWSCV", "aliases": ("CINCINNATI", "CVG", "AWSCV")},
|
||||
{"source_code": "DSV360_AWSDU", "aliases": ("DUB", "DUBLIN")},
|
||||
{"source_code": "DSV360_AWSAMS", "aliases": ("MOERDIJK", "AMS", "AWSAMS")},
|
||||
{"source_code": "DSV360_AWSSL", "aliases": ("USLCK", "SALT LAKE CITY", "SALTLAKECITY")},
|
||||
{"source_code": "DSV360_AWSSG", "aliases": ("SINGAPORE", "SG")},
|
||||
{"source_code": "CRANE_TZR2", "aliases": ("TZR2", "THAILAND")},
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventorySourceResolution:
|
||||
"""库存源解析结果。"""
|
||||
|
||||
status: str
|
||||
source: dict[str, Any] | None
|
||||
candidates: list[dict[str, Any]]
|
||||
destination_candidates: list[str]
|
||||
reason: str = ""
|
||||
|
||||
|
||||
def normalize_destination(value: Any) -> str:
|
||||
"""将 Dify/单据中的目的地线索标准化成可匹配 token。"""
|
||||
text = str(value or "").strip().upper()
|
||||
if not text:
|
||||
return ""
|
||||
return re.sub(r"[^A-Z0-9]+", " ", text).strip()
|
||||
|
||||
|
||||
def _append_candidate(candidates: list[str], value: Any) -> None:
|
||||
text = normalize_destination(value)
|
||||
if text and text not in candidates:
|
||||
candidates.append(text)
|
||||
|
||||
|
||||
def _extract_destination_object(candidates: list[str], value: Any) -> None:
|
||||
if not isinstance(value, dict):
|
||||
_append_candidate(candidates, value)
|
||||
return
|
||||
for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text"):
|
||||
_append_candidate(candidates, value.get(key))
|
||||
|
||||
|
||||
def extract_destination_candidates(task: ShippingTask) -> list[str]:
|
||||
"""
|
||||
从任务解析结果提取目的地/港口/仓库候选。
|
||||
【AI 触发时机】:需要根据发货通知判断库存 RPA 源时调用,Dify 输出与后端字段都作为候选证据。
|
||||
"""
|
||||
candidates: list[str] = []
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
for item in payload.get("destination_candidates") or []:
|
||||
_append_candidate(candidates, item)
|
||||
_extract_destination_object(candidates, payload.get("destination"))
|
||||
_append_candidate(candidates, task.ship_to)
|
||||
for line in task.lines_json or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
_extract_destination_object(candidates, line.get("destination"))
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to"):
|
||||
_append_candidate(candidates, line.get(key))
|
||||
return candidates
|
||||
|
||||
|
||||
def _matches_alias(candidate: str, alias: str) -> bool:
|
||||
normalized_alias = normalize_destination(alias)
|
||||
return candidate == normalized_alias or normalized_alias in candidate.split() or normalized_alias in candidate
|
||||
|
||||
|
||||
def resolve_inventory_source(task: ShippingTask) -> InventorySourceResolution:
|
||||
"""根据任务目的地候选解析唯一库存源;无法唯一命中时返回人工确认所需候选。"""
|
||||
candidates = extract_destination_candidates(task)
|
||||
matched_codes: list[str] = []
|
||||
for candidate in candidates:
|
||||
for rule in ROUTE_RULES:
|
||||
if any(_matches_alias(candidate, alias) for alias in rule.get("aliases") or []):
|
||||
code = str(rule.get("source_code") or "").strip().upper()
|
||||
if code and code not in matched_codes:
|
||||
matched_codes.append(code)
|
||||
|
||||
if len(matched_codes) == 1:
|
||||
source = build_rpa_inventory_source(matched_codes[0])
|
||||
if source:
|
||||
return InventorySourceResolution(
|
||||
status="resolved",
|
||||
source=source,
|
||||
candidates=[source],
|
||||
destination_candidates=candidates,
|
||||
)
|
||||
if len(matched_codes) > 1:
|
||||
matched_sources = [
|
||||
source
|
||||
for code in matched_codes
|
||||
for source in [build_rpa_inventory_source(code)]
|
||||
if source
|
||||
]
|
||||
return InventorySourceResolution(
|
||||
status="ambiguous",
|
||||
source=None,
|
||||
candidates=matched_sources,
|
||||
destination_candidates=candidates,
|
||||
reason="matched_multiple_sources",
|
||||
)
|
||||
return InventorySourceResolution(
|
||||
status="unresolved",
|
||||
source=None,
|
||||
candidates=list_inventory_sources(),
|
||||
destination_candidates=candidates,
|
||||
reason="no_route_rule_matched",
|
||||
)
|
||||
|
||||
|
||||
def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""读取任务当前已确认的 rpa_inventory_source。"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
source = payload.get("rpa_inventory_source")
|
||||
return source if isinstance(source, dict) and source.get("source_code") else None
|
||||
|
||||
|
||||
def save_task_rpa_inventory_source(
|
||||
task: ShippingTask,
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
resolution: InventorySourceResolution | None = None,
|
||||
) -> None:
|
||||
"""把已确认库存源写入 task.step_payload_json,供后续 RPA trigger 使用。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload["rpa_inventory_source"] = source
|
||||
if resolution:
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": resolution.status,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
"reason": resolution.reason,
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceResolution) -> None:
|
||||
"""库存源无法唯一命中时,把候选项写入 task.step_payload_json 供前端/Agent 展示。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": resolution.status,
|
||||
"destination_candidates": resolution.destination_candidates,
|
||||
"reason": resolution.reason,
|
||||
"candidates": resolution.candidates,
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_sources.py
|
||||
|
||||
用途:定义发货通知库存 RPA 源配置,并构造写入 trigger 的标准 rpa_inventory_source。
|
||||
依赖:纯配置与校验逻辑;inventory_source_rules / inventory_rpa_workflow 调用本模块。
|
||||
逻辑:第一版先用代码配置承载 DSV 360 与 Crane FootPrint 的库存入口,后续可迁移到数据库规则表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
|
||||
INVENTORY_SOURCES: dict[str, dict[str, Any]] = {
|
||||
"DSV360_AWSBI": {
|
||||
"source_code": "DSV360_AWSBI",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Bison / AWSBI",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Bison",
|
||||
"program_label": "AWSBI",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory By Location 3lv",
|
||||
"owner_code": "CADU-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSCV": {
|
||||
"source_code": "DSV360_AWSCV",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Cincinnati / AWSCV",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Cincinnati",
|
||||
"program_label": "AWSCV",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CACV-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSDU": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Dublin",
|
||||
"program_label": "AWSDU - Prod (JDA)",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CADU-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSAMS": {
|
||||
"source_code": "DSV360_AWSAMS",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Moerdijk / AWSAMS",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Moerdijk",
|
||||
"program_label": "AWSAMS",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CADU-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSSL": {
|
||||
"source_code": "DSV360_AWSSL",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Salt Lake City / AWSSL",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Salt Lake City",
|
||||
"program_label": "AWSSL",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CACV-0000000100",
|
||||
},
|
||||
},
|
||||
"DSV360_AWSSG": {
|
||||
"source_code": "DSV360_AWSSG",
|
||||
"source_type": "dsv360",
|
||||
"display_name": "DSV 360 / Singapore / AWSSG - Prod (JDA)",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {
|
||||
"program_group": "Singapore",
|
||||
"program_label": "AWSSG - Prod (JDA)",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
"owner_code": "CACV-0000000100",
|
||||
},
|
||||
},
|
||||
"CRANE_TZR2": {
|
||||
"source_code": "CRANE_TZR2",
|
||||
"source_type": "crane_footprint",
|
||||
"display_name": "Crane FootPrint / Warehouse TZR2",
|
||||
"enabled": True,
|
||||
"entry_url": "https://wms-portal.craneww.com/#/on-hand-details-query",
|
||||
"query": {
|
||||
"owner_code": "0000000100",
|
||||
"project_code": None,
|
||||
"warehouse_code": "TZR2",
|
||||
},
|
||||
"export": {
|
||||
"report_name": "On Hand Details Query",
|
||||
"download_mode": "file_download",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_inventory_source(source_code: str | None) -> dict[str, Any] | None:
|
||||
"""按 source_code 返回启用的库存源配置副本。"""
|
||||
code = str(source_code or "").strip().upper()
|
||||
source = INVENTORY_SOURCES.get(code)
|
||||
if not source or not source.get("enabled", True):
|
||||
return None
|
||||
return deepcopy(source)
|
||||
|
||||
|
||||
def list_inventory_sources() -> list[dict[str, Any]]:
|
||||
"""返回所有启用库存源配置副本,供人工检查点展示候选项。"""
|
||||
return [
|
||||
deepcopy(source)
|
||||
for source in INVENTORY_SOURCES.values()
|
||||
if source.get("enabled", True)
|
||||
]
|
||||
|
||||
|
||||
def build_rpa_inventory_source(
|
||||
source_code: str | None,
|
||||
*,
|
||||
query_override: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造 RPA trigger 使用的 rpa_inventory_source。
|
||||
【AI 触发时机】:HXOPS 已确定库存源后,写 RPA trigger 或确认人工选择时调用。
|
||||
"""
|
||||
source = get_inventory_source(source_code)
|
||||
if not source:
|
||||
return None
|
||||
if query_override:
|
||||
query = dict(source.get("query") or {})
|
||||
for key, value in query_override.items():
|
||||
if value is not None and str(value).strip():
|
||||
query[key] = value
|
||||
source["query"] = query
|
||||
return source
|
||||
@@ -34,6 +34,13 @@ from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
inventory_loaded_response,
|
||||
inventory_mapping_checkpoint_response,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
has_uploaded_inventory_file,
|
||||
parse_linked_inventory_file,
|
||||
read_linked_inventory_schema_preview,
|
||||
save_batch_inventory_upload,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_snapshot import parse_inventory_text
|
||||
from app.services.shipping_notice.inventory_upload import (
|
||||
has_uploaded_task_inventory,
|
||||
@@ -46,12 +53,16 @@ from app.services.shipping_notice.match_rule_desc import extract_mapping_payload
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_by_ref,
|
||||
resolve_task_from_payload,
|
||||
serialize_batch_for_tool,
|
||||
serialize_task_for_tool,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | None:
|
||||
"""从 payload 解析 inventory_lines / inventory_lines_json。"""
|
||||
@@ -108,9 +119,10 @@ def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
|
||||
|
||||
def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Parse inventory from uploaded file, chat text, or structured JSON."""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
# [STEP 1] 先归一化库存输入来源与映射提示。
|
||||
# 同一个入口要兼容已上传文件、聊天粘贴文本、结构化 JSON 和 LLM 传入的 map_json 扩展字段。
|
||||
@@ -131,23 +143,34 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
# [STEP 2] 按来源解析库存内容。
|
||||
# 优先复用已上传文件;否则再回退到 structured 或 raw_text,避免大 Excel 直接走 LLM 文本链路。
|
||||
if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_task_inventory(task.task_no)):
|
||||
if not has_uploaded_task_inventory(task.task_no):
|
||||
has_uploaded_file = has_uploaded_inventory_file(task) or has_uploaded_task_inventory(task.task_no)
|
||||
if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_file):
|
||||
if not has_uploaded_file:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
|
||||
message=t("workflow.inventory.uploaded_file_missing", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
|
||||
task.task_no,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file:
|
||||
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
|
||||
task,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
else:
|
||||
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
|
||||
task.task_no,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
source = "uploaded_file"
|
||||
warnings.append(f"parsed from uploaded file: {path.name}")
|
||||
elif not inventory_lines:
|
||||
@@ -167,15 +190,13 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=(
|
||||
f"库存文本过大({len(raw_text)} 字符,上限 {max_chars})。"
|
||||
"请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 "
|
||||
"POST /tools/upload_inventory_file 上传,再 "
|
||||
"parse_inventory(use_uploaded_file=true)。"
|
||||
message=t("workflow.inventory.text_too_large", lang=lang).format(
|
||||
chars=len(raw_text),
|
||||
max_chars=max_chars,
|
||||
),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
next_required_action="upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
|
||||
next_required_action=t("workflow.inventory.upload_then_parse", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
@@ -192,7 +213,7 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
|
||||
message=t("workflow.inventory.parse_failed", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "warnings": warnings},
|
||||
checkpoint=CP_MAP_INFER,
|
||||
)
|
||||
@@ -211,67 +232,76 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Return headers + sample rows for LLM column mapping (small payload)."""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
if not has_uploaded_task_inventory(task.task_no):
|
||||
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
|
||||
message=t("workflow.inventory.uploaded_file_missing", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
try:
|
||||
preview = read_task_inventory_schema_preview(task.task_no)
|
||||
if has_uploaded_inventory_file(task):
|
||||
preview = read_linked_inventory_schema_preview(task)
|
||||
else:
|
||||
preview = read_task_inventory_schema_preview(task.task_no)
|
||||
except OSError as exc:
|
||||
return tool_response(status="failed", task_id=task.task_no, message=f"读取库存表头失败: {exc}")
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc),
|
||||
)
|
||||
|
||||
log_task_event(task, "inventory_schema_preview", {"headers": preview.get("headers")})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=(
|
||||
"已读取库存表头与样例行。请根据 schema_preview 推断列映射,"
|
||||
"调用 apply_inventory_mapping(map_json=...)。"
|
||||
),
|
||||
message=t("workflow.inventory.preview_ready", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "schema_preview": preview},
|
||||
checkpoint=CP_MAP_INFER,
|
||||
next_required_action=(
|
||||
"根据 data.schema_preview.headers 与 sample_rows 推断 JSON:"
|
||||
'{"sku":"<列名>","reservation_id":"<列名>","available_qty":"<列名>"},'
|
||||
"再调用 apply_inventory_mapping"
|
||||
),
|
||||
next_required_action=t("workflow.inventory.preview_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
)
|
||||
|
||||
|
||||
def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Apply LLM/manual column mapping and parse full uploaded inventory file."""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
# [STEP 1] 先校验上传文件与 schema preview 是否存在。
|
||||
# 映射应用必须基于真实上传文件的表头,不能只凭 LLM 文本猜测继续执行。
|
||||
if not has_uploaded_task_inventory(task.task_no):
|
||||
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="未找到已上传的库存文件。请先 upload_inventory_file。",
|
||||
message=t("workflow.inventory.uploaded_file_missing_short", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
try:
|
||||
preview = read_task_inventory_schema_preview(task.task_no)
|
||||
if has_uploaded_inventory_file(task):
|
||||
preview = read_linked_inventory_schema_preview(task)
|
||||
else:
|
||||
preview = read_task_inventory_schema_preview(task.task_no)
|
||||
except OSError as exc:
|
||||
return tool_response(status="failed", task_id=task.task_no, message=f"读取库存表头失败: {exc}")
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc),
|
||||
)
|
||||
|
||||
raw = payload_map_json(payload)
|
||||
|
||||
@@ -306,11 +336,7 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=(
|
||||
"map_json 无效或不完整。"
|
||||
'需要提供 {"sku":"列名","reservation_id":"列名","available_qty":"列名"}。'
|
||||
"(库存的 Reservation ID 列允许为空值,但必须有该列标题)"
|
||||
),
|
||||
message=t("workflow.inventory.mapping_invalid", lang=lang),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"schema_preview": preview,
|
||||
@@ -331,28 +357,41 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=(
|
||||
"列映射与 Excel 表头不匹配。"
|
||||
f"(表头在第 {header_row} 行)"
|
||||
+ " ".join(mapping_errors)
|
||||
+ " 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。"
|
||||
message=t("workflow.inventory.mapping_header_mismatch", lang=lang).format(
|
||||
row=header_row,
|
||||
errors=" ".join(mapping_errors),
|
||||
),
|
||||
data={**serialize_task_for_tool(task), "schema_preview": preview},
|
||||
)
|
||||
|
||||
try:
|
||||
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
|
||||
task.task_no,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=preview.get("header_row_index"),
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file:
|
||||
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
|
||||
task,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=preview.get("header_row_index"),
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
else:
|
||||
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
|
||||
task.task_no,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=preview.get("header_row_index"),
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
return tool_response(status="failed", task_id=task.task_no, message=str(exc))
|
||||
except OSError as exc:
|
||||
return tool_response(status="failed", task_id=task.task_no, message=f"解析库存失败: {exc}")
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.parse_failed_detail", lang=lang).format(error=exc),
|
||||
)
|
||||
|
||||
warnings = [f"parsed with mapping from uploaded file: {path.name}"]
|
||||
upsert_inventory_mapping(task.customer_code, preview=preview, field_mapping=field_mapping)
|
||||
@@ -365,6 +404,8 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
require_mapping_review=True,
|
||||
event_type="inventory_mapping_applied",
|
||||
chain_payload=payload,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
)
|
||||
|
||||
|
||||
@@ -372,16 +413,30 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
"""Save multipart Excel; return schema preview for LLM mapping (no full parse)."""
|
||||
task = get_task_by_ref(str(task_id or ""))
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
|
||||
lang = resolve_lang({"lang": None})
|
||||
if str(task.process_status or "").strip().lower() in _TERMINAL_PROCESS_STATUSES:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.completed_task_locked", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
if upload is None or not getattr(upload, "filename", None):
|
||||
return tool_response(status="failed", task_id=task.task_no, message="未收到 file 字段")
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.file_missing", lang=lang),
|
||||
)
|
||||
|
||||
filename = str(upload.filename or "").strip()
|
||||
if not filename.lower().endswith((".xlsx", ".xls", ".csv")):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="仅支持 .xlsx / .xls / .csv 库存文件",
|
||||
message=t("workflow.inventory.file_type_unsupported", lang=lang),
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -390,21 +445,25 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="正在上传并解析库存文件",
|
||||
message=t("workflow.inventory.uploading", lang=lang),
|
||||
progress_percent=35,
|
||||
detail=f"正在处理库存文件 {filename}",
|
||||
detail=t("workflow.inventory.uploading_detail", lang=lang).format(filename=filename),
|
||||
)
|
||||
db.session.flush()
|
||||
save_task_inventory_upload(task.task_no, upload)
|
||||
preview = read_task_inventory_schema_preview(task.task_no)
|
||||
inv_file = save_batch_inventory_upload(task, upload)
|
||||
preview = read_linked_inventory_schema_preview(task)
|
||||
except OSError as exc:
|
||||
return tool_response(status="failed", task_id=task.task_no, message=f"保存库存文件失败: {exc}")
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.save_failed", lang=lang).format(error=exc),
|
||||
)
|
||||
|
||||
template_mapping = resolve_inventory_mapping(task.customer_code, preview=preview)
|
||||
if template_mapping and mapping_is_complete(template_mapping):
|
||||
try:
|
||||
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
|
||||
task.task_no,
|
||||
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
|
||||
task,
|
||||
field_mapping=template_mapping,
|
||||
mapping_source="template",
|
||||
)
|
||||
@@ -418,6 +477,8 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
source="uploaded_file_template",
|
||||
require_mapping_review=True,
|
||||
event_type="inventory_template_mapping_used",
|
||||
field_mapping=template_mapping,
|
||||
mapping_source="template",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -431,31 +492,50 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
|
||||
apply_task_transition(task, TaskTransition.MAP_INFER)
|
||||
log_task_event(task, "inventory_file_uploaded", {"filename": filename, "headers": preview.get("headers")})
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_snapshot_created",
|
||||
{
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"share_mode": inv_file.share_mode,
|
||||
"batch_no": task.batch.batch_no if task.batch else None,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
upload_message = "库存文件已上传。"
|
||||
upload_message = t("workflow.inventory.uploaded", lang=lang)
|
||||
if suggested_complete:
|
||||
upload_message += " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。"
|
||||
upload_message += t("workflow.inventory.uploaded_suggested_complete", lang=lang)
|
||||
else:
|
||||
upload_message += " 请由画布 LLM 推断列映射后 apply_inventory_mapping。"
|
||||
upload_message += t("workflow.inventory.uploaded_need_llm", lang=lang)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=upload_message,
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"batch_no": task.batch.batch_no if task.batch else None,
|
||||
"batch": serialize_batch_for_tool(task.batch) if task.batch else None,
|
||||
"schema_preview": preview,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"share_mode": inv_file.share_mode,
|
||||
"linked_task_nos": [
|
||||
link.task.task_no
|
||||
for link in (inv_file.links or [])
|
||||
if link.is_active and link.task
|
||||
],
|
||||
SUGGEST_OK: suggested_complete,
|
||||
AUTO_MAP: auto_map,
|
||||
},
|
||||
next_required_action="apply_inventory_mapping(map_json=...)",
|
||||
next_required_action=t("workflow.inventory.apply_mapping_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
)
|
||||
|
||||
|
||||
def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
# [STEP 1] 优先接受当前请求直接携带的库存明细。
|
||||
# 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。
|
||||
@@ -488,7 +568,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message="已有库存快照且字段对齐已确认,可调用 match_inventory。",
|
||||
message=t("workflow.inventory.ready_for_match", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -498,6 +578,6 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="暂无可用库存数据。请重试 RPA 自动导出,或手动上传货代库存 Excel。",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
@@ -77,38 +77,20 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
"title": "Hxops Shipping Notice Tools",
|
||||
"title": "Shipping Notice Tools",
|
||||
"version": "1.0.0",
|
||||
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。鉴权:Authorization Bearer 或 X-Integration-Key。",
|
||||
"description": (
|
||||
"货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:"
|
||||
"通知理解、字段修订、库存映射建议、人工确认收口与状态查询;"
|
||||
"不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。"
|
||||
"如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,"
|
||||
"不要在自然语言正文里列出按钮清单或“推荐下一步”动作列表;"
|
||||
"可点击按钮由宿主系统根据 action_buttons 统一渲染。"
|
||||
"鉴权:Authorization Bearer 或 X-Integration-Key。"
|
||||
),
|
||||
},
|
||||
"servers": [{"url": server}],
|
||||
"paths": {
|
||||
"/tools/create_batch": _post_op(
|
||||
"create_batch",
|
||||
"创建发货批次 batch(一次多文件上传的聚合容器)",
|
||||
{
|
||||
"batch_no": _str_prop("已存在的批次编号(可选)。传入时将直接复用该批次。"),
|
||||
"user_id": _int_prop("Hxops 用户 ID(可选)"),
|
||||
"conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"),
|
||||
"file_count": _int_prop("本批通知文件数量"),
|
||||
},
|
||||
),
|
||||
"/tools/create_task": _post_op(
|
||||
"create_task",
|
||||
"创建发货任务 task(可挂到某个 batch)",
|
||||
{
|
||||
"batch_no": batch_id,
|
||||
"task_id": _str_prop("已存在的发货任务编号(可选)。传入时将直接复用该任务,禁止重复创建。"),
|
||||
"user_id": _int_prop("Hxops 用户 ID(可选)"),
|
||||
"conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"),
|
||||
"source_type": _str_prop("来源:manual|email|wecom|pdf", enum=["manual", "email", "wecom", "pdf"]),
|
||||
"source_file_name": _str_prop("原始通知文件名(多文件场景建议传)"),
|
||||
"source_file_type": _str_prop("原始通知文件类型(多文件场景建议传)"),
|
||||
"batch_index": _int_prop("当前任务在批次中的顺序,从 1 开始"),
|
||||
"batch_total": _int_prop("当前批次总任务数"),
|
||||
"raw_content": _str_prop("原始发货通知文本(可选,后续 parse 也可传入)"),
|
||||
},
|
||||
),
|
||||
"/tools/parse_notice": _post_op(
|
||||
"parse_notice",
|
||||
"解析发货通知文本",
|
||||
@@ -177,30 +159,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
required=["task_id", "line_index"],
|
||||
),
|
||||
"/tools/parse_inventory": _post_op(
|
||||
"parse_inventory",
|
||||
"解析库存。大 Excel 禁止 raw_inventory_text(会超 LLM token);"
|
||||
"先 POST /tools/upload_inventory_file 上传,再 get_inventory_schema_preview → "
|
||||
"apply_inventory_mapping;或 use_uploaded_file=true(规则映射兜底)。小表可粘贴文本。"
|
||||
"成功后 stop_agent_turn,等 confirm_inventory_mapping 后再 match。",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"use_uploaded_file": _str_prop(
|
||||
"true=解析该任务已上传的 Excel(服务端直传,不经过 LLM)",
|
||||
enum=["true", "false"],
|
||||
),
|
||||
MAP_JSON: _str_prop(
|
||||
'可选,列映射 JSON 字符串,如 {"sku":"AWS Sku","available_qty":"Qty Available"}'
|
||||
),
|
||||
"raw_inventory_text": _str_prop(
|
||||
"仅小表(约 <8 万字符)。大 Excel 勿传此字段,改用 upload_inventory_file"
|
||||
),
|
||||
"inventory_lines_json": _str_prop(
|
||||
'可选,已整理好的 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
|
||||
),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/get_inventory_schema_preview": _post_op(
|
||||
"get_inventory_schema_preview",
|
||||
"读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
|
||||
@@ -209,7 +167,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
),
|
||||
"/tools/apply_inventory_mapping": _post_op(
|
||||
"apply_inventory_mapping",
|
||||
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
|
||||
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由后台任务续跑",
|
||||
{
|
||||
"task_id": task_id,
|
||||
MAP_JSON: _str_prop(
|
||||
@@ -218,49 +176,20 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
required=["task_id", MAP_JSON],
|
||||
),
|
||||
"/tools/ensure_inventory": _post_op(
|
||||
"ensure_inventory",
|
||||
"确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"mode": _str_prop("auto=自动/RPA;retry_rpa=重试 RPA", enum=["auto", "retry_rpa"]),
|
||||
"inventory_lines_json": _str_prop(
|
||||
'手工库存 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
|
||||
),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/auto_progress": _post_op(
|
||||
"auto_progress",
|
||||
"按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID(可选,用于仅知道会话时定位任务)"),
|
||||
},
|
||||
),
|
||||
"/tools/match_inventory": _post_op(
|
||||
"match_inventory",
|
||||
"匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;"
|
||||
"未确认时调用会被拒绝并返回 forbidden_next_tools",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"inventory_lines_json": _str_prop("可选,覆盖库存 JSON 数组后再匹配"),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/submit_decision": _post_op(
|
||||
"submit_decision",
|
||||
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
|
||||
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
|
||||
"decision": _str_prop(
|
||||
"confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;"
|
||||
"confirm=确认继续;reject=驳回;retry_rpa=重试 RPA 库存导出;rematch=重新匹配;reparse=重新解析;"
|
||||
"confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
|
||||
enum=[
|
||||
"confirm",
|
||||
"confirm_parse",
|
||||
"reject",
|
||||
"retry_rpa",
|
||||
"rematch",
|
||||
"reparse",
|
||||
"confirm_inventory_mapping",
|
||||
@@ -272,25 +201,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
required=["decision"],
|
||||
),
|
||||
"/tools/generate_shipment_excel": _post_op(
|
||||
"generate_shipment_excel",
|
||||
"生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
|
||||
{"task_id": task_id},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/upload_to_freight": _post_op(
|
||||
"upload_to_freight",
|
||||
"上传 Excel 到货代系统(RPA 或手工确认)",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"mode": _str_prop(
|
||||
"auto=触发 RPA;retry_upload=重试;manual_confirm=手工上传完成",
|
||||
enum=["auto", "retry_upload", "manual_confirm"],
|
||||
),
|
||||
"freight_ref_no": _str_prop("货代系统单号(可选;manual_confirm 通常无需填写)"),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/get_task_status": _post_op(
|
||||
"get_task_status",
|
||||
"查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
|
||||
@@ -307,15 +217,5 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
required=["batch_no"],
|
||||
),
|
||||
"/tools/switch_focus_task": _post_op(
|
||||
"switch_focus_task",
|
||||
"切换当前批次的聚焦任务",
|
||||
{
|
||||
"batch_no": batch_id,
|
||||
"task_no": task_id,
|
||||
"target_task_no": task_id,
|
||||
},
|
||||
required=["batch_no"],
|
||||
),
|
||||
},
|
||||
}
|
||||
@@ -13,6 +13,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app.services.shipping_notice import fulfillment_workflow
|
||||
from app import db
|
||||
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_LOW_CONF, RS_PARSE_REVIEW
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
awaiting_inventory_mapping_confirm,
|
||||
@@ -21,8 +22,8 @@ from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, auto_rpa_inventory_enabled
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, auto_rpa_inventory_enabled, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
|
||||
@@ -87,6 +88,19 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。
|
||||
if not task.inventory_lines_json:
|
||||
if not auto_rpa_inventory_enabled():
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="未开启自动 RPA 获取库存",
|
||||
progress_percent=100,
|
||||
current=0,
|
||||
total=1,
|
||||
detail="请手动上传货代库存 Excel,或开启自动 RPA 后重试。",
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
|
||||
@@ -14,7 +14,7 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import desc
|
||||
from sqlalchemy import asc, desc
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
@@ -146,6 +146,55 @@ def compute_batch_process_summary(tasks: list[ShippingTask]) -> dict[str, int]:
|
||||
}
|
||||
|
||||
|
||||
def _is_task_completed(task: ShippingTask) -> bool:
|
||||
"""判断任务是否已进入完成态,用于会话级聚合统计。"""
|
||||
return str(task.process_status or "").strip().lower() in {"uploaded", "completed", "closed"}
|
||||
|
||||
|
||||
def _is_task_failed(task: ShippingTask) -> bool:
|
||||
"""判断任务是否失败或上传失败,用于会话级异常优先展示。"""
|
||||
return (
|
||||
str(task.process_status or "").strip().lower() in {"rejected"}
|
||||
or str(task.upload_status or "").strip().lower() == "failed"
|
||||
)
|
||||
|
||||
|
||||
def _is_task_needs_human(task: ShippingTask) -> bool:
|
||||
"""判断任务是否停在人工门;失败态不重复计入人工门。"""
|
||||
if _is_task_failed(task) or _is_task_completed(task):
|
||||
return False
|
||||
return bool(getattr(task, "review_status", None) or getattr(task, "pending_human_reason", None))
|
||||
|
||||
|
||||
def _is_task_active(task: ShippingTask) -> bool:
|
||||
"""判断任务是否仍处于自动执行或等待外部系统返回的状态。"""
|
||||
if _is_task_completed(task) or _is_task_failed(task) or _is_task_needs_human(task):
|
||||
return False
|
||||
status = str(task.process_status or "").strip().lower()
|
||||
return status not in {"created", "pending_review"} and bool(status)
|
||||
|
||||
|
||||
def compute_conversation_workspace_summary(batches: list[ShippingBatch]) -> dict[str, int]:
|
||||
"""按会话聚合多个批次的状态计数,供 Agent 会话级工作台展示。"""
|
||||
tasks: list[ShippingTask] = []
|
||||
for batch in batches:
|
||||
tasks.extend(list(batch.tasks or []))
|
||||
completed = sum(1 for task in tasks if _is_task_completed(task))
|
||||
failed = sum(1 for task in tasks if _is_task_failed(task))
|
||||
needs_human = sum(1 for task in tasks if _is_task_needs_human(task))
|
||||
running = sum(1 for task in tasks if _is_task_active(task))
|
||||
pending = max(0, len(tasks) - completed - failed - needs_human - running)
|
||||
return {
|
||||
"batch_count": len(batches),
|
||||
"total": len(tasks),
|
||||
"completed": completed,
|
||||
"running": running,
|
||||
"failed": failed,
|
||||
"needs_human": needs_human,
|
||||
"pending": pending,
|
||||
}
|
||||
|
||||
|
||||
def extract_task_no_from_text(text: str) -> str | None:
|
||||
"""从自然语言文本中提取 SN- 任务编号。"""
|
||||
match = _TASK_NO_RE.search(str(text or ""))
|
||||
@@ -243,9 +292,15 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"upload_mode": task.upload_mode,
|
||||
"upload_attempt": task.upload_attempt,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"error_message": task.error_message or task.upload_error_message,
|
||||
"conversation_id": task.conversation_id,
|
||||
"export_file_name": task.export_file_name,
|
||||
"freight_ref_no": task.freight_ref_no,
|
||||
"step_payload": task.step_payload_json or {},
|
||||
"rpa_inventory_source": (task.step_payload_json or {}).get("rpa_inventory_source") if isinstance(task.step_payload_json, dict) else None,
|
||||
"inventory_source_resolution": (task.step_payload_json or {}).get("inventory_source_resolution") if isinstance(task.step_payload_json, dict) else None,
|
||||
"shortage": task.shortage_json,
|
||||
"line_results": task.line_results_json or [],
|
||||
"created_at": task.created_at.isoformat() if task.created_at else None,
|
||||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||||
}
|
||||
@@ -321,6 +376,38 @@ def serialize_batch_summary(batch: ShippingBatch) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def serialize_conversation_batch_workspace(batch: ShippingBatch, user_id: int) -> dict[str, Any]:
|
||||
"""序列化会话工作台中的单个批次,包含批次摘要、任务列表与焦点任务。"""
|
||||
focus_task = get_focus_task_for_batch(batch.batch_no, user_id)
|
||||
return {
|
||||
**serialize_batch_summary(batch),
|
||||
"tasks": list_batch_task_summaries(batch),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
}
|
||||
|
||||
|
||||
def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict[str, Any]:
|
||||
"""返回一个 Agent 会话下用户可见的所有发货批次与聚合摘要。"""
|
||||
value = str(conversation_id or "").strip()
|
||||
batches: list[ShippingBatch] = []
|
||||
if value:
|
||||
batches = (
|
||||
ShippingBatch.query.filter(ShippingBatch.conversation_id == value)
|
||||
.filter((ShippingBatch.user_id == user_id) | (ShippingBatch.user_id.is_(None)))
|
||||
.order_by(asc(ShippingBatch.created_at), asc(ShippingBatch.id))
|
||||
.all()
|
||||
)
|
||||
ordered_batches = batches
|
||||
return {
|
||||
"conversation_id": value,
|
||||
"summary": compute_conversation_workspace_summary(ordered_batches),
|
||||
"batches": [
|
||||
serialize_conversation_batch_workspace(batch, user_id)
|
||||
for batch in ordered_batches
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
|
||||
"""工作台任务列表用的 SUMMARY 投影。"""
|
||||
return serialize_task(task, TaskProjection.SUMMARY)
|
||||
|
||||
@@ -1,139 +1,142 @@
|
||||
"""
|
||||
services/shipping_notice/queue_service.py
|
||||
|
||||
用途:货代发货后台任务最小队列实现(基于 KbJob 持久化表)。
|
||||
依赖:models.KbJob、jobs.types、shipping_notice.batch_orchestrator。
|
||||
逻辑:Web 侧负责 enqueue;worker 侧通过 claim/process 消费单票任务,避免使用进程内 threading。
|
||||
用途:货代发货后台任务队列适配层。
|
||||
依赖:app.jobs.queue、jobs.types、shipping_notice.batch_orchestrator。
|
||||
逻辑:发货通知只写入通用 jobs 表,worker 通过 Job Runner 消费后执行单票编排。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app import db
|
||||
from app.jobs.queue import enqueue, fail_job, finish_job, process_next_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import KbJob
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.constants import PH_RPA_PENDING, PH_UPLOAD_RPA_PENDING
|
||||
|
||||
logger = logging.getLogger('shipping-worker')
|
||||
|
||||
SHIPPING_NOTICE_JOB_DOMAIN = "shipping_notice"
|
||||
|
||||
|
||||
def shipping_task_execution_mode() -> str:
|
||||
"""读取发货任务执行模式;默认 worker,sync 仅用于开发排查。"""
|
||||
return str(current_app.config.get('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker') or 'worker').strip().lower()
|
||||
|
||||
|
||||
def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = None, batch_no: str | None = None) -> tuple[bool, str]:
|
||||
"""持久化一条单票发货后台任务;sync 模式下直接执行。"""
|
||||
"""持久化一条单票发货后台任务;不再复用 kb_jobs。"""
|
||||
normalized_task_no = str(task_no or '').strip().upper()
|
||||
if not normalized_task_no:
|
||||
return False, 'task_no is required'
|
||||
|
||||
existing = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||||
KbJob.status.in_(('queued', 'running')),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for job in existing:
|
||||
payload = job.payload_json or {}
|
||||
if str(payload.get('task_no') or '').strip().upper() == normalized_task_no:
|
||||
return True, 'already_queued'
|
||||
|
||||
job = KbJob(
|
||||
job_type=JobType.SHIPPING_NOTICE_RUN.value,
|
||||
status='queued',
|
||||
progress=0,
|
||||
message='等待后台处理发货任务',
|
||||
payload_json={
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_NOTICE_RUN,
|
||||
{
|
||||
'task_no': normalized_task_no,
|
||||
'batch_no': str(batch_no or '').strip().upper() or None,
|
||||
},
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
business_ref=normalized_task_no,
|
||||
created_by_id=created_by_id,
|
||||
message='等待后台处理发货任务',
|
||||
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_JOB_MAX_ATTEMPTS', 3) or 3),
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
if shipping_task_execution_mode() == 'sync':
|
||||
ok, result = run_shipping_notice_job({'job_id': job.id})
|
||||
ok, result = run_shipping_notice_job({'job_id': job_id})
|
||||
return ok, result
|
||||
if shipping_task_execution_mode() in ('worker', 'rq'):
|
||||
return True, 'queued_for_worker'
|
||||
return True, 'queued_manual'
|
||||
|
||||
|
||||
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||
"""回收长时间 running 的发货后台任务,避免 worker 被卡死任务阻塞。"""
|
||||
timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300))
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_sec)
|
||||
stale_jobs = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||||
KbJob.status == 'running',
|
||||
KbJob.started_at.isnot(None),
|
||||
KbJob.started_at < cutoff,
|
||||
)
|
||||
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
|
||||
.all()
|
||||
def _should_requeue_waiting_external_result(task_no: str) -> bool:
|
||||
"""RPA 等外部回传中的任务需要持续复查,直到成功、超时重试或转人工。"""
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
return False
|
||||
process_status = str(task.process_status or '').strip()
|
||||
pending_reason = str(task.pending_human_reason or '').strip()
|
||||
return (
|
||||
process_status == 'waiting_inventory'
|
||||
and pending_reason == PH_RPA_PENDING
|
||||
and not task.inventory_lines_json
|
||||
) or (
|
||||
process_status == 'waiting_upload'
|
||||
and pending_reason == PH_UPLOAD_RPA_PENDING
|
||||
)
|
||||
if not stale_jobs:
|
||||
return 0, 'no_stale_jobs'
|
||||
|
||||
now = datetime.utcnow()
|
||||
message = f'发货任务执行超时(超过 {int(timeout_sec)}s),已自动回收'
|
||||
for job in stale_jobs:
|
||||
job.status = 'failed'
|
||||
job.error_message = message
|
||||
job.message = message
|
||||
job.finished_at = now
|
||||
job.progress = 100
|
||||
db.session.commit()
|
||||
logger.warning('recovered %s stale shipping_notice job(s)', len(stale_jobs))
|
||||
return len(stale_jobs), f'recovered_{len(stale_jobs)}'
|
||||
|
||||
|
||||
def claim_next_shipping_notice_job() -> KbJob | None:
|
||||
"""原子领取下一条 queued 的发货后台任务。"""
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
job = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||||
KbJob.status == 'queued',
|
||||
)
|
||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.first()
|
||||
def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
|
||||
"""把等待 RPA 回调的任务重新放回队列,供 worker 下一轮做超时/重试判断。"""
|
||||
if not _should_requeue_waiting_external_result(task_no):
|
||||
return
|
||||
scheduled_at = None
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
task = get_task_by_ref(task_no)
|
||||
if task and str(task.pending_human_reason or '').strip() == PH_RPA_PENDING:
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import next_inventory_rpa_recheck_at
|
||||
|
||||
scheduled_at = next_inventory_rpa_recheck_at(task)
|
||||
if scheduled_at is None:
|
||||
recheck_seconds = max(
|
||||
float(current_app.config.get('SHIPPING_NOTICE_RPA_WAIT_RECHECK_SECONDS', 10) or 10),
|
||||
1,
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
logger.exception('failed to claim next shipping notice job')
|
||||
return None
|
||||
scheduled_at = datetime.utcnow() + timedelta(seconds=recheck_seconds)
|
||||
enqueue(
|
||||
JobType.SHIPPING_NOTICE_RUN,
|
||||
{
|
||||
'task_no': task_no,
|
||||
'batch_no': (job.payload_json or {}).get('batch_no') if job and job.payload_json else None,
|
||||
},
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
business_ref=task_no,
|
||||
created_by_id=job.created_by_id if job else None,
|
||||
message='等待 RPA 回传,稍后自动复查',
|
||||
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_JOB_MAX_ATTEMPTS', 3) or 3),
|
||||
dedupe_active=False,
|
||||
scheduled_at=scheduled_at,
|
||||
)
|
||||
|
||||
if not job:
|
||||
db.session.rollback()
|
||||
return None
|
||||
|
||||
job.status = 'running'
|
||||
job.started_at = job.started_at or now
|
||||
job.progress = max(int(job.progress or 0), 1)
|
||||
job.message = 'worker 已领取发货任务'
|
||||
db.session.commit()
|
||||
return job
|
||||
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||
"""兼容旧调用:回收通用 jobs 表里超时的发货任务。"""
|
||||
from app.jobs.queue import recover_stale_jobs
|
||||
|
||||
timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300))
|
||||
count = recover_stale_jobs(domain=SHIPPING_NOTICE_JOB_DOMAIN, timeout_seconds=timeout_sec)
|
||||
if count:
|
||||
logger.warning('recovered %s stale shipping_notice job(s)', count)
|
||||
return count, f'recovered_{count}' if count else 'no_stale_jobs'
|
||||
|
||||
|
||||
def claim_next_shipping_notice_job() -> Job | None:
|
||||
"""兼容旧调用:领取下一条发货通知通用任务。"""
|
||||
from app.jobs.queue import claim_next_job
|
||||
|
||||
return claim_next_job(
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
job_types=[JobType.SHIPPING_NOTICE_RUN],
|
||||
)
|
||||
|
||||
|
||||
def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | None = None) -> tuple[bool, str]:
|
||||
"""执行单票发货任务;既可被 worker 调用,也可被 sync enqueue 直调。"""
|
||||
"""执行单票发货任务;既可被通用 Job handler 调用,也可被 sync enqueue 直调。"""
|
||||
from app.services.shipping_notice.batch_orchestrator import _run_single_task
|
||||
|
||||
job_id = payload.get('job_id')
|
||||
job = db.session.get(KbJob, int(job_id)) if job_id else None
|
||||
raw_job_id = payload.get('job_id')
|
||||
job_id = int(raw_job_id) if raw_job_id else None
|
||||
job = db.session.get(Job, job_id) if job_id else None
|
||||
if job is None:
|
||||
task_no = str(payload.get('task_no') or '').strip().upper()
|
||||
else:
|
||||
@@ -146,28 +149,40 @@ def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | No
|
||||
status = str(result.get('status') or '').strip().lower()
|
||||
success = status in {'ok', 'running', 'needs_human', 'skipped'}
|
||||
|
||||
if job_id is not None:
|
||||
job = db.session.get(Job, job_id)
|
||||
if job is not None:
|
||||
job.progress = 100
|
||||
job.finished_at = datetime.utcnow()
|
||||
job.result_json = dict(result)
|
||||
job.message = str(result.get('message') or '')[:500] or '发货任务处理完成'
|
||||
if success:
|
||||
job.status = 'success'
|
||||
job.error_message = None
|
||||
finish_job(
|
||||
job,
|
||||
result=dict(result),
|
||||
message=str(result.get('message') or '')[:500] or '发货任务处理完成',
|
||||
)
|
||||
if status == 'running':
|
||||
_requeue_external_wait_job(task_no, job=job)
|
||||
else:
|
||||
job.status = 'failed'
|
||||
job.error_message = str(result.get('message') or 'shipping notice job failed')[:1000]
|
||||
db.session.commit()
|
||||
fail_job(
|
||||
job,
|
||||
error=str(result.get('message') or 'shipping notice job failed')[:1000],
|
||||
result=dict(result),
|
||||
retryable=True,
|
||||
)
|
||||
|
||||
if logger:
|
||||
logger.info('shipping_notice job task_no=%s status=%s', task_no, status or 'unknown')
|
||||
return success, status or 'done'
|
||||
|
||||
|
||||
def process_next_shipping_notice_job() -> tuple[bool, str]:
|
||||
def process_next_shipping_notice_job(ctx: Any | None = None) -> tuple[bool, str]:
|
||||
"""worker 消费发货后台队列的单步入口。"""
|
||||
recover_stale_shipping_notice_jobs()
|
||||
job = claim_next_shipping_notice_job()
|
||||
if not job:
|
||||
return False, 'no_job'
|
||||
return run_shipping_notice_job({'job_id': job.id})
|
||||
if ctx is None:
|
||||
from app.jobs.context import JobContext
|
||||
|
||||
ctx = JobContext(config=dict(current_app.config), logger=logger, extras={'queues': ['shipping']})
|
||||
return process_next_job(
|
||||
ctx=ctx,
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
job_types=[JobType.SHIPPING_NOTICE_RUN],
|
||||
timeout_config_key='SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS',
|
||||
default_timeout_seconds=300,
|
||||
)
|
||||
@@ -24,6 +24,10 @@ _INVENTORY_SUCCESS_EVENTS = {
|
||||
"inventory_template_mapping_used",
|
||||
}
|
||||
|
||||
_INVENTORY_ATTEMPT_RESET_EVENTS = _INVENTORY_SUCCESS_EVENTS | {
|
||||
"decision_retry_rpa",
|
||||
}
|
||||
|
||||
_UPLOAD_SUCCESS_EVENTS = {
|
||||
"upload_rpa_success",
|
||||
"upload_manual_confirmed",
|
||||
@@ -35,13 +39,13 @@ def inventory_rpa_attempts(task: ShippingTask | None) -> int:
|
||||
if not task or task.id is None:
|
||||
return 0
|
||||
|
||||
last_success = (
|
||||
last_reset = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||||
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_SUCCESS_EVENTS))
|
||||
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_ATTEMPT_RESET_EVENTS))
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
since: datetime | None = last_success.created_at if last_success else None
|
||||
since: datetime | None = last_reset.created_at if last_reset else None
|
||||
|
||||
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
|
||||
|
||||
@@ -24,6 +24,7 @@ from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_INVENTORY_PENDING,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_MAP_INFER,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
@@ -38,8 +39,10 @@ from app.services.shipping_notice.constants import (
|
||||
CP_WAITING_UPLOAD,
|
||||
PH_ALIGN_REVIEW,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
PH_MAP_INFER,
|
||||
PH_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
PH_RSV_REQ,
|
||||
@@ -66,11 +69,14 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
"confirm": {"label": "确认", "message": "确认", "variant": "primary"},
|
||||
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
|
||||
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
|
||||
"replace_notice_file": {"label": "重新上传", "message": "重新上传发货通知", "variant": "primary"},
|
||||
"confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"},
|
||||
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
|
||||
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
|
||||
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
|
||||
"retry_rpa": {"label": "重试 RPA", "message": "重试 RPA 导出库存", "variant": "secondary"},
|
||||
"confirm_inventory_source": {"label": "确认库存源", "message": "确认库存查询来源", "variant": "primary"},
|
||||
"retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"},
|
||||
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
|
||||
"upload_inventory_file": {
|
||||
"label": "选择库存文件",
|
||||
@@ -119,9 +125,14 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
),
|
||||
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
|
||||
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
|
||||
CP_INVENTORY_SOURCE_REVIEW: (
|
||||
"confirm_inventory_source",
|
||||
"retry_resolve_inventory_source",
|
||||
"upload_inventory_file",
|
||||
),
|
||||
CP_RSV_REQ: ("reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"),
|
||||
RS_SHORTAGE_REVIEW: ("reparse_inventory", "correct_inventory_mapping", "rematch", "reject"),
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("reparse", "reject"),
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
|
||||
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
|
||||
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
|
||||
CP_READY_MATCH: ("match_inventory",),
|
||||
@@ -164,6 +175,42 @@ def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
|
||||
return buttons
|
||||
|
||||
|
||||
def inventory_source_action_buttons(task: ShippingTask) -> list[dict[str, str]]:
|
||||
"""
|
||||
将库存源候选项转成聊天区可直接点击的确认按钮。
|
||||
|
||||
核心逻辑:库存源待确认时,按钮必须携带 source_code,前端点击后可直接调用确认接口并触发 RPA,
|
||||
避免先把候选源文本发给 Agent 再等待二次确认。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
resolution = payload.get("inventory_source_resolution")
|
||||
candidates = resolution.get("candidates") if isinstance(resolution, dict) else None
|
||||
normalized_candidates: list[dict[str, Any]] = []
|
||||
if isinstance(candidates, list):
|
||||
for item in candidates:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
source_code = str(item.get("source_code") or "").strip().upper()
|
||||
if not source_code:
|
||||
continue
|
||||
normalized_candidates.append(item)
|
||||
if len(normalized_candidates) == 1:
|
||||
item = normalized_candidates[0]
|
||||
source_code = str(item.get("source_code") or "").strip().upper()
|
||||
display_name = str(item.get("display_name") or source_code).strip()
|
||||
return [
|
||||
{
|
||||
"id": "confirm_inventory_source",
|
||||
"label": f"确认:{display_name}",
|
||||
"message": f"确认库存查询来源:{display_name}",
|
||||
"variant": "primary",
|
||||
"source_code": source_code,
|
||||
},
|
||||
*build_action_buttons(["retry_resolve_inventory_source", "upload_inventory_file"]),
|
||||
]
|
||||
return build_action_buttons(list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]))
|
||||
|
||||
|
||||
def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
|
||||
"""按静态 checkpoint id 查 CHECKPOINT_REGISTRY 中的默认 human_options。"""
|
||||
if not checkpoint:
|
||||
@@ -302,6 +349,11 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
if reason == PH_INVENTORY_SOURCE_UNRESOLVED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]),
|
||||
)
|
||||
if reason == PH_SHORTAGE or task.review_status == RS_SHORTAGE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=RS_SHORTAGE_REVIEW,
|
||||
@@ -312,6 +364,11 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
checkpoint=CP_PARSE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]),
|
||||
)
|
||||
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
|
||||
)
|
||||
if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_FAILED,
|
||||
@@ -350,13 +407,18 @@ def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
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": ui.action_buttons,
|
||||
"action_buttons": action_buttons,
|
||||
}
|
||||
|
||||
|
||||
@@ -417,6 +479,7 @@ class TaskTransition(StrEnum):
|
||||
RPA_EXHAUSTED = "rpa_exhausted"
|
||||
RPA_PENDING = "rpa_pending"
|
||||
INV_UNAVAIL = "inv_unavail"
|
||||
INVENTORY_SOURCE_REVIEW = "inventory_source_review"
|
||||
RSV_REQUIRED = "rsv_required"
|
||||
MATCHED_FULFILLABLE = "matched_fulfillable"
|
||||
MATCH_SHORTAGE = "match_shortage"
|
||||
@@ -429,6 +492,8 @@ class TaskTransition(StrEnum):
|
||||
CORRECT_MAPPING = "correct_mapping"
|
||||
REPARSE_INVENTORY = "reparse_inventory"
|
||||
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
|
||||
NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
|
||||
REMATCH_REQUESTED = "rematch_requested"
|
||||
WAITING_UPLOAD = "waiting_upload"
|
||||
UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
||||
UPLOAD_FAILED = "upload_failed"
|
||||
@@ -478,6 +543,11 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
review_status=None,
|
||||
pending_human_reason=PH_INV_UNAVAIL,
|
||||
),
|
||||
TaskTransition.INVENTORY_SOURCE_REVIEW: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
),
|
||||
TaskTransition.RSV_REQUIRED: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=RS_RSV_REQ,
|
||||
@@ -535,6 +605,17 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
),
|
||||
TaskTransition.REMATCH_REQUESTED: _TransitionSpec(
|
||||
process_status="inventory_ready",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.WAITING_UPLOAD: _TransitionSpec(process_status="waiting_upload"),
|
||||
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
|
||||
process_status="waiting_upload",
|
||||
|
||||
@@ -18,10 +18,12 @@ from app import db
|
||||
from app.models import ChatLog, ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_PARSE_OK,
|
||||
CP_TASK_EXISTS,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.decision_workflow import submit_decision
|
||||
from app.services.shipping_notice.extract import extract_notice_fields
|
||||
from app.services.shipping_notice.notice_lines import normalize_notice_lines
|
||||
@@ -55,6 +57,57 @@ EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to",
|
||||
EDITABLE_NOTICE_LINE_FIELDS = frozenset({"sku", "reservation_id", "qty", "quantity", "required_date", "uom"})
|
||||
|
||||
|
||||
def _capture_destination_context(task: ShippingTask, parsed: dict[str, Any], lines: list[Any]) -> None:
|
||||
"""保存 Dify/启发式解析出的目的地候选,供 HXOPS 库存源规则解析使用。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
candidates: list[Any] = []
|
||||
destination = parsed.get("destination")
|
||||
if isinstance(destination, dict):
|
||||
payload["destination"] = destination
|
||||
candidates.append(destination)
|
||||
elif destination:
|
||||
candidates.append(destination)
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to_location"):
|
||||
if parsed.get(key):
|
||||
candidates.append(parsed.get(key))
|
||||
if task.ship_to:
|
||||
candidates.append(task.ship_to)
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
if line.get("destination"):
|
||||
candidates.append(line.get("destination"))
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to"):
|
||||
if line.get(key):
|
||||
candidates.append(line.get(key))
|
||||
if candidates:
|
||||
payload["destination_candidates"] = candidates
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def _has_parse_review_content(task: ShippingTask, lines: list[Any]) -> bool:
|
||||
"""判断解析结果是否有足够内容进入人工复核卡片。"""
|
||||
if any(isinstance(line, dict) for line in lines):
|
||||
return True
|
||||
return any(
|
||||
str(value or "").strip()
|
||||
for value in (
|
||||
task.customer_name,
|
||||
task.customer_code,
|
||||
task.ship_to,
|
||||
task.po_number,
|
||||
task.required_date,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
|
||||
|
||||
return _start(task_no)
|
||||
|
||||
|
||||
def _build_parse_review_chat_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
return {
|
||||
"taskId": task.task_no,
|
||||
@@ -193,6 +246,11 @@ def create_batch(payload: dict[str, Any]) -> ShippingBatch:
|
||||
return batch
|
||||
|
||||
|
||||
def _create_single_task_batch(payload: dict[str, Any]) -> ShippingBatch:
|
||||
"""为单票任务创建 file_count=1 的标准批次容器。"""
|
||||
return create_batch({**payload, "file_count": 1})
|
||||
|
||||
|
||||
def _should_defer_notice_parse(payload: dict[str, Any], item: dict[str, Any]) -> bool:
|
||||
"""判断是否将 parse_notice 延后到 Dify 画布(有 structured 或显式 auto_parse 时不延后)。"""
|
||||
if isinstance(item.get("structured"), dict) and item.get("structured"):
|
||||
@@ -356,22 +414,31 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
checkpoint=CP_TASK_EXISTS,
|
||||
)
|
||||
|
||||
batch = _create_single_task_batch(payload)
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no=generate_task_no(),
|
||||
batch_id=batch.id,
|
||||
user_id=payload.get("user_id"),
|
||||
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
|
||||
source_type=str(payload.get("source_type") or "manual"),
|
||||
batch_index=1,
|
||||
batch_total=1,
|
||||
raw_content=str(payload.get("raw_content") or "").strip() or None,
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add(task)
|
||||
log_task_event(task, "task_created", {"source_type": task.source_type})
|
||||
log_task_event(task, "task_created", {"source_type": task.source_type, "batch_no": batch.batch_no})
|
||||
db.session.flush()
|
||||
batch.current_focus_task_no = task.task_no
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message=f"已创建发货任务 {task.task_no}",
|
||||
data=serialize_task_for_tool(task),
|
||||
message=f"已创建发货批次 {batch.batch_no},任务 {task.task_no}",
|
||||
data={**serialize_task_for_tool(task), "batch": serialize_batch_for_tool(batch)},
|
||||
extra={"batch_no": batch.batch_no},
|
||||
)
|
||||
|
||||
|
||||
@@ -405,11 +472,16 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
and new_notice_payload
|
||||
and str(task.process_status or "").strip().lower() in {"uploaded", "rejected", "closed"}
|
||||
):
|
||||
batch = _create_single_task_batch(payload)
|
||||
db.session.flush()
|
||||
new_task = ShippingTask(
|
||||
task_no=generate_task_no(),
|
||||
batch_id=batch.id,
|
||||
user_id=payload.get("user_id"),
|
||||
conversation_id=conv_id or None,
|
||||
source_type=str(payload.get("source_type") or task.source_type or "manual"),
|
||||
batch_index=1,
|
||||
batch_total=1,
|
||||
raw_content=None,
|
||||
process_status="created",
|
||||
)
|
||||
@@ -417,8 +489,11 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
log_task_event(
|
||||
new_task,
|
||||
"task_created",
|
||||
{"source_type": new_task.source_type, "created_from": task.task_no},
|
||||
{"source_type": new_task.source_type, "created_from": task.task_no, "batch_no": batch.batch_no},
|
||||
)
|
||||
db.session.flush()
|
||||
batch.current_focus_task_no = new_task.task_no
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
task = new_task
|
||||
|
||||
@@ -466,6 +541,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.required_date = required_date or None
|
||||
task.lines_json = lines
|
||||
task.parse_confidence = confidence
|
||||
_capture_destination_context(task, parsed, lines)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
@@ -491,6 +567,21 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
# [STEP 3] 低置信度停待人审;否则标记 parsed 并准备后续库存链路。
|
||||
if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7):
|
||||
if not _has_parse_review_content(task, lines):
|
||||
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
|
||||
log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings})
|
||||
db.session.commit()
|
||||
message = (
|
||||
"未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本,"
|
||||
"或复制粘贴通知正文后重新解析。"
|
||||
)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=message,
|
||||
data={**serialize_task_for_tool(task), "warnings": warnings},
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
)
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
log_task_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings})
|
||||
_upsert_parse_review_chat_message(task)
|
||||
@@ -507,33 +598,27 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
auto_threshold = float(current_app.config.get("SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE") or 0.8)
|
||||
should_auto_continue = confidence >= auto_threshold and not task.inventory_lines_json
|
||||
lang = resolve_lang(payload)
|
||||
summary_text = format_parse_summary(
|
||||
**summary_kwargs,
|
||||
payload=payload,
|
||||
include_confirmation_hint=not should_auto_continue,
|
||||
)
|
||||
|
||||
# [STEP 4] 高置信度且尚无库存时,自动串联 auto_progress 或 ensure_inventory。
|
||||
# [STEP 4] 高置信度解析后不在当前请求线程里继续串行推进。
|
||||
# 统一把后续库存/匹配/导出链路交给后台 worker,避免请求线程兼任主调度器。
|
||||
if should_auto_continue:
|
||||
lang = payload.get("lang") if isinstance(payload, dict) else None
|
||||
auto_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
|
||||
if lang:
|
||||
auto_payload["lang"] = lang
|
||||
auto_result = auto_progress(auto_payload) if auto_progress_enabled() else ensure_inventory(auto_payload)
|
||||
msg = str(auto_result.get("message") or "").strip()
|
||||
merged_message = summary_text if not msg else f"{summary_text}\n\n{msg}"
|
||||
merged_data = {}
|
||||
if isinstance(auto_result.get("data"), dict):
|
||||
merged_data.update(auto_result["data"])
|
||||
merged_data["warnings"] = warnings
|
||||
db.session.refresh(task)
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
merged_message = (
|
||||
f"{summary_text}\n\n{t('workflow.parse.auto_continued', lang=lang)}"
|
||||
if orchestrator_started
|
||||
else f"{summary_text}\n\n{t('workflow.parse.check_later', lang=lang)}"
|
||||
)
|
||||
return tool_response(
|
||||
status=str(auto_result.get("status") or "ok"),
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=merged_message,
|
||||
data=merged_data,
|
||||
next_required_action=auto_result.get("next_required_action"),
|
||||
forbidden_next_tools=auto_result.get("forbidden_next_tools"),
|
||||
data={**serialize_task_for_tool(task), "warnings": warnings},
|
||||
)
|
||||
|
||||
return tool_response(
|
||||
@@ -577,6 +662,119 @@ def _reset_notice_edit_downstream(task: ShippingTask) -> None:
|
||||
task.idempotency_key = None
|
||||
|
||||
|
||||
def replace_task_notice(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
raw_text: str,
|
||||
source_file_name: str = "",
|
||||
source_file_type: str = "",
|
||||
warnings: list[Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
覆盖当前任务的发货通知正文,并重置解析/匹配/导出链路后重新编排。
|
||||
|
||||
核心逻辑:保留 task_no、batch_id、batch_index 等任务身份字段,只替换原始通知内容与文件元信息;
|
||||
清空旧解析结果和下游匹配/导出/上传状态,避免重新上传清晰文件时误新建批次。
|
||||
Args:
|
||||
task: 当前用户拥有的 ShippingTask。
|
||||
raw_text: 经 notice_upload.extract_notice_text 清洗后的通知正文。
|
||||
source_file_name: 新上传文件名。
|
||||
source_file_type: 新上传文件 MIME 类型。
|
||||
warnings: 文件清洗阶段产生的告警。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: Tool 风格响应,包含原 task_no 与后台编排启动状态。
|
||||
"""
|
||||
cleaned_text = str(raw_text or "").strip()
|
||||
cleaned_warnings = [str(item).strip() for item in (warnings or []) if str(item).strip()]
|
||||
if not cleaned_text:
|
||||
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
|
||||
task.error_message = "未能从重新上传的发货通知中抽取到可解析文本"
|
||||
task.raw_content = ""
|
||||
if source_file_name:
|
||||
task.source_file_name = source_file_name
|
||||
if source_file_type:
|
||||
task.source_file_type = source_file_type
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
step_title="确认解析",
|
||||
status="needs_human",
|
||||
message="发货通知文本抽取失败",
|
||||
progress_percent=100,
|
||||
current=0,
|
||||
total=0,
|
||||
detail="未能从文件中抽取到可审核内容,请重新上传清晰版 PDF/文本。",
|
||||
extra={"warnings": cleaned_warnings},
|
||||
)
|
||||
log_task_event(task, "notice_replace_extract_failed", {"warnings": cleaned_warnings})
|
||||
sync_batch_after_task_change(task)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="未能从重新上传的发货通知中抽取到可解析文本,请上传清晰版 PDF/文本或粘贴通知正文。",
|
||||
data={**serialize_task_for_tool(task), "warnings": cleaned_warnings},
|
||||
)
|
||||
|
||||
task.raw_content = cleaned_text
|
||||
if source_file_name:
|
||||
task.source_file_name = source_file_name
|
||||
if source_file_type:
|
||||
task.source_file_type = source_file_type
|
||||
task.customer_name = None
|
||||
task.customer_code = None
|
||||
task.ship_to = None
|
||||
task.po_number = None
|
||||
task.required_date = None
|
||||
task.lines_json = []
|
||||
task.parse_confidence = None
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
task.error_message = None
|
||||
task.process_status = "created"
|
||||
_reset_notice_edit_downstream(task)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step1_notice_submit",
|
||||
step_title="提交通知",
|
||||
status="completed",
|
||||
message="已重新上传发货通知并覆盖当前任务",
|
||||
progress_percent=100,
|
||||
current=1,
|
||||
total=1,
|
||||
detail="已保存新的通知正文,准备重新解析当前任务。",
|
||||
extra={"warnings": cleaned_warnings},
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"notice_replaced",
|
||||
{
|
||||
"source_file_name": source_file_name,
|
||||
"source_file_type": source_file_type,
|
||||
"warnings": cleaned_warnings,
|
||||
},
|
||||
)
|
||||
sync_batch_after_task_change(task)
|
||||
db.session.commit()
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=(
|
||||
f"已重新上传发货通知并覆盖当前任务 {task.task_no},后台已开始重新解析。"
|
||||
if orchestrator_started
|
||||
else f"已重新上传发货通知并覆盖当前任务 {task.task_no}。"
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"warnings": cleaned_warnings,
|
||||
"parse_status": "deferred",
|
||||
"orchestrator_started": orchestrator_started,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _commit_notice_edit(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
|
||||
@@ -14,6 +14,36 @@ if TYPE_CHECKING:
|
||||
from app.models import ShippingTask
|
||||
|
||||
|
||||
def _sanitize_user_facing_text(value: str) -> str:
|
||||
"""
|
||||
清理会被 Agent 复述给业务用户的内部项目名。
|
||||
|
||||
核心逻辑:Tool response 会进入 Dify 上下文,先在后端把项目代号替换为业务表达,
|
||||
避免模型把内部系统名称带到对话气泡中。
|
||||
"""
|
||||
text = str(value or "")
|
||||
replacements = (
|
||||
("通过 Hxops 聊天区上传", "在当前对话中上传"),
|
||||
("通过 HXOPS 聊天区上传", "在当前对话中上传"),
|
||||
("通过 hxops 聊天区上传", "在当前对话中上传"),
|
||||
("在 Hxops 聊天区上传", "在当前对话中上传"),
|
||||
("在 HXOPS 聊天区上传", "在当前对话中上传"),
|
||||
("在 hxops 聊天区上传", "在当前对话中上传"),
|
||||
("Hxops 聊天区", "当前对话"),
|
||||
("HXOPS 聊天区", "当前对话"),
|
||||
("hxops 聊天区", "当前对话"),
|
||||
("Hxops Chat", "当前对话"),
|
||||
("HXOPS Chat", "当前对话"),
|
||||
("hxops chat", "当前对话"),
|
||||
("Hxops", "当前系统"),
|
||||
("HXOPS", "当前系统"),
|
||||
("hxops", "当前系统"),
|
||||
)
|
||||
for old, new in replacements:
|
||||
text = text.replace(old, new)
|
||||
return text
|
||||
|
||||
|
||||
def tool_response(
|
||||
*,
|
||||
status: str,
|
||||
@@ -27,6 +57,7 @@ def tool_response(
|
||||
next_required_action: str | None = None,
|
||||
forbidden_next_tools: list[str] | None = None,
|
||||
stop_agent_turn: bool = False,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建发货通知 Tool 标准 JSON 响应。
|
||||
@@ -37,6 +68,7 @@ def tool_response(
|
||||
Args:
|
||||
stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。
|
||||
forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。
|
||||
extra: 需要保留在顶层的兼容字段,例如 batch_no。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
@@ -61,7 +93,7 @@ def tool_response(
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"status": status,
|
||||
"message": message,
|
||||
"message": _sanitize_user_facing_text(message),
|
||||
"data": data or {},
|
||||
}
|
||||
if task_id:
|
||||
@@ -79,9 +111,11 @@ def tool_response(
|
||||
if resolved_checkpoint:
|
||||
payload["checkpoint"] = resolved_checkpoint
|
||||
if next_required_action:
|
||||
payload["next_required_action"] = next_required_action
|
||||
payload["next_required_action"] = _sanitize_user_facing_text(next_required_action)
|
||||
if forbidden_next_tools:
|
||||
payload["forbidden_next_tools"] = forbidden_next_tools
|
||||
if stop_agent_turn:
|
||||
payload["stop_agent_turn"] = True
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
return payload
|
||||
@@ -31,6 +31,7 @@ get_inventory_schema_preview = inventory_workflow.get_inventory_schema_preview
|
||||
apply_inventory_mapping = inventory_workflow.apply_inventory_mapping
|
||||
upload_inventory_file = inventory_workflow.upload_inventory_file
|
||||
rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory
|
||||
confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source
|
||||
|
||||
# 履约阶段
|
||||
match_inventory = fulfillment_workflow.match_inventory
|
||||
|
||||
Reference in new issue
Block a user