feat(chat): 更新发货任务处理逻辑和界面文本
- 移除不必要的状态引用 - 更新上传处理提示文本,使用国际化支持 - 扩展发货任务摘要接口,增加错误信息和短缺信息 - 更新多语言支持的文本,改善用户体验 - 增加批次工作区的汇总信息和操作提示
This commit is contained in:
1 parent
0b083cfdbd
commit
1fc9976ca3
60 files changed
+3819
-582
No files matched your search
@@ -49,9 +49,12 @@ frontend/package-lock.json
|
|||||||
.vscode/*
|
.vscode/*
|
||||||
!.vscode/settings.json
|
!.vscode/settings.json
|
||||||
!.vscode/extensions.json
|
!.vscode/extensions.json
|
||||||
|
.trae/*
|
||||||
|
.cursor/*
|
||||||
.idea/
|
.idea/
|
||||||
*.swp
|
*.swp
|
||||||
*.swo
|
*.swo
|
||||||
|
.cursorrules
|
||||||
|
|
||||||
# Runtime files
|
# Runtime files
|
||||||
.run/
|
.run/
|
||||||
@@ -79,3 +82,4 @@ oracle_client/
|
|||||||
backend/data/kb/
|
backend/data/kb/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
backend/data/fixed_assets/manifest.json
|
backend/data/fixed_assets/manifest.json
|
||||||
|
backend/data/shipping_notice/
|
||||||
Vendored
+25
-1
@@ -4,6 +4,29 @@
|
|||||||
"python.terminal.activateEnvironment": true,
|
"python.terminal.activateEnvironment": true,
|
||||||
"python.venvPath": "${workspaceFolder}/backend",
|
"python.venvPath": "${workspaceFolder}/backend",
|
||||||
"python.venvFolders": [".venv"],
|
"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
|
// 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv
|
||||||
"terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)",
|
"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' }"
|
"Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
"js/ts.tsdk.path": "node_modules\\typescript\\lib"
|
||||||
}
|
}
|
||||||
+47
-4
@@ -38,6 +38,7 @@ from app.core.errors import (
|
|||||||
chat_bp = Blueprint('chat', __name__)
|
chat_bp = Blueprint('chat', __name__)
|
||||||
|
|
||||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||||
|
SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent'
|
||||||
|
|
||||||
|
|
||||||
def _can_use_leave_feature(agent_proxy) -> bool:
|
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 '')
|
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:
|
def _serialize_session(session: ChatSession) -> dict:
|
||||||
last_active = session.last_active_at or session.created_at
|
last_active = session.last_active_at or session.created_at
|
||||||
return {
|
return {
|
||||||
@@ -909,9 +932,23 @@ def get_chat_messages():
|
|||||||
).order_by(ChatLog.created_at.asc()).all()
|
).order_by(ChatLog.created_at.asc()).all()
|
||||||
|
|
||||||
messages = []
|
messages = []
|
||||||
|
agent_name = str(getattr(g.current_agent, 'name', '') or '').strip()
|
||||||
for log in logs:
|
for log in logs:
|
||||||
if log.query:
|
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 = {
|
assistant_msg = {
|
||||||
'role': 'assistant',
|
'role': 'assistant',
|
||||||
'content': log.answer,
|
'content': log.answer,
|
||||||
@@ -940,10 +977,14 @@ def save_local_message():
|
|||||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
conversation_id = (data.get('conversation_id') or '').strip()
|
conversation_id = (data.get('conversation_id') or '').strip()
|
||||||
|
role = (data.get('role') or 'assistant').strip()
|
||||||
message_type = data.get('type')
|
message_type = data.get('type')
|
||||||
content = data.get('content', '')
|
content = data.get('content', '')
|
||||||
payload = data.get('payload')
|
payload = data.get('payload')
|
||||||
user_query = data.get('query', '')
|
user_query = data.get('query', '')
|
||||||
|
if role == 'user':
|
||||||
|
user_query = user_query or content
|
||||||
|
content = ''
|
||||||
|
|
||||||
if not message_type:
|
if not message_type:
|
||||||
raise ValidationError('type is required')
|
raise ValidationError('type is required')
|
||||||
@@ -1074,6 +1115,7 @@ def chat_completions():
|
|||||||
"""
|
"""
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
query = data.get('query')
|
query = data.get('query')
|
||||||
|
display_query = str(data.get('display_query') or query or '').strip()
|
||||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||||
conversation_id = data.get('conversation_id')
|
conversation_id = data.get('conversation_id')
|
||||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||||
@@ -1117,7 +1159,7 @@ def chat_completions():
|
|||||||
user_id,
|
user_id,
|
||||||
agent_id,
|
agent_id,
|
||||||
existing_session.session_id,
|
existing_session.session_id,
|
||||||
title=query,
|
title=display_query,
|
||||||
status='running',
|
status='running',
|
||||||
)
|
)
|
||||||
external_conversation_id = session.external_conversation_id
|
external_conversation_id = session.external_conversation_id
|
||||||
@@ -1126,13 +1168,13 @@ def chat_completions():
|
|||||||
user_id,
|
user_id,
|
||||||
agent_id,
|
agent_id,
|
||||||
conversation_id,
|
conversation_id,
|
||||||
title=query,
|
title=display_query,
|
||||||
status='running',
|
status='running',
|
||||||
external_conversation_id=conversation_id,
|
external_conversation_id=conversation_id,
|
||||||
)
|
)
|
||||||
external_conversation_id = session.external_conversation_id
|
external_conversation_id = session.external_conversation_id
|
||||||
else:
|
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
|
normalized_files: list[dict] | None = None
|
||||||
if files is not None:
|
if files is not None:
|
||||||
@@ -1246,6 +1288,7 @@ def chat_completions():
|
|||||||
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
||||||
files=normalized_files,
|
files=normalized_files,
|
||||||
inputs=dify_inputs,
|
inputs=dify_inputs,
|
||||||
|
display_query=display_query,
|
||||||
)
|
)
|
||||||
|
|
||||||
def relay_stream():
|
def relay_stream():
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ from app.services.shipping_notice.constants import (
|
|||||||
from app.services.shipping_notice.query_service import (
|
from app.services.shipping_notice.query_service import (
|
||||||
EXPORT_MIME_TYPE,
|
EXPORT_MIME_TYPE,
|
||||||
get_batch_for_user,
|
get_batch_for_user,
|
||||||
|
get_conversation_batch_workspace,
|
||||||
get_focus_task_for_batch,
|
get_focus_task_for_batch,
|
||||||
get_task_for_user,
|
get_task_for_user,
|
||||||
list_batches_for_user,
|
list_batches_for_user,
|
||||||
@@ -67,6 +68,12 @@ def workspace_shipping_batches():
|
|||||||
limit = int(request.args.get('limit') or 100)
|
limit = int(request.args.get('limit') or 100)
|
||||||
return jsonify(list_batches_for_user(user.id, limit=limit))
|
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()
|
||||||
|
return jsonify(get_conversation_batch_workspace(conversation_id, user.id))
|
||||||
|
|
||||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||||
def workspace_create_shipping_batch_from_notices():
|
def workspace_create_shipping_batch_from_notices():
|
||||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||||
@@ -448,6 +455,16 @@ def workspace_mark_manual_uploaded(task_no: str):
|
|||||||
from app.services.shipping_notice import tools as shipping_tools
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}))
|
return 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'])
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||||
def workspace_generate_shipping_excel(task_no: str):
|
def workspace_generate_shipping_excel(task_no: str):
|
||||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||||
|
|||||||
@@ -160,7 +160,7 @@ class Config:
|
|||||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||||
'shipment_{task_no}_{ts}.xlsx',
|
'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)
|
# 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_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')
|
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')
|
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_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 = _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 = _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 = _backend_path(
|
||||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ def enqueue(
|
|||||||
message: 初始状态说明。
|
message: 初始状态说明。
|
||||||
dedupe_active: 是否复用 active 状态的同业务任务。
|
dedupe_active: 是否复用 active 状态的同业务任务。
|
||||||
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
|
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
|
||||||
scheduled_at: 预留参数,当前阶段不启用延迟调度。
|
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
|
||||||
"""
|
"""
|
||||||
normalized_type = _normalize_job_type(job_type)
|
normalized_type = _normalize_job_type(job_type)
|
||||||
normalized_domain = str(domain or "").strip() or "default"
|
normalized_domain = str(domain or "").strip() or "default"
|
||||||
@@ -90,6 +90,7 @@ def enqueue(
|
|||||||
return int(existing.id)
|
return int(existing.id)
|
||||||
|
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
|
queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now
|
||||||
job = Job(
|
job = Job(
|
||||||
domain=normalized_domain,
|
domain=normalized_domain,
|
||||||
job_type=normalized_type,
|
job_type=normalized_type,
|
||||||
@@ -102,7 +103,7 @@ def enqueue(
|
|||||||
attempts=0,
|
attempts=0,
|
||||||
max_attempts=max(1, int(max_attempts or 1)),
|
max_attempts=max(1, int(max_attempts or 1)),
|
||||||
created_by_id=created_by_id,
|
created_by_id=created_by_id,
|
||||||
created_at=now,
|
created_at=queue_at,
|
||||||
updated_at=now,
|
updated_at=now,
|
||||||
)
|
)
|
||||||
db.session.add(job)
|
db.session.add(job)
|
||||||
@@ -156,7 +157,11 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None,
|
|||||||
normalized_types = [_normalize_job_type(item) for item in (job_types or []) if _normalize_job_type(item)]
|
normalized_types = [_normalize_job_type(item) for item in (job_types or []) if _normalize_job_type(item)]
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
try:
|
try:
|
||||||
query = db.session.query(Job).filter(Job.domain == domain, Job.status == "queued")
|
query = db.session.query(Job).filter(
|
||||||
|
Job.domain == domain,
|
||||||
|
Job.status == "queued",
|
||||||
|
Job.created_at <= now,
|
||||||
|
)
|
||||||
if normalized_types:
|
if normalized_types:
|
||||||
query = query.filter(Job.job_type.in_(normalized_types))
|
query = query.filter(Job.job_type.in_(normalized_types))
|
||||||
job = (
|
job = (
|
||||||
|
|||||||
@@ -514,6 +514,7 @@ class DifyService:
|
|||||||
files: list[dict[str, Any]] | None = None,
|
files: list[dict[str, Any]] | None = None,
|
||||||
inputs: dict[str, Any] | None = None,
|
inputs: dict[str, Any] | None = None,
|
||||||
persist_chat_log: bool = True,
|
persist_chat_log: bool = True,
|
||||||
|
display_query: str | None = None,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
|
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
|
||||||
@@ -538,6 +539,7 @@ class DifyService:
|
|||||||
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
||||||
url = DifyService._build_chat_messages_url(base_url)
|
url = DifyService._build_chat_messages_url(base_url)
|
||||||
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
|
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
|
||||||
|
visible_query = str(display_query or query or '').strip()
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||||
@@ -648,7 +650,7 @@ class DifyService:
|
|||||||
session_id=session_id,
|
session_id=session_id,
|
||||||
hxops_turn_id=hxops_turn_id,
|
hxops_turn_id=hxops_turn_id,
|
||||||
normalized_conversation_id=normalized_conversation_id,
|
normalized_conversation_id=normalized_conversation_id,
|
||||||
query=query,
|
query=visible_query,
|
||||||
answer_text=answer_snapshot,
|
answer_text=answer_snapshot,
|
||||||
latency=latency_snapshot,
|
latency=latency_snapshot,
|
||||||
retriever_resources=resources_snapshot,
|
retriever_resources=resources_snapshot,
|
||||||
|
|||||||
@@ -14,12 +14,13 @@ from typing import Any
|
|||||||
from flask import current_app
|
from flask import current_app
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
|
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
|
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||||
from app.services.shipping_notice.dify_executor import run_shipping_parse_via_dify
|
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.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.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.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_BATCHES: set[str] = set()
|
||||||
_RUNNING_TASKS: set[str] = set()
|
_RUNNING_TASKS: set[str] = set()
|
||||||
@@ -59,10 +60,17 @@ def _unmark_running(bucket: set[str], key: str) -> None:
|
|||||||
|
|
||||||
def _should_orchestrate_task(task: Any) -> bool:
|
def _should_orchestrate_task(task: Any) -> bool:
|
||||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
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:
|
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||||
return False
|
return False
|
||||||
if getattr(task, "review_status", None):
|
if getattr(task, "review_status", None):
|
||||||
return False
|
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):
|
if getattr(task, "pending_human_reason", None):
|
||||||
return False
|
return False
|
||||||
if process_status in {"waiting_inventory", "waiting_upload", "upload_failed"}:
|
if process_status in {"waiting_inventory", "waiting_upload", "upload_failed"}:
|
||||||
@@ -73,10 +81,13 @@ def _should_orchestrate_task(task: Any) -> bool:
|
|||||||
def _is_retryable_task(task: Any) -> bool:
|
def _is_retryable_task(task: Any) -> bool:
|
||||||
"""判断任务是否允许由批次重试入口重新派发。"""
|
"""判断任务是否允许由批次重试入口重新派发。"""
|
||||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
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:
|
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||||
return False
|
return False
|
||||||
if getattr(task, "review_status", None):
|
if getattr(task, "review_status", None):
|
||||||
return False
|
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):
|
if getattr(task, "pending_human_reason", None):
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
@@ -111,7 +122,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
|||||||
if not _should_orchestrate_task(task):
|
if not _should_orchestrate_task(task):
|
||||||
return {
|
return {
|
||||||
"status": "skipped",
|
"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)
|
_refresh_batch_focus(task.task_no)
|
||||||
@@ -125,8 +140,27 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
|||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
|
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)
|
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:
|
if current_app:
|
||||||
current_app.logger.info(
|
current_app.logger.info(
|
||||||
"[shipping-orchestrator] dify-parse result task_no=%s status=%s process_status_before=%s provider_conversation_id=%s message=%s",
|
"[shipping-orchestrator] dify-parse result task_no=%s status=%s process_status_before=%s provider_conversation_id=%s message=%s",
|
||||||
@@ -307,7 +341,7 @@ def start_batch_orchestrator(batch_no: str | None) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||||
"""重试批次中仍可自动推进的任务,跳过已终态和人工阻断任务。"""
|
"""重试批次中可恢复的任务;RPA 耗尽态会手动开启新一轮库存导出。"""
|
||||||
normalized_batch_no = _normalize_ref(batch_no)
|
normalized_batch_no = _normalize_ref(batch_no)
|
||||||
if not normalized_batch_no:
|
if not normalized_batch_no:
|
||||||
return {"status": "failed", "message": "batch_no is required"}
|
return {"status": "failed", "message": "batch_no is required"}
|
||||||
@@ -321,6 +355,24 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
|||||||
if not _is_retryable_task(task):
|
if not _is_retryable_task(task):
|
||||||
skipped += 1
|
skipped += 1
|
||||||
continue
|
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):
|
if start_task_orchestrator(task.task_no):
|
||||||
started += 1
|
started += 1
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -198,11 +198,20 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
|
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
|
||||||
if decision == "retry_rpa":
|
if decision == "retry_rpa":
|
||||||
log_task_event(task, "decision_retry_rpa", {"comment": comment})
|
log_task_event(task, "decision_retry_rpa", {"comment": comment})
|
||||||
|
task.error_message = None
|
||||||
db.session.flush()
|
db.session.flush()
|
||||||
retry_payload = merge_tool_payload(task, payload, extra={"mode": "retry_rpa"})
|
retry_payload = merge_tool_payload(
|
||||||
|
task,
|
||||||
|
payload,
|
||||||
|
extra={"mode": "retry_rpa", "manual_retry_round": True},
|
||||||
|
)
|
||||||
return ensure_inventory(retry_payload)
|
return ensure_inventory(retry_payload)
|
||||||
|
|
||||||
if decision == "rematch":
|
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})
|
log_task_event(task, "decision_rematch", {"comment": comment})
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||||
|
|||||||
@@ -126,10 +126,14 @@ def latest_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | Non
|
|||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
def should_auto_chain_after_match(payload: dict[str, Any] | None) -> bool:
|
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
|
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(
|
def try_auto_chain_after_match(
|
||||||
@@ -139,10 +143,10 @@ def try_auto_chain_after_match(
|
|||||||
payload: dict[str, Any] | None = None,
|
payload: dict[str, Any] | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
匹配成功后按配置自动串联 Excel 导出与 RPA 上传(Hxops chat fallback 链)。
|
匹配成功后自动串联 Excel 导出与货代上传(Hxops chat fallback 链)。
|
||||||
|
|
||||||
核心逻辑:仅在 payload 含 auto_chain_fallback 且 match_result 为 ok 时触发;
|
核心逻辑:match_result 为 ok 后默认自动生成 Excel;若自动上传开关开启,
|
||||||
依次调用 generate_excel、upload_to_freight,并将消息 prepend 合并返回。
|
继续触发 RPA 上传。失败、超时或缺少 RPA 配置时转人工接管。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
task: 当前 ShippingTask。
|
task: 当前 ShippingTask。
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"parse.no_lines": "未解析到订单明细行,请重新上传或重新解析。",
|
"parse.no_lines": "未解析到订单明细行,请重新上传或重新解析。",
|
||||||
"parse.low_conf": "解析置信度较低,请重点核对料号、预订单号、数量、单价与金额。",
|
"parse.low_conf": "解析置信度较低,请重点核对料号、预订单号、数量、单价与金额。",
|
||||||
"parse.confirm": "请确认以上信息是否正确?",
|
"parse.confirm": "请确认以上信息是否正确?",
|
||||||
"parse.hint": "回复「确认」进入库存检查;「重新解析」重试;「驳回」终止本任务。",
|
"parse.hint": "请核对信息后使用下方按钮继续。",
|
||||||
"parse.hint_btn": "",
|
"parse.hint_btn": "",
|
||||||
"align.title": "【库存字段对齐确认 — 确认后再匹配】任务编号:{task_no}",
|
"align.title": "【库存字段对齐确认 — 确认后再匹配】任务编号:{task_no}",
|
||||||
"align.match_rule": "匹配规则:{rule}{note}",
|
"align.match_rule": "匹配规则:{rule}{note}",
|
||||||
@@ -35,7 +35,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"align.source.fallback": "(后端动态兜底)",
|
"align.source.fallback": "(后端动态兜底)",
|
||||||
"align.source.other": "({source})",
|
"align.source.other": "({source})",
|
||||||
"align.confirm": "请确认以上字段对齐是否正确。",
|
"align.confirm": "请确认以上字段对齐是否正确。",
|
||||||
"align.hint": "回复「确认」进入匹配;「更正映射」重选列;「重新上传」换库存文件;「驳回」终止本任务。",
|
"align.hint": "请核对字段对齐后使用下方按钮继续。",
|
||||||
"align.hint_btn": "",
|
"align.hint_btn": "",
|
||||||
"common.tips": "提示:",
|
"common.tips": "提示:",
|
||||||
"table.field": "字段",
|
"table.field": "字段",
|
||||||
@@ -109,6 +109,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"workflow.inventory.uploading": "正在上传并解析库存文件",
|
"workflow.inventory.uploading": "正在上传并解析库存文件",
|
||||||
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
|
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
|
||||||
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
|
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
|
||||||
|
"workflow.inventory.completed_task_locked": "该任务已完成,不能再重新上传库存。请切换到仍待处理的任务后再上传库存文件。",
|
||||||
"workflow.inventory.uploaded": "库存文件已上传。",
|
"workflow.inventory.uploaded": "库存文件已上传。",
|
||||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。",
|
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。",
|
||||||
"workflow.inventory.uploaded_need_llm": " 请由画布 LLM 推断列映射后 apply_inventory_mapping。",
|
"workflow.inventory.uploaded_need_llm": " 请由画布 LLM 推断列映射后 apply_inventory_mapping。",
|
||||||
@@ -133,7 +134,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"workflow.fulfillment.manual_already_done": "任务 {task_no} 已标记为完成,无需重复操作。",
|
"workflow.fulfillment.manual_already_done": "任务 {task_no} 已标记为完成,无需重复操作。",
|
||||||
"workflow.fulfillment.manual_confirmed": "已确认手工上传货代完成",
|
"workflow.fulfillment.manual_confirmed": "已确认手工上传货代完成",
|
||||||
"workflow.fulfillment.task_completed": "任务已完成",
|
"workflow.fulfillment.task_completed": "任务已完成",
|
||||||
"workflow.fulfillment.manual_done_message": "已标记为手工上传货代系统完成。任务 {task_no} 已全部处理完毕,无需再进行任何操作。",
|
"workflow.fulfillment.manual_done_message": "好的,任务 {task_no} 已确认完成,无需再处理。",
|
||||||
"workflow.fulfillment.upload_running": "RPA 上传进行中(第 {attempt}/{max_attempts} 次)。已等待 {elapsed}s / 超时 {timeout}s。请稍后再试(建议 {remaining}s 后)。",
|
"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_timeout_error": "RPA 上传超时(>{timeout}s)",
|
||||||
"workflow.fulfillment.upload_exhausted": "已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。",
|
"workflow.fulfillment.upload_exhausted": "已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。",
|
||||||
@@ -154,7 +155,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"parse.no_lines": "No order lines found. Please re-upload or re-parse.",
|
"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.low_conf": "Low confidence. Please double-check SKU, Qty, Reservation ID, Unit Price and Amount.",
|
||||||
"parse.confirm": "Please confirm the above information.",
|
"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": "",
|
"parse.hint_btn": "",
|
||||||
"align.title": "[Inventory mapping confirmation] Task: {task_no}",
|
"align.title": "[Inventory mapping confirmation] Task: {task_no}",
|
||||||
"align.match_rule": "Match rule: {rule}{note}",
|
"align.match_rule": "Match rule: {rule}{note}",
|
||||||
@@ -169,7 +170,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"align.source.fallback": " (backend fallback)",
|
"align.source.fallback": " (backend fallback)",
|
||||||
"align.source.other": " ({source})",
|
"align.source.other": " ({source})",
|
||||||
"align.confirm": "Please confirm the field alignment above.",
|
"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": "",
|
"align.hint_btn": "",
|
||||||
"common.tips": "Notes:",
|
"common.tips": "Notes:",
|
||||||
"table.field": "Field",
|
"table.field": "Field",
|
||||||
@@ -243,6 +244,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"workflow.inventory.uploading": "Uploading and parsing the inventory file.",
|
"workflow.inventory.uploading": "Uploading and parsing the inventory file.",
|
||||||
"workflow.inventory.uploading_detail": "Processing inventory file {filename}",
|
"workflow.inventory.uploading_detail": "Processing inventory file {filename}",
|
||||||
"workflow.inventory.save_failed": "Failed to save inventory file: {error}",
|
"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": "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_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.uploaded_need_llm": " Please let the canvas LLM infer the column mapping and then call apply_inventory_mapping.",
|
||||||
@@ -267,7 +269,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"workflow.fulfillment.manual_already_done": "Task {task_no} is already marked complete. No further action is needed.",
|
"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.manual_confirmed": "Manual freight upload has been confirmed.",
|
||||||
"workflow.fulfillment.task_completed": "Task completed.",
|
"workflow.fulfillment.task_completed": "Task completed.",
|
||||||
"workflow.fulfillment.manual_done_message": "The task has been marked as manually uploaded to the freight system. Task {task_no} is fully completed and no further action is needed.",
|
"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_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_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_exhausted": "RPA upload failed after {attempts} attempts. Please download the Excel and upload it manually.",
|
||||||
@@ -288,7 +290,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"parse.no_lines": "ไม่พบบรรทัดรายการสั่งซื้อ กรุณาอัปโหลดใหม่หรือแยกใหม่อีกครั้ง",
|
"parse.no_lines": "ไม่พบบรรทัดรายการสั่งซื้อ กรุณาอัปโหลดใหม่หรือแยกใหม่อีกครั้ง",
|
||||||
"parse.low_conf": "ความมั่นใจต่ำ กรุณาตรวจสอบ SKU, จำนวน, Reservation ID, ราคาต่อหน่วย และจำนวนเงิน",
|
"parse.low_conf": "ความมั่นใจต่ำ กรุณาตรวจสอบ SKU, จำนวน, Reservation ID, ราคาต่อหน่วย และจำนวนเงิน",
|
||||||
"parse.confirm": "กรุณายืนยันว่าข้อมูลด้านบนถูกต้องหรือไม่",
|
"parse.confirm": "กรุณายืนยันว่าข้อมูลด้านบนถูกต้องหรือไม่",
|
||||||
"parse.hint": 'พิมพ์ "ยืนยัน" เพื่อไปต่อ; "แยกใหม่" เพื่อลองใหม่; "ปฏิเสธ" เพื่อยุติงานนี้',
|
"parse.hint": "ตรวจสอบข้อมูลแล้วใช้ปุ่มด้านล่างเพื่อดำเนินการต่อ",
|
||||||
"parse.hint_btn": "",
|
"parse.hint_btn": "",
|
||||||
"align.title": "【ยืนยันการจับคู่คอลัมน์สต็อก】งาน: {task_no}",
|
"align.title": "【ยืนยันการจับคู่คอลัมน์สต็อก】งาน: {task_no}",
|
||||||
"align.match_rule": "กฎการจับคู่: {rule}{note}",
|
"align.match_rule": "กฎการจับคู่: {rule}{note}",
|
||||||
@@ -303,7 +305,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"align.source.fallback": " (สำรองโดยระบบ)",
|
"align.source.fallback": " (สำรองโดยระบบ)",
|
||||||
"align.source.other": " ({source})",
|
"align.source.other": " ({source})",
|
||||||
"align.confirm": "กรุณายืนยันว่าการจับคู่ฟิลด์ด้านบนถูกต้อง",
|
"align.confirm": "กรุณายืนยันว่าการจับคู่ฟิลด์ด้านบนถูกต้อง",
|
||||||
"align.hint": 'พิมพ์ "ยืนยัน" เพื่อจับคู่; "แก้ไขการจับคู่" เพื่อเลือกคอลัมน์ใหม่; "อัปโหลดใหม่" เพื่อเปลี่ยนไฟล์สต็อก; "ปฏิเสธ" เพื่อยุติ',
|
"align.hint": "ตรวจสอบการจับคู่ฟิลด์แล้วใช้ปุ่มด้านล่างเพื่อดำเนินการต่อ",
|
||||||
"align.hint_btn": "",
|
"align.hint_btn": "",
|
||||||
"common.tips": "หมายเหตุ:",
|
"common.tips": "หมายเหตุ:",
|
||||||
"table.field": "ฟิลด์",
|
"table.field": "ฟิลด์",
|
||||||
@@ -377,6 +379,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
|
"workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
|
||||||
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
|
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
|
||||||
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
|
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
|
||||||
|
"workflow.inventory.completed_task_locked": "งานนี้เสร็จสิ้นแล้ว จึงไม่สามารถอัปโหลดสต็อกซ้ำได้ โปรดสลับไปยังงานที่ยังต้องดำเนินการ",
|
||||||
"workflow.inventory.uploaded": "อัปโหลดไฟล์สต็อกแล้ว",
|
"workflow.inventory.uploaded": "อัปโหลดไฟล์สต็อกแล้ว",
|
||||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping ครบแล้ว จึงสามารถเรียก apply_inventory_mapping ได้ตรงจาก canvas โดยไม่ต้องผ่าน LLM",
|
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping ครบแล้ว จึงสามารถเรียก apply_inventory_mapping ได้ตรงจาก canvas โดยไม่ต้องผ่าน LLM",
|
||||||
"workflow.inventory.uploaded_need_llm": " โปรดให้ LLM บน canvas อนุมานการจับคู่คอลัมน์ แล้วจึงเรียก apply_inventory_mapping",
|
"workflow.inventory.uploaded_need_llm": " โปรดให้ LLM บน canvas อนุมานการจับคู่คอลัมน์ แล้วจึงเรียก apply_inventory_mapping",
|
||||||
@@ -401,7 +404,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
|||||||
"workflow.fulfillment.manual_already_done": "งาน {task_no} ถูกทำเครื่องหมายว่าเสร็จแล้ว จึงไม่ต้องดำเนินการซ้ำ",
|
"workflow.fulfillment.manual_already_done": "งาน {task_no} ถูกทำเครื่องหมายว่าเสร็จแล้ว จึงไม่ต้องดำเนินการซ้ำ",
|
||||||
"workflow.fulfillment.manual_confirmed": "ยืนยันการอัปโหลดเข้าระบบขนส่งด้วยตนเองแล้ว",
|
"workflow.fulfillment.manual_confirmed": "ยืนยันการอัปโหลดเข้าระบบขนส่งด้วยตนเองแล้ว",
|
||||||
"workflow.fulfillment.task_completed": "งานเสร็จสิ้นแล้ว",
|
"workflow.fulfillment.task_completed": "งานเสร็จสิ้นแล้ว",
|
||||||
"workflow.fulfillment.manual_done_message": "ทำเครื่องหมายว่าอัปโหลดเข้าระบบขนส่งด้วยตนเองเสร็จแล้ว งาน {task_no} เสร็จสมบูรณ์และไม่ต้องดำเนินการต่อ",
|
"workflow.fulfillment.manual_done_message": "เรียบร้อย งาน {task_no} ยืนยันว่าเสร็จแล้ว ไม่ต้องดำเนินการต่อ",
|
||||||
"workflow.fulfillment.upload_running": "RPA กำลังอัปโหลดอยู่ (ครั้งที่ {attempt}/{max_attempts}) รอแล้ว {elapsed}s / หมดเวลา {timeout}s โปรดลองอีกครั้งภายหลัง (แนะนำหลัง {remaining}s)",
|
"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_timeout_error": "RPA อัปโหลดหมดเวลา (>{timeout}s)",
|
||||||
"workflow.fulfillment.upload_exhausted": "พยายามอัปโหลดผ่าน RPA มาแล้ว {attempts} ครั้งแต่ยังไม่สำเร็จ โปรดดาวน์โหลด Excel แล้วอัปโหลดด้วยตนเอง",
|
"workflow.fulfillment.upload_exhausted": "พยายามอัปโหลดผ่าน RPA มาแล้ว {attempts} ครั้งแต่ยังไม่สำเร็จ โปรดดาวน์โหลด Excel แล้วอัปโหลดด้วยตนเอง",
|
||||||
|
|||||||
@@ -24,6 +24,13 @@ from app.services.shipping_notice.inventory_snapshot import (
|
|||||||
)
|
)
|
||||||
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
|
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:
|
def _safe_ref(value: str) -> str:
|
||||||
return re.sub(r"[^\w\-]+", "_", str(value or "").strip()) or "unknown"
|
return re.sub(r"[^\w\-]+", "_", str(value or "").strip()) or "unknown"
|
||||||
@@ -95,7 +102,8 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
|||||||
db.session.add(inv_file)
|
db.session.add(inv_file)
|
||||||
db.session.flush()
|
db.session.flush()
|
||||||
|
|
||||||
linked_tasks = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task]
|
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:
|
for item in linked_tasks:
|
||||||
replace_task_inventory_link(item, inv_file, role="owner" if item.id == task.id else "member")
|
replace_task_inventory_link(item, inv_file, role="owner" if item.id == task.id else "member")
|
||||||
return inv_file
|
return inv_file
|
||||||
@@ -199,6 +207,8 @@ def apply_inventory_parse_result_to_linked_tasks(
|
|||||||
for link in inv_file.links or []:
|
for link in inv_file.links or []:
|
||||||
if not link.is_active or not link.task:
|
if not link.is_active or not link.task:
|
||||||
continue
|
continue
|
||||||
|
if not _can_relink_inventory(link.task):
|
||||||
|
continue
|
||||||
link.task.inventory_snapshot_id = inv_file.id
|
link.task.inventory_snapshot_id = inv_file.id
|
||||||
link.task.inventory_lines_json = inventory_lines
|
link.task.inventory_lines_json = inventory_lines
|
||||||
linked_tasks.append(link.task)
|
linked_tasks.append(link.task)
|
||||||
@@ -222,7 +232,18 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
|
|||||||
|
|
||||||
【AI 触发时机】:库存快照完成解析或字段映射确认后由内部调用;不暴露给 Agent。
|
【AI 触发时机】:库存快照完成解析或字段映射确认后由内部调用;不暴露给 Agent。
|
||||||
"""
|
"""
|
||||||
task_nos = linked_task_nos_for_inventory_file(inv_file)
|
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:
|
if not task_nos:
|
||||||
return False
|
return False
|
||||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent
|
|||||||
def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]:
|
def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]:
|
||||||
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
|
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
|
||||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||||
|
manual_retry_round = mode == "retry_rpa"
|
||||||
|
|
||||||
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
|
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
|
||||||
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
|
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
|
||||||
@@ -140,18 +141,34 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
|||||||
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})
|
||||||
if trigger:
|
if trigger:
|
||||||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
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(
|
set_task_step_progress(
|
||||||
task,
|
task,
|
||||||
step_key="step3_inventory_prepare",
|
step_key="step3_inventory_prepare",
|
||||||
step_title="获取库存",
|
step_title="获取库存",
|
||||||
status="running",
|
status="running",
|
||||||
message="已触发 RPA 库存导出,等待结果",
|
message=progress_message,
|
||||||
progress_percent=60,
|
progress_percent=60,
|
||||||
current=attempt_no,
|
current=attempt_no,
|
||||||
total=max_attempts,
|
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:
|
if attempt_no >= max_attempts and not task.inventory_lines_json:
|
||||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||||
@@ -165,14 +182,16 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
|||||||
data=serialize_task_for_tool(task),
|
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()
|
db.session.commit()
|
||||||
return tool_response(
|
return tool_response(
|
||||||
status="running",
|
status="running",
|
||||||
task_id=task.task_no,
|
task_id=task.task_no,
|
||||||
message=(
|
message=f"{response_prefix}若 {timeout_seconds}s 内无回调/无落盘文件,可继续重试;超过最大次数将转人工上传。",
|
||||||
f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
|
|
||||||
f"若 {timeout_seconds}s 内无回调/无落盘文件,可继续重试;超过最大次数将转人工上传。"
|
|
||||||
),
|
|
||||||
data={
|
data={
|
||||||
**serialize_task_for_tool(task),
|
**serialize_task_for_tool(task),
|
||||||
"rpa": {
|
"rpa": {
|
||||||
|
|||||||
@@ -61,6 +61,8 @@ from app.services.shipping_notice.state_machine import TaskTransition, apply_tas
|
|||||||
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
|
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
|
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:
|
def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | None:
|
||||||
"""从 payload 解析 inventory_lines / inventory_lines_json。"""
|
"""从 payload 解析 inventory_lines / inventory_lines_json。"""
|
||||||
@@ -413,6 +415,15 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
|||||||
if not task:
|
if not task:
|
||||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
|
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
|
||||||
lang = resolve_lang({"lang": None})
|
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):
|
if upload is None or not getattr(upload, "filename", None):
|
||||||
return tool_response(
|
return tool_response(
|
||||||
status="failed",
|
status="failed",
|
||||||
|
|||||||
@@ -77,12 +77,15 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
|||||||
return {
|
return {
|
||||||
"openapi": "3.0.0",
|
"openapi": "3.0.0",
|
||||||
"info": {
|
"info": {
|
||||||
"title": "Hxops Shipping Notice Tools",
|
"title": "Shipping Notice Tools",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": (
|
"description": (
|
||||||
"货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:"
|
"货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:"
|
||||||
"通知理解、字段修订、库存映射建议、人工确认收口与状态查询;"
|
"通知理解、字段修订、库存映射建议、人工确认收口与状态查询;"
|
||||||
"不包含由 hxops worker 统一续跑的主推进工具,也不包含 RPA 回调。"
|
"不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。"
|
||||||
|
"如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,"
|
||||||
|
"不要在自然语言正文里列出按钮清单或“推荐下一步”动作列表;"
|
||||||
|
"可点击按钮由宿主系统根据 action_buttons 统一渲染。"
|
||||||
"鉴权:Authorization Bearer 或 X-Integration-Key。"
|
"鉴权:Authorization Bearer 或 X-Integration-Key。"
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -164,7 +167,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
|||||||
),
|
),
|
||||||
"/tools/apply_inventory_mapping": _post_op(
|
"/tools/apply_inventory_mapping": _post_op(
|
||||||
"apply_inventory_mapping",
|
"apply_inventory_mapping",
|
||||||
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由 hxops worker 续跑",
|
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由后台任务续跑",
|
||||||
{
|
{
|
||||||
"task_id": task_id,
|
"task_id": task_id,
|
||||||
MAP_JSON: _str_prop(
|
MAP_JSON: _str_prop(
|
||||||
@@ -175,7 +178,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
|||||||
),
|
),
|
||||||
"/tools/submit_decision": _post_op(
|
"/tools/submit_decision": _post_op(
|
||||||
"submit_decision",
|
"submit_decision",
|
||||||
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由 hxops worker 统一续跑。",
|
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
|
||||||
{
|
{
|
||||||
"task_id": task_id,
|
"task_id": task_id,
|
||||||
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
|
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ from enum import Enum
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from sqlalchemy import desc
|
from sqlalchemy import asc, desc
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import ShippingBatch, ShippingTask
|
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:
|
def extract_task_no_from_text(text: str) -> str | None:
|
||||||
"""从自然语言文本中提取 SN- 任务编号。"""
|
"""从自然语言文本中提取 SN- 任务编号。"""
|
||||||
match = _TASK_NO_RE.search(str(text or ""))
|
match = _TASK_NO_RE.search(str(text or ""))
|
||||||
@@ -243,9 +292,13 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
|||||||
"upload_mode": task.upload_mode,
|
"upload_mode": task.upload_mode,
|
||||||
"upload_attempt": task.upload_attempt,
|
"upload_attempt": task.upload_attempt,
|
||||||
"pending_human_reason": task.pending_human_reason,
|
"pending_human_reason": task.pending_human_reason,
|
||||||
|
"error_message": task.error_message or task.upload_error_message,
|
||||||
"conversation_id": task.conversation_id,
|
"conversation_id": task.conversation_id,
|
||||||
"export_file_name": task.export_file_name,
|
"export_file_name": task.export_file_name,
|
||||||
"freight_ref_no": task.freight_ref_no,
|
"freight_ref_no": task.freight_ref_no,
|
||||||
|
"step_payload": task.step_payload_json or {},
|
||||||
|
"shortage": task.shortage_json,
|
||||||
|
"line_results": task.line_results_json or [],
|
||||||
"created_at": task.created_at.isoformat() if task.created_at else None,
|
"created_at": task.created_at.isoformat() if task.created_at else None,
|
||||||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||||||
}
|
}
|
||||||
@@ -321,6 +374,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]:
|
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
|
||||||
"""工作台任务列表用的 SUMMARY 投影。"""
|
"""工作台任务列表用的 SUMMARY 投影。"""
|
||||||
return serialize_task(task, TaskProjection.SUMMARY)
|
return serialize_task(task, TaskProjection.SUMMARY)
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
import logging
|
import logging
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
from flask import current_app
|
from flask import current_app
|
||||||
|
|
||||||
@@ -16,6 +17,7 @@ from app import db
|
|||||||
from app.jobs.queue import enqueue, fail_job, finish_job, process_next_job
|
from app.jobs.queue import enqueue, fail_job, finish_job, process_next_job
|
||||||
from app.jobs.types import JobType
|
from app.jobs.types import JobType
|
||||||
from app.models import Job
|
from app.models import Job
|
||||||
|
from app.services.shipping_notice.constants import PH_RPA_PENDING, PH_UPLOAD_RPA_PENDING
|
||||||
|
|
||||||
logger = logging.getLogger('shipping-worker')
|
logger = logging.getLogger('shipping-worker')
|
||||||
|
|
||||||
@@ -54,6 +56,49 @@ def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = Non
|
|||||||
return True, 'queued_manual'
|
return True, 'queued_manual'
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
recheck_seconds = max(
|
||||||
|
float(current_app.config.get('SHIPPING_NOTICE_RPA_WAIT_RECHECK_SECONDS', 10) or 10),
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
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=datetime.utcnow() + timedelta(seconds=recheck_seconds),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||||
"""兼容旧调用:回收通用 jobs 表里超时的发货任务。"""
|
"""兼容旧调用:回收通用 jobs 表里超时的发货任务。"""
|
||||||
from app.jobs.queue import recover_stale_jobs
|
from app.jobs.queue import recover_stale_jobs
|
||||||
@@ -103,6 +148,8 @@ def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | No
|
|||||||
result=dict(result),
|
result=dict(result),
|
||||||
message=str(result.get('message') or '')[:500] or '发货任务处理完成',
|
message=str(result.get('message') or '')[:500] or '发货任务处理完成',
|
||||||
)
|
)
|
||||||
|
if status == 'running':
|
||||||
|
_requeue_external_wait_job(task_no, job=job)
|
||||||
else:
|
else:
|
||||||
fail_job(
|
fail_job(
|
||||||
job,
|
job,
|
||||||
|
|||||||
@@ -24,6 +24,10 @@ _INVENTORY_SUCCESS_EVENTS = {
|
|||||||
"inventory_template_mapping_used",
|
"inventory_template_mapping_used",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_INVENTORY_ATTEMPT_RESET_EVENTS = _INVENTORY_SUCCESS_EVENTS | {
|
||||||
|
"decision_retry_rpa",
|
||||||
|
}
|
||||||
|
|
||||||
_UPLOAD_SUCCESS_EVENTS = {
|
_UPLOAD_SUCCESS_EVENTS = {
|
||||||
"upload_rpa_success",
|
"upload_rpa_success",
|
||||||
"upload_manual_confirmed",
|
"upload_manual_confirmed",
|
||||||
@@ -35,13 +39,13 @@ def inventory_rpa_attempts(task: ShippingTask | None) -> int:
|
|||||||
if not task or task.id is None:
|
if not task or task.id is None:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
last_success = (
|
last_reset = (
|
||||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
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())
|
.order_by(ShippingTaskEvent.id.desc())
|
||||||
.first()
|
.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(
|
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||||
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
|
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
|
||||||
|
|||||||
@@ -429,6 +429,7 @@ class TaskTransition(StrEnum):
|
|||||||
CORRECT_MAPPING = "correct_mapping"
|
CORRECT_MAPPING = "correct_mapping"
|
||||||
REPARSE_INVENTORY = "reparse_inventory"
|
REPARSE_INVENTORY = "reparse_inventory"
|
||||||
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
|
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
|
||||||
|
REMATCH_REQUESTED = "rematch_requested"
|
||||||
WAITING_UPLOAD = "waiting_upload"
|
WAITING_UPLOAD = "waiting_upload"
|
||||||
UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
||||||
UPLOAD_FAILED = "upload_failed"
|
UPLOAD_FAILED = "upload_failed"
|
||||||
@@ -535,6 +536,12 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
|||||||
review_status=None,
|
review_status=None,
|
||||||
pending_human_reason=None,
|
pending_human_reason=None,
|
||||||
),
|
),
|
||||||
|
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.WAITING_UPLOAD: _TransitionSpec(process_status="waiting_upload"),
|
||||||
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
|
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
|
||||||
process_status="waiting_upload",
|
process_status="waiting_upload",
|
||||||
|
|||||||
@@ -391,9 +391,9 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
return tool_response(
|
return tool_response(
|
||||||
status="ok",
|
status="ok",
|
||||||
task_id=task.task_no,
|
task_id=task.task_no,
|
||||||
batch_no=batch.batch_no,
|
|
||||||
message=f"已创建发货批次 {batch.batch_no},任务 {task.task_no}",
|
message=f"已创建发货批次 {batch.batch_no},任务 {task.task_no}",
|
||||||
data={**serialize_task_for_tool(task), "batch": serialize_batch_for_tool(batch)},
|
data={**serialize_task_for_tool(task), "batch": serialize_batch_for_tool(batch)},
|
||||||
|
extra={"batch_no": batch.batch_no},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,36 @@ if TYPE_CHECKING:
|
|||||||
from app.models import ShippingTask
|
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(
|
def tool_response(
|
||||||
*,
|
*,
|
||||||
status: str,
|
status: str,
|
||||||
@@ -27,6 +57,7 @@ def tool_response(
|
|||||||
next_required_action: str | None = None,
|
next_required_action: str | None = None,
|
||||||
forbidden_next_tools: list[str] | None = None,
|
forbidden_next_tools: list[str] | None = None,
|
||||||
stop_agent_turn: bool = False,
|
stop_agent_turn: bool = False,
|
||||||
|
extra: dict[str, Any] | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
构建发货通知 Tool 标准 JSON 响应。
|
构建发货通知 Tool 标准 JSON 响应。
|
||||||
@@ -37,6 +68,7 @@ def tool_response(
|
|||||||
Args:
|
Args:
|
||||||
stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。
|
stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。
|
||||||
forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。
|
forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。
|
||||||
|
extra: 需要保留在顶层的兼容字段,例如 batch_no。
|
||||||
"""
|
"""
|
||||||
from app.services.shipping_notice.state_machine import (
|
from app.services.shipping_notice.state_machine import (
|
||||||
action_buttons_for_checkpoint,
|
action_buttons_for_checkpoint,
|
||||||
@@ -61,7 +93,7 @@ def tool_response(
|
|||||||
|
|
||||||
payload: dict[str, Any] = {
|
payload: dict[str, Any] = {
|
||||||
"status": status,
|
"status": status,
|
||||||
"message": message,
|
"message": _sanitize_user_facing_text(message),
|
||||||
"data": data or {},
|
"data": data or {},
|
||||||
}
|
}
|
||||||
if task_id:
|
if task_id:
|
||||||
@@ -79,9 +111,11 @@ def tool_response(
|
|||||||
if resolved_checkpoint:
|
if resolved_checkpoint:
|
||||||
payload["checkpoint"] = resolved_checkpoint
|
payload["checkpoint"] = resolved_checkpoint
|
||||||
if next_required_action:
|
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:
|
if forbidden_next_tools:
|
||||||
payload["forbidden_next_tools"] = forbidden_next_tools
|
payload["forbidden_next_tools"] = forbidden_next_tools
|
||||||
if stop_agent_turn:
|
if stop_agent_turn:
|
||||||
payload["stop_agent_turn"] = True
|
payload["stop_agent_turn"] = True
|
||||||
|
if extra:
|
||||||
|
payload.update(extra)
|
||||||
return payload
|
return payload
|
||||||
@@ -20,6 +20,11 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
|
|||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def _shipping_notice_stable_auto_config(app, request):
|
def _shipping_notice_stable_auto_config(app, request):
|
||||||
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
|
"""发货通知单测默认关闭 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"):
|
if request.node.get_closest_marker("auto_rpa"):
|
||||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||||
@@ -27,6 +32,7 @@ def _shipping_notice_stable_auto_config(app, request):
|
|||||||
return
|
return
|
||||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
|
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
|
||||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_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
|
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,6 @@ def test_resolve_backend_relative_path_data_prefix():
|
|||||||
|
|
||||||
def test_resolve_backend_relative_path_default():
|
def test_resolve_backend_relative_path_default():
|
||||||
root = backend_dir()
|
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))
|
resolved = Path(resolve_backend_relative_path(None, default))
|
||||||
assert resolved == default.resolve()
|
assert resolved == default.resolve()
|
||||||
@@ -205,6 +205,169 @@ def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(ap
|
|||||||
assert started == [data["batch_no"]]
|
assert started == [data["batch_no"]]
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
def test_shipping_orchestrator_enqueues_generic_job_not_kb_job(app):
|
||||||
"""发货通知后台编排应写入通用 jobs,不能污染 kb_jobs。"""
|
"""发货通知后台编排应写入通用 jobs,不能污染 kb_jobs。"""
|
||||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
|
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
|
||||||
@@ -306,6 +469,53 @@ def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
|
|||||||
assert called.get("dify") == task_no
|
assert called.get("dify") == task_no
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypatch):
|
||||||
"""编排器遇到非 created 且无人工阻塞的任务时应调用 auto_progress。"""
|
"""编排器遇到非 created 且无人工阻塞的任务时应调用 auto_progress。"""
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
|
|||||||
@@ -146,12 +146,13 @@ def test_batch_process_summary_shared_formula(app):
|
|||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
tasks = [done, running]
|
tasks = [done, running]
|
||||||
assert compute_batch_process_summary(tasks) == {
|
summary = compute_batch_process_summary(tasks)
|
||||||
"total": 2,
|
assert summary["total"] == 2
|
||||||
"completed": 1,
|
assert summary["completed"] == 1
|
||||||
"failed": 0,
|
assert summary["failed"] == 0
|
||||||
"running": 1,
|
assert summary["running"] == 1
|
||||||
}
|
assert summary["pending"] == 2
|
||||||
|
assert summary["current_task_no"] == "SN-RUN"
|
||||||
tool_batch = serialize_batch(batch, BatchProjection.TOOL)
|
tool_batch = serialize_batch(batch, BatchProjection.TOOL)
|
||||||
assert tool_batch["process_summary"]["completed"] == 1
|
assert tool_batch["process_summary"]["completed"] == 1
|
||||||
assert tool_batch["batch_no"] == "SB-SUMMARY"
|
assert tool_batch["batch_no"] == "SB-SUMMARY"
|
||||||
|
|||||||
@@ -83,10 +83,16 @@ def test_shipping_notice_tool_flow(app, client):
|
|||||||
)
|
)
|
||||||
assert match_res.status_code == 200
|
assert match_res.status_code == 200
|
||||||
match_data = match_res.get_json()
|
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 "库存" in match_data["message"]
|
assert "库存" in match_data["message"]
|
||||||
assert "A001" 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(
|
excel_res = client.post(
|
||||||
"/api/shipping-notice/tools/generate_shipment_excel",
|
"/api/shipping-notice/tools/generate_shipment_excel",
|
||||||
@@ -160,6 +166,67 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
|
|||||||
assert confirm_res.get_json()["status"] == "failed"
|
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):
|
def test_openapi_spec_public(app, client):
|
||||||
app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com"
|
app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com"
|
||||||
res = client.get("/api/shipping-notice/tools/openapi.json")
|
res = client.get("/api/shipping-notice/tools/openapi.json")
|
||||||
@@ -683,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
|
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):
|
def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
|
||||||
headers = _tool_headers(app)
|
headers = _tool_headers(app)
|
||||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
|
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
|
||||||
@@ -1016,6 +1159,169 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
|
|||||||
assert called.get("task_no") == task_id
|
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):
|
def test_submit_decision_by_conversation_id(app, client):
|
||||||
headers = _tool_headers(app)
|
headers = _tool_headers(app)
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"openapi": "3.0.0",
|
"openapi": "3.0.0",
|
||||||
"info": {
|
"info": {
|
||||||
"title": "Hxops Shipping Notice Tools",
|
"title": "Shipping Notice Tools",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:通知理解、字段修订、库存映射建议、人工确认收口与状态查询;不包含由 hxops worker 统一续跑的主推进工具,也不包含 RPA 回调。鉴权:Authorization Bearer 或 X-Integration-Key。"
|
"description": "货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:通知理解、字段修订、库存映射建议、人工确认收口与状态查询;不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,不要在自然语言正文里列出按钮清单或“推荐下一步”动作列表;可点击按钮由宿主系统根据 action_buttons 统一渲染。鉴权:Authorization Bearer 或 X-Integration-Key。"
|
||||||
},
|
},
|
||||||
"servers": [
|
"servers": [
|
||||||
{
|
{
|
||||||
@@ -305,8 +305,8 @@
|
|||||||
"/tools/apply_inventory_mapping": {
|
"/tools/apply_inventory_mapping": {
|
||||||
"post": {
|
"post": {
|
||||||
"operationId": "apply_inventory_mapping",
|
"operationId": "apply_inventory_mapping",
|
||||||
"summary": "应用 LLM/人工列映射并解析完整批次库存快照;返回 field_alignment 等待用户确认,后续本批各票由 hxops worker 独立续跑",
|
"summary": "应用 LLM/人工列映射并解析完整批次库存快照;返回 field_alignment 等待用户确认,后续本批各票由后台任务独立续跑",
|
||||||
"description": "应用 LLM/人工列映射并解析完整批次库存快照;返回 field_alignment 等待用户确认,后续本批各票由 hxops worker 独立续跑",
|
"description": "应用 LLM/人工列映射并解析完整批次库存快照;返回 field_alignment 等待用户确认,后续本批各票由后台任务独立续跑",
|
||||||
"parameters": [],
|
"parameters": [],
|
||||||
"requestBody": {
|
"requestBody": {
|
||||||
"required": true,
|
"required": true,
|
||||||
@@ -349,8 +349,8 @@
|
|||||||
"/tools/submit_decision": {
|
"/tools/submit_decision": {
|
||||||
"post": {
|
"post": {
|
||||||
"operationId": "submit_decision",
|
"operationId": "submit_decision",
|
||||||
"summary": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由 hxops worker 统一续跑。",
|
"summary": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
|
||||||
"description": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由 hxops worker 统一续跑。",
|
"description": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
|
||||||
"parameters": [],
|
"parameters": [],
|
||||||
"requestBody": {
|
"requestBody": {
|
||||||
"required": true,
|
"required": true,
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
+24
-19
@@ -59,10 +59,10 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
|||||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||||
|
|
||||||
# RPA 目录
|
# RPA 目录
|
||||||
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
|
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
|
||||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
|
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
|
||||||
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
|
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
|
||||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
|
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
|
||||||
|
|
||||||
# 发货 Excel 模板
|
# 发货 Excel 模板
|
||||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||||
@@ -217,12 +217,15 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv
|
|||||||
|
|
||||||
多任务是本方案最容易在联调时失真的部分,编排上必须显式约束:
|
多任务是本方案最容易在联调时失真的部分,编排上必须显式约束:
|
||||||
|
|
||||||
1. 同一 `batch` 任一时刻只允许一个**聚焦任务**,以 `current_focus_task_no` 为准。
|
1. 一个 Agent 会话代表一次业务委托;同一会话可包含多个 `batch`,前端通过 `GET /api/workspace/shipping-conversations/<conversation_id>/batch-workspace` 获取会话级执行工作台。
|
||||||
2. Dify 每轮只推进一个 task;不得在同一轮里循环处理整批任务。
|
2. 会话级工作台只做汇总、切换与聚焦:共享用户委托、全局规则、批次摘要;不把某个批次的确认、失败或重试结果自动扩散到其他批次。
|
||||||
3. 库存文件按批次作为统一库存快照保存;单票也会创建 `file_count=1` 的批次,后续每票独立匹配同一快照。
|
3. 同一 `batch` 任一时刻只允许一个**聚焦任务**,以 `current_focus_task_no` 为准。
|
||||||
4. 用户显式输入 `SN-...` 切换任务时,任务状态、确认、上传动作仍作用于该 task;库存上传/字段映射会作用于该 task 所属批次库存快照。
|
4. Dify 每轮只推进一个 task;不得在同一轮里循环处理整批任务。
|
||||||
5. 批次级“其余票继续处理”由后端 worker / 队列负责,不由 Dify 在对话中批量调 Tool。
|
5. 库存文件按批次作为统一库存快照保存;单票也会创建 `file_count=1` 的批次,后续每票独立匹配同一快照。
|
||||||
6. 任一 task 出现 `needs_human` 时,只阻断该 task;批次摘要可继续展示其他票状态,但当前对话仍只围绕聚焦 task 引导。
|
6. 用户显式输入 `SN-...` 切换任务时,任务状态、确认、上传动作仍作用于该 task;库存上传/字段映射会作用于该 task 所属批次库存快照。
|
||||||
|
7. 批次级“其余票继续处理”由后端 worker / 队列负责,不由 Dify 在对话中批量调 Tool。
|
||||||
|
8. 任一 task 出现 `needs_human` 时,只阻断该 task;会话和批次摘要可继续展示其他票状态,但当前对话仍只围绕聚焦 task 引导。
|
||||||
|
9. 聊天 UI 的“重试”按钮必须标明作用域,例如“重试当前批次可恢复任务”;本期不提供跨批次强制发货、批量忽略缺口等高风险动作。
|
||||||
|
|
||||||
### 2.3 配置顺序
|
### 2.3 配置顺序
|
||||||
|
|
||||||
@@ -1974,8 +1977,8 @@ Agent 禁用 Tool:
|
|||||||
|
|
||||||
说明:
|
说明:
|
||||||
|
|
||||||
- 以上动作可能出现在后端返回的 `human_options / action_buttons` 中,但它们属于 **Hxops 前端按钮或宿主交互动作**,不是 Dify 可直接调用的 OpenAPI Tool。
|
- 以上动作可能出现在后端返回的 `human_options / action_buttons` 中,但它们属于 **宿主系统按钮或宿主交互动作**,不是 Dify 可直接调用的 OpenAPI Tool。
|
||||||
- Agent 的职责是解释这些动作的含义,并引导用户点击按钮、上传文件或等待后端续跑;不能把这些 action id 当作 Tool 名称去调用。
|
- Agent 的职责是解释当前状态、业务原因和影响;可点击动作由宿主系统根据 `action_buttons` 统一渲染。Agent 不能把这些 action id 当作 Tool 名称去调用,也不要在自然语言正文中重复列出“推荐下一步”“请选择操作”“1. 刷新 / 2. 下载 Excel”之类的操作清单。
|
||||||
- 本节点负责模糊问题解释、自由输入收口与有限 Tool 调用,不负责首层路由或长链路编排。
|
- 本节点负责模糊问题解释、自由输入收口与有限 Tool 调用,不负责首层路由或长链路编排。
|
||||||
- 若线上出现 Agent 越权调用 Tool,优先检查这里的 Tool 白名单、Instruction 与上游直连动作分支,而不是修改 Answer 节点。
|
- 若线上出现 Agent 越权调用 Tool,优先检查这里的 Tool 白名单、Instruction 与上游直连动作分支,而不是修改 Answer 节点。
|
||||||
|
|
||||||
@@ -1986,21 +1989,21 @@ Agent 禁用 Tool:
|
|||||||
```text
|
```text
|
||||||
#### 角色
|
#### 角色
|
||||||
|
|
||||||
你是 **货代发货通知助手**,通过 Hxops Tool API 处理客户发货指令。需要人工复核时暂停,等待用户明确选择后再继续。
|
你是 **货代发货通知助手**,通过发货通知 Tool API 处理客户发货指令。需要人工复核时暂停,等待用户明确选择后再继续。
|
||||||
|
|
||||||
发货通知已由 **Hxops 聊天区上传并保存 raw_text**;随后由画布 LLM 节点解析订单需求,并调用 `parse_notice(structured=...)` 落库。你收到 `parse_msg`(或 `get_task_status.message`)后**原文展示**并引导确认。库存 Excel 由用户在 Hxops 上传后,由画布 **Tool 节点**完成列映射;Agent **禁止**自行推断 `map_json`,也不要脱离既定解析节点重复执行 `parse_notice`。
|
发货通知已由 **当前对话上传并保存 raw_text**;随后由画布 LLM 节点解析订单需求,并调用 `parse_notice(structured=...)` 落库。你收到 `parse_msg`(或 `get_task_status.message`)后**原文展示**并引导确认。库存 Excel 由用户在当前对话上传后,由画布 **Tool 节点**完成列映射;Agent **禁止**自行推断 `map_json`,也不要脱离既定解析节点重复执行 `parse_notice`。
|
||||||
若用户用自然语言要求“改采购单号 / 改预订单号 / 改料号 / 改数量 / 新增一行 / 删除一行”,应优先调用 `update_notice_fields`、`update_notice_line`、`add_notice_line`、`remove_notice_line` 持久化修改,禁止只在回复里口头改写解析结果。
|
若用户用自然语言要求“改采购单号 / 改预订单号 / 改料号 / 改数量 / 新增一行 / 删除一行”,应优先调用 `update_notice_fields`、`update_notice_line`、`add_notice_line`、`remove_notice_line` 持久化修改,禁止只在回复里口头改写解析结果。
|
||||||
|
|
||||||
当 Hxops 已上传通知并自动发起首轮续办时,你**不得**再询问用户“是否开始解析”“是否现在开始解析”“请确认是否开始解析”。首轮续办的正确行为是:立即读取 `raw_text` → 由画布 LLM 节点抽取 structured → 调用 `parse_notice(structured=...)` → 再根据返回结果决定是否进入人工确认。只有当 `parse_notice` 或后端状态机明确返回 `needs_human` / `stop_agent_turn=true` 时,才允许进入确认语义。
|
当 **当前对话** 已上传通知并自动发起首轮续办时,你**不得**再询问用户“是否开始解析”“是否现在开始解析”“请确认是否开始解析”。首轮续办的正确行为是:立即读取 `raw_text` → 由画布 LLM 节点抽取 structured → 调用 `parse_notice(structured=...)` → 再根据返回结果决定是否进入人工确认。只有当 `parse_notice` 或后端状态机明确返回 `needs_human` / `stop_agent_turn=true` 时,才允许进入确认语义。
|
||||||
|
|
||||||
首层附件分流由 Chatflow 的 Code 节点完成(通知/库存附件 → 引导回 Hxops 上传)。你负责第二层业务理解与 Tool 调用,**不要接管首层分流职责**。
|
首层附件分流由 Chatflow 的 Code 节点完成(通知/库存附件 → 引导回 **当前对话** 上传)。你负责第二层业务理解与 Tool 调用,**不要接管首层分流职责**。
|
||||||
|
|
||||||
#### 主流程
|
#### 主流程
|
||||||
|
|
||||||
【Hxops 已完成】建 task + raw_text 落库
|
【宿主系统已完成】建 task + raw_text 落库
|
||||||
→ Dify LLM 解析订单需求 + parse_notice(structured=...)
|
→ Dify LLM 解析订单需求 + parse_notice(structured=...)
|
||||||
→ submit_decision(confirm)
|
→ submit_decision(confirm)
|
||||||
→ Tool 库存上传(Hxops 前端)+ apply_inventory_mapping(Tool)
|
→ Tool 库存上传(**当前对话** 前端)+ apply_inventory_mapping(Tool)
|
||||||
→ 【暂停】align_msg
|
→ 【暂停】align_msg
|
||||||
→ submit_decision(confirm_inventory_mapping)
|
→ submit_decision(confirm_inventory_mapping)
|
||||||
→ hxops worker 统一续跑匹配、Excel 生成与上传
|
→ hxops worker 统一续跑匹配、Excel 生成与上传
|
||||||
@@ -2016,6 +2019,7 @@ Agent 禁用 Tool:
|
|||||||
| `stop_agent_turn` | `true` = 本轮立即停止,等待用户 |
|
| `stop_agent_turn` | `true` = 本轮立即停止,等待用户 |
|
||||||
| `forbidden_next_tools` | 禁止在本轮或下轮调用的 Tool |
|
| `forbidden_next_tools` | 禁止在本轮或下轮调用的 Tool |
|
||||||
| `human_options` | 须人工时的选项 |
|
| `human_options` | 须人工时的选项 |
|
||||||
|
| `action_buttons` | 宿主系统可渲染的按钮配置,Agent 只读取语义,不在正文重复列出 |
|
||||||
| `message` | 固定格式人类可读文案(须原文展示) |
|
| `message` | 固定格式人类可读文案(须原文展示) |
|
||||||
| `data.schema_preview` | 表头 + 样例行 |
|
| `data.schema_preview` | 表头 + 样例行 |
|
||||||
| `data.field_alignment` | 字段对齐详情 |
|
| `data.field_alignment` | 字段对齐详情 |
|
||||||
@@ -2035,9 +2039,10 @@ Agent 禁用 Tool:
|
|||||||
11. 多文件场景下,库存快照按批次共享;字段映射确认一次后,本批各 task 可由后端 worker 分别推进匹配、生成与上传。
|
11. 多文件场景下,库存快照按批次共享;字段映射确认一次后,本批各 task 可由后端 worker 分别推进匹配、生成与上传。
|
||||||
12. 解析修订:自然语言改 PO/料号/数量/增删行 → `update_notice_*`;禁止只在回复里口头改写。
|
12. 解析修订:自然语言改 PO/料号/数量/增删行 → `update_notice_*`;禁止只在回复里口头改写。
|
||||||
13. 禁止 Agent 调用 `create_batch` / `create_task`。
|
13. 禁止 Agent 调用 `create_batch` / `create_task`。
|
||||||
14. 通知文件原始上传由 Hxops 完成;订单需求首轮解析由 Dify LLM 节点产出 structured,再由 `parse_notice(structured=...)` 落库。
|
14. 通知文件原始上传由 **当前对话** 完成;订单需求首轮解析由 Dify LLM 节点产出 structured,再由 `parse_notice(structured=...)` 落库。
|
||||||
15. 禁止自行推断 `map_json`。
|
15. 禁止自行推断 `map_json`。
|
||||||
16. 若 `human_options` 出现 `upload_inventory_file / paste_inventory_json / retry_upload / generate_excel / download_excel / mark_manual_uploaded / refresh` 等前端动作,只负责解释并引导,不得把它们当作 Tool 调用。
|
16. 若 `human_options` 出现 `upload_inventory_file / paste_inventory_json / retry_upload / generate_excel / download_excel / mark_manual_uploaded / refresh` 等前端动作,只负责解释并引导,不得把它们当作 Tool 调用。
|
||||||
|
17. 若 Tool 返回 `action_buttons` / `human_options`,最终回复正文**禁止**生成任何操作菜单、编号选项、按钮清单或“推荐下一步”动作列表。不要输出类似“推荐下一步:”“请选择以下操作:”“请选择操作:”“1. 重新上传库存”“2. 更正映射”“3. 重新匹配”“4. 驳回”。正文只说明当前状态、业务原因和影响;如需要用户操作,只写“请使用下方按钮继续”。可点击按钮由宿主系统根据 `action_buttons` 渲染。
|
||||||
|
|
||||||
#### 查询模板
|
#### 查询模板
|
||||||
|
|
||||||
|
|||||||
@@ -91,7 +91,9 @@
|
|||||||
SN-20260529-A1B2C3D4
|
SN-20260529-A1B2C3D4
|
||||||
```
|
```
|
||||||
|
|
||||||
后续所有上传、确认、匹配、导出都围绕**同一任务编号**进行。请在对照库存、核对结果时始终关注助手回复中的该编号,**不要在同一对话里重复发起「新建任务」**,以免数据分散。
|
后续所有上传、确认、匹配、导出都围绕**明确的任务编号**进行。一次业务委托可以在同一 Agent 会话中拆成多个批次(`SB-...`)和多票任务(`SN-...`);聊天顶部会展示会话执行摘要、批次列表和当前聚焦任务。请在对照库存、核对结果时始终关注当前聚焦的批次与任务编号。
|
||||||
|
|
||||||
|
同一会话中的多个批次会共享业务委托背景和库存快照等上下文,但执行动作彼此隔离:确认、驳回、重试、上传等操作只影响界面标明的当前批次或当前任务,跨批次批量操作不会自动发生。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -524,10 +526,10 @@ A:业务上**一般为 8~12 位纯数字**(如 `1000140351`)。若格式
|
|||||||
A:不会。库存匹配只看 SKU、Reservation ID、需求数量;但导出 Excel 前仍建议在解析确认阶段核对单价与金额。
|
A:不会。库存匹配只看 SKU、Reservation ID、需求数量;但导出 Excel 前仍建议在解析确认阶段核对单价与金额。
|
||||||
|
|
||||||
**Q:助手文字建议和下方按钮不一致怎么办?**
|
**Q:助手文字建议和下方按钮不一致怎么办?**
|
||||||
A:以**按钮和任务当前状态**为准;若任务已驳回,不应再出现「确认字段对齐」类按钮。遇此类情况请联系 IT 并保留截图。
|
A:以**系统按钮和任务当前状态**为准。助手正文只负责说明状态,不应重复列出一套操作清单;若正文和按钮不一致,请以按钮为准并保留截图反馈。
|
||||||
|
|
||||||
**Q:同一对话里能否处理两票货?**
|
**Q:同一对话里能否处理两票货?**
|
||||||
A:建议**一票货一个对话、一个 SN-… 编号**,避免混淆。
|
A:可以。现在推荐按**一次业务委托一个 Agent 会话**处理;同一会话下可以包含多个批次和多票任务。操作前请看清顶部显示的当前批次 `SB-...` 和当前任务 `SN-...`,确认、驳回、重试等动作只作用于当前聚焦范围。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
|
|||||||
import type {
|
import type {
|
||||||
ShippingBatchSummary,
|
ShippingBatchSummary,
|
||||||
ShippingChatActionsResponse,
|
ShippingChatActionsResponse,
|
||||||
|
ShippingConversationWorkspace,
|
||||||
ShippingDecisionResponse,
|
ShippingDecisionResponse,
|
||||||
ShippingInventoryUploadResponse,
|
ShippingInventoryUploadResponse,
|
||||||
ShippingNoticeHeader,
|
ShippingNoticeHeader,
|
||||||
@@ -50,6 +51,12 @@ export const getWorkspaceShippingBatch = (batchNo: string) =>
|
|||||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}`,
|
`/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) =>
|
export const getWorkspaceShippingBatchFocusTask = (batchNo: string) =>
|
||||||
getJson<ShippingTaskSummary>(
|
getJson<ShippingTaskSummary>(
|
||||||
@@ -476,6 +483,27 @@ export async function markWorkspaceShippingManualUploaded(taskNo: string) {
|
|||||||
return body;
|
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。
|
* 生成发货 Excel。
|
||||||
* @param taskNo - 发货任务编号
|
* @param taskNo - 发货任务编号
|
||||||
@@ -504,6 +532,9 @@ export type {
|
|||||||
ShippingBatchSummary,
|
ShippingBatchSummary,
|
||||||
ShippingChatAction,
|
ShippingChatAction,
|
||||||
ShippingChatActionsResponse,
|
ShippingChatActionsResponse,
|
||||||
|
ShippingConversationBatch,
|
||||||
|
ShippingConversationWorkspace,
|
||||||
|
ShippingConversationWorkspaceSummary,
|
||||||
ShippingCurrentStepProgress,
|
ShippingCurrentStepProgress,
|
||||||
ShippingDecisionResponse,
|
ShippingDecisionResponse,
|
||||||
ShippingInventoryUploadResponse,
|
ShippingInventoryUploadResponse,
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ const props = defineProps<{
|
|||||||
canSendMessage: boolean;
|
canSendMessage: boolean;
|
||||||
isShippingNoticeAgent: boolean;
|
isShippingNoticeAgent: boolean;
|
||||||
shippingSuggestedPrompt: string;
|
shippingSuggestedPrompt: string;
|
||||||
|
shippingFocusTaskNo?: string;
|
||||||
|
shippingFocusReason?: string;
|
||||||
/** 用对象包裹 Ref,避免 template 自动解包 */
|
/** 用对象包裹 Ref,避免 template 自动解包 */
|
||||||
shippingPickerRefHolder: { pickerRef: Ref<HTMLInputElement | null> };
|
shippingPickerRefHolder: { pickerRef: Ref<HTMLInputElement | null> };
|
||||||
getKbLabel: (kb: string) => string;
|
getKbLabel: (kb: string) => string;
|
||||||
@@ -53,6 +55,7 @@ const emit = defineEmits<{
|
|||||||
'add-remote-url': [url: string];
|
'add-remote-url': [url: string];
|
||||||
'shipping-inventory-selected': [event: Event];
|
'shipping-inventory-selected': [event: Event];
|
||||||
'use-shipping-suggested-prompt': [];
|
'use-shipping-suggested-prompt': [];
|
||||||
|
'clear-shipping-focus': [];
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const filePickerRef = ref<HTMLInputElement | null>(null);
|
const filePickerRef = ref<HTMLInputElement | null>(null);
|
||||||
@@ -144,10 +147,26 @@ onBeforeUnmount(() => {
|
|||||||
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
|
<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="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 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
|
<textarea
|
||||||
v-model="inputValue"
|
v-model="inputValue"
|
||||||
rows="1"
|
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"
|
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;"
|
style="min-height: 44px; max-height: 220px;"
|
||||||
:disabled="isThinking || isVoiceTranscribing"
|
:disabled="isThinking || isVoiceTranscribing"
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ const {
|
|||||||
isMessageRunProgressLoading: (msg: ChatMessage) => boolean;
|
isMessageRunProgressLoading: (msg: ChatMessage) => boolean;
|
||||||
toolRunProgress: ToolRunProgress | null;
|
toolRunProgress: ToolRunProgress | null;
|
||||||
toolRunProgressTitle: string;
|
toolRunProgressTitle: string;
|
||||||
|
showScrollToBottom: boolean;
|
||||||
/** 供父级滚动逻辑绑定 main 元素 */
|
/** 供父级滚动逻辑绑定 main 元素 */
|
||||||
scrollContainerHolder: { el: Ref<HTMLElement | null> };
|
scrollContainerHolder: { el: Ref<HTMLElement | null> };
|
||||||
}>();
|
}>();
|
||||||
@@ -49,6 +50,7 @@ const emit = defineEmits<{
|
|||||||
regenerate: [];
|
regenerate: [];
|
||||||
'open-feedback': [index: number];
|
'open-feedback': [index: number];
|
||||||
'select-question': [question: string];
|
'select-question': [question: string];
|
||||||
|
'scroll-to-bottom': [];
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const bindScrollContainer = (node: unknown) => {
|
const bindScrollContainer = (node: unknown) => {
|
||||||
@@ -57,9 +59,10 @@ const bindScrollContainer = (node: unknown) => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<main
|
<main class="relative min-h-0 flex-1">
|
||||||
|
<div
|
||||||
:ref="bindScrollContainer"
|
:ref="bindScrollContainer"
|
||||||
class="flex-1 p-3 md:p-8"
|
class="h-full p-3 md:p-8"
|
||||||
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
|
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
|
||||||
>
|
>
|
||||||
<div :class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'">
|
<div :class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'">
|
||||||
@@ -104,5 +107,16 @@ const bindScrollContainer = (node: unknown) => {
|
|||||||
<ChatThinkingBubble v-if="showThinkingBubble" />
|
<ChatThinkingBubble v-if="showThinkingBubble" />
|
||||||
<div v-if="messages.length > 0" class="h-2 md:h-3" />
|
<div v-if="messages.length > 0" class="h-2 md:h-3" />
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
v-if="showScrollToBottom"
|
||||||
|
type="button"
|
||||||
|
class="absolute bottom-4 left-1/2 z-10 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-5"
|
||||||
|
:title="$t('chat.scrollToLatest')"
|
||||||
|
@click="emit('scroll-to-bottom')"
|
||||||
|
>
|
||||||
|
<span aria-hidden="true" class="-mt-1">↓</span>
|
||||||
|
</button>
|
||||||
</main>
|
</main>
|
||||||
</template>
|
</template>
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* features/chat/components/ChatViewContent.vue
|
* features/chat/components/ChatViewContent.vue
|
||||||
* 用途:对话页主区域,组合侧栏、发货批次进度区、消息列表、输入栏与内置浏览器。
|
* 用途:对话页主区域,组合侧栏、发货批次进度区、消息列表、输入栏与内置浏览器。
|
||||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingBatchProgressPanel、chat.context。
|
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingBatchProgressPanel、ShippingBatchWorkspaceDrawer、chat.context。
|
||||||
* 逻辑:本文件只做页面结构编排;发货批次进度样式与任务续办交互下沉到独立面板组件。
|
* 逻辑:本文件只做页面结构编排;发货批次进度样式与任务续办交互下沉到独立面板组件。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<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 ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
|
||||||
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||||
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.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';
|
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||||
|
|
||||||
const page = useChatPageContext();
|
const page = useChatPageContext();
|
||||||
@@ -85,14 +86,14 @@ const page = useChatPageContext();
|
|||||||
<div class="flex min-h-0 flex-1 flex-col">
|
<div class="flex min-h-0 flex-1 flex-col">
|
||||||
<ShippingBatchProgressPanel
|
<ShippingBatchProgressPanel
|
||||||
v-if="page.isShippingNoticeAgent && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
|
v-if="page.isShippingNoticeAgent && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
|
||||||
|
:conversation-workspace="page.shippingConversationWorkspace"
|
||||||
|
:active-batch-no="page.activeShippingBatchNo"
|
||||||
:batch-summary="page.shippingBatchSummary"
|
:batch-summary="page.shippingBatchSummary"
|
||||||
:batch-tasks="page.shippingBatchTasks"
|
:batch-tasks="page.shippingBatchTasks"
|
||||||
:active-task-detail="page.activeShippingTaskDetail"
|
:active-task-detail="page.activeShippingTaskDetail"
|
||||||
:tasks-expanded="page.shippingBatchTasksExpanded"
|
:workspace-open="page.shippingWorkspaceOpen"
|
||||||
:inventory-selection-active="page.shippingInventorySelectionActive && page.shippingBatchTasks?.length > 1"
|
@switch-batch="page.switchShippingBatch"
|
||||||
@update:tasks-expanded="page.shippingBatchTasksExpanded = $event"
|
@toggle-workspace="page.shippingWorkspaceOpen = !page.shippingWorkspaceOpen"
|
||||||
@focus-task="page.switchShippingFocusTask"
|
|
||||||
@resume-task="page.resumeShippingTask"
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ChatMessageList
|
<ChatMessageList
|
||||||
@@ -116,6 +117,7 @@ const page = useChatPageContext();
|
|||||||
:is-message-run-progress-loading="page.isMessageRunProgressLoading"
|
:is-message-run-progress-loading="page.isMessageRunProgressLoading"
|
||||||
:tool-run-progress="page.toolRunProgress"
|
:tool-run-progress="page.toolRunProgress"
|
||||||
:tool-run-progress-title="page.toolRunProgressTitle"
|
:tool-run-progress-title="page.toolRunProgressTitle"
|
||||||
|
:show-scroll-to-bottom="page.showScrollToBottom"
|
||||||
:scroll-container-holder="page.scrollContainerHolder"
|
:scroll-container-holder="page.scrollContainerHolder"
|
||||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||||
@edit="page.input = $event"
|
@edit="page.input = $event"
|
||||||
@@ -123,6 +125,7 @@ const page = useChatPageContext();
|
|||||||
@regenerate="page.regenerate"
|
@regenerate="page.regenerate"
|
||||||
@open-feedback="page.handleOpenFeedback($event)"
|
@open-feedback="page.handleOpenFeedback($event)"
|
||||||
@select-question="page.handleSend"
|
@select-question="page.handleSend"
|
||||||
|
@scroll-to-bottom="page.scrollToBottom"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ChatInputBar
|
<ChatInputBar
|
||||||
@@ -139,6 +142,8 @@ const page = useChatPageContext();
|
|||||||
:can-send-message="page.canSendMessage"
|
:can-send-message="page.canSendMessage"
|
||||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||||
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
|
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
|
||||||
|
:shipping-focus-task-no="page.focusedShippingTaskNo"
|
||||||
|
:shipping-focus-reason="page.shippingFocusReason"
|
||||||
:shipping-picker-ref-holder="page.shippingPickerRefHolder"
|
:shipping-picker-ref-holder="page.shippingPickerRefHolder"
|
||||||
:get-kb-label="page.getKbLabel"
|
:get-kb-label="page.getKbLabel"
|
||||||
@send="page.handleSend()"
|
@send="page.handleSend()"
|
||||||
@@ -148,6 +153,7 @@ const page = useChatPageContext();
|
|||||||
@add-remote-url="page.addRemoteUrlAttachment"
|
@add-remote-url="page.addRemoteUrlAttachment"
|
||||||
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
||||||
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
|
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
|
||||||
|
@clear-shipping-focus="page.clearShippingFocus"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -165,6 +171,23 @@ const page = useChatPageContext();
|
|||||||
@start-resize="page.browser.startResize"
|
@start-resize="page.browser.startResize"
|
||||||
@close="page.browser.close"
|
@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>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</ChatShell>
|
</ChatShell>
|
||||||
|
|||||||
@@ -1,43 +1,45 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
/**
|
/**
|
||||||
* features/chat/components/ShippingBatchProgressPanel.vue
|
* features/chat/components/ShippingBatchProgressPanel.vue
|
||||||
* 用途:发货通知聊天顶部批次进度卡片,按原型方案 C 展示批次概览、任务切换列表、七步进度与续办弹层。
|
* 用途:发货通知聊天顶部轻量批次状态条,展示当前批次进度与工作台入口。
|
||||||
* 依赖:shippingStepper、shipping.api.types、vue-i18n、lucide-vue-next。
|
* 依赖:shipping.api.types、vue-i18n、批次 retry API。
|
||||||
* 逻辑:上游由 ChatViewContent 传入批次/任务状态;本组件只负责展示与抛出 focus/resume 事件,不直接请求后端。
|
* 逻辑:生成式执行摘要由聊天消息流承载;本组件只提供固定状态 chrome 和明确范围的批次操作。
|
||||||
*/
|
*/
|
||||||
import { computed, ref } from 'vue';
|
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 { useI18n } from 'vue-i18n';
|
||||||
import { buildShippingWorkflowSteps, type ShippingWorkflowStepItem } from '@/features/chat/shipping';
|
|
||||||
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
|
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
|
||||||
import { useMessage } from '@/shared/composables/useMessage';
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
import type {
|
import type {
|
||||||
ShippingBatchSummary,
|
ShippingBatchSummary,
|
||||||
|
ShippingConversationWorkspace,
|
||||||
ShippingTaskDetail,
|
ShippingTaskDetail,
|
||||||
ShippingTaskSummary,
|
ShippingTaskSummary,
|
||||||
} from '@/features/chat/api/shipping.api';
|
} from '@/features/chat/api/shipping.api';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
|
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||||
|
activeBatchNo: string;
|
||||||
batchSummary: ShippingBatchSummary | null;
|
batchSummary: ShippingBatchSummary | null;
|
||||||
batchTasks: ShippingTaskSummary[];
|
batchTasks: ShippingTaskSummary[];
|
||||||
activeTaskDetail: ShippingTaskDetail | null;
|
activeTaskDetail: ShippingTaskDetail | null;
|
||||||
tasksExpanded: boolean;
|
workspaceOpen: boolean;
|
||||||
inventorySelectionActive: boolean;
|
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
'update:tasksExpanded': [value: boolean];
|
'switch-batch': [batchNo: string];
|
||||||
'focus-task': [taskNo: string];
|
'toggle-workspace': [];
|
||||||
'resume-task': [taskNo: string];
|
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const msg = useMessage();
|
const msg = useMessage();
|
||||||
const showTaskDialog = ref(false);
|
|
||||||
const retryingPending = ref(false);
|
const retryingPending = ref(false);
|
||||||
|
|
||||||
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
|
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 processSummary = computed(() => {
|
||||||
const summary = props.batchSummary?.process_summary || null;
|
const summary = props.batchSummary?.process_summary || null;
|
||||||
@@ -55,121 +57,36 @@ const processSummary = computed(() => {
|
|||||||
return { total, completed, running, pending };
|
return { total, completed, running, pending };
|
||||||
});
|
});
|
||||||
|
|
||||||
const currentTask = computed<ShippingTaskSummary | ShippingTaskDetail | null>(() => {
|
const abnormalCount = computed(() => {
|
||||||
const focusTaskNo = String(props.batchSummary?.current_focus_task_no || '').trim().toUpperCase();
|
const batchSummary = props.batchSummary?.process_summary || {};
|
||||||
if (focusTaskNo) {
|
return Number(batchSummary.failed || 0) + Number((batchSummary as { needs_human?: number }).needs_human || 0);
|
||||||
return props.batchTasks.find((task) => String(task.task_no || '').trim().toUpperCase() === focusTaskNo)
|
|
||||||
|| props.activeTaskDetail
|
|
||||||
|| null;
|
|
||||||
}
|
|
||||||
return props.activeTaskDetail || props.batchTasks[0] || null;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const currentTaskNo = computed(() => String(currentTask.value?.task_no || '').trim().toUpperCase());
|
const progressPercent = computed(() =>
|
||||||
const currentTaskName = computed(() =>
|
processSummary.value.total
|
||||||
String(
|
? Math.round((processSummary.value.completed / processSummary.value.total) * 100)
|
||||||
currentTask.value?.source_file_name
|
: 0,
|
||||||
|| currentTask.value?.customer_name
|
|
||||||
|| t('chat.shippingNoticeUi.currentNotice'),
|
|
||||||
).trim(),
|
|
||||||
);
|
);
|
||||||
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[]) =>
|
const executionStateMeta = computed(() => {
|
||||||
steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
if (abnormalCount.value > 0) {
|
||||||
|
|
||||||
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;
|
|
||||||
return {
|
return {
|
||||||
index: safeIndex + 1,
|
text: t('chat.shippingNoticeUi.needsIntervention'),
|
||||||
label: t(steps[safeIndex]?.label || 'chat.shippingNoticeUi.processing'),
|
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 {
|
||||||
|
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 handleRetryPending = async () => {
|
||||||
const batchNo = String(props.batchSummary?.batch_no || '').trim();
|
const batchNo = String(props.batchSummary?.batch_no || '').trim();
|
||||||
if (!batchNo || retryingPending.value) return;
|
if (!batchNo || retryingPending.value) return;
|
||||||
@@ -186,15 +103,37 @@ const handleRetryPending = async () => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section
|
<section class="w-full px-3 pt-3 md:px-8 md:pr-10">
|
||||||
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="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="border-b border-sky-100/80 px-4 py-3">
|
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
<div class="min-w-0 flex-1">
|
||||||
<div class="text-xs text-slate-500">
|
<div class="flex flex-wrap items-center gap-2 text-xs text-slate-500">
|
||||||
{{ summaryLine }}
|
<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>
|
||||||
<div class="flex items-center gap-2">
|
<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 shrink-0 items-center gap-2">
|
||||||
<button
|
<button
|
||||||
v-if="batchSummary?.batch_no"
|
v-if="batchSummary?.batch_no"
|
||||||
type="button"
|
type="button"
|
||||||
@@ -202,242 +141,20 @@ const handleRetryPending = async () => {
|
|||||||
:disabled="retryingPending"
|
:disabled="retryingPending"
|
||||||
@click="handleRetryPending"
|
@click="handleRetryPending"
|
||||||
>
|
>
|
||||||
|
<RefreshCw class="h-3.5 w-3.5" :class="retryingPending ? 'animate-spin' : ''" />
|
||||||
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryPendingTasks') }}
|
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryPendingTasks') }}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="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"
|
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" />
|
<List class="h-3.5 w-3.5" />
|
||||||
{{ t('chat.shippingNoticeUi.taskListResume') }}
|
{{ workspaceOpen ? t('chat.shippingNoticeUi.collapseTaskList') : t('chat.shippingNoticeUi.expandTaskList') }}
|
||||||
</button>
|
<span class="text-brand-600">{{ workspaceOpen ? '▲' : '▼' }}</span>
|
||||||
<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')} ▼` }}
|
|
||||||
</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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Teleport>
|
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</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 { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
|
||||||
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
|
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
|
||||||
|
|
||||||
|
export interface SendMessageLifecycleHooks {
|
||||||
|
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
const normalizeResources = (resources: unknown) => {
|
const normalizeResources = (resources: unknown) => {
|
||||||
if (!resources) return [];
|
if (!resources) return [];
|
||||||
if (Array.isArray(resources)) return resources;
|
if (Array.isArray(resources)) return resources;
|
||||||
@@ -191,15 +195,17 @@ 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: 'local_file'; upload_file_id: string }
|
||||||
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: 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();
|
||||||
const runViewId = viewId.value;
|
const runViewId = viewId.value;
|
||||||
const runMessages = messages.value;
|
const runMessages = messages.value;
|
||||||
const run: ChatRun = {
|
const run: ChatRun = {
|
||||||
runId: ++runSeq,
|
runId: ++runSeq,
|
||||||
agentId,
|
agentId,
|
||||||
viewId: runViewId,
|
viewId: runViewId,
|
||||||
query,
|
query: displayQuery,
|
||||||
messages: runMessages,
|
messages: runMessages,
|
||||||
conversationId: conversationId.value,
|
conversationId: conversationId.value,
|
||||||
status: 'running',
|
status: 'running',
|
||||||
@@ -209,7 +215,7 @@ export function useChat() {
|
|||||||
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
|
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
|
||||||
activeRunId.value = run.runId;
|
activeRunId.value = run.runId;
|
||||||
|
|
||||||
runMessages.push({ role: 'user', content: query });
|
runMessages.push({ role: 'user', content: displayQuery });
|
||||||
let botMsgIndex: number | null = null;
|
let botMsgIndex: number | null = null;
|
||||||
let hasAssistantContent = false;
|
let hasAssistantContent = false;
|
||||||
let hasTerminalEvent = false;
|
let hasTerminalEvent = false;
|
||||||
@@ -239,6 +245,7 @@ export function useChat() {
|
|||||||
files: files && files.length > 0 ? files : undefined,
|
files: files && files.length > 0 ? files : undefined,
|
||||||
task_id: context?.task_id || undefined,
|
task_id: context?.task_id || undefined,
|
||||||
batch_no: context?.batch_no || undefined,
|
batch_no: context?.batch_no || undefined,
|
||||||
|
display_query: context?.display_query || undefined,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -359,6 +366,12 @@ export function useChat() {
|
|||||||
if (messages.value === runMessages) {
|
if (messages.value === runMessages) {
|
||||||
isThinking.value = false;
|
isThinking.value = false;
|
||||||
}
|
}
|
||||||
|
if (run.status === 'done' && botMsgIndex !== null) {
|
||||||
|
const botMsg = runMessages[botMsgIndex];
|
||||||
|
if (botMsg) {
|
||||||
|
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -289,6 +289,7 @@ export function useChatPage() {
|
|||||||
clearAttachments: attachmentApi.clearAttachments,
|
clearAttachments: attachmentApi.clearAttachments,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
|
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
|
||||||
|
onAssistantMessageFinished: shipping.finalizeShippingAssistantMessage,
|
||||||
refreshHistoryAfterSend,
|
refreshHistoryAfterSend,
|
||||||
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
|
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
|
||||||
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
||||||
@@ -354,6 +355,8 @@ export function useChatPage() {
|
|||||||
currentUser,
|
currentUser,
|
||||||
chatScrollContainer,
|
chatScrollContainer,
|
||||||
scrollContainerHolder,
|
scrollContainerHolder,
|
||||||
|
showScrollToBottom: scroll.showScrollToBottom,
|
||||||
|
scrollToBottom: scroll.scrollToBottomSmooth,
|
||||||
messages,
|
messages,
|
||||||
isThinking,
|
isThinking,
|
||||||
conversationId,
|
conversationId,
|
||||||
@@ -414,13 +417,22 @@ export function useChatPage() {
|
|||||||
showChatRating,
|
showChatRating,
|
||||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||||
shippingBatchSummary: shipping.shippingBatchSummary,
|
shippingBatchSummary: shipping.shippingBatchSummary,
|
||||||
|
shippingConversationWorkspace: shipping.shippingConversationWorkspace,
|
||||||
|
activeShippingBatchNo: shipping.activeShippingBatchNo,
|
||||||
|
focusedShippingTaskNo: shipping.focusedShippingTaskNo,
|
||||||
|
shippingFocusReason: shipping.shippingFocusReason,
|
||||||
shippingBatchTasks: shipping.shippingBatchTasks,
|
shippingBatchTasks: shipping.shippingBatchTasks,
|
||||||
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
|
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
|
||||||
shippingBatchTasksExpanded: shipping.shippingBatchTasksExpanded,
|
shippingWorkspaceOpen: shipping.shippingWorkspaceOpen,
|
||||||
|
retryingShippingPendingTasks: shipping.retryingShippingPendingTasks,
|
||||||
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
|
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
|
||||||
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
|
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
|
||||||
|
switchShippingBatch: shipping.switchShippingBatch,
|
||||||
switchShippingFocusTask: shipping.switchShippingFocusTask,
|
switchShippingFocusTask: shipping.switchShippingFocusTask,
|
||||||
|
clearShippingFocus: shipping.clearShippingFocus,
|
||||||
resumeShippingTask: shipping.resumeShippingTask,
|
resumeShippingTask: shipping.resumeShippingTask,
|
||||||
|
retryCurrentShippingBatchPendingTasks: shipping.retryCurrentShippingBatchPendingTasks,
|
||||||
|
queryShippingShortageDetails: shipping.queryShippingShortageDetails,
|
||||||
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
|
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
|
||||||
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
|
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
|
||||||
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
|
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* features/chat/composables/useChatScroll.ts
|
* 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';
|
import type { ChatMessage } from '../types/chat.types';
|
||||||
|
|
||||||
export interface UseChatScrollOptions {
|
export interface UseChatScrollOptions {
|
||||||
@@ -13,6 +13,37 @@ export interface UseChatScrollOptions {
|
|||||||
export function useChatScroll(options: UseChatScrollOptions) {
|
export function useChatScroll(options: UseChatScrollOptions) {
|
||||||
const { container, messages } = options;
|
const { container, messages } = options;
|
||||||
let scrollToBottomFrame: number | null = null;
|
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 () => {
|
const scrollToBottom = async () => {
|
||||||
await nextTick();
|
await nextTick();
|
||||||
@@ -22,6 +53,17 @@ export function useChatScroll(options: UseChatScrollOptions) {
|
|||||||
top: el.scrollHeight,
|
top: el.scrollHeight,
|
||||||
behavior: 'auto',
|
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 () => {
|
const scrollToUserQuestion = async () => {
|
||||||
@@ -60,6 +102,9 @@ export function useChatScroll(options: UseChatScrollOptions) {
|
|||||||
window.cancelAnimationFrame(scrollToBottomFrame);
|
window.cancelAnimationFrame(scrollToBottomFrame);
|
||||||
scrollToBottomFrame = null;
|
scrollToBottomFrame = null;
|
||||||
}
|
}
|
||||||
|
observedContainer?.removeEventListener('scroll', updateNearBottomState);
|
||||||
|
observedContainer = null;
|
||||||
|
stopContainerWatch();
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 消息/思考态变化时自动滚动(思考结束滚到用户问题,否则贴底) */
|
/** 消息/思考态变化时自动滚动(思考结束滚到用户问题,否则贴底) */
|
||||||
@@ -79,15 +124,21 @@ export function useChatScroll(options: UseChatScrollOptions) {
|
|||||||
void scrollToUserQuestion();
|
void scrollToUserQuestion();
|
||||||
} else {
|
} else {
|
||||||
if (isThinking.value) wasThinking = true;
|
if (isThinking.value) wasThinking = true;
|
||||||
scheduleScrollToBottom();
|
if (isNearBottom.value) scheduleScrollToBottom();
|
||||||
|
else window.requestAnimationFrame(updateNearBottomState);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{ deep: false },
|
{ deep: false },
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
onBeforeUnmount(dispose);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
isNearBottom,
|
||||||
|
showScrollToBottom,
|
||||||
scrollToBottom,
|
scrollToBottom,
|
||||||
|
scrollToBottomSmooth,
|
||||||
scrollToUserQuestion,
|
scrollToUserQuestion,
|
||||||
scheduleScrollToBottom,
|
scheduleScrollToBottom,
|
||||||
setupThinkingScrollWatch,
|
setupThinkingScrollWatch,
|
||||||
|
|||||||
@@ -38,13 +38,20 @@ import {
|
|||||||
shippingActionButtonClass,
|
shippingActionButtonClass,
|
||||||
} from '../shipping';
|
} from '../shipping';
|
||||||
import {
|
import {
|
||||||
|
getWorkspaceShippingConversationBatches,
|
||||||
getWorkspaceShippingBatch,
|
getWorkspaceShippingBatch,
|
||||||
getWorkspaceShippingTask,
|
getWorkspaceShippingTask,
|
||||||
switchWorkspaceShippingBatchFocusTask,
|
switchWorkspaceShippingBatchFocusTask,
|
||||||
type ShippingBatchSummary,
|
type ShippingBatchSummary,
|
||||||
|
type ShippingConversationWorkspace,
|
||||||
type ShippingTaskDetail,
|
type ShippingTaskDetail,
|
||||||
type ShippingTaskSummary,
|
type ShippingTaskSummary,
|
||||||
} from '@/features/chat/api/shipping.api';
|
} from '@/features/chat/api/shipping.api';
|
||||||
|
import {
|
||||||
|
buildShortageDetailsMessage,
|
||||||
|
hasShortageLines,
|
||||||
|
isShippingShortageQueryIntent,
|
||||||
|
} from '../shipping/shippingShortageDetails';
|
||||||
|
|
||||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||||
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
|
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
|
||||||
@@ -75,6 +82,8 @@ export interface UseChatShippingOptions {
|
|||||||
agentId: number,
|
agentId: number,
|
||||||
kb: string,
|
kb: string,
|
||||||
files: ChatUploadFileSpec[],
|
files: ChatUploadFileSpec[],
|
||||||
|
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||||
|
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
|
||||||
) => Promise<void>;
|
) => Promise<void>;
|
||||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||||
@@ -114,9 +123,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
createNewChatView,
|
createNewChatView,
|
||||||
} = options;
|
} = options;
|
||||||
|
|
||||||
let invokeHandleSend: (() => Promise<void>) | null = null;
|
const shippingBindSend = (_fn: () => Promise<void>) => {
|
||||||
const shippingBindSend = (fn: () => Promise<void>) => {
|
void _fn;
|
||||||
invokeHandleSend = fn;
|
// 保留旧绑定入口,续办链路已改为直接调用 sendMessage 以支持 display_query 上下文。
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── 功能开关与 UI refs ────────────────────────────────────
|
// ── 功能开关与 UI refs ────────────────────────────────────
|
||||||
@@ -147,26 +156,30 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
});
|
});
|
||||||
const resolvedShippingTaskId = ref('');
|
const resolvedShippingTaskId = ref('');
|
||||||
const resolvedShippingBatchNo = ref('');
|
const resolvedShippingBatchNo = ref('');
|
||||||
|
const activeShippingBatchNo = ref('');
|
||||||
|
const focusedShippingTaskNo = ref('');
|
||||||
|
const shippingConversationWorkspace = ref<ShippingConversationWorkspace | null>(null);
|
||||||
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
|
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
|
||||||
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
|
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
|
||||||
const shippingBatchTasksExpanded = ref(false);
|
const shippingWorkspaceOpen = ref(false);
|
||||||
|
const retryingShippingPendingTasks = ref(false);
|
||||||
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
|
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
|
||||||
|
const shippingFocusReason = ref('');
|
||||||
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
|
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
|
||||||
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
|
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
|
||||||
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
|
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
|
||||||
const lastConversationSyncKey = ref('');
|
const lastConversationSyncKey = ref('');
|
||||||
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
|
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
const syncShippingBatchSummary = async (batchNo: string) => {
|
const applyShippingBatchDetail = (
|
||||||
const normalized = String(batchNo || '').trim();
|
detail: ShippingBatchSummary & { tasks?: ShippingTaskSummary[]; focus_task?: ShippingTaskSummary | null },
|
||||||
if (!normalized) {
|
fallbackBatchNo: string,
|
||||||
shippingBatchSummary.value = null;
|
) => {
|
||||||
shippingBatchTasks.value = [];
|
const normalizedBatchNo = detail.batch_no || fallbackBatchNo;
|
||||||
return;
|
resolvedShippingBatchNo.value = normalizedBatchNo;
|
||||||
|
if (!activeShippingBatchNo.value || activeShippingBatchNo.value === fallbackBatchNo) {
|
||||||
|
activeShippingBatchNo.value = normalizedBatchNo;
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
const detail = await getWorkspaceShippingBatch(normalized);
|
|
||||||
resolvedShippingBatchNo.value = detail.batch_no || normalized;
|
|
||||||
shippingBatchTasks.value = Array.isArray(detail.tasks) ? detail.tasks : [];
|
shippingBatchTasks.value = Array.isArray(detail.tasks) ? detail.tasks : [];
|
||||||
shippingBatchSummary.value = {
|
shippingBatchSummary.value = {
|
||||||
id: detail.id,
|
id: detail.id,
|
||||||
@@ -187,17 +200,59 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
if (preferredTaskNo) {
|
if (preferredTaskNo) {
|
||||||
resolvedShippingTaskId.value = preferredTaskNo;
|
resolvedShippingTaskId.value = preferredTaskNo;
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const syncShippingBatchSummary = async (batchNo: string) => {
|
||||||
|
const normalized = String(batchNo || '').trim();
|
||||||
|
if (!normalized) {
|
||||||
|
shippingBatchSummary.value = null;
|
||||||
|
shippingBatchTasks.value = [];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const detail = await getWorkspaceShippingBatch(normalized);
|
||||||
|
applyShippingBatchDetail(detail, normalized);
|
||||||
} catch {
|
} catch {
|
||||||
// ignore summary refresh failure in chat flow
|
// 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 switchShippingFocusTask = async (taskNo: string) => {
|
||||||
const batchNo = getActiveShippingBatchNo();
|
const batchNo = getActiveShippingBatchNo();
|
||||||
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
|
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
|
||||||
if (!batchNo || !normalizedTaskNo) return false;
|
if (!batchNo || !normalizedTaskNo) return false;
|
||||||
await switchWorkspaceShippingBatchFocusTask(batchNo, normalizedTaskNo);
|
await switchWorkspaceShippingBatchFocusTask(batchNo, normalizedTaskNo);
|
||||||
resolvedShippingTaskId.value = normalizedTaskNo;
|
resolvedShippingTaskId.value = normalizedTaskNo;
|
||||||
|
focusedShippingTaskNo.value = normalizedTaskNo;
|
||||||
|
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
|
||||||
if (shippingBatchSummary.value) {
|
if (shippingBatchSummary.value) {
|
||||||
shippingBatchSummary.value = {
|
shippingBatchSummary.value = {
|
||||||
...shippingBatchSummary.value,
|
...shippingBatchSummary.value,
|
||||||
@@ -205,11 +260,42 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
await syncShippingBatchSummary(batchNo);
|
await syncShippingBatchSummary(batchNo);
|
||||||
|
await syncShippingConversationWorkspace();
|
||||||
await syncActiveShippingTaskDetail(normalizedTaskNo);
|
await syncActiveShippingTaskDetail(normalizedTaskNo);
|
||||||
await refreshShippingActions();
|
await refreshShippingActions();
|
||||||
return true;
|
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 +310,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
shippingInventorySelectionTaskId.value = '';
|
shippingInventorySelectionTaskId.value = '';
|
||||||
resolvedShippingTaskId.value = '';
|
resolvedShippingTaskId.value = '';
|
||||||
resolvedShippingBatchNo.value = '';
|
resolvedShippingBatchNo.value = '';
|
||||||
|
activeShippingBatchNo.value = '';
|
||||||
|
focusedShippingTaskNo.value = '';
|
||||||
|
shippingFocusReason.value = '';
|
||||||
|
shippingConversationWorkspace.value = null;
|
||||||
shippingBatchSummary.value = null;
|
shippingBatchSummary.value = null;
|
||||||
shippingBatchTasks.value = [];
|
shippingBatchTasks.value = [];
|
||||||
shippingBatchTasksExpanded.value = false;
|
shippingWorkspaceOpen.value = false;
|
||||||
|
retryingShippingPendingTasks.value = false;
|
||||||
activeShippingTaskDetail.value = null;
|
activeShippingTaskDetail.value = null;
|
||||||
shippingConversationTaskIdCache.value = {};
|
shippingConversationTaskIdCache.value = {};
|
||||||
shippingInventorySchemaPreviewCache.value = {};
|
shippingInventorySchemaPreviewCache.value = {};
|
||||||
@@ -240,16 +331,31 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
|| '';
|
|| '';
|
||||||
|
|
||||||
const getActiveShippingBatchNo = () =>
|
const getActiveShippingBatchNo = () =>
|
||||||
resolvedShippingBatchNo.value
|
activeShippingBatchNo.value
|
||||||
|
|| resolvedShippingBatchNo.value
|
||||||
|| shippingBatchNoFromQuery.value
|
|| shippingBatchNoFromQuery.value
|
||||||
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|
||||||
|| '';
|
|| '';
|
||||||
|
|
||||||
const getCurrentShippingChatContext = () => ({
|
const getCurrentShippingChatContext = () => ({
|
||||||
task_id: getActiveShippingTaskId(),
|
task_id: getActiveBatchTaskId() || getActiveShippingTaskId(),
|
||||||
batch_no: getActiveShippingBatchNo(),
|
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 = () =>
|
const hasRunningShippingBatchTasks = () =>
|
||||||
shippingBatchTasks.value.some(
|
shippingBatchTasks.value.some(
|
||||||
(task) => !['uploaded', 'completed', 'closed', 'rejected'].includes(String(task.process_status || '').trim()),
|
(task) => !['uploaded', 'completed', 'closed', 'rejected'].includes(String(task.process_status || '').trim()),
|
||||||
@@ -269,10 +375,15 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const detail = await getWorkspaceShippingTask(normalized);
|
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;
|
activeShippingTaskDetail.value = detail;
|
||||||
const batchNo = String(detail.batch_no || '').trim();
|
if (detailBatchNo && resolvedShippingBatchNo.value !== detailBatchNo) {
|
||||||
if (batchNo && resolvedShippingBatchNo.value !== batchNo) {
|
resolvedShippingBatchNo.value = detailBatchNo;
|
||||||
resolvedShippingBatchNo.value = batchNo;
|
activeShippingBatchNo.value = activeShippingBatchNo.value || detailBatchNo;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
activeShippingTaskDetail.value = null;
|
activeShippingTaskDetail.value = null;
|
||||||
@@ -313,6 +424,16 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
return '';
|
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({
|
const { refreshShippingActions } = createShippingActionsRefresher({
|
||||||
isShippingNoticeAgent,
|
isShippingNoticeAgent,
|
||||||
messages,
|
messages,
|
||||||
@@ -330,6 +451,64 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
saveLocalMessageToBackend,
|
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({
|
const { sendShippingMenuMessage } = createShippingConversationHelpers({
|
||||||
conversationId,
|
conversationId,
|
||||||
history,
|
history,
|
||||||
@@ -410,7 +589,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
resolvedShippingBatchNo,
|
resolvedShippingBatchNo,
|
||||||
shippingBatchSummary,
|
shippingBatchSummary,
|
||||||
shippingBatchTasks,
|
shippingBatchTasks,
|
||||||
shippingBatchTasksExpanded,
|
|
||||||
shippingInventorySelectionActive,
|
shippingInventorySelectionActive,
|
||||||
shippingInventorySelectionTaskId,
|
shippingInventorySelectionTaskId,
|
||||||
shippingInventorySchemaPreviewCache,
|
shippingInventorySchemaPreviewCache,
|
||||||
@@ -422,7 +600,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
t,
|
t,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { handleShippingActionClick } = createShippingMenuHandlers({
|
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
|
||||||
isThinking,
|
isThinking,
|
||||||
getActiveShippingTaskId,
|
getActiveShippingTaskId,
|
||||||
messages,
|
messages,
|
||||||
@@ -455,6 +633,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
attachmentPolicy,
|
attachmentPolicy,
|
||||||
getActiveShippingTaskId,
|
getActiveShippingTaskId,
|
||||||
lastAssistantMessageContent,
|
lastAssistantMessageContent,
|
||||||
|
lastAssistantShippingActions,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
buildFileSpecsForSend,
|
buildFileSpecsForSend,
|
||||||
loadHistory,
|
loadHistory,
|
||||||
@@ -464,10 +643,13 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
openShippingInventoryPicker,
|
openShippingInventoryPicker,
|
||||||
executeShippingDecision,
|
executeShippingDecision,
|
||||||
executeShippingManualUpload,
|
executeShippingManualUpload,
|
||||||
|
handleShippingMenuAction,
|
||||||
handleShippingAutoUploadFile,
|
handleShippingAutoUploadFile,
|
||||||
handleShippingAutoUploadNoticeBatch,
|
handleShippingAutoUploadNoticeBatch,
|
||||||
refreshShippingActions,
|
refreshShippingActions,
|
||||||
shippingSuggestedPrompt,
|
shippingSuggestedPrompt,
|
||||||
|
isShippingShortageQueryIntent,
|
||||||
|
queryShippingShortageDetails,
|
||||||
msg,
|
msg,
|
||||||
t,
|
t,
|
||||||
});
|
});
|
||||||
@@ -492,8 +674,15 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
autoResumedShippingTasks.value[taskId] = true;
|
autoResumedShippingTasks.value[taskId] = true;
|
||||||
input.value = t('chat.shippingNoticeContinue', { taskId });
|
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId });
|
||||||
await invokeHandleSend?.();
|
await sendMessage(
|
||||||
|
t('chat.shippingNoticeContinue', { taskId }),
|
||||||
|
currentAgentId.value,
|
||||||
|
selectedKb.value,
|
||||||
|
[],
|
||||||
|
getCurrentShippingChatContextWithDisplay(displayText),
|
||||||
|
);
|
||||||
|
await loadHistory();
|
||||||
};
|
};
|
||||||
|
|
||||||
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
|
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
|
||||||
@@ -510,8 +699,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
/**
|
/**
|
||||||
* 续办指定任务,并把聊天上下文切到该任务继续推进。
|
* 续办指定任务,并把聊天上下文切到该任务继续推进。
|
||||||
*
|
*
|
||||||
* 核心逻辑:先切换批次焦点任务,再复用既有“请继续处理发货任务”提示词触发一次发送,
|
* 核心逻辑:先切换批次焦点任务,再把内部续办指令发给 Agent;
|
||||||
* 让 Agent 基于最新 task_id/batch_no 返回下一步动作。
|
* 前端和历史只展示业务端可理解的简短重试话术,避免暴露工具名。
|
||||||
* @param taskNo - 需要续办的任务编号
|
* @param taskNo - 需要续办的任务编号
|
||||||
* @returns 是否已成功触发续办
|
* @returns 是否已成功触发续办
|
||||||
*/
|
*/
|
||||||
@@ -520,11 +709,39 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
if (!normalizedTaskNo || !isShippingNoticeAgent.value || isThinking.value) return false;
|
if (!normalizedTaskNo || !isShippingNoticeAgent.value || isThinking.value) return false;
|
||||||
const switched = await switchShippingFocusTask(normalizedTaskNo);
|
const switched = await switchShippingFocusTask(normalizedTaskNo);
|
||||||
if (!switched) return false;
|
if (!switched) return false;
|
||||||
input.value = t('chat.shippingNoticeContinue', { taskId: normalizedTaskNo });
|
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: normalizedTaskNo });
|
||||||
await invokeHandleSend?.();
|
await sendMessage(
|
||||||
|
t('chat.shippingNoticeContinue', { taskId: normalizedTaskNo }),
|
||||||
|
currentAgentId.value,
|
||||||
|
selectedKb.value,
|
||||||
|
[],
|
||||||
|
getCurrentShippingChatContextWithDisplay(displayText),
|
||||||
|
);
|
||||||
|
await loadHistory();
|
||||||
|
await refreshShippingActions();
|
||||||
return true;
|
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 () => {
|
const onConversationLoadedEmpty = async () => {
|
||||||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
|
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
|
||||||
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
||||||
@@ -538,8 +755,15 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
||||||
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
|
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
|
||||||
void router.replace({ path: route.path, query: nextQuery });
|
void router.replace({ path: route.path, query: nextQuery });
|
||||||
input.value = t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value });
|
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: shippingTaskIdFromQuery.value });
|
||||||
await invokeHandleSend?.();
|
await sendMessage(
|
||||||
|
t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value }),
|
||||||
|
currentAgentId.value,
|
||||||
|
selectedKb.value,
|
||||||
|
[],
|
||||||
|
getCurrentShippingChatContextWithDisplay(displayText),
|
||||||
|
);
|
||||||
|
await loadHistory();
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -555,15 +779,16 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
}
|
}
|
||||||
if (!isShippingNoticeAgent.value) return;
|
if (!isShippingNoticeAgent.value) return;
|
||||||
const batchNo = getActiveShippingBatchNo();
|
const batchNo = getActiveShippingBatchNo();
|
||||||
const taskId = getActiveShippingTaskId();
|
const taskId = getActiveBatchTaskId();
|
||||||
if (!batchNo && !taskId) return;
|
if (!batchNo && !taskId) return;
|
||||||
|
|
||||||
shippingStatusPollTimer = setInterval(() => {
|
shippingStatusPollTimer = setInterval(() => {
|
||||||
if (!isShippingNoticeAgent.value) return;
|
if (!isShippingNoticeAgent.value) return;
|
||||||
const nextBatchNo = getActiveShippingBatchNo();
|
const nextBatchNo = getActiveShippingBatchNo();
|
||||||
const nextTaskId = getActiveShippingTaskId();
|
const nextTaskId = getActiveBatchTaskId();
|
||||||
if (!nextBatchNo && !nextTaskId) return;
|
if (!nextBatchNo && !nextTaskId) return;
|
||||||
void (async () => {
|
void (async () => {
|
||||||
|
await syncShippingConversationWorkspace();
|
||||||
if (nextBatchNo) await syncShippingBatchSummary(nextBatchNo);
|
if (nextBatchNo) await syncShippingBatchSummary(nextBatchNo);
|
||||||
if (nextTaskId) {
|
if (nextTaskId) {
|
||||||
await syncActiveShippingTaskDetail(nextTaskId);
|
await syncActiveShippingTaskDetail(nextTaskId);
|
||||||
@@ -591,7 +816,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
});
|
});
|
||||||
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
|
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
|
||||||
void refreshShippingActions().then(async () => {
|
void refreshShippingActions().then(async () => {
|
||||||
const taskId = getActiveShippingTaskId();
|
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
syncShippingParseReviewCard(taskId),
|
syncShippingParseReviewCard(taskId),
|
||||||
syncActiveShippingTaskDetail(taskId),
|
syncActiveShippingTaskDetail(taskId),
|
||||||
@@ -599,14 +824,17 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
await syncConversationMessagesIfNeeded(taskId);
|
await syncConversationMessagesIfNeeded(taskId);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
watch([resolvedShippingBatchNo, shippingBatchNoFromQuery], ([batchNo, queryBatchNo]) => {
|
watch([activeShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingBatchNo], ([activeBatchNo, queryBatchNo, batchNo]) => {
|
||||||
const nextBatchNo = String(batchNo || queryBatchNo || '').trim();
|
const nextBatchNo = String(activeBatchNo || queryBatchNo || batchNo || '').trim();
|
||||||
if (!nextBatchNo) {
|
if (!nextBatchNo) {
|
||||||
shippingBatchSummary.value = null;
|
shippingBatchSummary.value = null;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
void syncShippingBatchSummary(nextBatchNo);
|
void syncShippingBatchSummary(nextBatchNo);
|
||||||
}, { immediate: true });
|
}, { immediate: true });
|
||||||
|
watch([conversationId, isShippingNoticeAgent], () => {
|
||||||
|
void syncShippingConversationWorkspace();
|
||||||
|
}, { immediate: true });
|
||||||
watch(
|
watch(
|
||||||
[isShippingNoticeAgent, conversationId, resolvedShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
|
[isShippingNoticeAgent, conversationId, resolvedShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
|
||||||
() => {
|
() => {
|
||||||
@@ -634,14 +862,23 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
shippingTaskIdFromQuery,
|
shippingTaskIdFromQuery,
|
||||||
shippingBatchNoFromQuery,
|
shippingBatchNoFromQuery,
|
||||||
resolvedShippingBatchNo,
|
resolvedShippingBatchNo,
|
||||||
|
activeShippingBatchNo,
|
||||||
|
focusedShippingTaskNo,
|
||||||
|
shippingFocusReason,
|
||||||
|
shippingConversationWorkspace,
|
||||||
shippingBatchSummary,
|
shippingBatchSummary,
|
||||||
shippingBatchTasks,
|
shippingBatchTasks,
|
||||||
shippingBatchTasksExpanded,
|
shippingWorkspaceOpen,
|
||||||
|
retryingShippingPendingTasks,
|
||||||
activeShippingTaskDetail,
|
activeShippingTaskDetail,
|
||||||
getCurrentShippingChatContext,
|
getCurrentShippingChatContext,
|
||||||
getActiveShippingBatchNo,
|
getActiveShippingBatchNo,
|
||||||
|
switchShippingBatch,
|
||||||
switchShippingFocusTask,
|
switchShippingFocusTask,
|
||||||
|
clearShippingFocus,
|
||||||
resumeShippingTask,
|
resumeShippingTask,
|
||||||
|
retryCurrentShippingBatchPendingTasks,
|
||||||
|
queryShippingShortageDetails,
|
||||||
resetShippingConversationState,
|
resetShippingConversationState,
|
||||||
resumeShippingTaskFromQuery,
|
resumeShippingTaskFromQuery,
|
||||||
normalizeShippingHeaderForDisplay,
|
normalizeShippingHeaderForDisplay,
|
||||||
@@ -658,6 +895,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
|||||||
removeShippingParseReviewLine,
|
removeShippingParseReviewLine,
|
||||||
handleShippingActionClick,
|
handleShippingActionClick,
|
||||||
handleShippingInventorySelected,
|
handleShippingInventorySelected,
|
||||||
|
finalizeShippingAssistantMessage,
|
||||||
selectShippingInventoryUploadTask,
|
selectShippingInventoryUploadTask,
|
||||||
cancelShippingInventoryTaskSelection,
|
cancelShippingInventoryTaskSelection,
|
||||||
shippingActionButtonClass,
|
shippingActionButtonClass,
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ export const SHIPPING_DECISION_ACTIONS = new Set([
|
|||||||
'confirm_inventory_mapping',
|
'confirm_inventory_mapping',
|
||||||
'correct_inventory_mapping',
|
'correct_inventory_mapping',
|
||||||
'reparse_inventory',
|
'reparse_inventory',
|
||||||
|
'retry_rpa',
|
||||||
'reject',
|
'reject',
|
||||||
'reparse',
|
'reparse',
|
||||||
'rematch',
|
'rematch',
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ export function createLeaveLocalMessageApi(ctx: LeaveLocalMessageContext) {
|
|||||||
try {
|
try {
|
||||||
const data = await saveLocalChatMessage({
|
const data = await saveLocalChatMessage({
|
||||||
conversation_id: ctx.conversationId.value,
|
conversation_id: ctx.conversationId.value,
|
||||||
|
role: chatMsg.role,
|
||||||
type: chatMsg.type,
|
type: chatMsg.type,
|
||||||
content: chatMsg.content,
|
content: chatMsg.content,
|
||||||
payload: chatMsg.payload,
|
payload: chatMsg.payload,
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext)
|
|||||||
try {
|
try {
|
||||||
const data = await saveLocalChatMessage({
|
const data = await saveLocalChatMessage({
|
||||||
conversation_id: ctx.conversationId.value,
|
conversation_id: ctx.conversationId.value,
|
||||||
|
role: localMsg.role,
|
||||||
type: localMsg.type,
|
type: localMsg.type,
|
||||||
content: localMsg.content,
|
content: localMsg.content,
|
||||||
payload: localMsg.payload,
|
payload: localMsg.payload,
|
||||||
|
|||||||
@@ -25,7 +25,8 @@ export interface ChatPageSendContext {
|
|||||||
agentId: number,
|
agentId: number,
|
||||||
kb: string,
|
kb: string,
|
||||||
files: ChatUploadFileSpec[],
|
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>;
|
) => Promise<void>;
|
||||||
refreshHistoryAfterSend: () => Promise<void>;
|
refreshHistoryAfterSend: () => Promise<void>;
|
||||||
tryHandleShippingAttachmentAutoFlow: (
|
tryHandleShippingAttachmentAutoFlow: (
|
||||||
@@ -44,7 +45,8 @@ export interface ChatPageSendContext {
|
|||||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||||
t: (key: string) => string;
|
t: (key: string) => string;
|
||||||
copiedIndex: Ref<number | null>;
|
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) {
|
export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||||
@@ -98,6 +100,7 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
|||||||
ctx.selectedKb.value,
|
ctx.selectedKb.value,
|
||||||
files,
|
files,
|
||||||
ctx.getChatContext?.(),
|
ctx.getChatContext?.(),
|
||||||
|
{ onAssistantMessageFinished: ctx.onAssistantMessageFinished },
|
||||||
);
|
);
|
||||||
await ctx.refreshHistoryAfterSend();
|
await ctx.refreshHistoryAfterSend();
|
||||||
await ctx.refreshToolRunProgressAfterSend();
|
await ctx.refreshToolRunProgressAfterSend();
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export interface ShippingConversationContext {
|
|||||||
agentId: number,
|
agentId: number,
|
||||||
kb: string,
|
kb: string,
|
||||||
files: ChatUploadFileSpec[],
|
files: ChatUploadFileSpec[],
|
||||||
|
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||||
) => Promise<void>;
|
) => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,7 +41,10 @@ export function createShippingConversationHelpers(ctx: ShippingConversationConte
|
|||||||
const sendShippingMenuMessage = async (message: string) => {
|
const sendShippingMenuMessage = async (message: string) => {
|
||||||
const taskId = ctx.getActiveShippingTaskId();
|
const taskId = ctx.getActiveShippingTaskId();
|
||||||
const text = taskId ? `${message}\n任务编号:${taskId}` : message;
|
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);
|
await ensureShippingHistorySynced(ctx);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ export function formatShippingDecisionAssistantMessage(
|
|||||||
);
|
);
|
||||||
} else if (decision === 'confirm_inventory_mapping') {
|
} else if (decision === 'confirm_inventory_mapping') {
|
||||||
if (String(result.checkpoint || '').trim() === 'map_ok') {
|
if (String(result.checkpoint || '').trim() === 'map_ok') {
|
||||||
lines.push('', '下一步:匹配库存与发货需求(match_inventory)。');
|
lines.push('', '下一步:匹配库存与发货需求。');
|
||||||
}
|
}
|
||||||
} else if (decision === 'reparse_inventory') {
|
} else if (decision === 'reparse_inventory') {
|
||||||
lines.push('', '请重新上传或粘贴库存 Excel。');
|
lines.push('', '请重新上传或粘贴库存 Excel。');
|
||||||
|
|||||||
@@ -87,14 +87,20 @@ export function isShippingGenerateExcelIntent(text: string): boolean {
|
|||||||
].some((pattern) => pattern.test(normalized));
|
].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 {
|
export function isShippingDownloadExcelIntent(text: string): boolean {
|
||||||
const normalized = text.trim();
|
const normalized = normalizeShippingCommandText(text);
|
||||||
if (!normalized) return false;
|
if (!normalized) return false;
|
||||||
return [
|
if (!/(excel|xlsx|表格|发货文件|发货单)/i.test(normalized)) return false;
|
||||||
/^下载excel$/i,
|
if (/(生成|创建|制作|重新生成|重生成)/.test(normalized)) return false;
|
||||||
/^下载发货excel$/i,
|
return /(下载|获取|取得|拿|打开|查看|导出)/.test(normalized);
|
||||||
/下载.*excel/i,
|
|
||||||
].some((pattern) => pattern.test(normalized));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseShippingTaskSwitchIntent(text: string): ShippingTaskSwitchIntent | null {
|
export function parseShippingTaskSwitchIntent(text: string): ShippingTaskSwitchIntent | null {
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
* features/chat/shipping/shippingMenu.ts
|
* features/chat/shipping/shippingMenu.ts
|
||||||
* 用途:发货聊天数字菜单解析、动作按钮合并与决策文本识别(纯函数)。
|
* 用途:发货聊天数字菜单解析、动作按钮合并与决策文本识别(纯函数)。
|
||||||
* 依赖:shippingText.extractShippingActionsDirective、types/shipping.types。
|
* 依赖: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';
|
import type { ShippingActionButton, ShippingMenuAction } from '../types/shipping.types';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -77,7 +77,7 @@ export function normalizeApiShippingButtons(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 合并 API 按钮、HTML 指令与内容推断,得到最终 action_buttons 与 cleanedText。
|
* 合并 API 按钮与 HTML 指令,得到最终 action_buttons 与 cleanedText。
|
||||||
*/
|
*/
|
||||||
export function resolveShippingActionButtons(
|
export function resolveShippingActionButtons(
|
||||||
content: string,
|
content: string,
|
||||||
@@ -86,9 +86,10 @@ export function resolveShippingActionButtons(
|
|||||||
) {
|
) {
|
||||||
const directive = extractShippingActionsDirective(String(content || ''));
|
const directive = extractShippingActionsDirective(String(content || ''));
|
||||||
if (opts?.apiResolved) {
|
if (opts?.apiResolved) {
|
||||||
|
const buttons = normalizeApiShippingButtons(apiButtons);
|
||||||
return {
|
return {
|
||||||
buttons: normalizeApiShippingButtons(apiButtons),
|
buttons,
|
||||||
cleanedText: directive.cleanedText,
|
cleanedText: stripShippingActionListByButtons(directive.cleanedText, buttons),
|
||||||
fromDirective: false,
|
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 { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET } from '@/constants/shippingNoticeActions';
|
||||||
import type { ShippingActionButton, ShippingActionVariant } from '../types/shipping.types';
|
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 统一为「任务编号」展示。
|
* 隐藏 Agent 回复中的内部状态 token,并将 task_id 统一为「任务编号」展示。
|
||||||
*/
|
*/
|
||||||
export function sanitizeShippingConversationText(text: string, enabled: boolean): string {
|
export function sanitizeShippingConversationText(text: string, enabled: boolean): string {
|
||||||
if (!enabled) return text;
|
if (!enabled) return text;
|
||||||
let result = String(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\s*[::]/gi, '任务编号:')
|
||||||
.replace(/\btask_id\b/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(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, '');
|
||||||
result = result.replace(
|
result = result.replace(
|
||||||
/\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi,
|
/\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi,
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ export interface ShippingDecisionContext {
|
|||||||
* @returns 人工决策与手工上传确认处理函数
|
* @returns 人工决策与手工上传确认处理函数
|
||||||
*/
|
*/
|
||||||
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||||
|
const manualUploadInFlightTaskIds = new Set<string>();
|
||||||
|
|
||||||
const syncHistoryIfNeeded = async () => {
|
const syncHistoryIfNeeded = async () => {
|
||||||
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
|
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
|
||||||
await ctx.loadHistory();
|
await ctx.loadHistory();
|
||||||
@@ -108,17 +110,21 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
|
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
|
||||||
|
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
|
||||||
|
if (!normalizedTaskId || manualUploadInFlightTaskIds.has(normalizedTaskId)) return false;
|
||||||
|
manualUploadInFlightTaskIds.add(normalizedTaskId);
|
||||||
try {
|
try {
|
||||||
const result = await markWorkspaceShippingManualUploaded(taskId);
|
const result = await markWorkspaceShippingManualUploaded(normalizedTaskId);
|
||||||
const userText = (displayText || '已在货代系统手工上传完成').trim();
|
const userText = (displayText || '我已在货代系统完成上传').trim();
|
||||||
const assistantContent = [
|
const assistantContent = String(
|
||||||
String(result.message || '已标记为手工上传货代系统完成。').trim(),
|
result.message || `好的,任务 ${normalizedTaskId} 已确认完成,无需再处理。`,
|
||||||
`任务编号:${taskId}`,
|
).trim();
|
||||||
].join('\n');
|
const lastUserMessage = [...ctx.messages.value].reverse().find((item) => item.role === 'user');
|
||||||
|
const shouldAppendUser = String(lastUserMessage?.content || '').trim() !== userText;
|
||||||
const userMsg: ChatMessage = {
|
const userMsg: ChatMessage = {
|
||||||
role: 'user',
|
role: 'user',
|
||||||
type: 'text',
|
type: 'text',
|
||||||
content: `${userText}\n任务编号:${taskId}`,
|
content: userText,
|
||||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||||
local_only: true,
|
local_only: true,
|
||||||
};
|
};
|
||||||
@@ -130,14 +136,19 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
|||||||
local_only: true,
|
local_only: true,
|
||||||
shipping_actions_used: 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) => {
|
ctx.messages.value.forEach((rawMsg) => {
|
||||||
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
|
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
|
||||||
if (m.role === 'assistant') {
|
if (m.role === 'assistant') {
|
||||||
m.shipping_actions = undefined;
|
m.shipping_actions = undefined;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
if (shouldAppendUser) {
|
||||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||||
|
}
|
||||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||||
void ctx.refreshShippingActions();
|
void ctx.refreshShippingActions();
|
||||||
return true;
|
return true;
|
||||||
@@ -145,6 +156,8 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
|||||||
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
|
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
|
||||||
ctx.msg.warning(errorMessage);
|
ctx.msg.warning(errorMessage);
|
||||||
return false;
|
return false;
|
||||||
|
} finally {
|
||||||
|
manualUploadInFlightTaskIds.delete(normalizedTaskId);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import {
|
import {
|
||||||
generateWorkspaceShippingExcel,
|
generateWorkspaceShippingExcel,
|
||||||
matchWorkspaceShippingInventory,
|
matchWorkspaceShippingInventory,
|
||||||
|
retryWorkspaceShippingUpload,
|
||||||
type ShippingDecisionResponse,
|
type ShippingDecisionResponse,
|
||||||
type ShippingMatchLineResult,
|
type ShippingMatchLineResult,
|
||||||
} from '@/features/chat/api/shipping.api';
|
} from '@/features/chat/api/shipping.api';
|
||||||
@@ -71,7 +72,8 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
|||||||
) => {
|
) => {
|
||||||
if (ctx.isThinking.value) return;
|
if (ctx.isThinking.value) return;
|
||||||
if (action.id === 'refresh') {
|
if (action.id === 'refresh') {
|
||||||
await ctx.sendShippingMenuMessage(action.message || '刷新');
|
await ctx.refreshShippingActions();
|
||||||
|
ctx.msg.info(ctx.t('chat.shippingNoticeRefreshDone'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (action.id === 'download_excel') {
|
if (action.id === 'download_excel') {
|
||||||
@@ -125,6 +127,41 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
|||||||
}
|
}
|
||||||
return;
|
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 === 'edit_inventory_mapping') {
|
if (action.id === 'edit_inventory_mapping') {
|
||||||
const taskId = ctx.getActiveShippingTaskId();
|
const taskId = ctx.getActiveShippingTaskId();
|
||||||
if (!taskId) {
|
if (!taskId) {
|
||||||
@@ -175,13 +212,16 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
|||||||
}
|
}
|
||||||
if (action.id === 'mark_manual_uploaded') {
|
if (action.id === 'mark_manual_uploaded') {
|
||||||
if (chatMsg?.shipping_actions_used) return;
|
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();
|
const taskId = ctx.getActiveShippingTaskId();
|
||||||
if (!taskId) {
|
if (!taskId) {
|
||||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await ctx.executeShippingManualUpload(taskId, action.message || '已在货代系统手工上传完成');
|
await ctx.executeShippingManualUpload(taskId, '我已在货代系统完成上传');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (action.id === 'paste_inventory_json') {
|
if (action.id === 'paste_inventory_json') {
|
||||||
|
|||||||
@@ -77,36 +77,11 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
|||||||
taskId = taskNo;
|
taskId = taskNo;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// fall back to content-based buttons
|
// fall back to structured directive buttons embedded in the message
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
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;
|
let lastOpenAssistantIndex = -1;
|
||||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||||
const item = msgs[i];
|
const item = msgs[i];
|
||||||
@@ -124,6 +99,42 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex;
|
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) => {
|
msgs.forEach((rawMsg, index) => {
|
||||||
const chatMsg = rawMsg as ChatMessage & {
|
const chatMsg = rawMsg as ChatMessage & {
|
||||||
shipping_actions_used?: boolean;
|
shipping_actions_used?: boolean;
|
||||||
@@ -147,7 +158,7 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
|||||||
apiResolved ? (apiButtons ?? []) : null,
|
apiResolved ? (apiButtons ?? []) : null,
|
||||||
{ apiResolved },
|
{ apiResolved },
|
||||||
);
|
);
|
||||||
if (resolved.fromDirective) {
|
if (resolved.fromDirective || resolved.cleanedText !== String(chatMsg.content || '').trim()) {
|
||||||
chatMsg.content = resolved.cleanedText;
|
chatMsg.content = resolved.cleanedText;
|
||||||
}
|
}
|
||||||
buttons = resolved.buttons;
|
buttons = resolved.buttons;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
getWorkspaceShippingBatch,
|
getWorkspaceShippingBatch,
|
||||||
switchWorkspaceShippingBatchFocusTask,
|
switchWorkspaceShippingBatchFocusTask,
|
||||||
} from '@/features/chat/api/shipping.api';
|
} 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 { buildShippingFieldAlignmentText } from './shippingMapping';
|
||||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||||
import {
|
import {
|
||||||
@@ -45,6 +45,7 @@ export interface ShippingSendHandlerContext {
|
|||||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||||
getActiveShippingTaskId: () => string;
|
getActiveShippingTaskId: () => string;
|
||||||
lastAssistantMessageContent: () => string;
|
lastAssistantMessageContent: () => string;
|
||||||
|
lastAssistantShippingActions: () => ChatMessage['shipping_actions'];
|
||||||
sendMessage: (
|
sendMessage: (
|
||||||
content: string,
|
content: string,
|
||||||
agentId: number,
|
agentId: number,
|
||||||
@@ -59,10 +60,13 @@ export interface ShippingSendHandlerContext {
|
|||||||
openShippingInventoryPicker: () => boolean;
|
openShippingInventoryPicker: () => boolean;
|
||||||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||||||
executeShippingManualUpload: (taskId: 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>;
|
handleShippingAutoUploadFile: (file: File) => Promise<void>;
|
||||||
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
|
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
|
||||||
refreshShippingActions: () => Promise<void>;
|
refreshShippingActions: () => Promise<void>;
|
||||||
shippingSuggestedPrompt: ComputedRef<string>;
|
shippingSuggestedPrompt: ComputedRef<string>;
|
||||||
|
isShippingShortageQueryIntent: (text: string) => boolean;
|
||||||
|
queryShippingShortageDetails: (taskNo?: string, displayText?: string) => Promise<boolean>;
|
||||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||||
t: (key: string) => string;
|
t: (key: string) => string;
|
||||||
}
|
}
|
||||||
@@ -128,6 +132,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
|||||||
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
|
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
|
||||||
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
|
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
|
||||||
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
|
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
|
||||||
|
const requestedAutoFlow = ctx.shippingAutoFlowRequested.value;
|
||||||
ctx.shippingAutoFlowRequested.value = false;
|
ctx.shippingAutoFlowRequested.value = false;
|
||||||
const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
|
const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
|
||||||
const first = localFiles[0];
|
const first = localFiles[0];
|
||||||
@@ -152,12 +157,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
|||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (!trimmed) {
|
if (!trimmed || requestedAutoFlow) {
|
||||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||||
ctx.attachments.value = [];
|
ctx.attachments.value = [];
|
||||||
try {
|
try {
|
||||||
const prompt = ctx.shippingSuggestedPrompt.value || '解析发货通知并创建任务';
|
|
||||||
await ctx.pushShippingLocalUserMessage(prompt);
|
|
||||||
await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file));
|
await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file));
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
||||||
@@ -174,12 +177,31 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
|||||||
_trimmed: string,
|
_trimmed: string,
|
||||||
): Promise<boolean> => {
|
): Promise<boolean> => {
|
||||||
if (!ctx.isShippingNoticeAgent.value) return false;
|
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 (await trySwitchShippingTask(content)) {
|
||||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||||
ctx.attachments.value = [];
|
ctx.attachments.value = [];
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
const assistantCtx = ctx.lastAssistantMessageContent();
|
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);
|
const menuChoice = resolveShippingNumericChoice(content, assistantCtx);
|
||||||
if (menuChoice) {
|
if (menuChoice) {
|
||||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||||
@@ -188,6 +210,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
|||||||
} else if (menuChoice === 'paste') {
|
} else if (menuChoice === 'paste') {
|
||||||
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
||||||
return true;
|
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 {
|
} else {
|
||||||
await ctx.sendShippingMenuMessage(SHIPPING_MENU_ACTION_SPECS[menuChoice].message);
|
await ctx.sendShippingMenuMessage(SHIPPING_MENU_ACTION_SPECS[menuChoice].message);
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -28,7 +28,6 @@ export interface ShippingUploadHandlerContext {
|
|||||||
resolvedShippingBatchNo: Ref<string>;
|
resolvedShippingBatchNo: Ref<string>;
|
||||||
shippingBatchSummary: Ref<unknown | null>;
|
shippingBatchSummary: Ref<unknown | null>;
|
||||||
shippingBatchTasks: Ref<ShippingTaskSummary[]>;
|
shippingBatchTasks: Ref<ShippingTaskSummary[]>;
|
||||||
shippingBatchTasksExpanded: Ref<boolean>;
|
|
||||||
shippingInventorySelectionActive: Ref<boolean>;
|
shippingInventorySelectionActive: Ref<boolean>;
|
||||||
shippingInventorySelectionTaskId: Ref<string>;
|
shippingInventorySelectionTaskId: Ref<string>;
|
||||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||||
@@ -270,8 +269,8 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
|||||||
| undefined;
|
| undefined;
|
||||||
if (!first) return '';
|
if (!first) return '';
|
||||||
const kind = classifyShippingUploadFile(first.file, extractExt);
|
const kind = classifyShippingUploadFile(first.file, extractExt);
|
||||||
if (kind === 'inventory') return '上传库存并进入字段对齐';
|
if (kind === 'inventory') return ctx.t('chat.shippingNoticePrompt.notice.autoInventoryAction');
|
||||||
return '解析发货通知并创建任务';
|
return ctx.t('chat.shippingNoticePrompt.notice.autoNoticeAction');
|
||||||
});
|
});
|
||||||
|
|
||||||
const useShippingSuggestedPrompt = () => {
|
const useShippingSuggestedPrompt = () => {
|
||||||
|
|||||||
@@ -22,9 +22,12 @@ export interface ShippingTaskSummary {
|
|||||||
upload_mode?: string | null;
|
upload_mode?: string | null;
|
||||||
upload_attempt?: number | null;
|
upload_attempt?: number | null;
|
||||||
pending_human_reason?: string | null;
|
pending_human_reason?: string | null;
|
||||||
|
error_message?: string | null;
|
||||||
conversation_id?: string | null;
|
conversation_id?: string | null;
|
||||||
export_file_name?: string | null;
|
export_file_name?: string | null;
|
||||||
freight_ref_no?: string | null;
|
freight_ref_no?: string | null;
|
||||||
|
shortage?: ShippingShortageSummary | null;
|
||||||
|
line_results?: ShippingMatchLineResult[];
|
||||||
step_payload?: Record<string, unknown> & {
|
step_payload?: Record<string, unknown> & {
|
||||||
current_step_progress?: ShippingCurrentStepProgress;
|
current_step_progress?: ShippingCurrentStepProgress;
|
||||||
};
|
};
|
||||||
@@ -131,6 +134,27 @@ export interface ShippingBatchSummary {
|
|||||||
updated_at?: string | null;
|
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 {
|
export interface ShippingInventoryUploadResponse {
|
||||||
status: string;
|
status: string;
|
||||||
message?: string;
|
message?: string;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"defaultTitle": "Chat",
|
"defaultTitle": "Chat",
|
||||||
"assistantLabel": "HXOPS AI Assistant",
|
"assistantLabel": "AI Assistant",
|
||||||
"placeholder": "Ask anything...",
|
"placeholder": "Ask anything...",
|
||||||
"history": "Chat History",
|
"history": "Chat History",
|
||||||
"noHistory": "No history",
|
"noHistory": "No history",
|
||||||
@@ -13,13 +13,18 @@
|
|||||||
"loadingAgent": "Loading agent...",
|
"loadingAgent": "Loading agent...",
|
||||||
"thinking": "Generating response...",
|
"thinking": "Generating response...",
|
||||||
"disclaimer": "AI can make mistakes. Please verify important information.",
|
"disclaimer": "AI can make mistakes. Please verify important information.",
|
||||||
|
"scrollToLatest": "Scroll to latest message",
|
||||||
"createNewChat": "New Chat",
|
"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:",
|
"shippingNoticeActionsHint": "Choose an action:",
|
||||||
"shippingNoticeMissingTaskId": "Task ID not found. Complete shipping notice parsing first.",
|
"shippingNoticeMissingTaskId": "Task ID not found. Complete shipping notice parsing first.",
|
||||||
"shippingNoticeUploadDone": "Inventory file uploaded: {fileName}.",
|
"shippingNoticeUploadDone": "Inventory file uploaded: {fileName}.",
|
||||||
"shippingNoticeUploadOk": "Upload succeeded.",
|
"shippingNoticeUploadOk": "Upload succeeded.",
|
||||||
"shippingNoticeUploadFailed": "Inventory upload failed.",
|
"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.",
|
"shippingNoticePasteHint": "Paste inventory rows in the input box, then send.",
|
||||||
"shippingNoticeDecisionDone": "Action completed.",
|
"shippingNoticeDecisionDone": "Action completed.",
|
||||||
"shippingNoticePrompt": {
|
"shippingNoticePrompt": {
|
||||||
@@ -41,8 +46,10 @@
|
|||||||
"batchLabel": "batch {batchNo}",
|
"batchLabel": "batch {batchNo}",
|
||||||
"taskLabel": "current task {taskId}",
|
"taskLabel": "current task {taskId}",
|
||||||
"taskList": "Task list: {taskIds}.",
|
"taskList": "Task list: {taskIds}.",
|
||||||
"multiTask": "{summary}. {taskListText}Please only handle the current focus task. First call get_task_status to read the current task status; if the current task is still pending parsing, read raw_text, use the LLM to extract structured fields, then call parse_notice(structured=...) to persist them. If the task is already in a later step, directly explain the current status and guide me on the next step for this task. Do not ask me again whether parsing should start, and do not loop through other tasks in the batch.",
|
"autoInventoryAction": "Upload inventory and align columns",
|
||||||
"singleTask": "{summary}. Please first call get_task_status to read the current task status; if the current task is still pending parsing, read raw_text, use the LLM to extract structured fields, and directly call parse_notice(structured=...) to persist them. If the task is already in a later step, directly explain the current status and guide me on the next step. Do not ask me again whether parsing should start now."
|
"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": {
|
"shippingNoticeMapping": {
|
||||||
@@ -104,17 +111,79 @@
|
|||||||
"batchProgress": "Item {index}/{total}",
|
"batchProgress": "Item {index}/{total}",
|
||||||
"batchCurrentIndex": "Currently processing item {index}/{total}",
|
"batchCurrentIndex": "Currently processing item {index}/{total}",
|
||||||
"batchSummaryLine": "Batch {total} items · Completed {completed} · In progress {running} · Pending {pending}",
|
"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",
|
"currentNotice": "Current notice",
|
||||||
"currentStepLabel": "Current",
|
"currentStepLabel": "Current",
|
||||||
"stepHeadline": "Step {current}/{total} · {label}",
|
"stepHeadline": "Step {current}/{total} · {label}",
|
||||||
"stepFraction": "Step {current}/{total}",
|
"stepFraction": "Step {current}/{total}",
|
||||||
"stepNeedsConfirm": "Step {step} needs confirmation",
|
"stepNeedsConfirm": "Step {step} needs confirmation",
|
||||||
"taskListResume": "Task List / Resume",
|
"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",
|
"taskListTitle": "Task List",
|
||||||
"taskListHint": "Switching tasks also updates the top Stepper and available actions",
|
"taskListHint": "Switching tasks also updates the top Stepper and available actions",
|
||||||
"expandTaskList": "Expand list",
|
"expandTaskList": "Expand task list",
|
||||||
"collapseTaskList": "Collapse list",
|
"collapseTaskList": "Collapse task list",
|
||||||
"currentFocus": "Current focus →",
|
"currentFocus": "Current focus:",
|
||||||
|
"currentFocusDefaultReason": "Input will apply to this task",
|
||||||
|
"focusInputPlaceholder": "Handling {taskId}. Type an instruction...",
|
||||||
|
"clearFocus": "Clear focus",
|
||||||
"runningState": "In progress",
|
"runningState": "In progress",
|
||||||
"pendingState": "Pending",
|
"pendingState": "Pending",
|
||||||
"completedState": "Completed",
|
"completedState": "Completed",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"defaultTitle": "แชท",
|
"defaultTitle": "แชท",
|
||||||
"assistantLabel": "ผู้ช่วย AI ของ HXOPS",
|
"assistantLabel": "ผู้ช่วย AI",
|
||||||
"placeholder": "ถามอะไรก็ได้...",
|
"placeholder": "ถามอะไรก็ได้...",
|
||||||
"history": "ประวัติการแชท",
|
"history": "ประวัติการแชท",
|
||||||
"noHistory": "ไม่มีประวัติ",
|
"noHistory": "ไม่มีประวัติ",
|
||||||
@@ -13,13 +13,18 @@
|
|||||||
"loadingAgent": "กำลังโหลดตัวแทน...",
|
"loadingAgent": "กำลังโหลดตัวแทน...",
|
||||||
"thinking": "กำลังสร้างคำตอบ...",
|
"thinking": "กำลังสร้างคำตอบ...",
|
||||||
"disclaimer": "AI อาจทำผิดพลาดได้ โปรดตรวจสอบข้อมูลสำคัญ",
|
"disclaimer": "AI อาจทำผิดพลาดได้ โปรดตรวจสอบข้อมูลสำคัญ",
|
||||||
|
"scrollToLatest": "เลื่อนไปยังข้อความล่าสุด",
|
||||||
"createNewChat": "แชทใหม่",
|
"createNewChat": "แชทใหม่",
|
||||||
"shippingNoticeContinue": "กรุณาดำเนินการงานจัดส่งต่อ {taskId} โปรดเรียก get_task_status ก่อนและบอกขั้นตอนถัดไป",
|
"shippingNoticeContinue": "กรุณาดำเนินการงานจัดส่งต่อ {taskId} โปรดอ่านสถานะงานปัจจุบันก่อน หากยังต้องแยกข้อมูล ให้แยกใบแจ้งส่งสินค้าและบันทึกผลลัพธ์ มิฉะนั้นให้สรุปความคืบหน้าและขั้นตอนถัดไป",
|
||||||
"shippingNoticeActionsHint": "เลือกการทำงาน:",
|
"shippingNoticeActionsHint": "เลือกการทำงาน:",
|
||||||
"shippingNoticeMissingTaskId": "ไม่พบรหัสงาน โปรดแยกใบแจ้งส่งสินค้าก่อน",
|
"shippingNoticeMissingTaskId": "ไม่พบรหัสงาน โปรดแยกใบแจ้งส่งสินค้าก่อน",
|
||||||
"shippingNoticeUploadDone": "อัปโหลดไฟล์สต็อกแล้ว: {fileName}",
|
"shippingNoticeUploadDone": "อัปโหลดไฟล์สต็อกแล้ว: {fileName}",
|
||||||
"shippingNoticeUploadOk": "อัปโหลดสำเร็จ",
|
"shippingNoticeUploadOk": "อัปโหลดสำเร็จ",
|
||||||
"shippingNoticeUploadFailed": "อัปโหลดไฟล์สต็อกล้มเหลว",
|
"shippingNoticeUploadFailed": "อัปโหลดไฟล์สต็อกล้มเหลว",
|
||||||
|
"shippingNoticeRefreshDone": "รีเฟรชสถานะงานปัจจุบันแล้ว",
|
||||||
|
"shippingNoticeRetryUploadAction": "ลองอัปโหลดไปยังระบบขนส่งอีกครั้ง",
|
||||||
|
"shippingNoticeRetryUploadQueued": "เริ่มอัปโหลดอีกครั้งแล้ว โปรดรีเฟรชภายหลังเพื่อตรวจสอบผลลัพธ์",
|
||||||
|
"shippingNoticeRetryUploadFailed": "ลองอัปโหลดอีกครั้งไม่สำเร็จ",
|
||||||
"shippingNoticePasteHint": "วางข้อมูลสต็อกในช่องข้อความแล้วส่ง",
|
"shippingNoticePasteHint": "วางข้อมูลสต็อกในช่องข้อความแล้วส่ง",
|
||||||
"shippingNoticeDecisionDone": "ดำเนินการเสร็จแล้ว",
|
"shippingNoticeDecisionDone": "ดำเนินการเสร็จแล้ว",
|
||||||
"shippingNoticePrompt": {
|
"shippingNoticePrompt": {
|
||||||
@@ -41,8 +46,10 @@
|
|||||||
"batchLabel": "ชุดงาน {batchNo}",
|
"batchLabel": "ชุดงาน {batchNo}",
|
||||||
"taskLabel": "งานปัจจุบัน {taskId}",
|
"taskLabel": "งานปัจจุบัน {taskId}",
|
||||||
"taskList": "รายการงาน: {taskIds}",
|
"taskList": "รายการงาน: {taskIds}",
|
||||||
"multiTask": "{summary} {taskListText}กรุณาจัดการเฉพาะงานที่โฟกัสอยู่ในขณะนี้ก่อน เรียก get_task_status เพื่ออ่านสถานะงานปัจจุบันก่อน หากงานปัจจุบันยังรอการแยกข้อมูล ให้读取 raw_text ใช้ LLM แยกฟิลด์แบบมีโครงสร้าง แล้วเรียก parse_notice(structured=...) เพื่อบันทึก หากงานเข้าสู่ขั้นตอนถัดไปแล้ว ให้สรุปสถานะปัจจุบันและแนะนำขั้นตอนถัดไปของงานนี้โดยตรง ห้ามถามฉันซ้ำว่าจะเริ่มแยกข้อมูลหรือไม่ และไม่ต้องวนประมวลผลงานอื่นทั้งชุด",
|
"autoInventoryAction": "อัปโหลดสต็อกและจับคู่คอลัมน์",
|
||||||
"singleTask": "{summary} กรุณาเรียก get_task_status เพื่ออ่านสถานะงานปัจจุบันก่อน หากงานปัจจุบันยังรอการแยกข้อมูล ให้读取 raw_text ใช้ LLM แยกฟิลด์แบบมีโครงสร้าง แล้วเรียก parse_notice(structured=...) โดยตรงเพื่อบันทึก หากงานเข้าสู่ขั้นตอนถัดไปแล้ว ให้สรุปสถานะปัจจุบันและแนะนำขั้นตอนถัดไปโดยตรง ห้ามถามฉันซ้ำว่าจะเริ่มแยกข้อมูลตอนนี้หรือไม่"
|
"autoNoticeAction": "สร้างงานและแยกข้อมูลใบแจ้งจัดส่ง",
|
||||||
|
"multiTask": "{summary} {taskListText}กรุณาจัดการเฉพาะงานที่โฟกัสอยู่ในขณะนี้ก่อน อ่านสถานะงานปัจจุบันก่อน หากยังต้องแยกข้อมูล ให้แยกใบแจ้งส่งสินค้าและบันทึกผลลัพธ์ หากเข้าสู่ขั้นตอนถัดไปแล้ว ให้สรุปความคืบหน้าและขั้นตอนถัดไปโดยตรง อย่าถามซ้ำว่าจะเริ่มแยกข้อมูลหรือไม่ และไม่ต้องวนประมวลผลงานอื่นทั้งชุด",
|
||||||
|
"singleTask": "{summary} กรุณาอ่านสถานะงานปัจจุบันก่อน หากยังต้องแยกข้อมูล ให้แยกใบแจ้งส่งสินค้าและบันทึกผลลัพธ์ หากเข้าสู่ขั้นตอนถัดไปแล้ว ให้สรุปความคืบหน้าและขั้นตอนถัดไปโดยตรง อย่าถามซ้ำว่าจะเริ่มแยกข้อมูลหรือไม่"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"shippingNoticeMapping": {
|
"shippingNoticeMapping": {
|
||||||
@@ -104,17 +111,79 @@
|
|||||||
"batchProgress": "รายการ {index}/{total}",
|
"batchProgress": "รายการ {index}/{total}",
|
||||||
"batchCurrentIndex": "กำลังประมวลผลรายการที่ {index}/{total}",
|
"batchCurrentIndex": "กำลังประมวลผลรายการที่ {index}/{total}",
|
||||||
"batchSummaryLine": "ชุดนี้ {total} รายการ · เสร็จแล้ว {completed} · กำลังดำเนินการ {running} · รอดำเนินการ {pending}",
|
"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": "ใบแจ้งปัจจุบัน",
|
"currentNotice": "ใบแจ้งปัจจุบัน",
|
||||||
"currentStepLabel": "ปัจจุบัน",
|
"currentStepLabel": "ปัจจุบัน",
|
||||||
"stepHeadline": "ขั้นตอน {current}/{total} · {label}",
|
"stepHeadline": "ขั้นตอน {current}/{total} · {label}",
|
||||||
"stepFraction": "ขั้นตอน {current}/{total}",
|
"stepFraction": "ขั้นตอน {current}/{total}",
|
||||||
"stepNeedsConfirm": "ขั้นตอน {step} รอยืนยัน",
|
"stepNeedsConfirm": "ขั้นตอน {step} รอยืนยัน",
|
||||||
"taskListResume": "รายการงาน / ดำเนินการต่อ",
|
"taskListResume": "รายการงาน / ดำเนินการต่อ",
|
||||||
|
"retryPendingTasks": "ลองงานที่กู้คืนได้ในชุดงานปัจจุบันอีกครั้ง",
|
||||||
|
"retryPendingDone": "ส่งงานที่กู้คืนได้ใหม่แล้ว",
|
||||||
|
"retryFailed": "ลองใหม่ไม่สำเร็จ",
|
||||||
|
"retrying": "กำลังลองใหม่...",
|
||||||
"taskListTitle": "รายการงาน",
|
"taskListTitle": "รายการงาน",
|
||||||
"taskListHint": "เมื่อสลับงาน Stepper ด้านบนและการดำเนินการจะอัปเดตพร้อมกัน",
|
"taskListHint": "เมื่อสลับงาน Stepper ด้านบนและการดำเนินการจะอัปเดตพร้อมกัน",
|
||||||
"expandTaskList": "ขยายรายการ",
|
"expandTaskList": "ขยายรายการงาน",
|
||||||
"collapseTaskList": "ย่อรายการ",
|
"collapseTaskList": "ย่อรายการงาน",
|
||||||
"currentFocus": "โฟกัสปัจจุบัน →",
|
"currentFocus": "โฟกัสปัจจุบัน:",
|
||||||
|
"currentFocusDefaultReason": "ข้อความที่ป้อนจะมีผลกับงานนี้",
|
||||||
|
"focusInputPlaceholder": "กำลังจัดการ {taskId} พิมพ์คำสั่ง...",
|
||||||
|
"clearFocus": "ยกเลิกโฟกัส",
|
||||||
"runningState": "กำลังดำเนินการ",
|
"runningState": "กำลังดำเนินการ",
|
||||||
"pendingState": "รอยืนยัน",
|
"pendingState": "รอยืนยัน",
|
||||||
"completedState": "เสร็จแล้ว",
|
"completedState": "เสร็จแล้ว",
|
||||||
|
|||||||
@@ -13,13 +13,18 @@
|
|||||||
"loadingAgent": "正在加载应用...",
|
"loadingAgent": "正在加载应用...",
|
||||||
"thinking": "正在生成回答...",
|
"thinking": "正在生成回答...",
|
||||||
"disclaimer": "AI 可能会犯错,请核实重要信息。",
|
"disclaimer": "AI 可能会犯错,请核实重要信息。",
|
||||||
|
"scrollToLatest": "滚动到最新消息",
|
||||||
"createNewChat": "创建新对话",
|
"createNewChat": "创建新对话",
|
||||||
"shippingNoticeContinue": "请继续处理发货任务 {taskId}。该任务已存在,禁止调用 create_task。请先调用 get_task_status(task_id={taskId})查询当前状态并告知我下一步。",
|
"shippingNoticeContinue": "请继续处理发货任务 {taskId}。先读取当前任务状态;如果仍待解析,请解析发货通知并保存结果;如果已进入后续步骤,请直接说明当前进度和下一步。",
|
||||||
"shippingNoticeActionsHint": "请选择操作:",
|
"shippingNoticeActionsHint": "请选择操作:",
|
||||||
"shippingNoticeMissingTaskId": "未找到任务编号,请先完成发货通知解析。",
|
"shippingNoticeMissingTaskId": "未找到任务编号,请先完成发货通知解析。",
|
||||||
"shippingNoticeUploadDone": "库存文件已上传:{fileName}。",
|
"shippingNoticeUploadDone": "库存文件已上传:{fileName}。",
|
||||||
"shippingNoticeUploadOk": "上传成功。",
|
"shippingNoticeUploadOk": "上传成功。",
|
||||||
"shippingNoticeUploadFailed": "库存文件上传失败。",
|
"shippingNoticeUploadFailed": "库存文件上传失败。",
|
||||||
|
"shippingNoticeRefreshDone": "已刷新当前任务状态。",
|
||||||
|
"shippingNoticeRetryUploadAction": "重试上传货代",
|
||||||
|
"shippingNoticeRetryUploadQueued": "已重新触发上传,请稍后刷新查看结果。",
|
||||||
|
"shippingNoticeRetryUploadFailed": "重试上传失败。",
|
||||||
"shippingNoticePasteHint": "请在输入框粘贴库存小表内容后发送。",
|
"shippingNoticePasteHint": "请在输入框粘贴库存小表内容后发送。",
|
||||||
"shippingNoticeDecisionDone": "操作已完成。",
|
"shippingNoticeDecisionDone": "操作已完成。",
|
||||||
"shippingNoticePrompt": {
|
"shippingNoticePrompt": {
|
||||||
@@ -42,9 +47,9 @@
|
|||||||
"taskLabel": "当前任务 {taskId}",
|
"taskLabel": "当前任务 {taskId}",
|
||||||
"taskList": "任务列表:{taskIds}。",
|
"taskList": "任务列表:{taskIds}。",
|
||||||
"autoInventoryAction": "上传库存并进入字段对齐",
|
"autoInventoryAction": "上传库存并进入字段对齐",
|
||||||
"autoNoticeAction": "解析发货通知并创建任务",
|
"autoNoticeAction": "创建任务并解析发货通知",
|
||||||
"multiTask": "{summary}。{taskListText}请只处理当前焦点任务。先调用 get_task_status 读取当前任务状态;如果当前任务仍待解析,请读取 raw_text,用 LLM 抽取结构化字段后调用 parse_notice(structured=...) 落库;如果已经进入后续步骤,请直接解释当前状态并给出本任务下一步引导。禁止再次询问我“是否开始解析”,也不要整批循环处理其他任务。",
|
"multiTask": "{summary}。{taskListText}请只处理当前焦点任务。先读取当前任务状态;如果仍待解析,请解析发货通知并保存结果;如果已进入后续步骤,请直接说明当前进度和下一步。不要再次询问我是否开始解析,也不要整批循环处理其他任务。",
|
||||||
"singleTask": "{summary}。请先调用 get_task_status 读取当前任务状态;如果当前任务仍待解析,请读取 raw_text,用 LLM 抽取结构化字段后直接调用 parse_notice(structured=...) 落库;若已进入后续步骤,请直接解释当前状态并给出下一步引导。禁止再次询问我“是否开始解析”或“是否现在开始解析”。"
|
"singleTask": "{summary}。请先读取当前任务状态;如果仍待解析,请解析发货通知并保存结果;如果已进入后续步骤,请直接说明当前进度和下一步。不要再次询问我是否开始解析。"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"shippingNoticeMapping": {
|
"shippingNoticeMapping": {
|
||||||
@@ -106,21 +111,79 @@
|
|||||||
"batchProgress": "第 {index}/{total} 票",
|
"batchProgress": "第 {index}/{total} 票",
|
||||||
"batchCurrentIndex": "当前处理第 {index}/{total} 票",
|
"batchCurrentIndex": "当前处理第 {index}/{total} 票",
|
||||||
"batchSummaryLine": "本批 {total} 笔 · 已完成 {completed} · 进行中 {running} · 待处理 {pending}",
|
"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": "当前通知",
|
"currentNotice": "当前通知",
|
||||||
"currentStepLabel": "当前",
|
"currentStepLabel": "当前",
|
||||||
"stepHeadline": "步骤 {current}/{total} · {label}",
|
"stepHeadline": "步骤 {current}/{total} · {label}",
|
||||||
"stepFraction": "步骤 {current}/{total}",
|
"stepFraction": "步骤 {current}/{total}",
|
||||||
"stepNeedsConfirm": "步骤 {step} 待确认",
|
"stepNeedsConfirm": "步骤 {step} 待确认",
|
||||||
"taskListResume": "任务列表 / 续办",
|
"taskListResume": "任务列表 / 续办",
|
||||||
"retryPendingTasks": "重试未完成票",
|
"retryPendingTasks": "重试当前批次可恢复任务",
|
||||||
"retryPendingDone": "已重新提交未完成票",
|
"retryPendingDone": "已重新提交未完成票",
|
||||||
"retryFailed": "重试失败",
|
"retryFailed": "重试失败",
|
||||||
"retrying": "重试中...",
|
"retrying": "重试中...",
|
||||||
"taskListTitle": "任务列表",
|
"taskListTitle": "任务列表",
|
||||||
"taskListHint": "切换任务后,对话顶部 Stepper 与操作同步更新",
|
"taskListHint": "切换任务后,对话顶部 Stepper 与操作同步更新",
|
||||||
"expandTaskList": "展开列表",
|
"expandTaskList": "展开任务列表",
|
||||||
"collapseTaskList": "收起列表",
|
"collapseTaskList": "收起任务列表",
|
||||||
"currentFocus": "当前聚焦 →",
|
"currentFocus": "当前聚焦:",
|
||||||
|
"currentFocusDefaultReason": "输入内容将作用于该单票任务",
|
||||||
|
"focusInputPlaceholder": "正在处理 {taskId},输入指令...",
|
||||||
|
"clearFocus": "取消聚焦",
|
||||||
"runningState": "进行中",
|
"runningState": "进行中",
|
||||||
"pendingState": "待确认",
|
"pendingState": "待确认",
|
||||||
"completedState": "已完成",
|
"completedState": "已完成",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"defaultTitle": "對話",
|
"defaultTitle": "對話",
|
||||||
"assistantLabel": "HXOPS AI 助手",
|
"assistantLabel": "AI 助手",
|
||||||
"placeholder": "請輸入問題...",
|
"placeholder": "請輸入問題...",
|
||||||
"history": "歷史記錄",
|
"history": "歷史記錄",
|
||||||
"noHistory": "暫無歷史記錄",
|
"noHistory": "暫無歷史記錄",
|
||||||
@@ -13,13 +13,18 @@
|
|||||||
"loadingAgent": "正在加載應用...",
|
"loadingAgent": "正在加載應用...",
|
||||||
"thinking": "正在生成回答...",
|
"thinking": "正在生成回答...",
|
||||||
"disclaimer": "AI 可能會犯錯,請核實重要信息。",
|
"disclaimer": "AI 可能會犯錯,請核實重要信息。",
|
||||||
|
"scrollToLatest": "捲動到最新消息",
|
||||||
"createNewChat": "建立新對話",
|
"createNewChat": "建立新對話",
|
||||||
"shippingNoticeContinue": "請繼續處理發貨任務 {taskId}。請先呼叫 get_task_status,再告訴我下一步。",
|
"shippingNoticeContinue": "請繼續處理發貨任務 {taskId}。先讀取目前任務狀態;如果仍待解析,請解析發貨通知並儲存結果;如果已進入後續步驟,請直接說明目前進度和下一步。",
|
||||||
"shippingNoticeActionsHint": "請選擇操作:",
|
"shippingNoticeActionsHint": "請選擇操作:",
|
||||||
"shippingNoticeMissingTaskId": "找不到任務編號,請先完成發貨通知解析。",
|
"shippingNoticeMissingTaskId": "找不到任務編號,請先完成發貨通知解析。",
|
||||||
"shippingNoticeUploadDone": "庫存檔案已上傳:{fileName}。",
|
"shippingNoticeUploadDone": "庫存檔案已上傳:{fileName}。",
|
||||||
"shippingNoticeUploadOk": "上傳成功。",
|
"shippingNoticeUploadOk": "上傳成功。",
|
||||||
"shippingNoticeUploadFailed": "庫存檔案上傳失敗。",
|
"shippingNoticeUploadFailed": "庫存檔案上傳失敗。",
|
||||||
|
"shippingNoticeRefreshDone": "已重新整理目前任務狀態。",
|
||||||
|
"shippingNoticeRetryUploadAction": "重試上傳貨代",
|
||||||
|
"shippingNoticeRetryUploadQueued": "已重新觸發上傳,請稍後重新整理查看結果。",
|
||||||
|
"shippingNoticeRetryUploadFailed": "重試上傳失敗。",
|
||||||
"shippingNoticePasteHint": "請在輸入框貼上庫存小表內容後送出。",
|
"shippingNoticePasteHint": "請在輸入框貼上庫存小表內容後送出。",
|
||||||
"shippingNoticeDecisionDone": "操作已完成。",
|
"shippingNoticeDecisionDone": "操作已完成。",
|
||||||
"shippingNoticePrompt": {
|
"shippingNoticePrompt": {
|
||||||
@@ -42,9 +47,9 @@
|
|||||||
"taskLabel": "當前任務 {taskId}",
|
"taskLabel": "當前任務 {taskId}",
|
||||||
"taskList": "任務列表:{taskIds}。",
|
"taskList": "任務列表:{taskIds}。",
|
||||||
"autoInventoryAction": "上傳庫存並進入欄位對齊",
|
"autoInventoryAction": "上傳庫存並進入欄位對齊",
|
||||||
"autoNoticeAction": "解析發貨通知並建立任務",
|
"autoNoticeAction": "建立任務並解析發貨通知",
|
||||||
"multiTask": "{summary}。{taskListText}請只處理目前焦點任務。先呼叫 get_task_status 讀取目前任務狀態;如果目前任務仍待解析,請讀取 raw_text,用 LLM 抽取結構化欄位後呼叫 parse_notice(structured=...) 落庫;如果已進入後續步驟,請直接說明目前狀態並給出本任務下一步引導。禁止再次詢問我「是否開始解析」,也不要整批迴圈處理其他任務。",
|
"multiTask": "{summary}。{taskListText}請只處理目前焦點任務。先讀取目前任務狀態;如果仍待解析,請解析發貨通知並儲存結果;如果已進入後續步驟,請直接說明目前進度和下一步。不要再次詢問我是否開始解析,也不要整批迴圈處理其他任務。",
|
||||||
"singleTask": "{summary}。請先呼叫 get_task_status 讀取目前任務狀態;如果目前任務仍待解析,請讀取 raw_text,用 LLM 抽取結構化欄位後直接呼叫 parse_notice(structured=...) 落庫;若已進入後續步驟,請直接說明目前狀態並給出下一步引導。禁止再次詢問我「是否開始解析」或「是否現在開始解析」。"
|
"singleTask": "{summary}。請先讀取目前任務狀態;如果仍待解析,請解析發貨通知並儲存結果;如果已進入後續步驟,請直接說明目前進度和下一步。不要再次詢問我是否開始解析。"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"shippingNoticeMapping": {
|
"shippingNoticeMapping": {
|
||||||
@@ -106,17 +111,79 @@
|
|||||||
"batchProgress": "第 {index}/{total} 票",
|
"batchProgress": "第 {index}/{total} 票",
|
||||||
"batchCurrentIndex": "當前處理第 {index}/{total} 票",
|
"batchCurrentIndex": "當前處理第 {index}/{total} 票",
|
||||||
"batchSummaryLine": "本批 {total} 筆 · 已完成 {completed} · 進行中 {running} · 待處理 {pending}",
|
"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": "當前通知",
|
"currentNotice": "當前通知",
|
||||||
"currentStepLabel": "目前",
|
"currentStepLabel": "目前",
|
||||||
"stepHeadline": "步驟 {current}/{total} · {label}",
|
"stepHeadline": "步驟 {current}/{total} · {label}",
|
||||||
"stepFraction": "步驟 {current}/{total}",
|
"stepFraction": "步驟 {current}/{total}",
|
||||||
"stepNeedsConfirm": "步驟 {step} 待確認",
|
"stepNeedsConfirm": "步驟 {step} 待確認",
|
||||||
"taskListResume": "任務列表 / 續辦",
|
"taskListResume": "任務列表 / 續辦",
|
||||||
|
"retryPendingTasks": "重試目前批次可恢復任務",
|
||||||
|
"retryPendingDone": "已重新提交可恢復任務",
|
||||||
|
"retryFailed": "重試失敗",
|
||||||
|
"retrying": "重試中...",
|
||||||
"taskListTitle": "任務列表",
|
"taskListTitle": "任務列表",
|
||||||
"taskListHint": "切換任務後,對話頂部 Stepper 與操作會同步更新",
|
"taskListHint": "切換任務後,對話頂部 Stepper 與操作會同步更新",
|
||||||
"expandTaskList": "展開列表",
|
"expandTaskList": "展開任務列表",
|
||||||
"collapseTaskList": "收起列表",
|
"collapseTaskList": "收起任務列表",
|
||||||
"currentFocus": "目前聚焦 →",
|
"currentFocus": "目前聚焦:",
|
||||||
|
"currentFocusDefaultReason": "輸入內容將作用於該單票任務",
|
||||||
|
"focusInputPlaceholder": "正在處理 {taskId},輸入指令...",
|
||||||
|
"clearFocus": "取消聚焦",
|
||||||
"runningState": "進行中",
|
"runningState": "進行中",
|
||||||
"pendingState": "待確認",
|
"pendingState": "待確認",
|
||||||
"completedState": "已完成",
|
"completedState": "已完成",
|
||||||
|
|||||||
Reference in new issue
Block a user