Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	backend/app/jobs/queue.py
This commit is contained in:
hugo committed 2026-06-29 20:39:06 +08:00
commit ce80867d09
89 files changed
+10328 -4126

No files matched your search

+4 -4
View File
@@ -89,10 +89,10 @@ SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(相对 backend/ 根目录)
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
# 发货 Excel 模板(可选)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
+4 -4
View File
@@ -93,10 +93,10 @@ SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(相对 backend/ 根目录)
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
# 发货 Excel 模板(可选)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
+4
View File
@@ -49,9 +49,12 @@ frontend/package-lock.json
.vscode/*
!.vscode/settings.json
!.vscode/extensions.json
.trae/*
.cursor/*
.idea/
*.swp
*.swo
.cursorrules
# Runtime files
.run/
@@ -79,3 +82,4 @@ oracle_client/
backend/data/kb/
.pytest_cache/
backend/data/fixed_assets/manifest.json
backend/data/shipping_notice/
+25 -1
View File
@@ -4,6 +4,29 @@
"python.terminal.activateEnvironment": true,
"python.venvPath": "${workspaceFolder}/backend",
"python.venvFolders": [".venv"],
"github.copilot.chat.commitMessageGeneration.instructions": [
{
"text": "Generate Git commit messages in Simplified Chinese by default."
},
{
"text": "Follow Conventional Commits format: <type>(<scope>): <subject>."
},
{
"text": "Use English for type and scope; use Simplified Chinese for subject and body."
},
{
"text": "Allowed types are feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert."
},
{
"text": "The subject must be imperative, no period at the end, and no longer than 100 Chinese characters."
},
{
"text": "Avoid vague messages such as update, fix bug, or WIP."
},
{
"text": "When a body is useful, write concise Chinese bullet points describing concrete changes."
}
],
// 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv
"terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)",
@@ -30,5 +53,6 @@
"Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }"
]
}
}
},
"js/ts.tsdk.path": "node_modules\\typescript\\lib"
}
+50 -8
View File
@@ -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():
+8 -8
View File
@@ -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()
+98 -1
View File
@@ -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))
+9 -5
View File
@@ -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
View File
@@ -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
+6
View File
@@ -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',
]
+55
View File
@@ -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])
+61 -2
View File
@@ -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,
}
+6 -1
View File
@@ -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(
+252 -6
View File
@@ -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
+104
View File
@@ -3,6 +3,8 @@ from __future__ import annotations
import base64
import io
from pathlib import Path
import re
import xml.etree.ElementTree as ET
from edkb_system.contracts import Block, Context
@@ -13,6 +15,19 @@ _DEFAULT_PAGE_TEXT_LIMIT = 120
_MIN_SCAN_IMAGE_BYTES = 4 * 1024
_MIN_DEFAULT_IMAGE_BYTES = 16 * 1024
_MIN_TEXT_HEAVY_IMAGE_BYTES = 24 * 1024
_XFA_ROW_CONTAINER_TAGS = {"DATA"}
_XFA_SKIP_TAGS = {
"config",
"connectionSet",
"dataDescription",
"desc",
"extras",
"form",
"localeSet",
"manifest",
"occur",
"template",
}
def _is_scanned(text_chars: int, pages: int) -> bool:
@@ -44,6 +59,80 @@ def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str:
return f"data:{content_type};base64,{b64}"
def _local_name(tag: str) -> str:
return str(tag or "").rsplit("}", 1)[-1]
def _normalize_xfa_text(text: str) -> str:
return re.sub(r"[ \t\r\f\v]+", " ", str(text or "")).strip()
def _iter_xfa_roots(reader) -> list[ET.Element]:
try:
xfa_obj = getattr(reader, "xfa", None)
xfa = xfa_obj if isinstance(xfa_obj, dict) else getattr(xfa_obj, "xfa", None)
except Exception:
xfa = None
if not xfa:
return []
roots: list[ET.Element] = []
items = xfa.items() if isinstance(xfa, dict) else xfa
for _name, payload in items:
if isinstance(payload, str):
raw = payload.encode("utf-8", errors="ignore")
else:
raw = bytes(payload or b"")
if not raw.strip():
continue
try:
roots.append(ET.fromstring(raw))
except Exception:
continue
return roots
def _render_xfa_leaf_rows(node: ET.Element, prefix: tuple[str, ...] = ()) -> list[str]:
tag = _local_name(node.tag)
if tag in _XFA_SKIP_TAGS:
return []
children = [child for child in list(node) if isinstance(child.tag, str)]
text = _normalize_xfa_text(" ".join(node.itertext()))
if not children:
return [f"{'/'.join((*prefix, tag))}: {text}"] if text else []
leaf_children = [
child
for child in children
if not [grand for grand in list(child) if isinstance(grand.tag, str)]
and _normalize_xfa_text(" ".join(child.itertext()))
]
if tag in _XFA_ROW_CONTAINER_TAGS and leaf_children:
cells = [
f"{_local_name(child.tag)}={_normalize_xfa_text(' '.join(child.itertext()))}"
for child in leaf_children
]
return [f"{'/'.join((*prefix, tag))}: " + " | ".join(cells)]
rows: list[str] = []
for child in children:
rows.extend(_render_xfa_leaf_rows(child, (*prefix, tag)))
return rows
def _extract_xfa_text(reader) -> str:
rows: list[str] = []
seen: set[str] = set()
for root in _iter_xfa_roots(reader):
for row in _render_xfa_leaf_rows(root):
if row in seen:
continue
seen.add(row)
rows.append(row)
return "\n".join(rows).strip()
def _normalize_box(
bounds: tuple[float, float, float, float],
) -> tuple[float, float, float, float]:
@@ -224,6 +313,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
reader = PdfReader(str(file_path))
context.pages = len(reader.pages)
xfa_text = _extract_xfa_text(reader)
text_chars = 0
page_payloads: list[dict] = []
for page_idx, p in enumerate(reader.pages, start=1):
@@ -367,6 +457,20 @@ def run(input_data: dict, context: Context) -> list[Block]:
)
context.images += 1
if xfa_text:
blocks.append(
Block(
id="pdf-xfa",
page=1,
type="paragraph",
text=xfa_text,
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={"source": "pdf_xfa"},
)
)
context.extras["pdf_xfa_text"] = True
context.warnings.append("pdf xfa datasets extracted")
if scan_likely:
context.warnings.append("pdf likely scanned; OCR recommended")
context.extras["scan_likely"] = True
@@ -0,0 +1,74 @@
"""Add generic jobs table for non-KB background tasks.
Purpose:
Introduce a domain-aware background job table so shipping_notice no longer
reuses kb_jobs for orchestration.
Dependencies:
Alembic revision f9a0b1c2d3e4.
Flow:
Shipping notice workers enqueue and consume rows from jobs while existing
knowledge-base jobs remain on kb_jobs during phase one.
Revision ID: fa1b2c3d4e5f
Revises: f9a0b1c2d3e4
Create Date: 2026-06-26 08:45:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "fa1b2c3d4e5f"
down_revision = "f9a0b1c2d3e4"
branch_labels = None
depends_on = None
def upgrade():
"""Create the generic jobs table used by phase-one shipping jobs."""
op.create_table(
"jobs",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("domain", sa.String(length=64), nullable=False),
sa.Column("job_type", sa.String(length=64), nullable=False),
sa.Column("status", sa.String(length=32), nullable=False),
sa.Column("priority", sa.Integer(), nullable=False),
sa.Column("business_ref", sa.String(length=128), nullable=True),
sa.Column("payload_json", sa.JSON(), nullable=True),
sa.Column("result_json", sa.JSON(), nullable=True),
sa.Column("progress", sa.Integer(), nullable=False),
sa.Column("message", sa.Text(), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("attempts", sa.Integer(), nullable=False),
sa.Column("max_attempts", sa.Integer(), nullable=False),
sa.Column("locked_by", sa.String(length=128), nullable=True),
sa.Column("locked_at", sa.DateTime(), nullable=True),
sa.Column("created_by_id", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.Column("started_at", sa.DateTime(), nullable=True),
sa.Column("finished_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(["created_by_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_jobs_business_ref", "jobs", ["domain", "job_type", "business_ref"], unique=False)
op.create_index("ix_jobs_domain", "jobs", ["domain"], unique=False)
op.create_index("ix_jobs_domain_status_created", "jobs", ["domain", "status", "created_at"], unique=False)
op.create_index("ix_jobs_job_type", "jobs", ["job_type"], unique=False)
op.create_index("ix_jobs_locked_at", "jobs", ["locked_at"], unique=False)
op.create_index("ix_jobs_priority", "jobs", ["priority"], unique=False)
op.create_index("ix_jobs_status", "jobs", ["status"], unique=False)
op.create_index("ix_jobs_type_status_created", "jobs", ["job_type", "status", "created_at"], unique=False)
def downgrade():
"""Drop the generic jobs table."""
op.drop_index("ix_jobs_type_status_created", table_name="jobs")
op.drop_index("ix_jobs_status", table_name="jobs")
op.drop_index("ix_jobs_priority", table_name="jobs")
op.drop_index("ix_jobs_locked_at", table_name="jobs")
op.drop_index("ix_jobs_job_type", table_name="jobs")
op.drop_index("ix_jobs_domain_status_created", table_name="jobs")
op.drop_index("ix_jobs_domain", table_name="jobs")
op.drop_index("ix_jobs_business_ref", table_name="jobs")
op.drop_table("jobs")
@@ -0,0 +1,95 @@
"""Add shipping inventory file sharing tables.
Purpose:
Store freight shipping inventory as a batch-level snapshot that can be
linked to all tasks in the batch.
Dependencies:
Alembic revision fa1b2c3d4e5f.
Flow:
Upload creates one shipping_inventory_files row and active links in
shipping_task_inventory_links; each task still matches independently.
Revision ID: fb2c3d4e5f6a
Revises: fa1b2c3d4e5f
Create Date: 2026-06-26 10:30:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "fb2c3d4e5f6a"
down_revision = "fa1b2c3d4e5f"
branch_labels = None
depends_on = None
def upgrade():
"""Create shipping inventory snapshot and task link tables."""
op.create_table(
"shipping_inventory_files",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("inventory_file_no", sa.String(length=64), nullable=False),
sa.Column("batch_id", sa.Integer(), nullable=True),
sa.Column("user_id", sa.Integer(), nullable=True),
sa.Column("source_file_name", sa.String(length=255), nullable=True),
sa.Column("storage_path", sa.String(length=500), nullable=False),
sa.Column("schema_preview_json", sa.JSON(), nullable=True),
sa.Column("field_mapping_json", sa.JSON(), nullable=True),
sa.Column("mapping_source", sa.String(length=32), nullable=True),
sa.Column("mapping_confirmed", sa.Boolean(), server_default=sa.text("false"), nullable=False),
sa.Column("inventory_lines_json", sa.JSON(), nullable=True),
sa.Column("line_count", sa.Integer(), nullable=False),
sa.Column("share_mode", sa.String(length=32), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["batch_id"], ["shipping_batches.id"]),
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_shipping_inventory_files_batch_created", "shipping_inventory_files", ["batch_id", "created_at"], unique=False)
op.create_index("ix_shipping_inventory_files_batch_id", "shipping_inventory_files", ["batch_id"], unique=False)
op.create_index("ix_shipping_inventory_files_created_at", "shipping_inventory_files", ["created_at"], unique=False)
op.create_index("ix_shipping_inventory_files_inventory_file_no", "shipping_inventory_files", ["inventory_file_no"], unique=True)
op.create_index("ix_shipping_inventory_files_user_created", "shipping_inventory_files", ["user_id", "created_at"], unique=False)
op.create_index("ix_shipping_inventory_files_user_id", "shipping_inventory_files", ["user_id"], unique=False)
op.create_table(
"shipping_task_inventory_links",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("task_id", sa.Integer(), nullable=False),
sa.Column("inventory_file_id", sa.Integer(), nullable=False),
sa.Column("link_role", sa.String(length=32), nullable=False),
sa.Column("access_mode", sa.String(length=32), nullable=False),
sa.Column("is_active", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("linked_by_user_id", sa.Integer(), nullable=True),
sa.Column("linked_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["inventory_file_id"], ["shipping_inventory_files.id"]),
sa.ForeignKeyConstraint(["linked_by_user_id"], ["users.id"]),
sa.ForeignKeyConstraint(["task_id"], ["shipping_tasks.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_shipping_task_inventory_links_file_active", "shipping_task_inventory_links", ["inventory_file_id", "is_active"], unique=False)
op.create_index("ix_shipping_task_inventory_links_inventory_file_id", "shipping_task_inventory_links", ["inventory_file_id"], unique=False)
op.create_index("ix_shipping_task_inventory_links_is_active", "shipping_task_inventory_links", ["is_active"], unique=False)
op.create_index("ix_shipping_task_inventory_links_linked_at", "shipping_task_inventory_links", ["linked_at"], unique=False)
op.create_index("ix_shipping_task_inventory_links_task_active", "shipping_task_inventory_links", ["task_id", "is_active"], unique=False)
op.create_index("ix_shipping_task_inventory_links_task_id", "shipping_task_inventory_links", ["task_id"], unique=False)
def downgrade():
"""Drop shipping inventory snapshot tables."""
op.drop_index("ix_shipping_task_inventory_links_task_id", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_task_active", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_linked_at", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_is_active", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_inventory_file_id", table_name="shipping_task_inventory_links")
op.drop_index("ix_shipping_task_inventory_links_file_active", table_name="shipping_task_inventory_links")
op.drop_table("shipping_task_inventory_links")
op.drop_index("ix_shipping_inventory_files_user_id", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_user_created", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_inventory_file_no", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_created_at", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_batch_id", table_name="shipping_inventory_files")
op.drop_index("ix_shipping_inventory_files_batch_created", table_name="shipping_inventory_files")
op.drop_table("shipping_inventory_files")
+6
View File
@@ -20,6 +20,11 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
@pytest.fixture(autouse=True)
def _shipping_notice_stable_auto_config(app, request):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
tmp_path = request.getfixturevalue("tmp_path")
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
)
if request.node.get_closest_marker("auto_rpa"):
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
@@ -27,6 +32,7 @@ def _shipping_notice_stable_auto_config(app, request):
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
+1 -1
View File
@@ -23,6 +23,6 @@ def test_resolve_backend_relative_path_kb_storage_legacy_prefix():
def test_resolve_backend_relative_path_default():
root = backend_dir()
default = root / "data" / "freight_rpa" / "inventory_drop"
default = root / "data" / "shipping_notice" / "freight_rpa" / "inventory_drop"
resolved = Path(resolve_backend_relative_path(None, default))
assert resolved == default.resolve()
+769 -20
View File
@@ -7,12 +7,17 @@
4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。
"""
from datetime import datetime, timedelta
from io import BytesIO
from app import db
from app.models import Agent, ChatSession, ShippingBatch, ShippingTask, User
from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, ShippingTaskEvent, User
from app.auth_jwt import issue_local_access_token
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs
from app.jobs.context import JobContext
from app.jobs.queue import process_next_job
from app.jobs.types import JobType
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs, tools as shipping_tools
from app.services.shipping_notice.progress_workflow import auto_progress
def _tool_headers(app):
@@ -202,6 +207,598 @@ def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(ap
assert started == [data["batch_no"]]
def test_parse_notice_empty_result_requires_reupload_instead_of_review(app):
"""无订单行且无单头字段时,不应生成空审核卡片,应停在重新上传/清洗节点。"""
with app.app_context():
user = User(username="shipping_empty_parse_user", email="shipping_empty_parse_user@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-EMPTY-PARSE-001",
user_id=user.id,
source_type="pdf",
process_status="created",
raw_content="This PDF extraction contains no order table.",
)
db.session.add(task)
db.session.commit()
result = shipping_tools.parse_notice({"task_id": task.task_no})
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "notice_text_extraction_failed"
assert [button["id"] for button in result["action_buttons"]] == [
"replace_notice_file",
"reparse",
"reject",
]
assert task.pending_human_reason == "notice_text_extraction_failed"
assert task.review_status is None
assert task.lines_json == []
assert "重新上传" in result["message"]
def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app, client):
"""重新上传当前任务通知应保留 task_no/batch_no,只覆盖正文并清理旧解析结果。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch = ShippingBatch(
batch_no="SB-REPLACE-NOTICE-001",
user_id=user.id,
conversation_id="conv-replace-notice",
current_focus_task_no="SN-REPLACE-NOTICE-001",
file_count=1,
)
db.session.add(batch)
db.session.flush()
task = ShippingTask(
task_no="SN-REPLACE-NOTICE-001",
batch_id=batch.id,
user_id=user.id,
conversation_id="conv-replace-notice",
source_type="pdf",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
raw_content="old text",
source_file_name="old.pdf",
lines_json=[{"sku": "OLD", "qty": 1}],
match_status="shortage",
shortage_json={"OLD": 1},
export_file_name="old.xlsx",
)
db.session.add(task)
db.session.commit()
original_batch_count = ShippingBatch.query.count()
original_task_count = ShippingTask.query.count()
res = client.post(
"/api/workspace/shipping-tasks/SN-REPLACE-NOTICE-001/replace-notice",
headers=headers,
data={"file": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "new-notice.txt")},
content_type="multipart/form-data",
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] in {"ok", "running"}
assert data["data"]["task_no"] == "SN-REPLACE-NOTICE-001"
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-REPLACE-NOTICE-001").one()
assert ShippingBatch.query.count() == original_batch_count
assert ShippingTask.query.count() == original_task_count
assert task.batch.batch_no == "SB-REPLACE-NOTICE-001"
assert task.raw_content == "客户:ACME\nA001 x 10"
assert task.source_file_name == "new-notice.txt"
assert task.lines_json == []
assert task.review_status is None
assert task.pending_human_reason is None
assert task.match_status is None
assert task.shortage_json is None
assert task.export_file_name is None
def test_auto_progress_inventory_trigger_failure_marks_step3(app):
"""库存自动获取失败时应进入第 3 步库存准备,而不是继续显示解析确认。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = ""
with app.app_context():
user = User(username="shipping_inventory_step_user", email="shipping_inventory_step_user@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-INVENTORY-STEP-001",
user_id=user.id,
source_type="pdf",
process_status="parsed",
parse_confidence=0.95,
raw_content="客户:ACME\nA001 x 10",
lines_json=[{"sku": "A001", "qty": 10}],
current_step="step2_parse_confirm",
step_payload_json={
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
}
},
)
db.session.add(task)
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "upload_req"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "inv_unavail"
assert task.current_step == "step3_inventory_prepare"
assert task.step_payload_json["current_step_progress"]["status"] == "needs_human"
def test_workspace_task_detail_rechecks_timed_out_inventory_rpa(app, client, tmp_path):
"""工作台查询遇到已超时 RPA 等待态时,应兜底复查并自动触发下一次库存导出。"""
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 5
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
task = ShippingTask(
task_no="SN-RPA-RECHECK-001",
user_id=user.id,
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
parse_confidence=0.95,
raw_content="客户:ACME\nA001 x 10",
lines_json=[{"sku": "A001", "qty": 10}],
step_payload_json={
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
}
},
)
db.session.add(task)
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_rpa_triggered",
detail_json={"attempt": 1},
created_at=datetime.utcnow() - timedelta(seconds=10),
)
)
db.session.commit()
res = client.get("/api/workspace/shipping-tasks/SN-RPA-RECHECK-001", headers=headers)
assert res.status_code == 200
data = res.get_json()
assert data["process_status"] == "waiting_inventory"
assert data["pending_human_reason"] == "rpa_pending"
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-RPA-RECHECK-001").one()
events = ShippingTaskEvent.query.filter_by(task_id=task.id).order_by(ShippingTaskEvent.id.asc()).all()
triggered = [event for event in events if event.event_type == "inventory_rpa_triggered"]
failed = [event for event in events if event.event_type == "inventory_rpa_failed"]
rechecked = [event for event in events if event.event_type == "inventory_rpa_wait_rechecked"]
assert len(triggered) == 2
assert len(failed) == 1
assert len(rechecked) == 1
assert triggered[-1].detail_json["attempt"] == 2
assert task.step_payload_json["current_step_progress"]["current"] == 2
def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_path):
"""目的地 DUB 应解析到 DSV360_AWSDU,并写入 RPA 库存导出 trigger。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
with app.app_context():
user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-DUB",
user_id=user.id,
source_type="pdf",
process_status="parsed",
parse_confidence=0.95,
raw_content="Ship to Dublin DUB\nA001 x 10",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 10}],
step_payload_json={"destination": {"port_code": "DUB", "city": "Dublin"}},
)
db.session.add(task)
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
db.session.refresh(task)
assert result["status"] == "running"
source = task.step_payload_json["rpa_inventory_source"]
assert source["source_code"] == "DSV360_AWSDU"
trigger_path = tmp_path / "inventory_triggers" / f"inventory_export_{task.task_no}.json"
assert trigger_path.exists()
trigger_text = trigger_path.read_text(encoding="utf-8")
assert '"source_code": "DSV360_AWSDU"' in trigger_text
assert '"source_type": "dsv360"' in trigger_text
def test_inventory_source_rules_cover_dsv360_programs(app):
"""截图中的 DSV 360 Program 均应能通过别名解析到对应库存源。"""
from app.services.shipping_notice.inventory_source_rules import resolve_inventory_source
cases = [
("Bison", "DSV360_AWSBI"),
("Cincinnati", "DSV360_AWSCV"),
("Moerdijk", "DSV360_AWSAMS"),
]
with app.app_context():
for ship_to, expected_code in cases:
task = ShippingTask(
task_no=f"SN-INVENTORY-SOURCE-{expected_code}",
source_type="pdf",
process_status="parsed",
ship_to=ship_to,
lines_json=[{"sku": "A001", "qty": 10}],
)
resolution = resolve_inventory_source(task)
assert resolution.status == "resolved"
assert resolution.source is not None
assert resolution.source["source_code"] == expected_code
def test_auto_progress_unknown_destination_requires_inventory_source_review(app):
"""无法根据目的地唯一判断库存源时,应停在库存源人工确认检查点。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
with app.app_context():
user = User(username="shipping_inventory_source_unknown", email="shipping_inventory_source_unknown@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-UNKNOWN",
user_id=user.id,
source_type="pdf",
process_status="parsed",
parse_confidence=0.95,
raw_content="Ship to Mystery Port\nA001 x 10",
ship_to="Mystery Port",
lines_json=[{"sku": "A001", "qty": 10}],
)
db.session.add(task)
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "inventory_source_review"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "inventory_source_unresolved"
assert task.step_payload_json["inventory_source_resolution"]["status"] == "unresolved"
assert len(result["data"]["inventory_source_candidates"]) >= 4
def test_inventory_source_review_chat_actions_return_source_buttons(app):
"""库存源待确认且只有一个候选时,聊天按钮才携带具体 source_code。"""
from app.services.shipping_notice.state_machine import build_chat_actions_payload
with app.app_context():
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-ACTIONS",
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="inventory_source_unresolved",
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
"candidates": [
{
"source_code": "DSV360_AWSDU",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
}
],
}
},
)
payload = build_chat_actions_payload(task)
assert payload["checkpoint"] == "inventory_source_review"
first = payload["action_buttons"][0]
assert first["id"] == "confirm_inventory_source"
assert first["source_code"] == "DSV360_AWSDU"
assert first["label"] == "确认:DSV 360 / Dublin / AWSDU - Prod (JDA)"
def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
"""库存源候选很多时,不应把全部数据源铺成按钮。"""
from app.services.shipping_notice.state_machine import build_chat_actions_payload
with app.app_context():
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-MANY-ACTIONS",
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="inventory_source_unresolved",
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
"candidates": [
{
"source_code": "DSV360_AWSBI",
"display_name": "DSV 360 / Bison / AWSBI",
},
{
"source_code": "DSV360_AWSDU",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
},
],
}
},
)
payload = build_chat_actions_payload(task)
source_buttons = [
item for item in payload["action_buttons"]
if item["id"] == "confirm_inventory_source" and item.get("source_code")
]
assert source_buttons == []
assert [item["id"] for item in payload["action_buttons"]] == [
"confirm_inventory_source",
"retry_resolve_inventory_source",
"upload_inventory_file",
]
def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client):
"""同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch_a = ShippingBatch(
batch_no="SB-CONV-WS-A",
user_id=user.id,
conversation_id="conv-workspace-multi",
current_focus_task_no="SN-20260626-CONVA001",
file_count=2,
)
batch_b = ShippingBatch(
batch_no="SB-CONV-WS-B",
user_id=user.id,
conversation_id="conv-workspace-multi",
current_focus_task_no="SN-20260626-CONVB001",
file_count=2,
)
other_batch = ShippingBatch(
batch_no="SB-CONV-WS-OTHER",
user_id=user.id,
conversation_id="conv-workspace-other",
file_count=1,
)
db.session.add_all([batch_a, batch_b, other_batch])
db.session.flush()
db.session.add_all([
ShippingTask(
task_no="SN-20260626-CONVA001",
batch_id=batch_a.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="uploaded",
batch_index=1,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-CONVA002",
batch_id=batch_a.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="matched",
batch_index=2,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-CONVB001",
batch_id=batch_b.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="waiting_inventory",
review_status="align_review",
batch_index=1,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-CONVB002",
batch_id=batch_b.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="matched",
upload_status="failed",
batch_index=2,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-OTHER001",
batch_id=other_batch.id,
user_id=user.id,
conversation_id="conv-workspace-other",
source_type="manual",
process_status="uploaded",
batch_index=1,
batch_total=1,
),
])
db.session.commit()
res = client.get(
"/api/workspace/shipping-conversations/conv-workspace-multi/batch-workspace",
headers=headers,
)
assert res.status_code == 200
data = res.get_json()
assert data["conversation_id"] == "conv-workspace-multi"
assert data["summary"] == {
"batch_count": 2,
"total": 4,
"completed": 1,
"running": 1,
"failed": 1,
"needs_human": 1,
"pending": 0,
}
assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-WS-A", "SB-CONV-WS-B"]
assert data["batches"][0]["focus_task"]["task_no"] == "SN-20260626-CONVA001"
assert len(data["batches"][1]["tasks"]) == 2
def test_workspace_conversation_batch_workspace_filters_by_user(app, client):
"""会话级工作台只能返回当前用户可访问的批次。"""
headers = _workspace_headers(app)
with app.app_context():
current = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
other = User(
username="shipping_workspace_other",
email="shipping_workspace_other@example.com",
role="user",
status="active",
)
other.set_password("password")
db.session.add(other)
db.session.flush()
own_batch = ShippingBatch(
batch_no="SB-CONV-OWN",
user_id=current.id,
conversation_id="conv-workspace-secure",
file_count=1,
)
foreign_batch = ShippingBatch(
batch_no="SB-CONV-FOREIGN",
user_id=other.id,
conversation_id="conv-workspace-secure",
file_count=1,
)
db.session.add_all([own_batch, foreign_batch])
db.session.flush()
db.session.add_all([
ShippingTask(
task_no="SN-20260626-OWN00001",
batch_id=own_batch.id,
user_id=current.id,
conversation_id="conv-workspace-secure",
source_type="manual",
process_status="created",
),
ShippingTask(
task_no="SN-20260626-FGN00001",
batch_id=foreign_batch.id,
user_id=other.id,
conversation_id="conv-workspace-secure",
source_type="manual",
process_status="uploaded",
),
])
db.session.commit()
res = client.get(
"/api/workspace/shipping-conversations/conv-workspace-secure/batch-workspace",
headers=headers,
)
assert res.status_code == 200
data = res.get_json()
assert data["summary"]["batch_count"] == 1
assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-OWN"]
def test_shipping_orchestrator_enqueues_generic_job_not_kb_job(app):
"""发货通知后台编排应写入通用 jobs,不能污染 kb_jobs。"""
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
app.config["SHIPPING_NOTICE_TASK_EXECUTION_MODE"] = "worker"
with app.app_context():
batch = ShippingBatch(batch_no="SB-JOBS-QUEUE", file_count=1, user_id=123)
task = ShippingTask(
task_no="SN-20260626-JOBS0001",
batch=batch,
user_id=123,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
started = batch_orchestrator.start_task_orchestrator(task.task_no)
assert started is True
job = Job.query.filter_by(
domain="shipping_notice",
job_type="shipping_notice_run",
business_ref=task.task_no,
).first()
assert job is not None
assert job.status == "queued"
assert job.payload_json["task_no"] == task.task_no
assert KbJob.query.filter_by(job_type="shipping_notice_run").count() == 0
def test_process_shipping_job_survives_session_remove(app, monkeypatch):
"""Job Runner 应能处理业务编排内部 db.session.remove 后的状态回写。"""
app.config["SHIPPING_NOTICE_TASK_EXECUTION_MODE"] = "worker"
with app.app_context():
job = Job(
domain="shipping_notice",
job_type=JobType.SHIPPING_NOTICE_RUN.value,
status="queued",
business_ref="SN-20260626-DETACHED1",
payload_json={"task_no": "SN-20260626-DETACHED1"},
message="等待后台处理发货任务",
)
db.session.add(job)
db.session.commit()
job_id = job.id
def fake_run_single_task(task_no: str):
db.session.remove()
return {"status": "ok", "message": f"done {task_no}"}
monkeypatch.setattr(batch_orchestrator, "_run_single_task", fake_run_single_task)
ctx = JobContext(config=dict(app.config), logger=app.logger, extras={"queues": ["shipping"]})
processed, message = process_next_job(
ctx=ctx,
domain="shipping_notice",
job_types=[JobType.SHIPPING_NOTICE_RUN],
timeout_config_key="SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS",
)
assert processed is True
assert message == JobType.SHIPPING_NOTICE_RUN.value
refreshed = db.session.get(Job, job_id)
assert refreshed is not None
assert refreshed.status == "success"
assert refreshed.result_json["status"] == "ok"
def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
"""编排器遇到 created 任务时应调用后台 Dify 执行器。"""
with app.app_context():
@@ -234,6 +831,108 @@ def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
assert called.get("dify") == task_no
def test_submit_reparse_resets_task_and_starts_dify_orchestrator(app, monkeypatch):
"""重新解析必须回退到 created 并交给后台 Dify,不允许同步启发式解析。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-REPARSE-DIFY", file_count=1)
task = ShippingTask(
task_no="SN-20260629-REPARSE1",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
lines_json=[{"sku": "OLD", "qty": 1}],
parse_confidence=0.42,
match_status="shortage",
shortage_json={"OLD": 1},
line_results_json=[{"sku": "OLD", "status": "shortage"}],
inventory_lines_json=[{"sku": "OLD", "available_qty": 0}],
error_message="old error",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
started: list[str] = []
def fake_start(task_ref: str | None) -> bool:
if task_ref:
started.append(task_ref)
return True
monkeypatch.setattr(
"app.services.shipping_notice.decision_workflow.start_task_orchestrator",
fake_start,
)
result = shipping_tools.submit_decision({"task_id": task_no, "decision": "reparse"})
db.session.refresh(task)
assert result["status"] == "running"
assert started == [task_no]
assert task.process_status == "created"
assert task.review_status is None
assert task.pending_human_reason is None
assert task.lines_json == []
assert task.parse_confidence is None
assert task.match_status is None
assert task.shortage_json is None
assert task.line_results_json is None
assert task.inventory_lines_json is None
assert task.error_message is None
assert "Dify" in result["message"]
assert "【发货通知解析确认】" not in result["message"]
def test_run_single_task_refreshes_after_dify_parse_before_auto_progress(app, monkeypatch):
"""Dify Tool 提交解析结果后,编排器应刷新 session 并继续触发自动推进。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-PARSE-FOLLOW", file_count=1)
task = ShippingTask(
task_no="SN-20260629-FOLLOW01",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
def fake_dify(task_ref: str):
stmt = (
ShippingTask.__table__.update()
.where(ShippingTask.__table__.c.task_no == task_ref)
.values(
process_status="parsed",
review_status=None,
pending_human_reason=None,
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}],
)
)
with db.engine.begin() as conn:
conn.execute(stmt)
return {"status": "ok", "message": "parsed-by-dify"}
def fake_auto_progress(payload):
called["auto_progress"] = payload
return {"status": "running", "message": "rpa triggered"}
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
result = batch_orchestrator._run_single_task(task_no)
assert result["status"] == "running"
assert isinstance(called.get("auto_progress"), dict)
assert called["auto_progress"]["task_id"] == task_no
def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypatch):
"""编排器遇到非 created 且无人工阻塞的任务时应调用 auto_progress。"""
with app.app_context():
@@ -266,8 +965,8 @@ def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypat
assert called["auto_progress"]["task_id"] == task_no
def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app, monkeypatch):
"""后台 Dify 执行器应带上当前任务上下文,并回写 provider conversation id。"""
def test_run_shipping_parse_via_dify_passes_task_context_without_persisting_chat(app, monkeypatch):
"""后台 Dify 执行器应带当前任务上下文,但不复用/污染前端聊天记录。"""
with app.app_context():
user = User(
username="shipping_dify_user",
@@ -293,6 +992,7 @@ def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app
agent_id=agent.id,
title="shipping parse",
status="running",
external_conversation_id="22222222-2222-2222-2222-222222222222",
)
batch = ShippingBatch(
batch_no="SB-DIFY-EXEC",
@@ -321,28 +1021,35 @@ def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app
captured["conversation_id"] = conversation_id
captured["session_id"] = kwargs.get("session_id")
captured["inputs"] = kwargs.get("inputs")
captured["persist_chat_log"] = kwargs.get("persist_chat_log")
yield 'data: {"event":"message_end","conversation_id":"11111111-1111-1111-1111-111111111111","answer":"parsed"}\n\n'
monkeypatch.setattr(dify_executor.DifyService, "stream_chat", staticmethod(fake_stream_chat))
result = dify_executor.run_shipping_parse_via_dify(task.task_no)
assert result["status"] == "ok"
assert captured["query"] == "解析当前发货通知任务"
assert captured["user_id"] == user.id
assert captured["agent_id"] == agent.id
assert captured["conversation_id"] is None
assert captured["session_id"] == session.session_id
assert captured["persist_chat_log"] is False
assert isinstance(captured["inputs"], dict)
assert captured["inputs"]["entry_mode"] == "orchestrator_parse"
assert captured["inputs"]["trigger_source"] == "backend_orchestrator"
assert captured["inputs"]["user_message"] == ""
assert captured["inputs"]["current_task_no"] == task.task_no
assert captured["inputs"]["current_batch_no"] == batch.batch_no
assert captured["inputs"]["hxops_context"]["schema_version"] == "1"
assert captured["inputs"]["hxops_context"]["session"]["id"] == session.session_id
assert captured["inputs"]["hxops_context"]["request"]["id"] == f"shipping-orch-{task.task_no}"
assert captured["inputs"]["hxops_context"]["request"]["trigger_source"] == "backend_orchestrator"
assert captured["inputs"]["hxops_context"]["refs"] == [
{"field": "task", "value": task.task_no},
{"field": "batch", "value": batch.batch_no},
]
refreshed_session = ChatSession.query.filter_by(session_id=session.session_id).first()
assert refreshed_session is not None
assert refreshed_session.external_conversation_id == "11111111-1111-1111-1111-111111111111"
assert refreshed_session.external_conversation_id == "22222222-2222-2222-2222-222222222222"
def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
"""统一版 Dify inputs 应同时包含 entry_mode/user_message/trigger_source。"""
def test_build_dify_chat_inputs_returns_hxops_context_only(app):
"""货代发货 Agent 应只注入平台统一的 hxops_context。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-DIFY-INPUTS",
@@ -362,17 +1069,59 @@ def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
inputs = dify_inputs.build_dify_chat_inputs(
"conv-shipping-inputs-001",
entry_mode="user_chat",
user_message="这票现在什么状态?",
trigger_source="frontend_chat",
request_id="req-frontend-001",
)
assert inputs["entry_mode"] == "user_chat"
assert inputs["conversation_id"] == "conv-shipping-inputs-001"
assert inputs["current_batch_no"] == "SB-DIFY-INPUTS"
assert inputs["current_task_no"] == "SN-20260622-DDDD0004"
assert inputs["user_message"] == "这票现在什么状态?"
assert inputs["trigger_source"] == "frontend_chat"
assert set(inputs.keys()) == {"hxops_context"}
assert inputs["hxops_context"]["schema_version"] == "1"
assert inputs["hxops_context"]["session"]["id"] == "conv-shipping-inputs-001"
assert inputs["hxops_context"]["request"]["id"] == "req-frontend-001"
assert inputs["hxops_context"]["request"]["trigger_source"] == "frontend_chat"
assert inputs["hxops_context"]["refs"] == [
{"field": "task", "value": "SN-20260622-DDDD0004"},
{"field": "batch", "value": "SB-DIFY-INPUTS"},
]
def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation(app):
"""已有 Dify provider 会话号时,HXOPS 上下文仍应按本地 session 解析。"""
with app.app_context():
local_session_id = "conv-shipping-local-session-001"
provider_conversation_id = "f3b371e7-4d8b-40b6-80be-76fd98459c65"
batch = ShippingBatch(
batch_no="SB-DIFY-LOCAL",
conversation_id=local_session_id,
current_focus_task_no="SN-20260626-LOCAL001",
file_count=1,
)
task = ShippingTask(
task_no="SN-20260626-LOCAL001",
batch=batch,
conversation_id=local_session_id,
source_type="manual",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
provider_inputs = dify_inputs.build_dify_chat_inputs(provider_conversation_id)
local_inputs = dify_inputs.build_dify_chat_inputs(local_session_id)
assert provider_inputs["hxops_context"]["refs"] == []
assert local_inputs["hxops_context"]["session"]["id"] == local_session_id
assert local_inputs["hxops_context"]["refs"] == [
{"field": "task", "value": "SN-20260626-LOCAL001"},
{"field": "batch", "value": "SB-DIFY-LOCAL"},
]
def test_is_shipping_notice_chat_agent_accepts_current_dify_app_name():
"""兼容 Dify 侧当前使用的智能发货通知Agent命名。"""
class AgentLike:
name = "智能发货通知Agent"
assert dify_inputs.is_shipping_notice_chat_agent(AgentLike()) is True
def test_create_empty_batch_returns_batch_shell(app, client):
@@ -13,6 +13,24 @@ from app.services.shipping_notice.reservation_id import (
)
def test_extract_notice_text_reads_xfa_pdf_datasets():
"""XFA 表单型 PO 的订单字段应进入 raw_text,避免只抽页面文本漏明细。"""
from pathlib import Path
from app.services.shipping_notice.notice_upload import extract_notice_text
pdf_path = Path(__file__).resolve().parents[2] / "docs" / "prototype" / "4510038672.pdf"
text, meta = extract_notice_text(pdf_path)
assert meta["file_type"] == "pdf"
assert "pdf xfa datasets extracted" in meta["warnings"]
assert "HEADER/EBELN: 4510038672" in text
assert "HEADER/SHIPMENT_TEXT: 1000144510" in text
assert "TEMP-S000218922" in text
assert "MPN:D4-A08AR12000001" in text
assert "EINDT=2026-06-23" in text
def test_extract_reservation_id_from_pr_number():
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
@@ -9,7 +9,7 @@ from app.models import ShippingTask, ShippingTaskEvent
def _tool_headers():
return {"Content-Type": "application/json"}
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
@@ -19,6 +19,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
headers = _tool_headers()
create_res = client.post(
@@ -35,6 +36,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"destination": {"port_code": "DUB", "city": "Dublin"},
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
@@ -66,6 +68,7 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
drop = tmp_path / "drop"
drop.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
headers = _tool_headers()
create_res = client.post(
@@ -99,3 +102,47 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "inventory_ready"
def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
"""确认库存源后应立即进入 RPA pending,并写出库存导出 trigger。"""
from app import db
from app.services.shipping_notice.inventory_rpa_workflow import confirm_inventory_source
trigger = tmp_path / "triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
with app.app_context():
task = ShippingTask(
task_no="SN-CONFIRM-SOURCE-RPA",
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="inventory_source_unresolved",
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
"candidates": [
{
"source_code": "DSV360_AWSDU",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
}
],
}
},
lines_json=[{"sku": "A001", "qty": 1}],
)
db.session.add(task)
db.session.commit()
result = confirm_inventory_source({"task_id": task.task_no, "source_code": "DSV360_AWSDU"})
db.session.refresh(task)
assert result["status"] == "running"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.step_payload_json["rpa_inventory_source"]["source_code"] == "DSV360_AWSDU"
events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all()
assert len(events) == 1
assert list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json"))
@@ -146,12 +146,13 @@ def test_batch_process_summary_shared_formula(app):
db.session.commit()
tasks = [done, running]
assert compute_batch_process_summary(tasks) == {
"total": 2,
"completed": 1,
"failed": 0,
"running": 1,
}
summary = compute_batch_process_summary(tasks)
assert summary["total"] == 2
assert summary["completed"] == 1
assert summary["failed"] == 0
assert summary["running"] == 1
assert summary["pending"] == 2
assert summary["current_task_no"] == "SN-RUN"
tool_batch = serialize_batch(batch, BatchProjection.TOOL)
assert tool_batch["process_summary"]["completed"] == 1
assert tool_batch["batch_no"] == "SB-SUMMARY"
+461 -9
View File
@@ -1,7 +1,7 @@
import pytest
from app import db
from app.models import ShippingInventoryMapping, ShippingTask
from app.models import ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.match import match_notice_lines
@@ -83,10 +83,16 @@ def test_shipping_notice_tool_flow(app, client):
)
assert match_res.status_code == 200
match_data = match_res.get_json()
assert match_data["status"] == "ok"
assert match_data["status"] == "running"
assert "订单" in match_data["message"]
assert "库存" in match_data["message"]
assert "A001" in match_data["message"]
with app.app_context():
auto_exported = ShippingTask.query.filter_by(task_no=task_id).first()
assert auto_exported is not None
assert auto_exported.export_file_path
assert auto_exported.process_status == "waiting_upload"
assert auto_exported.pending_human_reason == "upload_rpa_pending"
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
@@ -160,19 +166,87 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
assert confirm_res.get_json()["status"] == "failed"
def test_submit_decision_rematch_reopens_shortage_for_worker(app, client, monkeypatch):
headers = _tool_headers(app)
started: list[str] = []
from app.services.shipping_notice import decision_workflow
monkeypatch.setattr(
decision_workflow,
"start_task_orchestrator",
lambda task_no: started.append(str(task_no)) or True,
)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
rematch_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "rematch"},
)
assert rematch_res.status_code == 200
assert rematch_res.get_json()["status"] == "running"
assert started == [task_id]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).one()
assert task.process_status == "inventory_ready"
assert task.review_status is None
assert task.pending_human_reason is None
assert task.match_status is None
assert task.shortage_json is None
assert task.line_results_json is None
def test_openapi_spec_public(app, client):
app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com"
res = client.get("/api/shipping-notice/tools/openapi.json")
assert res.status_code == 200
spec = res.get_json()
assert "create_task" in str(spec)
assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice"
props = spec["paths"]["/tools/create_task"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]
assert "raw_content" in props
assert "/rpa/" not in str(spec["paths"])
assert "/tools/parse_inventory" in spec["paths"]
assert "/tools/create_task" not in spec["paths"]
assert "/tools/create_batch" not in spec["paths"]
assert "/tools/parse_inventory" not in spec["paths"]
assert "/tools/ensure_inventory" not in spec["paths"]
assert "/tools/auto_progress" not in spec["paths"]
assert "/tools/match_inventory" not in spec["paths"]
assert "/tools/generate_shipment_excel" not in spec["paths"]
assert "/tools/upload_to_freight" not in spec["paths"]
assert "/tools/switch_focus_task" not in spec["paths"]
assert "/tools/get_inventory_schema_preview" in spec["paths"]
assert "/tools/apply_inventory_mapping" in spec["paths"]
submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"]
assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"]
def test_parse_inventory_from_chat_text(app, client):
@@ -676,6 +750,82 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
assert ShippingInventoryMapping.query.filter_by(customer_code="GLOBAL").count() >= 1
def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_path, monkeypatch):
"""已手工上传完成的票不能被后续批次库存快照重新带回 RPA 上传链路。"""
from io import BytesIO
from openpyxl import Workbook
from app.models import ShippingBatch, ShippingTaskInventoryLink
from app.services.shipping_notice import inventory_file_store
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "freight" / "upload_queue")
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(tmp_path / "freight" / "upload_triggers")
started_task_nos: list[str] = []
def fake_start_task_orchestrator(task_no: str) -> bool:
started_task_nos.append(task_no)
return True
monkeypatch.setattr(inventory_file_store, "start_task_orchestrator", fake_start_task_orchestrator, raising=False)
with app.app_context():
batch = ShippingBatch(batch_no="SB-COMPLETED-LOCK", file_count=2)
completed = ShippingTask(
task_no="SN-20260629-DONE0001",
batch=batch,
source_type="manual",
process_status="uploaded",
pending_human_reason=None,
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
batch_index=1,
batch_total=2,
)
pending = ShippingTask(
task_no="SN-20260629-PEND0002",
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A002", "reservation_id": "R-2", "qty": 1, "uom": "EA"}],
batch_index=2,
batch_total=2,
)
db.session.add_all([batch, completed, pending])
db.session.commit()
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["SKU", "Reservation ID", "Available Qty"])
ws.append(["A001", "R-1", 10])
ws.append(["A002", "R-2", 10])
wb.save(buf)
wb.close()
buf.seek(0)
upload_res = client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={"task_id": "SN-20260629-PEND0002", "file": (buf, "inventory.xlsx")},
)
assert upload_res.status_code == 200
with app.app_context():
completed = ShippingTask.query.filter_by(task_no="SN-20260629-DONE0001").one()
pending = ShippingTask.query.filter_by(task_no="SN-20260629-PEND0002").one()
completed_links = ShippingTaskInventoryLink.query.filter_by(task_id=completed.id, is_active=True).count()
pending_links = ShippingTaskInventoryLink.query.filter_by(task_id=pending.id, is_active=True).count()
assert completed.process_status == "uploaded"
assert completed.pending_human_reason is None
assert completed_links == 0
assert pending_links == 1
assert "SN-20260629-DONE0001" not in started_task_nos
def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
@@ -841,8 +991,17 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
@pytest.mark.auto_rpa
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
headers = _tool_headers(app)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
@@ -864,17 +1023,30 @@ def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
},
)
parse_data = parse_res.get_json()
assert parse_data["status"] == "running"
assert "【发货通知解析确认】" in parse_data["message"]
assert "回复「确认」进入库存检查" not in parse_data["message"]
assert parse_data.get("checkpoint") != "parse_review"
assert called.get("task_no") == task_id
@pytest.mark.auto_rpa
def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path):
def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
import app.services.shipping_notice.decision_workflow as decision_workflow
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
monkeypatch.setattr(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
@@ -904,7 +1076,250 @@ def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, cli
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "running"
assert "RPA 库存导出" in confirm_data["message"]
assert "后台" in confirm_data["message"]
assert "ensure_inventory" not in confirm_data["message"]
assert "match_inventory" not in confirm_data["message"]
assert called.get("task_no") == task_id
def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client, monkeypatch):
import app.services.shipping_notice.decision_workflow as decision_workflow
headers = _tool_headers(app)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task_db_id = task.id
task.inventory_lines_json = [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]
task.process_status = "inventory_ready"
task.review_status = "align_review"
task.pending_human_reason = "align_review"
db.session.commit()
with app.app_context():
db.session.add(
ShippingTaskEvent(
task_id=task_db_id,
event_type="inventory_mapping_inferred",
detail_json={
"column_meta": {
"headers": ["Reservation ID", "SKU", "Qty Available"],
"field_mapping": {
"reservation_id": "Reservation ID",
"sku": "SKU",
"available_qty": "Qty Available",
},
"mapping": {
"reservation_id": {"source_column": "Reservation ID"},
"sku": {"source_column": "SKU"},
"available_qty": {"source_column": "Qty Available"},
},
}
},
)
)
db.session.commit()
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "running"
assert "后台继续处理匹配与后续步骤" in confirm_data["message"]
assert called.get("task_no") == task_id
@pytest.mark.auto_rpa
def test_rpa_pending_timeout_recheck_triggers_next_inventory_export(app, client, tmp_path):
from datetime import datetime, timedelta
from app.services.shipping_notice.batch_orchestrator import _run_single_task
from app.services.shipping_notice.constants import PH_RPA_PENDING
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_rpa_triggered",
detail_json={"attempt": 1},
created_at=datetime.utcnow() - timedelta(seconds=5),
)
)
db.session.commit()
with app.app_context():
result = _run_single_task(task_id)
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["status"] == "running"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == PH_RPA_PENDING
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 2
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
@pytest.mark.auto_rpa
def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path):
from datetime import datetime, timedelta
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_EXHAUSTED
base_time = datetime.utcnow() - timedelta(minutes=5)
for idx in range(3):
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_rpa_triggered",
detail_json={"attempt": idx + 1},
created_at=base_time + timedelta(seconds=idx),
)
)
db.session.commit()
retry_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "retry_rpa"},
)
retry_data = retry_res.get_json()
assert retry_data["status"] == "running"
assert "新一轮第 1/3 次" in retry_data["message"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.error_message is None
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
assert progress.get("message") == "已手动重新触发 RPA 库存导出,等待结果"
assert progress.get("detail") == "新一轮第 1/3 次尝试"
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 4
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
@pytest.mark.auto_rpa
def test_batch_retry_rechecks_timed_out_rpa_pending_immediately(app, client, tmp_path):
from datetime import datetime, timedelta
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
from app.services.shipping_notice.constants import PH_RPA_PENDING
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
create_res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={"conversation_id": "conv-rpa-batch-retry"},
)
batch_no = create_res.get_json()["batch_no"]
task_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={
"batch_no": batch_no,
"conversation_id": "conv-rpa-batch-retry",
"source_type": "manual",
},
)
task_id = task_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_rpa_triggered",
detail_json={"attempt": 1},
created_at=datetime.utcnow() - timedelta(seconds=5),
)
)
db.session.commit()
with app.app_context():
result = retry_batch_pending_tasks(batch_no)
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["started"] == 1
assert result["skipped"] == 0
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == PH_RPA_PENDING
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 2
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
def test_submit_decision_by_conversation_id(app, client):
@@ -950,6 +1365,43 @@ def test_submit_decision_by_conversation_id(app, client):
assert dup_data.get("checkpoint") == "task_exists"
def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, monkeypatch):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
import app.services.shipping_notice.decision_workflow as decision_workflow
captured: dict[str, object] = {}
def fake_ensure_inventory(payload):
captured.update(payload)
return {
"status": "running",
"task_id": payload["task_id"],
"message": "已触发 RPA 库存导出(测试桩)",
}
monkeypatch.setattr(decision_workflow, "ensure_inventory", fake_ensure_inventory)
res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "retry_rpa", "comment": "retry now"},
)
data = res.get_json()
assert data["status"] == "running"
assert data["task_id"] == task_id
assert data["message"] == "已触发 RPA 库存导出(测试桩)"
assert captured["task_id"] == task_id
assert captured["mode"] == "retry_rpa"
def test_parse_inventory_rejects_oversized_text(app, client):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 100
@@ -0,0 +1,417 @@
# HXOPS 统一上下文注入原型设计
| 项目 | 说明 |
|------|------|
| 文档版本 | v1.0 |
| 读者 | 产品负责人、平台研发、Agent 研发、Dify 画布维护者、测试验收 |
| 产品名称 | HXOPS 统一上下文注入 |
| 适用范围 | 所有接入 HXOPS 的 Dify Agent / Chatflow / Workflow |
---
## 目录
- [一、需求缘起和要解决的问题](#一需求缘起和要解决的问题)
- [二、需求输出设计](#二需求输出设计)
- [三、规格需求](#三规格需求)
- [四、测试场景案例](#四测试场景案例)
- [五、补充说明](#五补充说明)
---
## 一、需求缘起和要解决的问题
### 1.1 需求缘起
HXOPS 当前已接入多个 Agent 场景,包括但不限于:
- 货代发货通知
- 文件检核
- OA / 请假类流程
- 知识库与其他平台型能力
这些 Agent 在接入 Dify 时,普遍存在一类平台共性问题:
**HXOPS 需要向 Dify 注入上下文,但各 Agent 当前使用的输入变量并不统一。**
例如:
- 有的 Agent 依赖 `task_id`
- 有的 Agent 依赖 `current_task_no`
- 有的 Agent 依赖 `conversation_id`
- 有的 Agent 依赖 `current_batch_no`
- 有的 Agent 还会定义业务专属输入变量
结果是:
- 平台侧要理解“每个应用需要什么字段”
- Dify 画布 Start 输入越来越分散
- 新增 Agent 时常常复制旧模式再改名
- 输入协议逐渐与业务实现强耦合
因此,需要抽象出一套**平台统一上下文注入协议**,由 HXOPS 统一注入,供所有 Dify 应用按统一方式消费。
### 1.2 现存核心痛点
#### 1.2.1 平台侧痛点
- 平台需要为不同 Agent 写不同的 Dify 输入拼装逻辑,难以维护。
- 输入字段名没有统一规范,平台很难形成稳定抽象层。
- 当业务对象命名变化时,平台与画布都要同步调整,改动成本高。
- 平台无法只做“上下文锚点注入”,而被迫承担部分业务流程输入设计。
#### 1.2.2 Dify 画布侧痛点
- 画布 Start 输入变量过多,且字段含义不稳定。
- 画布分支依赖输入变量本身,而不是依赖后端 Tool 的实时状态。
- 不同 Agent 画布重复定义同类变量,难以复用通用节点与通用分支。
- 当没有 `task_id/current_task_no` 等上下文时,很多画布缺少统一兜底流程。
#### 1.2.3 架构一致性痛点
- 用户输入、业务对象锚点、运行态状态混在一起,职责边界不清晰。
- Dify 原生 `query/files` 与 HXOPS 自定义输入重复表达,易形成双写。
- 平台无法明确区分“当前已知上下文”与“实时运行状态”。
- 运行态判断散落在输入变量、LLM 提示词和 Tool message 文案里,不利于平台化收敛。
### 1.3 原型开发目标与边界
#### 目标
提供一套 **HXOPS 统一上下文注入协议**,用于 HXOPS 调用 Dify 时统一传递上下文。
核心目标如下:
1. HXOPS 平台统一只传一个上下文对象:`hxops_context`
2. 用户输入与附件继续使用 Dify 原生 `query` / `files`
3. 业务对象统一通过 `refs` 表达
4. Dify 画布统一通过 `hxops_context` 定位当前业务对象
5. 运行态分支统一依赖后端 Tool 返回,不再依赖 Start 私有变量
#### 原型范围内
- 定义 `hxops_context` 的平台级结构
- 定义 `refs` 的统一表达方式
- 定义 HXOPS 如何发现并注入“当前已知业务对象”
- 定义 Dify 画布如何消费统一上下文
- 定义运行态分支与 Tool 返回的职责边界
#### 原型范围外
- 各业务 Tool 的具体实现细节
- 各 Agent OpenAPI 文档全面重写
- 前端工作台 UI 改版
- 某一类 Agent 的专属输入协议扩展
---
## 二、需求输出设计
### 2.1 整体设计思路
本原型将 HXOPS -> Dify 的输入模型拆成三层:
1. **Dify 原生输入层**
- `query`
- `files`
2. **HXOPS 平台上下文层**
- `inputs.hxops_context`
3. **Tool 运行态层**
- `status`
- `checkpoint`
- `stage`
- `next_required_action`
- `stop_agent_turn`
- 其他状态字段
三层职责如下:
```mermaid
flowchart TB
subgraph inputLayer [输入层]
Query["query"]
Files["files"]
end
subgraph contextLayer [平台上下文层]
HxopsContext["hxops_context"]
Refs["refs"]
end
subgraph runtimeLayer [运行态层]
ToolStatus["Tool 返回状态"]
end
Query --> HxopsContext
Files --> HxopsContext
HxopsContext --> Refs
Refs --> ToolStatus
```
**设计原则**
1. **输入与上下文分层**:用户输入继续走 `query/files`,平台补充上下文统一走 `hxops_context`。
2. **上下文只表达已知锚点**:`hxops_context` 只承载平台基础信息和当前已知对象引用。
3. **业务对象统一表达**:所有 Agent 统一通过 `refs` 传递业务对象锚点。
4. **运行态不提前注入**:`checkpoint/stage` 等实时状态不进入 `hxops_context`。
5. **画布先查状态再分支**:Dify 画布通过 `refs` 找对象,再通过 Tool 获取运行态。
### 2.2 核心功能清单
| 编号 | 功能名称 | 用户价值 | 主要输入 | 主要输出 |
|------|----------|----------|----------|----------|
| F1 | 统一上下文注入 | 平台不再为每个 Agent 单独定制变量 | HXOPS 会话、请求、绑定对象 | `hxops_context` |
| F2 | 基础上下文表达 | 稳定传递平台级会话与请求信息 | session/request 元数据 | `schema_version`、`session`、`request` |
| F3 | 业务对象锚点表达 | 统一表达 task/run/document 等对象 | 当前已知业务对象 | `refs[]` |
| F4 | Dify 统一消费 | 画布不再依赖私有 Start 输入协议 | `hxops_context` | 标准化内部变量 |
| F5 | 运行态状态驱动 | 流程分支统一依赖 Tool 返回 | 状态查询 Tool 响应 | 结构化流程状态 |
| F6 | 缺失上下文兜底 | 没有 refs 时仍可工作 | 空 `refs` | 用户提示 / 补充动作 |
### 2.3 核心业务流程
本原型的目标流程不是业务流程,而是**上下文注入与消费流程**。
```mermaid
flowchart TD
S1["步骤1 HXOPS 接收 query/files"] --> S2["步骤2 构造 hxops_context"]
S2 --> S3["步骤3 发现当前已知 refs"]
S3 --> S4["步骤4 调用 Dify 并传入 hxops_context"]
S4 --> S5["步骤5 Dify 读取 refs"]
S5 --> S6["步骤6 调状态查询 Tool"]
S6 --> S7["步骤7 按 Tool 返回状态分支"]
```
#### 流程说明
| 步骤 | 平台/画布做什么 | 输出 |
|------|------------------|------|
| 1 | HXOPS 收到用户请求或系统触发 | `query` / `files` |
| 2 | HXOPS 构造统一上下文对象 | `hxops_context` |
| 3 | HXOPS 发现当前已知业务对象 | `refs[]` |
| 4 | HXOPS 调用 Dify | `query` + `files` + `hxops_context` |
| 5 | Dify 画布读取 `hxops_context` | 内部标准化变量 |
| 6 | Dify 通过对象锚点调用状态 Tool | 结构化状态 |
| 7 | Dify 按 Tool 返回分支 | 动作 / 等待用户 / 完成 |
### 2.4 输出结果规范
#### 2.4.1 `hxops_context` 标准结构
```json
{
"hxops_context": {
"schema_version": "1",
"session": {
"id": "hxops-session-id"
},
"request": {
"id": "req_xxx",
"trigger_source": "user_chat",
"locale": "zh-CN"
},
"refs": [
{
"field": "task",
"value": "SN-20260623-AB12CD34"
}
]
}
}
```
#### 2.4.2 字段定义
| 字段 | 必填 | 说明 |
|------|------|------|
| `schema_version` | 是 | 协议版本,当前固定为 `"1"` |
| `session.id` | 是 | HXOPS 本地会话 ID |
| `request.id` | 否 | 请求追踪 ID |
| `request.trigger_source` | 否 | 平台触发来源 |
| `request.locale` | 否 | 当前语言环境 |
| `refs` | 是 | 当前已知业务对象锚点列表 |
#### 2.4.3 `refs` 标准结构
```json
"refs": [
{
"field": "task",
"value": "SN-20260623-AB12CD34"
},
{
"field": "batch",
"value": "BATCH-20260623-001"
}
]
```
#### 2.4.4 `refs.field` 推荐枚举
- `task`
- `batch`
- `run`
- `document`
- `group`
- `approval`
- `request`
#### 2.4.5 注入规则
| 规则 | 说明 |
|------|------|
| 基础字段始终注入 | `schema_version`、`session.id`、`request.*`、`refs` |
| `refs` 只注入当前已知对象 | 不根据“某应用需要什么”反向定制 |
| `refs` 可为空 | 无对象锚点时允许 `[]` |
| 同一 `field` 默认最多一条 | v1 不支持同类对象多值并列 |
| 运行态字段禁止进入 `hxops_context` | `checkpoint/stage/...` 一律从 Tool 返回 |
---
## 三、规格需求
### 3.1 平台注入规格
HXOPS 调用 Dify 时:
- 用户消息继续传 `query`
- 用户附件继续传 `files`
- 平台上下文统一传 `inputs.hxops_context`
不再要求平台按 Agent 注入以下字段:
- `current_task_no`
- `current_batch_no`
- `task_id`
- `conversation_id`
- `entry_mode`
### 3.2 `trigger_source` 规格
推荐枚举:
- `user_chat`
- `system`
- `scheduler`
- `callback`
- `retry`
要求:
- 仅表达平台来源
- 不表达业务模式
- 不夹带 Agent 私有流程语义
### 3.3 `refs` 发现规格
HXOPS 发现 `refs` 的优先级:
1. 当前显式上下文
2. 当前会话已绑定对象
3. 当前入口页面/路由带入对象
4. 最近一次已确认有效对象
5. 没有则不注入
### 3.4 Dify 消费规格
画布统一流程要求:
1. 读取 `hxops_context`
2. 解析 `refs`
3. 调用状态查询 Tool
4. 按 Tool 返回分支
禁止:
- 把 `hxops_context` 当实时状态来源
- 依赖私有 Start 变量做主流程分支
- 在缺少 `refs` 时直接报错终止
### 3.5 Tool 返回规格
为支持统一上下文注入,状态查询 Tool 与动作 Tool 应逐步统一返回:
- `status`
- `checkpoint`
- `stage`
- `next_required_action`
- `allowed_tools`
- `forbidden_next_tools`
- `stop_agent_turn`
- `human_options`
- `display_message`
- `display_payload`
优先级最高字段:
1. `checkpoint`
2. `next_required_action`
3. `stop_agent_turn`
### 3.6 禁止项
以下内容不得进入 `hxops_context`:
#### 与 Dify 原生输入重复
- `query`
- `files`
- `user_message`
- `attachments`
#### 运行态状态字段
- `checkpoint`
- `stage`
- `current_step`
- `next_required_action`
- `allowed_tools`
- `forbidden_next_tools`
- `stop_agent_turn`
#### Agent 私有流程开关
- `entry_mode`
- `shipping_mode`
- `parse_mode`
- `schedule_task_id`
---
## 四、测试场景案例
| 编号 | 场景 | 输入情况 | 预期 |
|------|------|----------|------|
| TC-01 | 只有 query,无业务锚点 | `refs=[]` | Dify 进入兜底提示,而非依赖旧私有变量 |
| TC-02 | 当前会话已绑定单个对象 | `refs=[run]` | 画布能识别对象并调用状态查询 Tool |
| TC-03 | 当前会话已绑定多个对象 | `refs=[task,batch]` | 画布可提取所需对象,状态查询可正常工作 |
| TC-04 | 不同 Agent 共享协议 | 一个 Agent 用 `task`,另一个用 `document` | 平台协议不变,画布按需解析 |
| TC-05 | 无旧变量兼容时运行 | 不再传 `current_task_no/current_batch_no` | 新画布仍可通过 `hxops_context` 工作 |
| TC-06 | Tool 返回 needs_human | `stop_agent_turn=true` | 画布停下等待用户,而非继续自动链路 |
| TC-07 | Tool 返回 completed | `checkpoint=completed` | 画布进入完成态总结 |
| TC-08 | 平台未发现任何对象 | `refs=[]` | 画布允许请求用户补充上下文 |
---
## 五、补充说明
### 5.1 本原型不要求一次性删除旧协议
为降低风险,建议采用渐进迁移:
1. 平台先并行注入 `hxops_context`
2. 画布改为优先读取 `hxops_context`
3. Tool 返回补齐状态字段
4. 最后再下线旧私有输入变量
### 5.2 本原型不是某个 Agent 的专属方案
该原型用于所有 HXOPS Agent,因此:
- 不能绑定货代专属字段名
- 不能绑定文件检核专属字段名
- 不能依赖某个业务模型的对象表达方式
### 5.3 一句话总结
HXOPS 统一上下文注入原型的核心是:
**平台统一只传 `hxops_context`,业务对象通过 `refs` 表达,Dify 统一通过状态查询 Tool 获取运行态,再按 Tool 返回进行流程分支。**
@@ -0,0 +1,353 @@
# HXOPS 统一上下文注入实现
> 文件定位:平台级实现方案文档。
> 目标:把 HXOPS -> Dify 的输入与分支逻辑收敛到统一协议,逐步替换现有 Agent 私有注入方式。
> 实现原则:平台统一只传 `hxops_context`,业务对象通过 `refs` 表达,运行态分支靠 Tool 返回。
---
## 1. 实现目标
在不破坏现有 Agent 运行的前提下,逐步完成以下收敛:
1. 平台统一构造 `inputs.hxops_context`
2. 各 Agent 不再定义私有 Start 输入协议
3. Dify 画布统一改为“先查状态,再分支”
4. Tool 返回统一提供状态驱动画布的关键字段
---
## 2. 实现范围
本实现方案覆盖三层:
1. 后端注入端
2. Dify 画布端
3. Tool 返回端
不包含:
- 具体业务 Tool 逻辑重写
- OpenAPI 细节的全面重构
- 具体某一 Agent 的 UI 改版
---
## 3. 后端注入端
### 3.1 平台统一注入出口
后端需要把“向 Dify 注入什么 inputs”的职责,从各 Agent 零散实现中抽出来,统一收敛到平台调用出口。
目标职责:
- 统一构造 `inputs.hxops_context`
- 继续透传 `query` / `files`
- 不再按 Agent 决定不同顶层输入变量名
建议实现一个统一构造函数:
```python
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,
) -> dict
```
输出:
```json
{
"schema_version": "1",
"session": {
"id": "..."
},
"request": {
"id": "...",
"trigger_source": "user_chat",
"locale": "zh-CN"
},
"refs": []
}
```
### 3.2 统一 `refs` 发现器
平台需要一个统一的“业务对象锚点发现器”。
建议实现:
```python
resolve_hxops_refs(
*,
request_data: dict | None = None,
session: object | None = None,
route_context: dict | None = None,
bound_context: dict | None = None,
) -> list[dict[str, str]]
```
职责:
- 收集当前显式上下文中的业务对象
- 收集当前会话绑定对象
- 收集入口页带入对象
- 做合法性过滤
- 转成统一 `refs` 结构
输出示例:
```json
[
{
"field": "task",
"value": "SN-20260623-AB12CD34"
},
{
"field": "batch",
"value": "BATCH-20260623-001"
}
]
```
### 3.3 Agent 适配层职责调整
现有各 Agent 的 `dify_inputs.py` 不应再负责“定义私有输入协议”,而应降级为:
- 帮助发现该 Agent 可识别的业务对象引用
- 补充 `refs`
- 最终仍统一回到平台级 `hxops_context`
也就是说,Agent 适配层职责从:
- “拼 Agent 专属 inputs”
改成:
- “发现 Agent 可提供的业务对象锚点”
### 3.4 与现有系统的兼容策略
建议三阶段兼容:
#### 阶段 1:并行注入
- 保留现有 Agent 私有 inputs
- 新增 `inputs.hxops_context`
- Dify 画布暂时同时兼容新旧两套协议
#### 阶段 2:画布切换
- Dify 画布优先读取 `hxops_context`
- 私有变量只作为兜底
#### 阶段 3:移除旧协议
- 删除旧私有输入变量拼装逻辑
- 平台统一只传 `hxops_context`
### 3.5 推荐后端改造项
建议明确拆成以下任务:
1. 新增 `build_hxops_context(...)`
2. 新增 `resolve_hxops_refs(...)`
3. 在统一 Dify 调用入口接入 `hxops_context`
4. 调整各 Agent `dify_inputs.py` 的职责
5. 增加注入日志,便于排障
---
## 4. Dify 画布端
### 4.1 Start 输入统一收口
画布不再要求平台按应用注入一堆私有变量。
Start 只依赖三类输入:
- `query`
- `files`
- `hxops_context`
### 4.2 上下文标准化节点
每套 Dify 画布建议在 Start 后增加一个 Code 节点:
节点职责:
- 读取 `hxops_context`
- 从 `refs` 中找自己关心的对象
- 输出画布内部统一变量
例如:
- `resolved_task_ref`
- `resolved_run_ref`
- `resolved_document_ref`
注意:
- 这是画布内部变量
- 不属于 HXOPS 对外注入协议
- 不同 Agent 可以选择性解析不同 `field`
### 4.3 画布统一路由原则
画布不再依赖输入变量直接决定主流程。
统一流程应为:
1. 读取 `hxops_context`
2. 解析对象锚点
3. 调状态查询 Tool
4. 按 Tool 返回路由
即:
- `hxops_context` 负责定位对象
- Tool 返回负责决定当前该做什么
### 4.4 画布必须允许 `refs` 为空
如果当前没有任何业务对象锚点,画布必须允许走兜底流程:
- 请用户指定任务号
- 请用户上传文件
- 请用户从工作台选择记录
不能假设:
- 每次都有 `task`
- 每次都有 `run`
- 每次都有 `document`
### 4.5 推荐画布结构
推荐统一结构:
1. Start
2. Code:normalize_hxops_context
3. Code:resolve_ref_by_field
4. Tool:get_*_status
5. Code:normalize_tool_status
6. IF:按 `checkpoint/stage/next_required_action/stop_agent_turn` 路由
7. Tool / Answer:执行动作或等待用户
### 4.6 推荐 Dify 画布改造项
建议统一补这些节点/规则:
1. `Code: normalize_hxops_context`
2. `Code: resolve_ref_by_field`
3. `Tool: get_*_status`
4. `Code: normalize_tool_status`
5. 主分支统一改为基于 Tool 状态路由
6. 缺少 `refs` 时的兜底 Answer
---
## 5. Tool 返回端
### 5.1 Tool 返回从“message 驱动”升级为“状态驱动”
当前很多画布分支依赖 `message` 文案理解流程。
要支撑平台化上下文注入,Tool 返回必须升级为结构化状态。
建议统一字段:
- `status`
- `checkpoint`
- `stage`
- `next_required_action`
- `allowed_tools`
- `forbidden_next_tools`
- `stop_agent_turn`
- `human_options`
- `display_message`
- `display_payload`
### 5.2 优先改造状态查询类 Tool
状态查询 Tool 是画布统一路由的入口,优先级最高。
推荐先统一:
- 货代的 `get_task_status`
- 文件检核的状态查询 Tool
- 其他 Agent 的主状态查询接口
### 5.3 动作 Tool 也要回标准状态
动作类 Tool 在执行完后,也应返回相同风格的状态结构。
例如:
- `parse_notice`
- `submit_decision`
- `apply_inventory_mapping`
- `match_inventory`
- `generate_excel`
- `upload_to_freight`
这样 Dify 画布执行动作后,不必再凭文案判断下一步。
### 5.4 推荐的最小返回结构
```json
{
"status": "ok",
"checkpoint": "parse_review",
"stage": "notice_parse",
"next_required_action": "confirm_parse",
"allowed_tools": ["submit_decision"],
"forbidden_next_tools": ["match_inventory"],
"stop_agent_turn": true,
"human_options": ["confirm", "reject", "reparse"],
"display_message": "当前任务解析完成,但需要人工确认。",
"display_payload": {}
}
```
### 5.5 Tool 返回端改造顺序
建议按以下顺序推进:
1. 状态查询 Tool 标准化
2. 关键动作 Tool 标准化
3. 错误结构标准化
4. `display_payload` 统一
5. `allowed_tools / stop_agent_turn` 补齐
---
## 6. 推荐实施顺序
### 阶段 1:协议铺底
- 后端新增 `hxops_context`
- 统一注入基础字段与 `refs`
- 画布开始读取 `hxops_context`
- 暂不删除旧协议
### 阶段 2:状态驱动画布
- Dify 画布改为“先查状态,再路由”
- 状态查询 Tool 补齐关键字段
- 动作 Tool 逐步返回标准状态
### 阶段 3:清理旧心智
- 移除 Agent 私有 Start 输入协议
- 移除画布对旧变量的依赖
- 平台仅保留 `query/files + hxops_context`
---
## 7. 一句话总结
HXOPS 统一上下文注入实现的核心是:
**后端统一注入 `hxops_context`,Dify 画布统一读取 `hxops_context` 定位对象并先查状态,所有运行态流程判断统一依赖后端 Tool 返回。**
+10 -466
View File
@@ -1,9 +1,9 @@
{
"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": [
{
@@ -11,132 +11,6 @@
}
],
"paths": {
"/tools/create_batch": {
"post": {
"operationId": "create_batch",
"summary": "创建发货批次 batch(一次多文件上传的聚合容器)",
"description": "创建发货批次 batch(一次多文件上传的聚合容器)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "已存在的批次编号(可选)。传入时将直接复用该批次。"
},
"user_id": {
"type": "integer",
"description": "Hxops 用户 ID(可选)"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID,便于工作台关联"
},
"file_count": {
"type": "integer",
"description": "本批通知文件数量"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/create_task": {
"post": {
"operationId": "create_task",
"summary": "创建发货任务 task(可挂到某个 batch)",
"description": "创建发货任务 task(可挂到某个 batch)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "发货批次编号(batch id),如 SB-20260617-ABCD1234"
},
"task_id": {
"type": "string",
"description": "已存在的发货任务编号(可选)。传入时将直接复用该任务,禁止重复创建。"
},
"user_id": {
"type": "integer",
"description": "Hxops 用户 ID(可选)"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID,便于工作台关联"
},
"source_type": {
"type": "string",
"description": "来源:manual|email|wecom|pdf",
"enum": [
"manual",
"email",
"wecom",
"pdf"
]
},
"source_file_name": {
"type": "string",
"description": "原始通知文件名(多文件场景建议传)"
},
"source_file_type": {
"type": "string",
"description": "原始通知文件类型(多文件场景建议传)"
},
"batch_index": {
"type": "integer",
"description": "当前任务在批次中的顺序,从 1 开始"
},
"batch_total": {
"type": "integer",
"description": "当前批次总任务数"
},
"raw_content": {
"type": "string",
"description": "原始发货通知文本(可选,后续 parse 也可传入)"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/parse_notice": {
"post": {
"operationId": "parse_notice",
@@ -389,70 +263,11 @@
}
}
},
"/tools/parse_inventory": {
"post": {
"operationId": "parse_inventory",
"summary": "解析库存。大 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。",
"description": "解析库存。大 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。",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"use_uploaded_file": {
"type": "string",
"description": "true=解析该任务已上传的 Excel(服务端直传,不经过 LLM)",
"enum": [
"true",
"false"
]
},
"map_json": {
"type": "string",
"description": "可选,列映射 JSON 字符串,如 {\"sku\":\"AWS Sku\",\"available_qty\":\"Qty Available\"}"
},
"raw_inventory_text": {
"type": "string",
"description": "仅小表(约 <8 万字符)。大 Excel 勿传此字段,改用 upload_inventory_file"
},
"inventory_lines_json": {
"type": "string",
"description": "可选,已整理好的 JSON 数组字符串,如 [{\"sku\":\"A001\",\"available_qty\":10}]"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/get_inventory_schema_preview": {
"post": {
"operationId": "get_inventory_schema_preview",
"summary": "读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
"description": "读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
"summary": "读取已上传批次库存快照的表头与样例行(小 payload,供 LLM 推断列映射)",
"description": "读取已上传批次库存快照的表头与样例行(小 payload,供 LLM 推断列映射)",
"parameters": [],
"requestBody": {
"required": true,
@@ -490,8 +305,8 @@
"/tools/apply_inventory_mapping": {
"post": {
"operationId": "apply_inventory_mapping",
"summary": "应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
"description": "应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
"summary": "应用 LLM/人工列映射并解析完整批次库存快照;返回 field_alignment 等待用户确认,后续本批各票由后台任务独立续跑",
"description": "应用 LLM/人工列映射并解析完整批次库存快照;返回 field_alignment 等待用户确认,后续本批各票由后台任务独立续跑",
"parameters": [],
"requestBody": {
"required": true,
@@ -531,145 +346,11 @@
}
}
},
"/tools/ensure_inventory": {
"post": {
"operationId": "ensure_inventory",
"summary": "确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
"description": "确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"mode": {
"type": "string",
"description": "auto=自动/RPA;retry_rpa=重试 RPA",
"enum": [
"auto",
"retry_rpa"
]
},
"inventory_lines_json": {
"type": "string",
"description": "手工库存 JSON 数组字符串,如 [{\"sku\":\"A001\",\"available_qty\":10}]"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/auto_progress": {
"post": {
"operationId": "auto_progress",
"summary": "按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
"description": "按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID(可选,用于仅知道会话时定位任务)"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/match_inventory": {
"post": {
"operationId": "match_inventory",
"summary": "匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;未确认时调用会被拒绝并返回 forbidden_next_tools",
"description": "匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;未确认时调用会被拒绝并返回 forbidden_next_tools",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"inventory_lines_json": {
"type": "string",
"description": "可选,覆盖库存 JSON 数组后再匹配"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/submit_decision": {
"post": {
"operationId": "submit_decision",
"summary": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
"description": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
"summary": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
"description": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
"parameters": [],
"requestBody": {
"required": true,
@@ -688,11 +369,12 @@
},
"decision": {
"type": "string",
"description": "confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
"description": "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",
@@ -726,97 +408,6 @@
}
}
},
"/tools/generate_shipment_excel": {
"post": {
"operationId": "generate_shipment_excel",
"summary": "生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
"description": "生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/upload_to_freight": {
"post": {
"operationId": "upload_to_freight",
"summary": "上传 Excel 到货代系统(RPA 或手工确认)",
"description": "上传 Excel 到货代系统(RPA 或手工确认)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"mode": {
"type": "string",
"description": "auto=触发 RPA;retry_upload=重试;manual_confirm=手工上传完成",
"enum": [
"auto",
"retry_upload",
"manual_confirm"
]
},
"freight_ref_no": {
"type": "string",
"description": "货代系统单号(可选;manual_confirm 通常无需填写)"
}
},
"required": [
"task_id"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/get_task_status": {
"post": {
"operationId": "get_task_status",
@@ -895,53 +486,6 @@
}
}
}
},
"/tools/switch_focus_task": {
"post": {
"operationId": "switch_focus_task",
"summary": "切换当前批次的聚焦任务",
"description": "切换当前批次的聚焦任务",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "发货批次编号(batch id),如 SB-20260617-ABCD1234"
},
"task_no": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"target_task_no": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
}
},
"required": [
"batch_no"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
}
}
}
File diff suppressed because it is too large. Load diff
+1423 -2399
View File
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -91,7 +91,9 @@
SN-20260529-A1B2C3D4
```
后续所有上传、确认、匹配、导出都围绕**同一任务编号**进行。请在对照库存、核对结果时始终关注助手回复中的该编号,**不要在同一对话里重复发起「新建任务」**,以免数据分散。
后续所有上传、确认、匹配、导出都围绕**明确的任务编号**进行。一次业务委托可以在同一 Agent 会话中拆成多个批次(`SB-...`)和多票任务(`SN-...`);聊天顶部会展示会话执行摘要、批次列表和当前聚焦任务。请在对照库存、核对结果时始终关注当前聚焦的批次与任务编号。
同一会话中的多个批次会共享业务委托背景和库存快照等上下文,但执行动作彼此隔离:确认、驳回、重试、上传等操作只影响界面标明的当前批次或当前任务,跨批次批量操作不会自动发生。
---
@@ -524,10 +526,10 @@ A:业务上**一般为 8~12 位纯数字**(如 `1000140351`)。若格式
A:不会。库存匹配只看 SKU、Reservation ID、需求数量;但导出 Excel 前仍建议在解析确认阶段核对单价与金额。
**Q:助手文字建议和下方按钮不一致怎么办?**
A:以**按钮和任务当前状态**为准;若任务已驳回,不应再出现「确认字段对齐」类按钮。遇此类情况请联系 IT 并保留截图。
A:以**系统按钮和任务当前状态**为准。助手正文只负责说明状态,不应重复列出一套操作清单;若正文和按钮不一致,请以按钮为准并保留截图反馈。
**Q:同一对话里能否处理两票货?**
A:建议**一票货一个对话、一个 SN-… 编号**,避免混淆。
A:可以。现在推荐按**一次业务委托一个 Agent 会话**处理;同一会话下可以包含多个批次和多票任务。操作前请看清顶部显示的当前批次 `SB-...` 和当前任务 `SN-...`,确认、驳回、重试等动作只作用于当前聚焦范围。
---
@@ -0,0 +1,87 @@
# 发货通知库存源路由与 RPA Driver 方案
## 背景
发货通知的库存导出不能再假设只有一个 RPA 地址或一种页面流程。不同目的地、出货港口或仓库线索可能对应不同货代系统入口,例如 DSV 360 的不同 Program,或 Crane FootPrint Portal 的不同 Warehouse。若选错库存源,后续库存匹配和出货 Excel 会建立在错误库存池上,风险高于“未查到库存”。
## 设计原则
- Dify LLM 负责从非结构化发货通知和用户对话中抽取候选字段,不负责最终 RPA URL 决策。
- HXOPS 负责标准化、规则匹配、唯一性判断、权限校验、人工确认和审计。
- RPA 只消费 HXOPS 给出的 `rpa_inventory_source` 参数,按 `source_type` 分发到不同 Driver。
- 通用化范围是 trigger 协议、状态机、超时重试、回调、库存标准化;页面操作逻辑由不同 Driver 独立实现。
- 用户对话可以做当前任务级临时覆盖;全局规则变更只能作为建议,需审核后生效。
## MVP 范围
第一版不改数据库结构,规则和源配置先放代码中,任务级上下文写入 `ShippingTask.step_payload_json`。
MVP 包含:
- 解析 Dify 输出的目的地候选字段,并保存到任务 step payload。
- 根据目的地/港口/仓库线索解析库存源。
- 唯一命中时自动写入 `rpa_inventory_source`。
- 无法命中或多命中时进入 `inventory_source_review` 人工检查点。
- RPA trigger JSON 增加 `rpa_inventory_source`。
- 后端测试覆盖 DSV 与 Crane 的基本路由。
暂不包含:
- 后台规则管理页面。
- 数据库规则表。
- 批次级对话覆盖。
- 全局规则建议审核流。
## Trigger 协议
```json
{
"action": "inventory_export",
"task_no": "SN-xxx",
"attempt": 1,
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"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"
}
}
}
```
Crane 示例:
```json
{
"source_code": "CRANE_TZR",
"source_type": "crane_footprint",
"entry_url": "https://wms-portal.craneww.com/#/on-hand-details-query",
"query": {
"owner_code": "0000000100",
"warehouse_code": "TZR",
"project_code": null
}
}
```
## 初始路由规则
- `BISON`, `AWSBI` -> `DSV360_AWSBI`
- `CINCINNATI`, `CVG`, `AWSCV` -> `DSV360_AWSCV`
- `DUB`, `DUBLIN` -> `DSV360_AWSDU`
- `MOERDIJK`, `AMS`, `AWSAMS` -> `DSV360_AWSAMS`
- `USLCK`, `SALT LAKE CITY` -> `DSV360_AWSSL`
- `SINGAPORE`, `SG` -> `DSV360_AWSSG`
- `TZR`, `THAILAND` -> `CRANE_TZR`
## 后续演进
- 将代码配置迁移到可维护规则表。
- 增加管理员审核的规则变更建议。
- RPA 侧实现 `dsv360` 与 `crane_footprint` Driver。
- 导入库存时校验 source_code、warehouse/program 与任务期望是否一致。
+7
View File
@@ -18,6 +18,13 @@
- Chatflow 编排见 **[docs/file_check.md](file_check.md)**(第二部分);OpenAPI 见 **[docs/openapi/file_check_tools_openapi.json](openapi/file_check_tools_openapi.json)**(`python backend/scripts/export_file_check_openapi.py`)。
- 复用知识库清洗与 Dify 同步链路,将检核报告 Excel 入库。
### 2.x 货代发货通知批次库存能力
- 单票与多票发货需求统一落入 `ShippingBatch`;单票使用 `file_count=1` 的批次容器。
- 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。
- 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。
- `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。
### 2.1 已有聊天路由能力
- 后端 `chat` 接口已支持按意图分流
@@ -7,11 +7,14 @@ export const SHIPPING_ACTION_IDS = [
'confirm',
'reject',
'reparse',
'replace_notice_file',
'confirm_inventory_mapping',
'correct_inventory_mapping',
'reparse_inventory',
'rematch',
'retry_rpa',
'confirm_inventory_source',
'retry_resolve_inventory_source',
'upload_inventory_file',
'retry_upload',
'download_excel',
@@ -50,6 +53,8 @@ export const SHIPPING_INTERNAL_STATUS_TOKENS = [
'export_ready',
'upload_req',
'inventory_pending',
'inventory_source_review',
'inventory_source_unresolved',
'map_ok',
'parse_ok',
'needs_human',
@@ -8,6 +8,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
import type {
ShippingBatchSummary,
ShippingChatActionsResponse,
ShippingConversationWorkspace,
ShippingDecisionResponse,
ShippingInventoryUploadResponse,
ShippingNoticeHeader,
@@ -50,6 +51,12 @@ export const getWorkspaceShippingBatch = (batchNo: string) =>
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}`,
);
/** 获取一个 Agent 会话下的多批次执行工作台快照。 */
export const getWorkspaceShippingConversationBatches = (conversationId: string) =>
getJson<ShippingConversationWorkspace>(
`/api/workspace/shipping-conversations/${encodeURIComponent(conversationId)}/batch-workspace`,
);
/** 获取指定批次当前焦点任务。 */
export const getWorkspaceShippingBatchFocusTask = (batchNo: string) =>
getJson<ShippingTaskSummary>(
@@ -92,6 +99,28 @@ export async function uploadWorkspaceShippingInventory(taskNo: string, file: Fil
return body;
}
/**
* 确认当前任务的库存 RPA 来源。
* @param taskNo - 发货任务编号
* @param sourceCode - 已配置的库存源编码
* @returns RPA 库存导出触发结果
*/
export async function confirmWorkspaceShippingInventorySource(taskNo: string, sourceCode: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/confirm-inventory-source`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ source_code: sourceCode }),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
/**
* 提交库存字段映射。
* @param taskNo - 发货任务编号
@@ -160,6 +189,28 @@ export async function createWorkspaceShippingTaskFromNotice(file: File, conversa
return body;
}
/**
* 重新上传发货通知并覆盖当前任务。
* @param taskNo - 需要覆盖的发货任务编号
* @param file - 新的发货通知文件
* @returns 覆盖后的任务状态与后台编排结果
*/
export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: File) {
const form = new FormData();
form.append('file', file);
const headers = getAuthHeaders();
delete (headers as Record<string, string>)['Content-Type'];
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/replace-notice`,
{ method: 'POST', headers, body: form },
);
const body = (await res.json().catch(() => ({}))) as ShippingNoticeUploadResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
/**
* 批量上传多份发货通知并创建批次。
* @param files - 发货通知附件列表
@@ -476,6 +527,27 @@ export async function markWorkspaceShippingManualUploaded(taskNo: string) {
return body;
}
/**
* 重试将发货 Excel 上传至货代系统。
* @param taskNo - 发货任务编号
* @returns RPA 上传触发或等待结果
*/
export async function retryWorkspaceShippingUpload(taskNo: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry-upload`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({}),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
/**
* 生成发货 Excel。
* @param taskNo - 发货任务编号
@@ -504,6 +576,9 @@ export type {
ShippingBatchSummary,
ShippingChatAction,
ShippingChatActionsResponse,
ShippingConversationBatch,
ShippingConversationWorkspace,
ShippingConversationWorkspaceSummary,
ShippingCurrentStepProgress,
ShippingDecisionResponse,
ShippingInventoryUploadResponse,
@@ -40,8 +40,11 @@ const props = defineProps<{
canSendMessage: boolean;
isShippingNoticeAgent: boolean;
shippingSuggestedPrompt: string;
shippingFocusTaskNo?: string;
shippingFocusReason?: string;
/** 用对象包裹 Ref,避免 template 自动解包 */
shippingPickerRefHolder: { pickerRef: Ref<HTMLInputElement | null> };
shippingNoticePickerRefHolder: { pickerRef: Ref<HTMLInputElement | null> };
getKbLabel: (kb: string) => string;
}>();
@@ -53,6 +56,7 @@ const emit = defineEmits<{
'add-remote-url': [url: string];
'shipping-inventory-selected': [event: Event];
'use-shipping-suggested-prompt': [];
'clear-shipping-focus': [];
}>();
const filePickerRef = ref<HTMLInputElement | null>(null);
@@ -118,6 +122,15 @@ const bindShippingPickerRef = (el: unknown) => {
props.shippingPickerRefHolder.pickerRef.value = (el as HTMLInputElement | null) ?? null;
};
const bindShippingNoticePickerRef = (el: unknown) => {
props.shippingNoticePickerRefHolder.pickerRef.value = (el as HTMLInputElement | null) ?? null;
};
const bindAttachmentPickerRef = (el: unknown) => {
filePickerRef.value = (el as HTMLInputElement | null) ?? null;
bindShippingNoticePickerRef(el);
};
const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
const target = event.target as Node | null;
if (!target) return;
@@ -164,11 +177,27 @@ watch(
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
<div class="relative mx-auto max-w-4xl">
<div class="flex flex-col rounded-2xl bg-surface p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
<div
v-if="isShippingNoticeAgent && shippingFocusTaskNo"
class="mb-2 flex items-center gap-2 rounded-xl bg-brand-500 px-3 py-2 text-xs font-medium text-white"
>
<span class="shrink-0">{{ $t('chat.shippingNoticeUi.currentFocus') }}</span>
<span class="rounded-md bg-white/15 px-2 py-0.5 font-mono">{{ shippingFocusTaskNo }}</span>
<span class="min-w-0 flex-1 truncate text-white/85">{{ shippingFocusReason || $t('chat.shippingNoticeUi.currentFocusDefaultReason') }}</span>
<button
type="button"
class="rounded-full p-1 text-white/80 transition hover:bg-white/15 hover:text-white"
:title="$t('chat.shippingNoticeUi.clearFocus')"
@click="emit('clear-shipping-focus')"
>
<X class="h-3.5 w-3.5" />
</button>
</div>
<textarea
ref="textareaRef"
v-model="inputValue"
rows="1"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : shippingFocusTaskNo ? $t('chat.shippingNoticeUi.focusInputPlaceholder', { taskId: shippingFocusTaskNo }) : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
style="min-height: 44px; max-height: 220px;"
:disabled="isVoiceTranscribing"
@@ -187,7 +216,7 @@ watch(
/>
<input
ref="filePickerRef"
:ref="bindAttachmentPickerRef"
type="file"
multiple
class="hidden"
@@ -38,6 +38,7 @@ const {
isMessageRunProgressLoading: (msg: ChatMessage) => boolean;
toolRunProgress: ToolRunProgress | null;
toolRunProgressTitle: string;
showScrollToBottom: boolean;
/** 供父级滚动逻辑绑定 main 元素 */
scrollContainerHolder: { el: Ref<HTMLElement | null> };
}>();
@@ -49,6 +50,7 @@ const emit = defineEmits<{
regenerate: [];
'open-feedback': [index: number];
'select-question': [question: string];
'scroll-to-bottom': [];
}>();
const bindScrollContainer = (node: unknown) => {
@@ -114,5 +116,15 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
<ChatThinkingBubble v-if="showThinkingBubble" />
<div v-if="messages.length > 0" class="h-2 md:h-3" />
</div>
<button
v-if="showScrollToBottom"
type="button"
class="sticky bottom-4 left-1/2 z-30 flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full border border-slate-100 bg-white text-[28px] font-light leading-none text-slate-500 shadow-[0_10px_28px_rgba(15,23,42,0.16)] transition hover:-translate-y-0.5 hover:border-slate-200 hover:text-slate-700 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300 dark:shadow-black/30 md:bottom-6"
:title="$t('chat.scrollToLatest')"
@click="emit('scroll-to-bottom')"
>
<span aria-hidden="true" class="-mt-1">↓</span>
</button>
</main>
</template>
@@ -1,7 +1,7 @@
/**
* features/chat/components/ChatViewContent.vue
* 用途:对话页主区域,组合侧栏、发货批次进度区、消息列表、输入栏与内置浏览器。
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingBatchProgressPanel、chat.context。
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingBatchProgressPanel、ShippingBatchWorkspaceDrawer、chat.context。
* 逻辑:本文件只做页面结构编排;发货批次进度样式与任务续办交互下沉到独立面板组件。
*/
<script setup lang="ts">
@@ -13,6 +13,7 @@ import ChatMessageList from '@/features/chat/components/ChatMessageList.vue';
import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.vue';
import ShippingBatchWorkspaceDrawer from '@/features/chat/components/ShippingBatchWorkspaceDrawer.vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
const page = useChatPageContext();
@@ -87,14 +88,14 @@ const page = useChatPageContext();
<div class="flex min-h-0 flex-1 flex-col">
<ShippingBatchProgressPanel
v-if="page.isShippingNoticeAgent && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
:conversation-workspace="page.shippingConversationWorkspace"
:active-batch-no="page.activeShippingBatchNo"
:batch-summary="page.shippingBatchSummary"
:batch-tasks="page.shippingBatchTasks"
:active-task-detail="page.activeShippingTaskDetail"
:tasks-expanded="page.shippingBatchTasksExpanded"
:inventory-selection-active="page.shippingInventorySelectionActive && page.shippingBatchTasks?.length > 1"
@update:tasks-expanded="page.shippingBatchTasksExpanded = $event"
@focus-task="page.switchShippingFocusTask"
@resume-task="page.resumeShippingTask"
:workspace-open="page.shippingWorkspaceOpen"
@switch-batch="page.switchShippingBatch"
@toggle-workspace="page.shippingWorkspaceOpen = !page.shippingWorkspaceOpen"
/>
<ChatMessageList
@@ -118,6 +119,7 @@ const page = useChatPageContext();
:is-message-run-progress-loading="page.isMessageRunProgressLoading"
:tool-run-progress="page.toolRunProgress"
:tool-run-progress-title="page.toolRunProgressTitle"
:show-scroll-to-bottom="page.showScrollToBottom"
:scroll-container-holder="page.scrollContainerHolder"
@copy="page.copyToClipboard($event.message, $event.index)"
@edit="page.input = $event"
@@ -125,6 +127,7 @@ const page = useChatPageContext();
@regenerate="page.regenerate"
@open-feedback="page.handleOpenFeedback($event)"
@select-question="page.handleSend"
@scroll-to-bottom="page.scrollToBottom"
/>
<ChatInputBar
@@ -142,7 +145,10 @@ const page = useChatPageContext();
:can-send-message="page.canSendMessage"
:is-shipping-notice-agent="page.isShippingNoticeAgent"
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
:shipping-focus-task-no="page.focusedShippingTaskNo"
:shipping-focus-reason="page.shippingFocusReason"
:shipping-picker-ref-holder="page.shippingPickerRefHolder"
:shipping-notice-picker-ref-holder="page.shippingNoticePickerRefHolder"
:get-kb-label="page.getKbLabel"
@send="page.handleSend()"
@voice-click="page.handleVoiceFeatureClick"
@@ -151,6 +157,7 @@ const page = useChatPageContext();
@add-remote-url="page.addRemoteUrlAttachment"
@shipping-inventory-selected="page.handleShippingInventorySelected"
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
@clear-shipping-focus="page.clearShippingFocus"
/>
</div>
@@ -168,6 +175,23 @@ const page = useChatPageContext();
@start-resize="page.browser.startResize"
@close="page.browser.close"
/>
<ShippingBatchWorkspaceDrawer
v-if="page.isShippingNoticeAgent && (page.shippingConversationWorkspace || page.shippingBatchSummary)"
v-model:open="page.shippingWorkspaceOpen"
:conversation-workspace="page.shippingConversationWorkspace"
:active-batch-no="page.activeShippingBatchNo"
:focused-task-no="page.focusedShippingTaskNo"
:batch-summary="page.shippingBatchSummary"
:batch-tasks="page.shippingBatchTasks"
:active-task-detail="page.activeShippingTaskDetail"
:retrying-pending="page.retryingShippingPendingTasks"
@switch-batch="page.switchShippingBatch"
@focus-task="page.switchShippingFocusTask"
@resume-task="page.resumeShippingTask"
@query-shortage="page.queryShippingShortageDetails"
@retry-pending="page.retryCurrentShippingBatchPendingTasks"
/>
</div>
</template>
</ChatShell>
@@ -1,43 +1,45 @@
<script setup lang="ts">
/**
* features/chat/components/ShippingBatchProgressPanel.vue
* 用途:发货通知聊天顶部批次进度卡片,按原型方案 C 展示批次概览、任务切换列表、七步进度与续办弹层。
* 依赖:shippingStepper、shipping.api.types、vue-i18n、lucide-vue-next。
* 逻辑:上游由 ChatViewContent 传入批次/任务状态;本组件只负责展示与抛出 focus/resume 事件,不直接请求后端。
* 用途:发货通知聊天顶部轻量批次状态条,展示当前批次进度与工作台入口。
* 依赖:shipping.api.types、vue-i18n、批次 retry API。
* 逻辑:生成式执行摘要由聊天消息流承载;本组件只提供固定状态 chrome 和明确范围的批次操作。
*/
import { computed, ref } from 'vue';
import { List, PlayCircle, X } from 'lucide-vue-next';
import { List, RefreshCw } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { buildShippingWorkflowSteps, type ShippingWorkflowStepItem } from '@/features/chat/shipping';
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
import { useMessage } from '@/shared/composables/useMessage';
import type {
ShippingBatchSummary,
ShippingConversationWorkspace,
ShippingTaskDetail,
ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
const props = defineProps<{
conversationWorkspace: ShippingConversationWorkspace | null;
activeBatchNo: string;
batchSummary: ShippingBatchSummary | null;
batchTasks: ShippingTaskSummary[];
activeTaskDetail: ShippingTaskDetail | null;
tasksExpanded: boolean;
inventorySelectionActive: boolean;
workspaceOpen: boolean;
}>();
const emit = defineEmits<{
'update:tasksExpanded': [value: boolean];
'focus-task': [taskNo: string];
'resume-task': [taskNo: string];
'switch-batch': [batchNo: string];
'toggle-workspace': [];
}>();
const { t } = useI18n();
const msg = useMessage();
const showTaskDialog = ref(false);
const retryingPending = ref(false);
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
const CIRCLED_NUMBERS = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨'];
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
const activeBatchNo = computed(() =>
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
);
const processSummary = computed(() => {
const summary = props.batchSummary?.process_summary || null;
@@ -55,121 +57,36 @@ const processSummary = computed(() => {
return { total, completed, running, pending };
});
const currentTask = computed<ShippingTaskSummary | ShippingTaskDetail | null>(() => {
const focusTaskNo = String(props.batchSummary?.current_focus_task_no || '').trim().toUpperCase();
if (focusTaskNo) {
return props.batchTasks.find((task) => String(task.task_no || '').trim().toUpperCase() === focusTaskNo)
|| props.activeTaskDetail
|| null;
}
return props.activeTaskDetail || props.batchTasks[0] || null;
const abnormalCount = computed(() => {
const batchSummary = props.batchSummary?.process_summary || {};
return Number(batchSummary.failed || 0) + Number((batchSummary as { needs_human?: number }).needs_human || 0);
});
const currentTaskNo = computed(() => String(currentTask.value?.task_no || '').trim().toUpperCase());
const currentTaskName = computed(() =>
String(
currentTask.value?.source_file_name
|| currentTask.value?.customer_name
|| t('chat.shippingNoticeUi.currentNotice'),
).trim(),
const progressPercent = computed(() =>
processSummary.value.total
? Math.round((processSummary.value.completed / processSummary.value.total) * 100)
: 0,
);
const currentTaskIndex = computed(() =>
Number(
currentTask.value?.batch_index
|| props.batchSummary?.process_summary?.current_index
|| 0,
),
);
const currentTaskTotal = computed(() =>
Number(
currentTask.value?.batch_total
|| props.batchSummary?.file_count
|| processSummary.value.total
|| 0,
),
);
const currentSteps = computed(() => buildShippingWorkflowSteps(currentTask.value));
const resolveActiveStep = (steps: ShippingWorkflowStepItem[]) =>
steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
const currentStepMeta = computed(() => {
const steps = currentSteps.value;
if (!steps.length) return { index: 0, label: t('chat.shippingNoticeUi.processing') };
const activeIndex = resolveActiveStep(steps);
const safeIndex = activeIndex >= 0 ? activeIndex : steps.length - 1;
const executionStateMeta = computed(() => {
if (abnormalCount.value > 0) {
return {
text: t('chat.shippingNoticeUi.needsIntervention'),
className: 'border-amber-100 bg-amber-50 text-amber-700',
};
}
if (processSummary.value.running > 0 || processSummary.value.pending > 0) {
return {
text: t('chat.shippingNoticeUi.runningState'),
className: 'border-sky-100 bg-sky-50 text-brand-700',
};
}
return {
index: safeIndex + 1,
label: t(steps[safeIndex]?.label || 'chat.shippingNoticeUi.processing'),
text: t('chat.shippingNoticeUi.completedState'),
className: 'border-emerald-100 bg-emerald-50 text-emerald-700',
};
});
const summaryLine = computed(() => t('chat.shippingNoticeUi.batchSummaryLine', {
total: processSummary.value.total,
completed: processSummary.value.completed,
running: processSummary.value.running,
pending: processSummary.value.pending,
}));
/**
* 将任务状态映射为原型中列表右侧的紧凑状态文案。
*
* 核心逻辑:完成态显示“已完成”,阻塞态显示“步骤 X 待确认”,运行态显示“步骤 X/Y”,
* 其余回退到“排队中”,以匹配原型中批次队列的短标签风格。
* @param task - 任务摘要或详情
* @returns 原型列表使用的短文案与颜色类
*/
const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail | null) => {
if (!task) {
return { text: t('chat.shippingNoticeUi.queuedState'), tone: 'text-muted' };
}
if (COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())) {
return { text: t('chat.shippingNoticeUi.completedState'), tone: 'text-emerald-700' };
}
const steps = buildShippingWorkflowSteps(task);
const blockedIndex = steps.findIndex((step) => step.status === 'blocked');
if (blockedIndex >= 0) {
return {
text: t('chat.shippingNoticeUi.stepNeedsConfirm', { step: blockedIndex + 1 }),
tone: 'text-amber-700',
};
}
const activeIndex = resolveActiveStep(steps);
if (activeIndex >= 0) {
return {
text: t('chat.shippingNoticeUi.stepFraction', { current: activeIndex + 1, total: steps.length }),
tone: 'text-brand-600',
};
}
return { text: t('chat.shippingNoticeUi.queuedState'), tone: 'text-muted' };
};
const shortTaskNo = (taskNo?: string | null) => {
const value = String(taskNo || '').trim();
if (value.length <= 10) return value || '--';
return `${value.slice(0, 5)}...${value.slice(-3)}`;
};
const isCurrentTask = (taskNo?: string | null) =>
String(taskNo || '').trim().toUpperCase() === currentTaskNo.value;
const openTaskDialog = () => {
if (!props.batchTasks.length) return;
showTaskDialog.value = true;
};
const handleFocusTask = (taskNo: string) => {
emit('focus-task', taskNo);
};
const handleResumeTask = (taskNo: string) => {
showTaskDialog.value = false;
emit('resume-task', taskNo);
};
const handleRetryPending = async () => {
const batchNo = String(props.batchSummary?.batch_no || '').trim();
if (!batchNo || retryingPending.value) return;
@@ -186,15 +103,37 @@ const handleRetryPending = async () => {
</script>
<template>
<section
class="mx-auto mt-4 w-full max-w-4xl overflow-hidden rounded-2xl border border-sky-100 bg-gradient-to-br from-sky-50 via-white to-emerald-50 shadow-sm"
>
<div class="border-b border-sky-100/80 px-4 py-3">
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="text-xs text-slate-500">
{{ summaryLine }}
<section class="w-full px-3 pt-3 md:px-8 md:pr-10">
<div
class="mx-auto w-full max-w-4xl rounded-2xl border border-default bg-gradient-to-r from-sky-50 via-white to-emerald-50 px-6 py-4 shadow-sm"
>
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-2 text-xs text-slate-500">
<span class="font-mono font-semibold text-brand-700">{{ activeBatchNo || '--' }}</span>
<span>
{{ t('chat.shippingNoticeUi.batchChromeSummary', {
total: processSummary.total,
completed: processSummary.completed,
running: processSummary.running,
abnormal: abnormalCount,
}) }}
</span>
<span
class="rounded-full border px-2 py-0.5 text-[11px] font-semibold"
:class="executionStateMeta.className"
>
{{ executionStateMeta.text }}
</span>
</div>
<div class="mt-2 h-1.5 max-w-md overflow-hidden rounded-full bg-slate-200">
<div
class="h-full rounded-full bg-brand-500 transition-all"
:style="{ width: `${progressPercent}%` }"
></div>
</div>
</div>
<div class="flex items-center gap-2">
<div class="flex shrink-0 items-center gap-2">
<button
v-if="batchSummary?.batch_no"
type="button"
@@ -202,242 +141,20 @@ const handleRetryPending = async () => {
:disabled="retryingPending"
@click="handleRetryPending"
>
<RefreshCw class="h-3.5 w-3.5" :class="retryingPending ? 'animate-spin' : ''" />
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryPendingTasks') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700"
@click="openTaskDialog"
@click="emit('toggle-workspace')"
>
<List class="h-3.5 w-3.5" />
{{ t('chat.shippingNoticeUi.taskListResume') }}
</button>
<button
v-if="batchTasks.length > 1"
type="button"
class="text-xs font-medium text-brand-600 transition hover:text-brand-700"
@click="emit('update:tasksExpanded', !tasksExpanded)"
>
{{ tasksExpanded ? `${t('chat.shippingNoticeUi.collapseTaskList')} ▲` : `${t('chat.shippingNoticeUi.expandTaskList')} ▼` }}
{{ workspaceOpen ? t('chat.shippingNoticeUi.collapseTaskList') : t('chat.shippingNoticeUi.expandTaskList') }}
<span class="text-brand-600">{{ workspaceOpen ? '▲' : '▼' }}</span>
</button>
</div>
</div>
<div
v-if="tasksExpanded && batchTasks.length"
class="mt-2 space-y-1 border-t border-dashed border-sky-100 pt-2"
>
<button
v-for="(task, index) in batchTasks"
:key="task.task_no"
type="button"
class="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-xs transition hover:bg-white/70"
:class="isCurrentTask(task.task_no) ? 'bg-white/80 ring-1 ring-brand-200' : ''"
@click="handleFocusTask(task.task_no)"
>
<span class="text-muted">{{ CIRCLED_NUMBERS[index] || `${index + 1}` }}</span>
<span class="flex-1 truncate" :class="isCurrentTask(task.task_no) ? 'font-medium text-secondary' : ''">
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
</span>
<span class="font-mono text-brand-600">{{ shortTaskNo(task.task_no) }}</span>
<span
class="rounded-full px-1.5 py-0.5"
:class="isCurrentTask(task.task_no) ? 'text-brand-600' : resolveTaskStateMeta(task).tone"
>
{{ resolveTaskStateMeta(task).text }}
</span>
</button>
</div>
</div>
<div class="space-y-3 px-4 py-4">
<div class="flex flex-wrap items-baseline justify-between gap-2">
<div>
<div class="font-mono text-sm font-semibold text-brand-700">
{{ currentTaskNo || batchSummary?.batch_no || '--' }}
</div>
<div class="mt-0.5 text-xs text-muted">
当前 · 第 {{ currentTaskIndex || 0 }}/{{ currentTaskTotal || 0 }} 笔 ·
<em class="not-italic text-secondary">{{ currentTaskName }}</em>
</div>
</div>
<div class="text-xs text-muted">
步骤 <strong class="text-secondary">{{ currentStepMeta.index }}</strong>/{{ currentSteps.length || 7 }} · {{ currentStepMeta.label }}
</div>
</div>
<div class="scheme-stepper">
<template v-for="(step, index) in currentSteps" :key="step.id">
<div
class="scheme-step-node"
:class="{
done: step.status === 'completed',
active: step.status === 'current' || step.status === 'blocked',
}"
>
<div class="scheme-step-dot">
{{ step.status === 'completed' ? '✓' : index + 1 }}
</div>
<div class="scheme-step-label">{{ t(step.label) }}</div>
</div>
</template>
</div>
<div
v-if="inventorySelectionActive"
class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800"
>
{{ t('chat.shippingNoticeUi.inventoryTaskPickHint') }}
</div>
</div>
<Teleport to="body">
<div
v-if="showTaskDialog"
class="fixed inset-0 z-[120] flex items-center justify-center bg-slate-900/30 px-4"
@click.self="showTaskDialog = false"
>
<div class="w-full max-w-[620px] rounded-[28px] bg-white p-5 shadow-[0_24px_80px_rgba(15,23,42,0.22)]">
<div class="flex items-start justify-between gap-4">
<div>
<div class="text-[32px] font-semibold tracking-tight text-slate-800">
{{ t('chat.shippingNoticeUi.taskListTitle') }}
</div>
<div class="mt-1 text-sm text-slate-500">
{{ t('chat.shippingNoticeUi.taskListHint') }}
</div>
</div>
<button
type="button"
class="rounded-full p-2 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"
@click="showTaskDialog = false"
>
<X class="h-5 w-5" />
</button>
</div>
<div class="mt-5 space-y-3">
<button
v-for="task in batchTasks"
:key="task.task_no"
type="button"
class="w-full rounded-3xl border px-4 py-4 text-left transition hover:border-[#8bc8f5] hover:bg-[#f8fbff]"
:class="isCurrentTask(task.task_no) ? 'border-[#8bc8f5] bg-[#f5fbff]' : 'border-[#e5edf5] bg-white'"
@click="handleResumeTask(task.task_no)"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-mono text-lg font-semibold text-[#1277c8]">
{{ task.task_no }}
</div>
<div class="mt-1 truncate text-[15px] text-slate-700">
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
</div>
<div class="mt-1 text-sm text-slate-500">
{{ resolveTaskStateMeta(task).text }}
</div>
<div
v-if="isCurrentTask(task.task_no)"
class="mt-2 inline-flex items-center gap-1 text-sm font-medium text-[#1277c8]"
>
{{ t('chat.shippingNoticeUi.currentFocus') }}
</div>
</div>
<div class="flex shrink-0 items-center gap-2">
<span
class="rounded-full px-3 py-1 text-sm font-medium"
:class="COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())
? 'bg-emerald-100 text-emerald-700'
: isCurrentTask(task.task_no)
? 'bg-sky-100 text-sky-700'
: 'bg-amber-100 text-amber-700'"
>
{{ COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())
? t('chat.shippingNoticeUi.completedState')
: isCurrentTask(task.task_no)
? t('chat.shippingNoticeUi.runningState')
: t('chat.shippingNoticeUi.pendingState') }}
</span>
<PlayCircle class="h-5 w-5 text-[#1492df]" />
</div>
</div>
</button>
</div>
</div>
</div>
</Teleport>
</section>
</template>
<style scoped>
.scheme-stepper {
display: flex;
overflow-x: auto;
padding-bottom: 0.25rem;
}
.scheme-step-node {
position: relative;
flex: 1;
min-width: 52px;
text-align: center;
}
.scheme-step-node:not(:last-child)::after {
content: '';
position: absolute;
top: 10px;
left: calc(50% + 11px);
width: calc(100% - 22px);
height: 2px;
background: #e2e8f0;
z-index: 0;
}
.scheme-step-node.done:not(:last-child)::after {
background: #0284c7;
}
.scheme-step-node.active:not(:last-child)::after {
background: linear-gradient(90deg, #0284c7 50%, #e2e8f0 50%);
}
.scheme-step-dot {
position: relative;
z-index: 1;
display: grid;
place-items: center;
width: 20px;
height: 20px;
margin: 0 auto 0.25rem;
border: 2px solid #e2e8f0;
border-radius: 9999px;
background: #fff;
color: #64748b;
font-size: 0.55rem;
font-weight: 700;
}
.scheme-step-node.done .scheme-step-dot {
border-color: #0284c7;
background: #0284c7;
color: #fff;
}
.scheme-step-node.active .scheme-step-dot {
border-color: #0284c7;
box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.18);
color: #0284c7;
}
.scheme-step-label {
color: #64748b;
font-size: 0.58rem;
line-height: 1.2;
}
.scheme-step-node.active .scheme-step-label {
color: #0284c7;
font-weight: 600;
}
</style>
@@ -0,0 +1,509 @@
<script setup lang="ts">
/**
* features/chat/components/ShippingBatchWorkspaceDrawer.vue
* 用途:发货通知 Agent 的右侧批次工作台抽屉,承载多批次切换、任务筛选、步骤诊断与恢复动作。
* 依赖:shippingStepper、shipping.api.types、vue-i18n、lucide-vue-next。
* 逻辑:上游传入会话级 workspace 与当前批次任务;本组件只做展示、筛选和事件抛出,执行动作仍由 useChatShipping 接管。
*/
import { computed, ref } from 'vue';
import { RefreshCw, Target, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { buildShippingWorkflowSteps, type ShippingWorkflowStepItem } from '@/features/chat/shipping';
import { hasShortageLines } from '@/features/chat/shipping/shippingShortageDetails';
import type {
ShippingBatchSummary,
ShippingConversationWorkspace,
ShippingTaskDetail,
ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
const props = defineProps<{
open: boolean;
conversationWorkspace: ShippingConversationWorkspace | null;
activeBatchNo: string;
focusedTaskNo: string;
batchSummary: ShippingBatchSummary | null;
batchTasks: ShippingTaskSummary[];
activeTaskDetail: ShippingTaskDetail | null;
retryingPending?: boolean;
}>();
const emit = defineEmits<{
'update:open': [value: boolean];
'switch-batch': [batchNo: string];
'focus-task': [taskNo: string];
'resume-task': [taskNo: string];
'query-shortage': [taskNo: string];
'retry-pending': [];
}>();
const { t } = useI18n();
const activeFilter = ref<'all' | 'abnormal' | 'completed'>('all');
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'completed', 'closed']);
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
const activeBatchNo = computed(() =>
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
);
const isFailedTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
task.upload_status === 'failed' || String(task.process_status || '').trim() === 'upload_failed';
const isCompletedTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim());
const isAbnormalTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
!isCompletedTask(task)
&& (isFailedTask(task)
|| Boolean(task.review_status || task.pending_human_reason)
|| String(task.process_status || '').trim() === 'waiting_inventory');
const batchAbnormalCount = (batch: ShippingBatchSummary) => {
const summary = batch.process_summary || {};
return Number(summary.failed || 0) + Number((summary as { needs_human?: number }).needs_human || 0);
};
const batchCompletedCount = (batch: ShippingBatchSummary) =>
Number(batch.process_summary?.completed || 0);
const batchTotalCount = (batch: ShippingBatchSummary) =>
Number(batch.process_summary?.total || batch.file_count || 0);
const taskCounts = computed(() => {
const tasks = props.batchTasks || [];
const completed = tasks.filter(isCompletedTask).length;
const abnormal = tasks.filter(isAbnormalTask).length;
return {
total: tasks.length,
abnormal,
completed,
};
});
const filteredTasks = computed(() => {
const tasks = props.batchTasks || [];
if (activeFilter.value === 'abnormal') return tasks.filter(isAbnormalTask);
if (activeFilter.value === 'completed') return tasks.filter(isCompletedTask);
return tasks;
});
const isCurrentTask = (taskNo?: string | null) =>
String(taskNo || '').trim().toUpperCase() === String(props.focusedTaskNo || props.activeTaskDetail?.task_no || '').trim().toUpperCase();
const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail) => {
if (isCompletedTask(task)) {
return { text: t('chat.shippingNoticeUi.completedState'), className: 'border-emerald-100 bg-emerald-50 text-emerald-700' };
}
if (isFailedTask(task)) {
return { text: t('chat.shippingNoticeUi.status.uploadFailed'), className: 'border-rose-100 bg-rose-50 text-rose-700' };
}
if (isAbnormalTask(task)) {
return { text: t('chat.shippingNoticeUi.pendingState'), className: 'border-amber-100 bg-amber-50 text-amber-700' };
}
return { text: t('chat.shippingNoticeUi.runningState'), className: 'border-sky-100 bg-sky-50 text-brand-700' };
};
const taskStepNumber = (task: ShippingTaskSummary | ShippingTaskDetail) =>
resolveActiveStep(buildShippingWorkflowSteps(task)) + 1;
const currentStepProgress = (task: ShippingTaskSummary | ShippingTaskDetail) =>
task.step_payload?.current_step_progress || null;
const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => {
const reason = String(task.pending_human_reason || '').trim();
const reviewStatus = String(task.review_status || '').trim();
const processStatus = String(task.process_status || '').trim();
const explicitError = String(task.error_message || '').trim();
const progress = currentStepProgress(task);
const progressMessage = String(progress?.message || '').trim();
const progressDetail = String(progress?.detail || '').trim();
const step = taskStepNumber(task);
if (isCompletedTask(task)) {
return {
title: t('chat.shippingNoticeUi.diagnosisCompletedTitle'),
advice: t('chat.shippingNoticeUi.diagnosisCompletedAdvice'),
};
}
if (progressMessage && reason === 'rpa_pending') {
return {
title: progressMessage,
advice: progressDetail || t('chat.shippingNoticeUi.diagnosisInventoryRpaAdvice'),
};
}
if (explicitError) {
return {
title: explicitError,
advice: progressDetail || t('chat.shippingNoticeUi.diagnosisAdviceRetryOrFocus'),
};
}
if (progressMessage && (isAbnormalTask(task) || progress?.status === 'needs_human')) {
return {
title: progressMessage,
advice: progressDetail || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
};
}
if (isFailedTask(task) || reason === 'upload_rpa_failed') {
return {
title: t('chat.shippingNoticeUi.diagnosisUploadFailedTitle'),
advice: t('chat.shippingNoticeUi.diagnosisUploadFailedAdvice'),
};
}
if (reason === 'shortage' || reason === 'shortage_review' || reviewStatus === 'shortage_review') {
return {
title: t('chat.shippingNoticeUi.diagnosisShortageTitle'),
advice: t('chat.shippingNoticeUi.diagnosisShortageAdvice'),
};
}
if (reason === 'rpa_exhausted' || reason === 'rpa_pending' || reason === 'inv_unavail') {
return {
title: t('chat.shippingNoticeUi.diagnosisInventoryRpaTitle'),
advice: t('chat.shippingNoticeUi.diagnosisInventoryRpaAdvice'),
};
}
if (reason === 'align_review' || reviewStatus === 'align_review') {
return {
title: t('chat.shippingNoticeUi.diagnosisAlignReviewTitle'),
advice: t('chat.shippingNoticeUi.diagnosisAlignReviewAdvice'),
};
}
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
return {
title: t('chat.shippingNoticeUi.diagnosisParseReviewTitle'),
advice: t('chat.shippingNoticeUi.diagnosisParseReviewAdvice'),
};
}
if (reason === 'rsv_required' || reviewStatus === 'rsv_required') {
return {
title: t('chat.shippingNoticeUi.diagnosisReservationRequiredTitle'),
advice: t('chat.shippingNoticeUi.diagnosisReservationRequiredAdvice'),
};
}
if (reason === 'map_infer' || processStatus === 'waiting_inventory') {
return {
title: t('chat.shippingNoticeUi.diagnosisInventoryWaitingTitle'),
advice: t('chat.shippingNoticeUi.diagnosisInventoryWaitingAdvice'),
};
}
return {
title: t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step }),
advice: t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
};
};
const resolveActiveStep = (steps: ShippingWorkflowStepItem[]) => {
const activeIndex = steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
return activeIndex >= 0 ? activeIndex : Math.max(0, steps.length - 1);
};
const handleSwitchBatch = (batchNo: string) => {
if (!batchNo || batchNo === activeBatchNo.value) return;
activeFilter.value = 'all';
emit('switch-batch', batchNo);
};
</script>
<template>
<aside
v-if="open"
class="hidden h-full w-[520px] shrink-0 flex-col border-l border-default bg-surface shadow-[-12px_0_40px_rgba(15,23,42,0.08)] xl:flex"
>
<header class="flex h-[92px] shrink-0 items-center justify-between border-b border-default px-6">
<div>
<div class="flex items-center gap-2 text-lg font-bold text-primary">
<span class="grid h-5 w-5 grid-cols-2 gap-0.5 text-brand-500">
<span class="rounded-sm bg-current"></span>
<span class="rounded-sm border border-current"></span>
<span class="rounded-sm border border-current"></span>
<span class="rounded-sm bg-current"></span>
</span>
{{ t('chat.shippingNoticeUi.batchWorkspaceTitle') }}
</div>
<p class="mt-1 text-[11px] text-muted">{{ t('chat.shippingNoticeUi.batchWorkspaceSubtitle') }}</p>
</div>
<button
type="button"
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition hover:bg-surface-soft hover:text-primary"
@click="emit('update:open', false)"
>
<X class="h-5 w-5" />
</button>
</header>
<div class="border-b border-default px-6 py-5">
<div class="flex gap-3 overflow-x-auto pb-1">
<button
v-for="batch in workspaceBatches"
:key="batch.batch_no"
type="button"
class="relative w-44 shrink-0 overflow-hidden rounded-xl border p-3 text-left transition-colors"
:class="batch.batch_no === activeBatchNo ? 'border-brand-300 bg-surface shadow-sm ring-1 ring-brand-100' : 'border-default bg-transparent hover:bg-surface-soft'"
@click="handleSwitchBatch(batch.batch_no)"
>
<div
v-if="batch.batch_no === activeBatchNo"
class="absolute left-0 top-0 h-1 w-full bg-brand-500"
></div>
<div class="mb-1 truncate font-mono text-xs font-bold text-primary">{{ batch.batch_no }}</div>
<div class="text-[10px] font-medium text-muted">
{{
batchAbnormalCount(batch) > 0
? t('chat.shippingNoticeUi.batchTabAbnormal', { completed: batchCompletedCount(batch), abnormal: batchAbnormalCount(batch) })
: t('chat.shippingNoticeUi.batchTabNormal', { total: batchTotalCount(batch) })
}}
</div>
</button>
</div>
</div>
<div class="flex-1 overflow-y-auto px-6 py-6">
<section class="rounded-2xl border border-default bg-surface p-4 shadow-sm">
<h3 class="text-sm font-bold text-primary">{{ t('chat.shippingNoticeUi.batchActionsTitle') }}</h3>
<div class="mt-4">
<button
type="button"
class="inline-flex w-full items-center justify-center gap-2 rounded-lg border border-default bg-white py-2 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="retryingPending"
@click="emit('retry-pending')"
>
<RefreshCw class="h-3.5 w-3.5" :class="retryingPending ? 'animate-spin' : ''" />
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryFailedTasks') }}
</button>
</div>
<div class="mt-3 rounded-lg border border-indigo-100 bg-indigo-50 p-3 text-xs leading-5 text-indigo-900/80">
{{ t('chat.shippingNoticeUi.batchActionSafetyNotice') }}
</div>
</section>
<section class="mt-6">
<div class="mb-3 flex items-center justify-between gap-3">
<h3 class="text-sm font-bold text-primary">
{{ t('chat.shippingNoticeUi.taskDetailCount', { count: filteredTasks.length }) }}
</h3>
<div class="flex rounded-lg bg-slate-100 p-1 text-xs">
<button
type="button"
class="rounded px-3 py-1 transition-colors"
:class="activeFilter === 'all' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
@click="activeFilter = 'all'"
>
{{ t('chat.shippingNoticeUi.filterAll') }}
</button>
<button
type="button"
class="rounded px-3 py-1 transition-colors"
:class="activeFilter === 'abnormal' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
@click="activeFilter = 'abnormal'"
>
{{ t('chat.shippingNoticeUi.filterAbnormal', { count: taskCounts.abnormal }) }}
</button>
<button
type="button"
class="rounded px-3 py-1 transition-colors"
:class="activeFilter === 'completed' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
@click="activeFilter = 'completed'"
>
{{ t('chat.shippingNoticeUi.filterCompleted', { count: taskCounts.completed }) }}
</button>
</div>
</div>
<div v-if="!filteredTasks.length" class="py-10 text-center text-sm text-muted">
{{ t('chat.shippingNoticeUi.emptyFilteredTasks') }}
</div>
<div v-else class="space-y-4">
<article
v-for="task in filteredTasks"
:key="task.task_no"
class="relative overflow-hidden rounded-2xl border bg-white p-4 shadow-sm transition-colors"
:class="[
isFailedTask(task) ? 'border-rose-100' : isAbnormalTask(task) ? 'border-amber-100' : 'border-default',
isCurrentTask(task.task_no) ? 'ring-1 ring-brand-200' : '',
]"
>
<div
class="absolute left-0 top-0 h-full w-1"
:class="isFailedTask(task) ? 'bg-rose-500' : isAbnormalTask(task) ? 'bg-amber-500' : 'bg-emerald-500'"
></div>
<div class="mb-4 flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="truncate font-mono text-sm font-bold text-primary">{{ task.task_no }}</div>
<div class="mt-0.5 truncate text-xs text-muted">
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
</div>
</div>
<span class="rounded border px-2 py-1 text-[10px] font-bold" :class="resolveTaskStateMeta(task).className">
{{ resolveTaskStateMeta(task).text }}
</span>
</div>
<div class="mb-5 mt-4">
<div class="scheme-stepper">
<template v-for="(step, index) in buildShippingWorkflowSteps(task)" :key="step.id">
<div
class="scheme-step-node"
:class="{
done: step.status === 'completed',
active: step.status === 'current',
blocked: step.status === 'blocked',
}"
>
<div class="scheme-step-dot">
<span v-if="step.status === 'completed'">✓</span>
<X v-else-if="step.status === 'blocked' && isFailedTask(task)" class="h-3 w-3" />
<span v-else-if="step.status === 'blocked'">!</span>
<span v-else>{{ index + 1 }}</span>
</div>
<div class="scheme-step-label">{{ t(step.label) }}</div>
</div>
</template>
</div>
</div>
<div
class="mb-3 rounded-lg border p-2.5 text-xs font-medium leading-5"
:class="isFailedTask(task) ? 'border-rose-100 bg-rose-50 text-rose-700' : isAbnormalTask(task) ? 'border-amber-100 bg-amber-50 text-amber-700' : 'border-emerald-100 bg-emerald-50 text-emerald-700'"
>
<div class="font-semibold">{{ resolveTaskDiagnosis(task).title }}</div>
<div class="mt-1 font-normal text-slate-600">{{ resolveTaskDiagnosis(task).advice }}</div>
</div>
<div class="flex gap-2">
<button
v-if="hasShortageLines(task)"
type="button"
class="flex flex-1 items-center justify-center gap-1.5 rounded-lg border border-amber-100 bg-amber-50 py-1.5 text-xs font-medium text-amber-700 transition-colors hover:bg-amber-100"
@click="emit('query-shortage', task.task_no)"
>
{{ t('chat.shippingNoticeUi.queryShortageDetails') }}
</button>
<button
type="button"
class="flex flex-1 items-center justify-center gap-1.5 rounded-lg border border-transparent bg-surface-soft py-1.5 text-xs font-medium text-secondary transition-colors hover:border-brand-200 hover:bg-brand-50 hover:text-brand-600"
@click="emit('focus-task', task.task_no)"
>
<Target class="h-3.5 w-3.5" />
{{ t('chat.shippingNoticeUi.focusRepair') }}
</button>
<button
type="button"
class="flex-1 rounded-lg border border-default bg-white py-1.5 text-xs font-medium text-secondary transition-colors hover:border-brand-300 hover:text-brand-700"
@click="emit('resume-task', task.task_no)"
>
{{ isCompletedTask(task) ? t('chat.shippingNoticeUi.viewDetail') : t('chat.shippingNoticeUi.retrySingleTask') }}
</button>
</div>
</article>
</div>
</section>
</div>
</aside>
<div
v-if="open"
class="fixed inset-0 z-[90] bg-slate-900/30 backdrop-blur-sm xl:hidden"
@click="emit('update:open', false)"
>
<aside
class="ml-auto flex h-full w-[min(92vw,520px)] flex-col border-l border-default bg-surface shadow-2xl"
@click.stop
>
<header class="flex h-16 shrink-0 items-center justify-between border-b border-default px-4">
<div class="font-bold text-primary">{{ t('chat.shippingNoticeUi.batchWorkspaceTitle') }}</div>
<button type="button" class="rounded-full p-2 text-muted hover:bg-surface-soft" @click="emit('update:open', false)">
<X class="h-5 w-5" />
</button>
</header>
<div class="flex-1 overflow-y-auto p-4 text-sm text-muted">
{{ t('chat.shippingNoticeUi.mobileWorkspaceHint') }}
</div>
</aside>
</div>
</template>
<style scoped>
.scheme-stepper {
display: flex;
overflow-x: auto;
padding-bottom: 0.25rem;
}
.scheme-step-node {
position: relative;
flex: 1;
min-width: 52px;
text-align: center;
}
.scheme-step-node:not(:last-child)::after {
content: '';
position: absolute;
top: 10px;
left: calc(50% + 11px);
width: calc(100% - 22px);
height: 2px;
background: #e2e8f0;
z-index: 0;
}
.scheme-step-node.done:not(:last-child)::after {
background: #0284c7;
}
.scheme-step-node.active:not(:last-child)::after {
background: linear-gradient(90deg, #0284c7 50%, #e2e8f0 50%);
}
.scheme-step-dot {
position: relative;
z-index: 1;
display: grid;
place-items: center;
width: 20px;
height: 20px;
margin: 0 auto 0.25rem;
border: 2px solid #e2e8f0;
border-radius: 9999px;
background: #fff;
color: #64748b;
font-size: 0.55rem;
font-weight: 700;
}
.scheme-step-node.done .scheme-step-dot {
border-color: #0284c7;
background: #0284c7;
color: #fff;
}
.scheme-step-node.active .scheme-step-dot {
border-color: #0284c7;
box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.18);
color: #0284c7;
}
.scheme-step-node.blocked .scheme-step-dot {
border-color: #f59e0b;
background: #fff;
color: #f59e0b;
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.18);
}
.scheme-step-node.blocked .scheme-step-label {
color: #d97706;
font-weight: 600;
}
.scheme-step-label {
color: #64748b;
font-size: 0.58rem;
line-height: 1.2;
}
.scheme-step-node.active .scheme-step-label {
color: #0284c7;
font-weight: 600;
}
</style>
@@ -8,6 +8,10 @@ import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
export interface SendMessageLifecycleHooks {
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
}
const normalizeResources = (resources: unknown) => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
@@ -283,8 +287,10 @@ export function useChat() {
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
>,
context?: { task_id?: string; batch_no?: string },
context?: { task_id?: string; batch_no?: string; display_query?: string },
hooks?: SendMessageLifecycleHooks,
) => {
const displayQuery = String(context?.display_query || query || '').trim();
clearLikelyCompletedStreamTimer();
cancelActiveStream();
const controller = new AbortController();
@@ -295,7 +301,7 @@ export function useChat() {
runId: ++runSeq,
agentId,
viewId: runViewId,
query,
query: displayQuery,
messages: runMessages,
conversationId: conversationId.value,
status: 'running',
@@ -305,7 +311,7 @@ export function useChat() {
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
activeRunId.value = run.runId;
runMessages.push({ role: 'user', content: query });
runMessages.push({ role: 'user', content: displayQuery });
let botMsgIndex: number | null = null;
let hasAssistantContent = false;
let hasTerminalEvent = false;
@@ -337,6 +343,7 @@ export function useChat() {
files: files && files.length > 0 ? files : undefined,
task_id: context?.task_id || undefined,
batch_no: context?.batch_no || undefined,
display_query: context?.display_query || undefined,
}),
});
@@ -499,6 +506,12 @@ export function useChat() {
if (messages.value === runMessages) {
isThinking.value = false;
}
if (run.status === 'done' && botMsgIndex !== null) {
const botMsg = runMessages[botMsgIndex];
if (botMsg) {
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
}
}
}
};
@@ -323,6 +323,7 @@ export function useChatPage() {
clearAttachments: attachmentApi.clearAttachments,
sendMessage,
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
onAssistantMessageFinished: shipping.finalizeShippingAssistantMessage,
refreshHistoryAfterSend,
refreshConversationAfterSend: async () => {
const currentConversationId = conversationId.value;
@@ -361,6 +362,7 @@ export function useChatPage() {
const leaveMessageHandlers = createLeaveMessageHandlers(leave);
const shippingMappingHandlers = createShippingMappingHandlers(shipping);
const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef));
const shippingNoticePickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingNoticePickerRef));
const showChatRating = ref(false);
@@ -410,6 +412,8 @@ export function useChatPage() {
currentUser,
chatScrollContainer,
scrollContainerHolder,
showScrollToBottom: scroll.showScrollToBottom,
scrollToBottom: scroll.scrollToBottomSmooth,
messages,
isThinking,
conversationId,
@@ -452,6 +456,7 @@ export function useChatPage() {
leaveMessageHandlers,
shippingMappingHandlers,
shippingPickerRefHolder,
shippingNoticePickerRefHolder,
shouldShowThinkingBubble: markdown.shouldShowThinkingBubble,
messageBubbleHandlers: markdown.messageBubbleHandlers,
shouldRenderMessage: markdown.shouldRenderMessage,
@@ -470,13 +475,22 @@ export function useChatPage() {
showChatRating,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
shippingBatchSummary: shipping.shippingBatchSummary,
shippingConversationWorkspace: shipping.shippingConversationWorkspace,
activeShippingBatchNo: shipping.activeShippingBatchNo,
focusedShippingTaskNo: shipping.focusedShippingTaskNo,
shippingFocusReason: shipping.shippingFocusReason,
shippingBatchTasks: shipping.shippingBatchTasks,
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
shippingBatchTasksExpanded: shipping.shippingBatchTasksExpanded,
shippingWorkspaceOpen: shipping.shippingWorkspaceOpen,
retryingShippingPendingTasks: shipping.retryingShippingPendingTasks,
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
switchShippingBatch: shipping.switchShippingBatch,
switchShippingFocusTask: shipping.switchShippingFocusTask,
clearShippingFocus: shipping.clearShippingFocus,
resumeShippingTask: shipping.resumeShippingTask,
retryCurrentShippingBatchPendingTasks: shipping.retryCurrentShippingBatchPendingTasks,
queryShippingShortageDetails: shipping.queryShippingShortageDetails,
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
@@ -1,8 +1,8 @@
/**
* features/chat/composables/useChatScroll.ts
* 聊天主区域滚动:贴底、滚到最新用户问题与思考态切换时的滚动策略。
* 聊天主区域滚动:贴底、滚到最新用户问题、悬浮跳底按钮与思考态切换时的滚动策略。
*/
import { nextTick, watch, type Ref } from 'vue';
import { computed, nextTick, onBeforeUnmount, ref, watch, type Ref } from 'vue';
import type { ChatMessage } from '../types/chat.types';
export interface UseChatScrollOptions {
@@ -13,6 +13,37 @@ export interface UseChatScrollOptions {
export function useChatScroll(options: UseChatScrollOptions) {
const { container, messages } = options;
let scrollToBottomFrame: number | null = null;
let observedContainer: HTMLElement | null = null;
const isNearBottom = ref(true);
const updateNearBottomState = () => {
const el = container.value;
if (!el) {
isNearBottom.value = true;
return;
}
const remaining = el.scrollHeight - el.scrollTop - el.clientHeight;
isNearBottom.value = remaining <= 96;
};
/** 绑定当前滚动容器,容器引用变化时同步换绑监听器。 */
const syncScrollListener = () => {
const nextContainer = container.value;
if (observedContainer === nextContainer) {
updateNearBottomState();
return;
}
observedContainer?.removeEventListener('scroll', updateNearBottomState);
observedContainer = nextContainer;
observedContainer?.addEventListener('scroll', updateNearBottomState, { passive: true });
updateNearBottomState();
};
const stopContainerWatch = watch(container, syncScrollListener, { immediate: true });
const showScrollToBottom = computed(() =>
messages.value.length >= 4 && !isNearBottom.value,
);
const scrollToBottom = async () => {
await nextTick();
@@ -22,6 +53,17 @@ export function useChatScroll(options: UseChatScrollOptions) {
top: el.scrollHeight,
behavior: 'auto',
});
updateNearBottomState();
};
const scrollToBottomSmooth = async () => {
await nextTick();
const el = container.value;
if (!el) return;
el.scrollTo({
top: el.scrollHeight,
behavior: 'smooth',
});
};
const scrollToUserQuestion = async () => {
@@ -60,6 +102,9 @@ export function useChatScroll(options: UseChatScrollOptions) {
window.cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = null;
}
observedContainer?.removeEventListener('scroll', updateNearBottomState);
observedContainer = null;
stopContainerWatch();
};
/** 消息/思考态变化时自动滚动(思考结束滚到用户问题,否则贴底) */
@@ -79,15 +124,21 @@ export function useChatScroll(options: UseChatScrollOptions) {
void scrollToUserQuestion();
} else {
if (isThinking.value) wasThinking = true;
scheduleScrollToBottom();
if (isNearBottom.value) scheduleScrollToBottom();
else window.requestAnimationFrame(updateNearBottomState);
}
},
{ deep: false },
);
};
onBeforeUnmount(dispose);
return {
isNearBottom,
showScrollToBottom,
scrollToBottom,
scrollToBottomSmooth,
scrollToUserQuestion,
scheduleScrollToBottom,
setupThinkingScrollWatch,
@@ -38,13 +38,20 @@ import {
shippingActionButtonClass,
} from '../shipping';
import {
getWorkspaceShippingConversationBatches,
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
switchWorkspaceShippingBatchFocusTask,
type ShippingBatchSummary,
type ShippingConversationWorkspace,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import {
buildShortageDetailsMessage,
hasShortageLines,
isShippingShortageQueryIntent,
} from '../shipping/shippingShortageDetails';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
@@ -75,6 +82,8 @@ export interface UseChatShippingOptions {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
@@ -114,9 +123,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
createNewChatView,
} = options;
let invokeHandleSend: (() => Promise<void>) | null = null;
const shippingBindSend = (fn: () => Promise<void>) => {
invokeHandleSend = fn;
const shippingBindSend = (_fn: () => Promise<void>) => {
void _fn;
// 保留旧绑定入口,续办链路已改为直接调用 sendMessage 以支持 display_query 上下文。
};
// ── 功能开关与 UI refs ────────────────────────────────────
@@ -126,6 +135,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
);
const shippingAutoFlowRequested = ref(false);
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
const shippingNoticePickerRef = ref<HTMLInputElement | null>(null);
const pendingShippingUploadTaskId = ref('');
const pendingShippingInventoryFile = ref<File | null>(null);
const shippingInventorySelectionActive = ref(false);
@@ -147,16 +157,52 @@ export function useChatShipping(options: UseChatShippingOptions) {
});
const resolvedShippingTaskId = ref('');
const resolvedShippingBatchNo = ref('');
const activeShippingBatchNo = ref('');
const focusedShippingTaskNo = ref('');
const shippingConversationWorkspace = ref<ShippingConversationWorkspace | null>(null);
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
const shippingBatchTasksExpanded = ref(false);
const shippingWorkspaceOpen = ref(false);
const retryingShippingPendingTasks = ref(false);
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
const shippingFocusReason = ref('');
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
const lastConversationSyncKey = ref('');
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
const applyShippingBatchDetail = (
detail: ShippingBatchSummary & { tasks?: ShippingTaskSummary[]; focus_task?: ShippingTaskSummary | null },
fallbackBatchNo: string,
) => {
const normalizedBatchNo = detail.batch_no || fallbackBatchNo;
resolvedShippingBatchNo.value = normalizedBatchNo;
if (!activeShippingBatchNo.value || activeShippingBatchNo.value === fallbackBatchNo) {
activeShippingBatchNo.value = normalizedBatchNo;
}
shippingBatchTasks.value = Array.isArray(detail.tasks) ? detail.tasks : [];
shippingBatchSummary.value = {
id: detail.id,
batch_no: detail.batch_no,
conversation_id: detail.conversation_id,
current_focus_task_no: detail.focus_task?.task_no || detail.current_focus_task_no || null,
file_count: detail.file_count,
process_summary: detail.process_summary || null,
created_at: detail.created_at,
updated_at: detail.updated_at,
};
const preferredTaskNo = String(
detail.focus_task?.task_no
|| detail.process_summary?.current_task_no
|| detail.current_focus_task_no
|| '',
).trim();
if (preferredTaskNo) {
resolvedShippingTaskId.value = preferredTaskNo;
}
};
const syncShippingBatchSummary = async (batchNo: string) => {
const normalized = String(batchNo || '').trim();
if (!normalized) {
@@ -166,38 +212,48 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
try {
const detail = await getWorkspaceShippingBatch(normalized);
resolvedShippingBatchNo.value = detail.batch_no || normalized;
shippingBatchTasks.value = Array.isArray(detail.tasks) ? detail.tasks : [];
shippingBatchSummary.value = {
id: detail.id,
batch_no: detail.batch_no,
conversation_id: detail.conversation_id,
current_focus_task_no: detail.focus_task?.task_no || detail.current_focus_task_no || null,
file_count: detail.file_count,
process_summary: detail.process_summary || null,
created_at: detail.created_at,
updated_at: detail.updated_at,
};
const preferredTaskNo = String(
detail.focus_task?.task_no
|| detail.process_summary?.current_task_no
|| detail.current_focus_task_no
|| '',
).trim();
if (preferredTaskNo) {
resolvedShippingTaskId.value = preferredTaskNo;
}
applyShippingBatchDetail(detail, normalized);
} catch {
// ignore summary refresh failure in chat flow
}
};
const applyConversationWorkspaceFocus = (workspace: ShippingConversationWorkspace) => {
const batches = Array.isArray(workspace.batches) ? workspace.batches : [];
if (!batches.length) return;
const queryBatchNo = String(shippingBatchNoFromQuery.value || '').trim();
const currentBatchNo = String(activeShippingBatchNo.value || resolvedShippingBatchNo.value || queryBatchNo || '').trim();
const selectedBatch = batches.find((item) => item.batch_no === currentBatchNo)
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : null)
|| batches.find((item) => item.focus_task?.task_no)
|| batches[0];
if (!selectedBatch) return;
applyShippingBatchDetail(selectedBatch, selectedBatch.batch_no);
};
const syncShippingConversationWorkspace = async () => {
const localConversationId = String(conversationId.value || '').trim();
if (!localConversationId || !isShippingNoticeAgent.value) {
shippingConversationWorkspace.value = null;
return;
}
try {
const workspace = await getWorkspaceShippingConversationBatches(localConversationId);
shippingConversationWorkspace.value = workspace;
applyConversationWorkspaceFocus(workspace);
} catch {
shippingConversationWorkspace.value = null;
}
};
const switchShippingFocusTask = async (taskNo: string) => {
const batchNo = getActiveShippingBatchNo();
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!batchNo || !normalizedTaskNo) return false;
await switchWorkspaceShippingBatchFocusTask(batchNo, normalizedTaskNo);
resolvedShippingTaskId.value = normalizedTaskNo;
focusedShippingTaskNo.value = normalizedTaskNo;
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
if (shippingBatchSummary.value) {
shippingBatchSummary.value = {
...shippingBatchSummary.value,
@@ -205,11 +261,42 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
}
await syncShippingBatchSummary(batchNo);
await syncShippingConversationWorkspace();
await syncActiveShippingTaskDetail(normalizedTaskNo);
await refreshShippingActions();
return true;
};
const clearShippingFocus = () => {
focusedShippingTaskNo.value = '';
shippingFocusReason.value = '';
};
const switchShippingBatch = async (batchNo: string) => {
const normalizedBatchNo = String(batchNo || '').trim();
if (!normalizedBatchNo) return false;
activeShippingBatchNo.value = normalizedBatchNo;
resolvedShippingBatchNo.value = normalizedBatchNo;
const workspaceBatch = shippingConversationWorkspace.value?.batches.find((item) => item.batch_no === normalizedBatchNo);
if (workspaceBatch) {
applyShippingBatchDetail(workspaceBatch, normalizedBatchNo);
} else {
await syncShippingBatchSummary(normalizedBatchNo);
}
const nextTaskNo = String(
shippingBatchSummary.value?.current_focus_task_no
|| shippingBatchSummary.value?.process_summary?.current_task_no
|| shippingBatchTasks.value[0]?.task_no
|| '',
).trim();
if (nextTaskNo) {
resolvedShippingTaskId.value = nextTaskNo;
await syncActiveShippingTaskDetail(nextTaskNo);
}
await refreshShippingActions();
return true;
};
/**
* 清空当前聊天页绑定的发货任务上下文。
*
@@ -224,9 +311,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingInventorySelectionTaskId.value = '';
resolvedShippingTaskId.value = '';
resolvedShippingBatchNo.value = '';
activeShippingBatchNo.value = '';
focusedShippingTaskNo.value = '';
shippingFocusReason.value = '';
shippingConversationWorkspace.value = null;
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
shippingBatchTasksExpanded.value = false;
shippingWorkspaceOpen.value = false;
retryingShippingPendingTasks.value = false;
activeShippingTaskDetail.value = null;
shippingConversationTaskIdCache.value = {};
shippingInventorySchemaPreviewCache.value = {};
@@ -240,16 +332,31 @@ export function useChatShipping(options: UseChatShippingOptions) {
|| '';
const getActiveShippingBatchNo = () =>
resolvedShippingBatchNo.value
activeShippingBatchNo.value
|| resolvedShippingBatchNo.value
|| shippingBatchNoFromQuery.value
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|| '';
const getCurrentShippingChatContext = () => ({
task_id: getActiveShippingTaskId(),
task_id: getActiveBatchTaskId() || getActiveShippingTaskId(),
batch_no: getActiveShippingBatchNo(),
});
const getCurrentShippingChatContextWithDisplay = (displayQuery: string) => ({
...getCurrentShippingChatContext(),
display_query: displayQuery,
});
const getActiveBatchTaskId = () => String(
shippingBatchSummary.value?.current_focus_task_no
|| shippingBatchSummary.value?.process_summary?.current_task_no
|| shippingBatchTasks.value[0]?.task_no
|| focusedShippingTaskNo.value
|| resolvedShippingTaskId.value
|| '',
).trim();
const hasRunningShippingBatchTasks = () =>
shippingBatchTasks.value.some(
(task) => !['uploaded', 'completed', 'closed', 'rejected'].includes(String(task.process_status || '').trim()),
@@ -269,10 +376,15 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
try {
const detail = await getWorkspaceShippingTask(normalized);
const detailBatchNo = String(detail.batch_no || '').trim();
const activeBatchNo = String(activeShippingBatchNo.value || '').trim();
if (activeBatchNo && detailBatchNo && detailBatchNo !== activeBatchNo) {
return;
}
activeShippingTaskDetail.value = detail;
const batchNo = String(detail.batch_no || '').trim();
if (batchNo && resolvedShippingBatchNo.value !== batchNo) {
resolvedShippingBatchNo.value = batchNo;
if (detailBatchNo && resolvedShippingBatchNo.value !== detailBatchNo) {
resolvedShippingBatchNo.value = detailBatchNo;
activeShippingBatchNo.value = activeShippingBatchNo.value || detailBatchNo;
}
} catch {
activeShippingTaskDetail.value = null;
@@ -313,6 +425,16 @@ export function useChatShipping(options: UseChatShippingOptions) {
return '';
};
const lastAssistantShippingActions = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
if (item?.role === 'assistant' && Array.isArray(item.shipping_actions)) {
return item.shipping_actions;
}
}
return [];
};
const { refreshShippingActions } = createShippingActionsRefresher({
isShippingNoticeAgent,
messages,
@@ -330,6 +452,64 @@ export function useChatShipping(options: UseChatShippingOptions) {
saveLocalMessageToBackend,
});
/**
* Dify SSE 完成后立即净化最后一条回复,并同步后端动作按钮。
*
* 核心逻辑:流式过程中只做展示层净化;终态事件到达后消息对象已经完整,
* 此时调用统一 refreshShippingActions,把 action_buttons 回写到当前 assistant 气泡。
*/
const finalizeShippingAssistantMessage = async () => {
if (!isShippingNoticeAgent.value) return;
await refreshShippingActions();
};
/**
* 为“查询缺口明细”定位任务事实来源。
*
* 核心逻辑:优先使用显式任务号或当前聚焦任务,再从批次摘要/当前详情中读取;
* 摘要缺少逐行缺口时补拉既有任务详情接口,确保聊天回复只基于后端事实数据。
*/
const resolveShippingTaskForShortageQuery = async (taskNo?: string) => {
const normalizedTaskNo = String(
taskNo
|| focusedShippingTaskNo.value
|| getActiveBatchTaskId()
|| getActiveShippingTaskId()
|| '',
).trim().toUpperCase();
if (!normalizedTaskNo) return null;
const summaryTask = shippingBatchTasks.value.find(
(item) => String(item.task_no || '').trim().toUpperCase() === normalizedTaskNo,
);
if (summaryTask && hasShortageLines(summaryTask)) return summaryTask;
const detail = activeShippingTaskDetail.value;
if (String(detail?.task_no || '').trim().toUpperCase() === normalizedTaskNo && hasShortageLines(detail)) {
return detail;
}
try {
return await getWorkspaceShippingTask(normalizedTaskNo);
} catch {
return summaryTask || null;
}
};
/**
* 在聊天流中输出确定性的缺口明细。
*
* 核心逻辑:追加一条本地用户意图消息和一条本地助手事实回复,不转发给 Dify,
* 避免大模型复述或重新计算预订单、料号与缺口数量。
*/
const queryShippingShortageDetails = async (taskNo?: string, displayText?: string) => {
const task = await resolveShippingTaskForShortageQuery(taskNo);
if (!task) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return true;
}
await pushShippingLocalUserMessage(displayText || t('chat.shippingNoticeUi.queryShortageDetails'));
await pushShippingLocalAssistantMessage(buildShortageDetailsMessage(task, t));
return true;
};
const { sendShippingMenuMessage } = createShippingConversationHelpers({
conversationId,
history,
@@ -410,7 +590,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
resolvedShippingBatchNo,
shippingBatchSummary,
shippingBatchTasks,
shippingBatchTasksExpanded,
shippingInventorySelectionActive,
shippingInventorySelectionTaskId,
shippingInventorySchemaPreviewCache,
@@ -422,7 +601,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
t,
});
const { handleShippingActionClick } = createShippingMenuHandlers({
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
isThinking,
getActiveShippingTaskId,
messages,
@@ -431,6 +610,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
sendShippingMenuMessage,
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
openShippingNoticePicker: () => {
shippingNoticePickerRef.value?.click();
return true;
},
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
@@ -455,6 +638,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
attachmentPolicy,
getActiveShippingTaskId,
lastAssistantMessageContent,
lastAssistantShippingActions,
sendMessage,
buildFileSpecsForSend,
loadHistory,
@@ -464,10 +648,13 @@ export function useChatShipping(options: UseChatShippingOptions) {
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
handleShippingMenuAction,
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
refreshShippingActions,
shippingSuggestedPrompt,
isShippingShortageQueryIntent,
queryShippingShortageDetails,
msg,
t,
});
@@ -492,8 +679,15 @@ export function useChatShipping(options: UseChatShippingOptions) {
return;
}
autoResumedShippingTasks.value[taskId] = true;
input.value = t('chat.shippingNoticeContinue', { taskId });
await invokeHandleSend?.();
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId });
await sendMessage(
t('chat.shippingNoticeContinue', { taskId }),
currentAgentId.value,
selectedKb.value,
[],
getCurrentShippingChatContextWithDisplay(displayText),
);
await loadHistory();
};
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
@@ -510,8 +704,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
/**
* 续办指定任务,并把聊天上下文切到该任务继续推进。
*
* 核心逻辑:先切换批次焦点任务,再复用既有“请继续处理发货任务”提示词触发一次发送,
* 让 Agent 基于最新 task_id/batch_no 返回下一步动作。
* 核心逻辑:先切换批次焦点任务,再把内部续办指令发给 Agent;
* 前端和历史只展示业务端可理解的简短重试话术,避免暴露工具名。
* @param taskNo - 需要续办的任务编号
* @returns 是否已成功触发续办
*/
@@ -520,11 +714,39 @@ export function useChatShipping(options: UseChatShippingOptions) {
if (!normalizedTaskNo || !isShippingNoticeAgent.value || isThinking.value) return false;
const switched = await switchShippingFocusTask(normalizedTaskNo);
if (!switched) return false;
input.value = t('chat.shippingNoticeContinue', { taskId: normalizedTaskNo });
await invokeHandleSend?.();
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: normalizedTaskNo });
await sendMessage(
t('chat.shippingNoticeContinue', { taskId: normalizedTaskNo }),
currentAgentId.value,
selectedKb.value,
[],
getCurrentShippingChatContextWithDisplay(displayText),
);
await loadHistory();
await refreshShippingActions();
return true;
};
const retryCurrentShippingBatchPendingTasks = async () => {
const batchNo = getActiveShippingBatchNo();
if (!batchNo || retryingShippingPendingTasks.value) return false;
retryingShippingPendingTasks.value = true;
try {
const { retryWorkspaceShippingBatchPending } = await import('@/features/chat/api/shipping.api');
const result = await retryWorkspaceShippingBatchPending(batchNo);
msg.success(result.message || t('chat.shippingNoticeUi.retryPendingDone'));
await syncShippingConversationWorkspace();
await syncShippingBatchSummary(batchNo);
await refreshShippingActions();
return true;
} catch (error) {
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
return false;
} finally {
retryingShippingPendingTasks.value = false;
}
};
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
@@ -538,8 +760,15 @@ export function useChatShipping(options: UseChatShippingOptions) {
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
void router.replace({ path: route.path, query: nextQuery });
input.value = t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value });
await invokeHandleSend?.();
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: shippingTaskIdFromQuery.value });
await sendMessage(
t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value }),
currentAgentId.value,
selectedKb.value,
[],
getCurrentShippingChatContextWithDisplay(displayText),
);
await loadHistory();
};
/**
@@ -555,15 +784,16 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
if (!isShippingNoticeAgent.value) return;
const batchNo = getActiveShippingBatchNo();
const taskId = getActiveShippingTaskId();
const taskId = getActiveBatchTaskId();
if (!batchNo && !taskId) return;
shippingStatusPollTimer = setInterval(() => {
if (!isShippingNoticeAgent.value) return;
const nextBatchNo = getActiveShippingBatchNo();
const nextTaskId = getActiveShippingTaskId();
const nextTaskId = getActiveBatchTaskId();
if (!nextBatchNo && !nextTaskId) return;
void (async () => {
await syncShippingConversationWorkspace();
if (nextBatchNo) await syncShippingBatchSummary(nextBatchNo);
if (nextTaskId) {
await syncActiveShippingTaskDetail(nextTaskId);
@@ -591,7 +821,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
});
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
void refreshShippingActions().then(async () => {
const taskId = getActiveShippingTaskId();
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
await Promise.all([
syncShippingParseReviewCard(taskId),
syncActiveShippingTaskDetail(taskId),
@@ -599,14 +829,17 @@ export function useChatShipping(options: UseChatShippingOptions) {
await syncConversationMessagesIfNeeded(taskId);
});
});
watch([resolvedShippingBatchNo, shippingBatchNoFromQuery], ([batchNo, queryBatchNo]) => {
const nextBatchNo = String(batchNo || queryBatchNo || '').trim();
watch([activeShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingBatchNo], ([activeBatchNo, queryBatchNo, batchNo]) => {
const nextBatchNo = String(activeBatchNo || queryBatchNo || batchNo || '').trim();
if (!nextBatchNo) {
shippingBatchSummary.value = null;
return;
}
void syncShippingBatchSummary(nextBatchNo);
}, { immediate: true });
watch([conversationId, isShippingNoticeAgent], () => {
void syncShippingConversationWorkspace();
}, { immediate: true });
watch(
[isShippingNoticeAgent, conversationId, resolvedShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
() => {
@@ -627,6 +860,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
prepareMarkdownDisplayText,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
shippingNoticePickerRef,
pendingShippingUploadTaskId,
shippingInventorySelectionActive,
shippingInventorySelectionTaskId,
@@ -634,14 +868,23 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingTaskIdFromQuery,
shippingBatchNoFromQuery,
resolvedShippingBatchNo,
activeShippingBatchNo,
focusedShippingTaskNo,
shippingFocusReason,
shippingConversationWorkspace,
shippingBatchSummary,
shippingBatchTasks,
shippingBatchTasksExpanded,
shippingWorkspaceOpen,
retryingShippingPendingTasks,
activeShippingTaskDetail,
getCurrentShippingChatContext,
getActiveShippingBatchNo,
switchShippingBatch,
switchShippingFocusTask,
clearShippingFocus,
resumeShippingTask,
retryCurrentShippingBatchPendingTasks,
queryShippingShortageDetails,
resetShippingConversationState,
resumeShippingTaskFromQuery,
normalizeShippingHeaderForDisplay,
@@ -658,6 +901,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
removeShippingParseReviewLine,
handleShippingActionClick,
handleShippingInventorySelected,
finalizeShippingAssistantMessage,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
shippingActionButtonClass,
@@ -26,6 +26,7 @@ export const SHIPPING_DECISION_ACTIONS = new Set([
'confirm_inventory_mapping',
'correct_inventory_mapping',
'reparse_inventory',
'retry_rpa',
'reject',
'reparse',
'rematch',
@@ -22,6 +22,7 @@ export function createLeaveLocalMessageApi(ctx: LeaveLocalMessageContext) {
try {
const data = await saveLocalChatMessage({
conversation_id: ctx.conversationId.value,
role: chatMsg.role,
type: chatMsg.type,
content: chatMsg.content,
payload: chatMsg.payload,
@@ -22,6 +22,7 @@ export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext)
try {
const data = await saveLocalChatMessage({
conversation_id: ctx.conversationId.value,
role: localMsg.role,
type: localMsg.type,
content: localMsg.content,
payload: localMsg.payload,
@@ -25,7 +25,8 @@ export interface ChatPageSendContext {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string },
context?: { task_id?: string; batch_no?: string; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
refreshHistoryAfterSend: () => Promise<void>;
refreshConversationAfterSend?: () => Promise<void>;
@@ -45,7 +46,8 @@ export interface ChatPageSendContext {
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
copiedIndex: Ref<number | null>;
getChatContext?: () => { task_id?: string; batch_no?: string };
getChatContext?: () => { task_id?: string; batch_no?: string; display_query?: string };
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
}
export function createChatPageSendApi(ctx: ChatPageSendContext) {
@@ -103,6 +105,7 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
ctx.selectedKb.value,
files,
ctx.getChatContext?.(),
{ onAssistantMessageFinished: ctx.onAssistantMessageFinished },
);
await ctx.refreshHistoryAfterSend();
await ctx.refreshConversationAfterSend?.();
@@ -20,6 +20,7 @@ export interface ShippingConversationContext {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; display_query?: string },
) => Promise<void>;
}
@@ -40,7 +41,10 @@ export function createShippingConversationHelpers(ctx: ShippingConversationConte
const sendShippingMenuMessage = async (message: string) => {
const taskId = ctx.getActiveShippingTaskId();
const text = taskId ? `${message}\n任务编号:${taskId}` : message;
await ctx.sendMessage(text, ctx.currentAgentId.value, ctx.selectedKb.value, []);
await ctx.sendMessage(text, ctx.currentAgentId.value, ctx.selectedKb.value, [], {
task_id: taskId || undefined,
display_query: message,
});
await ensureShippingHistorySynced(ctx);
};
@@ -38,7 +38,7 @@ export function formatShippingDecisionAssistantMessage(
);
} else if (decision === 'confirm_inventory_mapping') {
if (String(result.checkpoint || '').trim() === 'map_ok') {
lines.push('', '下一步:匹配库存与发货需求(match_inventory)。');
lines.push('', '下一步:匹配库存与发货需求。');
}
} else if (decision === 'reparse_inventory') {
lines.push('', '请重新上传或粘贴库存 Excel。');
@@ -87,14 +87,20 @@ export function isShippingGenerateExcelIntent(text: string): boolean {
].some((pattern) => pattern.test(normalized));
}
function normalizeShippingCommandText(text: string): string {
return String(text || '')
.trim()
.replace(/\s+/g, '')
.replace(/[,。!?、,.!?]/g, '')
.toLowerCase();
}
export function isShippingDownloadExcelIntent(text: string): boolean {
const normalized = text.trim();
const normalized = normalizeShippingCommandText(text);
if (!normalized) return false;
return [
/^下载excel$/i,
/^下载发货excel$/i,
/下载.*excel/i,
].some((pattern) => pattern.test(normalized));
if (!/(excel|xlsx|表格|发货文件|发货单)/i.test(normalized)) return false;
if (/(生成|创建|制作|重新生成|重生成)/.test(normalized)) return false;
return /(下载|获取|取得|拿|打开|查看|导出)/.test(normalized);
}
export function parseShippingTaskSwitchIntent(text: string): ShippingTaskSwitchIntent | null {
@@ -2,9 +2,9 @@
* features/chat/shipping/shippingMenu.ts
* 用途:发货聊天数字菜单解析、动作按钮合并与决策文本识别(纯函数)。
* 依赖:shippingText.extractShippingActionsDirective、types/shipping.types。
* 逻辑:useChatShippingSendHandler 在发送前调用;优先 API 按钮,其次 HTML 指令,最后内容推断。
* 逻辑:useChatShippingSendHandler 在发送前调用;按钮只来自 API 或结构化 HTML 指令,不从自然语言正文猜测。
*/
import { extractShippingActionsDirective } from './shippingText';
import { extractShippingActionsDirective, stripShippingActionListByButtons } from './shippingText';
import type { ShippingActionButton, ShippingMenuAction } from '../types/shipping.types';
/**
@@ -66,7 +66,7 @@ export function resolveShippingNumericChoice(
}
export function normalizeApiShippingButtons(
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
apiButtons: Array<{ id: string; label: string; message: string; variant?: string; source_code?: string }> | null,
): ShippingActionButton[] {
return (apiButtons || []).map((button) => ({
...button,
@@ -77,18 +77,19 @@ export function normalizeApiShippingButtons(
}
/**
* 合并 API 按钮、HTML 指令与内容推断,得到最终 action_buttons 与 cleanedText。
* 合并 API 按钮与 HTML 指令,得到最终 action_buttons 与 cleanedText。
*/
export function resolveShippingActionButtons(
content: string,
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
apiButtons: Array<{ id: string; label: string; message: string; variant?: string; source_code?: string }> | null,
opts?: { apiResolved?: boolean },
) {
const directive = extractShippingActionsDirective(String(content || ''));
if (opts?.apiResolved) {
const buttons = normalizeApiShippingButtons(apiButtons);
return {
buttons: normalizeApiShippingButtons(apiButtons),
cleanedText: directive.cleanedText,
buttons,
cleanedText: stripShippingActionListByButtons(directive.cleanedText, buttons),
fromDirective: false,
};
}
@@ -0,0 +1,75 @@
/**
* features/chat/shipping/shippingShortageDetails.ts
* 用途:发货通知缺口明细的确定性格式化与查询意图识别。
* 依赖:shipping.api 类型。
* 逻辑:工作台按钮与聊天输入拦截共用本文件,避免把缺口数量交给 LLM 重新推理。
*/
import type {
ShippingMatchLineResult,
ShippingTaskDetail,
ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
export const isShippingShortageQueryIntent = (text: string) => {
const value = String(text || '').trim().toLowerCase();
if (!value) return false;
return [
'查询缺口',
'缺口明细',
'缺哪些',
'哪个单缺',
'哪些料缺',
'库存缺口',
'shortage',
'shortages',
].some((keyword) => value.includes(keyword));
};
export const shortageLinesForTask = (task: ShippingTaskSummary | ShippingTaskDetail | null | undefined) => {
if (!task) return [];
if (Array.isArray(task.shortage?.lines) && task.shortage.lines.length) {
return task.shortage.lines;
}
if (Array.isArray(task.line_results)) {
return task.line_results.filter((line) => Number(line.shortage_qty || 0) > 0);
}
return [];
};
export const hasShortageLines = (task: ShippingTaskSummary | ShippingTaskDetail | null | undefined) =>
shortageLinesForTask(task).length > 0;
export const formatShippingQty = (value: unknown) => {
const num = Number(value || 0);
return Number.isFinite(num) ? num.toLocaleString(undefined, { maximumFractionDigits: 3 }) : '-';
};
export const formatShortageLine = (
line: ShippingMatchLineResult,
index: number,
t: (key: string, params?: Record<string, unknown>) => string,
) => t('chat.shippingNoticeUi.diagnosisShortageLine', {
index: index + 1,
sku: line.sku || '-',
reservationId: line.reservation_id || '-',
required: formatShippingQty(line.required_qty),
available: formatShippingQty(line.available_qty),
shortage: formatShippingQty(line.shortage_qty),
});
export const buildShortageDetailsMessage = (
task: ShippingTaskSummary | ShippingTaskDetail,
t: (key: string, params?: Record<string, unknown>) => string,
) => {
const lines = shortageLinesForTask(task);
if (!lines.length) {
return t('chat.shippingNoticeUi.shortageNoDetails', { taskId: task.task_no });
}
return [
t('chat.shippingNoticeUi.shortageDetailsMessageTitle', {
taskId: task.task_no,
file: task.source_file_name || task.customer_name || '-',
}),
...lines.map((line, index) => formatShortageLine(line, index, t)),
].join('\n');
};
@@ -7,14 +7,115 @@
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET } from '@/constants/shippingNoticeActions';
import type { ShippingActionButton, ShippingActionVariant } from '../types/shipping.types';
/**
* 文本归一化用于判断 Agent 正文编号项是否重复描述了结构化按钮。
*/
const normalizeActionComparableText = (value: string) =>
String(value || '')
.toLowerCase()
.replace(/[\s`"'“”‘’《》〈〉()()[\]{}【】|::,,.。;;、\-—_!?!?/\\]+/g, '');
const isNumberedActionLine = (line: string) =>
/^\s*(?:[-*]\s*)?[1-91-9][\.\、\)::]\s*/.test(line);
const isActionListContextLine = (line: string) =>
/(?:请选择操作|选择操作|操作选项|按钮)/.test(line);
const isActionListTailLine = (line: string) =>
/(?:选择哪|希望.*(?:处理|执行|操作)|要.*哪一项|点击.*按钮)/.test(line);
/**
* 根据后端 action_buttons 移除 Agent 正文中重复生成的编号操作列表。
*
* 核心逻辑:不写死具体按钮文案;只在编号行命中当前 action_buttons 的 label/message 时移除,
* 并顺带移除相邻的“请选择操作”类上下文行。正常新链路不应依赖本兜底。
*/
export function stripShippingActionListByButtons(
text: string,
buttons: Array<Pick<ShippingActionButton, 'label' | 'message'>> | null | undefined,
): string {
const source = String(text || '');
const normalizedActions = (buttons || [])
.flatMap((button) => [button.label, button.message])
.map((item) => normalizeActionComparableText(String(item || '')))
.filter((item) => item.length >= 2);
if (!normalizedActions.length) return source;
const lines = source.split('\n');
const remove = new Set<number>();
lines.forEach((line, index) => {
if (!isNumberedActionLine(line)) return;
const normalizedLine = normalizeActionComparableText(line);
if (normalizedActions.some((action) => normalizedLine.includes(action) || action.includes(normalizedLine))) {
remove.add(index);
}
});
if (!remove.size) return source;
for (const index of Array.from(remove)) {
for (let cursor = index - 1; cursor >= 0 && cursor >= index - 3; cursor -= 1) {
const line = lines[cursor] || '';
if (!line.trim()) {
remove.add(cursor);
continue;
}
if (isActionListContextLine(line)) {
remove.add(cursor);
continue;
}
break;
}
for (let cursor = index + 1; cursor < lines.length && cursor <= index + 3; cursor += 1) {
const line = lines[cursor] || '';
if (!line.trim()) {
remove.add(cursor);
continue;
}
if (isNumberedActionLine(line)) continue;
if (isActionListTailLine(line)) {
remove.add(cursor);
continue;
}
break;
}
}
return lines
.filter((_, index) => !remove.has(index))
.join('\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/**
* 隐藏 Agent 回复中的内部状态 token,并将 task_id 统一为「任务编号」展示。
*/
export function sanitizeShippingConversationText(text: string, enabled: boolean): string {
if (!enabled) return text;
let result = String(text || '')
.replace(/通过\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传')
.replace(/在\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传')
.replace(/(?:Hxops|HXOPS|hxops)\s*聊天区/gi, '当前对话')
.replace(/(?:Hxops|HXOPS|hxops)\s*Chat/gi, '当前对话')
.replace(/到\s*(?:Hxops|HXOPS|hxops)(\s*[??])?/gi, '到当前对话$1')
.replace(/\b(?:Hxops|HXOPS|hxops)\b/g, '当前系统')
.replace(/\btask_id\s*[::]/gi, '任务编号:')
.replace(/\btask_id\b/gi, '任务编号');
result = result
.replace(/\bcreate_task\b/gi, '新建任务')
.replace(/\bget_task_status\b/gi, '查询任务状态')
.replace(/\bparse_notice\b/gi, '解析发货通知')
.replace(/\bsubmit_decision\b/gi, '提交处理结果')
.replace(/\bmatch_inventory\b/gi, '匹配库存')
.replace(/\bgenerate_excel\b/gi, '生成发货 Excel')
.replace(/\bgenerate_shipment_excel\b/gi, '生成发货 Excel')
.replace(/\bupload_to_freight\b/gi, '上传货代系统')
.replace(/\bapply_inventory_mapping\b/gi, '应用库存字段映射')
.replace(/\bget_inventory_schema_preview\b/gi, '读取库存表头预览')
.replace(/\bretry_rpa\b/gi, '重试库存抓取')
.replace(/\bretry_upload\b/gi, '重试上传货代')
.replace(/\bstructured\b/gi, '结构化内容')
.replace(/\braw_text\b/gi, '通知原文');
result = result.replace(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, '');
result = result.replace(
/\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi,
@@ -4,6 +4,8 @@
* 依赖:无;useChatShippingUploadHandler 在上传成功后调用。
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify LLM 解析续办。
*/
import i18n from '@/i18n';
/**
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
*/
@@ -16,17 +18,29 @@ export function buildShippingInventoryUploadPrompt(
&& (result.data as { field_alignment?: unknown }).field_alignment
&& typeof (result.data as { field_alignment?: unknown }).field_alignment === 'object');
const suggestOk = Boolean((result?.data as { suggest_ok?: boolean } | undefined)?.suggest_ok);
const prefix = fileName ? `我已上传库存文件《${fileName}》` : '我已上传库存文件';
const batchNo = String(
(result?.batch_no as string | undefined)
|| ((result?.data as { batch_no?: string } | undefined)?.batch_no)
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|| '',
).trim();
const prefix = batchNo
? (fileName
? String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixBatchWithFile', { fileName, batchNo }))
: String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixBatch', { batchNo })))
: (fileName
? String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixWithFile', { fileName }))
: String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefix')));
if (checkpoint === 'map_infer') {
if (suggestOk) {
return `${prefix}。请继续处理库存列映射;如果系统已识别出完整映射,请直接应用映射,并展示字段对齐结果给我确认。`;
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.mapInferSuggested', { prefix }));
}
return `${prefix}。请继续解析库存列映射,并在拿到可用映射后展示字段对齐结果给我确认。`;
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.mapInferPending', { prefix }));
}
if (checkpoint === 'align_review' || hasAlignment) {
return `${prefix}。请展示库存字段对齐结果,并引导我确认或更正映射。`;
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.alignReview', { prefix }));
}
return `${prefix}。请继续处理库存导入,并告诉我下一步。`;
return String(i18n.global.t('chat.shippingNoticePrompt.inventory.default', { prefix }));
}
/**
@@ -54,16 +68,29 @@ export function buildShippingNoticeUploadPrompt(
: [];
const fileCount = Number(options?.fileCount || 0);
const fileLabel = options?.fileName
? `《${options.fileName}》`
: (fileCount > 1 ? `${fileCount} 份发货通知` : '发货通知');
const parts = [`我已上传${fileLabel}`];
if (batchNo) parts.push(`批次 ${batchNo}`);
if (taskId) parts.push(`当前任务 ${taskId}`);
if (fileCount > 1 || taskIds.length > 1) {
const taskListText = taskIds.length ? `任务列表:${taskIds.join('、')}。` : '';
return `${parts.join(',')}。${taskListText}请立即开始整批处理,不要只处理当前任务。先调用 get_batch_status 查看整批状态,再按批次顺序逐票处理:必要时调用 switch_focus_task 切到对应任务,然后读取该任务 raw_text,用 LLM 抽取结构化字段并调用 parse_notice(structured=...) 落库;若抽取失败可仅传 task_id 让后端用 raw_text 兜底。每处理完一票,都继续切到下一票,直到本批每一票都进入各自下一阶段(待确认、待上传库存、自动推进中的任一状态)。禁止再次询问我“是否开始解析”或只停在第一票。`;
? String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelSingleFile', { fileName: options.fileName }))
: (fileCount > 1
? String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelMulti', { fileCount }))
: String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelDefault')));
const parts = [String(i18n.global.t('chat.shippingNoticePrompt.notice.uploadedPrefix', { fileLabel }))];
if (batchNo) {
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.batchLabel', { batchNo })));
}
return `${parts.join(',')}。请立即读取任务 raw_text,用 LLM 抽取结构化字段后直接调用 parse_notice(structured=...) 落库;若抽取失败可仅传 raw_text 走后端规则兜底。禁止再次询问我“是否开始解析”或“是否现在开始解析”。解析完成后,请直接展示解析结果供我确认。`;
if (taskId) {
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.taskLabel', { taskId })));
}
if (fileCount > 1 || taskIds.length > 1) {
const taskListText = taskIds.length
? String(i18n.global.t('chat.shippingNoticePrompt.notice.taskList', { taskIds: taskIds.join('、') }))
: '';
return String(i18n.global.t('chat.shippingNoticePrompt.notice.multiTask', {
summary: parts.join(','),
taskListText,
}));
}
return String(i18n.global.t('chat.shippingNoticePrompt.notice.singleTask', {
summary: parts.join(','),
}));
}
/**
@@ -37,6 +37,8 @@ export interface ShippingDecisionContext {
* @returns 人工决策与手工上传确认处理函数
*/
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
const manualUploadInFlightTaskIds = new Set<string>();
const syncHistoryIfNeeded = async () => {
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
await ctx.loadHistory();
@@ -108,17 +110,21 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
};
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
if (!normalizedTaskId || manualUploadInFlightTaskIds.has(normalizedTaskId)) return false;
manualUploadInFlightTaskIds.add(normalizedTaskId);
try {
const result = await markWorkspaceShippingManualUploaded(taskId);
const userText = (displayText || '已在货代系统手工上传完成').trim();
const assistantContent = [
String(result.message || '已标记为手工上传货代系统完成。').trim(),
`任务编号:${taskId}`,
].join('\n');
const result = await markWorkspaceShippingManualUploaded(normalizedTaskId);
const userText = (displayText || '我已在货代系统完成上传').trim();
const assistantContent = String(
result.message || `好的,任务 ${normalizedTaskId} 已确认完成,无需再处理。`,
).trim();
const lastUserMessage = [...ctx.messages.value].reverse().find((item) => item.role === 'user');
const shouldAppendUser = String(lastUserMessage?.content || '').trim() !== userText;
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: `${userText}\n任务编号:${taskId}`,
content: userText,
local_id: ctx.newLocalMessageId('shipping-user'),
local_only: true,
};
@@ -130,14 +136,19 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
local_only: true,
shipping_actions_used: true,
};
ctx.messages.value.push(userMsg, assistantMsg);
if (shouldAppendUser) {
ctx.messages.value.push(userMsg);
}
ctx.messages.value.push(assistantMsg);
ctx.messages.value.forEach((rawMsg) => {
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
if (m.role === 'assistant') {
m.shipping_actions = undefined;
}
});
await ctx.saveLocalMessageToBackend(userMsg, userText);
if (shouldAppendUser) {
await ctx.saveLocalMessageToBackend(userMsg, userText);
}
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
void ctx.refreshShippingActions();
return true;
@@ -145,6 +156,8 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
ctx.msg.warning(errorMessage);
return false;
} finally {
manualUploadInFlightTaskIds.delete(normalizedTaskId);
}
};
@@ -5,15 +5,18 @@
* 逻辑:由 useChatShipping 调用本文件;本文件根据 action.id 决定触发后端接口、本地消息落库或前端 UI 行为。
*/
import {
confirmWorkspaceShippingInventorySource,
generateWorkspaceShippingExcel,
getWorkspaceShippingTask,
matchWorkspaceShippingInventory,
retryWorkspaceShippingUpload,
type ShippingDecisionResponse,
type ShippingMatchLineResult,
} from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingMatchResultPayload } from '../types/shipping.types';
import type { ShippingActionButton, ShippingMatchResultPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
export interface ShippingMenuHandlerContext {
@@ -25,6 +28,7 @@ export interface ShippingMenuHandlerContext {
sendShippingMenuMessage: (message: string) => Promise<void>;
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
openShippingInventoryPicker: () => boolean;
openShippingNoticePicker: () => boolean;
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
@@ -40,9 +44,53 @@ export interface ShippingMenuHandlerContext {
* @returns 菜单动作与按钮点击处理函数
*/
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
const normalizeInventorySourceText = (value: string) =>
String(value || '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '');
const recentInventorySourceHint = () => {
const parts: string[] = [];
for (let i = ctx.messages.value.length - 1; i >= 0 && parts.length < 6; i -= 1) {
const content = String(ctx.messages.value[i]?.content || '').trim();
if (content) parts.push(content);
}
return parts.join('\n');
};
const resolveInventorySourceCodeFromContext = async (taskId: string): Promise<string> => {
const detail = await getWorkspaceShippingTask(taskId);
const resolution = detail.inventory_source_resolution;
const candidates = resolution && typeof resolution === 'object'
? (resolution as { candidates?: unknown }).candidates
: null;
if (!Array.isArray(candidates) || candidates.length === 0) return '';
if (candidates.length === 1) {
const only = candidates[0];
return only && typeof only === 'object'
? String((only as { source_code?: unknown }).source_code || '').trim().toUpperCase()
: '';
}
const hint = normalizeInventorySourceText(recentInventorySourceHint());
if (!hint) return '';
const matches = candidates.filter((item) => {
if (!item || typeof item !== 'object') return false;
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
const values = [
source.source_code,
source.display_name,
source.warehouse_code,
source.program_name,
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
return values.some((value) => hint.includes(value) || value.includes(hint));
});
if (matches.length !== 1) return '';
return String((matches[0] as { source_code?: unknown }).source_code || '').trim().toUpperCase();
};
const buildMatchResultPayload = (
taskId: string,
result: ShippingDecisionResponse & { action_buttons?: Array<{ id: string; label: string; message: string; variant?: 'primary' | 'secondary' | 'danger' }> },
result: ShippingDecisionResponse & { action_buttons?: Array<{ id: string; label: string; message: string; variant?: 'primary' | 'secondary' | 'danger'; source_code?: string }> },
): ShippingMatchResultPayload => {
const data = (result?.data && typeof result.data === 'object') ? result.data as Record<string, unknown> : {};
const lineResults = Array.isArray(data.line_results)
@@ -66,12 +114,13 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
};
const handleShippingMenuAction = async (
action: { id?: string; message: string },
action: ShippingActionButton | { id?: string; message: string },
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
) => {
if (ctx.isThinking.value) return;
if (action.id === 'refresh') {
await ctx.sendShippingMenuMessage(action.message || '刷新');
await ctx.refreshShippingActions();
ctx.msg.info(ctx.t('chat.shippingNoticeRefreshDone'));
return;
}
if (action.id === 'download_excel') {
@@ -125,6 +174,92 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
}
return;
}
if (action.id === 'retry_upload') {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
try {
const result = await retryWorkspaceShippingUpload(taskId);
const userText = action.message || ctx.t('chat.shippingNoticeRetryUploadAction');
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: `${userText}\n任务编号:${taskId}`,
local_id: ctx.newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: String(result.message || ctx.t('chat.shippingNoticeRetryUploadQueued')).trim(),
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeRetryUploadFailed');
ctx.msg.warning(errorMessage);
}
return;
}
if (action.id === 'confirm_inventory_source') {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
try {
let sourceCode = String((action as { source_code?: unknown }).source_code || '').trim().toUpperCase();
if (!sourceCode) {
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
}
if (!sourceCode) {
ctx.msg.warning('请直接输入要使用的库存源线索,例如 AWSDU、Dublin 或 Singapore。');
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
const result = await confirmWorkspaceShippingInventorySource(taskId, sourceCode);
const label = String(('label' in action ? action.label : '') || sourceCode).trim();
const userText = `确认库存查询来源:${label}`;
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: `${userText}\n任务编号:${taskId}`,
local_id: ctx.newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: String(result.message || '').trim(),
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
ctx.msg.warning(errorMessage);
if (chatMsg) chatMsg.shipping_actions_used = false;
}
return;
}
if (action.id === 'retry_resolve_inventory_source') {
await ctx.refreshShippingActions();
ctx.msg.info('已重新刷新库存源状态');
return;
}
if (action.id === 'edit_inventory_mapping') {
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
@@ -138,6 +273,10 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
ctx.openShippingInventoryPicker();
return;
}
if (action.id === 'replace_notice_file') {
ctx.openShippingNoticePicker();
return;
}
if (action.id === 'match_inventory') {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
@@ -175,13 +314,16 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
}
if (action.id === 'mark_manual_uploaded') {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
if (chatMsg) {
chatMsg.shipping_actions_used = true;
chatMsg.shipping_actions = undefined;
}
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
await ctx.executeShippingManualUpload(taskId, action.message || '已在货代系统手工上传完成');
await ctx.executeShippingManualUpload(taskId, '我已在货代系统完成上传');
return;
}
if (action.id === 'paste_inventory_json') {
@@ -201,7 +343,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
const handleShippingActionClick = async (
chatMsg: ChatMessage & { shipping_actions_used?: boolean },
action: { id?: string; message: string },
action: ShippingActionButton,
) => {
await handleShippingMenuAction(action, chatMsg);
};
@@ -77,36 +77,11 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
taskId = taskNo;
}
} catch {
// fall back to content-based buttons
// fall back to structured directive buttons embedded in the message
}
}
}
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null;
let apiCheckpoint: string | null = null;
let apiResolved = false;
if (taskId && !ctx.isThinking.value) {
const seq = ++shippingActionsRequestSeq;
try {
const data = await getShippingChatActions(taskId);
if (seq === shippingActionsRequestSeq) {
apiResolved = true;
apiCheckpoint = data.checkpoint ? String(data.checkpoint) : null;
apiButtons = data.action_buttons?.length ? data.action_buttons : null;
}
} catch {
// fall back to content-based buttons
}
}
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
msgs.forEach((rawMsg) => {
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
if (m.role === 'assistant') {
m.shipping_actions = undefined;
}
});
return;
}
let lastOpenAssistantIndex = -1;
for (let i = msgs.length - 1; i >= 0; i -= 1) {
const item = msgs[i];
@@ -124,6 +99,42 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
}
}
const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex;
if (targetAssistantIndex >= 0) {
const target = msgs[targetAssistantIndex] as ChatMessage & { shipping_actions?: ShippingActionButton[] };
const resolved = resolveShippingActionButtons(String(target.content || ''), null);
if (resolved.cleanedText !== String(target.content || '').trim()) {
target.content = resolved.cleanedText;
}
if (resolved.buttons.length && !target.shipping_actions?.length) {
target.shipping_actions = resolved.buttons;
}
}
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null;
let apiCheckpoint: string | null = null;
let apiResolved = false;
if (taskId) {
const seq = ++shippingActionsRequestSeq;
try {
const data = await getShippingChatActions(taskId);
if (seq === shippingActionsRequestSeq) {
apiResolved = true;
apiCheckpoint = data.checkpoint ? String(data.checkpoint) : null;
apiButtons = data.action_buttons?.length ? data.action_buttons : null;
}
} catch {
// keep structured directive buttons if present
}
}
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
msgs.forEach((rawMsg) => {
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
if (m.role === 'assistant') {
m.shipping_actions = undefined;
}
});
return;
}
msgs.forEach((rawMsg, index) => {
const chatMsg = rawMsg as ChatMessage & {
shipping_actions_used?: boolean;
@@ -147,7 +158,7 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
apiResolved ? (apiButtons ?? []) : null,
{ apiResolved },
);
if (resolved.fromDirective) {
if (resolved.fromDirective || resolved.cleanedText !== String(chatMsg.content || '').trim()) {
chatMsg.content = resolved.cleanedText;
}
buttons = resolved.buttons;
@@ -6,11 +6,13 @@
*/
import {
applyWorkspaceShippingInventoryMapping,
confirmWorkspaceShippingInventorySource,
generateWorkspaceShippingExcel,
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
switchWorkspaceShippingBatchFocusTask,
} from '@/features/chat/api/shipping.api';
import { SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
import { buildShippingFieldAlignmentText } from './shippingMapping';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import {
@@ -45,6 +47,7 @@ export interface ShippingSendHandlerContext {
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
getActiveShippingTaskId: () => string;
lastAssistantMessageContent: () => string;
lastAssistantShippingActions: () => ChatMessage['shipping_actions'];
sendMessage: (
content: string,
agentId: number,
@@ -59,10 +62,13 @@ export interface ShippingSendHandlerContext {
openShippingInventoryPicker: () => boolean;
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
handleShippingMenuAction: (action: { id?: string; message: string }) => Promise<void>;
handleShippingAutoUploadFile: (file: File) => Promise<void>;
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
refreshShippingActions: () => Promise<void>;
shippingSuggestedPrompt: ComputedRef<string>;
isShippingShortageQueryIntent: (text: string) => boolean;
queryShippingShortageDetails: (taskNo?: string, displayText?: string) => Promise<boolean>;
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
}
@@ -75,6 +81,59 @@ export interface ShippingSendHandlerContext {
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
*/
export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
const normalizeInventorySourceText = (value: string) =>
String(value || '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '');
const tryConfirmInventorySourceFromText = async (content: string): Promise<boolean> => {
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) return false;
const normalized = normalizeInventorySourceText(content);
if (!normalized) return false;
try {
const detail = await getWorkspaceShippingTask(taskId);
if (detail.pending_human_reason !== 'inventory_source_unresolved') return false;
const resolution = detail.inventory_source_resolution;
const candidates = resolution && typeof resolution === 'object'
? (resolution as { candidates?: unknown }).candidates
: null;
if (!Array.isArray(candidates) || candidates.length === 0) return false;
const hit = candidates.find((item) => {
if (!item || typeof item !== 'object') return false;
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
const values = [
source.source_code,
source.display_name,
source.warehouse_code,
source.program_name,
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
return values.some((value) => normalized === value || normalized.includes(value) || value.includes(normalized));
}) as { source_code?: unknown; display_name?: unknown } | undefined;
const sourceCode = String(hit?.source_code || '').trim().toUpperCase();
if (!sourceCode) return false;
if (typeof content !== 'string') return false;
ctx.input.value = '';
ctx.attachments.value = [];
const label = String(hit?.display_name || sourceCode).trim();
await ctx.pushShippingLocalUserMessage(content.trim());
const result = await confirmWorkspaceShippingInventorySource(taskId, sourceCode);
await ctx.pushShippingLocalAssistantMessage(
[
String(result.message || '').trim(),
`已确认库存查询来源:${label}`,
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
);
void ctx.refreshShippingActions();
return true;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
ctx.msg.warning(errorMessage);
return true;
}
};
const trySwitchShippingTask = async (content: string): Promise<boolean> => {
const intent = parseShippingTaskSwitchIntent(content);
if (!intent) return false;
@@ -128,6 +187,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
const requestedAutoFlow = ctx.shippingAutoFlowRequested.value;
ctx.shippingAutoFlowRequested.value = false;
const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
const first = localFiles[0];
@@ -152,12 +212,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
}
return true;
}
if (!trimmed) {
if (!trimmed || requestedAutoFlow) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
try {
const prompt = ctx.shippingSuggestedPrompt.value || '解析发货通知并创建任务';
await ctx.pushShippingLocalUserMessage(prompt);
await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file));
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
@@ -174,12 +232,36 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
_trimmed: string,
): Promise<boolean> => {
if (!ctx.isShippingNoticeAgent.value) return false;
if (ctx.isShippingShortageQueryIntent(content)) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
return ctx.queryShippingShortageDetails(undefined, content.trim());
}
if (await trySwitchShippingTask(content)) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
return true;
}
if (await tryConfirmInventorySourceFromText(content)) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
return true;
}
const assistantCtx = ctx.lastAssistantMessageContent();
const numericText = content.trim();
if (/^[1-91-9](?:[\.\、\)::]?)$/.test(numericText)) {
const num = Number.isFinite(Number(numericText.charAt(0)))
? Number(numericText.charAt(0))
: '0123456789'.indexOf(numericText.charAt(0));
const actions = ctx.lastAssistantShippingActions() || [];
const action = num >= 1 ? actions[num - 1] : undefined;
if (action) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
await ctx.handleShippingMenuAction(action);
return true;
}
}
const menuChoice = resolveShippingNumericChoice(content, assistantCtx);
if (menuChoice) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
@@ -188,6 +270,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
} else if (menuChoice === 'paste') {
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
return true;
} else if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) {
const spec = SHIPPING_MENU_ACTION_SPECS[menuChoice];
await ctx.executeShippingDecision(menuChoice, spec?.label || spec?.message || menuChoice);
return true;
} else {
await ctx.sendShippingMenuMessage(SHIPPING_MENU_ACTION_SPECS[menuChoice].message);
return true;
@@ -8,6 +8,7 @@ import { computed } from 'vue';
import {
createWorkspaceShippingBatchFromNotices,
createWorkspaceShippingTask,
replaceWorkspaceShippingTaskNotice,
uploadWorkspaceShippingInventory,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
@@ -28,7 +29,6 @@ export interface ShippingUploadHandlerContext {
resolvedShippingBatchNo: Ref<string>;
shippingBatchSummary: Ref<unknown | null>;
shippingBatchTasks: Ref<ShippingTaskSummary[]>;
shippingBatchTasksExpanded: Ref<boolean>;
shippingInventorySelectionActive: Ref<boolean>;
shippingInventorySelectionTaskId: Ref<string>;
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
@@ -48,9 +48,6 @@ export interface ShippingUploadHandlerContext {
* @returns 自动上传、文件选择器和建议提示相关处理函数
*/
export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) {
const hasMultipleShippingBatchTasks = () =>
Array.isArray(ctx.shippingBatchTasks.value) && ctx.shippingBatchTasks.value.length > 1;
const resetInventoryTaskSelection = () => {
ctx.shippingInventorySelectionActive.value = false;
ctx.shippingInventorySelectionTaskId.value = '';
@@ -76,22 +73,14 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
const uploadInventoryForTask = async (taskId: string, file: File) => {
ctx.resolvedShippingTaskId.value = taskId;
const result = await uploadWorkspaceShippingInventory(taskId, file);
const batchNo = String(
((result as unknown as { data?: { batch_no?: string } }).data?.batch_no)
|| ((result as unknown as { data?: { batch?: { batch_no?: string } } }).data?.batch?.batch_no)
|| '',
).trim();
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
await continueShippingInventoryUploadWithDify(taskId, result as unknown as Record<string, unknown>, file.name);
};
const promptInventoryTaskSelection = async (pendingFile?: File) => {
if (pendingFile) ctx.pendingShippingInventoryFile.value = pendingFile;
ctx.shippingBatchTasksExpanded.value = true;
ctx.pendingShippingUploadTaskId.value = '';
ctx.shippingInventorySelectionTaskId.value = '';
ctx.shippingInventorySelectionActive.value = true;
await ctx.pushShippingLocalAssistantMessage(
ctx.t(
pendingFile
? 'chat.shippingNoticeUi.inventoryTaskPickPendingHint'
: 'chat.shippingNoticeUi.inventoryTaskPickHint',
),
);
void ctx.refreshShippingActions();
};
const selectShippingInventoryUploadTask = (taskId: string): boolean => {
@@ -145,19 +134,36 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
}
};
const handleReplaceNoticeForCurrentTask = async (taskId: string, file: File) => {
const result = await replaceWorkspaceShippingTaskNotice(taskId, file);
syncBatchContextFromNoticeResponse(result as unknown as Record<string, unknown>);
ctx.resolvedShippingTaskId.value = taskId;
const hint = String(result.message || '').trim();
const status = String((result as { status?: string }).status || '').trim();
const orchestratorStarted = Boolean(
(result.data as { orchestrator_started?: boolean } | undefined)?.orchestrator_started,
);
await ctx.pushShippingLocalAssistantMessage(
[
hint || `已重新上传发货通知并覆盖当前任务 ${taskId}`,
`任务编号:${taskId}`,
orchestratorStarted ? '后台已开始重新解析当前任务,请稍后查看进度自动刷新。' : '',
status === 'needs_human' ? '请根据提示重新上传清晰文件,或粘贴通知正文。' : '',
].filter(Boolean).join('\n'),
);
void ctx.refreshShippingActions();
};
const handleShippingAutoUploadFile = async (file: File) => {
const kind = classifyShippingUploadFile(file, extractExt);
if (kind === 'inventory') {
if (hasMultipleShippingBatchTasks()) {
await promptInventoryTaskSelection(file);
return;
}
let taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
const created = await createWorkspaceShippingTask({
source_type: 'manual',
conversation_id: String(ctx.conversationId.value || '').trim() || undefined,
});
syncBatchContextFromNoticeResponse(created as unknown as Record<string, unknown>);
taskId = String(created.task_id || '').trim();
if (!taskId) {
ctx.msg.warning('自动创建发货任务失败');
@@ -167,6 +173,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
await uploadInventoryForTask(taskId, file);
return;
}
const activeTaskId = String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
if (activeTaskId) {
await handleReplaceNoticeForCurrentTask(activeTaskId, file);
return;
}
const result = await createWorkspaceShippingBatchFromNotices(
[file],
String(ctx.conversationId.value || '').trim() || undefined,
@@ -203,6 +214,12 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
const noticeFiles = files.filter(Boolean);
if (!noticeFiles.length) return;
const activeTaskId = String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
const singleNoticeFile = noticeFiles[0];
if (noticeFiles.length === 1 && activeTaskId && singleNoticeFile) {
await handleReplaceNoticeForCurrentTask(activeTaskId, singleNoticeFile);
return;
}
const result = await createWorkspaceShippingBatchFromNotices(
noticeFiles,
String(ctx.conversationId.value || '').trim() || undefined,
@@ -250,10 +267,6 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
};
const openShippingInventoryPicker = (): boolean => {
if (hasMultipleShippingBatchTasks()) {
void promptInventoryTaskSelection();
return true;
}
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
@@ -288,8 +301,8 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
| undefined;
if (!first) return '';
const kind = classifyShippingUploadFile(first.file, extractExt);
if (kind === 'inventory') return '上传库存并进入字段对齐';
return '解析发货通知并创建任务';
if (kind === 'inventory') return ctx.t('chat.shippingNoticePrompt.notice.autoInventoryAction');
return ctx.t('chat.shippingNoticePrompt.notice.autoNoticeAction');
});
const useShippingSuggestedPrompt = () => {
@@ -22,12 +22,17 @@ export interface ShippingTaskSummary {
upload_mode?: string | null;
upload_attempt?: number | null;
pending_human_reason?: string | null;
error_message?: string | null;
conversation_id?: string | null;
export_file_name?: string | null;
freight_ref_no?: string | null;
shortage?: ShippingShortageSummary | null;
line_results?: ShippingMatchLineResult[];
step_payload?: Record<string, unknown> & {
current_step_progress?: ShippingCurrentStepProgress;
};
rpa_inventory_source?: Record<string, unknown> | null;
inventory_source_resolution?: Record<string, unknown> | null;
created_at?: string | null;
updated_at?: string | null;
}
@@ -101,6 +106,7 @@ export interface ShippingChatAction {
label: string;
message: string;
variant: 'primary' | 'secondary' | 'danger';
source_code?: string;
}
export interface ShippingChatActionsResponse {
@@ -131,6 +137,27 @@ export interface ShippingBatchSummary {
updated_at?: string | null;
}
export interface ShippingConversationWorkspaceSummary {
batch_count: number;
total: number;
completed: number;
running: number;
failed: number;
needs_human: number;
pending: number;
}
export interface ShippingConversationBatch extends ShippingBatchSummary {
tasks: ShippingTaskSummary[];
focus_task?: ShippingTaskSummary | null;
}
export interface ShippingConversationWorkspace {
conversation_id: string;
summary: ShippingConversationWorkspaceSummary;
batches: ShippingConversationBatch[];
}
export interface ShippingInventoryUploadResponse {
status: string;
message?: string;
@@ -82,6 +82,7 @@ export interface ShippingMatchResultPayload {
label: string;
message: string;
variant: 'primary' | 'secondary' | 'danger';
source_code?: string;
}>;
}
@@ -90,4 +91,5 @@ export interface ShippingActionButton {
label: string;
message: string;
variant?: ShippingActionVariant;
source_code?: string;
}
+106 -14
View File
@@ -1,6 +1,6 @@
{
"defaultTitle": "Chat",
"assistantLabel": "HXOPS AI Assistant",
"assistantLabel": "AI Assistant",
"placeholder": "Ask anything...",
"history": "Chat History",
"noHistory": "No history",
@@ -13,15 +13,45 @@
"loadingAgent": "Loading agent...",
"thinking": "Generating response...",
"disclaimer": "AI can make mistakes. Please verify important information.",
"scrollToLatest": "Scroll to latest message",
"createNewChat": "New Chat",
"shippingNoticeContinue": "Please continue shipping task {taskId}. Call get_task_status first and tell me the next step.",
"shippingNoticeContinue": "Please continue shipping task {taskId}. Read the current task status first; if it still needs parsing, parse the shipping notice and save the result; otherwise explain the current progress and next step.",
"shippingNoticeActionsHint": "Choose an action:",
"shippingNoticeMissingTaskId": "Task ID not found. Complete shipping notice parsing first.",
"shippingNoticeUploadDone": "Inventory file uploaded: {fileName}.",
"shippingNoticeUploadOk": "Upload succeeded.",
"shippingNoticeUploadFailed": "Inventory upload failed.",
"shippingNoticeRefreshDone": "Current task status refreshed.",
"shippingNoticeRetryUploadAction": "Retry freight upload",
"shippingNoticeRetryUploadQueued": "Upload has been triggered again. Refresh later to check the result.",
"shippingNoticeRetryUploadFailed": "Retry upload failed.",
"shippingNoticePasteHint": "Paste inventory rows in the input box, then send.",
"shippingNoticeDecisionDone": "Action completed.",
"shippingNoticePrompt": {
"inventory": {
"prefix": "I have uploaded the inventory file",
"prefixWithFile": "I have uploaded the inventory file \"{fileName}\"",
"prefixBatch": "I have uploaded the batch inventory snapshot for batch {batchNo}",
"prefixBatchWithFile": "I have uploaded the batch inventory snapshot \"{fileName}\" for batch {batchNo}",
"mapInferSuggested": "{prefix}. Please continue the inventory column mapping. If the system has already identified a complete mapping, apply it directly and show me the field alignment result for confirmation.",
"mapInferPending": "{prefix}. Please continue parsing the inventory column mapping, and after a usable mapping is available, show me the field alignment result for confirmation.",
"alignReview": "{prefix}. Please show the inventory field alignment result and guide me to confirm or correct the mapping.",
"default": "{prefix}. Please continue the inventory import and tell me the next step."
},
"notice": {
"fileLabelSingleFile": "\"{fileName}\"",
"fileLabelMulti": "{fileCount} shipping notices",
"fileLabelDefault": "the shipping notice",
"uploadedPrefix": "I have uploaded {fileLabel}",
"batchLabel": "batch {batchNo}",
"taskLabel": "current task {taskId}",
"taskList": "Task list: {taskIds}.",
"autoInventoryAction": "Upload inventory and align columns",
"autoNoticeAction": "Create tasks and parse shipping notices",
"multiTask": "{summary}. {taskListText}Please only handle the current focus task. Read the current task status first; if it still needs parsing, parse the shipping notice and save the result. If it is already in a later step, explain the current progress and next step directly. Do not ask me again whether parsing should start, and do not loop through other tasks in the batch.",
"singleTask": "{summary}. Read the current task status first; if it still needs parsing, parse the shipping notice and save the result. If it is already in a later step, explain the current progress and next step directly. Do not ask me again whether parsing should start."
}
},
"shippingNoticeMapping": {
"inventoryHeaders": "Inventory headers",
"headerRow": "Header row: {row}",
@@ -70,7 +100,7 @@
"inventoryAvailable": "Inventory available",
"shortageQty": "Shortage",
"statusLabel": "Status",
"shortageBanner": "Inventory shortage exists. Do not continue to freight upload yet. Resolve the shortage first, or use the available actions to confirm partial shipment / retry matching.",
"shortageBanner": "Inventory shortage exists. Do not continue to freight upload yet. Resolve the shortage first, or use the available actions to retry matching / revise the input.",
"shortageDetails": "Shortage details",
"shortageRowDetail": "Line {index}: Reservation ID {reservationId}, SKU {sku}, shortage {shortage}",
"availableActions": "Available actions",
@@ -81,17 +111,79 @@
"batchProgress": "Item {index}/{total}",
"batchCurrentIndex": "Currently processing item {index}/{total}",
"batchSummaryLine": "Batch {total} items · Completed {completed} · In progress {running} · Pending {pending}",
"conversationWorkspaceTitle": "Agent session execution summary",
"conversationSummaryLine": "{batches} batches · {total} tasks · {completed} completed · {running} running · {abnormal} need intervention",
"batchChromeSummary": "{total} tasks, {completed} done, {running} running, {abnormal} need intervention",
"agentExecutionSummary": "Agent execution summary",
"workspaceSubtitle": "{batches} batches · {total} tasks, {completed} completed, {abnormal} need intervention",
"noBlockingTasks": "No blocking tasks in the current batch. It is completed or being archived automatically.",
"focusTaskRecommendation": "Focus this task first, confirm the blocker, then continue recovery within the batch.",
"focusThisTask": "Fix this task",
"showWorkspace": "Batch workspace",
"hideWorkspace": "Hide workspace",
"batchWorkspaceTitle": "Batch workspace",
"batchWorkspaceSubtitle": "Switch batches, filter tasks, and diagnose steps",
"batchActionsTitle": "Batch actions",
"retryFailedTasks": "Retry all failed",
"batchActionSafetyNotice": "Human-review tasks are not retried in bulk; completed tasks are not uploaded again. Batch recovery only handles failed or queued tasks.",
"taskDetailCount": "Task details ({count})",
"filterAll": "All",
"filterAbnormal": "Abnormal ({count})",
"filterCompleted": "Done ({count})",
"emptyFilteredTasks": "No matching tasks",
"focusRepair": "Focus repair",
"queryShortageDetails": "Query shortage details",
"retrySingleTask": "Retry single task",
"retrySingleTaskMessage": "Retry current task {taskId}",
"viewDetail": "View details",
"mobileWorkspaceHint": "The workspace is open on mobile. Pick a task from the list to continue.",
"diagnosisAdviceRetryOrFocus": "Focus this task first to inspect context; retry only if it is a transient external-system failure.",
"diagnosisUploadFailedTitle": "Freight-system upload failed and no success receipt was returned.",
"diagnosisUploadFailedAdvice": "Retry this task. If it keeps failing, check freight login state, field formats, or upload manually.",
"diagnosisShortageTitle": "Inventory matching found a shortage, so full shipment cannot continue directly.",
"diagnosisShortageAdvice": "Shipment is blocked. Replenish inventory or correct the notice, then match inventory again.",
"diagnosisShortageLine": "Line {index}: reservation {reservationId}, SKU {sku}, required {required}, available {available}, shortage {shortage}",
"diagnosisShortageAdviceWithLines": "Shortage details: {lines}. Replenish inventory or correct the notice, then match again.",
"shortageDetailsMessageTitle": "Inventory shortage details for task {taskId} ({file}):",
"shortageNoDetails": "No inventory shortage was found for task {taskId}.",
"diagnosisInventoryRpaTitle": "Inventory RPA did not return an available inventory snapshot.",
"diagnosisInventoryRpaAdvice": "Retry inventory capture first; if the external system is unavailable, upload an inventory file manually.",
"diagnosisAlignReviewTitle": "Inventory column mapping needs manual confirmation.",
"diagnosisAlignReviewAdvice": "Confirm SKU, Reservation ID, and available-quantity mappings to avoid matching the wrong item.",
"diagnosisParseReviewTitle": "Notice parsing confidence is low and needs review.",
"diagnosisParseReviewAdvice": "Check customer, PO, required date, and order lines before continuing.",
"diagnosisReservationRequiredTitle": "Reservation ID is missing, so inventory cannot be locked by reservation.",
"diagnosisReservationRequiredAdvice": "Add the Reservation ID, or confirm this customer can proceed without one.",
"diagnosisInventoryWaitingTitle": "Waiting for inventory file or inventory entry confirmation.",
"diagnosisInventoryWaitingAdvice": "Upload the batch inventory snapshot or confirm the automatic capture entry.",
"diagnosisCompletedTitle": "Task is completed and archived.",
"diagnosisCompletedAdvice": "No action required; review export files or upload receipts if needed.",
"diagnosisStepWaitingTitle": "Step {step} is waiting for a prerequisite.",
"diagnosisStepWaitingAdvice": "Monitor it in the workspace, or focus this task to inspect context.",
"currentTaskDiagnosis": "Current task diagnosis",
"currentTaskPosition": "Item {index}/{total}",
"batchTabAbnormal": "{completed} completed · {abnormal} abnormal",
"batchTabNormal": "{total} tasks normal",
"interventionQueue": "Needs intervention",
"needsIntervention": "Needs intervention",
"currentNotice": "Current notice",
"currentStepLabel": "Current",
"stepHeadline": "Step {current}/{total} · {label}",
"stepFraction": "Step {current}/{total}",
"stepNeedsConfirm": "Step {step} needs confirmation",
"taskListResume": "Task List / Resume",
"retryPendingTasks": "Retry recoverable tasks in current batch",
"retryPendingDone": "Recoverable tasks have been resubmitted",
"retryFailed": "Retry failed",
"retrying": "Retrying...",
"taskListTitle": "Task List",
"taskListHint": "Switching tasks also updates the top Stepper and available actions",
"expandTaskList": "Expand list",
"collapseTaskList": "Collapse list",
"currentFocus": "Current focus →",
"expandTaskList": "Expand task list",
"collapseTaskList": "Collapse task list",
"currentFocus": "Current focus:",
"currentFocusDefaultReason": "Input will apply to this task",
"focusInputPlaceholder": "Handling {taskId}. Type an instruction...",
"clearFocus": "Clear focus",
"runningState": "In progress",
"pendingState": "Pending",
"completedState": "Completed",
@@ -100,13 +192,13 @@
"nextTask": "Next",
"collapseTasks": "Hide tasks",
"viewTasks": "View tasks",
"inventoryTaskPickTitle": "Select inventory target task",
"inventoryTaskPickHint": "This batch contains multiple tasks. To avoid cross-task mistakes, choose which task this inventory belongs to before uploading.",
"inventoryTaskPickPendingHint": "This batch contains multiple tasks. To avoid cross-task mistakes, select the target task first and the pending inventory file will continue uploading after selection.",
"inventoryTaskPickTitle": "Batch inventory snapshot",
"inventoryTaskPickHint": "This batch contains multiple tasks. The inventory file will be uploaded as one batch snapshot, then each task matches independently.",
"inventoryTaskPickPendingHint": "This batch contains multiple tasks. The pending inventory file will be uploaded as one batch snapshot, then each task matches independently.",
"cancelInventoryTaskPick": "Cancel",
"uploadInventoryToTask": "Upload to this task",
"inventoryTargetTask": "Inventory target {taskId}",
"inventoryTargetIdle": "Waiting for target selection",
"uploadInventoryToTask": "Upload batch inventory",
"inventoryTargetTask": "Batch inventory entry {taskId}",
"inventoryTargetIdle": "Waiting for batch inventory",
"fileCount": "Files",
"runningCount": "Running",
"completedCount": "Completed",
@@ -141,13 +233,13 @@
},
"matchStatus": {
"fulfillable": "Fully fulfillable",
"partial": "Partially fulfillable",
"partial": "Shortage exists",
"unfulfillable": "Unfulfillable",
"pending": "Pending match"
},
"rowStatus": {
"ok": "Enough",
"partial": "Partial",
"partial": "Shortage",
"shortage": "Shortage"
},
"stepper": {
+106 -14
View File
@@ -1,6 +1,6 @@
{
"defaultTitle": "แชท",
"assistantLabel": "ผู้ช่วย AI ของ HXOPS",
"assistantLabel": "ผู้ช่วย AI",
"placeholder": "ถามอะไรก็ได้...",
"history": "ประวัติการแชท",
"noHistory": "ไม่มีประวัติ",
@@ -13,15 +13,45 @@
"loadingAgent": "กำลังโหลดตัวแทน...",
"thinking": "กำลังสร้างคำตอบ...",
"disclaimer": "AI อาจทำผิดพลาดได้ โปรดตรวจสอบข้อมูลสำคัญ",
"scrollToLatest": "เลื่อนไปยังข้อความล่าสุด",
"createNewChat": "แชทใหม่",
"shippingNoticeContinue": "กรุณาดำเนินการงานจัดส่งต่อ {taskId} โปรดเรียก get_task_status ก่อนและบอกขั้นตอนถัดไป",
"shippingNoticeContinue": "กรุณาดำเนินการงานจัดส่งต่อ {taskId} โปรดอ่านสถานะงานปัจจุบันก่อน หากยังต้องแยกข้อมูล ให้แยกใบแจ้งส่งสินค้าและบันทึกผลลัพธ์ มิฉะนั้นให้สรุปความคืบหน้าและขั้นตอนถัดไป",
"shippingNoticeActionsHint": "เลือกการทำงาน:",
"shippingNoticeMissingTaskId": "ไม่พบรหัสงาน โปรดแยกใบแจ้งส่งสินค้าก่อน",
"shippingNoticeUploadDone": "อัปโหลดไฟล์สต็อกแล้ว: {fileName}",
"shippingNoticeUploadOk": "อัปโหลดสำเร็จ",
"shippingNoticeUploadFailed": "อัปโหลดไฟล์สต็อกล้มเหลว",
"shippingNoticeRefreshDone": "รีเฟรชสถานะงานปัจจุบันแล้ว",
"shippingNoticeRetryUploadAction": "ลองอัปโหลดไปยังระบบขนส่งอีกครั้ง",
"shippingNoticeRetryUploadQueued": "เริ่มอัปโหลดอีกครั้งแล้ว โปรดรีเฟรชภายหลังเพื่อตรวจสอบผลลัพธ์",
"shippingNoticeRetryUploadFailed": "ลองอัปโหลดอีกครั้งไม่สำเร็จ",
"shippingNoticePasteHint": "วางข้อมูลสต็อกในช่องข้อความแล้วส่ง",
"shippingNoticeDecisionDone": "ดำเนินการเสร็จแล้ว",
"shippingNoticePrompt": {
"inventory": {
"prefix": "ฉันได้อัปโหลดไฟล์สต็อกแล้ว",
"prefixWithFile": "ฉันได้อัปโหลดไฟล์สต็อก \"{fileName}\" แล้ว",
"prefixBatch": "ฉันได้อัปโหลดสแนปช็อตสต็อกของชุดงาน {batchNo} แล้ว",
"prefixBatchWithFile": "ฉันได้อัปโหลดสแนปช็อตสต็อก \"{fileName}\" ของชุดงาน {batchNo} แล้ว",
"mapInferSuggested": "{prefix} กรุณาดำเนินการจับคู่คอลัมน์สต็อกต่อ หากระบบรู้จักการจับคู่ครบแล้ว ให้ใช้การจับคู่นั้นได้ทันทีและแสดงผลการจัดแนวฟิลด์ให้ฉันยืนยัน",
"mapInferPending": "{prefix} กรุณาแยกการจับคู่คอลัมน์สต็อกต่อ และเมื่อได้การจับคู่ที่ใช้ได้แล้ว ให้แสดงผลการจัดแนวฟิลด์ให้ฉันยืนยัน",
"alignReview": "{prefix} กรุณาแสดงผลการจัดแนวฟิลด์สต็อก และแนะนำให้ฉันยืนยันหรือแก้ไขการจับคู่",
"default": "{prefix} กรุณาดำเนินการนำเข้าสต็อกต่อ และบอกฉันว่าขั้นตอนถัดไปคืออะไร"
},
"notice": {
"fileLabelSingleFile": "\"{fileName}\"",
"fileLabelMulti": "ใบแจ้งจัดส่ง {fileCount} ฉบับ",
"fileLabelDefault": "ใบแจ้งจัดส่ง",
"uploadedPrefix": "ฉันได้อัปโหลด{fileLabel}แล้ว",
"batchLabel": "ชุดงาน {batchNo}",
"taskLabel": "งานปัจจุบัน {taskId}",
"taskList": "รายการงาน: {taskIds}",
"autoInventoryAction": "อัปโหลดสต็อกและจับคู่คอลัมน์",
"autoNoticeAction": "สร้างงานและแยกข้อมูลใบแจ้งจัดส่ง",
"multiTask": "{summary} {taskListText}กรุณาจัดการเฉพาะงานที่โฟกัสอยู่ในขณะนี้ก่อน อ่านสถานะงานปัจจุบันก่อน หากยังต้องแยกข้อมูล ให้แยกใบแจ้งส่งสินค้าและบันทึกผลลัพธ์ หากเข้าสู่ขั้นตอนถัดไปแล้ว ให้สรุปความคืบหน้าและขั้นตอนถัดไปโดยตรง อย่าถามซ้ำว่าจะเริ่มแยกข้อมูลหรือไม่ และไม่ต้องวนประมวลผลงานอื่นทั้งชุด",
"singleTask": "{summary} กรุณาอ่านสถานะงานปัจจุบันก่อน หากยังต้องแยกข้อมูล ให้แยกใบแจ้งส่งสินค้าและบันทึกผลลัพธ์ หากเข้าสู่ขั้นตอนถัดไปแล้ว ให้สรุปความคืบหน้าและขั้นตอนถัดไปโดยตรง อย่าถามซ้ำว่าจะเริ่มแยกข้อมูลหรือไม่"
}
},
"shippingNoticeMapping": {
"inventoryHeaders": "หัวคอลัมน์สต็อก",
"headerRow": "แถวหัวตาราง: {row}",
@@ -70,7 +100,7 @@
"inventoryAvailable": "สต็อกที่ใช้ได้",
"shortageQty": "จำนวนที่ขาด",
"statusLabel": "สถานะ",
"shortageBanner": "มีสต็อกขาดอยู่ จึงยังไม่ควรอัปโหลดไปยังผู้ให้บริการขนส่งต่อ กรุณาจัดการส่วนที่ขาดก่อน หรือใช้ปุ่มที่มีให้เพื่อยืนยันการส่งบางส่วน / จับคู่ใหม่",
"shortageBanner": "มีสต็อกขาดอยู่ จึงยังไม่ควรอัปโหลดไปยังผู้ให้บริการขนส่งต่อ กรุณาจัดการส่วนที่ขาดก่อน หรือใช้ปุ่มที่มีให้เพื่อจับคู่ใหม่ / กลับไปแก้ไขข้อมูล",
"shortageDetails": "รายละเอียดส่วนขาด",
"shortageRowDetail": "แถว {index}: Reservation ID {reservationId}, SKU {sku}, ขาด {shortage}",
"availableActions": "การทำงานที่ใช้ได้",
@@ -81,17 +111,79 @@
"batchProgress": "รายการ {index}/{total}",
"batchCurrentIndex": "กำลังประมวลผลรายการที่ {index}/{total}",
"batchSummaryLine": "ชุดนี้ {total} รายการ · เสร็จแล้ว {completed} · กำลังดำเนินการ {running} · รอดำเนินการ {pending}",
"conversationWorkspaceTitle": "สรุปการดำเนินงานของเซสชัน Agent",
"conversationSummaryLine": "{batches} ชุดงาน · {total} งาน · เสร็จแล้ว {completed} · กำลังดำเนินการ {running} · ต้องแทรกแซง {abnormal}",
"batchChromeSummary": "{total} งาน, เสร็จแล้ว {completed}, กำลังทำ {running}, ต้องแทรกแซง {abnormal}",
"agentExecutionSummary": "สรุปการดำเนินงานของ Agent",
"workspaceSubtitle": "{batches} ชุดงาน · {total} งาน, เสร็จแล้ว {completed}, ต้องแทรกแซง {abnormal}",
"noBlockingTasks": "ชุดงานปัจจุบันไม่มีงานที่บล็อกอยู่ เสร็จแล้วหรือกำลังจัดเก็บอัตโนมัติ",
"focusTaskRecommendation": "แนะนำให้โฟกัสงานนี้ก่อน ตรวจสอบสาเหตุที่บล็อก แล้วค่อยดำเนินการกู้คืนในชุดงานต่อ",
"focusThisTask": "แก้งานนี้",
"showWorkspace": "เวิร์กสเปซชุดงาน",
"hideWorkspace": "ซ่อนเวิร์กสเปซ",
"batchWorkspaceTitle": "เวิร์กสเปซชุดงาน",
"batchWorkspaceSubtitle": "สลับชุดงาน กรองงาน และวิเคราะห์ขั้นตอน",
"batchActionsTitle": "การทำงานแบบชุด",
"retryFailedTasks": "ลองงานที่ล้มเหลวทั้งหมดอีกครั้ง",
"batchActionSafetyNotice": "งานที่ต้องให้คนตรวจจะไม่ถูกลองใหม่แบบชุด งานที่เสร็จแล้วจะไม่ถูกอัปโหลดซ้ำ การกู้คืนแบบชุดจะจัดการเฉพาะงานที่ล้มเหลวหรืออยู่ในคิว",
"taskDetailCount": "รายละเอียดงาน ({count})",
"filterAll": "ทั้งหมด",
"filterAbnormal": "ผิดปกติ ({count})",
"filterCompleted": "เสร็จแล้ว ({count})",
"emptyFilteredTasks": "ไม่มีงานที่ตรงเงื่อนไข",
"focusRepair": "โฟกัสแก้ไข",
"queryShortageDetails": "ดูรายละเอียดส่วนขาด",
"retrySingleTask": "ลองงานเดียวอีกครั้ง",
"retrySingleTaskMessage": "ลองงานปัจจุบัน {taskId} อีกครั้ง",
"viewDetail": "ดูรายละเอียด",
"mobileWorkspaceHint": "เปิดเวิร์กสเปซบนมือถือแล้ว โปรดเลือกงานจากรายการเพื่อดำเนินการต่อ",
"diagnosisAdviceRetryOrFocus": "ควรโฟกัสงานนี้เพื่อตรวจบริบทก่อน หากเป็นปัญหาระบบภายนอกชั่วคราวจึงค่อยลองใหม่",
"diagnosisUploadFailedTitle": "อัปโหลดไปยังระบบขนส่งล้มเหลว และยังไม่ได้รับใบตอบรับสำเร็จ",
"diagnosisUploadFailedAdvice": "ลองงานนี้ใหม่ หากยังล้มเหลวให้ตรวจสถานะล็อกอิน รูปแบบฟิลด์ หรืออัปโหลดด้วยตนเอง",
"diagnosisShortageTitle": "การจับคู่สต็อกพบจำนวนขาด จึงยังดำเนินการส่งเต็มจำนวนไม่ได้",
"diagnosisShortageAdvice": "ระบบบล็อกการจัดส่งต่อ โปรดเติมสต็อกหรือแก้ไขใบแจ้ง แล้วจับคู่สต็อกใหม่",
"diagnosisShortageLine": "แถว {index}: Reservation {reservationId}, SKU {sku}, ต้องการ {required}, มี {available}, ขาด {shortage}",
"diagnosisShortageAdviceWithLines": "รายละเอียดส่วนขาด: {lines} โปรดเติมสต็อกหรือแก้ไขใบแจ้ง แล้วจับคู่ใหม่",
"shortageDetailsMessageTitle": "รายละเอียดสต็อกขาดของงาน {taskId} ({file}):",
"shortageNoDetails": "ไม่พบสต็อกขาดสำหรับงาน {taskId}",
"diagnosisInventoryRpaTitle": "Inventory RPA ยังไม่ส่งคืนสแนปช็อตสต็อกที่ใช้ได้",
"diagnosisInventoryRpaAdvice": "ลองดึงสต็อกใหม่ก่อน หากระบบภายนอกใช้ไม่ได้ ให้อัปโหลดไฟล์สต็อกด้วยตนเอง",
"diagnosisAlignReviewTitle": "ต้องยืนยันการแมปคอลัมน์สต็อกด้วยตนเอง",
"diagnosisAlignReviewAdvice": "ยืนยันการแมป SKU, Reservation ID และจำนวนที่ใช้ได้ เพื่อป้องกันการจับคู่ผิดรายการ",
"diagnosisParseReviewTitle": "ความมั่นใจในการอ่านใบแจ้งต่ำ ต้องตรวจทานข้อมูล",
"diagnosisParseReviewAdvice": "ตรวจลูกค้า PO วันที่ต้องการ และรายการคำสั่งซื้อก่อนดำเนินการต่อ",
"diagnosisReservationRequiredTitle": "ไม่มี Reservation ID จึงล็อกสต็อกตามใบจองไม่ได้",
"diagnosisReservationRequiredAdvice": "เพิ่ม Reservation ID หรือยืนยันว่าลูกค้ารายนี้ดำเนินการได้โดยไม่ต้องมีใบจอง",
"diagnosisInventoryWaitingTitle": "กำลังรอไฟล์สต็อกหรือการยืนยันช่องทางสต็อก",
"diagnosisInventoryWaitingAdvice": "อัปโหลดสแนปช็อตสต็อกของชุดงาน หรือยืนยันช่องทางดึงอัตโนมัติ",
"diagnosisCompletedTitle": "งานเสร็จแล้วและถูกจัดเก็บแล้ว",
"diagnosisCompletedAdvice": "ไม่ต้องดำเนินการ หากต้องการตรวจสอบให้ดูไฟล์ส่งออกหรือใบตอบรับ",
"diagnosisStepWaitingTitle": "ขั้นตอน {step} กำลังรอเงื่อนไขก่อนหน้า",
"diagnosisStepWaitingAdvice": "ติดตามในเวิร์กสเปซ หรือโฟกัสงานนี้เพื่อตรวจบริบท",
"currentTaskDiagnosis": "การวิเคราะห์งานปัจจุบัน",
"currentTaskPosition": "รายการ {index}/{total}",
"batchTabAbnormal": "เสร็จแล้ว {completed} · ผิดปกติ {abnormal}",
"batchTabNormal": "{total} งานปกติทั้งหมด",
"interventionQueue": "งานที่ต้องแทรกแซง",
"needsIntervention": "ต้องแทรกแซง",
"currentNotice": "ใบแจ้งปัจจุบัน",
"currentStepLabel": "ปัจจุบัน",
"stepHeadline": "ขั้นตอน {current}/{total} · {label}",
"stepFraction": "ขั้นตอน {current}/{total}",
"stepNeedsConfirm": "ขั้นตอน {step} รอยืนยัน",
"taskListResume": "รายการงาน / ดำเนินการต่อ",
"retryPendingTasks": "ลองงานที่กู้คืนได้ในชุดงานปัจจุบันอีกครั้ง",
"retryPendingDone": "ส่งงานที่กู้คืนได้ใหม่แล้ว",
"retryFailed": "ลองใหม่ไม่สำเร็จ",
"retrying": "กำลังลองใหม่...",
"taskListTitle": "รายการงาน",
"taskListHint": "เมื่อสลับงาน Stepper ด้านบนและการดำเนินการจะอัปเดตพร้อมกัน",
"expandTaskList": "ขยายรายการ",
"collapseTaskList": "ย่อรายการ",
"currentFocus": "โฟกัสปัจจุบัน →",
"expandTaskList": "ขยายรายการงาน",
"collapseTaskList": "ย่อรายการงาน",
"currentFocus": "โฟกัสปัจจุบัน:",
"currentFocusDefaultReason": "ข้อความที่ป้อนจะมีผลกับงานนี้",
"focusInputPlaceholder": "กำลังจัดการ {taskId} พิมพ์คำสั่ง...",
"clearFocus": "ยกเลิกโฟกัส",
"runningState": "กำลังดำเนินการ",
"pendingState": "รอยืนยัน",
"completedState": "เสร็จแล้ว",
@@ -100,13 +192,13 @@
"nextTask": "ถัดไป",
"collapseTasks": "ซ่อนงาน",
"viewTasks": "ดูงาน",
"inventoryTaskPickTitle": "เลือกงานเป้าหมายของสต็อก",
"inventoryTaskPickHint": "ชุดงานนี้มีหลายงาน เพื่อป้องกันการอัปโหลดผิดงาน โปรดเลือกก่อนว่าสต็อกนี้เป็นของงานใด",
"inventoryTaskPickPendingHint": "ชุดงานนี้มีหลายงาน เพื่อป้องกันการอัปโหลดผิดงาน โปรดเลือกงานเป้าหมายก่อน แล้วระบบจะอัปโหลดไฟล์สต็อกที่เพิ่งเลือกต่อให้",
"inventoryTaskPickTitle": "สแนปช็อตสต็อกของชุดงาน",
"inventoryTaskPickHint": "ชุดงานนี้มีหลายงาน ไฟล์สต็อกจะถูกอัปโหลดเป็นสแนปช็อตเดียวของชุดงาน แล้วแต่ละงานจะจับคู่แยกกัน",
"inventoryTaskPickPendingHint": "ชุดงานนี้มีหลายงาน ไฟล์สต็อกที่รออยู่จะถูกอัปโหลดเป็นสแนปช็อตเดียวของชุดงาน แล้วแต่ละงานจะจับคู่แยกกัน",
"cancelInventoryTaskPick": "ยกเลิก",
"uploadInventoryToTask": "อัปโหลดไปงานนี้",
"inventoryTargetTask": "เป้าหมายสต็อก {taskId}",
"inventoryTargetIdle": "รอเลือกงานเป้าหมาย",
"uploadInventoryToTask": "อัปโหลดสต็อกชุดงาน",
"inventoryTargetTask": "ทางเข้าสต็อกชุดงาน {taskId}",
"inventoryTargetIdle": "รอสต็อกของชุดงาน",
"fileCount": "จำนวนไฟล์",
"runningCount": "กำลังดำเนินการ",
"completedCount": "เสร็จแล้ว",
@@ -141,13 +233,13 @@
},
"matchStatus": {
"fulfillable": "จัดส่งได้ครบ",
"partial": "จัดส่งได้บางส่วน",
"partial": "มีสต็อกขาด",
"unfulfillable": "จัดส่งไม่ได้",
"pending": "รอจับคู่"
},
"rowStatus": {
"ok": "เพียงพอ",
"partial": "บางส่วน",
"partial": "ขาด",
"shortage": "ขาด"
},
"stepper": {
+102 -14
View File
@@ -13,15 +13,45 @@
"loadingAgent": "正在加载应用...",
"thinking": "正在生成回答...",
"disclaimer": "AI 可能会犯错,请核实重要信息。",
"scrollToLatest": "滚动到最新消息",
"createNewChat": "创建新对话",
"shippingNoticeContinue": "请继续处理发货任务 {taskId}。该任务已存在,禁止调用 create_task。请先调用 get_task_status(task_id={taskId})查询当前状态并告知我下一步。",
"shippingNoticeContinue": "请继续处理发货任务 {taskId}。先读取当前任务状态;如果仍待解析,请解析发货通知并保存结果;如果已进入后续步骤,请直接说明当前进度和下一步。",
"shippingNoticeActionsHint": "请选择操作:",
"shippingNoticeMissingTaskId": "未找到任务编号,请先完成发货通知解析。",
"shippingNoticeUploadDone": "库存文件已上传:{fileName}。",
"shippingNoticeUploadOk": "上传成功。",
"shippingNoticeUploadFailed": "库存文件上传失败。",
"shippingNoticeRefreshDone": "已刷新当前任务状态。",
"shippingNoticeRetryUploadAction": "重试上传货代",
"shippingNoticeRetryUploadQueued": "已重新触发上传,请稍后刷新查看结果。",
"shippingNoticeRetryUploadFailed": "重试上传失败。",
"shippingNoticePasteHint": "请在输入框粘贴库存小表内容后发送。",
"shippingNoticeDecisionDone": "操作已完成。",
"shippingNoticePrompt": {
"inventory": {
"prefix": "我已上传库存文件",
"prefixWithFile": "我已上传库存文件《{fileName}》",
"prefixBatch": "我已为批次 {batchNo} 上传本批库存快照",
"prefixBatchWithFile": "我已为批次 {batchNo} 上传本批库存快照《{fileName}》",
"mapInferSuggested": "{prefix}。请继续处理库存列映射;如果系统已识别出完整映射,请直接应用映射,并展示字段对齐结果给我确认。",
"mapInferPending": "{prefix}。请继续解析库存列映射,并在拿到可用映射后展示字段对齐结果给我确认。",
"alignReview": "{prefix}。请展示库存字段对齐结果,并引导我确认或更正映射。",
"default": "{prefix}。请继续处理库存导入,并告诉我下一步。"
},
"notice": {
"fileLabelSingleFile": "《{fileName}》",
"fileLabelMulti": "{fileCount} 份发货通知",
"fileLabelDefault": "发货通知",
"uploadedPrefix": "我已上传{fileLabel}",
"batchLabel": "批次 {batchNo}",
"taskLabel": "当前任务 {taskId}",
"taskList": "任务列表:{taskIds}。",
"autoInventoryAction": "上传库存并进入字段对齐",
"autoNoticeAction": "创建任务并解析发货通知",
"multiTask": "{summary}。{taskListText}请只处理当前焦点任务。先读取当前任务状态;如果仍待解析,请解析发货通知并保存结果;如果已进入后续步骤,请直接说明当前进度和下一步。不要再次询问我是否开始解析,也不要整批循环处理其他任务。",
"singleTask": "{summary}。请先读取当前任务状态;如果仍待解析,请解析发货通知并保存结果;如果已进入后续步骤,请直接说明当前进度和下一步。不要再次询问我是否开始解析。"
}
},
"shippingNoticeMapping": {
"inventoryHeaders": "库存表头",
"headerRow": "表头行:{row}",
@@ -70,7 +100,7 @@
"inventoryAvailable": "库存可用",
"shortageQty": "缺口",
"statusLabel": "状态",
"shortageBanner": "存在库存缺口,当前不能直接继续上传货代。请先处理缺口,或按可用按钮确认部分发货 / 重新匹配。",
"shortageBanner": "存在库存缺口,当前不能继续上传货代。请先处理缺口,或按可用按钮重新匹配 / 返回修订。",
"shortageDetails": "缺口明细",
"shortageRowDetail": "第 {index} 行:预订单号 {reservationId},料号 {sku},缺口 {shortage}",
"availableActions": "可用操作",
@@ -81,21 +111,79 @@
"batchProgress": "第 {index}/{total} 票",
"batchCurrentIndex": "当前处理第 {index}/{total} 票",
"batchSummaryLine": "本批 {total} 笔 · 已完成 {completed} · 进行中 {running} · 待处理 {pending}",
"conversationWorkspaceTitle": "Agent 会话执行摘要",
"conversationSummaryLine": "{batches} 个批次 · {total} 票任务 · {completed} 完成 · {running} 执行中 · {abnormal} 需介入",
"batchChromeSummary": "{total} 票任务,{completed} 完成,{running} 执行中,{abnormal} 需介入",
"agentExecutionSummary": "Agent 执行摘要",
"workspaceSubtitle": "{batches} 个批次 · {total} 票任务,{completed} 已完成,{abnormal} 需要介入",
"noBlockingTasks": "当前批次没有阻断任务,已完成或正在自动归档。",
"focusTaskRecommendation": "建议先聚焦此单,确认阻断原因后再继续批次内恢复。",
"focusThisTask": "修正此单",
"showWorkspace": "批次工作台",
"hideWorkspace": "隐藏工作台",
"batchWorkspaceTitle": "批次工作台",
"batchWorkspaceSubtitle": "多批次切换、筛选与步骤诊断",
"batchActionsTitle": "批量操作",
"retryFailedTasks": "重试所有失败",
"batchActionSafetyNotice": "待人工任务不会被批量重试;已完成任务不会重复上传。批量恢复仅处理失败或排队任务。",
"taskDetailCount": "任务明细 ({count})",
"filterAll": "全部",
"filterAbnormal": "异常 ({count})",
"filterCompleted": "完成 ({count})",
"emptyFilteredTasks": "暂无相关任务",
"focusRepair": "聚焦修正",
"queryShortageDetails": "查询缺口明细",
"retrySingleTask": "单独重试",
"retrySingleTaskMessage": "重试当前任务 {taskId}",
"viewDetail": "查看明细",
"mobileWorkspaceHint": "移动端工作台已打开,请在任务列表中选择要处理的单票。",
"diagnosisAdviceRetryOrFocus": "建议先聚焦此单查看上下文;若属于外部系统临时失败,可单独重试。",
"diagnosisUploadFailedTitle": "上传货代系统失败,未收到成功回执。",
"diagnosisUploadFailedAdvice": "建议单独重试;若连续失败,请检查货代系统登录状态、字段格式或人工上传。",
"diagnosisShortageTitle": "库存匹配存在缺口,当前不能直接生成完整发货。",
"diagnosisShortageAdvice": "系统已阻断后续发货,请按下方缺口明细补库存或修正通知单后重新匹配。",
"diagnosisShortageLine": "第 {index} 行:预订单号 {reservationId},料号 {sku},需求 {required},可用 {available},缺口 {shortage}",
"diagnosisShortageAdviceWithLines": "缺口明细:{lines}。请补库存或修正通知单后重新匹配。",
"shortageDetailsMessageTitle": "任务 {taskId}({file})的库存缺口明细:",
"shortageNoDetails": "任务 {taskId} 当前未发现库存缺口。",
"diagnosisInventoryRpaTitle": "库存 RPA 未返回可用库存快照。",
"diagnosisInventoryRpaAdvice": "建议先重试库存抓取;若外部系统不可用,可人工上传库存文件。",
"diagnosisAlignReviewTitle": "库存字段映射需要人工确认。",
"diagnosisAlignReviewAdvice": "建议确认 SKU、Reservation ID、可用数量等列映射,避免匹配错料。",
"diagnosisParseReviewTitle": "通知单解析置信度不足,需要复核单头或明细。",
"diagnosisParseReviewAdvice": "建议核对客户、PO、需求日期和订单行后再继续。",
"diagnosisReservationRequiredTitle": "缺少 Reservation ID,无法按预订单锁定库存。",
"diagnosisReservationRequiredAdvice": "建议补充 Reservation ID,或确认该客户允许不带预订单处理。",
"diagnosisInventoryWaitingTitle": "等待库存文件或库存入口确认。",
"diagnosisInventoryWaitingAdvice": "建议上传本批库存快照,或确认系统自动抓取入口。",
"diagnosisCompletedTitle": "任务已完成并归档。",
"diagnosisCompletedAdvice": "无需处理;如需核验可查看导出文件或上传回执。",
"diagnosisStepWaitingTitle": "步骤 {step} 正在等待前置条件。",
"diagnosisStepWaitingAdvice": "建议保持在工作台观察,必要时聚焦此单查看上下文。",
"currentTaskDiagnosis": "当前任务诊断",
"currentTaskPosition": "第 {index}/{total} 票",
"batchTabAbnormal": "{completed} 完成 · {abnormal} 异常",
"batchTabNormal": "{total} 票全部正常",
"interventionQueue": "需介入任务",
"needsIntervention": "需介入",
"currentNotice": "当前通知",
"currentStepLabel": "当前",
"stepHeadline": "步骤 {current}/{total} · {label}",
"stepFraction": "步骤 {current}/{total}",
"stepNeedsConfirm": "步骤 {step} 待确认",
"taskListResume": "任务列表 / 续办",
"retryPendingTasks": "重试未完成票",
"retryPendingTasks": "重试当前批次可恢复任务",
"retryPendingDone": "已重新提交未完成票",
"retryFailed": "重试失败",
"retrying": "重试中...",
"taskListTitle": "任务列表",
"taskListHint": "切换任务后,对话顶部 Stepper 与操作同步更新",
"expandTaskList": "展开列表",
"collapseTaskList": "收起列表",
"currentFocus": "当前聚焦 →",
"expandTaskList": "展开任务列表",
"collapseTaskList": "收起任务列表",
"currentFocus": "当前聚焦:",
"currentFocusDefaultReason": "输入内容将作用于该单票任务",
"focusInputPlaceholder": "正在处理 {taskId},输入指令...",
"clearFocus": "取消聚焦",
"runningState": "进行中",
"pendingState": "待确认",
"completedState": "已完成",
@@ -104,13 +192,13 @@
"nextTask": "下一票",
"collapseTasks": "收起任务",
"viewTasks": "查看任务",
"inventoryTaskPickTitle": "请选择库存归属任务",
"inventoryTaskPickHint": "当前批次包含多票。为避免串单,请先明确选择库存要上传到哪一票。",
"inventoryTaskPickPendingHint": "当前批次包含多票。为避免串单,请先选择库存归属任务,系统会在选定后继续上传刚才的库存文件。",
"inventoryTaskPickTitle": "本批库存快照",
"inventoryTaskPickHint": "当前批次包含多票。库存文件将作为本批统一快照,后续每票独立匹配。",
"inventoryTaskPickPendingHint": "当前批次包含多票。系统会把刚才的库存文件作为本批统一快照上传,并由每票独立匹配。",
"cancelInventoryTaskPick": "取消选择",
"uploadInventoryToTask": "上传库存到此票",
"inventoryTargetTask": "库存目标 {taskId}",
"inventoryTargetIdle": "等待选择库存目标",
"uploadInventoryToTask": "上传为本批库存",
"inventoryTargetTask": "本批库存入口 {taskId}",
"inventoryTargetIdle": "等待上传本批库存",
"fileCount": "文件数",
"runningCount": "处理中",
"completedCount": "已完成",
@@ -145,13 +233,13 @@
},
"matchStatus": {
"fulfillable": "可全部发货",
"partial": "部分满足",
"partial": "存在缺口",
"unfulfillable": "无法满足",
"pending": "待匹配"
},
"rowStatus": {
"ok": "充足",
"partial": "部分满足",
"partial": "缺口",
"shortage": "缺口"
},
"stepper": {
+106 -14
View File
@@ -1,6 +1,6 @@
{
"defaultTitle": "對話",
"assistantLabel": "HXOPS AI 助手",
"assistantLabel": "AI 助手",
"placeholder": "請輸入問題...",
"history": "歷史記錄",
"noHistory": "暫無歷史記錄",
@@ -13,15 +13,45 @@
"loadingAgent": "正在加載應用...",
"thinking": "正在生成回答...",
"disclaimer": "AI 可能會犯錯,請核實重要信息。",
"scrollToLatest": "捲動到最新消息",
"createNewChat": "建立新對話",
"shippingNoticeContinue": "請繼續處理發貨任務 {taskId}。請先呼叫 get_task_status,再告訴我下一步。",
"shippingNoticeContinue": "請繼續處理發貨任務 {taskId}。先讀取目前任務狀態;如果仍待解析,請解析發貨通知並儲存結果;如果已進入後續步驟,請直接說明目前進度和下一步。",
"shippingNoticeActionsHint": "請選擇操作:",
"shippingNoticeMissingTaskId": "找不到任務編號,請先完成發貨通知解析。",
"shippingNoticeUploadDone": "庫存檔案已上傳:{fileName}。",
"shippingNoticeUploadOk": "上傳成功。",
"shippingNoticeUploadFailed": "庫存檔案上傳失敗。",
"shippingNoticeRefreshDone": "已重新整理目前任務狀態。",
"shippingNoticeRetryUploadAction": "重試上傳貨代",
"shippingNoticeRetryUploadQueued": "已重新觸發上傳,請稍後重新整理查看結果。",
"shippingNoticeRetryUploadFailed": "重試上傳失敗。",
"shippingNoticePasteHint": "請在輸入框貼上庫存小表內容後送出。",
"shippingNoticeDecisionDone": "操作已完成。",
"shippingNoticePrompt": {
"inventory": {
"prefix": "我已上傳庫存檔案",
"prefixWithFile": "我已上傳庫存檔案《{fileName}》",
"prefixBatch": "我已為批次 {batchNo} 上傳本批庫存快照",
"prefixBatchWithFile": "我已為批次 {batchNo} 上傳本批庫存快照《{fileName}》",
"mapInferSuggested": "{prefix}。請繼續處理庫存欄位映射;如果系統已辨識出完整映射,請直接套用映射,並展示欄位對齊結果給我確認。",
"mapInferPending": "{prefix}。請繼續解析庫存欄位映射,並在取得可用映射後展示欄位對齊結果給我確認。",
"alignReview": "{prefix}。請展示庫存欄位對齊結果,並引導我確認或更正映射。",
"default": "{prefix}。請繼續處理庫存匯入,並告訴我下一步。"
},
"notice": {
"fileLabelSingleFile": "《{fileName}》",
"fileLabelMulti": "{fileCount} 份發貨通知",
"fileLabelDefault": "發貨通知",
"uploadedPrefix": "我已上傳{fileLabel}",
"batchLabel": "批次 {batchNo}",
"taskLabel": "當前任務 {taskId}",
"taskList": "任務列表:{taskIds}。",
"autoInventoryAction": "上傳庫存並進入欄位對齊",
"autoNoticeAction": "建立任務並解析發貨通知",
"multiTask": "{summary}。{taskListText}請只處理目前焦點任務。先讀取目前任務狀態;如果仍待解析,請解析發貨通知並儲存結果;如果已進入後續步驟,請直接說明目前進度和下一步。不要再次詢問我是否開始解析,也不要整批迴圈處理其他任務。",
"singleTask": "{summary}。請先讀取目前任務狀態;如果仍待解析,請解析發貨通知並儲存結果;如果已進入後續步驟,請直接說明目前進度和下一步。不要再次詢問我是否開始解析。"
}
},
"shippingNoticeMapping": {
"inventoryHeaders": "庫存表頭",
"headerRow": "表頭列:{row}",
@@ -70,7 +100,7 @@
"inventoryAvailable": "庫存可用",
"shortageQty": "缺口",
"statusLabel": "狀態",
"shortageBanner": "存在庫存缺口,目前不能直接繼續上傳貨代。請先處理缺口,或依可用按鈕確認部分發貨 / 重新匹配。",
"shortageBanner": "存在庫存缺口,目前不能繼續上傳貨代。請先處理缺口,或依可用按鈕重新匹配 / 返回修訂。",
"shortageDetails": "缺口明細",
"shortageRowDetail": "第 {index} 行:預訂單號 {reservationId},料號 {sku},缺口 {shortage}",
"availableActions": "可用操作",
@@ -81,17 +111,79 @@
"batchProgress": "第 {index}/{total} 票",
"batchCurrentIndex": "當前處理第 {index}/{total} 票",
"batchSummaryLine": "本批 {total} 筆 · 已完成 {completed} · 進行中 {running} · 待處理 {pending}",
"conversationWorkspaceTitle": "Agent 會話執行摘要",
"conversationSummaryLine": "{batches} 個批次 · {total} 票任務 · {completed} 完成 · {running} 執行中 · {abnormal} 需介入",
"batchChromeSummary": "{total} 票任務,{completed} 完成,{running} 執行中,{abnormal} 需介入",
"agentExecutionSummary": "Agent 執行摘要",
"workspaceSubtitle": "{batches} 個批次 · {total} 票任務,{completed} 已完成,{abnormal} 需要介入",
"noBlockingTasks": "目前批次沒有阻斷任務,已完成或正在自動歸檔。",
"focusTaskRecommendation": "建議先聚焦此單,確認阻斷原因後再繼續批次內恢復。",
"focusThisTask": "修正此單",
"showWorkspace": "批次工作台",
"hideWorkspace": "隱藏工作台",
"batchWorkspaceTitle": "批次工作台",
"batchWorkspaceSubtitle": "多批次切換、篩選與步驟診斷",
"batchActionsTitle": "批量操作",
"retryFailedTasks": "重試所有失敗",
"batchActionSafetyNotice": "待人工任務不會被批量重試;已完成任務不會重複上傳。批量恢復僅處理失敗或排隊任務。",
"taskDetailCount": "任務明細 ({count})",
"filterAll": "全部",
"filterAbnormal": "異常 ({count})",
"filterCompleted": "完成 ({count})",
"emptyFilteredTasks": "暫無相關任務",
"focusRepair": "聚焦修正",
"queryShortageDetails": "查詢缺口明細",
"retrySingleTask": "單獨重試",
"retrySingleTaskMessage": "重試目前任務 {taskId}",
"viewDetail": "查看明細",
"mobileWorkspaceHint": "行動端工作台已開啟,請在任務列表中選擇要處理的單票。",
"diagnosisAdviceRetryOrFocus": "建議先聚焦此單查看上下文;若屬於外部系統暫時失敗,可單獨重試。",
"diagnosisUploadFailedTitle": "上傳貨代系統失敗,未收到成功回執。",
"diagnosisUploadFailedAdvice": "建議單獨重試;若連續失敗,請檢查貨代系統登入狀態、欄位格式或人工上傳。",
"diagnosisShortageTitle": "庫存匹配存在缺口,目前不能直接生成完整發貨。",
"diagnosisShortageAdvice": "系統已阻斷後續發貨,請按下方缺口明細補庫存或修正通知單後重新匹配。",
"diagnosisShortageLine": "第 {index} 行:預訂單號 {reservationId},料號 {sku},需求 {required},可用 {available},缺口 {shortage}",
"diagnosisShortageAdviceWithLines": "缺口明細:{lines}。請補庫存或修正通知單後重新匹配。",
"shortageDetailsMessageTitle": "任務 {taskId}({file})的庫存缺口明細:",
"shortageNoDetails": "任務 {taskId} 目前未發現庫存缺口。",
"diagnosisInventoryRpaTitle": "庫存 RPA 未返回可用庫存快照。",
"diagnosisInventoryRpaAdvice": "建議先重試庫存抓取;若外部系統不可用,可人工上傳庫存檔。",
"diagnosisAlignReviewTitle": "庫存欄位映射需要人工確認。",
"diagnosisAlignReviewAdvice": "建議確認 SKU、Reservation ID、可用數量等欄位映射,避免匹配錯料。",
"diagnosisParseReviewTitle": "通知單解析信心不足,需要覆核單頭或明細。",
"diagnosisParseReviewAdvice": "建議核對客戶、PO、需求日期和訂單行後再繼續。",
"diagnosisReservationRequiredTitle": "缺少 Reservation ID,無法按預訂單鎖定庫存。",
"diagnosisReservationRequiredAdvice": "建議補充 Reservation ID,或確認該客戶允許不帶預訂單處理。",
"diagnosisInventoryWaitingTitle": "等待庫存檔案或庫存入口確認。",
"diagnosisInventoryWaitingAdvice": "建議上傳本批庫存快照,或確認系統自動抓取入口。",
"diagnosisCompletedTitle": "任務已完成並歸檔。",
"diagnosisCompletedAdvice": "無需處理;如需核驗可查看匯出檔或上傳回執。",
"diagnosisStepWaitingTitle": "步驟 {step} 正在等待前置條件。",
"diagnosisStepWaitingAdvice": "建議保持在工作台觀察,必要時聚焦此單查看上下文。",
"currentTaskDiagnosis": "目前任務診斷",
"currentTaskPosition": "第 {index}/{total} 票",
"batchTabAbnormal": "{completed} 完成 · {abnormal} 異常",
"batchTabNormal": "{total} 票全部正常",
"interventionQueue": "需介入任務",
"needsIntervention": "需介入",
"currentNotice": "當前通知",
"currentStepLabel": "目前",
"stepHeadline": "步驟 {current}/{total} · {label}",
"stepFraction": "步驟 {current}/{total}",
"stepNeedsConfirm": "步驟 {step} 待確認",
"taskListResume": "任務列表 / 續辦",
"retryPendingTasks": "重試目前批次可恢復任務",
"retryPendingDone": "已重新提交可恢復任務",
"retryFailed": "重試失敗",
"retrying": "重試中...",
"taskListTitle": "任務列表",
"taskListHint": "切換任務後,對話頂部 Stepper 與操作會同步更新",
"expandTaskList": "展開列表",
"collapseTaskList": "收起列表",
"currentFocus": "目前聚焦 →",
"expandTaskList": "展開任務列表",
"collapseTaskList": "收起任務列表",
"currentFocus": "目前聚焦:",
"currentFocusDefaultReason": "輸入內容將作用於該單票任務",
"focusInputPlaceholder": "正在處理 {taskId},輸入指令...",
"clearFocus": "取消聚焦",
"runningState": "進行中",
"pendingState": "待確認",
"completedState": "已完成",
@@ -100,13 +192,13 @@
"nextTask": "下一票",
"collapseTasks": "收起任務",
"viewTasks": "查看任務",
"inventoryTaskPickTitle": "請選擇庫存歸屬任務",
"inventoryTaskPickHint": "當前批次包含多票。為避免串單,請先明確選擇庫存要上傳到哪一票。",
"inventoryTaskPickPendingHint": "當前批次包含多票。為避免串單,請先選擇庫存歸屬任務,系統會在選定後繼續上傳剛才的庫存檔案。",
"inventoryTaskPickTitle": "本批庫存快照",
"inventoryTaskPickHint": "當前批次包含多票。庫存檔案將作為本批統一快照,後續每票獨立匹配。",
"inventoryTaskPickPendingHint": "當前批次包含多票。系統會把剛才的庫存檔案作為本批統一快照上傳,並由每票獨立匹配。",
"cancelInventoryTaskPick": "取消選擇",
"uploadInventoryToTask": "上傳庫存到此票",
"inventoryTargetTask": "庫存目標 {taskId}",
"inventoryTargetIdle": "等待選擇庫存目標",
"uploadInventoryToTask": "上傳為本批庫存",
"inventoryTargetTask": "本批庫存入口 {taskId}",
"inventoryTargetIdle": "等待上傳本批庫存",
"fileCount": "檔案數",
"runningCount": "處理中",
"completedCount": "已完成",
@@ -141,13 +233,13 @@
},
"matchStatus": {
"fulfillable": "可全部發貨",
"partial": "部分滿足",
"partial": "存在缺口",
"unfulfillable": "無法滿足",
"pending": "待匹配"
},
"rowStatus": {
"ok": "充足",
"partial": "部分滿足",
"partial": "缺口",
"shortage": "缺口"
},
"stepper": {
+63 -3
View File
@@ -29,9 +29,69 @@ python scripts/rpa/freight_rpa_worker.py
## 生产 RPA
`FREIGHT_RPA_MOCK=false` 时 worker **不会**自动处理触发文件,需业务按 SOP 用 UiPath / Power Automate 等:
`FREIGHT_RPA_MOCK=false` 时 worker 会尝试用 Playwright 打开货代网站并下载库存 Excel。首次使用需要在 RPA 终端安装浏览器驱动:
1. 监听 `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` 新 JSON → 登录货代 UI 导出库存 → 保存到 `FREIGHT_INVENTORY_DROP_DIR` → POST `inventory-ready`。
2. 监听 `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` → 读取 `file_path` 在货代 UI 上传 → POST `upload-complete`。
```powershell
pip install playwright
python -m playwright install chromium
```
可以使用两种登录方式:
1. 自动登录:RPA worker 从本机环境变量读取账号密码,打开库存源 URL 后如检测到登录页则自动填写。
2. 登录态复用:使用非 headless 模式先手工登录一次,登录态会保存在 `FREIGHT_RPA_BROWSER_PROFILE_DIR`。
账号密码不要写入 trigger JSON,也不要提交到代码仓库。建议配置为 Windows 用户级环境变量或企业凭据管理器注入的进程环境变量。
```powershell
$env:FREIGHT_RPA_MOCK = "false"
$env:FREIGHT_RPA_HEADLESS = "false"
$env:FREIGHT_RPA_BROWSER_PROFILE_DIR = "backend/data/freight_rpa/browser_profile"
$env:FREIGHT_RPA_DSV_USERNAME = "<DSV账号>"
$env:FREIGHT_RPA_DSV_PASSWORD = "<DSV密码>"
$env:FREIGHT_RPA_CRANE_USERNAME = "<Crane账号>"
$env:FREIGHT_RPA_CRANE_PASSWORD = "<Crane密码>"
python scripts/rpa/freight_rpa_worker.py
```
如果登录框默认识别不稳定,可覆盖登录 selector:
| 环境变量 | 用途 |
|---------|------|
| `FREIGHT_RPA_DSV_USERNAME_SELECTOR` | DSV 用户名输入框 |
| `FREIGHT_RPA_DSV_PASSWORD_SELECTOR` | DSV 密码输入框 |
| `FREIGHT_RPA_DSV_LOGIN_BUTTON_SELECTOR` | DSV 登录按钮 |
| `FREIGHT_RPA_CRANE_USERNAME_SELECTOR` | Crane 用户名输入框 |
| `FREIGHT_RPA_CRANE_PASSWORD_SELECTOR` | Crane 密码输入框 |
| `FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR` | Crane 登录按钮 |
若页面出现 MFA、验证码或 SSO 二次确认,worker 会失败并回调错误,需要人工处理后重试。
库存 trigger 需要包含 `rpa_inventory_source`,worker 会按 `source_type` 分发:
| source_type | Driver |
|-------------|--------|
| `dsv360` | 打开 DSV 360,进入 Reports / Program / Inventory 报表并下载 |
| `crane_footprint` | 打开 Crane FootPrint On Hand Details Query,选择 Owner/Project/Warehouse 后下载 |
页面控件如果默认可见文本无法稳定点击,可通过环境变量覆盖 selector:
| 环境变量 | 用途 |
|---------|------|
| `FREIGHT_RPA_DSV_REPORTS_SELECTOR` | DSV Reports 菜单 |
| `FREIGHT_RPA_DSV_PROGRAM_SELECTOR` | DSV Program 项 |
| `FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR` | DSV Inventory 分组 |
| `FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR` | DSV On Hand Inventory by Location |
| `FREIGHT_RPA_DSV_OWNER_SELECTOR` | DSV Owner 输入框 |
| `FREIGHT_RPA_DSV_EXPORT_SELECTOR` | DSV 导出按钮 |
| `FREIGHT_RPA_CRANE_OWNER_SELECTOR` | Crane Owner 下拉/输入 |
| `FREIGHT_RPA_CRANE_PROJECT_SELECTOR` | Crane Project 下拉/输入 |
| `FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR` | Crane Warehouse 下拉/输入 |
| `FREIGHT_RPA_CRANE_RUN_SELECTOR` | Crane Run Report 按钮 |
| `FREIGHT_RPA_CRANE_EXPORT_SELECTOR` | Crane 下载按钮 |
发货 Excel 上传仍保留原 PoC 行为:`FREIGHT_RPA_MOCK=false` 时不会自动上传,需后续实现上传 Driver 或接入 UiPath / Power Automate。
回调 Header:`X-Shipping-Tool-Key: <SHIPPING_NOTICE_TOOL_API_KEY>`。
+282 -6
View File
@@ -18,6 +18,10 @@ Optional:
FREIGHT_RPA_MOCK=true
FREIGHT_RPA_POLL_SECONDS=3
FREIGHT_RPA_SAMPLE_INVENTORY=path/to/sample.xlsx
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/freight_rpa/browser_profile
FREIGHT_RPA_HEADLESS=false
FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD
FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD
"""
from __future__ import annotations
@@ -30,6 +34,7 @@ import urllib.error
import urllib.request
from datetime import datetime
from pathlib import Path
from typing import Any
try:
from openpyxl import Workbook
@@ -105,6 +110,279 @@ def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
return dest
def _download_name(task_no: str, source_code: str, suffix: str = ".xlsx") -> str:
safe_source = "".join(ch for ch in source_code if ch.isalnum() or ch in {"-", "_"}) or "UNKNOWN"
stamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
return f"inventory_{task_no}_{safe_source}_{stamp}{suffix}"
def _require_playwright():
try:
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from playwright.sync_api import sync_playwright
except ImportError as exc:
raise RuntimeError(
"Playwright is required for real RPA. Install it on the RPA terminal with: "
"pip install playwright && python -m playwright install chromium"
) from exc
return sync_playwright, PlaywrightTimeoutError
def _browser_timeout_ms() -> int:
return max(5_000, int(_env("FREIGHT_RPA_BROWSER_TIMEOUT_MS", "60000") or "60000"))
def _click_text(page: Any, text: str, *, exact: bool = True) -> None:
page.get_by_text(text, exact=exact).click(timeout=_browser_timeout_ms())
def _click_selector_or_text(page: Any, selector_env: str, fallback_text: str | None = None) -> None:
selector = _env(selector_env)
if selector:
page.locator(selector).first.click(timeout=_browser_timeout_ms())
return
if fallback_text:
_click_text(page, fallback_text, exact=True)
return
raise RuntimeError(f"Missing selector env: {selector_env}")
def _fill_selector_or_label(page: Any, selector_env: str, label: str, value: str | None) -> None:
text = str(value or "").strip()
if not text:
return
selector = _env(selector_env)
if selector:
page.locator(selector).first.fill(text, timeout=_browser_timeout_ms())
return
page.get_by_label(label).fill(text, timeout=_browser_timeout_ms())
def _select_or_fill(page: Any, selector_env: str, label: str, value: str | None) -> None:
text = str(value or "").strip()
if not text:
return
selector = _env(selector_env)
locator = page.locator(selector).first if selector else page.get_by_label(label)
try:
locator.select_option(label=text, timeout=_browser_timeout_ms())
return
except Exception:
pass
try:
locator.select_option(value=text, timeout=_browser_timeout_ms())
return
except Exception:
pass
locator.fill(text, timeout=_browser_timeout_ms())
def _visible_locator(page: Any, selector: str | None):
if not selector:
return None
locator = page.locator(selector).first
try:
return locator if locator.is_visible(timeout=2_000) else None
except Exception:
return None
def _fill_login_field(page: Any, selector_env: str, value_env: str, fallback_selectors: tuple[str, ...]) -> bool:
value = _env(value_env)
if not value:
return False
selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item)
for selector in selectors:
locator = _visible_locator(page, selector)
if locator is None:
continue
locator.fill(value, timeout=_browser_timeout_ms())
return True
return False
def _click_login_submit(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool:
selector = _env(selector_env)
locator = _visible_locator(page, selector)
if locator is not None:
locator.click(timeout=_browser_timeout_ms())
return True
for text in fallback_texts:
try:
page.get_by_role("button", name=text).click(timeout=3_000)
return True
except Exception:
pass
try:
page.get_by_text(text, exact=True).click(timeout=3_000)
return True
except Exception:
pass
return False
def _maybe_auto_login(page: Any, prefix: str) -> None:
"""
如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。
"""
username_env = f"FREIGHT_RPA_{prefix}_USERNAME"
password_env = f"FREIGHT_RPA_{prefix}_PASSWORD"
if not _env(username_env) or not _env(password_env):
return
user_filled = _fill_login_field(
page,
f"FREIGHT_RPA_{prefix}_USERNAME_SELECTOR",
username_env,
(
'input[name="username"]',
'input[name="userName"]',
'input[name="email"]',
'input[type="email"]',
'input[type="text"]',
),
)
password_filled = _fill_login_field(
page,
f"FREIGHT_RPA_{prefix}_PASSWORD_SELECTOR",
password_env,
('input[name="password"]', 'input[type="password"]'),
)
if not user_filled and not password_filled:
return
if user_filled != password_filled:
raise RuntimeError(f"{prefix} login form partially detected; please configure login selectors")
if not _click_login_submit(
page,
f"FREIGHT_RPA_{prefix}_LOGIN_BUTTON_SELECTOR",
("Sign in", "Login", "Log in", "登录"),
):
raise RuntimeError(f"{prefix} login fields detected but submit button was not found")
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
raise RuntimeError(f"{prefix} login did not complete; MFA/SSO/manual verification may be required")
def _save_download(download: Any, drop_dir: Path, task_no: str, source_code: str) -> Path:
suggested = str(download.suggested_filename or "")
suffix = Path(suggested).suffix or ".xlsx"
dest = drop_dir / _download_name(task_no, source_code, suffix=suffix)
download.save_as(str(dest))
return dest
def _open_browser(download_dir: Path):
sync_playwright, _timeout = _require_playwright()
playwright = sync_playwright().start()
profile = _env("FREIGHT_RPA_BROWSER_PROFILE_DIR")
if not profile:
profile = str(Path(__file__).resolve().parents[2] / "backend" / "data" / "freight_rpa" / "browser_profile")
profile_dir = Path(profile)
profile_dir.mkdir(parents=True, exist_ok=True)
headless = _env("FREIGHT_RPA_HEADLESS", "false").lower() == "true"
context = playwright.chromium.launch_persistent_context(
str(profile_dir),
headless=headless,
accept_downloads=True,
downloads_path=str(download_dir),
)
page = context.pages[0] if context.pages else context.new_page()
page.set_default_timeout(_browser_timeout_ms())
return playwright, context, page
def _download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
query = source.get("query") if isinstance(source.get("query"), dict) else {}
entry_url = str(source.get("entry_url") or "").strip()
if not entry_url:
raise RuntimeError("DSV360 inventory source missing entry_url")
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
_maybe_auto_login(page, "DSV")
_click_selector_or_text(page, "FREIGHT_RPA_DSV_REPORTS_SELECTOR", "Reports")
_click_selector_or_text(
page,
"FREIGHT_RPA_DSV_PROGRAM_SELECTOR",
str(query.get("program_label") or ""),
)
_click_selector_or_text(
page,
"FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR",
str(query.get("report_group") or "Inventory"),
)
_click_selector_or_text(
page,
"FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR",
str(query.get("report_name") or "On Hand Inventory by Location"),
)
_fill_selector_or_label(page, "FREIGHT_RPA_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"))
_fill_selector_or_label(page, "FREIGHT_RPA_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"))
export_selector = _env("FREIGHT_RPA_DSV_EXPORT_SELECTOR")
export_text = _env("FREIGHT_RPA_DSV_EXPORT_TEXT", "file_download")
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
if export_selector:
page.locator(export_selector).first.click(timeout=_browser_timeout_ms())
else:
try:
_click_text(page, export_text, exact=True)
except Exception:
_click_text(page, "Download", exact=True)
return download_info.value
def _download_crane_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
query = source.get("query") if isinstance(source.get("query"), dict) else {}
entry_url = str(source.get("entry_url") or "").strip()
if not entry_url:
raise RuntimeError("Crane inventory source missing entry_url")
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
_maybe_auto_login(page, "CRANE")
_select_or_fill(page, "FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code"))
_select_or_fill(page, "FREIGHT_RPA_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code"))
_select_or_fill(page, "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR", "Choose Warehouse ..", query.get("warehouse_code"))
_click_selector_or_text(page, "FREIGHT_RPA_CRANE_RUN_SELECTOR", "Run Report")
export_selector = _env("FREIGHT_RPA_CRANE_EXPORT_SELECTOR")
export_text = _env("FREIGHT_RPA_CRANE_EXPORT_TEXT", "file_download")
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
if export_selector:
page.locator(export_selector).first.click(timeout=_browser_timeout_ms())
else:
_click_text(page, export_text, exact=True)
return download_info.value
def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) -> Path:
task_no = str(trigger.get("task_no") or "").strip()
source = trigger.get("rpa_inventory_source")
if not isinstance(source, dict):
raise RuntimeError("inventory trigger missing rpa_inventory_source")
source_type = str(source.get("source_type") or "").strip()
source_code = str(source.get("source_code") or "").strip() or source_type or "UNKNOWN"
if not source_type:
raise RuntimeError("inventory source missing source_type")
playwright = context = None
try:
playwright, context, page = _open_browser(drop_dir)
if source_type == "dsv360":
download = _download_dsv360_inventory(page, trigger, source)
elif source_type == "crane_footprint":
download = _download_crane_inventory(page, trigger, source)
else:
raise RuntimeError(f"unsupported inventory source_type: {source_type}")
return _save_download(download, drop_dir, task_no, source_code)
finally:
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
task_no = str(body.get("task_no") or "").strip()
@@ -114,21 +392,19 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
return
mock = _env("FREIGHT_RPA_MOCK", "true").lower() == "true"
if not mock:
print(f"[inventory] real RPA not implemented; trigger kept: {trigger_path.name}")
return
try:
out_file = _write_sample_inventory(drop_dir, task_no)
out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir)
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
"success": True,
"file_path": str(out_file),
"source_code": ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else None),
})
processed_dir.mkdir(parents=True, exist_ok=True)
done = processed_dir / trigger_path.name
trigger_path.replace(done)
print(f"[inventory] mock export done for {task_no} -> {out_file.name}")
mode = "mock" if mock else "browser"
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
except Exception as exc:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,