feat(shipping-notice): 实现对话级批量重试自动推进功能,优化库存与PDF匹配逻辑
- 新增对话级批量重试自动推进的完整链路:后端服务、API、数据投影逻辑 - 前端新增对话级重试按钮、多语言国际化支持与API类型定义 - 优化行级库存重试控制,新增retryable字段统一管控重试按钮展示,清理废弃的view_fulfillment_detail动作,标准化前端动作码排序逻辑 - 修复PDF坐标匹配的fail-close防护逻辑,避免生成伪精确匹配分数 - 调整订单确认后流程,提前进入库存获取阶段,移除冗余的确认建单按钮,优化用户流转体验 - 新增对应单元测试用例覆盖核心业务逻辑
This commit is contained in:
1 parent
fd6a23f870
commit
1008911a7e
41 files changed
+3956
-1256
No files matched your search
@@ -498,6 +498,30 @@ def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-conversations/<conversation_id>/retry-auto-progress',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_retry_conversation_auto_progress(conversation_id: str):
|
||||
"""
|
||||
对话级「重试自动推进」:扫描会话下可恢复 Case/正式 OT 并逐对象重试。
|
||||
|
||||
核心逻辑:委托 conversation_retry_auto_progress_service;前端不提交对象列表;
|
||||
返回 summary + items;写 conversation_retry_auto_progress 汇总审计。
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
|
||||
retry_auto_progress_for_conversation,
|
||||
)
|
||||
|
||||
return _ok(retry_auto_progress_for_conversation(
|
||||
user_id=int(user.id),
|
||||
conversation_id=str(conversation_id or '').strip(),
|
||||
reason=str(data.get('reason') or 'user_retry_auto_progress'),
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
@@ -649,27 +673,56 @@ def workspace_shipping_task_chat_actions(task_no: str):
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_task(task_no: str):
|
||||
"""
|
||||
重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。
|
||||
用户侧重试当前正式 OT:统一决策器选择 resolve_source / fetch / rematch / auto_progress。
|
||||
|
||||
核心逻辑:注入当前用户为操作人,保证 TaskEvent / 统一审计可追溯。
|
||||
核心逻辑:委托 task_retry_decision_service.retry_task_with_decision(scope=task);
|
||||
不再直接调用通用 retry_task 重置编排器。
|
||||
"""
|
||||
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
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {
|
||||
'task_id': task.task_no,
|
||||
'operator_id': user.id,
|
||||
'actor_id': user.id,
|
||||
'_trusted_user_id': user.id,
|
||||
'event_source': 'workspace_api',
|
||||
}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return _ok(shipping_tools.retry_task(payload))
|
||||
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
|
||||
|
||||
return _ok(retry_task_with_decision(
|
||||
task_no=str(task.task_no),
|
||||
user_id=int(user.id),
|
||||
scope='task',
|
||||
reason=str(data.get('reason') or data.get('comment') or 'user_retry'),
|
||||
trigger='user_retry',
|
||||
continue_auto_progress=False,
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-tasks/<task_no>/lines/<line_key>/retry',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_retry_shipping_task_line(task_no: str, line_key: str):
|
||||
"""
|
||||
行级统一「重试」:与任务级共用决策器,scope=line。
|
||||
|
||||
核心逻辑:前端不传内部动作码;后端按行库存事实选择 fetch/rematch/needs_human。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
|
||||
|
||||
return _ok(retry_task_with_decision(
|
||||
task_no=str(task.task_no),
|
||||
user_id=int(user.id),
|
||||
scope='line',
|
||||
line_key=str(line_key or '').strip(),
|
||||
reason=str(data.get('reason') or 'user_retry_inventory'),
|
||||
trigger='user_line_retry',
|
||||
continue_auto_progress=False,
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
@@ -943,34 +996,40 @@ def workspace_remove_shipping_notice_line(task_no: str):
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
|
||||
def workspace_auto_progress_shipping_task(task_no: str):
|
||||
"""
|
||||
用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。
|
||||
系统/确认后调度兼容入口:内部委托统一决策器(continue_auto_progress=True)。
|
||||
|
||||
核心逻辑:标记 source=workspace_api 并注入操作人,避免用户触发被记成匿名 system。
|
||||
核心逻辑:用户界面不应再调用本接口;用户重试走 /retry 或对话级 API。
|
||||
"""
|
||||
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
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload: dict = {
|
||||
'task_id': task.task_no,
|
||||
'source': 'workspace_api',
|
||||
'operator_id': user.id,
|
||||
'actor_id': user.id,
|
||||
'_trusted_user_id': user.id,
|
||||
}
|
||||
for key in ('lang', 'locale', 'language'):
|
||||
if data.get(key):
|
||||
payload[key] = data[key]
|
||||
break
|
||||
result = shipping_tools.auto_progress(payload)
|
||||
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
|
||||
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
gen_data = result.get('data')
|
||||
if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
|
||||
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
|
||||
result = {**result, 'data': gen_data}
|
||||
result = retry_task_with_decision(
|
||||
task_no=str(task.task_no),
|
||||
user_id=int(user.id),
|
||||
scope='task',
|
||||
reason=str(data.get('reason') or 'system_auto_progress'),
|
||||
trigger='system_auto_progress',
|
||||
continue_auto_progress=True,
|
||||
)
|
||||
|
||||
# 兼容旧前端:若仍有 export 路径则附带 download_url。
|
||||
if isinstance(result, dict) and result.get('status') in {'completed', 'running', 'ok'}:
|
||||
# 重新加载任务以读取 export_file_path(若决策器已推进到导出)。
|
||||
refreshed = get_task_for_user(task_no, user.id)
|
||||
export_path = getattr(refreshed, 'export_file_path', None) if refreshed is not None else None
|
||||
if export_path:
|
||||
result = {
|
||||
**result,
|
||||
'data': {
|
||||
**dict(result.get('data') or {}),
|
||||
'export_file_path': export_path,
|
||||
'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export',
|
||||
},
|
||||
}
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||
|
||||
@@ -0,0 +1,463 @@
|
||||
"""
|
||||
services/shipping_notice/conversation_retry_auto_progress_service.py
|
||||
|
||||
用途:对话级「重试自动推进」投影与批量执行(Case STP / 正式 OT 统一决策器)。
|
||||
依赖:order_review_projection、order_stp_auto_create_service、task_retry_decision_service、
|
||||
fulfillment_audit、ShippingOrderReviewCase / ShippingOrderProcessingRun / ShippingNotice。
|
||||
逻辑:eligible 唯一依据 automation.retryable=true;建单前 Case→retry_stp_auto_create,
|
||||
正式 OT→task_retry_decision_service(与任务级 /retry 同源);不批量行库存;
|
||||
写 conversation_retry_auto_progress 汇总审计,对象级审计由既有链路写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ACTION_RETRY_AUTO_PROGRESS = 'retry_auto_progress'
|
||||
ACTION_RETRY_STP = 'retry_stp_auto_create'
|
||||
OBJECT_REVIEW_CASE = 'review_case'
|
||||
OBJECT_FORMAL_TASK = 'formal_task'
|
||||
|
||||
|
||||
def project_conversation_allowed_actions(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
投影对话级可执行动作(当前仅重试自动推进)。
|
||||
|
||||
核心逻辑:扫描会话下 Case;automation.retryable=true 计入 eligible_count;
|
||||
无合格对象时返回空列表(前端不渲染禁用空按钮)。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户。
|
||||
conversation_id: 会话 ID。
|
||||
|
||||
Returns:
|
||||
``[{code, eligible_count}]`` 或 ``[]``。
|
||||
"""
|
||||
normalized = str(conversation_id or '').strip()
|
||||
if not normalized or not user_id:
|
||||
return []
|
||||
eligible = _list_eligible_targets(user_id=int(user_id), conversation_id=normalized)
|
||||
if not eligible:
|
||||
return []
|
||||
return [{
|
||||
'code': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'eligible_count': len(eligible),
|
||||
}]
|
||||
|
||||
|
||||
def retry_auto_progress_for_conversation(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
reason: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对话级批量重试自动推进。
|
||||
|
||||
核心逻辑:按 conversation_id 服务端扫描;逐对象重读最新 automation 后执行;
|
||||
Case→STP(内部 refresh_validation);正式 OT→auto_progress;不批量行库存。
|
||||
|
||||
Args:
|
||||
user_id: 操作人。
|
||||
conversation_id: 会话 ID。
|
||||
reason: 可选原因(写入审计 metadata)。
|
||||
|
||||
Returns:
|
||||
``{conversation_id, summary, items}``。
|
||||
|
||||
Raises:
|
||||
ValidationError: conversation_id 为空。
|
||||
NotFoundError: 会话下无可访问对象且会话不存在于用户范围。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
normalized = str(conversation_id or '').strip()
|
||||
if not normalized:
|
||||
raise ValidationError('conversation_id is required')
|
||||
|
||||
cases = _list_conversation_cases(user_id=int(user_id), conversation_id=normalized)
|
||||
if not cases and not _conversation_has_any_asset(user_id=int(user_id), conversation_id=normalized):
|
||||
raise NotFoundError('Conversation not found')
|
||||
|
||||
items: list[dict[str, Any]] = []
|
||||
for case in cases:
|
||||
items.append(_retry_one_case(user_id=int(user_id), case=case))
|
||||
|
||||
summary = _summarize_items(items)
|
||||
record_fulfillment_audit(
|
||||
event_type='conversation_retry_auto_progress',
|
||||
aggregate_type='shipping_conversation',
|
||||
aggregate_id=normalized,
|
||||
action='retry_auto_progress',
|
||||
actor_id=int(user_id),
|
||||
conversation_id=normalized,
|
||||
owner_user_id=int(user_id),
|
||||
result='success' if summary['failed'] == 0 else 'partial',
|
||||
metadata={
|
||||
'reason': str(reason or 'user_retry_auto_progress')[:200],
|
||||
'summary': summary,
|
||||
'items': items,
|
||||
},
|
||||
source='api',
|
||||
)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('conversation retry audit commit failed conversation_id=%s', normalized)
|
||||
|
||||
return {
|
||||
'conversation_id': normalized,
|
||||
'summary': summary,
|
||||
'items': items,
|
||||
}
|
||||
|
||||
|
||||
def _conversation_has_any_asset(*, user_id: int, conversation_id: str) -> bool:
|
||||
"""会话是否存在属于当前用户的 Run / 正式任务(用于 404 判定)。"""
|
||||
run_exists = (
|
||||
ShippingOrderProcessingRun.query
|
||||
.filter_by(user_id=int(user_id), conversation_id=conversation_id)
|
||||
.limit(1)
|
||||
.first()
|
||||
)
|
||||
if run_exists is not None:
|
||||
return True
|
||||
notice_exists = (
|
||||
ShippingNotice.query
|
||||
.filter_by(user_id=int(user_id), conversation_id=conversation_id)
|
||||
.limit(1)
|
||||
.first()
|
||||
)
|
||||
return notice_exists is not None
|
||||
|
||||
|
||||
def _list_conversation_cases(*, user_id: int, conversation_id: str) -> list[ShippingOrderReviewCase]:
|
||||
"""
|
||||
列出会话下全部复核 Case(按 id 升序,稳定执行顺序)。
|
||||
|
||||
核心逻辑:经 ProcessingRun.conversation_id + user_id 关联,禁止跨会话/跨用户。
|
||||
"""
|
||||
return (
|
||||
db.session.query(ShippingOrderReviewCase)
|
||||
.join(
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase.run_id == ShippingOrderProcessingRun.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderProcessingRun.conversation_id == conversation_id,
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _automation_for_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""投影 Case automation(与工作台同源)。"""
|
||||
from app.services.shipping_notice.order_review_projection import (
|
||||
_project_case_automation_status,
|
||||
_project_post_confirm_auto_progress,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
enrich_automation_status,
|
||||
resolve_formal_ot,
|
||||
)
|
||||
|
||||
draft = case.current_draft
|
||||
validation = dict(draft.validation_result_json or {}) if draft is not None else None
|
||||
post_confirm = _project_post_confirm_auto_progress(case)
|
||||
automation = _project_case_automation_status(
|
||||
case,
|
||||
validation=validation,
|
||||
post_confirm=post_confirm,
|
||||
)
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
return enrich_automation_status(
|
||||
automation if isinstance(automation, dict) else {},
|
||||
formal_ot=formal_ot,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
|
||||
def _formal_task_no(case: ShippingOrderReviewCase, automation: dict[str, Any]) -> str | None:
|
||||
"""解析正式 OT 编号(有则走 auto-progress,无则走 STP)。"""
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
|
||||
formal = resolve_formal_ot(case)
|
||||
if formal.get('task_missing'):
|
||||
return None
|
||||
if not formal.get('has_formal_ot'):
|
||||
return None
|
||||
task_no = str(
|
||||
automation.get('task_no')
|
||||
or getattr(case, 'confirmed_task_no', None)
|
||||
or ''
|
||||
).strip()
|
||||
return task_no or None
|
||||
|
||||
|
||||
def _list_eligible_targets(*, user_id: int, conversation_id: str) -> list[dict[str, Any]]:
|
||||
"""扫描可重试对象(仅 retryable=true)。"""
|
||||
targets: list[dict[str, Any]] = []
|
||||
for case in _list_conversation_cases(user_id=user_id, conversation_id=conversation_id):
|
||||
automation = _automation_for_case(case)
|
||||
if not bool(automation.get('retryable')):
|
||||
continue
|
||||
task_no = _formal_task_no(case, automation)
|
||||
if task_no:
|
||||
targets.append({
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'case_no': case.case_no,
|
||||
})
|
||||
elif not case.confirmed_task_id:
|
||||
targets.append({
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'case_no': case.case_no,
|
||||
})
|
||||
return targets
|
||||
|
||||
|
||||
def _skip_reason_from_automation(automation: dict[str, Any], *, task_missing: bool) -> str | None:
|
||||
"""
|
||||
根据最新 automation 返回跳过原因;可执行时返回 None。
|
||||
|
||||
核心逻辑:queued/running/completed/task_missing 跳过;needs_human 跳过;
|
||||
manual_fallback 的 owner_type=human 仍可 retryable,不得误判为人工阻断跳过。
|
||||
"""
|
||||
if task_missing:
|
||||
return 'task_missing'
|
||||
status = str(automation.get('status') or '').strip().lower()
|
||||
if status in {'queued', 'running'}:
|
||||
return 'already_running'
|
||||
if status in {'completed', 'succeeded'}:
|
||||
return 'already_completed'
|
||||
if status == 'needs_human':
|
||||
return 'human_blocking'
|
||||
if not bool(automation.get('retryable')):
|
||||
return 'not_retryable'
|
||||
return None
|
||||
|
||||
|
||||
def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""
|
||||
对单个 Case 执行重试或跳过。
|
||||
|
||||
核心逻辑:重读 automation;正式 OT→auto_progress;否则 STP;异常映射为 failed/skipped。
|
||||
"""
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
|
||||
automation = _automation_for_case(case)
|
||||
formal = resolve_formal_ot(case)
|
||||
task_missing = bool(formal.get('task_missing'))
|
||||
task_no = _formal_task_no(case, automation)
|
||||
|
||||
if task_no:
|
||||
skip = _skip_reason_from_automation(automation, task_missing=task_missing)
|
||||
if skip:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': skip,
|
||||
}
|
||||
return _execute_formal_task_retry(user_id=user_id, task_no=task_no)
|
||||
|
||||
if task_missing or case.confirmed_task_id:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'task_missing' if task_missing else 'already_confirmed',
|
||||
}
|
||||
|
||||
skip = _skip_reason_from_automation(automation, task_missing=False)
|
||||
if skip:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': skip,
|
||||
}
|
||||
return _execute_stp_retry(user_id=user_id, case_no=str(case.case_no))
|
||||
|
||||
|
||||
def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
|
||||
"""调用既有 STP retry;捕获业务错误为逐对象 outcome。"""
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
retry_stp_auto_create_for_case,
|
||||
)
|
||||
|
||||
try:
|
||||
result = retry_stp_auto_create_for_case(user_id=user_id, case_no=case_no)
|
||||
status = str(result.get('status') or '').strip().lower()
|
||||
if status in {'queued', 'reused', 'enqueued'}:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'queued',
|
||||
'reason_code': None,
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': status or 'not_retryable',
|
||||
}
|
||||
except AppError as err:
|
||||
code = str(getattr(err, 'code', None) or 'SHIPPING.STP_ENQUEUE_FAILED')
|
||||
if 'ALREADY_CONFIRMED' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_confirmed',
|
||||
}
|
||||
if 'NOT_ELIGIBLE' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': code,
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': code,
|
||||
}
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('conversation STP retry failed case_no=%s', case_no)
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.STP_ENQUEUE_FAILED',
|
||||
}
|
||||
|
||||
|
||||
def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
|
||||
"""正式 OT 重试:委托统一决策器(与任务级 /retry 同源)。"""
|
||||
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
|
||||
|
||||
try:
|
||||
result = retry_task_with_decision(
|
||||
task_no=str(task_no),
|
||||
user_id=int(user_id),
|
||||
scope='task',
|
||||
reason='conversation_retry_auto_progress',
|
||||
trigger='conversation_retry',
|
||||
continue_auto_progress=False,
|
||||
)
|
||||
except AppError as err:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': str(getattr(err, 'code', None) or 'SHIPPING.AUTO_PROGRESS_FAILED'),
|
||||
}
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('conversation task retry failed task_no=%s', task_no)
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.AUTO_PROGRESS_FAILED',
|
||||
}
|
||||
|
||||
status = str((result or {}).get('status') or '').strip().lower()
|
||||
action = str((result or {}).get('action') or '') or ACTION_RETRY_AUTO_PROGRESS
|
||||
if status == 'needs_human':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': str((result or {}).get('reason_code') or 'human_blocking'),
|
||||
}
|
||||
if status == 'failed':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'failed',
|
||||
'reason_code': str((result or {}).get('reason_code') or status),
|
||||
}
|
||||
if action == 'noop' and str((result or {}).get('reason_code') or '') == 'already_running':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_running',
|
||||
}
|
||||
if action == 'noop' and status == 'completed':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': str((result or {}).get('reason_code') or 'already_completed'),
|
||||
}
|
||||
if status in {'running', 'completed', 'queued'}:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'queued',
|
||||
'reason_code': None,
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': str((result or {}).get('reason_code') or status or 'not_retryable'),
|
||||
}
|
||||
|
||||
|
||||
def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""汇总逐对象结果。"""
|
||||
retried = skipped = failed = 0
|
||||
for item in items:
|
||||
outcome = str(item.get('outcome') or '').strip().lower()
|
||||
if outcome == 'queued':
|
||||
retried += 1
|
||||
elif outcome == 'failed':
|
||||
failed += 1
|
||||
else:
|
||||
skipped += 1
|
||||
return {
|
||||
'total': len(items),
|
||||
'retried': retried,
|
||||
'skipped': skipped,
|
||||
'failed': failed,
|
||||
}
|
||||
+33
-4
@@ -13,15 +13,29 @@ def _coordinate_mapping(value: Any) -> dict[str, Any]:
|
||||
return dict(value) if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _append_issue(layout: dict[str, Any], issue: str) -> None:
|
||||
"""稳定追加坐标恢复失败码,不改变原 issues 相对顺序。"""
|
||||
existing = layout.get('issues') if isinstance(layout.get('issues'), list) else []
|
||||
issues = [str(item) for item in existing]
|
||||
if issue not in issues:
|
||||
issues.append(issue)
|
||||
layout['issues'] = issues
|
||||
|
||||
|
||||
def ensure_on_demand_coordinate_evidence(
|
||||
*, document: ShippingOrderDocument, layout: dict[str, Any], page_nos: set[int] | None,
|
||||
table_by_page: dict[int, dict[str, Any] | list[dict[str, Any]]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。"""
|
||||
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。
|
||||
|
||||
【AI/调用方触发时机】:
|
||||
- 订单字段重放、模板匹配或明细重建前,为当前 snapshot 恢复缺失页的真实坐标。
|
||||
- 失败不静默;任何 PDFium/OCR 失败都会在 layout['issues'] 追加稳定失败码,
|
||||
上游可据此将 matcher 从 no_match 转为 evidence_insufficient。
|
||||
"""
|
||||
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
|
||||
return layout
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
# 兼容历史布局快照:布局任务曾将坐标证据写在顶层,正式抽取仍需复用它。
|
||||
if not evidence:
|
||||
legacy_keys = ('pages', 'page_glyphs', 'sources', 'tables')
|
||||
evidence = {
|
||||
@@ -29,7 +43,6 @@ def ensure_on_demand_coordinate_evidence(
|
||||
for key in legacy_keys
|
||||
if isinstance(layout.get(key), dict)
|
||||
}
|
||||
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
|
||||
current_version = getattr(document, 'current_layout_version', None)
|
||||
current_payload = getattr(current_version, 'payload_json', None)
|
||||
if isinstance(current_payload, dict):
|
||||
@@ -44,7 +57,15 @@ def ensure_on_demand_coordinate_evidence(
|
||||
sources = _coordinate_mapping(evidence.get('sources'))
|
||||
source_pages = _coordinate_mapping(sources.get('pages'))
|
||||
tables = _coordinate_mapping(evidence.get('tables'))
|
||||
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
|
||||
# [FAIL-CLOSED GATE] page_glyphs 必须对所需页真实存在;不能用 pages 元数据或
|
||||
# 非数字脏键来假装已恢复。MinerU HTML 表 + 空 page_glyphs 的组合必须继续走
|
||||
# 真实 PDFium/OCR 抽取,否则会退化为"伪精确匹配分数"。
|
||||
present_pages = {
|
||||
int(key) for key in page_glyphs
|
||||
if str(key).isdigit() and isinstance(page_glyphs.get(key), list) and len(page_glyphs.get(key) or []) > 0
|
||||
}
|
||||
needs_recovery = bool(page_nos is None) or not page_nos.issubset(present_pages)
|
||||
if not needs_recovery:
|
||||
return layout
|
||||
tables_by_page: dict[int, list[dict[str, Any]]] = {}
|
||||
for raw_table in layout.get('tables') or []:
|
||||
@@ -70,11 +91,15 @@ def ensure_on_demand_coordinate_evidence(
|
||||
)
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is None:
|
||||
_append_issue(layout, 'coordinate_evidence_asset_missing')
|
||||
return layout
|
||||
try:
|
||||
native_pages = extract_native_pdf_pages(read_asset_bytes(asset))
|
||||
except Exception:
|
||||
# [FAIL-CLOSED] PDFium 级异常必须显式上报;禁止用 MinerU HTML 列名顶替坐标。
|
||||
_append_issue(layout, 'coordinate_evidence_native_pdf_unavailable')
|
||||
return layout
|
||||
recovered_any_page = False
|
||||
for page in native_pages:
|
||||
if page_nos is not None and int(page.page_no) not in page_nos:
|
||||
continue
|
||||
@@ -87,12 +112,14 @@ def ensure_on_demand_coordinate_evidence(
|
||||
source = 'ocr_coordinate'
|
||||
except Exception:
|
||||
glyphs = []
|
||||
_append_issue(layout, f'coordinate_evidence_ocr_failed_page_{page.page_no}')
|
||||
if not glyphs:
|
||||
continue
|
||||
page_key = str(page.page_no)
|
||||
pages[page_key] = {'width': page.width, 'height': page.height}
|
||||
page_glyphs[page_key] = glyphs
|
||||
source_pages[page_key] = source
|
||||
recovered_any_page = True
|
||||
for table in tables_by_page.get(int(page.page_no), []):
|
||||
table_id = str(table.get('table_id') or '')
|
||||
chars = _native_characters_in_table(
|
||||
@@ -107,6 +134,8 @@ def ensure_on_demand_coordinate_evidence(
|
||||
chars = []
|
||||
if table_id and chars:
|
||||
tables[table_id] = chars
|
||||
if page_nos is not None and not recovered_any_page:
|
||||
_append_issue(layout, 'coordinate_evidence_no_page_recovered')
|
||||
next_layout = dict(layout)
|
||||
next_layout['coordinate_evidence'] = {
|
||||
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
|
||||
|
||||
@@ -119,7 +119,22 @@ def match_frozen_coordinate_profiles(
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
if not pages or (not glyph_tables and not page_glyphs and not tables):
|
||||
# [FAIL-CLOSED GATE] 第零层:on-demand 坐标恢复显式失败时直接拒绝匹配。
|
||||
# 任何 coordinate_evidence_* 失败码都意味着正式证据不可用,MinerU HTML 列名
|
||||
# 不得作为坐标模板匹配的替代事实源。
|
||||
layout_issues = {str(item) for item in (layout.get('issues') or []) if str(item)}
|
||||
coordinate_failure_issues = {
|
||||
code for code in layout_issues if code.startswith('coordinate_evidence_')
|
||||
}
|
||||
if coordinate_failure_issues:
|
||||
return ProfileMatchResult(status='evidence_insufficient')
|
||||
# [FAIL-CLOSED GATE] 第一层:坐标字符证据必须至少有一种来源。
|
||||
# MinerU HTML tables(layout['tables'])只有结构化列名、没有绝对坐标/bbox,
|
||||
# 严禁单独充当坐标模板的匹配证据。否则会出现"MinerU 有列名但 matcher
|
||||
# header_tokens=空、column_count=0、evidence_coverage 伪分数"的分裂。
|
||||
if not pages:
|
||||
return ProfileMatchResult(status='evidence_insufficient')
|
||||
if not glyph_tables and not page_glyphs:
|
||||
return ProfileMatchResult(status='evidence_insufficient')
|
||||
|
||||
page_text = _layout_page_text(
|
||||
@@ -201,6 +216,25 @@ def match_frozen_coordinate_profiles(
|
||||
)
|
||||
reason_codes.extend(hard_conflict_codes)
|
||||
|
||||
# [FAIL-CLOSED GATE] 第二层:身份证据缺失时,结构/几何维度不得独立构成模板命中。
|
||||
# 用户场景:page_glyphs 虽有字符但观测不到 header_tokens 或
|
||||
# column_centers;若签名冻结了核心列身份证据,就必须以身份优先、
|
||||
# 结构辅助。否则 table_geometry + page_structure 的弱证据会掩盖
|
||||
# "列名证据没有进入匹配器" 的真正问题。
|
||||
signature_patterns = (
|
||||
[item for item in (signature_body or {}).get('table_patterns') or [] if isinstance(item, dict)]
|
||||
if signature_body is not None else []
|
||||
)
|
||||
signature_expects_identity = any(
|
||||
bool(p.get('header_tokens') or p.get('column_centers') or (p.get('column_count') or 0) > 0)
|
||||
for p in signature_patterns
|
||||
)
|
||||
observed_header = [str(item) for item in (observed.get('header_tokens') or []) if str(item).strip()]
|
||||
observed_col_count = int(observed.get('column_count') or 0)
|
||||
observed_has_identity = bool(observed_header) or observed_col_count > 0
|
||||
if signature_expects_identity and not observed_has_identity:
|
||||
reason_codes.append('profile_core_column_evidence_missing')
|
||||
|
||||
weights = profile.document_match.scoring_weights
|
||||
score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results)
|
||||
hard_match = not reason_codes
|
||||
@@ -256,6 +290,19 @@ def match_frozen_coordinate_profiles(
|
||||
status='no_match', candidates=rendered,
|
||||
top1_score=top1_score, top2_score=top2_score, margin=margin,
|
||||
)
|
||||
# [FAIL-CLOSED GATE] 第三层:全局证据不足优先于 no_match / layout_drift。
|
||||
# 当所有候选要么缺签名身份证据、要么观测不到核心列名/列坐标时,必须
|
||||
# evidence_insufficient,禁止把"没证据"误报成"模板都不匹配"。
|
||||
global_identity_missing = all(
|
||||
'profile_core_column_evidence_missing' in item.reason_codes
|
||||
or 'profile_signature_missing' in item.reason_codes
|
||||
for item in rendered
|
||||
)
|
||||
if global_identity_missing:
|
||||
return ProfileMatchResult(
|
||||
status='evidence_insufficient', candidates=rendered,
|
||||
top1_score=None, top2_score=None, margin=None,
|
||||
)
|
||||
if _any_special_profile_feature(candidates, page_text=page_text):
|
||||
return ProfileMatchResult(
|
||||
status='layout_drift', candidates=rendered,
|
||||
|
||||
@@ -500,10 +500,12 @@ def _native_pdf_fallback_snapshot(
|
||||
layout_payload=layout_payload_preview,
|
||||
)
|
||||
evidence_started = perf_counter()
|
||||
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
|
||||
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
|
||||
# [FAIL-CLOSED OVERRIDE] Fallback 快照即使是 PDFium 文本回退,也必须默认
|
||||
# 保存整页 glyph。否则一旦 on-demand 恢复异常(如 asset_id 丢失或 PDFium 崩
|
||||
# 溃),matcher 会看到"MinerU 列名存在 + 空 page_glyphs"的分裂证据,输出
|
||||
# 伪精确模板分数。坐标预算由后续 compact 负责兜底,初始生成必须包含身份证据。
|
||||
evidence = _table_coordinate_evidence(
|
||||
pages=native_pages, tables=tables, include_page_glyphs=False,
|
||||
pages=native_pages, tables=tables, include_page_glyphs=True,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
if diagnostics is not None:
|
||||
|
||||
@@ -5,7 +5,8 @@ services/shipping_notice/line_inventory_match_projection.py
|
||||
依赖:ShippingNoticeLineInventoryMatch、Config 自动履约开关。
|
||||
逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用;
|
||||
ready+not_found→available=0;result_missing 不得转 0;
|
||||
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮)。
|
||||
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
|
||||
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -35,7 +36,30 @@ STATUS_INVALID_KEY = 'invalid_key'
|
||||
ACTION_RETRY_PREPARATION = 'retry_inventory_preparation'
|
||||
ACTION_RETRY_MATCHING = 'retry_inventory_matching'
|
||||
ACTION_CLOSE = 'close_unfulfillable'
|
||||
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail'
|
||||
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail' # 已下线:不得再下发 UI
|
||||
|
||||
|
||||
def project_line_retryable(
|
||||
*,
|
||||
inventory_allowed_actions: list[str] | None,
|
||||
user_line_status: str | None,
|
||||
inventory_rpa_running: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
行级是否对用户展示统一「重试」按钮。
|
||||
|
||||
核心逻辑:存在内部库存动作且非短缺/冲突人工阻断、非 RPA 运行中。
|
||||
UI 只消费本布尔值,不展示内部动作码。
|
||||
"""
|
||||
if inventory_rpa_running:
|
||||
return False
|
||||
status = str(user_line_status or '').strip().lower()
|
||||
if status in {
|
||||
'shortage', 'source_conflict', 'wave_created', 'fulfilled', 'closed', 'inventory_matched',
|
||||
}:
|
||||
return False
|
||||
return bool([a for a in (inventory_allowed_actions or []) if a])
|
||||
|
||||
|
||||
SOURCE_STATUS_RESOLVED = 'resolved'
|
||||
SOURCE_STATUS_RESOLVING = 'resolving'
|
||||
@@ -326,7 +350,9 @@ def resolve_line_allowed_actions(
|
||||
user_line_status: str | None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
行生命周期动作;本轮仅 close_unfulfillable(已完成/已关闭不展示)。
|
||||
行生命周期动作;仅 close_unfulfillable。
|
||||
|
||||
核心逻辑:已完成/已关闭/已入波次不开放行动作;彻底移除 view_fulfillment_detail。
|
||||
"""
|
||||
if not has_formal_ot:
|
||||
return []
|
||||
@@ -335,8 +361,6 @@ def resolve_line_allowed_actions(
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed',
|
||||
}:
|
||||
if user_status in {'wave_created', 'fulfilled'}:
|
||||
return [ACTION_VIEW_FULFILLMENT] if user_status != 'closed' else []
|
||||
return []
|
||||
return [ACTION_CLOSE]
|
||||
|
||||
@@ -477,6 +501,7 @@ def project_line_inventory_view(
|
||||
},
|
||||
'user_line_status': user_status,
|
||||
'decision_source': decision_source,
|
||||
'retryable': False,
|
||||
'inventory_allowed_actions': [],
|
||||
'line_allowed_actions': [],
|
||||
'allowed_actions': [],
|
||||
@@ -538,6 +563,11 @@ def project_line_inventory_view(
|
||||
source_code=fact.get('inventory_source_code'),
|
||||
source_labels=source_labels,
|
||||
)
|
||||
retryable = project_line_retryable(
|
||||
inventory_allowed_actions=inv_actions,
|
||||
user_line_status=user_status,
|
||||
inventory_rpa_running=bool(inventory_rpa_running),
|
||||
)
|
||||
return {
|
||||
'inventory_status': inventory_status,
|
||||
'match_result': match_result,
|
||||
@@ -552,6 +582,7 @@ def project_line_inventory_view(
|
||||
'matching_rule_version': fact.get('matching_rule_version'),
|
||||
'user_line_status': user_status,
|
||||
'decision_source': decision_source,
|
||||
'retryable': retryable,
|
||||
'inventory_allowed_actions': inv_actions,
|
||||
'line_allowed_actions': line_actions,
|
||||
'allowed_actions': [*inv_actions, *line_actions],
|
||||
|
||||
@@ -1686,7 +1686,9 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
|
||||
def _route_reason_for_issue(issue: str) -> str:
|
||||
"""把内部解析问题收敛为管理员可长期依赖的稳定路由原因码。"""
|
||||
mapping = {
|
||||
'order_profile_evidence_insufficient': 'required_anchor_missing',
|
||||
'order_layout_prerequisite_missing': 'coordinate_evidence_unavailable',
|
||||
'order_layout_evidence_incomplete': 'coordinate_evidence_unavailable',
|
||||
'order_profile_evidence_insufficient': 'coordinate_evidence_unavailable',
|
||||
'order_profile_no_match': 'profile_not_found',
|
||||
'order_profile_ambiguous': 'profile_ambiguous',
|
||||
'order_profile_layout_drift': 'profile_drift_detected',
|
||||
@@ -1694,6 +1696,9 @@ def _route_reason_for_issue(issue: str) -> str:
|
||||
'order_profile_multiple_matches': 'profile_ambiguous',
|
||||
'order_profile_coordinate_reconstruction_unavailable': 'coordinate_evidence_unavailable',
|
||||
}
|
||||
# 第零层:on-demand 坐标恢复失败码直接收敛为证据不可用,不经过 fallback 误报为 drift。
|
||||
if str(issue).startswith('coordinate_evidence_'):
|
||||
return 'coordinate_evidence_unavailable'
|
||||
return mapping.get(issue, 'profile_drift_detected')
|
||||
|
||||
|
||||
|
||||
@@ -1357,6 +1357,16 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
task,
|
||||
line_projections=list(validation.get('line_projections') or []),
|
||||
)
|
||||
# [STEP] 候选库存源已在建单前冻结;正式 OT 创建完成后立即进入获取库存,
|
||||
# 不再让统一进度停留在“创建正式订单”。最终行级实际库存源仍由后续匹配决定。
|
||||
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
|
||||
|
||||
sync_order_task_processing_state(
|
||||
order_task,
|
||||
stage='inventory_fetching',
|
||||
status='processing',
|
||||
reason_code='inventory_candidates_frozen_after_confirm',
|
||||
)
|
||||
# [STEP] 建单前已校验客户确认:立即绑定标准客户,禁止落入 customer_review。
|
||||
from app.services.shipping_notice.candidate_qualification_service import (
|
||||
resolve_confirmed_bill_to_customer_id,
|
||||
|
||||
@@ -489,6 +489,7 @@ def project_review_case_line_decisions(
|
||||
'inventory_source_code': inv_view.get('inventory_source_code'),
|
||||
'inventory_source': inv_view.get('inventory_source'),
|
||||
'decision_source': inv_view.get('decision_source'),
|
||||
'retryable': bool(inv_view.get('retryable')),
|
||||
'inventory_allowed_actions': list(inv_view.get('inventory_allowed_actions') or []),
|
||||
'line_allowed_actions': list(inv_view.get('line_allowed_actions') or []),
|
||||
'allowed_actions': list(inv_view.get('allowed_actions') or []),
|
||||
|
||||
@@ -19,7 +19,7 @@ backend/app/services/shipping_notice/order_review_projection.py
|
||||
固定投影 customer_resolution / field_conflicts / duplicate / profile_match /
|
||||
field_completeness / completed_checks / current_stage / reservation /
|
||||
line_fulfillment(分域 inventory/line_allowed_actions)/ inventory_issue_fallback /
|
||||
automation;
|
||||
automation / conversation_allowed_actions;
|
||||
profile_match:普通用户四态裁剪,管理员保留完整审计;
|
||||
automation 区分 pre_ot_stp / post_ot_progress 与 owner_type,禁止资格冒充正在推进;
|
||||
正式 OT automation/needs_retry 同源绑定 shipping_notice_run Job;
|
||||
@@ -30,6 +30,8 @@ backend/app/services/shipping_notice/order_review_projection.py
|
||||
为每行/表头投影 field_meta(value_source / locked / override_reason);
|
||||
已确认 Case 附带 confirmed_task_no 与 post_confirm_auto_progress,供刷新后恢复「已建单待推进」;
|
||||
已确认 Case available_actions 含 edit_formal_task,并投影 formal_editable_field_ids;
|
||||
普通路径不再投影 confirm(自动建单走 STP;无 manual_create_fallback);
|
||||
conversation_allowed_actions 与对话处理 GET 同源(retry_auto_progress + eligible_count);
|
||||
WorkflowItem 已关闭时 available_actions 仅保留 view;
|
||||
不返回全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。
|
||||
"""
|
||||
@@ -521,9 +523,8 @@ def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
|
||||
actions.append('create_draft')
|
||||
else:
|
||||
actions.append('edit_draft')
|
||||
if case.current_draft is not None and str((case.current_draft.validation_result_json or {}).get('status') or '') == 'ready':
|
||||
actions.append('confirm')
|
||||
# STP 失败 / manual_fallback:可重试自动建单(与确认兜底互斥由前端按 automation.status 控制)。
|
||||
# 普通路径不投影 confirm;自动建单走 STP retry;本轮不提供 manual_create_fallback。
|
||||
# STP 失败 / manual_fallback:可重试自动建单。
|
||||
automation = None
|
||||
try:
|
||||
automation = _project_case_automation_status(
|
||||
@@ -776,10 +777,8 @@ def serialize_review_case(
|
||||
'recovery_available': False,
|
||||
}
|
||||
|
||||
# task_missing:禁止 confirm;无恢复 API 时明确 view + contact_admin。
|
||||
available_actions = _allowed_actions(case)
|
||||
if formal_ot.get('task_missing') or formal_ot.get('has_formal_ot'):
|
||||
available_actions = [a for a in available_actions if a != 'confirm']
|
||||
# task_missing:无恢复 API 时明确 view + contact_admin;防御性剥离残留 confirm。
|
||||
available_actions = [a for a in _allowed_actions(case) if a != 'confirm']
|
||||
if formal_ot.get('task_missing'):
|
||||
available_actions = ['view', 'contact_admin']
|
||||
|
||||
@@ -807,6 +806,23 @@ def serialize_review_case(
|
||||
automation=automation if isinstance(automation, dict) else None,
|
||||
)
|
||||
|
||||
# 对话级动作与 GET /shipping-processing/conversations 同源;切换 Case 时刷新。
|
||||
conversation_allowed_actions: list[dict[str, Any]] = []
|
||||
try:
|
||||
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
|
||||
project_conversation_allowed_actions,
|
||||
)
|
||||
|
||||
conversation_id = str(getattr(run, 'conversation_id', None) or '').strip()
|
||||
owner_id = int(getattr(run, 'user_id', 0) or 0)
|
||||
if conversation_id and owner_id:
|
||||
conversation_allowed_actions = project_conversation_allowed_actions(
|
||||
user_id=owner_id,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
conversation_allowed_actions = []
|
||||
|
||||
return {
|
||||
'case_no': case.case_no,
|
||||
'run_no': run.run_no,
|
||||
@@ -853,6 +869,7 @@ def serialize_review_case(
|
||||
'order_data_version': order_data_version,
|
||||
'process_gate': process_gate,
|
||||
'inventory_issue_fallback': inventory_issue_fallback,
|
||||
'conversation_allowed_actions': conversation_allowed_actions,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -170,6 +170,8 @@ CONVERSATION_PROCESSING_TASK_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozense
|
||||
'conversation_processing_task_focused',
|
||||
'conversation_processing_task_viewed',
|
||||
'conversation_processing_task_acknowledged',
|
||||
# 对话级批量「重试自动推进」汇总事件(对象级仍写 STP / auto-progress 既有审计)。
|
||||
'conversation_retry_auto_progress',
|
||||
})
|
||||
|
||||
# 输入追加阻断原因码;前端只展示 i18n,禁止本地发明 reason。
|
||||
|
||||
@@ -14,7 +14,8 @@ services/shipping_notice/shipping_processing_projection.py
|
||||
写入 stage_nodes 与 available_actions;stage/status 以 OT 已写入值为准(BE-07,禁止 Notice 覆盖);
|
||||
已挂正式 Notice 时 stage/stage_label_key 与 Case.current_stage 同源(project_stage_for_task);
|
||||
**只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert);已建 Notice 时填 shipping_notice_no;
|
||||
work_items 构建后由 _conversation_processing_from_work_items 重建兼容 conversation_processing。
|
||||
work_items 构建后由 _conversation_processing_from_work_items 重建兼容 conversation_processing;
|
||||
附带 conversation_allowed_actions(与 Case 工作台同源,retry_auto_progress)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -1358,6 +1359,31 @@ def _conversation_processing_from_work_items(
|
||||
}
|
||||
|
||||
|
||||
def _project_conversation_allowed_actions_safe(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
安全投影对话级动作;失败时返回空列表,避免拖垮会话处理读源。
|
||||
"""
|
||||
try:
|
||||
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
|
||||
project_conversation_allowed_actions,
|
||||
)
|
||||
|
||||
return project_conversation_allowed_actions(
|
||||
user_id=int(user_id),
|
||||
conversation_id=str(conversation_id or '').strip(),
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logging.getLogger(__name__).exception(
|
||||
'conversation_allowed_actions projection failed conversation_id=%s',
|
||||
conversation_id,
|
||||
)
|
||||
return []
|
||||
|
||||
|
||||
def project_conversation_processing_items(
|
||||
*,
|
||||
user_id: int,
|
||||
@@ -1523,6 +1549,10 @@ def project_conversation_processing_items(
|
||||
'conversation_id': normalized,
|
||||
'work_items': work_items,
|
||||
'conversation_processing': rebuilt,
|
||||
'conversation_allowed_actions': _project_conversation_allowed_actions_safe(
|
||||
user_id=int(user_id),
|
||||
conversation_id=normalized,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,715 @@
|
||||
"""
|
||||
services/shipping_notice/task_retry_decision_service.py
|
||||
|
||||
用途:正式 OT「重试」统一决策与执行入口(任务级 / 行级 / 对话级 / auto-progress 兼容)。
|
||||
依赖:inventory_source_gate、inventory_workflow、fulfillment_workflow.match_inventory、
|
||||
progress_workflow.auto_progress、fulfillment_audit、ShippingNotice /
|
||||
ShippingNoticeLineInventoryMatch。
|
||||
逻辑:用户只表达重试意图;本服务按最新事实选择 resolve_source / fetch_inventory /
|
||||
rematch / needs_human / noop / failed,或非库存阶段委托 auto_progress;
|
||||
禁止对话级与任务级分叉实现;幂等键与审计字段一并返回。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Literal
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
Scope = Literal['task', 'line']
|
||||
|
||||
ACTION_RESOLVE_SOURCE = 'resolve_source'
|
||||
ACTION_FETCH_INVENTORY = 'fetch_inventory'
|
||||
ACTION_REMATCH = 'rematch'
|
||||
ACTION_NEEDS_HUMAN = 'needs_human'
|
||||
ACTION_NOOP = 'noop'
|
||||
ACTION_FAILED = 'failed'
|
||||
ACTION_AUTO_PROGRESS = 'auto_progress'
|
||||
|
||||
STATUS_RUNNING = 'running'
|
||||
STATUS_NEEDS_HUMAN = 'needs_human'
|
||||
STATUS_COMPLETED = 'completed'
|
||||
STATUS_FAILED = 'failed'
|
||||
|
||||
PH_RPA_PENDING = 'rpa_pending'
|
||||
PH_UPLOAD_PENDING = 'upload_rpa_pending'
|
||||
PH_UPLOAD_FAILED = 'upload_rpa_failed'
|
||||
|
||||
|
||||
def retry_task_with_decision(
|
||||
*,
|
||||
task_no: str,
|
||||
user_id: int,
|
||||
scope: Scope = 'task',
|
||||
line_key: str | None = None,
|
||||
reason: str | None = None,
|
||||
trigger: str = 'user_retry',
|
||||
continue_auto_progress: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
统一重试决策并执行。
|
||||
|
||||
核心逻辑:加锁读取任务事实 → 决策树 → 执行既有库存/推进处理器 → 写审计 → 返回统一结果。
|
||||
|
||||
Args:
|
||||
task_no: 正式任务号。
|
||||
user_id: 操作人。
|
||||
scope: task=整单;line=单行。
|
||||
line_key: scope=line 时必填。
|
||||
reason: 用户/系统原因。
|
||||
trigger: 调用方标识(user_retry / conversation_retry / system_auto_progress)。
|
||||
continue_auto_progress: True 时库存节点通过后继续 auto_progress(兼容调度入口)。
|
||||
|
||||
Returns:
|
||||
含 action/status/retryable/decision_version/snapshot_id/job_id/idempotency_key 等。
|
||||
|
||||
Raises:
|
||||
ValidationError / NotFoundError / AppError。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.query_service import get_task_for_user
|
||||
|
||||
normalized_task = str(task_no or '').strip()
|
||||
if not normalized_task:
|
||||
raise ValidationError('task_no is required')
|
||||
scope_norm: Scope = 'line' if str(scope or '').strip().lower() == 'line' else 'task'
|
||||
line = str(line_key or '').strip() or None
|
||||
if scope_norm == 'line' and not line:
|
||||
raise ValidationError('line_key is required for line scope')
|
||||
|
||||
task = get_task_for_user(normalized_task, int(user_id))
|
||||
if task is None:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
decision_version = int(getattr(task, 'order_data_version', None) or 1)
|
||||
decided = _decide(task, scope=scope_norm, line_key=line)
|
||||
action = str(decided.get('action') or ACTION_NOOP)
|
||||
idempotency_key = _build_idempotency_key(
|
||||
task=task,
|
||||
action=action,
|
||||
decision_version=decision_version,
|
||||
line_key=line,
|
||||
)
|
||||
|
||||
# [STEP] 幂等:同键活跃运行中直接回放。
|
||||
if _is_inventory_rpa_active(task) and action in {ACTION_FETCH_INVENTORY, ACTION_REMATCH, ACTION_AUTO_PROGRESS}:
|
||||
result = _result_payload(
|
||||
task=task,
|
||||
action=ACTION_NOOP,
|
||||
status=STATUS_RUNNING,
|
||||
retryable=False,
|
||||
reason_code='already_running',
|
||||
decision_version=decision_version,
|
||||
idempotency_key=idempotency_key,
|
||||
idempotent_replay=True,
|
||||
message='已有库存处理在运行',
|
||||
)
|
||||
_audit_decision(
|
||||
task=task,
|
||||
user_id=int(user_id),
|
||||
scope=scope_norm,
|
||||
line_key=line,
|
||||
trigger=trigger,
|
||||
reason=reason,
|
||||
result=result,
|
||||
)
|
||||
return result
|
||||
|
||||
executed = _execute(
|
||||
task=task,
|
||||
user_id=int(user_id),
|
||||
decided=decided,
|
||||
continue_auto_progress=bool(continue_auto_progress),
|
||||
decision_version=decision_version,
|
||||
idempotency_key=idempotency_key,
|
||||
line_key=line,
|
||||
)
|
||||
_audit_decision(
|
||||
task=task,
|
||||
user_id=int(user_id),
|
||||
scope=scope_norm,
|
||||
line_key=line,
|
||||
trigger=trigger,
|
||||
reason=reason,
|
||||
result=executed,
|
||||
)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('task retry decision commit failed task_no=%s', normalized_task)
|
||||
raise
|
||||
return executed
|
||||
|
||||
|
||||
def decide_retry_action_only(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
scope: Scope = 'task',
|
||||
line_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
只读决策(供投影 / 测试);不执行副作用。
|
||||
|
||||
Returns:
|
||||
``{action, reason_code, retryable, ...}``。
|
||||
"""
|
||||
return _decide(task, scope=scope, line_key=line_key)
|
||||
|
||||
|
||||
def _decide(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
scope: Scope,
|
||||
line_key: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""按冻结优先级计算 RetryDecision。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
|
||||
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
|
||||
pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower()
|
||||
|
||||
if process_status in {'completed', 'fulfilled', 'closed', 'cancelled'}:
|
||||
return {
|
||||
'action': ACTION_NOOP,
|
||||
'status': STATUS_COMPLETED,
|
||||
'retryable': False,
|
||||
'reason_code': 'already_completed',
|
||||
}
|
||||
if pending in {PH_RPA_PENDING, PH_UPLOAD_PENDING} or _is_inventory_rpa_active(task):
|
||||
return {
|
||||
'action': ACTION_NOOP,
|
||||
'status': STATUS_RUNNING,
|
||||
'retryable': False,
|
||||
'reason_code': 'already_running',
|
||||
}
|
||||
if pending == PH_UPLOAD_FAILED:
|
||||
return {
|
||||
'action': ACTION_NEEDS_HUMAN,
|
||||
'status': STATUS_NEEDS_HUMAN,
|
||||
'retryable': False,
|
||||
'reason_code': 'upload_rpa_failed',
|
||||
}
|
||||
|
||||
if scope == 'line' and line_key:
|
||||
return _decide_for_line(task, line_key=line_key)
|
||||
|
||||
# [STEP] 库存源不稳定:先解析源,不得直接写 RPA。
|
||||
if not is_inventory_source_stable(task):
|
||||
status = str(getattr(task, 'inventory_source_status', None) or '').strip().lower()
|
||||
if status in {'ambiguous', 'candidates_frozen', 'conflicted', 'unresolved', ''}:
|
||||
# 多候选 / 客户未指定:不得自动选源进 RPA。
|
||||
codes = _frozen_or_candidate_codes(task)
|
||||
if status == 'conflicted' or (len(codes) > 1 and status in {'ambiguous', 'candidates_frozen'}):
|
||||
# 客户已确认源(user_confirmed)才允许继续;多候选未确认必须人工。
|
||||
customer_specified = status == 'user_confirmed' or bool(
|
||||
str(getattr(task, 'inventory_source_confirmed_by', None) or '').strip()
|
||||
)
|
||||
if not customer_specified and len(codes) > 1:
|
||||
return {
|
||||
'action': ACTION_NEEDS_HUMAN,
|
||||
'status': STATUS_NEEDS_HUMAN,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_source_candidates_need_human',
|
||||
}
|
||||
return {
|
||||
'action': ACTION_RESOLVE_SOURCE,
|
||||
'status': STATUS_RUNNING,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_source_unstable',
|
||||
}
|
||||
|
||||
has_lines = bool(getattr(task, 'inventory_lines_json', None))
|
||||
snapshot_id = getattr(task, 'inventory_snapshot_id', None)
|
||||
if not has_lines and not snapshot_id:
|
||||
return {
|
||||
'action': ACTION_FETCH_INVENTORY,
|
||||
'status': STATUS_RUNNING,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_snapshot_missing',
|
||||
}
|
||||
|
||||
# 有快照/明细但匹配未完成或失败 → rematch;短缺 → needs_human。
|
||||
match_hint = _task_match_hint(task)
|
||||
if match_hint.get('needs_human'):
|
||||
return {
|
||||
'action': ACTION_NEEDS_HUMAN,
|
||||
'status': STATUS_NEEDS_HUMAN,
|
||||
'retryable': False,
|
||||
'reason_code': match_hint.get('reason_code') or 'inventory_shortage',
|
||||
}
|
||||
if match_hint.get('needs_rematch'):
|
||||
return {
|
||||
'action': ACTION_REMATCH,
|
||||
'status': STATUS_RUNNING,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_match_incomplete',
|
||||
}
|
||||
|
||||
# 非库存阻断:委托现有 auto_progress 推进后续阶段。
|
||||
return {
|
||||
'action': ACTION_AUTO_PROGRESS,
|
||||
'status': STATUS_RUNNING,
|
||||
'retryable': False,
|
||||
'reason_code': None,
|
||||
}
|
||||
|
||||
|
||||
def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]:
|
||||
"""行级决策:只处理该行库存事实。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
project_line_inventory_view,
|
||||
project_line_retryable,
|
||||
)
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
return {
|
||||
'action': ACTION_RESOLVE_SOURCE,
|
||||
'status': STATUS_RUNNING,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_source_unstable',
|
||||
}
|
||||
|
||||
row = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_key=str(line_key))
|
||||
.order_by(ShippingNoticeLineInventoryMatch.id.desc())
|
||||
.first()
|
||||
)
|
||||
fact = {
|
||||
'match_result': getattr(row, 'match_result', None) if row else None,
|
||||
'inventory_status': getattr(row, 'inventory_status', None) if row else 'preparing',
|
||||
'available_qty': getattr(row, 'available_qty', None) if row else None,
|
||||
'required_qty': getattr(row, 'required_qty', None) if row else None,
|
||||
'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None) if row else None,
|
||||
'inventory_source_code': getattr(row, 'inventory_source_code', None) if row else None,
|
||||
'matched_at': getattr(row, 'matched_at', None) if row else None,
|
||||
'matching_rule_version': getattr(row, 'matching_rule_version', None) if row else None,
|
||||
'detail_json': dict(getattr(row, 'detail_json', None) or {}) if row else {},
|
||||
}
|
||||
view = project_line_inventory_view(
|
||||
has_formal_ot=True,
|
||||
fact=fact,
|
||||
required_qty=fact.get('required_qty'),
|
||||
stored_line_status=None,
|
||||
decision_source=None,
|
||||
can_fulfill_complete_line=False,
|
||||
inventory_rpa_running=_is_inventory_rpa_active(task),
|
||||
)
|
||||
user_status = str(view.get('user_line_status') or '')
|
||||
if user_status in {'shortage', 'source_conflict'}:
|
||||
return {
|
||||
'action': ACTION_NEEDS_HUMAN,
|
||||
'status': STATUS_NEEDS_HUMAN,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_shortage' if user_status == 'shortage' else 'inventory_source_conflict',
|
||||
}
|
||||
if not project_line_retryable(
|
||||
inventory_allowed_actions=list(view.get('inventory_allowed_actions') or []),
|
||||
user_line_status=user_status,
|
||||
inventory_rpa_running=_is_inventory_rpa_active(task),
|
||||
):
|
||||
return {
|
||||
'action': ACTION_NOOP,
|
||||
'status': STATUS_COMPLETED,
|
||||
'retryable': False,
|
||||
'reason_code': 'already_completed',
|
||||
}
|
||||
inv_actions = set(view.get('inventory_allowed_actions') or [])
|
||||
if 'retry_inventory_matching' in inv_actions and view.get('inventory_snapshot_id'):
|
||||
return {
|
||||
'action': ACTION_REMATCH,
|
||||
'status': STATUS_RUNNING,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_match_incomplete',
|
||||
'line_key': line_key,
|
||||
}
|
||||
return {
|
||||
'action': ACTION_FETCH_INVENTORY,
|
||||
'status': STATUS_RUNNING,
|
||||
'retryable': False,
|
||||
'reason_code': 'inventory_snapshot_missing',
|
||||
'line_key': line_key,
|
||||
}
|
||||
|
||||
|
||||
def _execute(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
user_id: int,
|
||||
decided: dict[str, Any],
|
||||
continue_auto_progress: bool,
|
||||
decision_version: int,
|
||||
idempotency_key: str,
|
||||
line_key: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""执行决策动作并映射统一响应。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
adjudicate_and_apply_inventory_source,
|
||||
ensure_inventory_source_review_state,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
action = str(decided.get('action') or ACTION_NOOP)
|
||||
base_kwargs = {
|
||||
'task': task,
|
||||
'decision_version': decision_version,
|
||||
'idempotency_key': idempotency_key,
|
||||
'snapshot_id': getattr(task, 'inventory_snapshot_id', None),
|
||||
'source_code': str(getattr(task, 'inventory_source_code', None) or '') or None,
|
||||
}
|
||||
|
||||
if action == ACTION_NOOP:
|
||||
return _result_payload(
|
||||
action=ACTION_NOOP,
|
||||
status=str(decided.get('status') or STATUS_COMPLETED),
|
||||
retryable=False,
|
||||
reason_code=str(decided.get('reason_code') or 'already_completed'),
|
||||
message='无需重试',
|
||||
**base_kwargs,
|
||||
)
|
||||
|
||||
if action == ACTION_NEEDS_HUMAN:
|
||||
return _result_payload(
|
||||
action=ACTION_NEEDS_HUMAN,
|
||||
status=STATUS_NEEDS_HUMAN,
|
||||
retryable=False,
|
||||
reason_code=str(decided.get('reason_code') or 'needs_human'),
|
||||
message='当前需要人工处理',
|
||||
**base_kwargs,
|
||||
)
|
||||
|
||||
try:
|
||||
if action == ACTION_RESOLVE_SOURCE:
|
||||
adjudicate_and_apply_inventory_source(task)
|
||||
ensure_inventory_source_review_state(task)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
if not is_inventory_source_stable(task):
|
||||
return _result_payload(
|
||||
action=ACTION_NEEDS_HUMAN,
|
||||
status=STATUS_NEEDS_HUMAN,
|
||||
retryable=False,
|
||||
reason_code='inventory_source_candidates_need_human',
|
||||
message='库存源未稳定,需要人工确认',
|
||||
**base_kwargs,
|
||||
)
|
||||
# 源已稳定:继续获取库存。
|
||||
action = ACTION_FETCH_INVENTORY
|
||||
|
||||
if action == ACTION_FETCH_INVENTORY:
|
||||
# 先尝试复用快照;仍无则显式 retry_rpa。
|
||||
reused = ensure_inventory({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'auto',
|
||||
'operator_id': int(user_id),
|
||||
'_trusted_user_id': int(user_id),
|
||||
'event_source': 'workspace_api',
|
||||
})
|
||||
if str((reused or {}).get('status') or '') in {'ok', 'completed'}:
|
||||
if continue_auto_progress:
|
||||
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
|
||||
return _map_tool_result(
|
||||
reused,
|
||||
action=ACTION_FETCH_INVENTORY,
|
||||
base_kwargs=base_kwargs,
|
||||
message='已复用库存快照',
|
||||
)
|
||||
fetched = ensure_inventory({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'retry_rpa',
|
||||
'operator_id': int(user_id),
|
||||
'_trusted_user_id': int(user_id),
|
||||
'event_source': 'workspace_api',
|
||||
})
|
||||
return _map_tool_result(
|
||||
fetched,
|
||||
action=ACTION_FETCH_INVENTORY,
|
||||
base_kwargs={
|
||||
**base_kwargs,
|
||||
'snapshot_id': getattr(task, 'inventory_snapshot_id', None),
|
||||
},
|
||||
message='已提交库存获取',
|
||||
)
|
||||
|
||||
if action == ACTION_REMATCH:
|
||||
matched = shipping_tools.match_inventory({
|
||||
'task_id': task.task_no,
|
||||
'operator_id': int(user_id),
|
||||
'_trusted_user_id': int(user_id),
|
||||
'event_source': 'workspace_api',
|
||||
'line_key': line_key,
|
||||
})
|
||||
mapped = _map_tool_result(
|
||||
matched,
|
||||
action=ACTION_REMATCH,
|
||||
base_kwargs=base_kwargs,
|
||||
message='已提交库存匹配',
|
||||
)
|
||||
if continue_auto_progress and mapped.get('status') == STATUS_COMPLETED:
|
||||
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
|
||||
return mapped
|
||||
|
||||
# ACTION_AUTO_PROGRESS 或 continue
|
||||
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
|
||||
except AppError as err:
|
||||
return _result_payload(
|
||||
action=ACTION_FAILED,
|
||||
status=STATUS_FAILED,
|
||||
retryable=True,
|
||||
reason_code=str(getattr(err, 'code', None) or 'SHIPPING.RETRY_FAILED'),
|
||||
message=str(getattr(err, 'message', None) or err),
|
||||
**base_kwargs,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_LOGGER.exception('task retry execute failed task_no=%s action=%s', task.task_no, action)
|
||||
return _result_payload(
|
||||
action=ACTION_FAILED,
|
||||
status=STATUS_FAILED,
|
||||
retryable=True,
|
||||
reason_code='SHIPPING.RETRY_FAILED',
|
||||
message=str(exc)[:500],
|
||||
**base_kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _run_auto_progress(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
user_id: int,
|
||||
base_kwargs: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""委托现有 auto_progress 推进非库存/后续阶段。"""
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
result = shipping_tools.auto_progress({
|
||||
'task_id': task.task_no,
|
||||
'source': 'workspace_api',
|
||||
'operator_id': int(user_id),
|
||||
'actor_id': int(user_id),
|
||||
'_trusted_user_id': int(user_id),
|
||||
'trigger': 'task_retry_decision',
|
||||
})
|
||||
return _map_tool_result(
|
||||
result,
|
||||
action=ACTION_AUTO_PROGRESS,
|
||||
base_kwargs=base_kwargs,
|
||||
message='已提交自动推进',
|
||||
)
|
||||
|
||||
|
||||
def _map_tool_result(
|
||||
tool_result: dict[str, Any] | None,
|
||||
*,
|
||||
action: str,
|
||||
base_kwargs: dict[str, Any],
|
||||
message: str,
|
||||
) -> dict[str, Any]:
|
||||
"""将既有 tool 响应映射为统一 Retry 结果。"""
|
||||
status_raw = str((tool_result or {}).get('status') or '').strip().lower()
|
||||
if status_raw in {'needs_human', 'waiting_manual', 'wait_manual_upload'}:
|
||||
return _result_payload(
|
||||
action=ACTION_NEEDS_HUMAN,
|
||||
status=STATUS_NEEDS_HUMAN,
|
||||
retryable=False,
|
||||
reason_code=str((tool_result or {}).get('error_code') or 'needs_human'),
|
||||
message=str((tool_result or {}).get('message') or '当前需要人工处理'),
|
||||
job_id=(tool_result or {}).get('job_id'),
|
||||
**base_kwargs,
|
||||
)
|
||||
if status_raw in {'failed', 'enqueue_failed', 'sync_execution_failed'}:
|
||||
return _result_payload(
|
||||
action=ACTION_FAILED,
|
||||
status=STATUS_FAILED,
|
||||
retryable=True,
|
||||
reason_code=str((tool_result or {}).get('error_code') or status_raw),
|
||||
message=str((tool_result or {}).get('message') or '自动处理失败'),
|
||||
job_id=(tool_result or {}).get('job_id'),
|
||||
**base_kwargs,
|
||||
)
|
||||
if status_raw in {'ok', 'completed', 'succeeded'}:
|
||||
return _result_payload(
|
||||
action=action,
|
||||
status=STATUS_COMPLETED,
|
||||
retryable=False,
|
||||
reason_code=None,
|
||||
message=str((tool_result or {}).get('message') or message),
|
||||
job_id=(tool_result or {}).get('job_id'),
|
||||
**base_kwargs,
|
||||
)
|
||||
# running / queued / processing
|
||||
return _result_payload(
|
||||
action=action,
|
||||
status=STATUS_RUNNING,
|
||||
retryable=False,
|
||||
reason_code=None,
|
||||
message=str((tool_result or {}).get('message') or message),
|
||||
job_id=(tool_result or {}).get('job_id'),
|
||||
**base_kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _result_payload(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
action: str,
|
||||
status: str,
|
||||
retryable: bool,
|
||||
reason_code: str | None,
|
||||
decision_version: int,
|
||||
idempotency_key: str,
|
||||
message: str,
|
||||
snapshot_id: Any = None,
|
||||
source_code: str | None = None,
|
||||
job_id: Any = None,
|
||||
idempotent_replay: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""组装统一响应。"""
|
||||
return {
|
||||
'task_no': task.task_no,
|
||||
'idempotent_replay': bool(idempotent_replay),
|
||||
'action': action,
|
||||
'stage': str(getattr(task, 'process_status', None) or '') or None,
|
||||
'status': status,
|
||||
'retryable': bool(retryable),
|
||||
'job_id': job_id,
|
||||
'reason_code': reason_code,
|
||||
'message': message,
|
||||
'decision_version': int(decision_version),
|
||||
'snapshot_id': int(snapshot_id) if snapshot_id not in (None, '') else None,
|
||||
'source_code': source_code,
|
||||
'idempotency_key': idempotency_key,
|
||||
}
|
||||
|
||||
|
||||
def _build_idempotency_key(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
action: str,
|
||||
decision_version: int,
|
||||
line_key: str | None,
|
||||
) -> str:
|
||||
"""按冻结约定生成业务幂等键。"""
|
||||
task_no = str(task.task_no)
|
||||
source = str(getattr(task, 'inventory_source_code', None) or 'NA').strip().upper() or 'NA'
|
||||
snapshot = getattr(task, 'inventory_snapshot_id', None) or 'none'
|
||||
if action == ACTION_FETCH_INVENTORY:
|
||||
key = f'inventory-fetch:{task_no}:{source}:v{decision_version}'
|
||||
elif action == ACTION_REMATCH:
|
||||
key = f'inventory-match:{task_no}:{snapshot}:v{decision_version}'
|
||||
elif action == ACTION_RESOLVE_SOURCE:
|
||||
key = f'inventory-source:{task_no}:v{decision_version}'
|
||||
else:
|
||||
key = f'auto-progress:{task_no}:v{decision_version}'
|
||||
if line_key:
|
||||
key = f'{key}:line:{line_key}'
|
||||
return key
|
||||
|
||||
|
||||
def _is_inventory_rpa_active(task: ShippingNotice) -> bool:
|
||||
"""库存 RPA 是否仍在等待。"""
|
||||
pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower()
|
||||
process = str(getattr(task, 'process_status', None) or '').strip().lower()
|
||||
if pending == PH_RPA_PENDING:
|
||||
return True
|
||||
if process == 'waiting_inventory' and pending == PH_RPA_PENDING:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _frozen_or_candidate_codes(task: ShippingNotice) -> list[str]:
|
||||
"""读取冻结/候选库存源编码。"""
|
||||
try:
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
return list(task_frozen_inventory_source_codes(task) or [])
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
|
||||
|
||||
def _task_match_hint(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""根据行匹配事实判断是否需 rematch 或人工。"""
|
||||
rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.order_by(ShippingNoticeLineInventoryMatch.id.desc())
|
||||
.limit(200)
|
||||
.all()
|
||||
)
|
||||
if not rows:
|
||||
# 有库存明细但无匹配行 → 需要匹配。
|
||||
if getattr(task, 'inventory_lines_json', None) or getattr(task, 'inventory_snapshot_id', None):
|
||||
return {'needs_rematch': True}
|
||||
return {}
|
||||
needs_rematch = False
|
||||
for row in rows:
|
||||
result = str(getattr(row, 'match_result', None) or '').strip().lower()
|
||||
status = str(getattr(row, 'inventory_status', None) or '').strip().lower()
|
||||
if result in {'not_found'} or status in {'source_conflict'}:
|
||||
# 短缺/冲突:人工。
|
||||
return {'needs_human': True, 'reason_code': 'inventory_shortage' if result == 'not_found' else 'inventory_source_conflict'}
|
||||
if result in {'mapping_failed', 'result_missing', 'preparing', ''} or status in {'mapping_failed', 'preparing'}:
|
||||
needs_rematch = True
|
||||
if needs_rematch:
|
||||
return {'needs_rematch': True}
|
||||
return {}
|
||||
|
||||
|
||||
def _audit_decision(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
user_id: int,
|
||||
scope: Scope,
|
||||
line_key: str | None,
|
||||
trigger: str,
|
||||
reason: str | None,
|
||||
result: dict[str, Any],
|
||||
) -> None:
|
||||
"""写对象级重试决策审计。"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
action = str(result.get('action') or ACTION_NOOP)
|
||||
event_type = {
|
||||
ACTION_RESOLVE_SOURCE: 'inventory_source_resolved',
|
||||
ACTION_FETCH_INVENTORY: 'inventory_rpa_triggered',
|
||||
ACTION_REMATCH: 'inventory_matching_started',
|
||||
ACTION_AUTO_PROGRESS: 'auto_progress_retried',
|
||||
ACTION_NEEDS_HUMAN: 'auto_progress_retried',
|
||||
ACTION_NOOP: 'auto_progress_retried',
|
||||
ACTION_FAILED: 'auto_progress_retried',
|
||||
}.get(action, 'auto_progress_retried')
|
||||
record_fulfillment_audit(
|
||||
event_type=event_type,
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
action='retry',
|
||||
actor_id=int(user_id),
|
||||
task_no=str(task.task_no),
|
||||
conversation_id=str(getattr(task, 'conversation_id', None) or '') or None,
|
||||
owner_user_id=int(getattr(task, 'user_id', 0) or user_id),
|
||||
reason_code=str(result.get('reason_code') or '') or None,
|
||||
reason=str(reason or trigger)[:200],
|
||||
result='success' if result.get('status') != STATUS_FAILED else 'failed',
|
||||
error_code=str(result.get('reason_code') or '') if result.get('status') == STATUS_FAILED else None,
|
||||
metadata={
|
||||
'scope': scope,
|
||||
'line_key': line_key,
|
||||
'trigger': trigger,
|
||||
'previous_stage': str(getattr(task, 'process_status', None) or '') or None,
|
||||
'next_stage': result.get('stage'),
|
||||
'action': action,
|
||||
'decision_version': result.get('decision_version'),
|
||||
'snapshot_id': result.get('snapshot_id'),
|
||||
'job_id': result.get('job_id'),
|
||||
'idempotency_key': result.get('idempotency_key'),
|
||||
'status': result.get('status'),
|
||||
},
|
||||
source='api',
|
||||
strict=False,
|
||||
)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
tests/test_conversation_retry_auto_progress.py
|
||||
|
||||
用途:锁定对话级重试自动推进的 eligible 判定、跳过原因与汇总结构。
|
||||
依赖:conversation_retry_auto_progress_service。
|
||||
逻辑:纯单元测跳过映射与 summary;不依赖完整 DB 工厂。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
|
||||
ACTION_RETRY_AUTO_PROGRESS,
|
||||
_skip_reason_from_automation,
|
||||
_summarize_items,
|
||||
project_conversation_allowed_actions,
|
||||
)
|
||||
|
||||
|
||||
def test_skip_reason_maps_queued_and_not_retryable():
|
||||
"""queued → already_running;retryable=false → not_retryable。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'queued', 'retryable': False},
|
||||
task_missing=False,
|
||||
) == 'already_running'
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'waiting_to_start', 'retryable': False},
|
||||
task_missing=False,
|
||||
) == 'not_retryable'
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'failed', 'retryable': True},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_manual_fallback_human_owner_still_retryable():
|
||||
"""manual_fallback 虽 owner=human,但 retryable 时不得跳过。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'manual_fallback', 'retryable': True, 'owner_type': 'human'},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_task_missing_always_skipped():
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'failed', 'retryable': True},
|
||||
task_missing=True,
|
||||
) == 'task_missing'
|
||||
|
||||
|
||||
def test_summarize_items_counts_outcomes():
|
||||
summary = _summarize_items([
|
||||
{'outcome': 'queued'},
|
||||
{'outcome': 'queued'},
|
||||
{'outcome': 'skipped', 'reason_code': 'already_running'},
|
||||
{'outcome': 'failed'},
|
||||
])
|
||||
assert summary == {'total': 4, 'retried': 2, 'skipped': 1, 'failed': 1}
|
||||
|
||||
|
||||
def test_project_conversation_allowed_actions_empty_without_conversation():
|
||||
"""无 conversation_id 时不返回禁用空按钮。"""
|
||||
assert project_conversation_allowed_actions(user_id=1, conversation_id='') == []
|
||||
assert ACTION_RETRY_AUTO_PROGRESS == 'retry_auto_progress'
|
||||
@@ -12,7 +12,6 @@ from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
ACTION_CLOSE,
|
||||
ACTION_RETRY_MATCHING,
|
||||
ACTION_RETRY_PREPARATION,
|
||||
ACTION_VIEW_FULFILLMENT,
|
||||
normalize_match_quantities,
|
||||
project_line_inventory_view,
|
||||
project_user_line_status,
|
||||
@@ -120,8 +119,8 @@ def test_shortage_actions_preparation_and_close_only():
|
||||
assert line == [ACTION_CLOSE]
|
||||
|
||||
|
||||
def test_wave_created_only_view_detail():
|
||||
"""已入波次仅查看履约详情。"""
|
||||
def test_wave_created_hides_line_actions():
|
||||
"""已入波次不再下发 view_fulfillment_detail。"""
|
||||
line = resolve_line_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
stored_line_status='task_created',
|
||||
@@ -136,7 +135,7 @@ def test_wave_created_only_view_detail():
|
||||
user_line_status='wave_created',
|
||||
)
|
||||
assert inv == []
|
||||
assert line == [ACTION_VIEW_FULFILLMENT]
|
||||
assert line == []
|
||||
|
||||
|
||||
def test_result_missing_projects_file_missing_and_retry_prep():
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
tests/test_task_retry_decision_service.py
|
||||
|
||||
用途:锁定统一重试决策树的只读分支(noop / fetch)与行级 retryable。
|
||||
依赖:task_retry_decision_service、line_inventory_match_projection。
|
||||
逻辑:不启全量 Flask;验证决策优先级。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.line_inventory_match_projection import project_line_retryable
|
||||
from app.services.shipping_notice.task_retry_decision_service import (
|
||||
ACTION_FETCH_INVENTORY,
|
||||
ACTION_NOOP,
|
||||
decide_retry_action_only,
|
||||
)
|
||||
|
||||
|
||||
def _task(**kwargs):
|
||||
defaults = {
|
||||
'task_no': 'OT-1',
|
||||
'id': 1,
|
||||
'process_status': 'parsed',
|
||||
'pending_human_reason': None,
|
||||
'inventory_lines_json': None,
|
||||
'inventory_snapshot_id': None,
|
||||
'inventory_source_status': 'resolved',
|
||||
'inventory_source_code': 'DSB_SLC',
|
||||
'inventory_source_confirmed_by': None,
|
||||
'order_data_version': 3,
|
||||
}
|
||||
defaults.update(kwargs)
|
||||
return SimpleNamespace(**defaults)
|
||||
|
||||
|
||||
def test_project_line_retryable_hides_shortage_and_running():
|
||||
assert project_line_retryable(
|
||||
inventory_allowed_actions=['retry_inventory_preparation'],
|
||||
user_line_status='shortage',
|
||||
) is False
|
||||
assert project_line_retryable(
|
||||
inventory_allowed_actions=['retry_inventory_preparation'],
|
||||
user_line_status='inventory_file_missing',
|
||||
inventory_rpa_running=True,
|
||||
) is False
|
||||
assert project_line_retryable(
|
||||
inventory_allowed_actions=['retry_inventory_preparation'],
|
||||
user_line_status='inventory_file_missing',
|
||||
) is True
|
||||
|
||||
|
||||
def test_decide_completed_is_noop():
|
||||
task = _task(process_status='completed')
|
||||
decided = decide_retry_action_only(task, scope='task')
|
||||
assert decided['action'] == ACTION_NOOP
|
||||
assert decided['reason_code'] == 'already_completed'
|
||||
|
||||
|
||||
def test_decide_missing_snapshot_fetch(monkeypatch):
|
||||
task = _task(process_status='parsed', inventory_snapshot_id=None, inventory_lines_json=None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.is_inventory_source_stable',
|
||||
lambda _t: True,
|
||||
)
|
||||
decided = decide_retry_action_only(task, scope='task')
|
||||
assert decided['action'] == ACTION_FETCH_INVENTORY
|
||||
|
||||
|
||||
def test_decide_rpa_pending_already_running():
|
||||
task = _task(pending_human_reason='rpa_pending', process_status='waiting_inventory')
|
||||
decided = decide_retry_action_only(task, scope='task')
|
||||
assert decided['action'] == ACTION_NOOP
|
||||
assert decided['reason_code'] == 'already_running'
|
||||
@@ -0,0 +1,961 @@
|
||||
# 在途仓自动调拨 AI Agent 一期最小化实现规格说明书
|
||||
|
||||
> 状态:需求冻结,可进入内部评审
|
||||
> 适用项目:HXOPS Enterprise AI Gateway
|
||||
> 目标用户:拥有“在途仓调拨 Agent”权限的仓库管理人员
|
||||
> 技术基线:Vue 3 + TypeScript + TailwindCSS;Flask + SQLAlchemy 2.0 + PostgreSQL;Gevent SSE;现有 Job/Worker、RPA、企业微信和 MinIO
|
||||
> 兼容原则:不考虑历史版本兼容,不建设独立集成中心,不允许 Dify 直接写 ERP
|
||||
|
||||
---
|
||||
|
||||
## 1. 文档目标
|
||||
|
||||
本规格定义在途仓自动调拨一期最小化实现的业务规则、用户体验、前后端契约、后台任务、数据模型、审计、通知、风险、文件级改造计划和量化验收标准。
|
||||
|
||||
一期的核心结果是:仓库管理人员可以在现有 HXOPS 对话页中查询可调拨数据,看到收料文件准备和 ERP 查询进度,确认后由后台 Worker 安全执行 ERP 原子调拨;每日排程可自动处理新增和历史可恢复异常,所有操作均可审计追溯。
|
||||
|
||||
---
|
||||
|
||||
## 2. 设计依据
|
||||
|
||||
### 2.1 当前项目复用原则
|
||||
|
||||
| 现有能力 | 一期使用方式 |
|
||||
| --- | --- |
|
||||
| `ChatView` / `ChatSidebar` / `ChatMessageList` / `ChatInputBar` | 直接复用,不新增独立业务工作台 |
|
||||
| Agent Registry、`agent_code`、`capabilities`、`handler_config` | 注册调拨 Agent 及其进度契约 |
|
||||
| Chat Action Registry | 承载预检、确认、进度、重试、关闭等结构化操作 |
|
||||
| SSE 对话链路 | 输出即时阶段说明;长任务由 Run 投影恢复 |
|
||||
| `ChatLog` / `ChatToolRun` / `ScheduleRun` | 关联会话、操作轮次和后台 Run |
|
||||
| 通用 Job Queue、shipping worker | 扩展调拨 Job 类型;使用独立进程或独立队列消费 |
|
||||
| 库存来源管理、RPA Profile、Callback、ready 快照 | 增加 `receipt` 收料用途和相关配置 |
|
||||
| 企业微信文本卡片和文件消息 | 发送每次自动调拨排程的汇总通知和异常 Excel |
|
||||
| Shipping 审计事件、快照、Diff、Hash | 抽取为调拨领域审计模式,不复制低级实现 |
|
||||
| MinIO | 归档大型审计快照、脱敏报文和 Excel |
|
||||
|
||||
### 2.2 行业实践参考
|
||||
|
||||
参考高社区认可项目的实现思想,不引入其运行时依赖:
|
||||
|
||||
- Dify:Agent 负责意图理解,关键业务写操作交给受控 Tool。
|
||||
- Open WebUI、LibreChat:结构化消息卡与普通对话共存,会话中恢复后台任务状态。
|
||||
- Temporal、LangGraph:长任务状态持久化、可恢复执行、人工介入和幂等处理。
|
||||
- n8n:节点级执行状态、凭据隔离、执行历史和失败定位。
|
||||
|
||||
一期贯彻以下原则:
|
||||
|
||||
1. Dify 不持有 ERP 写权限。
|
||||
2. 对话请求不同步等待 RPA 或 ERP 长流程。
|
||||
3. 后台 Run 和 Invoice Attempt 是业务真相源。
|
||||
4. 所有外部写入均有幂等键、状态门禁和审计上下文。
|
||||
5. 自动恢复是“重新预检后的受控补偿”,不是重放旧请求。
|
||||
|
||||
---
|
||||
|
||||
## 3. 范围
|
||||
|
||||
### 3.1 一期实现
|
||||
|
||||
- 对话查询今天可调拨数量。
|
||||
- 按 DBS、Crane 或指定 Invoice 查询。
|
||||
- 检查当前业务日期的最新 `ready` 收料文件。
|
||||
- 文件缺失时实时触发 RPA,并在对话中持续展示进度。
|
||||
- 按 HUB 仓收料日期执行 D+1 成熟规则。
|
||||
- 相同 Invoice 多行汇总收料数量。
|
||||
- 按 Invoice No 查询 ERP 账面库存。
|
||||
- 生成可执行、未成熟、阻断和预计调拨数量。
|
||||
- 用户选择全部或部分可执行 Invoice。
|
||||
- 10 分钟确认卡。
|
||||
- 后台逐张调用 ERP 原子新建、审核、过账接口。
|
||||
- 对话中展示执行进度和最终结果。
|
||||
- 每日收料文件抓取排程,默认 08:00。
|
||||
- 每日自动调拨排程,默认 09:00。
|
||||
- 自动复核历史未成功且未人工关闭的 Invoice。
|
||||
- 安全恢复、手工重试、请求停止、人工关闭。
|
||||
- 一次自动调拨排程发送一条企业微信汇总通知并附异常 Excel。
|
||||
- 全节点审计和 MinIO 归档。
|
||||
|
||||
### 3.2 一期不实现
|
||||
|
||||
- 独立集成中心。
|
||||
- 新的仓库业务后台或一级菜单。
|
||||
- Dify 直连 ERP、RPA、数据库或企业微信。
|
||||
- 用户修改来源仓、ERP 组织、目标 HUB 仓或调拨数量。
|
||||
- 部分数量调拨、单位换算、批次或库位逻辑。
|
||||
- ERP 写操作自动技术重试。
|
||||
- `result_unknown` 自动重试。
|
||||
- 通知自动重试。
|
||||
- 空数据通知。
|
||||
- 业务删除和历史兼容层。
|
||||
|
||||
---
|
||||
|
||||
## 4. 核心业务定义
|
||||
|
||||
### 4.1 业务日期和成熟规则
|
||||
|
||||
- 业务时区固定为 `Asia/Shanghai`。
|
||||
- 当前业务日期为 `T`。
|
||||
- 可进入预检:`receipt_date < T`。
|
||||
- `receipt_date = T` 标记为 `not_matured`,不查询 ERP、不计入可调拨数量、不视为异常。
|
||||
- 用户说“今天可调拨”表示:截至昨天及更早、尚未成功调拨且未人工关闭的全部 Invoice。
|
||||
|
||||
### 4.2 收料文件新鲜度
|
||||
|
||||
复用条件:
|
||||
|
||||
```text
|
||||
source_code + business_date + file_purpose(receipt)
|
||||
```
|
||||
|
||||
必须存在当前业务日期生成的最新 `ready` 文件。只有前一日文件时不得复用,必须实时抓取。
|
||||
|
||||
同一来源同一业务日期同一用途只允许一个活动抓取任务;并发请求绑定已有任务。
|
||||
|
||||
### 4.3 文件字段
|
||||
|
||||
必要业务字段:
|
||||
|
||||
- Invoice No
|
||||
- 料号
|
||||
- HUB 仓收料日期
|
||||
- 收料数量
|
||||
|
||||
系统追溯字段:
|
||||
|
||||
- 来源编码
|
||||
- 文件编号和版本
|
||||
- checksum
|
||||
- Sheet
|
||||
- 原始行号
|
||||
- 抓取和解析时间
|
||||
- RPA Run、Source Job
|
||||
|
||||
相同 Invoice 多行只汇总收料数量,并永久保留原始行追溯。
|
||||
|
||||
### 4.4 文件阻断
|
||||
|
||||
整张 Invoice 阻断条件:
|
||||
|
||||
- Invoice No、料号、日期或数量为空。
|
||||
- 数量不是有效数字或小于等于 0。
|
||||
- 必填列、目标 Sheet 缺失。
|
||||
- 同一 Invoice 出现多个料号。
|
||||
- 同一 Invoice 出现多个收料日期。
|
||||
- 同一 Invoice 跨 Sheet 内容冲突。
|
||||
- Callback 来源身份与任务来源不一致。
|
||||
|
||||
### 4.5 ERP 匹配和写入
|
||||
|
||||
- ERP 查询和写入均使用 SOAP WebService。
|
||||
- 查询和写入默认超时均为 60 秒。
|
||||
- 数量必须满足 `receipt_quantity == erp_book_inventory`。
|
||||
- 大于或小于均阻断,不允许截断或部分调拨。
|
||||
- ERP 写接口原子完成新建、审核、过账,失败完整回滚。
|
||||
- 同一 ERP 组织内 Invoice No 是幂等键。
|
||||
- 重复 Invoice 返回原调拨单号,并可证明已审核、过账,投影为 `duplicate_success`。
|
||||
- ERP 写操作自动重试为 0。
|
||||
|
||||
---
|
||||
|
||||
## 5. 角色与权限
|
||||
|
||||
一期仅有一个业务角色:拥有该 Agent 权限的仓库管理人员。
|
||||
|
||||
| 操作 | 权限 |
|
||||
| --- | --- |
|
||||
| 查询所有来源、Run、Invoice | 允许 |
|
||||
| 发起预检 | 允许 |
|
||||
| 选择 Invoice、确认执行 | 允许 |
|
||||
| 查看所有有权限用户发起的 Run | 允许 |
|
||||
| 请求停止剩余任务 | 允许,原因必填 |
|
||||
| 手工重试可重试项 | 允许 |
|
||||
| `manually_closed` | 允许,原因必填 |
|
||||
| 修改数量、仓库、ERP 组织 | 禁止 |
|
||||
| 删除业务或审计记录 | 禁止 |
|
||||
|
||||
配置页面继续使用现有管理员权限,本 HTML 原型不展示管理员视角。
|
||||
|
||||
---
|
||||
|
||||
## 6. 完整业务流程
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[用户对话或自动调拨排程] --> B[解析来源 日期 Invoice范围]
|
||||
B --> C[按来源检查当日 receipt ready文件]
|
||||
C --> D{文件是否ready}
|
||||
D -->|是| H[文件校验与解析]
|
||||
D -->|正在抓取| E[绑定已有RPA任务]
|
||||
D -->|不存在| F[创建实时RPA Source Job]
|
||||
F --> G[等待Callback并持续投影进度]
|
||||
E --> G
|
||||
G --> H
|
||||
H --> I[过滤当天未成熟Invoice]
|
||||
I --> J[相同Invoice多行汇总]
|
||||
J --> K[合并历史未完成待办]
|
||||
K --> L[查询ERP账面库存]
|
||||
L --> M[数量匹配和幂等检查]
|
||||
M --> N[生成预检快照和Hash]
|
||||
N --> O{触发方式}
|
||||
O -->|只读查询| P[返回预检结果]
|
||||
O -->|对话执行| Q[展示10分钟确认卡]
|
||||
Q --> R[用户确认]
|
||||
O -->|自动排程| S[按策略直接创建执行Run]
|
||||
R --> S
|
||||
S --> T[Worker写入前重新预检]
|
||||
T --> U[逐项ERP原子调拨]
|
||||
U --> V[生成结果和异常Excel]
|
||||
V --> W{自动排程且非空数据}
|
||||
W -->|是| X[发送一条企微汇总通知和附件]
|
||||
W -->|否| Y[只保留Run和审计]
|
||||
```
|
||||
|
||||
### 6.1 文件准备进度阶段
|
||||
|
||||
1. 理解查询范围。
|
||||
2. 检查当前业务日期收料文件。
|
||||
3. 复用文件、绑定抓取任务或触发 RPA。
|
||||
4. 等待 RPA Callback。
|
||||
5. 校验文件。
|
||||
6. 过滤未成熟数据。
|
||||
7. 汇总 Invoice。
|
||||
8. 查询 ERP 库存。
|
||||
9. 匹配可调拨结果。
|
||||
|
||||
每阶段使用 `pending | running | success | failed | skipped`,并分别展示 DBS、Crane 状态,不伪造总体百分比。
|
||||
|
||||
### 6.2 确认失效
|
||||
|
||||
确认卡保存文件快照、checksum、来源配置版本、仓库映射版本、ERP 库存、选择清单、预计总数量和预检 Hash。
|
||||
|
||||
以下变化导致确认失效:
|
||||
|
||||
- 超过 10 分钟。
|
||||
- 文件或 checksum 变化。
|
||||
- ERP 库存变化。
|
||||
- 来源或仓库映射变化。
|
||||
- 用户选择范围变化。
|
||||
|
||||
Worker 执行前必须重新查询 ERP;变化项进入 `precheck_expired`,不得写 ERP。
|
||||
|
||||
---
|
||||
|
||||
## 7. 历史失败恢复与防遗忘
|
||||
|
||||
### 7.1 待处理池
|
||||
|
||||
```text
|
||||
未成功 AND 未 manually_closed
|
||||
→ transfer_backlog
|
||||
```
|
||||
|
||||
每日自动调拨排程同时处理:
|
||||
|
||||
- 当日新成熟 Invoice。
|
||||
- 所有历史待处理 Invoice。
|
||||
|
||||
### 7.2 恢复策略
|
||||
|
||||
| 原状态 | 下次排程行为 | 自动执行 |
|
||||
| --- | --- | --- |
|
||||
| `blocked_quantity_mismatch` | 最新文件与 ERP 重新预检 | 全门禁通过后是 |
|
||||
| `blocked_inventory_not_found` | 重新查询 ERP | 全门禁通过后是 |
|
||||
| `technical_failed` | 重新预检,不重放旧请求 | 全门禁通过后是 |
|
||||
| `precheck_expired` | 重新预检 | 全门禁通过后是 |
|
||||
| 文件结构错误 | 等待新 ready 文件重新解析 | 解析和预检通过后是 |
|
||||
| `result_unknown` | 人工核实 | 否 |
|
||||
| `manually_closed` | 永久排除 | 否 |
|
||||
| `success` / `duplicate_success` | 幂等跳过 | 否 |
|
||||
|
||||
每次恢复必须创建新的 Attempt,旧记录不可覆盖。
|
||||
|
||||
### 7.3 老化升级
|
||||
|
||||
默认阈值可配置:
|
||||
|
||||
| 年龄 | 等级 | 行为 |
|
||||
| ---: | --- | --- |
|
||||
| 0-1 天 | 普通待办 | 正常展示和排程复核 |
|
||||
| 3 天 | 即将超期 | Agent 首页高亮、通知汇总展示 |
|
||||
| 5 天 | 升级 | 通知任务所有者和配置通知人 |
|
||||
| 7 天及以上 | 严重积压 | 每日汇总提醒,直至成功或关闭 |
|
||||
|
||||
`result_unknown` 从出现之日起单独高风险展示。
|
||||
|
||||
---
|
||||
|
||||
## 8. 状态机
|
||||
|
||||
### 8.1 Transfer Run
|
||||
|
||||
```text
|
||||
queued
|
||||
→ preparing_files
|
||||
→ prechecking
|
||||
→ awaiting_confirmation 仅对话执行
|
||||
→ executing
|
||||
→ success | partial_failed | failed | cancelled
|
||||
```
|
||||
|
||||
空数据:`success`,结果标记 `no_data`。
|
||||
|
||||
### 8.2 Source Job
|
||||
|
||||
```text
|
||||
pending
|
||||
→ checking_file
|
||||
→ waiting_rpa_callback
|
||||
→ parsing
|
||||
→ prechecking
|
||||
→ executing
|
||||
→ success | partial_failed | failed
|
||||
```
|
||||
|
||||
DBS、Crane 独立执行、独立锁、独立审计,互不阻断。
|
||||
|
||||
### 8.3 Invoice Item
|
||||
|
||||
```text
|
||||
pending
|
||||
├─ not_matured
|
||||
├─ blocked_invalid_file
|
||||
├─ blocked_quantity_mismatch
|
||||
├─ blocked_inventory_not_found
|
||||
├─ precheck_expired
|
||||
├─ queued
|
||||
├─ executing
|
||||
├─ success
|
||||
├─ duplicate_success
|
||||
├─ technical_failed
|
||||
├─ result_unknown
|
||||
├─ cancelled
|
||||
└─ manually_closed
|
||||
```
|
||||
|
||||
### 8.4 请求停止
|
||||
|
||||
- 已成功单据保留。
|
||||
- 正在调用 ERP 的 Invoice 等待返回。
|
||||
- 尚未开始的 Invoice 标记 `cancelled`。
|
||||
- 不撤销 ERP 已完成单据。
|
||||
- 原因必填,保存前后快照。
|
||||
|
||||
---
|
||||
|
||||
## 9. 前后端解耦规划
|
||||
|
||||
### 9.1 解耦原则
|
||||
|
||||
- 前端只依赖稳定 REST/SSE DTO,不理解 SOAP、WSDL、RPA 文件路径或数据库模型。
|
||||
- 后端 Chat Action 只调用调拨应用服务,不直接操作 ERP Adapter。
|
||||
- 调拨服务返回结构化错误码,前端按四语言翻译。
|
||||
- 所有卡片均可由历史 `ChatLog.payload` 重建。
|
||||
- Run 是异步真相源;SSE 只负责即时反馈,轮询负责恢复。
|
||||
|
||||
### 9.2 建议API
|
||||
|
||||
| Method | Path | 用途 |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/in-transit-transfer/prechecks` | 创建或复用文件准备和预检Run |
|
||||
| GET | `/api/in-transit-transfer/prechecks/{id}` | 获取预检和来源进度 |
|
||||
| POST | `/api/in-transit-transfer/prechecks/{id}/confirm` | 确认选择并创建执行Run |
|
||||
| GET | `/api/in-transit-transfer/runs/{runNo}` | Run进度和结果 |
|
||||
| GET | `/api/in-transit-transfer/runs/{runNo}/items` | Invoice分页明细 |
|
||||
| POST | `/api/in-transit-transfer/runs/{runNo}/cancel` | 请求停止剩余任务 |
|
||||
| POST | `/api/in-transit-transfer/items/{id}/retry` | 原Run创建新Attempt |
|
||||
| POST | `/api/in-transit-transfer/items/{id}/manual-close` | 人工关闭 |
|
||||
| GET | `/api/in-transit-transfer/runs/{runNo}/exceptions.xlsx` | 下载异常Excel |
|
||||
| GET | `/api/in-transit-transfer/items/{id}/audit` | 查询Invoice审计时间线 |
|
||||
| GET | `/api/in-transit-transfer/backlog/summary` | Agent欢迎页待办摘要 |
|
||||
|
||||
统一响应遵循项目契约:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {},
|
||||
"request_id": "req_xxx"
|
||||
}
|
||||
```
|
||||
|
||||
### 9.3 预检DTO摘要
|
||||
|
||||
```json
|
||||
{
|
||||
"precheck_id": "TPC-20260806-001",
|
||||
"status": "awaiting_confirmation",
|
||||
"business_date": "2026-08-06",
|
||||
"eligible_receipt_date_to": "2026-08-05",
|
||||
"expires_at": "2026-08-06T09:20:00+08:00",
|
||||
"sources": [],
|
||||
"counts": {
|
||||
"file_invoice_count": 40,
|
||||
"not_matured_count": 8,
|
||||
"prechecked_count": 32,
|
||||
"executable_count": 27,
|
||||
"blocked_count": 5
|
||||
},
|
||||
"estimated_transfer_quantity": "18460",
|
||||
"estimated_erp_write_count": 27,
|
||||
"precheck_hash": "sha256:..."
|
||||
}
|
||||
```
|
||||
|
||||
### 9.4 Chat结构化消息类型
|
||||
|
||||
- `transfer-file-progress`
|
||||
- `transfer-precheck-result`
|
||||
- `transfer-confirmation`
|
||||
- `transfer-run-progress`
|
||||
- `transfer-run-result`
|
||||
- `transfer-exception`
|
||||
- `transfer-backlog-summary`
|
||||
|
||||
---
|
||||
|
||||
## 10. 后台执行与并发
|
||||
|
||||
建议一个收料抓取排程和一个自动调拨排程:
|
||||
|
||||
- 08:00 收料文件抓取排程。
|
||||
- 09:00 自动调拨排程。
|
||||
|
||||
自动调拨排程不能假设 08:00 成功,仍调用统一 `ensure_receipt_file_ready()`。
|
||||
|
||||
默认并发:
|
||||
|
||||
| 参数 | 默认 |
|
||||
| --- | ---: |
|
||||
| 来源并发 | 2 |
|
||||
| ERP 查询并发 | 2 |
|
||||
| ERP 写并发 | 1 |
|
||||
| 同来源活动 Source Job | 1 |
|
||||
| 同 Invoice 执行 | 1 |
|
||||
|
||||
建议环境变量:
|
||||
|
||||
```text
|
||||
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=2
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=2
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=1
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=60
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=60
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=600
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
|
||||
```
|
||||
|
||||
ERP地址和凭据只允许通过环境变量或Secret注入。
|
||||
|
||||
---
|
||||
|
||||
## 11. 审计规格
|
||||
|
||||
### 11.1 公共字段
|
||||
|
||||
- event ID、event type、operation。
|
||||
- entity type、entity ID。
|
||||
- Run、Source Job、Invoice、Attempt ID。
|
||||
- Agent、Chat Session、Chat Log ID。
|
||||
- operation ID、request ID。
|
||||
- actor type、user ID、role、display name。
|
||||
- client IP、user agent摘要。
|
||||
- operation time。
|
||||
- before/after snapshot、Diff。
|
||||
- before/after Hash。
|
||||
- file snapshot、source config、warehouse mapping版本。
|
||||
- result code、result message。
|
||||
|
||||
### 11.2 审计矩阵
|
||||
|
||||
| 节点 | 操作者 | 快照规则 |
|
||||
| --- | --- | --- |
|
||||
| 发起查询 | 用户 | 条件、返回数、摘要Hash;不保存完整结果 |
|
||||
| 检查/复用文件 | 用户、排程、系统 | 文件ID、版本、checksum、命中结果 |
|
||||
| 触发/绑定RPA | 用户、排程、RPA | Source Job、触发原因、原Job关系 |
|
||||
| RPA领取和Callback | RPA、worker | 状态前后、文件身份、checksum |
|
||||
| 文件校验和日期过滤 | worker | 错误列表、总数、未成熟数、Hash |
|
||||
| Invoice汇总 | worker | 原始行引用和汇总结果Hash |
|
||||
| ERP查询 | worker | 脱敏请求响应摘要、耗时、Hash |
|
||||
| 创建预检 | 用户、排程 | 完整预检快照和Hash |
|
||||
| 选择Invoice | 用户 | 选择前后集合Diff |
|
||||
| 确认执行 | 用户 | 确认Hash、有效期、预计写入 |
|
||||
| ERP调拨 | worker | 状态前后、单号、错误码、脱敏报文Hash |
|
||||
| 请求停止 | 用户 | 原因和Run/Item前后状态 |
|
||||
| 手工重试 | 用户 | 原因、新Attempt和重新预检证据 |
|
||||
| 自动历史复核 | 排程 | 每次保存摘要;相同结果引用前次完整快照 |
|
||||
| 人工关闭 | 用户 | 原因、数量、文件版本、状态前后 |
|
||||
| 查看详情/审计 | 用户 | 对象、时间、来源页面 |
|
||||
| 下载Excel | 用户 | 文件ID、checksum、下载结果 |
|
||||
| 通知 | worker、用户 | 接收人、附件、结果、错误 |
|
||||
| MinIO归档 | 系统 | 对象路径、Hash、归档前后状态 |
|
||||
|
||||
### 11.3 保留策略
|
||||
|
||||
- 业务用户不可删除。
|
||||
- 数据库永久保留索引、关键摘要、Hash、操作者和对象路径。
|
||||
- 大型快照、脱敏报文、Excel归档MinIO。
|
||||
- MinIO归档必须重新计算Hash并写审计事件。
|
||||
|
||||
---
|
||||
|
||||
## 12. 企业微信与Excel
|
||||
|
||||
每次非空自动调拨排程发送一条汇总通知,DBS、Crane合并展示。接收人是任务所有者和来源配置通知人的去重合集。
|
||||
|
||||
通知包含:
|
||||
|
||||
- 本次新数据成功、阻断数量。
|
||||
- 历史异常恢复成功数量。
|
||||
- 当前待处理、`result_unknown`、3天以上积压数量。
|
||||
- 调拨总数量和ERP单据数。
|
||||
- 一份本次排程异常Excel。
|
||||
|
||||
Excel Sheet:
|
||||
|
||||
1. 执行汇总
|
||||
2. 数量不一致
|
||||
3. ERP无库存
|
||||
4. ERP技术失败
|
||||
5. ERP结果未知
|
||||
6. 通知失败
|
||||
7. 原始文件追溯
|
||||
|
||||
空数据Run:`success + no_data`,不调用ERP、不通知。
|
||||
|
||||
---
|
||||
|
||||
## 13. MD线框原型
|
||||
|
||||
### 13.1 Agent欢迎页
|
||||
|
||||
```text
|
||||
┌─ 对话侧栏 ──────────┬────────────────────────────────────────────┐
|
||||
│ 在途仓调拨 Agent │ 在途仓调拨助手 │
|
||||
│ + 新对话 │ │
|
||||
│ │ 今日待处理 │
|
||||
│ 历史会话 │ 历史待处理 5 已恢复 2 结果未知 1 超期 2 │
|
||||
│ 今日自动调拨 │ │
|
||||
│ DBS数量异常 │ [查询今天可调拨数据] │
|
||||
│ INV-001处理结果 │ [执行今天全部可调拨项] │
|
||||
│ │ [查看待处理异常] │
|
||||
│ │ │
|
||||
│ │ ┌────────────────────────────────────────┐ │
|
||||
│ │ │ 输入问题或调拨指令... 发送 │ │
|
||||
│ │ └────────────────────────────────────────┘ │
|
||||
└──────────────────────┴────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
边界:只显示当前用户有权访问的Agent会话;管理员配置使用独立后台原型。
|
||||
|
||||
历史会话按一次用户对话或一次Run归并。文件准备、ERP查询和预检完成是同一会话的阶段投影,不得分别生成“查询今天可调拨数据”和“今日调拨预检”两条历史记录。会话副标题随最新阶段更新。
|
||||
|
||||
### 13.2 文件准备进度
|
||||
|
||||
```text
|
||||
用户:查询今天有多少可以调拨
|
||||
|
||||
AI:正在检查今天的DBS和Crane收料文件;缺失来源会实时抓取。
|
||||
|
||||
┌─ 正在准备可调拨数据 ──────────────────────────────┐
|
||||
│ 可处理收料日期 截至 2026-08-05 │
|
||||
│ 当前阶段 准备收料Excel │
|
||||
│ │
|
||||
│ DBS ✓ 复用今日08:00 ready文件 │
|
||||
│ Crane ◉ 未找到今日文件,RPA已领取,等待Callback │
|
||||
│ │
|
||||
│ 后续:校验 → 过滤未成熟 → 汇总 → ERP查询 → 匹配 │
|
||||
│ [刷新进度] │
|
||||
└────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
交互:原位更新,不连续刷出多条消息;关闭页面后任务继续。
|
||||
|
||||
### 13.3 预检结果
|
||||
|
||||
```text
|
||||
┌─ 今日调拨预检 ────────────────────────────────────┐
|
||||
│ 文件内Invoice 40 │
|
||||
│ 当天收料未成熟 8 │
|
||||
│ 进入ERP预检 32 │
|
||||
│ 可执行 27 │
|
||||
│ 数量不一致 3 │
|
||||
│ ERP无库存 2 │
|
||||
│ 可调拨总数量 18,460 PCS │
|
||||
│ │
|
||||
│ [查看明细] [选择Invoice] [执行全部可调拨项] │
|
||||
└────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 13.4 Invoice选择与确认
|
||||
|
||||
```text
|
||||
┌─ 执行前确认 ──────────────────────────────────────┐
|
||||
│ 搜索Invoice [_______________________________] │
|
||||
│ [✓] INV-001 DBS 1,200 = 1,200 可执行 │
|
||||
│ [✓] INV-002 DBS 800 = 800 可执行 │
|
||||
│ [ ] INV-003 DBS 1,200 ≠ 1,000 已阻断 │
|
||||
│ [✓] INV-004 Crane 600 = 600 可执行 │
|
||||
│ │
|
||||
│ 已选择 3张 总数量 2,600 PCS ERP写入 3张 │
|
||||
│ 确认有效期 10分钟 │
|
||||
│ [取消] [返回预检] [执行调拨] │
|
||||
└────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 13.5 调拨执行进度
|
||||
|
||||
```text
|
||||
┌─ RUN-20260806-0900 · 执行中 ──────────────────────┐
|
||||
│ 文件准备 2/2来源完成 │
|
||||
│ ERP库存查询 32/32 │
|
||||
│ 数量匹配 27通过 / 5阻断 │
|
||||
│ ERP调拨 19/27 │
|
||||
│ 通知 等待 │
|
||||
│ │
|
||||
│ DBS 12/15 Crane 7/12 │
|
||||
│ [查看明细] [请求停止] │
|
||||
└────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 13.6 结果摘要
|
||||
|
||||
```text
|
||||
┌─ 调拨完成 ────────────────────────────────────────┐
|
||||
│ 成功过账 27 历史恢复 2 重复成功 1 │
|
||||
│ 数量不一致 3 ERP无库存 1 结果未知 1 │
|
||||
│ 调拨总数量 18,460 PCS │
|
||||
│ 通知 已发送 │
|
||||
│ [成功单据] [异常详情] [下载Excel] │
|
||||
└────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 13.7 异常详情
|
||||
|
||||
```text
|
||||
┌─ INV-260806-019 ──────────────────────────────────┐
|
||||
│ 来源 DBS 状态 数量不一致 │
|
||||
│ 文件 receipt-v20.xlsx Sheet Receipt │
|
||||
│ 原始行 128、129 收料 1,200 / ERP 1,000 │
|
||||
│ │
|
||||
│ 审计时间线 │
|
||||
│ 09:01 文件解析完成 │
|
||||
│ 09:02 ERP查询完成 │
|
||||
│ 09:02 数量门禁阻断 │
|
||||
│ │
|
||||
│ [下载证据] [手工重试] [无需再处理] │
|
||||
└────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 13.8 人工关闭
|
||||
|
||||
```text
|
||||
┌─ 标记无需继续处理 ────────────────────────────────┐
|
||||
│ Invoice INV-260806-019 │
|
||||
│ 关闭原因 * │
|
||||
│ ┌────────────────────────────────────────────────┐ │
|
||||
│ │ │ │
|
||||
│ └────────────────────────────────────────────────┘ │
|
||||
│ 关闭后不再自动处理,原始记录和审计永久保留。 │
|
||||
│ [取消] [确认关闭] │
|
||||
└────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 13.9 管理后台:数据来源
|
||||
|
||||
```text
|
||||
┌─ HXOPS管理后台 ───────────────────────────────────────────────────┐
|
||||
│ 调拨配置 │
|
||||
│ ● 数据来源 ┌─ 收料文件来源 ──────────────────────────────┐ │
|
||||
│ 调拨策略 │ DBS收料汇总 Crane收料汇总 │ │
|
||||
│ 仓库与组织 │ 用途 receipt 用途 receipt │ │
|
||||
│ 自动排程 │ RPA Profile HTTP Callback │ │
|
||||
│ 通知设置 │ 解析方案 V3 解析方案 V3 │ │
|
||||
│ │ 固定来源仓 固定来源仓 │ │
|
||||
│ 发布与治理 │ [编辑] [验证配置] [停用] │ │
|
||||
│ 发布管理 └──────────────────────────────────────────────┘ │
|
||||
│ 连接验证 V4草稿│
|
||||
│ 配置审计 [保存草稿] [发布] │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
边界:发货库存与收料配置是不同来源实例;配置、锁和运行互不影响。页面不读取或回显ERP、RPA凭据。
|
||||
|
||||
### 13.10 管理后台:调拨策略与仓库映射
|
||||
|
||||
```text
|
||||
┌─ 调拨策略 Draft V4 ─────────────────────────────────────────────┐
|
||||
│ 业务时区 Asia/Shanghai 成熟规则 D+1 │
|
||||
│ 数量门禁 必须完全相等 确认有效期 10分钟 │
|
||||
│ ERP查询超时 60秒(环境变量) ERP写超时 60秒 │
|
||||
│ [开] 对话执行前一次确认 │
|
||||
│ [开] 历史可恢复异常每日复核 │
|
||||
│ [关] result_unknown自动重试(强制不可开启) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌─ 组织与仓库映射 ───────────────────────────────────────────────┐
|
||||
│ 路由 ERP组织 来源实例 固定来源仓 目标HUB仓 │
|
||||
│ DBS-TRANSFER HX-CN01 DBS收料 DBS-TRANSIT 系统库存映射 │
|
||||
│ CRANE-TRANSFER HX-CN01 Crane收料 CRANE-TRANSIT 系统库存映射│
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 13.11 管理后台:排程、通知、发布与审计
|
||||
|
||||
```text
|
||||
┌─ 自动排程 ──────────────────────────────────────────────────────┐
|
||||
│ 每日收料文件抓取 08:00 DBS、Crane并发2 [编辑][停用] │
|
||||
│ 每日自动调拨 09:00 查询并发2 / 写并发1 [编辑][停用] │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
┌─ 通知设置 ──────────────────────────────────────────────────────┐
|
||||
│ 任务所有者 李仓储 额外通知人 王仓管、陈主管 │
|
||||
│ 非空Run一条汇总通知 一份七Sheet异常Excel │
|
||||
│ 空数据不通知 notification_failed不改变业务结果 │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
┌─ 发布门禁与审计 ────────────────────────────────────────────────┐
|
||||
│ 来源 ✓ 映射 ✓ 环境变量 ✓ 通知人 ! 配置验证 ✓ │
|
||||
│ [查看Diff] [运行校验] [发布V4] │
|
||||
│ 操作人、时间、对象、before/after、Diff、Hash、版本永久可追溯 │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
后台HTML原型:`docs/prototype/in-transit-transfer-admin-config-mvp.html`。支持 `?page=sources|strategy|mapping|schedules|notifications|release|validation|audit`。
|
||||
|
||||
---
|
||||
|
||||
## 14. 分阶段实施与文件清单
|
||||
|
||||
### Phase 0:领域模型、配置和审计底座
|
||||
|
||||
目标:冻结数据契约、状态机、来源配置和审计能力。
|
||||
|
||||
#### 修改文件
|
||||
|
||||
| 路径 | 具体修改 |
|
||||
| --- | --- |
|
||||
| `backend/app/models/shipping_inventory_config.py` | 为库存来源增加 `purpose`、任务所有者、通知人、收料解析用途和调拨启用字段;更新约束 |
|
||||
| `backend/app/models/__init__.py` | 导出调拨领域模型 |
|
||||
| `backend/app/api/admin/shipping_inventory.py` | 库存来源CRUD支持收料类型和调拨字段,返回配置版本 |
|
||||
| `backend/app/services/shipping_notice/inventory_source_repository.py` | 运行时快照支持按purpose读取,避免发货与收料混用 |
|
||||
| `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue` | 复用现有页面增加收料来源字段,不新增管理页 |
|
||||
| `frontend/src/features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts` | 表单归一化、校验和脏状态比较 |
|
||||
| `frontend/src/features/admin/api/admin.api.ts` | 扩展来源DTO |
|
||||
| `docs/prototype/in-transit-transfer-agent-mvp.html` | 合并查询、文件准备和预检为同一历史会话的阶段投影 |
|
||||
| `docs/demand.md`、`docs/tec.md`、`docs/funclist.md` | 同步需求、架构和功能清单 |
|
||||
|
||||
#### 新增文件
|
||||
|
||||
| 路径 | 内容 |
|
||||
| --- | --- |
|
||||
| `backend/app/models/in_transit_transfer.py` | Run、SourceJob、Precheck、InvoiceItem、Attempt、AuditEvent、Archive模型 |
|
||||
| `backend/migrations/versions/<revision>_add_in_transit_transfer.py` | 数据库迁移 |
|
||||
| `backend/app/services/in_transit_transfer/contracts.py` | Pydantic请求、响应和快照契约 |
|
||||
| `backend/app/services/in_transit_transfer/status.py` | 状态和转换门禁 |
|
||||
| `backend/app/services/in_transit_transfer/audit.py` | 操作者、快照、Diff、Hash和归档索引 |
|
||||
| `backend/tests/services/in_transit_transfer/test_status.py` | 状态机测试 |
|
||||
| `backend/tests/services/in_transit_transfer/test_audit.py` | 审计完整性测试 |
|
||||
| `docs/prototype/in-transit-transfer-admin-config-mvp.html` | 数据来源、策略、映射、排程、通知、发布校验和配置审计交互原型 |
|
||||
|
||||
验收:迁移升级/回滚成功;非法状态转换拒绝率100%;写操作审计字段完整率100%;Hash复算一致率100%;原库存来源功能无回归;后台原型八个配置页面均可独立打开;敏感凭据明文展示数量为0。
|
||||
|
||||
### Phase 1:文件准备和只读预检
|
||||
|
||||
目标:对话可看到文件抓取全过程并获得准确预检结果,不写ERP。
|
||||
|
||||
#### 修改文件
|
||||
|
||||
| 路径 | 具体修改 |
|
||||
| --- | --- |
|
||||
| `backend/app/services/chat/action_types.py` | 增加调拨查询和预检Action类型 |
|
||||
| `backend/app/services/chat/action_schema.py` | 增加日期、来源、Invoice范围校验 |
|
||||
| `backend/app/services/chat/action_registry.py` | 加载调拨Handler |
|
||||
| `backend/app/jobs/types.py` | 增加收料文件准备和调拨预检Job类型 |
|
||||
| `backend/app/jobs/store.py` | shipping/transfer队列可领取新Job |
|
||||
| `frontend/src/features/chat/types/chat.types.ts` | 增加结构化消息payload |
|
||||
| `frontend/src/features/chat/components/messages/ChatMessageBubble.vue` | 按message type挂载调拨卡片 |
|
||||
| `frontend/src/features/chat/components/ChatMessageList.vue` | 同一Run只显示最新投影 |
|
||||
| `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` | 调拨文案 |
|
||||
| `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json` | 调拨错误码 |
|
||||
|
||||
#### 新增文件
|
||||
|
||||
| 路径 | 内容 |
|
||||
| --- | --- |
|
||||
| `backend/app/services/in_transit_transfer/file_preparation.py` | `ensure_receipt_file_ready`和RPA绑定 |
|
||||
| `backend/app/services/in_transit_transfer/file_parser.py` | 字段、结构、日期校验 |
|
||||
| `backend/app/services/in_transit_transfer/invoice_aggregator.py` | 多行汇总和原始行追溯 |
|
||||
| `backend/app/services/in_transit_transfer/erp_adapter.py` | SOAP查询/写入隔离;一期先由业务模块实现 |
|
||||
| `backend/app/services/in_transit_transfer/precheck_service.py` | 成熟过滤、ERP查询、匹配和Hash |
|
||||
| `backend/app/services/in_transit_transfer/chat_actions.py` | 文件准备、预检、查询Action |
|
||||
| `backend/app/jobs/handlers/in_transit_transfer_precheck.py` | 异步文件和预检Handler |
|
||||
| `backend/app/api/in_transit_transfer.py` | 预检、进度和明细API |
|
||||
| `frontend/src/features/chat/api/transfer.api.ts` | 前端API |
|
||||
| `frontend/src/features/chat/types/transfer.types.ts` | DTO类型 |
|
||||
| `frontend/src/features/chat/components/messages/TransferFileProgressCard.vue` | 来源级文件进度 |
|
||||
| `frontend/src/features/chat/components/messages/TransferPrecheckCard.vue` | 预检卡 |
|
||||
| `frontend/src/features/chat/components/TransferInvoiceDetailDrawer.vue` | Invoice明细 |
|
||||
| 对应前后端测试 | 文件幂等、日期、解析、汇总、ERP查询、历史恢复 |
|
||||
|
||||
验收:缺文件时5秒内返回进度卡;并发请求只触发一次RPA;当天收料100%不查ERP;多行汇总准确率100%;DBS失败不影响Crane;历史会话可恢复进度;同一查询Run在历史侧栏中始终只有一条会话记录。
|
||||
|
||||
### Phase 2:确认和ERP调拨
|
||||
|
||||
目标:用户一次确认后由独立Worker安全执行ERP写入。
|
||||
|
||||
#### 修改文件
|
||||
|
||||
| 路径 | 具体修改 |
|
||||
| --- | --- |
|
||||
| `backend/app/jobs/types.py` | 增加Transfer Run和Item Job |
|
||||
| `backend/app/jobs/handlers/__init__.py` | 注册Handler |
|
||||
| `backend/worker_shipping.py` | 支持调拨队列/独立并发参数 |
|
||||
| `docker-compose.yml` | 增加`hxops-transfer-worker`服务,复用后端镜像 |
|
||||
| `frontend/src/features/chat/composables/useToolRunProgress.ts` | 识别调拨进度契约 |
|
||||
| `frontend/src/features/chat/components/messages/ChatMessageBubble.vue` | 挂载确认、进度、结果卡 |
|
||||
|
||||
#### 新增文件
|
||||
|
||||
| 路径 | 内容 |
|
||||
| --- | --- |
|
||||
| `backend/app/services/in_transit_transfer/orchestrator.py` | Run、SourceJob、Item编排 |
|
||||
| `backend/app/services/in_transit_transfer/execution_service.py` | 写前复检、ERP调用和结果投影 |
|
||||
| `backend/app/services/in_transit_transfer/concurrency.py` | 来源、查询和写入限流 |
|
||||
| `backend/app/services/in_transit_transfer/cancellation.py` | 请求停止剩余项 |
|
||||
| `backend/app/jobs/handlers/in_transit_transfer_run.py` | Run Handler |
|
||||
| `backend/app/jobs/handlers/in_transit_transfer_item.py` | Invoice Handler |
|
||||
| `backend/workers/worker_in_transit_transfer.py` | transfer队列启动入口 |
|
||||
| `frontend/src/features/chat/components/messages/TransferConfirmationCard.vue` | 勾选和确认 |
|
||||
| `frontend/src/features/chat/components/messages/TransferProgressCard.vue` | 执行进度 |
|
||||
| `frontend/src/features/chat/components/messages/TransferResultCard.vue` | 最终结果 |
|
||||
| `frontend/src/features/chat/composables/useChatTransfer.ts` | 前端交互编排 |
|
||||
| 对应测试 | 确认失效、幂等、并发、取消、重连 |
|
||||
|
||||
验收:未确认或过期确认的ERP写入数为0;库存变化项写入数为0;同Invoice无重复;关闭页面后Run继续;写并发1稳定完成;成功/重复成功单号可追溯。
|
||||
|
||||
### Phase 3:排程、历史恢复、异常和通知
|
||||
|
||||
目标:每日自动运行、受控恢复历史异常并防止遗忘。
|
||||
|
||||
#### 修改文件
|
||||
|
||||
| 路径 | 具体修改 |
|
||||
| --- | --- |
|
||||
| `backend/app/services/schedule/job_registry.py` | 注册收料抓取和自动调拨排程 |
|
||||
| `backend/app/services/schedule/job_params.py` | 来源、所有者、通知人、并发和恢复参数 |
|
||||
| `backend/app/services/schedule/schedule_contract.py` | 调拨排程契约 |
|
||||
| `backend/app/services/schedule/scheduler_service.py` | 调拨Run收尾和通知 |
|
||||
| `frontend/src/features/chat/components/ChatWelcomePanel.vue` | Agent能力声明时展示待办摘要 |
|
||||
|
||||
#### 新增文件
|
||||
|
||||
| 路径 | 内容 |
|
||||
| --- | --- |
|
||||
| `backend/app/services/schedule/in_transit_receipt_file_job.py` | 08:00文件抓取排程 |
|
||||
| `backend/app/services/schedule/in_transit_transfer_job.py` | 09:00自动调拨排程 |
|
||||
| `backend/app/services/in_transit_transfer/backlog_service.py` | 历史待处理池和老化 |
|
||||
| `backend/app/services/in_transit_transfer/recovery_service.py` | 自动复核和新Attempt |
|
||||
| `backend/app/services/in_transit_transfer/retry_service.py` | 手工重试 |
|
||||
| `backend/app/services/in_transit_transfer/manual_close_service.py` | 人工关闭 |
|
||||
| `backend/app/services/in_transit_transfer/excel_export.py` | 七Sheet Excel |
|
||||
| `backend/app/services/in_transit_transfer/notification.py` | 一次排程一条企微通知 |
|
||||
| `frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue` | 欢迎页待办摘要 |
|
||||
| `frontend/src/features/chat/components/messages/TransferExceptionCard.vue` | 异常卡 |
|
||||
| `frontend/src/features/chat/components/TransferManualCloseDialog.vue` | 人工关闭 |
|
||||
| `frontend/src/features/chat/components/TransferAuditDrawer.vue` | 审计时间线 |
|
||||
| 对应测试 | 自动恢复、老化、Excel、通知、关闭和重试 |
|
||||
|
||||
验收:历史可恢复异常下一排程自动复核;`result_unknown`自动写入为0;每次恢复创建新Attempt;3/5/7天阈值正确;每次非空排程仅一条通知;Excel七Sheet齐全;通知失败不改变ERP结果。
|
||||
|
||||
### Phase 4:生产硬化和归档
|
||||
|
||||
目标:完成安全、性能、恢复、归档和上线验收。
|
||||
|
||||
#### 新增或修改文件
|
||||
|
||||
| 路径 | 内容 |
|
||||
| --- | --- |
|
||||
| `backend/app/services/in_transit_transfer/archive.py` | MinIO归档和Hash验证 |
|
||||
| `backend/app/services/in_transit_transfer/recovery.py` | 陈旧Job和Worker崩溃恢复 |
|
||||
| `backend/app/services/in_transit_transfer/metrics.py` | 成功率、耗时和积压指标 |
|
||||
| `backend/tests/performance/test_in_transit_transfer.py` | 性能和并发测试 |
|
||||
| `frontend/src/features/chat/e2e/in-transit-transfer.spec.ts` | 全流程E2E |
|
||||
| `docs/test_plan_matrix.md` | 调拨验收矩阵 |
|
||||
| `docs/features/in-transit-transfer/technical.md` | 运行维护手册 |
|
||||
| `docs/features/README.md` | 文档索引 |
|
||||
|
||||
验收:Worker重启不重复成功项;审计丢失率0;归档Hash通过率100%;所有越权写请求403;四语言完整;`npm run build`、专项单测、E2E通过;测试ERP可创建并作废真实测试单。
|
||||
|
||||
---
|
||||
|
||||
## 15. 风险与关键问题
|
||||
|
||||
### 15.1 核心关键风险
|
||||
|
||||
**预检确认与Worker实际写入之间,文件、库存或映射变化,导致实际写入超出用户确认范围。**
|
||||
|
||||
控制:冻结文件快照和版本;保存预检Hash;10分钟失效;写前重新查询ERP;变化项进入`precheck_expired`;任何门禁失败均不写ERP。
|
||||
|
||||
### 15.2 技术风险
|
||||
|
||||
| 风险 | 影响 | 控制 |
|
||||
| --- | --- | --- |
|
||||
| ERP并发能力未知 | 超时、结果未知 | 写并发默认1,压测后提升 |
|
||||
| SOAP超时 | 状态不确定 | Invoice幂等验证;不自动重放;人工核实 |
|
||||
| RPA Callback丢失 | 对话长时间等待 | 租约、超时、来源级失败和人工刷新 |
|
||||
| 重复抓取 | 货代系统压力、快照冲突 | 来源+日期+用途幂等键 |
|
||||
| Worker崩溃 | Job卡死 | `FOR UPDATE SKIP LOCKED`、租约、陈旧回收 |
|
||||
| SSE断开 | 用户看不到进度 | Run持久化、轮询恢复、原位投影 |
|
||||
| 审计膨胀 | 数据库压力 | 摘要Hash、MinIO归档、索引留库 |
|
||||
| 通知附件过大 | 发送失败 | 精简Excel;必要时受控下载链接 |
|
||||
|
||||
### 15.3 业务风险
|
||||
|
||||
| 风险 | 控制 |
|
||||
| --- | --- |
|
||||
| 当天收料被误调拨 | D+1硬门禁,未成熟不查询ERP |
|
||||
| 历史失败被遗忘 | 自动待办池、每日复核、3/5/7天升级 |
|
||||
| 自动恢复误补偿 | 最新文件、ERP、幂等、映射全门禁和新Attempt |
|
||||
| 人工关闭滥用 | 原因必填、快照、永久审计 |
|
||||
| 通知失败被当成业务失败 | `notification_failed`与ERP结果分离 |
|
||||
| 用户误选范围 | 确认卡展示Invoice、数量、预计写入和有效期 |
|
||||
|
||||
### 15.4 资源风险
|
||||
|
||||
| 风险 | 控制 |
|
||||
| --- | --- |
|
||||
| shipping worker负载过高 | 独立transfer worker进程 |
|
||||
| PostgreSQL写放大 | 批量提交、必要索引、快照归档 |
|
||||
| MinIO容量增长 | 生命周期、对象压缩、低成本存储 |
|
||||
| ERP测试资源不足 | 沙箱组织、可作废真实测试单 |
|
||||
| 团队并行改动Chat核心组件 | 小扩展点、卡片独立组件、契约测试 |
|
||||
|
||||
### 15.5 进度风险
|
||||
|
||||
| 风险 | 控制 |
|
||||
| --- | --- |
|
||||
| ERP响应样例变化 | Phase 0冻结WSDL和样例 |
|
||||
| 收料文件结构不稳定 | 样本测试、解析Profile版本、结构漂移阻断 |
|
||||
| 审计在末期补做 | Phase 0先建审计,后续每节点强制接入 |
|
||||
| 前后端契约漂移 | DTO、契约测试、Mock数据并行开发 |
|
||||
| 范围膨胀到集成中心 | 明确一期不实现,ERP Adapter仅业务内隔离 |
|
||||
|
||||
---
|
||||
|
||||
## 16. 总体验收门槛
|
||||
|
||||
一期进入生产前必须同时满足:
|
||||
|
||||
1. 所有核心对话页面符合现有Chat UI,所有后台配置页面符合现有AdminLayout、库存来源和排程工作台风格。
|
||||
2. 所有写操作有操作人、时间、内容、before/after快照和Hash。
|
||||
3. 所有只读操作有条件、返回数、结果摘要Hash和关联上下文。
|
||||
4. 当天收料ERP查询和写入数量均为0。
|
||||
5. 未确认、过期确认、变化预检的ERP写入数量均为0。
|
||||
6. `result_unknown`自动重试数量为0。
|
||||
7. 历史可恢复项能自动进入新Attempt,旧Attempt不变。
|
||||
8. DBS和Crane故障互不影响。
|
||||
9. 非空自动排程仅发送一条汇总通知和一份Excel。
|
||||
10. 前端构建、四语言、专项测试、E2E、迁移和真实ERP沙箱验收全部通过。
|
||||
11. 查询、文件准备、ERP预检在一次对话中原位投影,历史侧栏不产生重复阶段记录。
|
||||
12. 后台配置必须经过草稿、校验、发布流程;ERP与RPA凭据明文展示数量为0。
|
||||
@@ -0,0 +1,82 @@
|
||||
<!--
|
||||
docs/prototype/in-transit-transfer-admin-config-mvp.html
|
||||
用途:演示在途仓自动调拨一期后台配置、发布校验和审计追溯页面。
|
||||
依赖:独立 HTML、CSS、原生 JavaScript;视觉结构复用 HXOPS AdminLayout、库存来源管理和排程工作台。
|
||||
逻辑:左侧切换配置域,中间维护草稿,右侧持续展示版本、发布门禁和审计;不展示或保存任何真实凭据。
|
||||
-->
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>HXOPS · 在途仓调拨后台配置</title>
|
||||
<style>
|
||||
:root{--page:#f5f7fb;--surface:#fff;--soft:#f8fafc;--line:#e2e8f0;--line2:#cbd5e1;--text:#0f172a;--secondary:#334155;--muted:#64748b;--brand:#2563eb;--brand2:#1d4ed8;--brand-soft:#eff6ff;--ok:#15803d;--ok-soft:#f0fdf4;--warn:#a16207;--warn-soft:#fffbeb;--danger:#be123c;--danger-soft:#fff1f2;--shadow:0 10px 28px -24px rgba(15,23,42,.45)}
|
||||
*{box-sizing:border-box}html,body{height:100%}body{margin:0;min-width:1180px;background:var(--page);color:var(--secondary);font:14px/1.5 "PingFang SC","Microsoft YaHei","Segoe UI",Arial,sans-serif}button,input,select,textarea{font:inherit}button{cursor:pointer}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:3px solid rgba(37,99,235,.2);outline-offset:2px}
|
||||
.shell{min-height:100vh}.topbar{height:72px;display:flex;align-items:center;justify-content:space-between;padding:0 28px;border-bottom:1px solid var(--line);background:rgba(255,255,255,.96)}.brand{display:flex;align-items:center;gap:13px}.logo{width:42px;height:42px;border-radius:14px;display:grid;place-items:center;background:linear-gradient(135deg,#3b82f6,#4f46e5);color:#fff;font-weight:800;box-shadow:0 9px 18px -12px #2563eb}.brand h1{margin:0;color:var(--text);font-size:20px}.brand p{margin:1px 0 0;color:var(--muted);font-size:11px}.header-tools{display:flex;align-items:center;gap:10px}.env,.version{padding:7px 11px;border:1px solid #bfdbfe;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-size:11px;font-weight:600}.version{border-color:var(--line);background:#fff;color:var(--secondary)}.avatar{width:34px;height:34px;border-radius:50%;display:grid;place-items:center;background:#dbeafe;color:#1d4ed8;font-weight:700}
|
||||
.layout{display:grid;grid-template-columns:236px minmax(720px,1fr) 310px;min-height:calc(100vh - 72px)}.sidebar{border-right:1px solid var(--line);background:#fff;padding:20px 14px}.nav-group{margin-bottom:22px}.nav-label{padding:0 11px 7px;color:#94a3b8;font-size:10px;font-weight:700;letter-spacing:.08em}.nav-item{width:100%;display:flex;align-items:center;gap:10px;padding:10px 12px;border:0;border-radius:10px;background:transparent;color:var(--secondary);text-align:left;margin:2px 0}.nav-item:hover{background:var(--soft)}.nav-item.active{background:#eaf3ff;color:#1d4ed8;font-weight:700;box-shadow:inset 3px 0 #3b82f6}.nav-icon{width:22px;text-align:center;color:#94a3b8}.nav-item.active .nav-icon{color:#2563eb}.boundary{margin-top:26px;padding:12px;border:1px solid var(--line);border-radius:12px;background:var(--soft)}.boundary b{display:block;color:var(--text);font-size:11px}.boundary p{margin:5px 0 0;color:var(--muted);font-size:10px}
|
||||
.main{min-width:0;padding:24px}.page-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:18px}.page-head h2{margin:0;color:var(--text);font-size:22px}.page-head p{margin:5px 0 0;color:var(--muted);font-size:12px}.head-actions{display:flex;gap:8px}.btn{padding:8px 12px;border:1px solid var(--line2);border-radius:9px;background:#fff;color:var(--secondary);font-size:11px;font-weight:650}.btn:hover{background:var(--soft)}.btn.primary{border-color:var(--brand);background:var(--brand);color:#fff}.btn.primary:hover{background:var(--brand2)}.btn.danger{border-color:#fecdd3;background:var(--danger-soft);color:var(--danger)}.panel{border:1px solid var(--line);border-radius:16px;background:#fff;box-shadow:var(--shadow);overflow:hidden}.panel-head{display:flex;align-items:center;justify-content:space-between;padding:15px 17px;border-bottom:1px solid var(--line)}.panel-head h3{margin:0;color:var(--text);font-size:15px}.panel-head p{margin:2px 0 0;color:var(--muted);font-size:10px}.badge{display:inline-flex;align-items:center;padding:3px 8px;border:1px solid var(--line);border-radius:999px;background:var(--soft);color:var(--muted);font-size:10px;font-weight:650}.badge.ok{border-color:#bbf7d0;background:var(--ok-soft);color:var(--ok)}.badge.warn{border-color:#fde68a;background:var(--warn-soft);color:var(--warn)}.badge.info{border-color:#bfdbfe;background:var(--brand-soft);color:#1d4ed8}.panel-body{padding:17px}.summary{display:grid;grid-template-columns:repeat(4,1fr);gap:9px;margin-bottom:16px}.stat{padding:11px 12px;border:1px solid var(--line);border-radius:11px;background:var(--soft)}.stat span{display:block;color:var(--muted);font-size:9px}.stat strong{display:block;margin-top:2px;color:var(--text);font-size:17px}.stat.warn strong{color:var(--warn)}
|
||||
.source-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.source-card{padding:14px;border:1px solid var(--line);border-radius:13px;background:#fff}.source-top{display:flex;align-items:flex-start;justify-content:space-between}.source-top h4{margin:0;color:var(--text);font-size:14px}.source-top p{margin:2px 0 0;color:var(--muted);font-size:10px}.kv{display:grid;grid-template-columns:118px 1fr;gap:10px;padding:8px 0;border-bottom:1px solid var(--line);font-size:11px}.kv:last-child{border-bottom:0}.kv span{color:var(--muted)}.kv b{text-align:right;color:var(--text)}.card-actions{display:flex;gap:7px;margin-top:11px}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:13px 15px}.field{display:grid;gap:5px}.field.full{grid-column:1/-1}.field label{color:var(--secondary);font-size:11px;font-weight:650}.field small{color:var(--muted);font-size:9px}.input,.select,.textarea{width:100%;padding:9px 10px;border:1px solid var(--line2);border-radius:9px;background:#fff;color:var(--text)}.textarea{min-height:76px;resize:vertical}.input[readonly]{background:var(--soft);color:var(--muted)}.switch-row{display:flex;align-items:center;justify-content:space-between;padding:11px 0;border-bottom:1px solid var(--line)}.switch-copy b{display:block;color:var(--text);font-size:11px}.switch-copy span{display:block;color:var(--muted);font-size:9px}.switch{width:39px;height:22px;padding:2px;border:0;border-radius:999px;background:#cbd5e1}.switch:after{content:"";display:block;width:18px;height:18px;border-radius:50%;background:#fff;transition:.15s}.switch.on{background:#2563eb}.switch.on:after{transform:translateX(17px)}.info-box{padding:11px 12px;border:1px solid #bfdbfe;border-radius:10px;background:var(--brand-soft);color:#1e40af;font-size:10px}.warn-box{padding:11px 12px;border:1px solid #fde68a;border-radius:10px;background:var(--warn-soft);color:#92400e;font-size:10px}.secret-box{display:flex;align-items:center;justify-content:space-between;padding:12px;border:1px dashed var(--line2);border-radius:11px;background:var(--soft)}.secret-box b{display:block;color:var(--text);font-size:11px}.secret-box span{display:block;color:var(--muted);font-size:9px}.secret-state{color:var(--ok)!important;font-weight:700}.table{width:100%;border-collapse:collapse;font-size:10px}.table th,.table td{padding:9px 8px;border-bottom:1px solid var(--line);text-align:left}.table th{background:var(--soft);color:var(--muted);font-weight:650}.table td{color:var(--secondary)}.table strong{color:var(--text)}
|
||||
.rail{border-left:1px solid var(--line);background:#fbfdff;padding:20px 16px}.rail h3{margin:0;color:var(--text);font-size:14px}.rail-sub{margin:2px 0 14px;color:var(--muted);font-size:10px}.release-card,.audit-card{padding:13px;border:1px solid var(--line);border-radius:13px;background:#fff;margin-bottom:12px}.release-top{display:flex;justify-content:space-between;gap:10px}.release-top b{color:var(--text);font-size:11px}.release-top span{color:var(--muted);font-size:9px}.check{display:grid;grid-template-columns:18px 1fr;gap:7px;padding:8px 0;border-bottom:1px solid var(--line)}.check:last-child{border-bottom:0}.check-dot{width:17px;height:17px;border-radius:50%;display:grid;place-items:center;background:#dcfce7;color:var(--ok);font-size:9px;font-weight:800}.check.warn .check-dot{background:#fef3c7;color:var(--warn)}.check b{display:block;color:var(--text);font-size:10px}.check span{display:block;color:var(--muted);font-size:9px}.audit-row{display:grid;grid-template-columns:12px 1fr;gap:8px;padding:7px 0}.audit-dot{width:8px;height:8px;margin-top:4px;border-radius:50%;background:#60a5fa}.audit-row b{display:block;color:var(--text);font-size:10px}.audit-row span{display:block;color:var(--muted);font-size:9px}.hidden{display:none!important}.toast{position:fixed;right:330px;bottom:24px;display:none;padding:10px 14px;border:1px solid #bbf7d0;border-radius:10px;background:var(--ok-soft);color:#166534;box-shadow:0 12px 24px -18px #0f172a;font-size:11px}.toast.show{display:block}
|
||||
@media(max-width:1450px){.layout{grid-template-columns:220px minmax(700px,1fr)}.rail{display:none}.toast{right:24px}}@media(prefers-reduced-motion:reduce){*{transition:none!important}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<header class="topbar"><div class="brand"><div class="logo">H</div><div><h1>HXOPS 管理后台</h1><p>在途仓自动调拨 · 配置与发布</p></div></div><div class="header-tools"><span class="env">测试环境</span><span class="version">已发布 V3</span><div class="avatar">管</div></div></header>
|
||||
<div class="layout">
|
||||
<aside class="sidebar">
|
||||
<div class="nav-group"><div class="nav-label">调拨配置</div>
|
||||
<button class="nav-item active" data-page="sources"><span class="nav-icon">◇</span>数据来源</button>
|
||||
<button class="nav-item" data-page="strategy"><span class="nav-icon">⌘</span>调拨策略</button>
|
||||
<button class="nav-item" data-page="mapping"><span class="nav-icon">▦</span>仓库与组织</button>
|
||||
<button class="nav-item" data-page="schedules"><span class="nav-icon">◷</span>自动排程</button>
|
||||
<button class="nav-item" data-page="notifications"><span class="nav-icon">◉</span>通知设置</button>
|
||||
</div>
|
||||
<div class="nav-group"><div class="nav-label">发布与治理</div>
|
||||
<button class="nav-item" data-page="release"><span class="nav-icon">✓</span>发布管理</button>
|
||||
<button class="nav-item" data-page="validation"><span class="nav-icon">⌁</span>连接验证</button>
|
||||
<button class="nav-item" data-page="audit"><span class="nav-icon">≡</span>配置审计</button>
|
||||
</div>
|
||||
<div class="boundary"><b>安全边界</b><p>ERP地址与凭据由环境变量或Secret注入。页面只显示配置状态,不读取或回显明文。</p></div>
|
||||
</aside>
|
||||
<main class="main"><div id="page"></div></main>
|
||||
<aside class="rail">
|
||||
<h3>草稿发布状态</h3><p class="rail-sub">当前配置集 TRANSFER-POLICY · Draft V4</p>
|
||||
<section class="release-card"><div class="release-top"><div><b>发布门禁</b><span>6项检查</span></div><span class="badge warn">1项待处理</span></div>
|
||||
<div class="check"><div class="check-dot">✓</div><div><b>DBS收料来源</b><span>已启用并绑定解析方案V3</span></div></div>
|
||||
<div class="check"><div class="check-dot">✓</div><div><b>Crane收料来源</b><span>已启用并通过Callback验证</span></div></div>
|
||||
<div class="check"><div class="check-dot">✓</div><div><b>仓库与ERP组织</b><span>映射完整且无冲突</span></div></div>
|
||||
<div class="check"><div class="check-dot">✓</div><div><b>环境变量</b><span>ERP SOAP与超时参数已注入</span></div></div>
|
||||
<div class="check warn"><div class="check-dot">!</div><div><b>通知接收人</b><span>Crane额外通知人尚未确认</span></div></div>
|
||||
<div class="check"><div class="check-dot">✓</div><div><b>配置测试</b><span>最近一次验证通过</span></div></div>
|
||||
</section>
|
||||
<section class="audit-card"><div class="release-top"><div><b>最近变更</b><span>完整Diff永久审计</span></div></div>
|
||||
<div class="audit-row"><div class="audit-dot"></div><div><b>李仓储修改调拨策略</b><span>11:08 · D+1规则未变化</span></div></div>
|
||||
<div class="audit-row"><div class="audit-dot"></div><div><b>王管理员保存排程草稿</b><span>10:42 · 并发2 → 2</span></div></div>
|
||||
<div class="audit-row"><div class="audit-dot"></div><div><b>系统完成连接验证</b><span>09:16 · DBS、Crane、ERP查询通过</span></div></div>
|
||||
</section>
|
||||
<button class="btn primary" style="width:100%" data-action="publish">校验并发布 V4</button>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
<div class="toast" id="toast">草稿已保存,并记录配置Diff与操作审计。</div>
|
||||
<script>
|
||||
const badge=(text,type='')=>`<span class="badge ${type}">${text}</span>`;
|
||||
const head=(title,desc,actions=true)=>`<div class="page-head"><div><h2>${title}</h2><p>${desc}</p></div>${actions?'<div class="head-actions"><button class="btn" data-action="discard">放弃未保存更改</button><button class="btn primary" data-action="save">保存草稿</button></div>':''}</div>`;
|
||||
const sourceCard=(code,name,driver,connectionLabel,connectionValue,file)=>`<article class="source-card"><div class="source-top"><div><h4>${name}</h4><p>${code} · ${driver}</p></div>${badge('已启用','ok')}</div><div class="kv"><span>业务用途</span><b>收料 receipt</b></div><div class="kv"><span>${connectionLabel}</span><b>${connectionValue}</b></div><div class="kv"><span>解析方案</span><b>收料汇总 V3</b></div><div class="kv"><span>当前有效文件</span><b>${file}</b></div><div class="kv"><span>固定来源仓</span><b>${code}-TRANSIT</b></div><div class="card-actions"><button class="btn" data-action="edit">编辑</button><button class="btn" data-action="test">验证配置</button><button class="btn danger" data-action="disable">停用</button></div></article>`;
|
||||
function sources(){return `${head('数据来源','复用现有库存来源管理,为 DBS、Crane 增加独立的收料用途实例。')}<div class="summary"><div class="stat"><span>收料来源</span><strong>2</strong></div><div class="stat"><span>已启用</span><strong>2</strong></div><div class="stat"><span>解析方案</span><strong>V3</strong></div><div class="stat"><span>今日Ready文件</span><strong>2 / 2</strong></div></div><section class="panel"><div class="panel-head"><div><h3>收料文件来源</h3><p>发货库存与收料是不同来源实例,配置与运行互不影响</p></div><button class="btn primary" data-action="new-source">新增收料来源</button></div><div class="panel-body"><div class="source-grid">${sourceCard('DBS','DBS 收料汇总','DBS Driver','RPA连接','DBS-RPA-PROD','receipt-dbs-20260806.xlsx')}${sourceCard('CRANE','Crane 收料汇总','HTTP Callback','接入方式','HTTP Callback','receipt-crane-20260806.xlsx')}</div></div></section>`}
|
||||
function strategy(){return `${head('调拨策略','集中定义成熟日期、数量门禁、确认及历史异常恢复规则。')}<section class="panel"><div class="panel-head"><div><h3>TRANSFER-POLICY · Draft V4</h3><p>策略修改只有发布后才影响新Run;执行中的Run继续使用冻结版本</p></div>${badge('草稿','warn')}</div><div class="panel-body"><div class="form-grid"><div class="field"><label>业务时区</label><select class="select"><option>Asia/Shanghai</option></select></div><div class="field"><label>成熟规则</label><select class="select"><option>D+1:收料日期必须早于业务日期</option></select></div><div class="field"><label>数量匹配</label><select class="select"><option>收料数量必须完全等于ERP账面库存</option></select></div><div class="field"><label>确认卡有效期</label><input class="input" value="10 分钟"></div><div class="field"><label>ERP查询超时</label><input class="input" value="60 秒" readonly><small>来源:IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS</small></div><div class="field"><label>ERP写入超时</label><input class="input" value="60 秒" readonly><small>来源:IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS</small></div><div class="field full"><div class="switch-row"><div class="switch-copy"><b>对话执行前需要一次确认</b><span>未来可配置直接执行;一期默认开启</span></div><button class="switch on" data-action="toggle"></button></div><div class="switch-row"><div class="switch-copy"><b>历史可恢复异常每日自动复核</b><span>数量不一致、ERP无库存和明确技术失败通过全门禁后创建新Attempt</span></div><button class="switch on" data-action="toggle"></button></div><div class="switch-row"><div class="switch-copy"><b>result_unknown 自动重试</b><span>高风险项只允许人工核实,一期强制关闭</span></div><button class="switch" disabled></button></div></div><div class="field"><label>老化提醒阈值</label><input class="input" value="3 天"></div><div class="field"><label>升级 / 严重积压</label><input class="input" value="5 天 / 7 天"></div><div class="field full"><div class="warn-box">策略禁止配置部分调拨、数量容差或自动重试ERP写操作。上述规则是一期开单安全门禁。</div></div></div></div></section>`}
|
||||
function mapping(){return `${head('仓库与组织','一个路由只对应一个ERP组织;来源仓固定来自来源配置,目标HUB仓由现有映射解析。')}<section class="panel"><div class="panel-head"><div><h3>组织与仓库映射</h3><p>保存时执行唯一性和完整性校验</p></div>${badge('2条有效','ok')}</div><div class="panel-body"><table class="table"><thead><tr><th>路由</th><th>ERP组织</th><th>来源实例</th><th>固定来源仓</th><th>目标HUB仓</th><th>状态</th><th>操作</th></tr></thead><tbody><tr><td><strong>DBS-TRANSFER</strong></td><td>HX-CN01</td><td>DBS收料汇总</td><td>DBS-TRANSIT</td><td>系统库存映射</td><td>${badge('有效','ok')}</td><td><button class="btn" data-action="edit">编辑</button></td></tr><tr><td><strong>CRANE-TRANSFER</strong></td><td>HX-CN01</td><td>Crane收料汇总</td><td>CRANE-TRANSIT</td><td>系统库存映射</td><td>${badge('有效','ok')}</td><td><button class="btn" data-action="edit">编辑</button></td></tr></tbody></table><div class="info-box" style="margin-top:14px">强制校验:来源实例必须唯一绑定来源仓;同一路由只能对应一个ERP组织;目标HUB仓映射缺失时整张Invoice阻断。</div></div></section>`}
|
||||
function schedules(){return `${head('自动排程','一个收料抓取排程与一个自动调拨排程;各来源在同一排程中独立并行。')}<section class="panel"><div class="panel-head"><div><h3>排程列表</h3><p>自动调拨不会假设08:00抓取成功,执行时仍会统一检查当日Ready文件</p></div><button class="btn primary" data-action="new-schedule">新增排程</button></div><div class="panel-body"><div class="source-grid"><article class="source-card"><div class="source-top"><div><h4>每日收料文件抓取</h4><p>SCH-RECEIPT-0800</p></div>${badge('运行中','ok')}</div><div class="kv"><span>Cron</span><b>每天 08:00</b></div><div class="kv"><span>来源</span><b>DBS、Crane · 并发2</b></div><div class="kv"><span>输出</span><b>当日最新Ready收料文件</b></div><div class="kv"><span>最近运行</span><b>成功 · 08:03:12</b></div><div class="card-actions"><button class="btn" data-action="edit">编辑</button><button class="btn" data-action="run">立即运行</button><button class="btn danger" data-action="disable">停用</button></div></article><article class="source-card"><div class="source-top"><div><h4>每日自动调拨</h4><p>SCH-TRANSFER-0900</p></div>${badge('运行中','ok')}</div><div class="kv"><span>Cron</span><b>每天 09:00</b></div><div class="kv"><span>处理范围</span><b>DBS、Crane与历史待办</b></div><div class="kv"><span>ERP并发</span><b>查询2 · 写入1</b></div><div class="kv"><span>通知</span><b>每次非空Run一条汇总</b></div><div class="card-actions"><button class="btn" data-action="edit">编辑</button><button class="btn" data-action="run">立即运行</button><button class="btn danger" data-action="disable">停用</button></div></article></div></div></section>`}
|
||||
function notifications(){return `${head('通知设置','自动排程完成后向任务所有者及额外通知人发送一次汇总;通知结果与ERP业务结果分离。')}<section class="panel"><div class="panel-head"><div><h3>企业微信通知</h3><p>空数据不通知,通知失败记录 notification_failed 且不自动重试</p></div>${badge('已启用','ok')}</div><div class="panel-body"><div class="form-grid"><div class="field"><label>任务所有者</label><input class="input" value="李仓储(li.cangchu)"></div><div class="field"><label>额外通知人员</label><input class="input" value="王仓管、陈主管"></div><div class="field"><label>通知粒度</label><select class="select"><option>每次自动调拨排程一条汇总</option></select></div><div class="field"><label>异常附件</label><select class="select"><option>一份七Sheet异常Excel</option></select></div><div class="field full"><div class="switch-row"><div class="switch-copy"><b>全部成功也发送通知</b><span>非空Run均发送结果汇总</span></div><button class="switch on" data-action="toggle"></button></div><div class="switch-row"><div class="switch-copy"><b>空数据发送通知</b><span>一期关闭;只保留success + no_data审计</span></div><button class="switch" data-action="toggle"></button></div></div><div class="field full"><div class="info-box">通知接收人取任务所有者与来源配置通知人的去重合集。附件失败时仍发送文本摘要,并记录失败原因。</div></div></div></div></section>`}
|
||||
function release(){return `${head('发布管理','配置以草稿、校验、发布的方式生效;不允许直接修改生产有效版本。',false)}<section class="panel"><div class="panel-head"><div><h3>Draft V4 与 Published V3</h3><p>发布后新Run绑定V4,已存在Run继续使用V3冻结快照</p></div>${badge('待校验','warn')}</div><div class="panel-body"><table class="table"><thead><tr><th>配置项</th><th>发布版本 V3</th><th>草稿 V4</th><th>变化</th></tr></thead><tbody><tr><td>Crane额外通知人</td><td>王仓管</td><td>王仓管、陈主管</td><td>${badge('已修改','info')}</td></tr><tr><td>历史恢复</td><td>开启</td><td>开启</td><td>无变化</td></tr><tr><td>确认有效期</td><td>10分钟</td><td>10分钟</td><td>无变化</td></tr><tr><td>ERP写并发</td><td>1</td><td>1</td><td>环境变量</td></tr></tbody></table><div class="card-actions"><button class="btn" data-action="validate">运行发布校验</button><button class="btn primary" data-action="publish">发布 V4</button><button class="btn" data-action="diff">查看完整Diff</button></div></div></section>`}
|
||||
function validation(){return `${head('连接验证','验证RPA、Callback、解析和ERP只读查询;禁止从配置页发起ERP写入测试。',false)}<section class="panel"><div class="panel-head"><div><h3>最近一次配置验证</h3><p>TEST-TRANSFER-20260806-0916 · 使用测试环境</p></div>${badge('全部通过','ok')}</div><div class="panel-body"><table class="table"><thead><tr><th>检查项</th><th>范围</th><th>耗时</th><th>结果</th><th>证据</th></tr></thead><tbody><tr><td><strong>DBS RPA连接</strong></td><td>登录与报表定位</td><td>8.4s</td><td>${badge('通过','ok')}</td><td>脱敏日志</td></tr><tr><td><strong>Crane Callback</strong></td><td>身份、operation_id</td><td>1.2s</td><td>${badge('通过','ok')}</td><td>请求摘要Hash</td></tr><tr><td><strong>收料解析</strong></td><td>四字段与多行汇总</td><td>0.8s</td><td>${badge('通过','ok')}</td><td>样本结果</td></tr><tr><td><strong>ERP SOAP查询</strong></td><td>测试Invoice只读查询</td><td>2.1s</td><td>${badge('通过','ok')}</td><td>脱敏响应</td></tr><tr><td><strong>ERP写权限</strong></td><td>配置页面</td><td>-</td><td>${badge('禁止','warn')}</td><td>安全门禁</td></tr></tbody></table><div class="card-actions"><button class="btn primary" data-action="test">重新验证</button><button class="btn" data-action="download">下载验证报告</button></div></div></section>`}
|
||||
function audit(){return `${head('配置审计','查询、查看、保存、校验、发布和停用均记录操作人、时间、内容及变更前后快照。',false)}<section class="panel"><div class="panel-head"><div><h3>配置审计日志</h3><p>大型快照归档MinIO,数据库永久保留摘要、Hash和对象路径</p></div><button class="btn" data-action="export">导出审计</button></div><div class="panel-body"><table class="table"><thead><tr><th>时间</th><th>操作人</th><th>操作</th><th>对象</th><th>版本</th><th>变更摘要</th><th>结果</th></tr></thead><tbody><tr><td>11:08:26</td><td>李仓储</td><td>保存草稿</td><td>调拨策略</td><td>Draft V4</td><td>before/after Hash已保存</td><td>${badge('成功','ok')}</td></tr><tr><td>10:42:11</td><td>王管理员</td><td>修改排程</td><td>SCH-TRANSFER-0900</td><td>Draft V4</td><td>通知人员变更</td><td>${badge('成功','ok')}</td></tr><tr><td>09:16:44</td><td>系统</td><td>配置验证</td><td>全部连接</td><td>Published V3</td><td>4通过、1禁止</td><td>${badge('成功','ok')}</td></tr><tr><td>08:51:03</td><td>赵管理员</td><td>查看详情</td><td>DBS收料来源</td><td>Published V3</td><td>只读访问已审计</td><td>${badge('成功','ok')}</td></tr></tbody></table></div></section>`}
|
||||
const pages={sources,strategy,mapping,schedules,notifications,release,validation,audit};let active='sources';
|
||||
function bind(){document.querySelectorAll('[data-action]').forEach(el=>el.onclick=()=>{if(el.classList.contains('switch'))el.classList.toggle('on');const t=document.getElementById('toast');t.textContent=el.dataset.action==='publish'?'发布校验已启动;通过后将生成新版本并写入完整审计。':el.dataset.action==='test'?'已创建只读配置验证任务,不会调用ERP写接口。':'草稿已保存,并记录配置Diff与操作审计。';t.classList.add('show');setTimeout(()=>t.classList.remove('show'),2400)})}
|
||||
function show(id){active=pages[id]?id:'sources';document.getElementById('page').innerHTML=pages[active]();document.querySelectorAll('[data-page]').forEach(el=>el.classList.toggle('active',el.dataset.page===active));bind();const url=new URL(location.href);url.searchParams.set('page',active);history.replaceState(null,'',url)}
|
||||
document.querySelectorAll('[data-page]').forEach(el=>el.onclick=()=>show(el.dataset.page));show(new URLSearchParams(location.search).get('page')||'sources');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,77 @@
|
||||
<!--
|
||||
docs/prototype/in-transit-transfer-agent-mvp.html
|
||||
用途:在现有 HXOPS Chat UI 中演示在途仓自动调拨 Agent 一期最小业务闭环。
|
||||
依赖:独立 HTML、CSS、原生 JavaScript;视觉结构参考 ChatShell、ChatSidebar、ChatMessageList、ChatInputBar。
|
||||
逻辑:左侧历史会话用于切换核心业务状态;消息卡只模拟交互,不调用真实 RPA、ERP 或企业微信。
|
||||
-->
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>HXOPS · 在途仓自动调拨 Agent MVP</title>
|
||||
<style>
|
||||
:root{--page:#f8fafc;--surface:#fff;--soft:#f1f5f9;--line:#e2e8f0;--line2:#cbd5e1;--text:#0f172a;--secondary:#334155;--muted:#64748b;--brand:#0284c7;--brand2:#e0f2fe;--brand3:#f0f9ff;--ok:#15803d;--okbg:#f0fdf4;--warn:#a16207;--warnbg:#fffbeb;--err:#be123c;--errbg:#fff1f2;--shadow:0 12px 32px -24px rgba(15,23,42,.45)}
|
||||
*{box-sizing:border-box}html,body{height:100%}body{margin:0;min-width:1100px;background:var(--page);color:var(--secondary);font:14px/1.55 "PingFang SC","Microsoft YaHei","Segoe UI",Arial,sans-serif}button,input,textarea{font:inherit}button{cursor:pointer}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:3px solid rgba(14,165,233,.25);outline-offset:2px}.hidden{display:none!important}
|
||||
.app{display:flex;height:100vh;overflow:hidden;background:var(--surface)}.sidebar{width:320px;flex:0 0 320px;display:flex;flex-direction:column;border-right:1px solid var(--line);background:rgba(255,255,255,.98)}.agent-head{display:flex;align-items:center;gap:11px;padding:17px 16px 14px}.agent-avatar{width:36px;height:36px;border-radius:12px;display:grid;place-items:center;color:#fff;background:linear-gradient(135deg,#0ea5e9,#0369a1);font-weight:800;box-shadow:0 7px 16px -9px rgba(2,132,199,.75)}.agent-name{min-width:0}.agent-name strong{display:block;color:var(--text);font-size:15px}.agent-name span{display:block;color:var(--muted);font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.collapse{margin-left:auto;border:0;background:transparent;color:#94a3b8;font-size:17px}.new-chat{margin:0 16px 13px;padding:9px 12px;border:1px solid #bae6fd;border-radius:10px;background:var(--brand3);color:#0369a1;font-weight:600;text-align:left}.history-label{display:flex;justify-content:space-between;padding:8px 17px;color:var(--muted);font-size:11px;font-weight:600}.history{flex:1;overflow:auto;padding:0 9px}.history-item{position:relative;width:100%;border:0;border-radius:9px;background:transparent;padding:10px 12px;text-align:left;color:var(--secondary);margin:1px 0}.history-item:hover{background:#f8fafc}.history-item.active{background:#f0f9ff;color:#0369a1;font-weight:600}.history-item span{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.history-item small{display:block;margin-top:2px;color:#94a3b8;font-size:10px;font-weight:400}.attention{position:absolute;right:10px;top:14px;width:7px;height:7px;border-radius:50%;background:#f59e0b}.attention.err{background:#e11d48}.sidebar-bottom{border-top:1px solid var(--line);padding:13px 15px}.agent-switch{padding:10px;border:1px solid var(--line);border-radius:12px;background:#fbfdff}.agent-switch b{display:block;color:var(--text);font-size:11px}.agent-switch span{display:block;color:var(--muted);font-size:10px;margin-top:2px}.user-row{display:flex;align-items:center;gap:9px;margin-top:12px;color:var(--secondary);font-size:11px}.user-avatar{width:28px;height:28px;border-radius:50%;display:grid;place-items:center;background:#0284c7;color:#fff;font-weight:700}.user-row i{margin-left:auto;color:#94a3b8;font-style:normal}
|
||||
.main{min-width:0;flex:1;display:flex;flex-direction:column;background:var(--surface)}.mobile-head{height:57px;display:flex;align-items:center;padding:0 22px;border-bottom:1px solid var(--line);color:var(--text);font-weight:700}.mobile-head span{margin-left:8px;color:var(--muted);font-size:11px;font-weight:400}.content-shell{min-height:0;flex:1;display:flex}.chat-column{min-width:0;flex:1;display:flex;flex-direction:column}.messages{min-height:0;flex:1;overflow:auto;background:var(--surface);padding:24px 20px 18px}.conversation{max-width:880px;margin:0 auto}.welcome{padding:42px 10px 20px;text-align:center}.welcome-logo{width:58px;height:58px;margin:0 auto 14px;border-radius:19px;display:grid;place-items:center;background:linear-gradient(135deg,#0ea5e9,#0369a1);color:#fff;font-size:21px;font-weight:800;box-shadow:0 12px 25px -16px rgba(2,132,199,.9)}.welcome h1{margin:0;color:var(--text);font-size:26px}.welcome p{margin:7px auto 0;max-width:560px;color:var(--muted);font-size:13px}.backlog{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;max-width:720px;margin:24px auto 0;text-align:left}.backlog div{padding:11px 12px;border:1px solid var(--line);border-radius:12px;background:#fff}.backlog span{display:block;color:var(--muted);font-size:9px}.backlog strong{display:block;margin-top:3px;color:var(--text);font-size:18px}.backlog .risk strong{color:#b45309}.backlog .danger strong{color:#be123c}.questions{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;max-width:720px;margin:18px auto 0}.question{border:1px solid var(--line);border-radius:12px;background:#fff;padding:12px 13px;color:var(--secondary);text-align:left;box-shadow:0 5px 16px -16px rgba(15,23,42,.6)}.question:hover{border-color:#7dd3fc;background:#f0f9ff;color:#0369a1}.question small{display:block;margin-top:3px;color:var(--muted);font-size:10px}.turn{display:flex;gap:11px;margin-bottom:18px}.turn.user{justify-content:flex-end}.turn-avatar{width:30px;height:30px;flex:0 0 30px;border-radius:50%;display:grid;place-items:center;background:#e0f2fe;color:#0369a1;font-size:11px;font-weight:700}.turn.user .turn-avatar{order:2;background:#0284c7;color:#fff}.turn-main{max-width:82%}.turn-label{margin:0 0 4px 2px;color:var(--muted);font-size:10px}.turn.user .turn-label{text-align:right;margin-right:2px}.bubble{padding:11px 14px;border:1px solid var(--line);border-radius:5px 15px 15px 15px;background:#fff;color:var(--secondary);box-shadow:0 6px 16px -15px rgba(15,23,42,.7)}.turn.user .bubble{border-color:#0284c7;border-radius:15px 5px 15px 15px;background:#0284c7;color:#fff}.system-pill{width:max-content;max-width:90%;margin:0 auto 18px;padding:5px 10px;border:1px solid var(--line);border-radius:999px;background:#fff;color:var(--muted);font-size:10px}
|
||||
.card{margin:5px 41px 18px;border:1px solid #bae6fd;border-radius:14px;background:#fff;overflow:hidden;box-shadow:var(--shadow)}.card-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;padding:13px 15px;border-bottom:1px solid #bae6fd;background:linear-gradient(135deg,#f0f9ff,#fff)}.card-title{display:flex;gap:9px;align-items:flex-start}.card-icon{width:28px;height:28px;flex:0 0 28px;border-radius:9px;display:grid;place-items:center;background:#e0f2fe;color:#0369a1;font-weight:800}.card-head h3{margin:0;color:var(--text);font-size:14px}.card-head p{margin:2px 0 0;color:var(--muted);font-size:10px}.badge{display:inline-flex;align-items:center;white-space:nowrap;padding:3px 8px;border:1px solid transparent;border-radius:999px;font-size:10px;font-weight:600}.badge.info{color:#0369a1;border-color:#bae6fd;background:#f0f9ff}.badge.ok{color:#15803d;border-color:#bbf7d0;background:#f0fdf4}.badge.warn{color:#a16207;border-color:#fde68a;background:#fffbeb}.badge.err{color:#be123c;border-color:#fecdd3;background:#fff1f2}.badge.muted{color:#64748b;border-color:#e2e8f0;background:#f8fafc}.card-body{padding:13px 15px}.summary-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}.summary-item{padding:9px 10px;border:1px solid var(--line);border-radius:10px;background:#fbfdff}.summary-item span{display:block;color:var(--muted);font-size:9px}.summary-item strong{display:block;margin-top:2px;color:var(--text);font-size:15px}.summary-item.warn strong{color:#b45309}.summary-item.err strong{color:#be123c}.data-rows{margin-top:6px}.data-row{display:grid;grid-template-columns:150px 1fr;gap:12px;padding:8px 0;border-bottom:1px solid var(--line);font-size:11px}.data-row:last-child{border-bottom:0}.data-row span{color:var(--muted)}.data-row strong{text-align:right;color:var(--text)}.stage-list{display:grid;gap:1px}.stage{display:grid;grid-template-columns:28px 160px 1fr auto;align-items:center;gap:10px;padding:9px 0;border-bottom:1px solid var(--line);font-size:11px}.stage:last-child{border-bottom:0}.stage-dot{width:22px;height:22px;border-radius:50%;display:grid;place-items:center;background:#f1f5f9;color:#94a3b8;font-size:10px;font-weight:700}.stage.success .stage-dot{background:#dcfce7;color:#15803d}.stage.running .stage-dot{background:#e0f2fe;color:#0284c7}.stage.failed .stage-dot{background:#ffe4e6;color:#be123c}.stage b{color:var(--text)}.stage small{color:var(--muted)}.source-box{margin-top:10px;display:grid;grid-template-columns:repeat(2,1fr);gap:8px}.source{padding:10px 11px;border:1px solid var(--line);border-radius:10px;background:#fbfdff}.source-top{display:flex;justify-content:space-between;align-items:center}.source b{color:var(--text);font-size:11px}.source p{margin:5px 0 0;color:var(--muted);font-size:10px}.progress-track{height:6px;margin-top:8px;border-radius:999px;background:#e2e8f0;overflow:hidden}.progress-fill{height:100%;border-radius:999px;background:#0ea5e9}.notice{margin:0 41px 16px;padding:10px 12px;border:1px solid #fde68a;border-radius:11px;background:#fffbeb;color:#92400e;font-size:11px}.notice.err{border-color:#fecdd3;background:#fff1f2;color:#9f1239}.notice.ok{border-color:#bbf7d0;background:#f0fdf4;color:#166534}.card-actions{display:flex;gap:8px;flex-wrap:wrap;padding:0 15px 14px}.btn{padding:7px 11px;border:1px solid var(--line2);border-radius:9px;background:#fff;color:var(--secondary);font-size:11px;font-weight:600}.btn:hover{background:#f8fafc}.btn.primary{border-color:#0284c7;background:#0284c7;color:#fff}.btn.danger{border-color:#fda4af;background:#fff1f2;color:#be123c}.invoice-table{width:100%;border-collapse:collapse;font-size:10px}.invoice-table th,.invoice-table td{padding:8px 7px;border-bottom:1px solid var(--line);text-align:left}.invoice-table th{color:var(--muted);background:#f8fafc;font-weight:600}.invoice-table input{accent-color:#0284c7}.invoice-table tr.blocked{color:#94a3b8;background:#fffaf5}.audit{display:grid}.audit-row{display:grid;grid-template-columns:55px 15px 1fr;gap:8px;align-items:start;padding:7px 0;font-size:10px}.audit-row time{color:var(--muted)}.audit-line{position:relative;width:8px;height:8px;margin-top:4px;border-radius:50%;background:#38bdf8}.audit-line:after{content:"";position:absolute;left:3px;top:9px;width:1px;height:23px;background:#dbeafe}.audit-row:last-child .audit-line:after{display:none}.audit-row b{display:block;color:var(--text)}.audit-row span{display:block;color:var(--muted);margin-top:1px}.action-feedback{display:none;margin:0 41px 16px;padding:10px 12px;border:1px solid #bbf7d0;border-radius:11px;background:#f0fdf4;color:#166534;font-size:11px}
|
||||
.input-area{padding:12px 20px 16px;background:#fff}.input-wrap{max-width:880px;margin:0 auto;border:1px solid var(--line2);border-radius:15px;background:#fff;box-shadow:0 10px 26px -24px rgba(15,23,42,.8);padding:10px 11px 8px}.input-wrap textarea{width:100%;height:42px;resize:none;border:0;outline:0;color:var(--text);background:transparent;padding:3px 4px}.input-tools{display:flex;align-items:center;gap:7px}.tool-btn{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:#64748b}.tool-btn:hover{background:#f1f5f9}.send{margin-left:auto;width:32px;height:32px;border:0;border-radius:9px;background:#0284c7;color:#fff;font-weight:800}.input-hint{max-width:880px;margin:5px auto 0;text-align:center;color:#94a3b8;font-size:9px}
|
||||
.workflow{width:310px;flex:0 0 310px;border-left:1px solid var(--line);background:#fbfdff;display:flex;flex-direction:column}.workflow-head{padding:17px 16px 13px;border-bottom:1px solid var(--line)}.workflow-head b{display:block;color:var(--text);font-size:13px}.workflow-head span{display:block;color:var(--muted);font-size:10px;margin-top:2px}.workflow-body{padding:14px;overflow:auto}.scope-card{padding:11px;border:1px solid var(--line);border-radius:11px;background:#fff}.scope-card h4{margin:0 0 8px;color:var(--text);font-size:11px}.scope-row{display:flex;justify-content:space-between;padding:5px 0;color:var(--muted);font-size:10px}.scope-row b{color:var(--secondary)}.rail{margin-top:15px}.rail-item{position:relative;padding:0 0 16px 29px}.rail-item:before{content:"";position:absolute;left:9px;top:16px;bottom:0;width:1px;background:#dbeafe}.rail-item:last-child:before{display:none}.rail-dot{position:absolute;left:1px;top:1px;width:18px;height:18px;border-radius:50%;display:grid;place-items:center;background:#e2e8f0;color:#64748b;font-size:8px;font-weight:800}.rail-item.done .rail-dot{background:#dcfce7;color:#15803d}.rail-item.active .rail-dot{background:#e0f2fe;color:#0284c7;box-shadow:0 0 0 4px #f0f9ff}.rail-item.failed .rail-dot{background:#ffe4e6;color:#be123c}.rail-item b{display:block;color:var(--text);font-size:10px}.rail-item span{display:block;color:var(--muted);font-size:9px;margin-top:2px}.workflow-foot{margin-top:auto;padding:13px;border-top:1px solid var(--line);color:var(--muted);font-size:9px}.toast{display:none;position:fixed;right:332px;bottom:24px;padding:10px 14px;border-radius:10px;background:#163349;color:#fff;box-shadow:0 12px 25px rgba(15,23,42,.22);z-index:20;font-size:11px}
|
||||
@media(max-width:1320px){.workflow{display:none}.toast{right:24px}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
<aside class="sidebar">
|
||||
<div class="agent-head"><div class="agent-avatar">AI</div><div class="agent-name"><strong>在途仓调拨 Agent</strong><span>查询并执行 DBS、Crane 在途仓调拨</span></div><button class="collapse" title="收起侧栏">‹</button></div>
|
||||
<button class="new-chat" data-scene="welcome">+ 新对话</button>
|
||||
<div class="history-label"><span>历史记录</span><span>清空</span></div>
|
||||
<div class="history" id="history"></div>
|
||||
<div class="sidebar-bottom"><div class="agent-switch"><b>可用 Agent</b><span>当前:在途仓调拨 Agent</span></div><div class="user-row"><div class="user-avatar">仓</div><span>仓库管理人员</span><i>···</i></div></div>
|
||||
</aside>
|
||||
<main class="main">
|
||||
<header class="mobile-head">在途仓调拨 Agent <span>业务写操作由 HXOPS 后端执行</span></header>
|
||||
<div class="content-shell">
|
||||
<section class="chat-column">
|
||||
<div class="messages" id="messages"><div class="conversation" id="conversation"></div></div>
|
||||
<div class="input-area"><div class="input-wrap"><textarea id="prompt" placeholder="输入问题或调拨指令,例如:查询今天可调拨数据"></textarea><div class="input-tools"><button class="tool-btn" title="附件">+</button><button class="tool-btn" title="知识库">▤</button><button class="tool-btn" title="语音">⌁</button><button class="send" id="send" title="发送">↑</button></div></div><div class="input-hint">AI 可能会出错。ERP写入前请核对确认卡中的范围、数量和预计单据数。</div></div>
|
||||
</section>
|
||||
<aside class="workflow"><div class="workflow-head"><b>本次处理</b><span id="workflow-run">等待开始</span></div><div class="workflow-body" id="workflow-body"></div><div class="workflow-foot">后台任务关闭页面后仍会继续;再次进入会话将恢复进度。</div></aside>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<div class="toast" id="toast"></div>
|
||||
<script>
|
||||
const sceneList=[
|
||||
{id:'welcome',title:'新对话',meta:'查看今日待办',dot:'warn'},
|
||||
{id:'file',title:'查询今天可调拨数据',meta:'预检完成 · 27张可执行 · 5张阻断',dot:'ok'},
|
||||
{id:'confirm',title:'执行今日可调拨项',meta:'等待用户确认',dot:'warn'},
|
||||
{id:'running',title:'RUN-20260806-0900',meta:'ERP调拨 19 / 27',dot:'info'},
|
||||
{id:'result',title:'今日自动调拨完成',meta:'27成功 · 5异常',dot:'ok'},
|
||||
{id:'exception',title:'INV-260806-019 数量异常',meta:'已积压3天',dot:'err'}
|
||||
];
|
||||
const stageNames=['理解查询范围','准备收料文件','校验并汇总Invoice','查询ERP库存','数量匹配','执行ERP调拨','生成结果与通知'];
|
||||
let active='welcome';
|
||||
const badge=(text,kind='muted')=>`<span class="badge ${kind}">${text}</span>`;
|
||||
const turn=(role,content)=>`<div class="turn ${role==='user'?'user':''}"><div class="turn-avatar">${role==='user'?'我':'AI'}</div><div class="turn-main"><div class="turn-label">${role==='user'?'仓库管理人员':'在途仓调拨助手'}</div><div class="bubble">${content}</div></div></div>`;
|
||||
const actions=(labels)=>`<div class="card-actions">${labels.map((x,i)=>`<button class="btn ${i===labels.length-1?'primary':''} proto-action">${x}</button>`).join('')}</div>`;
|
||||
const feedback=()=>`<div class="action-feedback" id="feedback"></div>`;
|
||||
function welcome(){return `<div class="welcome"><div class="welcome-logo">AI</div><h1>你好,我是在途仓调拨助手</h1><p>我会准备最新收料文件、查询ERP库存,并在你确认后执行调拨。当天收料数据不会进入调拨。</p><div class="backlog"><div><span>历史待处理</span><strong>5</strong></div><div><span>已恢复可执行</span><strong>2</strong></div><div class="danger"><span>结果未知</span><strong>1</strong></div><div class="risk"><span>超过3天</span><strong>2</strong></div></div><div class="questions"><button class="question" data-go="file">查询今天可调拨数据<small>检查最新收料文件和ERP库存</small></button><button class="question" data-go="confirm">执行今天全部可调拨项<small>先预检,再展示一次确认卡</small></button><button class="question" data-go="precheck">只查询DBS<small>限定来源进行只读预检</small></button><button class="question" data-go="exception">查看待处理异常<small>包含历史积压和结果未知</small></button></div></div>`}
|
||||
function fileScene(){return `<div class="system-pill">可处理收料日期截至 2026-08-05 · 当前业务日期 2026-08-06</div>${turn('user','查询今天有多少可以调拨。')}${turn('assistant','正在准备 DBS 和 Crane 的收料数据。我会先检查今天的有效文件,缺失来源会实时触发 RPA;完成后继续查询 ERP 库存。')}<section class="card"><div class="card-head"><div class="card-title"><div class="card-icon">↻</div><div><h3>正在准备可调拨数据</h3><p>来源级任务独立运行,DBS 与 Crane 互不影响</p></div></div>${badge('执行中','info')}</div><div class="card-body"><div class="stage-list"><div class="stage success"><div class="stage-dot">✓</div><b>理解查询范围</b><small>收料日期早于今天,且未成功、未人工关闭</small>${badge('完成','ok')}</div><div class="stage running"><div class="stage-dot">2</div><b>准备收料Excel</b><small>复用或实时抓取当前业务日期文件</small>${badge('进行中','info')}</div><div class="stage"><div class="stage-dot">3</div><b>校验并汇总</b><small>等待全部可用来源准备完成</small>${badge('等待','muted')}</div><div class="stage"><div class="stage-dot">4</div><b>查询ERP并匹配</b><small>不会查询当天未成熟收料</small>${badge('等待','muted')}</div></div><div class="source-box"><div class="source"><div class="source-top"><b>DBS</b>${badge('ready','ok')}</div><p>复用今日 08:00 文件<br>receipt-dbs-20260806.xlsx</p><div class="progress-track"><div class="progress-fill" style="width:100%"></div></div></div><div class="source"><div class="source-top"><b>Crane</b>${badge('等待Callback','info')}</div><p>未找到今日ready文件<br>RPA已领取,等待货代系统导出</p><div class="progress-track"><div class="progress-fill" style="width:48%"></div></div></div></div></div>${actions(['后台继续执行','刷新进度'])}</section><div class="notice">文件抓取在后台继续。关闭页面或切换会话不会中断任务,再次进入可恢复当前进度。</div>${feedback()}`}
|
||||
function precheckScene(){return `<div class="system-pill">文件快照已冻结 · DBS v20 · Crane v11</div>${turn('user','今天有多少可以调拨?')}${turn('assistant','文件准备和 ERP 库存查询已经完成。当天收料的 8 张 Invoice 尚未成熟,未进入 ERP 查询。')}<section class="card"><div class="card-head"><div class="card-title"><div class="card-icon">✓</div><div><h3>今日调拨预检</h3><p>收料日期截至 2026-08-05</p></div></div>${badge('预检完成','ok')}</div><div class="card-body"><div class="summary-grid"><div class="summary-item"><span>文件内Invoice</span><strong>40</strong></div><div class="summary-item warn"><span>当天收料未成熟</span><strong>8</strong></div><div class="summary-item"><span>进入ERP预检</span><strong>32</strong></div><div class="summary-item"><span>可执行</span><strong>27</strong></div><div class="summary-item err"><span>数量不一致</span><strong>3</strong></div><div class="summary-item err"><span>ERP无库存</span><strong>2</strong></div><div class="summary-item"><span>可调拨总数量</span><strong>18,460</strong></div><div class="summary-item"><span>预计ERP单据</span><strong>27</strong></div></div><div class="data-rows"><div class="data-row"><span>DBS</span><strong>15可执行 · 3阻断</strong></div><div class="data-row"><span>Crane</span><strong>12可执行 · 2阻断</strong></div><div class="data-row"><span>历史异常恢复</span><strong>2张已恢复并计入可执行</strong></div></div></div>${actions(['下载预检明细','查看Invoice','执行全部可调拨项'])}</section><div class="notice ok">只读查询到此结束,不会产生任何ERP调拨单。点击执行后仍需核对一次确认卡。</div>${feedback()}`}
|
||||
function confirmScene(){return `<div class="system-pill">确认卡有效期 10 分钟 · 当前剩余 08:42</div>${turn('user','执行今天全部可调拨项。')}${turn('assistant','请核对以下范围。阻断项不可选择,系统只会执行数量完全匹配的整张 Invoice。')}<section class="card"><div class="card-head"><div class="card-title"><div class="card-icon">!</div><div><h3>执行前确认</h3><p>文件或ERP库存变化后,本确认自动失效</p></div></div>${badge('需要确认','warn')}</div><div class="card-body"><table class="invoice-table"><thead><tr><th></th><th>Invoice</th><th>来源</th><th>收料数量</th><th>ERP库存</th><th>状态</th></tr></thead><tbody><tr><td><input type="checkbox" checked></td><td>INV-260806-001</td><td>DBS</td><td>1,200</td><td>1,200</td><td>${badge('可执行','ok')}</td></tr><tr><td><input type="checkbox" checked></td><td>INV-260806-002</td><td>DBS</td><td>800</td><td>800</td><td>${badge('可执行','ok')}</td></tr><tr class="blocked"><td><input type="checkbox" disabled></td><td>INV-260806-003</td><td>DBS</td><td>1,200</td><td>1,000</td><td>${badge('数量不一致','warn')}</td></tr><tr><td><input type="checkbox" checked></td><td>INV-260806-004</td><td>Crane</td><td>600</td><td>600</td><td>${badge('历史恢复','info')}</td></tr></tbody></table><div class="data-rows"><div class="data-row"><span>已选择</span><strong>27张 Invoice</strong></div><div class="data-row"><span>预计调拨总数量</span><strong>18,460 PCS</strong></div><div class="data-row"><span>预计ERP写入</span><strong>27张原子新建、审核、过账</strong></div></div></div>${actions(['取消','返回预检','执行调拨'])}</section><div class="notice">执行前 Worker 会重新查询 ERP 库存。变化项将标记为 precheck_expired,不会写入 ERP。</div>${feedback()}`}
|
||||
function runningScene(){return `<div class="system-pill">RUN-20260806-0900 · 后台任务持续执行</div>${turn('user','刚才的调拨执行到哪里了?')}${turn('assistant','文件、ERP库存查询和数量匹配已经完成,当前正在逐张执行ERP原子调拨。')}<section class="card"><div class="card-head"><div class="card-title"><div class="card-icon">↻</div><div><h3>自动调拨执行中</h3><p>逐项执行可执行Invoice,失败项不影响其他项</p></div></div>${badge('执行中','info')}</div><div class="card-body"><div class="summary-grid"><div class="summary-item"><span>待执行</span><strong>27</strong></div><div class="summary-item"><span>已处理</span><strong>19</strong></div><div class="summary-item"><span>成功</span><strong>18</strong></div><div class="summary-item err"><span>技术失败</span><strong>1</strong></div></div><div class="stage-list" style="margin-top:10px"><div class="stage success"><div class="stage-dot">✓</div><b>文件准备</b><small>2 / 2 来源完成</small>${badge('完成','ok')}</div><div class="stage success"><div class="stage-dot">✓</div><b>ERP库存查询</b><small>32 / 32</small>${badge('完成','ok')}</div><div class="stage success"><div class="stage-dot">✓</div><b>数量匹配</b><small>27通过 / 5阻断</small>${badge('完成','ok')}</div><div class="stage running"><div class="stage-dot">4</div><b>ERP调拨</b><small>19 / 27</small>${badge('进行中','info')}</div><div class="stage"><div class="stage-dot">5</div><b>结果与通知</b><small>等待执行结束</small>${badge('等待','muted')}</div></div><div class="source-box"><div class="source"><div class="source-top"><b>DBS</b><span>12 / 15</span></div><div class="progress-track"><div class="progress-fill" style="width:80%"></div></div></div><div class="source"><div class="source-top"><b>Crane</b><span>7 / 12</span></div><div class="progress-track"><div class="progress-fill" style="width:58%"></div></div></div></div></div>${actions(['查看Invoice明细','请求停止剩余任务'])}</section><div class="notice">请求停止只影响尚未开始的Invoice,已经成功的ERP调拨单不会撤销。</div>${feedback()}`}
|
||||
function resultScene(){return `<div class="system-pill">RUN-20260806-0900 · 09:04:38完成</div>${turn('user','今天自动调拨结果怎么样?')}${turn('assistant','本次调拨已完成。27张Invoice完成过账,其中2张来自历史异常恢复;5张仍需处理。')}<section class="card"><div class="card-head"><div class="card-title"><div class="card-icon">✓</div><div><h3>调拨完成</h3><p>企业微信已发送一条汇总通知并附异常Excel</p></div></div>${badge('部分完成','warn')}</div><div class="card-body"><div class="summary-grid"><div class="summary-item"><span>成功过账</span><strong>27</strong></div><div class="summary-item"><span>历史恢复成功</span><strong>2</strong></div><div class="summary-item"><span>重复成功</span><strong>1</strong></div><div class="summary-item"><span>调拨总数量</span><strong>18,460</strong></div><div class="summary-item err"><span>数量不一致</span><strong>3</strong></div><div class="summary-item err"><span>ERP无库存</span><strong>1</strong></div><div class="summary-item err"><span>结果未知</span><strong>1</strong></div><div class="summary-item"><span>通知</span><strong style="color:#15803d">已发送</strong></div></div><div class="data-rows"><div class="data-row"><span>DBS</span><strong>15成功 · 3阻断</strong></div><div class="data-row"><span>Crane</span><strong>12成功 · 2阻断</strong></div><div class="data-row"><span>当前历史积压</span><strong>5待处理 · 2超过3天</strong></div></div></div>${actions(['查看成功单据','查看异常详情','下载异常Excel'])}</section><div class="notice ok">通知失败只会记录 notification_failed,不会改变ERP调拨结果。</div>${feedback()}`}
|
||||
function exceptionScene(){return `<div class="system-pill">历史待处理 · 已积压3天 · 每日自动复核</div>${turn('user','INV-260806-019 为什么还没有调拨?')}${turn('assistant','该Invoice最近一次复核仍为数量不一致。系统每天会重新读取最新文件并查询ERP;满足全部门禁后会创建新Attempt自动恢复。')}<section class="card"><div class="card-head"><div class="card-title"><div class="card-icon">!</div><div><h3>INV-260806-019</h3><p>数量不一致 · DBS · 待处理</p></div></div>${badge('即将超期','warn')}</div><div class="card-body"><div class="data-rows"><div class="data-row"><span>收料文件</span><strong>receipt-dbs-20260806.xlsx</strong></div><div class="data-row"><span>Sheet / 原始行</span><strong>Receipt / 128、129</strong></div><div class="data-row"><span>汇总收料数量</span><strong>1,200 PCS</strong></div><div class="data-row"><span>ERP账面库存</span><strong>1,000 PCS</strong></div><div class="data-row"><span>最近复核</span><strong>2026-08-06 09:02:18</strong></div></div><div class="audit"><div class="audit-row"><time>08-03</time><div class="audit-line"></div><div><b>首次数量门禁阻断</b><span>Attempt 1 · RPA 1,200 / ERP 900</span></div></div><div class="audit-row"><time>08-05</time><div class="audit-line"></div><div><b>自动复核,仍未匹配</b><span>Attempt 2 · RPA 1,200 / ERP 1,000</span></div></div><div class="audit-row"><time>今天</time><div class="audit-line"></div><div><b>自动复核,结果未变化</b><span>保存摘要Hash并关联前次完整快照</span></div></div></div></div>${actions(['下载证据','手工重新预检','标记无需继续处理'])}</section><div class="notice err">result_unknown不会自动重试。数量不一致和ERP无库存仅在最新文件、库存、幂等和映射全部通过后自动恢复。</div>${feedback()}`}
|
||||
const renderers={welcome,file:fileScene,precheck:precheckScene,confirm:confirmScene,running:runningScene,result:resultScene,exception:exceptionScene};
|
||||
const railState={welcome:0,file:2,precheck:5,confirm:5,running:6,result:7,exception:5};
|
||||
function renderHistory(){const conversationScene=active==='precheck'?'file':active;document.getElementById('history').innerHTML=sceneList.slice(1).map(s=>{const isQuery=s.id==='file';const meta=isQuery&&active==='file'?'Crane 文件实时抓取中':s.meta;const dot=isQuery&&active==='file'?'info':s.dot;return `<button class="history-item ${s.id===conversationScene?'active':''}" data-scene="${s.id}"><span>${s.title}</span><small>${meta}</small>${dot==='err'?'<i class="attention err"></i>':dot==='warn'?'<i class="attention"></i>':''}</button>`}).join('');document.querySelectorAll('[data-scene]').forEach(b=>b.onclick=()=>show(b.dataset.scene));}
|
||||
function renderWorkflow(id){if(id==='welcome'){document.getElementById('workflow-run').textContent='等待开始';document.getElementById('workflow-body').innerHTML=`<div class="scope-card"><h4>调拨规则</h4><div class="scope-row"><span>成熟日期</span><b>D+1</b></div><div class="scope-row"><span>文件口径</span><b>当日最新ready</b></div><div class="scope-row"><span>数量规则</span><b>必须完全相等</b></div><div class="scope-row"><span>ERP写入</span><b>确认后执行</b></div></div>`;return}const current=railState[id];document.getElementById('workflow-run').textContent=id==='running'?'RUN-20260806-0900':id==='result'?'RUN-20260806-0900 · 已完成':'当前会话任务';document.getElementById('workflow-body').innerHTML=`<div class="scope-card"><h4>本次范围</h4><div class="scope-row"><span>来源</span><b>DBS、Crane</b></div><div class="scope-row"><span>收料日期</span><b>截至08-05</b></div><div class="scope-row"><span>历史待办</span><b>自动带入</b></div></div><div class="rail">${stageNames.map((x,i)=>{const n=i+1;const cls=n<current?'done':n===current?'active':id==='exception'&&n===5?'failed':'';return `<div class="rail-item ${cls}"><div class="rail-dot">${n<current?'✓':n}</div><b>${x}</b><span>${n<current?'已完成':n===current?'当前阶段':'等待'}</span></div>`}).join('')}</div>`}
|
||||
function bindActions(){document.querySelectorAll('.proto-action').forEach(btn=>btn.onclick=()=>{const fb=document.getElementById('feedback');if(fb){fb.style.display='block';fb.textContent=`原型操作:已选择“${btn.textContent}”。实际系统将写入审计并按当前门禁继续。`}toast(`已选择:${btn.textContent}`)});document.querySelectorAll('[data-go]').forEach(btn=>btn.onclick=()=>show(btn.dataset.go));}
|
||||
function show(id){active=renderers[id]?id:'welcome';document.getElementById('conversation').innerHTML=renderers[active]();renderHistory();renderWorkflow(active);bindActions();document.getElementById('messages').scrollTop=0;const url=new URL(location.href);url.searchParams.set('scene',active);history.replaceState(null,'',url)}
|
||||
function toast(text){const el=document.getElementById('toast');el.textContent=text;el.style.display='block';setTimeout(()=>el.style.display='none',2200)}
|
||||
document.getElementById('send').onclick=()=>{const text=document.getElementById('prompt').value.trim();if(!text)return;document.getElementById('prompt').value='';if(/执行|调拨/.test(text))show('confirm');else if(/异常|失败|INV/.test(text))show('exception');else show('file')};document.getElementById('prompt').addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();document.getElementById('send').click()}});show(new URLSearchParams(location.search).get('scene')||'welcome');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -441,6 +441,40 @@ export const retryWorkspaceShippingOrderStpAutoCreate = (caseNo: string) =>
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 对话级「重试自动推进」:服务端扫描会话下可恢复 Case/正式 OT。
|
||||
* 核心逻辑:前端不提交对象列表;返回 summary + 逐对象 items。
|
||||
* @param conversationId - 会话 ID
|
||||
* @param reason - 可选原因码
|
||||
*/
|
||||
export const retryWorkspaceConversationAutoProgress = (
|
||||
conversationId: string,
|
||||
reason = 'user_retry_auto_progress',
|
||||
) =>
|
||||
requestJson<{
|
||||
conversation_id: string;
|
||||
summary: {
|
||||
total: number;
|
||||
retried: number;
|
||||
skipped: number;
|
||||
failed: number;
|
||||
};
|
||||
items: Array<{
|
||||
object_type: 'review_case' | 'formal_task' | string;
|
||||
object_ref: string;
|
||||
action?: string | null;
|
||||
outcome: 'queued' | 'skipped' | 'failed' | string;
|
||||
reason_code?: string | null;
|
||||
}>;
|
||||
}>(
|
||||
`/api/workspace/shipping-conversations/${encodeURIComponent(conversationId)}/retry-auto-progress`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ reason }),
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 为复核明细人工选定一个或多个已启用库存源候选。
|
||||
* 核心逻辑:携带 expected_draft_version 乐观锁;服务端写入行级 inventory_routing 后重跑资格校验。
|
||||
@@ -1034,7 +1068,21 @@ export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: F
|
||||
export async function retryWorkspaceShippingTask(taskNo: string, comment?: string) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry`,
|
||||
jsonPost(comment ? { comment } : {}),
|
||||
jsonPost(comment ? { comment, reason: comment } : { reason: 'user_retry' }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 行级统一「重试」:后端决策器选择 fetch/rematch/needs_human。
|
||||
* 核心逻辑:前端不传内部动作码。
|
||||
* @param taskNo - 正式任务号
|
||||
* @param lineKey - 行键
|
||||
*/
|
||||
export async function retryWorkspaceShippingTaskLine(taskNo: string, lineKey: string) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/lines/${encodeURIComponent(lineKey)}/retry`,
|
||||
jsonPost({ reason: 'user_retry_inventory' }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
+8
-7
@@ -78,13 +78,14 @@ const statusLabel = computed(() => {
|
||||
});
|
||||
|
||||
/**
|
||||
* 主卡重试:仅在有 task_no 且非 task_missing 时由父组件控制 showRetry。
|
||||
* 主卡重试:对象级;建单前无 task_no 也可重试 STP;正式 OT 需 task_no。
|
||||
*/
|
||||
const canShowRetry = computed(() => (
|
||||
Boolean(props.showRetry)
|
||||
&& !props.taskMissing
|
||||
&& Boolean(String(props.taskNo || '').trim())
|
||||
));
|
||||
const canShowRetry = computed(() => {
|
||||
if (!props.showRetry || props.taskMissing) return false;
|
||||
if (String(props.taskNo || '').trim()) return true;
|
||||
// 建单前 STP:无 OT 号也可重试。
|
||||
return String(props.automation?.phase || '').trim() !== 'post_ot_progress';
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -149,7 +150,7 @@ const canShowRetry = computed(() => (
|
||||
@click="emit('retry')"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
{{ t('chat.shippingOrderReview.autoProgress.retryStp') }}
|
||||
{{ t('chat.shippingOrderReview.autoProgress.retryObject') }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
+22
-48
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts
|
||||
* 用途:锁定库存浮层仅渲染 inventory_allowed_actions;关闭在更多操作;Teleport 菜单可见。
|
||||
* 用途:锁定行级只渲染统一「重试」与关闭;消费 retryable,不展示内部动作码。
|
||||
*/
|
||||
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
@@ -17,11 +17,8 @@ const i18n = createI18n({
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
lineOps: {
|
||||
inventoryProcessing: '库存处理',
|
||||
retryPreparation: '重试获取库存',
|
||||
retryMatching: '重新匹配库存',
|
||||
retry: '重试',
|
||||
moreActions: '更多操作',
|
||||
viewFulfillment: '查看履约详情',
|
||||
},
|
||||
fulfillmentDecision: {
|
||||
closeLine: '关闭该明细',
|
||||
@@ -32,11 +29,12 @@ const i18n = createI18n({
|
||||
},
|
||||
});
|
||||
|
||||
function mountOps(line: Partial<ShippingOrderReviewLineFulfillmentLine>) {
|
||||
function mountOps(line: Partial<ShippingOrderReviewLineFulfillmentLine>, extra: Record<string, unknown> = {}) {
|
||||
return mount(ReviewLineInventoryOps, {
|
||||
props: {
|
||||
line: line as ShippingOrderReviewLineFulfillmentLine,
|
||||
editable: true,
|
||||
...extra,
|
||||
},
|
||||
attachTo: document.body,
|
||||
global: { plugins: [i18n] },
|
||||
@@ -48,68 +46,44 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('ReviewLineInventoryOps', () => {
|
||||
it('shows only preparation when matching not allowed', async () => {
|
||||
it('shows unified retry when retryable', async () => {
|
||||
const wrapper = mountOps({
|
||||
inventory_allowed_actions: ['retry_inventory_preparation'],
|
||||
retryable: true,
|
||||
line_allowed_actions: [],
|
||||
});
|
||||
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
|
||||
expect(document.querySelector('[data-testid="review-line-retry-preparation"]')).toBeTruthy();
|
||||
expect(document.querySelector('[data-testid="review-line-retry-matching"]')).toBeFalsy();
|
||||
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeFalsy();
|
||||
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(true);
|
||||
await wrapper.get('[data-testid="review-line-retry"]').trigger('click');
|
||||
expect(wrapper.emitted('retry-line')?.length).toBe(1);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('puts close under more actions, not inventory panel', async () => {
|
||||
it('hides retry when not retryable even if internal actions present', () => {
|
||||
const wrapper = mountOps({
|
||||
inventory_allowed_actions: ['retry_inventory_preparation'],
|
||||
retryable: false,
|
||||
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
|
||||
line_allowed_actions: ['close_unfulfillable'],
|
||||
});
|
||||
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
|
||||
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeFalsy();
|
||||
await wrapper.get('[data-testid="review-line-more-actions"]').trigger('click');
|
||||
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeTruthy();
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('hides inventory icon when no inventory actions and no problem status', () => {
|
||||
const wrapper = mountOps({
|
||||
inventory_allowed_actions: [],
|
||||
line_allowed_actions: ['close_unfulfillable'],
|
||||
user_line_status: 'inventory_matched',
|
||||
inventory_status: 'ready',
|
||||
display_available: '50',
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-line-view-inventory"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-line-more-actions"]').exists()).toBe(true);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('shows inventory icon from problem status even when backend actions empty', async () => {
|
||||
it('disables retry while task running', () => {
|
||||
const wrapper = mountOps({
|
||||
inventory_allowed_actions: [],
|
||||
retryable: true,
|
||||
line_allowed_actions: [],
|
||||
user_line_status: 'inventory_pending',
|
||||
inventory_status: 'preparing',
|
||||
display_available: 'pending',
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-line-view-inventory"]').exists()).toBe(true);
|
||||
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
|
||||
expect(document.querySelector('[data-testid="review-line-retry-preparation"]')).toBeTruthy();
|
||||
}, { taskRunning: true });
|
||||
expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('emits retry-inventory for both floating actions', async () => {
|
||||
it('puts close under more actions', async () => {
|
||||
const wrapper = mountOps({
|
||||
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
|
||||
line_allowed_actions: [],
|
||||
retryable: false,
|
||||
line_allowed_actions: ['close_unfulfillable'],
|
||||
});
|
||||
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
|
||||
expect(document.querySelector('[data-testid="review-line-retry-preparation"]')).toBeTruthy();
|
||||
expect(document.querySelector('[data-testid="review-line-retry-matching"]')).toBeTruthy();
|
||||
(document.querySelector('[data-testid="review-line-retry-matching"]') as HTMLButtonElement).click();
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(wrapper.emitted('retry-inventory')?.[0]).toEqual(['retry_inventory_matching']);
|
||||
await wrapper.get('[data-testid="review-line-more-actions"]').trigger('click');
|
||||
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeTruthy();
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
@@ -1,118 +1,55 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLineInventoryOps.vue
|
||||
用途:明细行库存处理浮层 + 行级更多操作(关闭);不进库存工作台、不在右侧挂动作。
|
||||
依赖:vue-i18n、lucide、line.inventory_allowed_actions / line_allowed_actions。
|
||||
逻辑:优先后端动作;库存问题态后端漏下发时前端兜底 preparation(+匹配失败时 matching);
|
||||
菜单 Teleport 到 body,避免表格 overflow 裁切。
|
||||
用途:明细行统一「重试」+ 更多操作(关闭);不进库存工作台。
|
||||
依赖:vue-i18n、lucide、line.retryable / line_allowed_actions。
|
||||
逻辑:只消费 retryable 布尔与 close 动作;不展示内部动作码;不发具体节点。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { MoreHorizontal, Warehouse } from 'lucide-vue-next';
|
||||
import { MoreHorizontal, RefreshCw } from 'lucide-vue-next';
|
||||
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
line: ShippingOrderReviewLineFulfillmentLine | null | undefined;
|
||||
editable: boolean;
|
||||
busy?: boolean;
|
||||
/** 任务整体 queued/running 时禁用行级写 */
|
||||
taskRunning?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'retry-inventory': [actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching'];
|
||||
'retry-line': [];
|
||||
'close-line': [];
|
||||
'view-fulfillment': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const inventoryMenuOpen = ref(false);
|
||||
const moreMenuOpen = ref(false);
|
||||
const inventoryBtnRef = ref<HTMLElement | null>(null);
|
||||
const moreBtnRef = ref<HTMLElement | null>(null);
|
||||
const inventoryMenuStyle = ref<Record<string, string>>({});
|
||||
const moreMenuStyle = ref<Record<string, string>>({});
|
||||
|
||||
const PROBLEM_USER_STATUSES = new Set([
|
||||
'inventory_file_missing',
|
||||
'inventory_file_expired',
|
||||
'inventory_match_failed',
|
||||
'inventory_source_unrecognized',
|
||||
'source_conflict',
|
||||
'shortage',
|
||||
'inventory_pending',
|
||||
'acquiring_inventory',
|
||||
'auto_fulfill_failed',
|
||||
]);
|
||||
const PROBLEM_INVENTORY_STATUSES = new Set([
|
||||
'preparing',
|
||||
'unavailable',
|
||||
'mapping_failed',
|
||||
'source_conflict',
|
||||
'invalid_key',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 库存动作集合:后端优先;问题态漏下发时兜底 preparation / matching。
|
||||
* 是否展示统一「重试」:仅后端 retryable,且任务未整体运行。
|
||||
*/
|
||||
const inventoryActions = computed(() => {
|
||||
const fromBe = [...(props.line?.inventory_allowed_actions || [])].filter(Boolean);
|
||||
if (fromBe.length) return new Set(fromBe);
|
||||
if (!props.line) return new Set<string>();
|
||||
|
||||
const userStatus = String(props.line.user_line_status || '').trim();
|
||||
const invStatus = String(props.line.inventory_status || '').trim();
|
||||
const matchResult = String(props.line.match_result || '').trim();
|
||||
const isProblem = (
|
||||
PROBLEM_USER_STATUSES.has(userStatus)
|
||||
|| PROBLEM_INVENTORY_STATUSES.has(invStatus)
|
||||
|| props.line.display_available === 'pending'
|
||||
|| Boolean(props.line.is_shortage)
|
||||
);
|
||||
if (!isProblem) return new Set<string>();
|
||||
|
||||
const actions = new Set<string>(['retry_inventory_preparation']);
|
||||
if (
|
||||
userStatus === 'inventory_match_failed'
|
||||
|| invStatus === 'mapping_failed'
|
||||
|| matchResult === 'mapping_failed'
|
||||
) {
|
||||
actions.add('retry_inventory_matching');
|
||||
}
|
||||
return actions;
|
||||
});
|
||||
|
||||
const lineActions = computed(() => {
|
||||
const fromBe = [...(props.line?.line_allowed_actions || [])].filter(Boolean);
|
||||
if (fromBe.length) return new Set(fromBe);
|
||||
const userStatus = String(props.line?.user_line_status || '').trim();
|
||||
if (!props.line) return new Set<string>();
|
||||
if (['wave_created', 'fulfilled', 'closed'].includes(userStatus)) {
|
||||
return userStatus === 'closed' ? new Set<string>() : new Set(['view_fulfillment_detail']);
|
||||
}
|
||||
if (PROBLEM_USER_STATUSES.has(userStatus) || Boolean(props.line.is_shortage)) {
|
||||
return new Set(['close_unfulfillable']);
|
||||
}
|
||||
return new Set<string>();
|
||||
});
|
||||
|
||||
const showInventoryOps = computed(() => (
|
||||
inventoryActions.value.has('retry_inventory_preparation')
|
||||
|| inventoryActions.value.has('retry_inventory_matching')
|
||||
const showRetry = computed(() => (
|
||||
Boolean(props.line?.retryable)
|
||||
&& !props.taskRunning
|
||||
));
|
||||
const canRetryPreparation = computed(() => inventoryActions.value.has('retry_inventory_preparation'));
|
||||
const canRetryMatching = computed(() => inventoryActions.value.has('retry_inventory_matching'));
|
||||
const canClose = computed(() => lineActions.value.has('close_unfulfillable'));
|
||||
const canViewFulfillment = computed(() => lineActions.value.has('view_fulfillment_detail'));
|
||||
const showMore = computed(() => canClose.value || canViewFulfillment.value);
|
||||
|
||||
const canClose = computed(() => (
|
||||
[...(props.line?.line_allowed_actions || [])].includes('close_unfulfillable')
|
||||
));
|
||||
const showMore = computed(() => canClose.value);
|
||||
|
||||
/**
|
||||
* 按触发按钮定位浮动菜单(fixed,避免被表格 overflow 裁切)。
|
||||
* 定位更多菜单。
|
||||
*/
|
||||
function placeMenu(anchor: HTMLElement | null, target: typeof inventoryMenuStyle) {
|
||||
function placeMenu(anchor: HTMLElement | null) {
|
||||
if (!anchor || typeof window === 'undefined') return;
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const width = 168;
|
||||
const left = Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8));
|
||||
target.value = {
|
||||
moreMenuStyle.value = {
|
||||
position: 'fixed',
|
||||
top: `${Math.round(rect.bottom + 4)}px`,
|
||||
left: `${Math.round(left)}px`,
|
||||
@@ -121,68 +58,31 @@ function placeMenu(anchor: HTMLElement | null, target: typeof inventoryMenuStyle
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭所有浮层。
|
||||
*/
|
||||
function closeMenus() {
|
||||
inventoryMenuOpen.value = false;
|
||||
moreMenuOpen.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文档点击/滚动时关闭浮层,避免残留遮挡。
|
||||
*/
|
||||
function onDocPointerDown(event: Event) {
|
||||
const target = event.target as Node | null;
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (!target) return;
|
||||
const el = target as HTMLElement;
|
||||
if (el.closest?.('[data-testid="review-line-inventory-panel"]')) return;
|
||||
if (el.closest?.('[data-testid="review-line-more-menu"]')) return;
|
||||
if (el.closest?.('[data-testid="review-line-view-inventory"]')) return;
|
||||
if (el.closest?.('[data-testid="review-line-more-actions"]')) return;
|
||||
if (target.closest?.('[data-testid="review-line-more-menu"]')) return;
|
||||
if (target.closest?.('[data-testid="review-line-more-actions"]')) return;
|
||||
closeMenus();
|
||||
}
|
||||
|
||||
function onViewportChange() {
|
||||
if (inventoryMenuOpen.value) placeMenu(inventoryBtnRef.value, inventoryMenuStyle);
|
||||
if (moreMenuOpen.value) placeMenu(moreBtnRef.value, moreMenuStyle);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换库存处理浮层。
|
||||
*/
|
||||
async function toggleInventoryMenu() {
|
||||
moreMenuOpen.value = false;
|
||||
inventoryMenuOpen.value = !inventoryMenuOpen.value;
|
||||
if (inventoryMenuOpen.value) {
|
||||
await nextTick();
|
||||
placeMenu(inventoryBtnRef.value, inventoryMenuStyle);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换更多操作浮层。
|
||||
*/
|
||||
async function toggleMoreMenu() {
|
||||
inventoryMenuOpen.value = false;
|
||||
moreMenuOpen.value = !moreMenuOpen.value;
|
||||
if (moreMenuOpen.value) {
|
||||
await nextTick();
|
||||
placeMenu(moreBtnRef.value, moreMenuStyle);
|
||||
placeMenu(moreBtnRef.value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发库存动作并关闭浮层。
|
||||
*/
|
||||
function onRetry(actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching') {
|
||||
closeMenus();
|
||||
emit('retry-inventory', actionCode);
|
||||
function onRetry() {
|
||||
if (props.busy || props.taskRunning || !showRetry.value) return;
|
||||
emit('retry-line');
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭明细(由父级弹确认框)。
|
||||
*/
|
||||
function onCloseLine() {
|
||||
closeMenus();
|
||||
emit('close-line');
|
||||
@@ -190,33 +90,27 @@ function onCloseLine() {
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('pointerdown', onDocPointerDown, true);
|
||||
window.addEventListener('scroll', onViewportChange, true);
|
||||
window.addEventListener('resize', onViewportChange);
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document === 'undefined') return;
|
||||
document.removeEventListener('pointerdown', onDocPointerDown, true);
|
||||
window.removeEventListener('scroll', onViewportChange, true);
|
||||
window.removeEventListener('resize', onViewportChange);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative inline-flex items-center gap-0.5">
|
||||
<button
|
||||
v-if="showInventoryOps"
|
||||
ref="inventoryBtnRef"
|
||||
v-if="showRetry"
|
||||
type="button"
|
||||
class="rounded p-1.5 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800"
|
||||
data-testid="review-line-view-inventory"
|
||||
:disabled="busy"
|
||||
:aria-label="t('chat.shippingOrderReview.lineOps.inventoryProcessing')"
|
||||
:title="t('chat.shippingOrderReview.lineOps.inventoryProcessing')"
|
||||
:aria-expanded="inventoryMenuOpen"
|
||||
@click="toggleInventoryMenu"
|
||||
class="inline-flex items-center gap-0.5 rounded border border-amber-300 bg-amber-50 px-1.5 py-0.5 text-[11px] text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-line-retry"
|
||||
:disabled="!editable || busy || taskRunning"
|
||||
:aria-label="t('chat.shippingOrderReview.lineOps.retry')"
|
||||
:title="t('chat.shippingOrderReview.lineOps.retry')"
|
||||
@click="onRetry"
|
||||
>
|
||||
<Warehouse class="h-3.5 w-3.5" aria-hidden="true" />
|
||||
<RefreshCw class="h-3 w-3" :class="busy ? 'animate-spin' : ''" aria-hidden="true" />
|
||||
{{ t('chat.shippingOrderReview.lineOps.retry') }}
|
||||
</button>
|
||||
|
||||
<button
|
||||
@@ -225,7 +119,7 @@ onBeforeUnmount(() => {
|
||||
type="button"
|
||||
class="rounded p-1.5 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800"
|
||||
data-testid="review-line-more-actions"
|
||||
:disabled="!editable || busy"
|
||||
:disabled="!editable || busy || taskRunning"
|
||||
:aria-label="t('chat.shippingOrderReview.lineOps.moreActions')"
|
||||
:title="t('chat.shippingOrderReview.lineOps.moreActions')"
|
||||
:aria-expanded="moreMenuOpen"
|
||||
@@ -235,35 +129,6 @@ onBeforeUnmount(() => {
|
||||
</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="inventoryMenuOpen && showInventoryOps"
|
||||
class="rounded-md border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-900"
|
||||
role="menu"
|
||||
data-testid="review-line-inventory-panel"
|
||||
:style="inventoryMenuStyle"
|
||||
>
|
||||
<button
|
||||
v-if="canRetryPreparation"
|
||||
type="button"
|
||||
class="block w-full px-3 py-2 text-left text-xs hover:bg-slate-50 dark:hover:bg-slate-800"
|
||||
role="menuitem"
|
||||
data-testid="review-line-retry-preparation"
|
||||
@click="onRetry('retry_inventory_preparation')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineOps.retryPreparation') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canRetryMatching"
|
||||
type="button"
|
||||
class="block w-full px-3 py-2 text-left text-xs hover:bg-slate-50 dark:hover:bg-slate-800"
|
||||
role="menuitem"
|
||||
data-testid="review-line-retry-matching"
|
||||
@click="onRetry('retry_inventory_matching')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineOps.retryMatching') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="moreMenuOpen && showMore"
|
||||
class="rounded-md border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-900"
|
||||
@@ -271,16 +136,6 @@ onBeforeUnmount(() => {
|
||||
data-testid="review-line-more-menu"
|
||||
:style="moreMenuStyle"
|
||||
>
|
||||
<button
|
||||
v-if="canViewFulfillment"
|
||||
type="button"
|
||||
class="block w-full px-3 py-2 text-left text-xs hover:bg-slate-50 dark:hover:bg-slate-800"
|
||||
role="menuitem"
|
||||
data-testid="review-line-fulfillment-detail"
|
||||
@click="closeMenus(); emit('view-fulfillment')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineOps.viewFulfillment') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canClose"
|
||||
type="button"
|
||||
|
||||
@@ -203,7 +203,7 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
data-testid="review-retry-stp-auto-create"
|
||||
@click="emit('retry-stp')"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.autoProgress.retryStp') }}
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.autoProgress.retryObject') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('validate')"
|
||||
@@ -214,17 +214,6 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
>
|
||||
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('confirm') && !hideConfirmBecauseAutoGate"
|
||||
type="button"
|
||||
:disabled="controlsBusy || !canConfirmBuild"
|
||||
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
data-testid="review-confirm-create"
|
||||
:title="!canConfirmBuild ? t('chat.shippingOrderReview.buildEligibility.confirmBlocked') : undefined"
|
||||
@click="emit('confirm')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.confirmCreate') }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewWorkbenchHeader.vue
|
||||
用途:订单复核工作台顶栏,展示标题上下文与保存状态。
|
||||
用途:订单复核工作台顶栏——对话级动作、审计/版本入口与保存状态。
|
||||
依赖:vue-i18n、lucide-vue-next。
|
||||
逻辑:ShippingOrderReviewView 传入 run/reviewProgressContext 上下文;emit back 与 open-version-history;不含对话上下文切换。
|
||||
逻辑:仅当后端 conversation_allowed_actions 含 retry_auto_progress 时渲染对话级按钮;
|
||||
审计/版本为查看入口;「已保存」为状态文本;不含单个任务单写操作。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { ArrowLeft } from 'lucide-vue-next';
|
||||
import { ArrowLeft, RefreshCw } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -19,12 +20,18 @@ const props = defineProps<{
|
||||
isReadOnly: boolean;
|
||||
showVersionHistory?: boolean;
|
||||
showAuditTrail?: boolean;
|
||||
/** 对话级「重试自动推进」;仅 eligible_count>0 时由父级置 true */
|
||||
showConversationRetry?: boolean;
|
||||
conversationRetryEligibleCount?: number;
|
||||
conversationRetrying?: boolean;
|
||||
conversationRetryDisabled?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
back: [];
|
||||
'open-version-history': [];
|
||||
'open-audit-trail': [];
|
||||
'retry-conversation-auto-progress': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -41,6 +48,11 @@ const subtitle = computed(() => {
|
||||
}
|
||||
return t('chat.shippingOrderReview.run', { runNo: props.runNo });
|
||||
});
|
||||
|
||||
const showRetry = computed(() => (
|
||||
Boolean(props.showConversationRetry)
|
||||
&& Number(props.conversationRetryEligibleCount || 0) > 0
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -57,6 +69,24 @@ const subtitle = computed(() => {
|
||||
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
|
||||
<p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ subtitle }}</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="showRetry"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-2.5 py-1.5 text-xs font-medium text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-conversation-retry-auto-progress"
|
||||
:disabled="conversationRetrying || conversationRetryDisabled || isReadOnly"
|
||||
@click="emit('retry-conversation-auto-progress')"
|
||||
>
|
||||
<RefreshCw
|
||||
class="h-3.5 w-3.5"
|
||||
:class="conversationRetrying ? 'animate-spin' : ''"
|
||||
/>
|
||||
{{ t('chat.shippingOrderReview.autoProgress.retry') }}
|
||||
<span
|
||||
v-if="conversationRetryEligibleCount"
|
||||
class="rounded bg-amber-200/80 px-1 text-[10px] dark:bg-amber-900/60"
|
||||
>{{ conversationRetryEligibleCount }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="showAuditTrail"
|
||||
type="button"
|
||||
|
||||
+9
-16
@@ -204,7 +204,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
const doneCard = wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]');
|
||||
expect(doneCard.find('[data-testid="sidebar-progress-inline"]').exists()).toBe(false);
|
||||
expect(doneCard.find('[data-testid="shipping-processing-task-actions"]').exists()).toBe(false);
|
||||
expect(doneCard.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(true);
|
||||
expect(doneCard.find('[data-testid="shipping-processing-action-view_result"]').exists()).toBe(true);
|
||||
expect(doneCard.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
@@ -241,13 +241,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(titleEl.text()).not.toContain('4518838152.pdf');
|
||||
|
||||
// UI-02:有文件对象时不双开「查看详情」与「展开文件详情」。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false);
|
||||
await wrapper.find('[data-testid="shipping-processing-expand-files"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').text()).toContain('取消整个任务');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows view_details when task cannot expand file details, and keeps cancel as overflow', async () => {
|
||||
@@ -274,10 +271,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(false);
|
||||
// 无文件对象时取消可直接挂在卡上(低频文字链,非主 CTA)。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows multi-document title from authoritative projection without workflow fallback', async () => {
|
||||
@@ -384,11 +381,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
const expandBtn = wrapper.find('[data-testid="shipping-processing-expand-files"]');
|
||||
await expandBtn.trigger('click');
|
||||
expect(wrapper.emitted('expandFiles')?.[0]?.[0]).toMatchObject({ user_task_no: 'OT-NEED' });
|
||||
await expandBtn.trigger('click');
|
||||
expect(wrapper.emitted('collapseFiles')).toBeTruthy();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders twenty processing tasks in one top-level container', async () => {
|
||||
@@ -490,12 +483,12 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(2);
|
||||
expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(1);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待复核');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('库存匹配');
|
||||
expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0);
|
||||
// UI-02:有 workItem 时仍保留展开文件详情(OT-NEED 为多文件)。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] [data-testid="shipping-processing-expand-files"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] [data-testid="shipping-processing-expand-files"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] [data-testid="shipping-processing-action-view_details"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
+36
-76
@@ -265,26 +265,28 @@ function primaryActionItem(task: ConversationProcessingUserTask): ActionPresenta
|
||||
return taskActionPresentation(task).primary;
|
||||
}
|
||||
|
||||
/** needs_action 的用户语义提示:不重复主按钮文案。 */
|
||||
function currentNeedLabel(task: ConversationProcessingUserTask): string {
|
||||
if (task.group !== 'needs_action') return '';
|
||||
const action = String(task.primary_action || task.available_actions?.[0] || '').trim().toLowerCase();
|
||||
const labels: Record<string, string> = {
|
||||
confirm_customer: 'chat.shippingProcessing.currentNeed.confirmCustomer',
|
||||
resolve_field_conflicts: 'chat.shippingProcessing.currentNeed.resolveFieldConflicts',
|
||||
open_inventory_match_review: 'chat.shippingProcessing.currentNeed.inventoryMatch',
|
||||
open_order_processing: 'chat.shippingProcessing.currentNeed.orderDraft',
|
||||
retry: 'chat.shippingProcessing.currentNeed.retry',
|
||||
retry_parse: 'chat.shippingProcessing.currentNeed.retry',
|
||||
};
|
||||
const key = labels[action];
|
||||
return key && te(key) ? t(key) : t('chat.shippingProcessing.currentNeed.generic');
|
||||
}
|
||||
|
||||
/**
|
||||
* 次要文字链:有文件对象时可展开 → 不返回 view_details(改由展开文件入口承载);
|
||||
* 无文件对象时优先 view_details,否则取非 cancel 的 presentation.secondary。
|
||||
*/
|
||||
function secondaryActionItem(task: ConversationProcessingUserTask): ActionPresentationItem | null {
|
||||
if (canExpandFileDetails(task)) return null;
|
||||
const presentation = taskActionPresentation(task);
|
||||
const candidates = [
|
||||
presentation.secondary,
|
||||
...presentation.overflow,
|
||||
].filter((item): item is ActionPresentationItem => Boolean(item));
|
||||
const viewDetails = candidates.find(
|
||||
(item) => String(item.actionCode || '').trim().toLowerCase() === 'view_details',
|
||||
);
|
||||
if (viewDetails) return viewDetails;
|
||||
const secondary = presentation.secondary;
|
||||
if (!secondary) return null;
|
||||
const code = String(secondary.actionCode || '').trim().toLowerCase();
|
||||
if (code === 'cancel_task' || code === 'cancel_run' || code === 'view_details') return null;
|
||||
return secondary;
|
||||
function secondaryActionItem(_task: ConversationProcessingUserTask): ActionPresentationItem | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -310,11 +312,8 @@ function overflowActionItems(task: ConversationProcessingUserTask): ActionPresen
|
||||
* 是否展示低频溢出:有文件对象时仅展开后显示;无文件对象时直接挂在卡上(如取消)。
|
||||
* 有 workItem 时不渲染任务级溢出(动作由进度条负责)。
|
||||
*/
|
||||
function shouldShowOverflowActions(task: ConversationProcessingUserTask): boolean {
|
||||
if (projectionForTask(task)) return false;
|
||||
if (!overflowActionItems(task).length) return false;
|
||||
if (canExpandFileDetails(task)) return isDetailsExpanded(task);
|
||||
return true;
|
||||
function shouldShowOverflowActions(_task: ConversationProcessingUserTask): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -329,15 +328,19 @@ function shouldShowTaskLevelActions(task: ConversationProcessingUserTask): boole
|
||||
* 处理记录只读卡:仅保留 view_details 文字链(无主 CTA / 取消 / 重解析)。
|
||||
*/
|
||||
function recordViewDetailsItem(task: ConversationProcessingUserTask): ActionPresentationItem | null {
|
||||
if (String(task.status_label || '').trim().toLowerCase() === 'cancelled') return null;
|
||||
const presentation = taskActionPresentation(task);
|
||||
const candidates = [
|
||||
presentation.primary,
|
||||
presentation.secondary,
|
||||
...presentation.overflow,
|
||||
].filter((item): item is ActionPresentationItem => Boolean(item));
|
||||
return candidates.find(
|
||||
(item) => String(item.actionCode || '').trim().toLowerCase() === 'view_details',
|
||||
) || null;
|
||||
return candidates.find((item) => {
|
||||
const code = String(item.actionCode || '').trim().toLowerCase();
|
||||
return code === 'view_details' || code === 'view_result';
|
||||
}) || (String(task.group || '') === 'completed'
|
||||
? { intent: 'view_result', actionCode: 'view_result', labelKey: 'chat.shippingProcessing.action.view_result' }
|
||||
: null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -591,8 +594,15 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
v-if="task.group === 'needs_action' && currentNeedLabel(task)"
|
||||
class="mt-1 text-[11px] text-secondary"
|
||||
data-testid="shipping-processing-current-need"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel(task) }}
|
||||
</div>
|
||||
<SidebarProgressInline
|
||||
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
v-if="task.group === 'processing' && progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="progressModeForTask(task) === 'compact'"
|
||||
@@ -612,57 +622,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
>
|
||||
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
data-testid="shipping-processing-expand-files"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
<ChevronRight v-else class="h-3 w-3" />
|
||||
{{ isDetailsExpanded(task)
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
<button
|
||||
v-else-if="secondaryActionItem(task)"
|
||||
type="button"
|
||||
class="text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
:data-testid="`shipping-processing-action-${secondaryActionItem(task)!.actionCode}`"
|
||||
@click="onTaskAction(task, secondaryActionItem(task)!.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, secondaryActionItem(task)!) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-else-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="mt-1.5 inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
data-testid="shipping-processing-expand-files"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
<ChevronRight v-else class="h-3 w-3" />
|
||||
{{ isDetailsExpanded(task)
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
<div
|
||||
v-if="shouldShowOverflowActions(task)"
|
||||
class="mt-1.5 flex flex-wrap gap-x-3 gap-y-1"
|
||||
data-testid="shipping-processing-task-overflow-actions"
|
||||
>
|
||||
<button
|
||||
v-for="item in overflowActionItems(task)"
|
||||
:key="`${task.user_task_no}-overflow-${item.actionCode}`"
|
||||
type="button"
|
||||
class="text-[11px] text-muted underline-offset-2 hover:text-secondary hover:underline"
|
||||
:data-testid="`shipping-processing-action-${item.actionCode}`"
|
||||
@click="onTaskAction(task, item.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, item) }}
|
||||
</button>
|
||||
<span v-if="task.group === 'needs_action'" class="sr-only">{{ currentNeedLabel(task) }}</span>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
@@ -54,7 +54,7 @@ const props = defineProps<{
|
||||
controller?: UseShippingNoticeWorkflowReturn | null;
|
||||
}>();
|
||||
|
||||
const { t, te, locale } = useI18n();
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -93,8 +93,6 @@ const ctl = computed((): UseShippingNoticeWorkflowReturn => (
|
||||
const collapsed = ref(false);
|
||||
/** 复核返回对话时展示的聚焦提示(由 focus_notice 触发一次)。 */
|
||||
const focusTaskBanner = ref<string | null>(null);
|
||||
/** 侧栏默认展示本批次全部文件,用户需要同时看到已完成与待处理状态。 */
|
||||
const pendingOnlyFilter = ref(false);
|
||||
const actionBusyItemNo = ref<string | null>(null);
|
||||
const detailOpen = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
@@ -106,28 +104,26 @@ const reasonDialogItem = ref<ShippingWorkflowItem | null>(null);
|
||||
/** 任务级取消:走 Run API,不绑单个 WorkflowItem。 */
|
||||
const reasonDialogRunNo = ref<string | null>(null);
|
||||
|
||||
/** 当前展开文件明细的 OT 任务;收起后清空。 */
|
||||
/** 移除右侧常驻批次与文件列表:文件明细改为进入订单处理工作台后展示。 */
|
||||
const expandedTask = ref<ConversationProcessingUserTask | null>(null);
|
||||
/** 文件明细:由展开任务的 document objects 合成。 */
|
||||
/** 文件行仅用于 Gate 恢复卡、路由聚焦匹配 activeItem 与 open_review 动作兜底。 */
|
||||
const items = computed((): ShippingWorkflowItem[] => (
|
||||
mapUserTaskObjectsToFileRows(expandedTask.value)
|
||||
));
|
||||
const processing = computed(() => ctl.value.processing?.value ?? null);
|
||||
const processingWorkItems = computed((): ShippingProcessingProjection[] => (
|
||||
Array.isArray(ctl.value.processingWorkItems?.value)
|
||||
? ctl.value.processingWorkItems.value
|
||||
: []
|
||||
));
|
||||
const processing = computed(() => ctl.value.processing?.value ?? null);
|
||||
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
|
||||
const displayProcessing = computed(() => processing.value);
|
||||
const loading = computed(() => ctl.value.loading.value);
|
||||
/** 初始加载:首次打开投影仍为空时显示摘要占位。 */
|
||||
const initialLoading = computed(() => Boolean(ctl.value.initialLoading?.value));
|
||||
/** 用户主动刷新(刷新按钮 / 重试 / 重解析等):驱动顶部刷新图标旋转。 */
|
||||
const manualRefreshing = computed(() => Boolean(ctl.value.manualRefreshing?.value));
|
||||
const error = computed(() => ctl.value.error.value);
|
||||
/** 用户从任务卡展开后,按任务内当前有效 PDF 身份过滤;旧数据才回退到 run_no。 */
|
||||
const fileFilterRunNo = ref<string | null>(null);
|
||||
const fileFilterDocumentKeys = ref<Set<string>>(new Set());
|
||||
/** 任务卡明确展开文件详情时为 true(有任务卡时才约束显隐)。 */
|
||||
const filesDetailVisible = ref(false);
|
||||
/** 路由或复核返回的权威 OT 聚焦号。 */
|
||||
const routeFocusedTaskNo = computed(() => String(
|
||||
route.query.focus_task_no
|
||||
|| focusTaskBanner.value
|
||||
@@ -155,53 +151,6 @@ const activeItem = computed(() => {
|
||||
}) || items.value.find((item) => resolveItemDisplayStatus(item) === 'pending_review') || items.value[0] || null;
|
||||
});
|
||||
|
||||
const visibleItems = computed(() => {
|
||||
const documentKeys = fileFilterDocumentKeys.value;
|
||||
if (documentKeys.size) {
|
||||
return items.value.filter((item) => workflowItemDocumentKeys(item).some(
|
||||
(key) => documentKeys.has(key),
|
||||
));
|
||||
}
|
||||
const runNo = String(fileFilterRunNo.value || '').trim();
|
||||
if (!runNo) return items.value;
|
||||
return items.value.filter((item) => String(item.current_run_no || '').trim() === runNo);
|
||||
});
|
||||
|
||||
/**
|
||||
* 解析 WorkflowItem 的 PDF 身份候选,顺序与后端聚合契约一致。
|
||||
* @param item - 侧栏 WorkflowItem
|
||||
* @returns 可用于匹配任务文档对象的稳定身份键列表
|
||||
*/
|
||||
function workflowItemDocumentKeys(item: ShippingWorkflowItem): string[] {
|
||||
const keys: string[] = [];
|
||||
const hash = String(item.content_hash || '').trim().toLowerCase();
|
||||
const rootId = Number(item.root_document_id || 0);
|
||||
const documentId = Number(item.current_document_id || 0);
|
||||
if (hash) keys.push(`hash:${hash}`);
|
||||
if (rootId > 0) keys.push(`root:${rootId}`);
|
||||
if (documentId > 0) keys.push(`doc:${documentId}`);
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析任务投影内当前有效 PDF 身份,用于跨 Run 展开完整文件集合。
|
||||
* @param task - 用户可见任务卡
|
||||
* @returns 当前有效 PDF 的稳定身份键集合
|
||||
*/
|
||||
function taskDocumentKeys(task: ConversationProcessingUserTask): Set<string> {
|
||||
const keys = new Set<string>();
|
||||
for (const object of task.objects || []) {
|
||||
if (object.kind !== 'document') continue;
|
||||
const hash = String(object.content_hash || '').trim().toLowerCase();
|
||||
const rootId = Number(object.root_document_id || 0);
|
||||
const documentId = Number(object.document_id || 0);
|
||||
if (hash) keys.add(`hash:${hash}`);
|
||||
if (rootId > 0) keys.add(`root:${rootId}`);
|
||||
if (documentId > 0) keys.add(`doc:${documentId}`);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** 任务聚合投影存在时隐藏独立「当前阶段」卡,避免三套状态重复(UI-F04)。 */
|
||||
const showStandaloneCurrentStage = computed(() => {
|
||||
const projection = displayProcessing.value;
|
||||
@@ -248,12 +197,9 @@ watch(
|
||||
);
|
||||
|
||||
/**
|
||||
* 文件列表显隐:有用户任务卡时仅展开后显示;无任务卡时不展示空壳文件抽屉。
|
||||
* 移除右侧常驻「批次与文件列表」长列表抽屉(UI-REFACTOR 方案 7)。
|
||||
* 文件明细进入订单处理工作台后展示;此处仅保留 Gate 卡与独立 DetailDrawer,避免两套投影矛盾与高度抖动。
|
||||
*/
|
||||
const showFilesDrawer = computed(() => {
|
||||
if (collapsed.value) return false;
|
||||
return filesDetailVisible.value && Boolean(expandedTask.value);
|
||||
});
|
||||
|
||||
function itemActivityLabel(item: ShippingWorkflowItem | null): string {
|
||||
if (!item) return t('chat.shippingProcessing.emptyCompact');
|
||||
@@ -357,25 +303,28 @@ async function onProcessingFocus(taskNo: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 展开任务文件详情:优先按任务内当前有效 PDF 集合过滤;旧投影回退到代表 run_no。
|
||||
* 展开文件详情 → 直接进入订单处理工作台(方案 7:移除右侧常驻文件列表)。
|
||||
* 文件明细在工作台展示;此处仍保留 expandedTask 以便 Gate 卡找到聚焦 Run。
|
||||
* 无 run_no 时 toast 提示,禁止静默 return。
|
||||
*/
|
||||
function onExpandTaskFiles(task: ConversationProcessingUserTask) {
|
||||
async function onExpandTaskFiles(task: ConversationProcessingUserTask) {
|
||||
const runNo = String(task.run_no || '').trim();
|
||||
const documentKeys = taskDocumentKeys(task);
|
||||
expandedTask.value = task;
|
||||
fileFilterDocumentKeys.value = documentKeys;
|
||||
fileFilterRunNo.value = documentKeys.size ? null : (runNo || null);
|
||||
filesDetailVisible.value = true;
|
||||
// 走原有工作台入口,保持与「继续处理」按钮一致;失败则静默(仍保留本地聚焦)。
|
||||
if (runNo) {
|
||||
try {
|
||||
await openReviewFromTask(task);
|
||||
} catch {
|
||||
/* 路由失败不阻塞,交由上层统一错误处理。 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 收起任务文件详情:清空过滤并隐藏下方文件列表。
|
||||
* 收起文件详情:仅清空本地过滤聚焦态,右侧不再常驻文件长列表。
|
||||
*/
|
||||
function onCollapseTaskFiles() {
|
||||
expandedTask.value = null;
|
||||
fileFilterRunNo.value = null;
|
||||
fileFilterDocumentKeys.value = new Set();
|
||||
filesDetailVisible.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -461,104 +410,6 @@ async function onProcessingTaskAction(payload: {
|
||||
}
|
||||
}
|
||||
|
||||
type ItemGroupKey =
|
||||
| 'processing'
|
||||
| 'queued'
|
||||
| 'completed'
|
||||
| 'pending_review'
|
||||
| 'failed'
|
||||
| 'waiting_manual_upload';
|
||||
|
||||
const PROCESSING_STATUSES = new Set([
|
||||
'layout_parsing',
|
||||
'extracting',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
]);
|
||||
const QUEUED_STATUSES = new Set(['queued']);
|
||||
const FAILED_STATUSES = new Set(['failed', 'reparse_failed']);
|
||||
/** 真正完成/取消;待人工登记不是完成。 */
|
||||
const COMPLETED_STATUSES = new Set(['closed', 'cancelled']);
|
||||
const WAITING_MANUAL_UPLOAD_STATUSES = new Set(['manual_upload_pending']);
|
||||
const UPLOAD_RPA_RUNNING_STATUSES = new Set(['upload_rpa_pending', 'upload_rpa_running']);
|
||||
const PENDING_REVIEW_STATUSES = new Set(['pending_review']);
|
||||
const ACTIONABLE_FILTER_STATUSES = new Set([
|
||||
'pending_review',
|
||||
'failed',
|
||||
'reparse_failed',
|
||||
'queued',
|
||||
'manual_upload_pending',
|
||||
'upload_rpa_pending',
|
||||
'upload_rpa_running',
|
||||
'upload_rpa_failed',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 将 Item 归入展示分组;优先 is_waiting_manual_upload / display(禁止单靠 lifecycle 推断人工待办)。
|
||||
*/
|
||||
function resolveGroup(item: ShippingWorkflowItem): ItemGroupKey {
|
||||
const display = resolveItemDisplayStatus(item);
|
||||
if (PENDING_REVIEW_STATUSES.has(display)) return 'pending_review';
|
||||
if (FAILED_STATUSES.has(display) || display === 'upload_rpa_failed') return 'failed';
|
||||
if (UPLOAD_RPA_RUNNING_STATUSES.has(display)) return 'processing';
|
||||
if (item.is_waiting_manual_upload === true || item.upload_phase === 'manual_pending') {
|
||||
return 'waiting_manual_upload';
|
||||
}
|
||||
if (WAITING_MANUAL_UPLOAD_STATUSES.has(display) && item.is_waiting_manual_upload !== false) {
|
||||
return 'waiting_manual_upload';
|
||||
}
|
||||
const status = String(item.lifecycle_status || '').trim();
|
||||
if (PENDING_REVIEW_STATUSES.has(status)) return 'pending_review';
|
||||
if (FAILED_STATUSES.has(status)) return 'failed';
|
||||
if (
|
||||
item.is_waiting_manual_upload !== false
|
||||
&& WAITING_MANUAL_UPLOAD_STATUSES.has(status)
|
||||
&& !UPLOAD_RPA_RUNNING_STATUSES.has(display)
|
||||
&& display !== 'upload_rpa_failed'
|
||||
&& item.upload_phase !== 'rpa_pending'
|
||||
&& item.upload_phase !== 'rpa_running'
|
||||
&& item.upload_phase !== 'rpa_failed'
|
||||
) {
|
||||
return 'waiting_manual_upload';
|
||||
}
|
||||
if (COMPLETED_STATUSES.has(status)) return 'completed';
|
||||
if (QUEUED_STATUSES.has(status)) return 'queued';
|
||||
if (PROCESSING_STATUSES.has(status)) return 'processing';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否允许取消:优先后端 available_actions;无 Run 时隐藏(co8 Workflow Item API 已下线)。
|
||||
*/
|
||||
function canCancel(item: ShippingWorkflowItem): boolean {
|
||||
if (!String(item.current_run_no || '').trim()) return false;
|
||||
const actions = item.available_actions;
|
||||
if (Array.isArray(actions)) return actions.includes('cancel');
|
||||
return !COMPLETED_STATUSES.has(String(item.lifecycle_status || '').trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否允许重试/重新识别:必须以后端 available_actions 为准,且绑定 current_run_no。
|
||||
*/
|
||||
function canReparse(item: ShippingWorkflowItem): boolean {
|
||||
if (!String(item.current_run_no || '').trim()) return false;
|
||||
const actions = item.available_actions;
|
||||
if (Array.isArray(actions)) return actions.includes('reparse');
|
||||
// 无契约时 fail-closed:禁止仅凭 pending_review 展示(会稳定触发 CASE_REQUIRED)。
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 重识别按钮文案:区分 Case 新版本与失败 Run 重试。
|
||||
*/
|
||||
function reparseActionLabel(item: ShippingWorkflowItem): string {
|
||||
if (item.reparse_kind === 'failed_run_retry') {
|
||||
return t('chat.shippingProcessing.actions.retryFailedRun');
|
||||
}
|
||||
return t('chat.shippingProcessing.actions.reparse');
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表主标题:优先文件名。
|
||||
*/
|
||||
@@ -570,42 +421,6 @@ function itemTitle(item: ShippingWorkflowItem): string {
|
||||
});
|
||||
}
|
||||
|
||||
const filteredItems = computed(() => {
|
||||
const source = visibleItems.value;
|
||||
if (!pendingOnlyFilter.value) return source;
|
||||
return source.filter((item) => {
|
||||
const display = resolveItemDisplayStatus(item);
|
||||
return (
|
||||
ACTIONABLE_FILTER_STATUSES.has(display)
|
||||
|| ACTIONABLE_FILTER_STATUSES.has(String(item.lifecycle_status || '').trim())
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const grouped = computed(() => {
|
||||
const buckets: Record<ItemGroupKey, ShippingWorkflowItem[]> = {
|
||||
processing: [],
|
||||
queued: [],
|
||||
pending_review: [],
|
||||
waiting_manual_upload: [],
|
||||
failed: [],
|
||||
completed: [],
|
||||
};
|
||||
for (const item of filteredItems.value) {
|
||||
buckets[resolveGroup(item)].push(item);
|
||||
}
|
||||
return buckets;
|
||||
});
|
||||
|
||||
const groupOrder: ItemGroupKey[] = [
|
||||
'processing',
|
||||
'queued',
|
||||
'pending_review',
|
||||
'waiting_manual_upload',
|
||||
'failed',
|
||||
'completed',
|
||||
];
|
||||
|
||||
/**
|
||||
* 解析生命周期状态文案。
|
||||
*/
|
||||
@@ -614,20 +429,6 @@ function statusLabel(status: string): string {
|
||||
return te(key) ? t(key) : t('chat.shippingProcessing.itemStatus.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化更新时间。
|
||||
*/
|
||||
function formatUpdatedLabel(value?: string | null): string {
|
||||
const date = new Date(String(value || ''));
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
const time = new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).format(date);
|
||||
return t('chat.shippingOrderExtractionDocumentTiming.updated', { time });
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动刷新。
|
||||
*/
|
||||
@@ -635,17 +436,6 @@ async function onRefresh() {
|
||||
await ctl.value.refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开详情抽屉:仅用列表投影,不再请求已 DROP 的 WorkflowItem 详情 API。
|
||||
*/
|
||||
function openDetail(item: ShippingWorkflowItem) {
|
||||
const itemNo = String(item.item_no || '').trim();
|
||||
if (!itemNo) return;
|
||||
detailOpen.value = true;
|
||||
detailItem.value = item;
|
||||
detailLoading.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开取消原因弹窗:优先绑定 current_run_no,走 Run 级取消 API。
|
||||
*/
|
||||
@@ -902,12 +692,15 @@ watch(
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
:disabled="initialLoading || manualRefreshing"
|
||||
:title="t('chat.shippingProcessing.actions.refresh')"
|
||||
data-testid="shipping-workflow-refresh"
|
||||
@click="onRefresh"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
|
||||
<RefreshCw
|
||||
class="h-3.5 w-3.5"
|
||||
:class="{ 'animate-spin': initialLoading || manualRefreshing }"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -982,174 +775,11 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showFilesDrawer"
|
||||
class="mt-3 min-h-0 flex-1 overflow-y-auto rounded-xl border border-default bg-surface-soft/40 p-2"
|
||||
data-testid="shipping-workflow-details-drawer"
|
||||
>
|
||||
<section
|
||||
class="flex min-h-0 w-full flex-col"
|
||||
:aria-label="t('chat.shippingProcessing.detailsDrawerTitle')"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ t('chat.shippingProcessing.detailsDrawerTitle') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[11px] text-secondary">
|
||||
{{ t('chat.shippingProcessing.compactSummary', {
|
||||
active: items.length,
|
||||
total: counts.total,
|
||||
}) }}
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-[11px] text-secondary">{{ t('chat.shippingProcessing.activity.fileListTitle') }}</span>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<div
|
||||
class="mb-3 flex flex-wrap gap-1.5 text-[11px]"
|
||||
data-testid="shipping-workflow-counts"
|
||||
>
|
||||
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
|
||||
{{ t('chat.shippingProcessing.counts.processing', { count: counts.processing }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="counts.pending_review > 0"
|
||||
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.counts.pendingReview', { count: counts.pending_review }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="(counts.waiting_manual_upload || 0) > 0"
|
||||
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-800 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.counts.waitingManualUpload', {
|
||||
count: counts.waiting_manual_upload || 0,
|
||||
}) }}
|
||||
</span>
|
||||
<span class="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200">
|
||||
{{ t('chat.shippingProcessing.counts.completed', { count: counts.completed }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="counts.failed > 0"
|
||||
class="rounded-md bg-rose-50 px-2 py-0.5 text-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.counts.failed', { count: counts.failed }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<template v-for="groupKey in groupOrder" :key="groupKey">
|
||||
<section
|
||||
v-if="grouped[groupKey].length"
|
||||
class="mb-3"
|
||||
:data-testid="`shipping-workflow-group-${groupKey}`"
|
||||
>
|
||||
<h3 class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-secondary">
|
||||
{{ t(`chat.shippingProcessing.groups.${groupKey}`) }}
|
||||
</h3>
|
||||
<ul class="space-y-2">
|
||||
<li
|
||||
v-for="item in grouped[groupKey]"
|
||||
:key="item.item_no"
|
||||
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
|
||||
:data-testid="`shipping-workflow-item-${item.item_no}`"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div
|
||||
class="truncate text-xs font-semibold text-primary"
|
||||
:title="itemTitle(item)"
|
||||
data-testid="shipping-workflow-item-filename"
|
||||
>
|
||||
{{ itemTitle(item) }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[11px] text-muted">
|
||||
{{ t('chat.shippingProcessing.versionLabel', { version: item.current_version_no }) }}
|
||||
· {{ itemActivityLabel(item) }}
|
||||
<span v-if="!item.current_case_no" class="ml-1 text-secondary">
|
||||
· {{ t('chat.shippingProcessing.noReviewCaseYet') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium"
|
||||
:class="{
|
||||
'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-100':
|
||||
groupKey === 'pending_review'
|
||||
|| groupKey === 'failed'
|
||||
|| groupKey === 'waiting_manual_upload',
|
||||
'bg-sky-100 text-sky-800 dark:bg-sky-900/50 dark:text-sky-100':
|
||||
groupKey === 'processing' || groupKey === 'queued',
|
||||
'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-100':
|
||||
groupKey === 'completed',
|
||||
}"
|
||||
>
|
||||
{{ statusLabel(resolveItemDisplayStatus(item)) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="item.last_activity_at || item.updated_at" class="mt-0.5 text-[11px] text-muted">
|
||||
{{ formatUpdatedLabel(item.last_activity_at || item.updated_at) }}
|
||||
</div>
|
||||
<div v-if="groupKey === 'processing' || groupKey === 'queued'" class="mt-1 text-[11px] text-brand-700 dark:text-brand-300">
|
||||
{{ t('chat.shippingProcessing.activity.currentAction', { action: itemActivityLabel(item) }) }}
|
||||
</div>
|
||||
<ProcessGateRecoveryCard
|
||||
v-if="item.process_gate?.current_blocking_gate"
|
||||
class="mt-2"
|
||||
:summary="item.process_gate"
|
||||
:can-handle="true"
|
||||
:navigation-context="gateNavigationContext"
|
||||
@refreshed="() => void ctl.refresh()"
|
||||
@refresh-needed="() => void ctl.refresh()"
|
||||
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
|
||||
/>
|
||||
<div class="mt-2 flex min-w-0 items-center gap-2 overflow-x-auto whitespace-nowrap pb-0.5">
|
||||
<button
|
||||
v-if="groupKey === 'pending_review' && item.current_run_no"
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center gap-1 rounded-md bg-brand-600 px-2.5 py-1 text-[11px] font-semibold text-white shadow-sm hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-workflow-action-open-review"
|
||||
@click="openReview(item)"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.actions.openReview') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
|
||||
data-testid="shipping-workflow-action-view"
|
||||
@click="openDetail(item)"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.actions.viewProgress') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canReparse(item)"
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center gap-1 text-[11px] font-medium text-amber-800 hover:underline disabled:opacity-50 dark:text-amber-200"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-workflow-action-reparse"
|
||||
@click="openReparseDialog(item)"
|
||||
>
|
||||
{{ reparseActionLabel(item) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canCancel(item)"
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center gap-1 text-[11px] font-medium text-rose-700 hover:underline disabled:opacity-50"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-workflow-action-cancel"
|
||||
@click="openCancelDialog(item)"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.actions.cancelFile') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<!--
|
||||
方案 7:移除右侧常驻「批次与文件列表」聚合抽屉,避免与任务卡投影矛盾与高度抖动。
|
||||
文件明细统一在订单处理工作台展示;任务卡仅显示任务名 / 文件数 / 状态 / 主按钮。
|
||||
Gate 级阻断与进度详情仍通过 ProcessGateRecoveryCard 与 ShippingWorkflowItemDetailDrawer 呈现。
|
||||
-->
|
||||
|
||||
<ShippingWorkflowItemDetailDrawer
|
||||
:open="detailOpen"
|
||||
|
||||
@@ -15,6 +15,10 @@ import {
|
||||
groupConversationProcessingTasks,
|
||||
mapUserTaskObjectsToFileRows,
|
||||
resolveConversationProcessingFromUnified,
|
||||
normalizeActionCodes,
|
||||
buildTaskSemanticKey,
|
||||
buildProcessingSemanticKey,
|
||||
stabilizeTaskObjects,
|
||||
} from './conversationProcessingProjection';
|
||||
import type {
|
||||
ShippingProcessingProjection,
|
||||
@@ -730,3 +734,166 @@ describe('conversationProcessingProjection', () => {
|
||||
expect(merged?.recent_task_no).toBe('OT-RECENT');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 方案 1~4 的防御链单元测试:
|
||||
* normalize → semanticKey → stabilize;任何一环击穿都会导致轮询按钮闪烁。
|
||||
* 对应验收:动作顺序变化按钮不变 / updated_at 变化按钮不变 / 轮询相同数据按钮 DOM 不变。
|
||||
*/
|
||||
describe('conversationProcessingProjection — normalize & semantic & stabilize', () => {
|
||||
it('normalizeActionCodes: 去空白、小写、去重、字典序排序', () => {
|
||||
expect(normalizeActionCodes([' View_Details ', 'Confirm_Customer', 'view_details', ' confirm_customer ']))
|
||||
.toEqual(['confirm_customer', 'view_details']);
|
||||
expect(normalizeActionCodes([null, undefined, '', ' ', 'cancel', '0']))
|
||||
.toEqual(['0', 'cancel']);
|
||||
expect(normalizeActionCodes([])).toEqual([]);
|
||||
expect(normalizeActionCodes([undefined, null])).toEqual([]);
|
||||
});
|
||||
|
||||
it('buildTaskSemanticKey: available_actions 乱序 → 同一签名(不影响按钮顺序)', () => {
|
||||
const base: Parameters<typeof projectConversationProcessingFromWorkItems>[0][number] = {
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-1',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-1',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-10T00:00:00Z',
|
||||
currentGate: {
|
||||
gateCode: 'order_freeze_readiness',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'open_order_review',
|
||||
blockingReasonCode: 'review_case_draft',
|
||||
attemptNo: 0,
|
||||
},
|
||||
availableActions: ['open_order_review', 'view_details'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'a.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 0,
|
||||
customerName: null,
|
||||
poNumber: 'PO-1',
|
||||
},
|
||||
childOrderTasks: [],
|
||||
};
|
||||
const p1 = projectConversationProcessingFromWorkItems([{ ...base }]);
|
||||
const p2 = projectConversationProcessingFromWorkItems([
|
||||
{ ...base, availableActions: ['view_details', 'open_order_review'], lastActivityAt: '2099-01-01T00:00:00Z' },
|
||||
]);
|
||||
const t1 = p1!.needs_action[0]!;
|
||||
const t2 = p2!.needs_action[0]!;
|
||||
// 相同语义字段 -> 同签名;即使 available_actions 顺序不同、lastActivityAt 不同。
|
||||
expect(buildTaskSemanticKey(t1)).toBe(buildTaskSemanticKey(t2));
|
||||
// available_actions 内永远是 normalized 排序后的数组,不是原始后端乱序。
|
||||
expect(t1.available_actions).toEqual(['open_order_review', 'view_details']);
|
||||
expect(t2.available_actions).toEqual(['open_order_review', 'view_details']);
|
||||
});
|
||||
|
||||
it('stabilizeTaskObjects: 同一 user_task_no 且语义相同,优先复用旧对象引用(避免 DOM 重建)', () => {
|
||||
const baseTask = (no: string, updatedAt: string) => ({
|
||||
user_task_no: no,
|
||||
group: 'processing' as const,
|
||||
status_label: 'document_parsing',
|
||||
run_no: 'RUN-1',
|
||||
title: '订单识别任务',
|
||||
primary_action: 'view_details',
|
||||
display_kind: 'single_document_task',
|
||||
file_count: 1,
|
||||
can_append: false,
|
||||
updated_at: updatedAt,
|
||||
last_activity_at: updatedAt,
|
||||
available_actions: ['view_details'],
|
||||
current_gate: null,
|
||||
user_task_authoritative: true,
|
||||
documents: [],
|
||||
});
|
||||
const oldOne = baseTask('OT-1', '2026-08-10T00:00:00Z');
|
||||
const nextOne = baseTask('OT-1', '2026-08-10T00:00:02Z');
|
||||
const oldTasks = [oldOne];
|
||||
const nextRawTasks = [nextOne];
|
||||
const stabilized = stabilizeTaskObjects(oldTasks, nextRawTasks);
|
||||
// updated_at/last_activity_at 不参与 semanticKey 比较 -> 复用旧引用。
|
||||
expect(stabilized[0]).toBe(oldOne);
|
||||
expect(stabilized[0].updated_at).toBe('2026-08-10T00:00:00Z');
|
||||
});
|
||||
|
||||
it('buildProcessingSemanticKey: 只基于语义字段,忽略 updated_at/last_activity_at 扰动', () => {
|
||||
function makeProjection() {
|
||||
return projectConversationProcessingFromWorkItems([{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-A',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-A',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-10T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: ['view_details'],
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'a.pdf',
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 0,
|
||||
customerName: null, poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
}])!;
|
||||
}
|
||||
const pA = makeProjection();
|
||||
const pB = makeProjection();
|
||||
// 模拟轮询差异:updated_at / last_activity_at / created_at 等辅助字段都变。
|
||||
pA.processing[0]!.updated_at = '2026-08-10T00:00:00Z';
|
||||
pA.processing[0]!.last_activity_at = '2026-08-10T00:00:00Z';
|
||||
pB.processing[0]!.updated_at = '2026-08-10T00:00:02Z';
|
||||
pB.processing[0]!.last_activity_at = '2026-08-10T00:00:02Z';
|
||||
expect(buildProcessingSemanticKey(pA)).toBe(buildProcessingSemanticKey(pB));
|
||||
});
|
||||
|
||||
it('stabilizeTaskObjects: 语义变化时(status 改变)必须返回新对象,不能错误冻结旧状态', () => {
|
||||
const oldTask = {
|
||||
user_task_no: 'OT-1',
|
||||
group: 'processing' as const,
|
||||
status_label: 'document_parsing',
|
||||
run_no: 'RUN-1',
|
||||
title: '订单识别任务',
|
||||
primary_action: 'view_details',
|
||||
display_kind: 'single_document_task',
|
||||
file_count: 1,
|
||||
can_append: false,
|
||||
updated_at: '2026-08-10T00:00:00Z',
|
||||
last_activity_at: '2026-08-10T00:00:00Z',
|
||||
available_actions: ['view_details'],
|
||||
current_gate: null,
|
||||
user_task_authoritative: true,
|
||||
documents: [],
|
||||
};
|
||||
const nextTask = {
|
||||
...oldTask,
|
||||
group: 'needs_action' as const,
|
||||
status_label: 'waiting_review',
|
||||
primary_action: 'open_order_review',
|
||||
available_actions: ['open_order_review', 'view_details'],
|
||||
updated_at: '2026-08-10T00:00:10Z',
|
||||
last_activity_at: '2026-08-10T00:00:10Z',
|
||||
current_gate: {
|
||||
blockingReasonCode: 'review_case_draft',
|
||||
nextActionCode: 'open_order_review',
|
||||
},
|
||||
};
|
||||
const stabilized = stabilizeTaskObjects([oldTask], [nextTask]);
|
||||
// 状态从 processing→needs_action 语义已变,必须替换成新引用。
|
||||
expect(stabilized[0]).not.toBe(oldTask);
|
||||
expect(stabilized[0].status_label).toBe('waiting_review');
|
||||
expect(stabilized[0].available_actions).toEqual(['open_order_review', 'view_details']);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@
|
||||
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
|
||||
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
|
||||
* 可由统一 work_items(order_task)合成兼容分组。
|
||||
* 语义签名与任务稳定化:轮询返回相同业务状态时复用旧对象,避免按钮闪烁。
|
||||
*/
|
||||
|
||||
import type {
|
||||
@@ -19,8 +20,111 @@ import type {
|
||||
WorkflowNodeStatus,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
/**
|
||||
* 标准化动作码列表:去空白、小写、去重、字典序排序。
|
||||
* 核心逻辑:后端返回顺序或临时字段变化时,确保前端动作集合稳定。
|
||||
*
|
||||
* @param actions - 原始动作码数组
|
||||
* @returns 标准化后的动作码数组(唯一、已排序)
|
||||
*/
|
||||
export function normalizeActionCodes(actions: unknown[]): string[] {
|
||||
return [...new Set(
|
||||
(actions || [])
|
||||
.map((item) => String(item || '').trim().toLowerCase())
|
||||
.filter(Boolean),
|
||||
)].sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建单个用户任务的语义签名:只包含决定按钮与展示的核心字段。
|
||||
* 排除 updated_at / last_activity_at 等仅用于辅助提示的字段。
|
||||
*
|
||||
* @param task - 用户可见任务
|
||||
* @returns 语义签名字符串;任务为 null 时返回空串
|
||||
*/
|
||||
export function buildTaskSemanticKey(
|
||||
task: ConversationProcessingUserTask | null | undefined,
|
||||
): string {
|
||||
if (!task) return '';
|
||||
return JSON.stringify({
|
||||
taskNo: task.user_task_no,
|
||||
group: task.group,
|
||||
status: task.status_label,
|
||||
runNo: task.run_no,
|
||||
displayKind: task.display_kind,
|
||||
fileCount: task.file_count,
|
||||
title: task.title,
|
||||
primaryAction: task.primary_action || null,
|
||||
currentGate: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
|
||||
.current_gate
|
||||
? {
|
||||
blockingReasonCode: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
|
||||
.current_gate?.blockingReasonCode || null,
|
||||
nextActionCode: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
|
||||
.current_gate?.nextActionCode || null,
|
||||
}
|
||||
: null,
|
||||
availableActions: normalizeActionCodes(task.available_actions || []),
|
||||
canAppend: task.can_append ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建整个会话处理投影的语义签名:summary + 各分组任务签名。
|
||||
*
|
||||
* @param projection - 会话处理投影
|
||||
* @returns 语义签名字符串;投影为 null 时返回空串
|
||||
*/
|
||||
export function buildProcessingSemanticKey(
|
||||
projection: ConversationProcessingProjection | null | undefined,
|
||||
): string {
|
||||
if (!projection) return '';
|
||||
return JSON.stringify({
|
||||
summary: {
|
||||
total_tasks: projection.summary?.total_tasks || 0,
|
||||
total_files: projection.summary?.total_files || 0,
|
||||
processing: projection.summary?.processing || 0,
|
||||
needs_action: projection.summary?.needs_action || 0,
|
||||
completed: projection.summary?.completed || 0,
|
||||
history: projection.summary?.history || 0,
|
||||
},
|
||||
focused_task_no: projection.focused_task_no || null,
|
||||
recent_task_no: projection.recent_task_no || null,
|
||||
needs_action: (projection.needs_action || []).map(buildTaskSemanticKey),
|
||||
processing: (projection.processing || []).map(buildTaskSemanticKey),
|
||||
completed: (projection.completed || []).map(buildTaskSemanticKey),
|
||||
history: (projection.history || []).map(buildTaskSemanticKey),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按任务号复用旧对象:语义签名相同时返回旧引用,保证 Vue v-for 复用 DOM。
|
||||
*
|
||||
* @param previousTasks - 上一次渲染的任务列表
|
||||
* @param nextRawTasks - 本次轮询生成的新任务列表(原始未稳定化)
|
||||
* @returns 稳定化后的任务列表;语义未变的任务沿用旧引用
|
||||
*/
|
||||
export function stabilizeTaskObjects(
|
||||
previousTasks: ConversationProcessingUserTask[],
|
||||
nextRawTasks: ConversationProcessingUserTask[],
|
||||
): ConversationProcessingUserTask[] {
|
||||
const previousByTaskNo = new Map(
|
||||
(previousTasks || []).map((task) => [String(task.user_task_no || ''), task]),
|
||||
);
|
||||
return (nextRawTasks || []).map((nextTask) => {
|
||||
const previous = previousByTaskNo.get(String(nextTask.user_task_no || ''));
|
||||
if (!previous) return nextTask;
|
||||
if (buildTaskSemanticKey(previous) === buildTaskSemanticKey(nextTask)) {
|
||||
return previous;
|
||||
}
|
||||
return nextTask;
|
||||
});
|
||||
}
|
||||
|
||||
/** 需要人工处理的生命周期集合。 */
|
||||
const NEEDS_ACTION_LIFECYCLES = new Set([
|
||||
'blocked',
|
||||
'waiting_review',
|
||||
'pending_review',
|
||||
'manual_upload_pending',
|
||||
'failed',
|
||||
@@ -28,6 +132,16 @@ const NEEDS_ACTION_LIFECYCLES = new Set([
|
||||
'upload_rpa_failed',
|
||||
]);
|
||||
|
||||
const HUMAN_ACTION_CODES = new Set([
|
||||
'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate',
|
||||
'open_order_review', 'open_order_processing', 'enter_manual_review',
|
||||
'open_inventory_source_review', 'confirm_inventory_source',
|
||||
'open_inventory_match_review', 'rematch', 'match_inventory',
|
||||
'open_shortage_review', 'upload_inventory_file', 'open_manual_upload',
|
||||
'wait_manual_upload', 'retry', 'retry_parse', 'retry_failed_documents',
|
||||
'retry_failed_attachments', 'open_profile_review',
|
||||
]);
|
||||
|
||||
/** 处理中生命周期集合。 */
|
||||
const PROCESSING_LIFECYCLES = new Set([
|
||||
'queued',
|
||||
@@ -288,7 +402,7 @@ export function classifyConversationProcessingGroup(
|
||||
status: string | null | undefined,
|
||||
options?: { hasBlockingGate?: boolean; needsCustomerConfirm?: boolean },
|
||||
): ConversationProcessingTaskGroup {
|
||||
if (options?.hasBlockingGate || options?.needsCustomerConfirm) return 'needs_action';
|
||||
if (options?.needsCustomerConfirm) return 'needs_action';
|
||||
const normalized = String(status || '').trim();
|
||||
if (NEEDS_ACTION_LIFECYCLES.has(normalized)) return 'needs_action';
|
||||
if (COMPLETED_LIFECYCLES.has(normalized)) return 'completed';
|
||||
@@ -297,7 +411,7 @@ export function classifyConversationProcessingGroup(
|
||||
if (normalized === 'review_required' || normalized === 'partially_completed') {
|
||||
return 'needs_action';
|
||||
}
|
||||
if (normalized === 'failed' || normalized === 'cancelled') return 'needs_action';
|
||||
if (normalized === 'failed') return 'needs_action';
|
||||
if (normalized === 'completed') return 'completed';
|
||||
if (normalized === 'processing' || normalized === 'queued') return 'processing';
|
||||
return 'processing';
|
||||
@@ -431,10 +545,16 @@ export function projectConversationProcessingTasks(
|
||||
const effectiveItems = uniqueDocuments.map((row) => row.source_item);
|
||||
// 任务级分组/操作只由最近代表 Item 决定;旧 Run 仅贡献未受影响的 PDF,不得反向污染状态。
|
||||
const statuses = [resolveItemDisplayStatus(primaryItem)];
|
||||
const hasGate = Boolean(primaryItem.process_gate?.current_blocking_gate);
|
||||
const primaryActions = Array.isArray(primaryItem.available_actions)
|
||||
? primaryItem.available_actions
|
||||
: [];
|
||||
const hasHumanAction = primaryActions.some((value) => {
|
||||
const code = String(value || '').trim().toLowerCase();
|
||||
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
|
||||
});
|
||||
let group: ConversationProcessingTaskGroup = 'history';
|
||||
for (const status of statuses) {
|
||||
const g = classifyConversationProcessingGroup(status, { hasBlockingGate: hasGate });
|
||||
const g = classifyConversationProcessingGroup(status, { needsCustomerConfirm: hasHumanAction });
|
||||
if (g === 'needs_action') {
|
||||
group = 'needs_action';
|
||||
break;
|
||||
@@ -523,12 +643,27 @@ export function groupConversationProcessingTasks(
|
||||
options?: {
|
||||
focusedTaskNo?: string | null;
|
||||
recentTaskNo?: string | null;
|
||||
/** 上一版投影(语义稳定化复用旧对象引用)。 */
|
||||
previousProjection?: ConversationProcessingProjection | null;
|
||||
},
|
||||
): ConversationProcessingProjection {
|
||||
const needs_action = tasks.filter((t) => t.group === 'needs_action');
|
||||
const processing = tasks.filter((t) => t.group === 'processing');
|
||||
const completed = tasks.filter((t) => t.group === 'completed');
|
||||
const history = tasks.filter((t) => t.group === 'history');
|
||||
const previousTasks: ConversationProcessingUserTask[] = options?.previousProjection
|
||||
? [
|
||||
...(options.previousProjection.needs_action || []),
|
||||
...(options.previousProjection.processing || []),
|
||||
...(options.previousProjection.completed || []),
|
||||
...(options.previousProjection.history || []),
|
||||
]
|
||||
: [];
|
||||
const stabilized = stabilizeTaskObjects(previousTasks, tasks);
|
||||
const needs_action_raw = stabilized.filter((t) => t.group === 'needs_action');
|
||||
const processing_raw = stabilized.filter((t) => t.group === 'processing');
|
||||
const completed_raw = stabilized.filter((t) => t.group === 'completed');
|
||||
const history_raw = stabilized.filter((t) => t.group === 'history');
|
||||
const needs_action = stabilizeTaskObjects(options?.previousProjection?.needs_action || [], needs_action_raw);
|
||||
const processing = stabilizeTaskObjects(options?.previousProjection?.processing || [], processing_raw);
|
||||
const completed = stabilizeTaskObjects(options?.previousProjection?.completed || [], completed_raw);
|
||||
const history = stabilizeTaskObjects(options?.previousProjection?.history || [], history_raw);
|
||||
const all = [...needs_action, ...processing, ...completed, ...history];
|
||||
const summary: ConversationProcessingSummary = {
|
||||
total_tasks: all.length,
|
||||
@@ -572,14 +707,15 @@ export function mapShippingProcessingStatusToTaskGroup(
|
||||
item: ShippingProcessingProjection,
|
||||
): ConversationProcessingTaskGroup {
|
||||
const status = String(item.status || '').trim().toLowerCase();
|
||||
const gateAction = String(item.currentGate?.nextActionCode || '').trim();
|
||||
const gateAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase();
|
||||
const hasHumanAction = [gateAction, ...(item.availableActions || [])]
|
||||
.map((value) => String(value || '').trim().toLowerCase())
|
||||
.some((value) => HUMAN_ACTION_CODES.has(value) || value.startsWith('retry_failed_'));
|
||||
if (
|
||||
status === 'waiting_review'
|
||||
|| status === 'blocked'
|
||||
|| status === 'failed'
|
||||
|| gateAction === 'open_order_review'
|
||||
|| gateAction === 'retry_parse'
|
||||
|| gateAction === 'retry_failed_documents'
|
||||
|| hasHumanAction
|
||||
) {
|
||||
return 'needs_action';
|
||||
}
|
||||
@@ -615,19 +751,22 @@ export function mergeConversationProcessingFocusMetadata(
|
||||
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
|
||||
* 核心逻辑:work_items 非空时始终由 order_task 工作项合成任务列表;禁止优先 embedded
|
||||
* (兄弟 OT 仅出现在 work_items,embedded 可能缺 sibling)。
|
||||
* 语义稳定化:对比 previousProjection 的签名,复用未变的任务对象引用。
|
||||
*
|
||||
* @param workItems - unified.work_items
|
||||
* @param embedded - unified.conversation_processing
|
||||
* @param previousProjection - 上一版投影(用于任务对象稳定化)
|
||||
* @returns 会话处理投影;无可用数据时 null
|
||||
*/
|
||||
export function resolveConversationProcessingFromUnified(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
previousProjection?: ConversationProcessingProjection | null,
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
if (items.length > 0) {
|
||||
return mergeConversationProcessingFocusMetadata(
|
||||
projectConversationProcessingFromWorkItems(items),
|
||||
projectConversationProcessingFromWorkItems(items, previousProjection),
|
||||
embedded,
|
||||
);
|
||||
}
|
||||
@@ -638,22 +777,22 @@ export function resolveConversationProcessingFromUnified(
|
||||
/**
|
||||
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
|
||||
*
|
||||
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组。
|
||||
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组;
|
||||
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
|
||||
*
|
||||
* @param workItems - 统一投影 work_items
|
||||
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
|
||||
* @returns 兼容投影;无 order_task 时返回 null
|
||||
*/
|
||||
export function projectConversationProcessingFromWorkItems(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
previousProjection?: ConversationProcessingProjection | null,
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
const orderTasks = items.filter((row) => row.workItemType === 'order_task');
|
||||
if (!orderTasks.length) return null;
|
||||
|
||||
const needs_action: ConversationProcessingUserTask[] = [];
|
||||
const processing: ConversationProcessingUserTask[] = [];
|
||||
const completed: ConversationProcessingUserTask[] = [];
|
||||
const history: ConversationProcessingUserTask[] = [];
|
||||
const rawTasks: ConversationProcessingUserTask[] = [];
|
||||
|
||||
for (const item of orderTasks) {
|
||||
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
|
||||
@@ -661,6 +800,8 @@ export function projectConversationProcessingFromWorkItems(
|
||||
const group = mapShippingProcessingStatusToTaskGroup(item);
|
||||
const docCount = Number(item.sourceSummary?.documentCount || 0);
|
||||
const filename = String(item.sourceSummary?.filename || '').trim();
|
||||
const normalizedActions = normalizeActionCodes(item.availableActions || []);
|
||||
const gateNextAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase() || null;
|
||||
const task: ConversationProcessingUserTask = {
|
||||
user_task_no: taskNo,
|
||||
user_task_authoritative: true,
|
||||
@@ -670,22 +811,30 @@ export function projectConversationProcessingFromWorkItems(
|
||||
group,
|
||||
status_label: String(item.status || '') || null,
|
||||
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
|
||||
// [P0] 消费后端投影 run_no,禁止写死 null 导致「进入订单处理」静默失败。
|
||||
run_no: String(item.runNo || '').trim() || null,
|
||||
can_append: false,
|
||||
last_activity_at: item.lastActivityAt || null,
|
||||
available_actions: Array.isArray(item.availableActions) ? [...item.availableActions] : [],
|
||||
primary_action: item.currentGate?.nextActionCode || item.availableActions?.[0] || null,
|
||||
available_actions: normalizedActions,
|
||||
primary_action: gateNextAction || normalizedActions[0] || null,
|
||||
};
|
||||
if (group === 'needs_action') needs_action.push(task);
|
||||
else if (group === 'processing') processing.push(task);
|
||||
else if (group === 'completed') completed.push(task);
|
||||
else history.push(task);
|
||||
rawTasks.push(task);
|
||||
}
|
||||
|
||||
const active = [...needs_action, ...processing, ...completed];
|
||||
if (!active.length && !history.length) return null;
|
||||
// 后端未返回 embedded 汇总时,仍按 OT 主 PDF ID 去重,禁止兄弟 OT 重复累计。
|
||||
if (!rawTasks.length) return null;
|
||||
|
||||
const needs_action_raw: ConversationProcessingUserTask[] = [];
|
||||
const processing_raw: ConversationProcessingUserTask[] = [];
|
||||
const completed_raw: ConversationProcessingUserTask[] = [];
|
||||
const history_raw: ConversationProcessingUserTask[] = [];
|
||||
for (const task of rawTasks) {
|
||||
if (task.group === 'needs_action') needs_action_raw.push(task);
|
||||
else if (task.group === 'processing') processing_raw.push(task);
|
||||
else if (task.group === 'completed') completed_raw.push(task);
|
||||
else history_raw.push(task);
|
||||
}
|
||||
const active = [...needs_action_raw, ...processing_raw, ...completed_raw];
|
||||
if (!active.length && !history_raw.length) return null;
|
||||
|
||||
const documentIds = new Set(
|
||||
orderTasks
|
||||
.map((item) => Number(item.sourceSummary?.documentId || 0))
|
||||
@@ -694,6 +843,35 @@ export function projectConversationProcessingFromWorkItems(
|
||||
const totalFiles = documentIds.size > 0
|
||||
? documentIds.size
|
||||
: active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
|
||||
|
||||
const stabilizedAll = stabilizeTaskObjects(
|
||||
previousProjection
|
||||
? [
|
||||
...(previousProjection.needs_action || []),
|
||||
...(previousProjection.processing || []),
|
||||
...(previousProjection.completed || []),
|
||||
...(previousProjection.history || []),
|
||||
]
|
||||
: [],
|
||||
rawTasks,
|
||||
);
|
||||
const needs_action = stabilizeTaskObjects(
|
||||
previousProjection?.needs_action || [],
|
||||
stabilizedAll.filter((t) => t.group === 'needs_action'),
|
||||
);
|
||||
const processing = stabilizeTaskObjects(
|
||||
previousProjection?.processing || [],
|
||||
stabilizedAll.filter((t) => t.group === 'processing'),
|
||||
);
|
||||
const completed = stabilizeTaskObjects(
|
||||
previousProjection?.completed || [],
|
||||
stabilizedAll.filter((t) => t.group === 'completed'),
|
||||
);
|
||||
const history = stabilizeTaskObjects(
|
||||
previousProjection?.history || [],
|
||||
stabilizedAll.filter((t) => t.group === 'history'),
|
||||
);
|
||||
|
||||
return {
|
||||
summary: {
|
||||
total_tasks: active.length,
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
* 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。
|
||||
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing;
|
||||
* focus/viewed 写路径优先应用响应中的 work_items;
|
||||
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;无活跃任务时停轮询。
|
||||
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;
|
||||
* 分层轮询:系统处理中 2s 轮询,待复核 30s 轮询;
|
||||
* 区分 initialLoading / manualRefreshing / polling 三种 loading 态;
|
||||
* 语义签名比较:业务状态未变化时不替换投影对象,防止按钮闪烁与 DOM 重建。
|
||||
*/
|
||||
import {
|
||||
computed,
|
||||
@@ -27,7 +30,10 @@ import type {
|
||||
ConversationProcessingProjection,
|
||||
ShippingProcessingProjection,
|
||||
} from '../types/shipping.api.types';
|
||||
import { resolveConversationProcessingFromUnified } from './conversationProcessingProjection';
|
||||
import {
|
||||
buildProcessingSemanticKey,
|
||||
resolveConversationProcessingFromUnified,
|
||||
} from './conversationProcessingProjection';
|
||||
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
@@ -46,7 +52,14 @@ export type UseShippingNoticeWorkflowReturn = {
|
||||
processing: Ref<ConversationProcessingProjection | null>;
|
||||
/** 统一 ShippingProcessing work_items。 */
|
||||
processingWorkItems: Ref<ShippingProcessingProjection[]>;
|
||||
/** 兼容旧消费者:任何加载状态均为 true。 */
|
||||
loading: Ref<boolean>;
|
||||
/** 首次打开会话加载中(投影仍为空)。 */
|
||||
initialLoading: Ref<boolean>;
|
||||
/** 用户主动点击刷新或执行重试/重解析/取消等写操作后加载。 */
|
||||
manualRefreshing: Ref<boolean>;
|
||||
/** 后台静默轮询中(不显示 loading,不禁用按钮)。 */
|
||||
polling: Ref<boolean>;
|
||||
error: Ref<string | null>;
|
||||
refresh: () => Promise<void>;
|
||||
focusConversationTask: (taskNo: string) => Promise<void>;
|
||||
@@ -67,12 +80,19 @@ function readOption<T>(source: MaybeRefOrGetter<T>): T {
|
||||
}
|
||||
|
||||
/**
|
||||
* 按页面可见性选择轮询间隔。
|
||||
* 按页面可见性 + 业务状态选择轮询间隔。
|
||||
* 分层策略:系统处理中 2s;待人工复核 30s;后台标签页 8s(若仍需轮询)。
|
||||
*/
|
||||
function resolvePollMs(): number {
|
||||
function resolvePollMs(
|
||||
processing?: ConversationProcessingProjection | null,
|
||||
): number {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
||||
return BACKGROUND_POLL_MS;
|
||||
}
|
||||
const processingCount = Number(
|
||||
processing?.summary?.processing || processing?.processing?.length || 0,
|
||||
);
|
||||
if (processingCount > 0) return FOREGROUND_POLL_MS;
|
||||
return FOREGROUND_POLL_MS;
|
||||
}
|
||||
|
||||
@@ -87,14 +107,16 @@ export function resolveProcessingPollBackoffMs(failureCount: number): number {
|
||||
|
||||
/**
|
||||
* 判断是否应继续轮询统一 ShippingProcessing。
|
||||
* 核心逻辑:processing / needs_action 有活跃项则继续。
|
||||
* 核心逻辑:仅系统处理中(processing>0)时持续 2s 轮询;
|
||||
* 待人工复核不触发后台轮询;全部完成/取消/历史时停止轮询。
|
||||
*/
|
||||
export function shouldContinueProcessingPolling(
|
||||
processing?: ConversationProcessingProjection | null,
|
||||
): boolean {
|
||||
const processingCount = Number(processing?.summary?.processing || processing?.processing?.length || 0);
|
||||
const needsActionCount = Number(processing?.summary?.needs_action || processing?.needs_action?.length || 0);
|
||||
return processingCount > 0 || needsActionCount > 0;
|
||||
const processingCount = Number(
|
||||
processing?.summary?.processing || processing?.processing?.length || 0,
|
||||
);
|
||||
return processingCount > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,8 +131,13 @@ export function useShippingNoticeWorkflow(
|
||||
): UseShippingNoticeWorkflowReturn {
|
||||
const processing = ref<ConversationProcessingProjection | null>(null);
|
||||
const processingWorkItems = ref<ShippingProcessingProjection[]>([]);
|
||||
const loading = ref(false);
|
||||
const initialLoading = ref(false);
|
||||
const manualRefreshing = ref(false);
|
||||
const polling = ref(false);
|
||||
const error = ref<string | null>(null);
|
||||
const loading = computed(() => (
|
||||
initialLoading.value || manualRefreshing.value || polling.value
|
||||
));
|
||||
|
||||
let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollGeneration = 0;
|
||||
@@ -119,6 +146,7 @@ export function useShippingNoticeWorkflow(
|
||||
let inFlightRefresh: { conversationId: string; promise: Promise<void> } | null = null;
|
||||
let failureCount = 0;
|
||||
let pollingStopped = false;
|
||||
let lastSemanticKey = '';
|
||||
|
||||
const normalizedConversationId = computed(() =>
|
||||
String(readOption(options.conversationId) || '').trim(),
|
||||
@@ -152,12 +180,21 @@ export function useShippingNoticeWorkflow(
|
||||
/**
|
||||
* 仅拉取统一 shipping-processing 投影。
|
||||
* 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据;
|
||||
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据。
|
||||
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据;
|
||||
* 语义签名相同则不替换 projection 对象,避免 DOM 重建与按钮闪烁。
|
||||
*
|
||||
* @param conversationId - 会话 ID
|
||||
* @param mode - 请求模式:initial=首次加载 / manual=用户主动触发 / poll=后台轮询
|
||||
* @returns Promise<void>;可恢复网络失败写入 error,不向页面抛出。
|
||||
*/
|
||||
async function executeRefresh(conversationId: string): Promise<void> {
|
||||
async function executeRefresh(
|
||||
conversationId: string,
|
||||
mode: 'initial' | 'manual' | 'poll',
|
||||
): Promise<void> {
|
||||
const generation = ++requestGeneration;
|
||||
loading.value = true;
|
||||
if (mode === 'initial') initialLoading.value = true;
|
||||
else if (mode === 'manual') manualRefreshing.value = true;
|
||||
else polling.value = true;
|
||||
const controller = createRequestController();
|
||||
try {
|
||||
// [STEP 1] 统一投影为唯一读源。
|
||||
@@ -170,8 +207,19 @@ export function useShippingNoticeWorkflow(
|
||||
|
||||
const workItems = Array.isArray(unified?.work_items) ? unified.work_items : [];
|
||||
const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined;
|
||||
const prevProjection = processing.value;
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems,
|
||||
embedded,
|
||||
prevProjection,
|
||||
);
|
||||
const nextSemanticKey = buildProcessingSemanticKey(nextProjection);
|
||||
|
||||
processingWorkItems.value = workItems;
|
||||
processing.value = resolveConversationProcessingFromUnified(workItems, embedded);
|
||||
if (nextSemanticKey !== lastSemanticKey) {
|
||||
processing.value = nextProjection;
|
||||
lastSemanticKey = nextSemanticKey;
|
||||
}
|
||||
error.value = null;
|
||||
failureCount = 0;
|
||||
} catch (reason) {
|
||||
@@ -186,12 +234,17 @@ export function useShippingNoticeWorkflow(
|
||||
: 'network_recoverable';
|
||||
} finally {
|
||||
if (requestController === controller) requestController = null;
|
||||
if (generation === requestGeneration) loading.value = false;
|
||||
if (generation === requestGeneration) {
|
||||
if (mode === 'initial') initialLoading.value = false;
|
||||
else if (mode === 'manual') manualRefreshing.value = false;
|
||||
else polling.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取统一进度;同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。
|
||||
* 拉取统一进度(用户主动刷新模式:显示刷新图标旋转,不轮询)。
|
||||
* 同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。
|
||||
*/
|
||||
function refresh(): Promise<void> {
|
||||
const conversationId = normalizedConversationId.value;
|
||||
@@ -199,12 +252,15 @@ export function useShippingNoticeWorkflow(
|
||||
processing.value = null;
|
||||
processingWorkItems.value = [];
|
||||
error.value = null;
|
||||
lastSemanticKey = '';
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (inFlightRefresh?.conversationId === conversationId) {
|
||||
return inFlightRefresh.promise;
|
||||
}
|
||||
const promise = executeRefresh(conversationId).finally(() => {
|
||||
const isFirstLoad = processing.value === null && !initialLoading.value && !manualRefreshing.value && !polling.value;
|
||||
const mode: 'initial' | 'manual' = isFirstLoad ? 'initial' : 'manual';
|
||||
const promise = executeRefresh(conversationId, mode).finally(() => {
|
||||
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
|
||||
});
|
||||
inFlightRefresh = { conversationId, promise };
|
||||
@@ -213,7 +269,8 @@ export function useShippingNoticeWorkflow(
|
||||
|
||||
/**
|
||||
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
|
||||
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块。
|
||||
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块;
|
||||
* 每次回写后更新语义签名,避免下一轮轮询误判为「无变化」。
|
||||
*/
|
||||
function applyMutationProcessingResponse(response: {
|
||||
processing?: ConversationProcessingProjection | null;
|
||||
@@ -222,13 +279,25 @@ export function useShippingNoticeWorkflow(
|
||||
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
|
||||
if (workItems.length > 0) {
|
||||
processingWorkItems.value = workItems as typeof processingWorkItems.value;
|
||||
processing.value = resolveConversationProcessingFromUnified(
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
response.processing ?? null,
|
||||
processing.value,
|
||||
);
|
||||
const nextKey = buildProcessingSemanticKey(nextProjection);
|
||||
if (nextKey !== lastSemanticKey) {
|
||||
processing.value = nextProjection;
|
||||
lastSemanticKey = nextKey;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (response.processing) processing.value = response.processing;
|
||||
if (response.processing) {
|
||||
const nextKey = buildProcessingSemanticKey(response.processing);
|
||||
if (nextKey !== lastSemanticKey) {
|
||||
processing.value = response.processing;
|
||||
lastSemanticKey = nextKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -257,6 +326,23 @@ export function useShippingNoticeWorkflow(
|
||||
applyMutationProcessingResponse(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行后台静默轮询:不设置 manualRefreshing,使用 polling 态。
|
||||
* 失败时复用 executeRefresh 的 failureCount 统计。
|
||||
*/
|
||||
async function runBackgroundPoll(conversationId: string): Promise<void> {
|
||||
const existing = inFlightRefresh;
|
||||
if (existing?.conversationId === conversationId) {
|
||||
await existing.promise;
|
||||
return;
|
||||
}
|
||||
const promise = executeRefresh(conversationId, 'poll').finally(() => {
|
||||
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
|
||||
});
|
||||
inFlightRefresh = { conversationId, promise };
|
||||
await promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调度下一次轮询;失败时按退避间隔。
|
||||
*/
|
||||
@@ -264,7 +350,10 @@ export function useShippingNoticeWorkflow(
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
pollTimer = setTimeout(async () => {
|
||||
if (generation !== pollGeneration || pollingStopped) return;
|
||||
await refresh();
|
||||
const conversationId = normalizedConversationId.value;
|
||||
if (conversationId) {
|
||||
await runBackgroundPoll(conversationId);
|
||||
}
|
||||
if (generation !== pollGeneration || pollingStopped) return;
|
||||
if (!normalizedConversationId.value) return;
|
||||
if (error.value) {
|
||||
@@ -276,7 +365,7 @@ export function useShippingNoticeWorkflow(
|
||||
}
|
||||
const nextDelay = failureCount > 0
|
||||
? resolveProcessingPollBackoffMs(failureCount)
|
||||
: resolvePollMs();
|
||||
: resolvePollMs(processing.value);
|
||||
schedulePoll(generation, nextDelay);
|
||||
}, delayMs);
|
||||
}
|
||||
@@ -300,7 +389,7 @@ export function useShippingNoticeWorkflow(
|
||||
return;
|
||||
}
|
||||
if (!shouldContinueProcessingPolling(processing.value)) return;
|
||||
schedulePoll(generation, resolvePollMs());
|
||||
schedulePoll(generation, resolvePollMs(processing.value));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -315,6 +404,7 @@ export function useShippingNoticeWorkflow(
|
||||
processing.value = null;
|
||||
processingWorkItems.value = [];
|
||||
error.value = null;
|
||||
lastSemanticKey = '';
|
||||
}
|
||||
restartPolling();
|
||||
}, { immediate: true });
|
||||
@@ -344,6 +434,9 @@ export function useShippingNoticeWorkflow(
|
||||
processing,
|
||||
processingWorkItems,
|
||||
loading,
|
||||
initialLoading,
|
||||
manualRefreshing,
|
||||
polling,
|
||||
error,
|
||||
refresh,
|
||||
focusConversationTask,
|
||||
|
||||
@@ -2080,6 +2080,11 @@ export interface ShippingOrderReviewCase {
|
||||
build_eligibility?: ShippingOrderReviewBuildEligibility;
|
||||
} | null;
|
||||
available_actions: string[];
|
||||
/** 对话级可执行动作(与对话处理 GET 同源);仅 retryable 对象计入。 */
|
||||
conversation_allowed_actions?: Array<{
|
||||
code: string;
|
||||
eligible_count: number;
|
||||
}>;
|
||||
/** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */
|
||||
formal_editable_field_ids?: string[];
|
||||
/** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */
|
||||
@@ -2467,8 +2472,11 @@ export interface ShippingOrderReviewLineFulfillmentLine {
|
||||
source?: string | null;
|
||||
} | null;
|
||||
decision_source?: 'system' | 'user' | 'unknown' | null;
|
||||
/** @deprecated 使用 inventory_allowed_actions + line_allowed_actions */
|
||||
/** 行级统一「重试」是否可点;前端禁止用 inventory_allowed_actions 猜按钮。 */
|
||||
retryable?: boolean;
|
||||
/** @deprecated 内部诊断保留;UI 不消费 */
|
||||
allowed_actions?: string[];
|
||||
/** 内部动作码(诊断/执行);UI 不渲染 */
|
||||
inventory_allowed_actions?: string[];
|
||||
line_allowed_actions?: string[];
|
||||
auto_fulfill_error_message?: string | null;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* features/chat/views/ShippingOrderReviewView.spec.ts
|
||||
* 用途:锁定复核工作台布局重构阶段 1 的主结构与模式契约。
|
||||
* 用途:锁定复核工作台布局与统一重试契约。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n、vue-router mocks。
|
||||
* 逻辑:标准模式无对话上下文、无常驻 PDF 列;存在主编辑区/摘要侧栏/底栏确认按钮;
|
||||
* 敏感面板审计失败不打开;确认后推进失败可由 Case 投影刷新恢复。
|
||||
* 逻辑:标准模式无对话上下文、无常驻 PDF 列;底栏无「确认并创建任务」;
|
||||
* 正式 OT / STP 对象级重试走 /retry 或 STP retry;敏感面板审计失败不打开。
|
||||
*/
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { computed, ref } from 'vue';
|
||||
@@ -15,8 +15,9 @@ import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
|
||||
import {
|
||||
auditWorkspaceShippingOrderReviewEligibilityDetails,
|
||||
auditWorkspaceShippingOrderReviewVersionHistory,
|
||||
autoProgressWorkspaceShippingTask,
|
||||
getWorkspaceShippingTask,
|
||||
retryWorkspaceShippingOrderStpAutoCreate,
|
||||
retryWorkspaceShippingTask,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const focusSuggestionField = vi.fn();
|
||||
@@ -119,12 +120,16 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
|
||||
...actual,
|
||||
auditWorkspaceShippingOrderReviewVersionHistory: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
|
||||
auditWorkspaceShippingOrderReviewEligibilityDetails: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
|
||||
autoProgressWorkspaceShippingTask: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
retryWorkspaceShippingTask: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
retryWorkspaceShippingOrderStpAutoCreate: vi.fn().mockResolvedValue({
|
||||
status: 'queued',
|
||||
job_id: 901,
|
||||
case: null,
|
||||
}),
|
||||
getWorkspaceShippingTask: vi.fn().mockResolvedValue({
|
||||
task_no: 'SN-MOCK',
|
||||
status: 'created',
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -476,7 +481,6 @@ async function mountView() {
|
||||
},
|
||||
llmSuggestion: { request: '请求 AI' },
|
||||
restoreMachine: '恢复机器值',
|
||||
buildEligibility: { confirmBlocked: '不可建单' },
|
||||
saving: '保存中',
|
||||
saved: '已保存',
|
||||
saveFailed: '失败',
|
||||
@@ -502,16 +506,24 @@ async function mountView() {
|
||||
},
|
||||
},
|
||||
autoProgress: {
|
||||
status: { unknown: '', needs_retry: '待重试' },
|
||||
status: { unknown: '', needs_retry: '待重试', needs_human: '需要人工处理' },
|
||||
result: '{status}',
|
||||
checkpoint: '{checkpoint}',
|
||||
viewTask: '返回对话查看进度',
|
||||
returnToChat: '返回对话查看进度',
|
||||
retry: '重试自动推进',
|
||||
retryObject: '重试',
|
||||
retrySuccess: '已重新触发',
|
||||
retryStp: '重试自动推进',
|
||||
retryStpSuccess: '已重新入队自动建单',
|
||||
},
|
||||
conversationRetry: {
|
||||
title: '对话重试结果',
|
||||
retried: '已重试',
|
||||
skipped: '已跳过',
|
||||
failed: '失败',
|
||||
closeAndRefresh: '关闭并刷新',
|
||||
},
|
||||
currentProcessing: {
|
||||
title: '当前处理状态',
|
||||
status: '状态',
|
||||
@@ -536,6 +548,24 @@ async function mountView() {
|
||||
waitingPreOt: '等待自动建单',
|
||||
waitingPostOt: '等待系统启动自动推进',
|
||||
},
|
||||
buildEligibility: {
|
||||
confirmBlocked: '不可建单',
|
||||
autoGateWaitingHint: '资格已达标,等待系统自动建单',
|
||||
autoGateRunningHint: '系统正在自动推进',
|
||||
},
|
||||
fulfillmentDecision: {
|
||||
actions: '操作',
|
||||
availableQty: '可用',
|
||||
shortage: '缺口',
|
||||
},
|
||||
lineOps: {
|
||||
retry: '重试',
|
||||
moreActions: '更多操作',
|
||||
inventorySource: '库存源',
|
||||
},
|
||||
workflowProgress: {
|
||||
automatingFooterHint: '系统自动推进中',
|
||||
},
|
||||
confirmSuccess: '{taskNo}',
|
||||
confirmAutoProgress: '{taskNo}',
|
||||
confirmProgressFailed: '已创建任务 {taskNo},但自动推进失败,请重试推进',
|
||||
@@ -679,10 +709,11 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps confirm footer visible when draft exists', async () => {
|
||||
it('keeps footer actions without confirm-create when draft exists', async () => {
|
||||
const wrapper = await mountView();
|
||||
// 关键断言:底栏仍在,但正常路径不再暴露「确认并创建任务」。
|
||||
expect(wrapper.find('[data-testid="review-footer-actions"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders empty optional schema fields as editable line columns', async () => {
|
||||
@@ -802,11 +833,21 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
expect(messageMocks.warning).toHaveBeenCalledWith('审计记录失败,敏感面板未打开,请重试');
|
||||
});
|
||||
|
||||
it('restores amber retry banner from post_confirm_auto_progress after reload', async () => {
|
||||
it('restores object-level retry from post_confirm_auto_progress after reload', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed',
|
||||
has_formal_ot: true,
|
||||
task_missing: false,
|
||||
confirmed_task_id: 7,
|
||||
confirmed_task_no: 'SN-RECOVER-1',
|
||||
automation: {
|
||||
status: 'failed',
|
||||
retryable: true,
|
||||
phase: 'post_ot_progress',
|
||||
can_auto_create: false,
|
||||
can_build: true,
|
||||
},
|
||||
post_confirm_auto_progress: {
|
||||
task_no: 'SN-RECOVER-1',
|
||||
needs_retry: true,
|
||||
@@ -816,17 +857,16 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
const banner = wrapper.find('[data-testid="review-confirm-outcome"]');
|
||||
// 关键断言:页面重载后仍能从 Case 投影恢复推进失败重试入口。
|
||||
expect(banner.exists()).toBe(true);
|
||||
expect(banner.attributes('data-progress-failed')).toBe('true');
|
||||
expect(wrapper.find('[data-testid="retry-auto-progress-after-confirm"]').exists()).toBe(true);
|
||||
expect(banner.text()).toContain('SN-RECOVER-1');
|
||||
});
|
||||
// 关键断言:琥珀色确认条已移除;刷新后对象级重试挂在当前处理卡。
|
||||
expect(wrapper.find('[data-testid="review-confirm-outcome"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="retry-auto-progress-after-confirm"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-RECOVER-1');
|
||||
}, 15000);
|
||||
|
||||
it('retries formal OT auto-progress from main card after refresh without confirmSuccess (UI-01)', async () => {
|
||||
// 关键断言:刷新后无 confirmSuccess 时,主卡仍用 confirmed_task_no 调 auto-progress API。
|
||||
vi.mocked(autoProgressWorkspaceShippingTask).mockClear();
|
||||
it('retries formal OT via unified /retry from main card after refresh without confirmSuccess (UI-01)', async () => {
|
||||
// 关键断言:刷新后无 confirmSuccess 时,主卡仍用 confirmed_task_no 调统一 /retry(禁止 auto-progress)。
|
||||
vi.mocked(retryWorkspaceShippingTask).mockClear();
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed',
|
||||
@@ -854,8 +894,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
expect(retryBtn.exists()).toBe(true);
|
||||
await retryBtn.trigger('click');
|
||||
await flushPromises();
|
||||
expect(autoProgressWorkspaceShippingTask).toHaveBeenCalledWith('SN-OT-FAIL-1');
|
||||
});
|
||||
expect(retryWorkspaceShippingTask).toHaveBeenCalledWith('SN-OT-FAIL-1');
|
||||
}, 15000);
|
||||
|
||||
it('keeps top / wide / narrow stage labels identical via Progress projection (waiting_system_start)', async () => {
|
||||
// 关键断言:Case.current_stage 故意降级为误导码;三处必须消费 Progress label_key 文案。
|
||||
@@ -928,7 +968,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
...activeCase.value,
|
||||
status: 'ready',
|
||||
confirmed_task_no: null,
|
||||
available_actions: ['validate', 'confirm', 'retry_stp_auto_create'],
|
||||
available_actions: ['validate', 'retry_stp_auto_create'],
|
||||
automation: {
|
||||
status: 'failed',
|
||||
retryable: true,
|
||||
@@ -939,20 +979,21 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
const btn = wrapper.find('[data-testid="review-retry-stp-auto-create"]');
|
||||
// 关键断言:failed 态必须露出 STP 重试入口(非确认后 auto_progress 重试)。
|
||||
expect(btn.exists()).toBe(true);
|
||||
await btn.trigger('click');
|
||||
// 关键断言:failed 态主卡/底栏露出 STP 重试(非确认后 auto_progress)。
|
||||
const railBtn = wrapper.find('[data-testid="review-current-processing-retry"]');
|
||||
const footerBtn = wrapper.find('[data-testid="review-retry-stp-auto-create"]');
|
||||
expect(railBtn.exists() || footerBtn.exists()).toBe(true);
|
||||
await (railBtn.exists() ? railBtn : footerBtn).trigger('click');
|
||||
await flushPromises();
|
||||
expect(retryWorkspaceShippingOrderStpAutoCreate).toHaveBeenCalledWith('CASE-1');
|
||||
});
|
||||
}, 15000);
|
||||
|
||||
it('shows STP retry for manual_fallback while keeping confirm fallback (UI-02)', async () => {
|
||||
it('shows STP retry for manual_fallback without confirm-create (UI-02)', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'ready',
|
||||
confirmed_task_no: null,
|
||||
available_actions: ['validate', 'confirm', 'retry_stp_auto_create'],
|
||||
available_actions: ['validate', 'retry_stp_auto_create'],
|
||||
automation: {
|
||||
status: 'manual_fallback',
|
||||
retryable: true,
|
||||
@@ -963,9 +1004,13 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="review-retry-stp-auto-create"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(true);
|
||||
});
|
||||
expect(
|
||||
wrapper.find('[data-testid="review-current-processing-retry"]').exists()
|
||||
|| wrapper.find('[data-testid="review-retry-stp-auto-create"]').exists(),
|
||||
).toBe(true);
|
||||
// 关键断言:正常路径不再保留「确认并创建任务」兜底。
|
||||
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
|
||||
}, 15000);
|
||||
|
||||
it('hides profile match panel when profile_match.available is false', async () => {
|
||||
activeCase.value = {
|
||||
@@ -994,31 +1039,35 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('treats HTTP/confirm_ok success with confirm_outcome failed as progress failure', async () => {
|
||||
confirmMock.mockResolvedValueOnce({
|
||||
task_no: 'SN-CONFIRM-PROGRESS-FAIL',
|
||||
confirm_ok: true,
|
||||
confirm_outcome: 'confirmed_auto_progress_failed',
|
||||
auto_progress_started: false,
|
||||
auto_progress: {
|
||||
status: 'enqueue_failed',
|
||||
message: '入队失败',
|
||||
checkpoint: 'created',
|
||||
it('hydrates progress-failed retry state from Case projection without confirm UI', async () => {
|
||||
// 关键断言:无确认建单按钮时,仍可从 post_confirm_auto_progress 恢复对象级重试入口。
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed',
|
||||
has_formal_ot: true,
|
||||
task_missing: false,
|
||||
confirmed_task_id: 55,
|
||||
confirmed_task_no: 'SN-CONFIRM-PROGRESS-FAIL',
|
||||
automation: {
|
||||
status: 'failed',
|
||||
retryable: true,
|
||||
phase: 'post_ot_progress',
|
||||
can_auto_create: false,
|
||||
can_build: true,
|
||||
},
|
||||
case: activeCase.value,
|
||||
});
|
||||
post_confirm_auto_progress: {
|
||||
task_no: 'SN-CONFIRM-PROGRESS-FAIL',
|
||||
needs_retry: true,
|
||||
status: 'needs_retry',
|
||||
message: '入队失败',
|
||||
},
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
await wrapper.find('[data-testid="review-confirm-create"]').trigger('click');
|
||||
await flushPromises();
|
||||
await wrapper.find('[data-testid="review-action-confirm-submit"]').trigger('click');
|
||||
await flushPromises();
|
||||
const banner = wrapper.find('[data-testid="review-confirm-outcome"]');
|
||||
// 关键断言:不得仅凭 success/confirm_ok 判定推进成功;须读 confirm_outcome。
|
||||
expect(confirmMock).toHaveBeenCalled();
|
||||
expect(banner.exists()).toBe(true);
|
||||
expect(banner.attributes('data-progress-failed')).toBe('true');
|
||||
expect(messageMocks.warning).toHaveBeenCalled();
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-CONFIRM-PROGRESS-FAIL');
|
||||
}, 15000);
|
||||
});
|
||||
|
||||
describe('ShippingOrderReviewView viewport layout remediation', () => {
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
ReviewCurrentProcessingCard、ReviewCompletedChecksPanel、ReviewFieldCompletenessPanel、
|
||||
ReviewAutomationStatusPanel、ReviewBuildEligibilitySummary、ReviewInventory*、
|
||||
ReviewLineInventoryOps(履约操作并入明细右侧列)、ReviewLineFulfillmentDetail(行内履约摘要)、
|
||||
ProcessGateRecoveryCard;formal_task 仅显式动作挂载 TaskTodoPanel(主写在 Footer)。
|
||||
ProcessGateRecoveryCard;formal_task 仅显式动作挂载 TaskTodoPanel(主写在 Footer);
|
||||
shipping.api.retryWorkspaceConversationAutoProgress(对话级重试)。
|
||||
逻辑:建单前订单检查为主卡;正式 OT 后保持 standard,不自动切 formal_task 空壳;
|
||||
不挂当前处理/履约摘要重复卡;库存动作仅明细行浮层;写操作仅底栏。
|
||||
对话级「重试自动推进」在顶栏;当前 Case 对象级重试优先右栏 CurrentProcessingCard,
|
||||
仅当未挂载该卡时回落到底栏;库存动作仅明细行浮层;写操作仅底栏。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
@@ -28,16 +30,16 @@ import {
|
||||
import {
|
||||
auditWorkspaceShippingOrderReviewEligibilityDetails,
|
||||
auditWorkspaceShippingOrderReviewVersionHistory,
|
||||
autoProgressWorkspaceShippingTask,
|
||||
attemptWorkspaceShippingOrderReviewFieldLocate,
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment,
|
||||
getWorkspaceShippingOrderReviewEvidenceItem,
|
||||
getWorkspaceShippingTask,
|
||||
retryWorkspaceConversationAutoProgress,
|
||||
retryWorkspaceShippingOrderStpAutoCreate,
|
||||
retryWorkspaceShippingTask,
|
||||
retryWorkspaceShippingTaskLine,
|
||||
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
|
||||
} from '../api/shipping.api';
|
||||
import type {
|
||||
ShippingOrderReviewLineFulfillmentDecisionCode,
|
||||
ShippingOrderReviewLineFulfillmentLine,
|
||||
} from '../types/shipping.api.types';
|
||||
import ReviewActionConfirmDialog, {
|
||||
@@ -71,7 +73,6 @@ import ReviewWorkbenchHeader from '../components/shipping-review/ReviewWorkbench
|
||||
import ReviewWorkbenchModeToggle from '../components/shipping-review/ReviewWorkbenchModeToggle.vue';
|
||||
import ReviewUnsavedSwitchDialog from '../components/shipping-review/ReviewUnsavedSwitchDialog.vue';
|
||||
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
|
||||
import { postWorkspaceProcessGateAction } from '@/features/shipping-process-gates/api/process-gates.api';
|
||||
import TaskTodoPanel from '@/features/workspace/shipping-task-center/TaskTodoPanel.vue';
|
||||
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
|
||||
import ReviewLineNoOverrideDialog, {
|
||||
@@ -312,6 +313,42 @@ const evidenceFocusConsumed = ref(false);
|
||||
return Boolean(automation?.retryable) || (activeCase.value?.available_actions || []).includes('retry_stp_auto_create');
|
||||
});
|
||||
|
||||
/**
|
||||
* 对话级重试动作:后端 conversation_allowed_actions 中 retry_auto_progress 且 eligible_count>0。
|
||||
*/
|
||||
const conversationRetryAction = computed(() => {
|
||||
const actions = activeCase.value?.conversation_allowed_actions || [];
|
||||
return actions.find((item) => (
|
||||
item.code === 'retry_auto_progress' && Number(item.eligible_count || 0) > 0
|
||||
)) || null;
|
||||
});
|
||||
|
||||
/** 顶栏是否展示对话级「重试自动推进」。 */
|
||||
const showConversationRetry = computed(() => (
|
||||
Boolean(conversationRetryAction.value) && Boolean(String(conversationId.value || '').trim())
|
||||
));
|
||||
|
||||
/** 对话级可重试对象数量(徽标)。 */
|
||||
const conversationRetryEligibleCount = computed(() => (
|
||||
Number(conversationRetryAction.value?.eligible_count || 0)
|
||||
));
|
||||
|
||||
/**
|
||||
* 是否挂载右侧/窄屏「当前处理」卡:task_missing、正式 OT、或自动化进行中/失败态。
|
||||
* 核心逻辑:对象级重试优先挂在此卡上,未挂载时才回落底栏。
|
||||
*/
|
||||
const mountCurrentProcessingCard = computed(() => {
|
||||
if (!activeCase.value) return false;
|
||||
if (Boolean(activeCase.value.task_missing)) return true;
|
||||
if (hasFormalOt.value) return true;
|
||||
const status = String(activeCase.value.automation?.status || '').trim().toLowerCase();
|
||||
return ['waiting_to_start', 'queued', 'running', 'failed', 'manual_fallback'].includes(status);
|
||||
});
|
||||
|
||||
/** 对象级重试:有当前处理卡时放右栏/窄屏主卡;否则回落底栏。 */
|
||||
const showObjectRetryOnRail = computed(() => showStpRetry.value && mountCurrentProcessingCard.value);
|
||||
const showObjectRetryOnFooter = computed(() => showStpRetry.value && !mountCurrentProcessingCard.value);
|
||||
|
||||
/**
|
||||
* 正式 OT 后履约/库存卡片是否展开:仅 human + 可执行 blocking 时展开对应卡;
|
||||
* 系统等待/排队/运行默认折叠。
|
||||
@@ -435,10 +472,23 @@ const confirmSuccess = ref<{
|
||||
restoredFromProjection?: boolean;
|
||||
} | null>(null);
|
||||
const progressRetrying = ref(false);
|
||||
const conversationRetrying = ref(false);
|
||||
const conversationRetryResultOpen = ref(false);
|
||||
const conversationRetryResult = ref<{
|
||||
summary: { total: number; retried: number; skipped: number; failed: number };
|
||||
items: Array<{
|
||||
object_type: string;
|
||||
object_ref: string;
|
||||
action?: string | null;
|
||||
outcome: string;
|
||||
reason_code?: string | null;
|
||||
}>;
|
||||
} | null>(null);
|
||||
|
||||
/**
|
||||
* 从 Case 投影恢复「已建单但仍待推进」琥珀色重试条(覆盖页面刷新场景)。
|
||||
* 核心逻辑:仅当 post_confirm_auto_progress.needs_retry 时写入;不覆盖同会话即时 confirm 结果。
|
||||
* 注:确认成功琥珀色 UI 已移除(避免与对话级/对象级重试重复);本 hydrate 仍供内部状态与流程动作使用。
|
||||
*/
|
||||
function hydrateConfirmProgressFromCase() {
|
||||
const caseRow = activeCase.value;
|
||||
@@ -924,16 +974,6 @@ const openAuditTrail = () => {
|
||||
auditTrailOpen.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换行内履约摘要:只展开当前行,不进入库存工作台。
|
||||
* @param lineKey - 明细行键
|
||||
*/
|
||||
function toggleFulfillmentDetail(lineKey: string) {
|
||||
const key = String(lineKey || '').trim();
|
||||
if (!key) return;
|
||||
fulfillmentDetailLineKey.value = fulfillmentDetailLineKey.value === key ? null : key;
|
||||
}
|
||||
|
||||
/**
|
||||
* 收起行内履约摘要。
|
||||
*/
|
||||
@@ -1001,73 +1041,6 @@ function displayShortageQty(line: ShippingOrderReviewLineFulfillmentLine | null)
|
||||
return String(line.shortage_qty);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化用户态状态码(与文案/badge 共用)。
|
||||
*/
|
||||
function resolveUserLineStatusCode(line: ShippingOrderReviewLineFulfillmentLine | null): string {
|
||||
if (!line) return '';
|
||||
const inventoryPending = (
|
||||
line.display_available === 'pending'
|
||||
|| ['preparing', 'mapping_failed', 'source_conflict', 'unavailable', 'invalid_key'].includes(
|
||||
String(line.inventory_status || ''),
|
||||
)
|
||||
);
|
||||
let code = String(line.user_line_status || '').trim();
|
||||
if (inventoryPending && (!code || code === 'pending_decision')) {
|
||||
code = 'inventory_pending';
|
||||
} else if (!code) {
|
||||
code = String(line.line_status || '').trim();
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户态履约/库存状态文案(优先 user_line_status;库存未就绪时不展示「待决定」)。
|
||||
* 核心逻辑:display_available=pending 或 preparing/conflict 等 → inventory_pending;
|
||||
* 仅在库存数字已就绪后才信任 pending_decision / line_status。
|
||||
*/
|
||||
function userLineStatusLabel(line: ShippingOrderReviewLineFulfillmentLine | null): string {
|
||||
const code = resolveUserLineStatusCode(line);
|
||||
if (!code) return '—';
|
||||
const key = `chat.shippingOrderReview.fulfillmentDecision.userLineStatus.${code}`;
|
||||
if (te(key)) return t(key);
|
||||
const legacy = `chat.shippingOrderReview.fulfillmentDecision.lineStatus.${code}`;
|
||||
return te(legacy) ? t(legacy) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态列 badge 视觉层级(UI-4):短缺/失败强调,进度次之,终态弱化。
|
||||
*/
|
||||
function userLineStatusBadgeClass(line: ShippingOrderReviewLineFulfillmentLine | null): string {
|
||||
const code = resolveUserLineStatusCode(line);
|
||||
const base = 'inline-flex max-w-full items-center rounded-md px-1.5 py-0.5 text-[11px] font-medium leading-tight';
|
||||
switch (code) {
|
||||
case 'shortage':
|
||||
case 'auto_fulfill_failed':
|
||||
case 'inventory_file_expired':
|
||||
return `${base} bg-rose-100 text-rose-800 dark:bg-rose-950/60 dark:text-rose-200`;
|
||||
case 'source_conflict':
|
||||
case 'invalid':
|
||||
case 'inventory_source_unrecognized':
|
||||
case 'inventory_file_missing':
|
||||
case 'inventory_match_failed':
|
||||
return `${base} bg-amber-100 text-amber-900 dark:bg-amber-950/50 dark:text-amber-100`;
|
||||
case 'inventory_pending':
|
||||
case 'acquiring_inventory':
|
||||
case 'auto_fulfilling':
|
||||
return `${base} bg-sky-100 text-sky-900 dark:bg-sky-950/50 dark:text-sky-100`;
|
||||
case 'wave_created':
|
||||
case 'ready_to_fulfill':
|
||||
case 'inventory_matched':
|
||||
return `${base} bg-emerald-100 text-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100`;
|
||||
case 'fulfilled':
|
||||
case 'closed':
|
||||
return `${base} bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300`;
|
||||
default:
|
||||
return `${base} bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 只读库存源展示(后端 inventory_source;禁止前端推断)。
|
||||
*/
|
||||
@@ -1084,6 +1057,15 @@ function displayInventorySource(line: ShippingOrderReviewLineFulfillmentLine | n
|
||||
if (label && code) return `${label}(${code})`;
|
||||
if (label) return label;
|
||||
if (code) return code;
|
||||
// 建单后最终行级库存源尚未匹配时,展示建单前已冻结的候选集合,
|
||||
// 避免把“已识别候选”误显示为空;最终 source 仍只由后端履约投影提供。
|
||||
const candidate = (buildEligibility.value?.line_projections || []).find(
|
||||
(item) => String(item.line_key || '') === String(line.line_key || ''),
|
||||
);
|
||||
const candidates = (candidate?.candidate_inventory_source_codes || [])
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean);
|
||||
if (candidates.length) return candidates.join(', ');
|
||||
return '—';
|
||||
}
|
||||
|
||||
@@ -1100,27 +1082,44 @@ function displayAvailableQty(line: ShippingOrderReviewLineFulfillmentLine | null
|
||||
|
||||
const lineOpsBusyKey = ref<string | null>(null);
|
||||
|
||||
/** 库存文件缺失/过期或库存匹配失败时,复用当前 Process Gate 的 RPA 重试动作。 */
|
||||
async function retryLineInventoryRpa(lineKey: string, actionCode: string) {
|
||||
const gate = activeCase.value?.process_gate;
|
||||
const executionNo = String(gate?.execution_no || '').trim();
|
||||
const blockingGate = gate?.current_blocking_gate;
|
||||
const gateCode = String(blockingGate?.gate_code || '').trim();
|
||||
const expectedVersion = Number(blockingGate?.evaluation_version || 0);
|
||||
if (!executionNo || !gateCode || !actionCode || !Number.isFinite(expectedVersion) || expectedVersion < 1) {
|
||||
/** 任务整体 queued/running:行级写操作隐藏/禁用。 */
|
||||
const taskAutomationRunning = computed(() => {
|
||||
const status = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
|
||||
return ['queued', 'running', 'processing', 'automating'].includes(status);
|
||||
});
|
||||
|
||||
/**
|
||||
* 明细行统一「重试」:POST .../lines/{line_key}/retry;不传内部动作码。
|
||||
*/
|
||||
async function retryLineUnified(lineKey: string) {
|
||||
const key = String(lineKey || '').trim();
|
||||
if (!key || taskAutomationRunning.value || caseSwitchLoading.value) {
|
||||
msg.warning(t('chat.shippingOrderReview.lineOps.retryRpaUnavailable'));
|
||||
return;
|
||||
}
|
||||
lineOpsBusyKey.value = lineKey;
|
||||
const taskNo = String(
|
||||
confirmedNoticeTaskNo.value
|
||||
|| activeCase.value?.confirmed_task_no
|
||||
|| formalOtRetryTaskNo.value
|
||||
|| '',
|
||||
).trim();
|
||||
if (!taskNo) {
|
||||
msg.warning(t('chat.shippingOrderReview.lineOps.retryRpaUnavailable'));
|
||||
return;
|
||||
}
|
||||
lineOpsBusyKey.value = key;
|
||||
try {
|
||||
await postWorkspaceProcessGateAction(executionNo, gateCode, {
|
||||
action_code: actionCode,
|
||||
expected_gate_version: expectedVersion,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
payload: { line_key: lineKey },
|
||||
});
|
||||
msg.success(t('chat.shippingOrderReview.lineOps.retryRpaSubmitted'));
|
||||
const result = await retryWorkspaceShippingTaskLine(taskNo, key);
|
||||
const status = String(result?.status || '').trim().toLowerCase();
|
||||
if (status === 'needs_human') {
|
||||
msg.warning(String(result?.message || t('chat.shippingOrderReview.autoProgress.status.needs_human')));
|
||||
} else if (status === 'failed') {
|
||||
msg.warning(String(result?.message || t('chat.shippingOrderReview.lineOps.retryRpaFailed')));
|
||||
} else {
|
||||
msg.success(t('chat.shippingOrderReview.lineOps.retryRpaSubmitted'));
|
||||
}
|
||||
await reloadLatestDraft();
|
||||
void refreshShippingProcessing();
|
||||
} catch (error) {
|
||||
msg.error(
|
||||
error instanceof BusinessError
|
||||
@@ -1133,40 +1132,10 @@ async function retryLineInventoryRpa(lineKey: string, actionCode: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 行内履约决定(等待/关闭);换源只导航。
|
||||
* Case 级库存兜底卡「重试」:走任务级统一决策器(无行键时)。
|
||||
*/
|
||||
async function onLineFulfillmentDecide(
|
||||
lineKey: string,
|
||||
code: ShippingOrderReviewLineFulfillmentDecisionCode,
|
||||
) {
|
||||
if (code === 'close_unfulfillable') {
|
||||
openCloseFulfillmentDialog([lineKey]);
|
||||
return;
|
||||
}
|
||||
// 更换库存源已取消:客户指定源不可覆盖,不再导航库存工作台。
|
||||
if (code === 'change_inventory_source') {
|
||||
return;
|
||||
}
|
||||
const caseNo = String(activeCase.value?.case_no || '').trim();
|
||||
if (!caseNo || lineOpsBusyKey.value) return;
|
||||
lineOpsBusyKey.value = lineKey;
|
||||
try {
|
||||
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
|
||||
line_key: lineKey,
|
||||
decision_code: code,
|
||||
expected_draft_version: activeCase.value?.draft?.draft_version ?? undefined,
|
||||
});
|
||||
msg.success(t('chat.shippingOrderReview.fulfillmentDecision.decideSuccess'));
|
||||
await reloadLatestDraft();
|
||||
} catch (error) {
|
||||
msg.error(
|
||||
error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: t('chat.shippingOrderReview.fulfillmentDecision.decideFailed'),
|
||||
);
|
||||
} finally {
|
||||
lineOpsBusyKey.value = null;
|
||||
}
|
||||
async function retryCaseInventoryFallback() {
|
||||
await retryFormalOtAutoProgress();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1324,8 +1293,8 @@ const canEnterInventory = computed(() => {
|
||||
});
|
||||
const availableActions = computed(() => activeCase.value?.available_actions || []);
|
||||
|
||||
/** 订单处理工作台写权限(只读查看为 false)。 */
|
||||
const workbenchActionsExecutable = computed(() => !isReadOnly.value);
|
||||
/** 订单处理工作台写权限(只读查看 / Case 切换中为 false)。 */
|
||||
const workbenchActionsExecutable = computed(() => !isReadOnly.value && !caseSwitchLoading.value);
|
||||
|
||||
/** 当前 Case 面板可用性,供注册表 requiresPanel 守卫。 */
|
||||
const workbenchPanelAvailability = computed((): WorkbenchPanelAvailability => {
|
||||
@@ -1566,7 +1535,7 @@ const linesTableMinWidthClass = computed(() => {
|
||||
const linesTableColumnCount = computed(() => {
|
||||
let count = 1 + visibleLineSchemaFields.value.length + 1; // # + schema + ops
|
||||
if (!showLineInventoryColumns.value) return count;
|
||||
count += 2; // inventory source + status
|
||||
count += 1; // inventory source only(available/shortage 已由 qty 字段计入)
|
||||
if (hasVisibleQtyField.value) {
|
||||
count += visibleLineSchemaFields.value.filter((field) => isQtySchemaField(field)).length * 2;
|
||||
} else {
|
||||
@@ -1798,46 +1767,13 @@ const actionDialogOpen = ref(false);
|
||||
const lineNoOverrideOpen = ref(false);
|
||||
const pendingLineNoEdit = ref<{ lineKey: string; fieldId: string; value: string } | null>(null);
|
||||
|
||||
/** 将自动推进结果映射为本地化状态;服务端 message 继续作为具体停留原因。 */
|
||||
const autoProgressStatusLabel = (status: string) => {
|
||||
const normalized = String(status || '').trim();
|
||||
const key = `chat.shippingOrderReview.autoProgress.status.${normalized}`;
|
||||
return normalized && te(key) ? t(key) : t('chat.shippingOrderReview.autoProgress.status.unknown');
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认后主路径留在复核页:统一动作栏驱动重试/刷新/任务台;返回对话仅作次要链接。
|
||||
*/
|
||||
const openTaskProgress = (orderTaskNo: string, noticeNo?: string) => {
|
||||
const focusNo = String(orderTaskNo || '').trim();
|
||||
const notice = String(noticeNo || '').trim();
|
||||
// [UI-01] 无 OT 时禁止用 Notice 编号冒充 focus_task_no。
|
||||
if (!focusNo) return;
|
||||
const activeConversationId = String(route.query.conversation_id || conversationId.value || '').trim();
|
||||
const bannerNo = focusNo || notice;
|
||||
// [STEP] toast + focus_task_no=OT;禁止用 SN Notice 编号选中进度卡。
|
||||
msg.success(t('chat.shippingOrderReview.autoProgress.returnedFocusHint', { taskNo: bannerNo }));
|
||||
void router.replace({
|
||||
name: 'Chat',
|
||||
params: { agentId: agentId.value },
|
||||
query: {
|
||||
conversation_id: activeConversationId || undefined,
|
||||
focus_task_no: focusNo || undefined,
|
||||
focus_notice_no: notice || undefined,
|
||||
focus_run_no: String(runNo.value || '').trim() || undefined,
|
||||
focus_notice: '1',
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 正式 OT auto-progress 共用重试:POST /shipping-tasks/<taskNo>/auto-progress。
|
||||
* 核心逻辑:taskNo 来自参数 / confirmed_task_no / post_confirm;不依赖即时 confirmSuccess;
|
||||
* task_missing 或无 task_no 时不请求。
|
||||
* @param preferredTaskNo - 即时确认条可传入 outcome.taskNo
|
||||
* 正式 OT 用户侧重试:POST /shipping-tasks/<taskNo>/retry(统一决策器)。
|
||||
* 核心逻辑:禁止再调 auto-progress;task_missing 或无 task_no 时不请求。
|
||||
* @param preferredTaskNo - 可选任务号覆盖
|
||||
*/
|
||||
const retryFormalOtAutoProgress = async (preferredTaskNo?: string | null) => {
|
||||
if (Boolean(activeCase.value?.task_missing) || progressRetrying.value) return;
|
||||
if (Boolean(activeCase.value?.task_missing) || progressRetrying.value || caseSwitchLoading.value) return;
|
||||
const taskNo = String(
|
||||
preferredTaskNo
|
||||
|| formalOtRetryTaskNo.value
|
||||
@@ -1847,7 +1783,7 @@ const retryFormalOtAutoProgress = async (preferredTaskNo?: string | null) => {
|
||||
if (!taskNo) return;
|
||||
progressRetrying.value = true;
|
||||
try {
|
||||
const result = await autoProgressWorkspaceShippingTask(taskNo);
|
||||
const result = await retryWorkspaceShippingTask(taskNo);
|
||||
const status = String(result?.status || 'ok');
|
||||
const progressFailed = ['failed', 'enqueue_failed', 'sync_execution_failed'].includes(status);
|
||||
if (confirmSuccess.value?.taskNo === taskNo || confirmSuccess.value) {
|
||||
@@ -1866,6 +1802,8 @@ const retryFormalOtAutoProgress = async (preferredTaskNo?: string | null) => {
|
||||
}
|
||||
if (progressFailed) {
|
||||
msg.warning(t('chat.shippingOrderReview.confirmProgressFailed', { taskNo }));
|
||||
} else if (status === 'needs_human') {
|
||||
msg.warning(String(result?.message || t('chat.shippingOrderReview.autoProgress.status.needs_human')));
|
||||
} else {
|
||||
msg.success(t('chat.shippingOrderReview.autoProgress.retrySuccess'));
|
||||
}
|
||||
@@ -1879,16 +1817,7 @@ const retryFormalOtAutoProgress = async (preferredTaskNo?: string | null) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* 即时确认条重试:保留原入口,内部委托共用封装。
|
||||
*/
|
||||
const retryAutoProgressAfterConfirm = async () => {
|
||||
const outcome = confirmSuccess.value;
|
||||
if (!outcome?.taskNo || progressRetrying.value) return;
|
||||
await retryFormalOtAutoProgress(outcome.taskNo);
|
||||
};
|
||||
|
||||
/**
|
||||
* 底栏「重试自动推进」:正式 OT 走 auto-progress;建单前走 STP retry。
|
||||
* 底栏对象级「重试」兜底:正式 OT 走统一 /retry;建单前走 STP。
|
||||
*/
|
||||
const onFooterRetryAutomation = async () => {
|
||||
if (hasFormalOt.value) {
|
||||
@@ -1904,7 +1833,7 @@ const onFooterRetryAutomation = async () => {
|
||||
*/
|
||||
const retryStpAutoCreate = async () => {
|
||||
const caseNo = String(activeCase.value?.case_no || '').trim();
|
||||
if (!caseNo || progressRetrying.value) return;
|
||||
if (!caseNo || progressRetrying.value || caseSwitchLoading.value) return;
|
||||
progressRetrying.value = true;
|
||||
try {
|
||||
const result = await retryWorkspaceShippingOrderStpAutoCreate(caseNo);
|
||||
@@ -1921,6 +1850,52 @@ const retryStpAutoCreate = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 对话级「重试自动推进」:扫描会话下可恢复 Case/正式 OT。
|
||||
* 核心逻辑:调用 retryWorkspaceConversationAutoProgress;打开结果弹窗;刷新草稿与处理投影。
|
||||
*/
|
||||
const retryConversationAutoProgress = async () => {
|
||||
const id = String(conversationId.value || '').trim();
|
||||
if (!id || conversationRetrying.value || !showConversationRetry.value) return;
|
||||
if (caseSwitchLoading.value || progressRetrying.value) return;
|
||||
conversationRetrying.value = true;
|
||||
try {
|
||||
const result = await retryWorkspaceConversationAutoProgress(id);
|
||||
conversationRetryResult.value = {
|
||||
summary: result.summary,
|
||||
items: result.items || [],
|
||||
};
|
||||
conversationRetryResultOpen.value = true;
|
||||
await reloadLatestDraft();
|
||||
await refreshShippingProcessing();
|
||||
} catch (error) {
|
||||
msg.error(resolveReviewErrorMessage(error));
|
||||
} finally {
|
||||
conversationRetrying.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 「关闭并刷新」:关闭对话级重试结果弹窗并重新拉取工作台投影。
|
||||
*/
|
||||
const closeConversationRetryResult = async () => {
|
||||
conversationRetryResultOpen.value = false;
|
||||
conversationRetryResult.value = null;
|
||||
await reloadLatestDraft();
|
||||
await refreshShippingProcessing();
|
||||
};
|
||||
|
||||
/**
|
||||
* 对话级重试跳过原因文案:优先 i18n reason.*,否则回退原始 reason_code。
|
||||
* @param reasonCode - 后端 reason_code
|
||||
*/
|
||||
const conversationRetrySkipReasonLabel = (reasonCode?: string | null) => {
|
||||
const code = String(reasonCode || '').trim();
|
||||
if (!code) return '';
|
||||
const key = `chat.shippingOrderReview.conversationRetry.reason.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
};
|
||||
|
||||
/**
|
||||
* 滚动到工作台锚点(data-testid)。
|
||||
*/
|
||||
@@ -2109,7 +2084,7 @@ const onUnifiedProcessingAction = async (item: ActionPresentationItem) => {
|
||||
}
|
||||
|
||||
if (behavior === 'retry') {
|
||||
await retryAutoProgressAfterConfirm();
|
||||
await retryFormalOtAutoProgress();
|
||||
await refreshShippingProcessing();
|
||||
return;
|
||||
}
|
||||
@@ -2626,9 +2601,14 @@ watch(
|
||||
:is-read-only="isReadOnly"
|
||||
:show-version-history="Boolean(activeCase)"
|
||||
:show-audit-trail="Boolean(activeCase)"
|
||||
:show-conversation-retry="showConversationRetry"
|
||||
:conversation-retry-eligible-count="conversationRetryEligibleCount"
|
||||
:conversation-retrying="conversationRetrying"
|
||||
:conversation-retry-disabled="caseSwitchLoading || progressRetrying"
|
||||
@back="back"
|
||||
@open-version-history="openVersionHistory"
|
||||
@open-audit-trail="openAuditTrail"
|
||||
@retry-conversation-auto-progress="() => void retryConversationAutoProgress()"
|
||||
/>
|
||||
|
||||
<div
|
||||
@@ -2707,63 +2687,6 @@ watch(
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="confirmSuccess"
|
||||
class="mx-4 mt-3 rounded-xl px-3 py-2 text-sm"
|
||||
:class="confirmSuccess.progressFailed
|
||||
? 'border border-amber-300 bg-amber-50 text-amber-950 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-100'
|
||||
: 'border border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-100'"
|
||||
data-testid="review-confirm-outcome"
|
||||
:data-progress-failed="confirmSuccess.progressFailed ? 'true' : 'false'"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<p>
|
||||
{{ confirmSuccess.progressFailed
|
||||
? t('chat.shippingOrderReview.confirmProgressFailed', { taskNo: confirmSuccess.taskNo })
|
||||
: confirmSuccess.autoProgress
|
||||
? t('chat.shippingOrderReview.confirmAutoProgress', { taskNo: confirmSuccess.taskNo })
|
||||
: t('chat.shippingOrderReview.confirmSuccess', { taskNo: confirmSuccess.taskNo }) }}
|
||||
</p>
|
||||
<p v-if="confirmSuccess.progressStatus" class="mt-1 text-xs">
|
||||
{{ t('chat.shippingOrderReview.autoProgress.result', { status: autoProgressStatusLabel(confirmSuccess.progressStatus) }) }}
|
||||
</p>
|
||||
<p v-if="confirmSuccess.progressMessage" class="mt-1 text-xs">{{ confirmSuccess.progressMessage }}</p>
|
||||
<p v-if="confirmSuccess.checkpoint" class="mt-1 text-xs text-amber-800 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.autoProgress.checkpoint', { checkpoint: confirmSuccess.checkpoint }) }}
|
||||
</p>
|
||||
<p
|
||||
v-if="shippingProcessingSummaryLabel"
|
||||
class="mt-1 text-xs"
|
||||
data-testid="review-shipping-processing-summary"
|
||||
>
|
||||
{{ shippingProcessingSummaryLabel }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 flex-wrap items-center gap-2">
|
||||
<button
|
||||
v-if="confirmSuccess.progressFailed"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded border border-amber-500 bg-amber-100/80 px-2.5 py-1.5 text-xs font-medium hover:bg-amber-100 disabled:opacity-50 dark:bg-amber-900/40 dark:hover:bg-amber-900"
|
||||
:disabled="progressRetrying"
|
||||
data-testid="retry-auto-progress-after-confirm"
|
||||
@click="retryAutoProgressAfterConfirm"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.autoProgress.retry') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="confirmSuccess.orderTaskNo"
|
||||
type="button"
|
||||
class="text-xs font-medium text-emerald-800 underline hover:text-emerald-950 dark:text-emerald-200 dark:hover:text-emerald-50"
|
||||
data-testid="open-confirmed-task-progress-link"
|
||||
@click="openTaskProgress(confirmSuccess.orderTaskNo, confirmSuccess.taskNo)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.autoProgress.returnToChat') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 确认后统一进度主路径留在本页;返回对话仅作次要聚焦链接。 -->
|
||||
|
||||
<div v-if="loading" class="p-8 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.loading') }}</div>
|
||||
@@ -3037,13 +2960,13 @@ watch(
|
||||
@set-mode="onWorkbenchModeChange"
|
||||
/>
|
||||
|
||||
<!-- 窄屏:仅展示真正阻断卡;正式 OT 后不挂当前处理/履约摘要重复卡 -->
|
||||
<!-- 窄屏:阻断卡 + 当前处理卡(对象级重试优先于此) -->
|
||||
<div
|
||||
class="space-y-2 xl:hidden"
|
||||
data-testid="review-primary-blockers-narrow"
|
||||
>
|
||||
<ReviewCurrentProcessingCard
|
||||
v-if="!hasFormalOt && activeCase?.task_missing"
|
||||
v-if="mountCurrentProcessingCard"
|
||||
:stage-code="currentProcessingStageDisplay.code"
|
||||
:stage-label-key="currentProcessingStageDisplay.labelKey"
|
||||
:stage-inconsistent="currentProcessingStageDisplay.inconsistent"
|
||||
@@ -3052,15 +2975,15 @@ watch(
|
||||
:confirmed-task-id="activeCase?.confirmed_task_id"
|
||||
:show-admin-diagnosis="showAdminTaskMissingDiagnosis"
|
||||
:automation="activeCase?.automation"
|
||||
:show-retry="false"
|
||||
:retrying="progressRetrying"
|
||||
@retry="() => void retryFormalOtAutoProgress()"
|
||||
:show-retry="showObjectRetryOnRail"
|
||||
:retrying="progressRetrying || caseSwitchLoading"
|
||||
@retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"
|
||||
/>
|
||||
<ReviewInventoryIssueFallbackCard
|
||||
v-if="hasFormalOt && activeCase?.inventory_issue_fallback && !activeCase?.line_fulfillment?.has_line_inventory_projection"
|
||||
:fallback="activeCase.inventory_issue_fallback"
|
||||
:busy="Boolean(lineOpsBusyKey)"
|
||||
@retry-preparation="() => void retryLineInventoryRpa('case', 'retry_inventory_preparation')"
|
||||
@retry-preparation="() => void retryCaseInventoryFallback()"
|
||||
/>
|
||||
<ProcessGateRecoveryCard
|
||||
v-if="!reparseProgressActive && showHumanBlockingGate && activeCase?.process_gate"
|
||||
@@ -3337,12 +3260,6 @@ watch(
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}
|
||||
</th>
|
||||
</template>
|
||||
<th
|
||||
v-if="showLineInventoryColumns"
|
||||
class="min-w-24 border-b border-slate-200 px-2 py-1.5 font-medium dark:border-slate-800"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.status') }}
|
||||
</th>
|
||||
<th class="sticky right-0 z-10 min-w-28 border-b border-slate-200 bg-slate-50 px-2 py-1.5 dark:border-slate-800 dark:bg-slate-950">
|
||||
<span class="sr-only">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</span>
|
||||
</th>
|
||||
@@ -3484,14 +3401,6 @@ watch(
|
||||
{{ displayShortageQty(lineFulfillmentFor(String(line.line_key || ''))) }}
|
||||
</td>
|
||||
</template>
|
||||
<td v-if="showLineInventoryColumns" class="px-2 py-1.5 align-middle">
|
||||
<span
|
||||
:class="userLineStatusBadgeClass(lineFulfillmentFor(String(line.line_key || '')))"
|
||||
data-testid="review-line-status-badge"
|
||||
>
|
||||
{{ userLineStatusLabel(lineFulfillmentFor(String(line.line_key || ''))) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="sticky right-0 z-10 min-w-28 whitespace-nowrap bg-white px-2 py-1.5 dark:bg-slate-900">
|
||||
<div class="flex items-center justify-end gap-0.5">
|
||||
<button
|
||||
@@ -3520,9 +3429,9 @@ watch(
|
||||
:line="lineFulfillmentFor(String(line.line_key || ''))"
|
||||
:editable="editable"
|
||||
:busy="lineOpsBusyKey === String(line.line_key || '') || saving"
|
||||
@retry-inventory="(actionCode) => void retryLineInventoryRpa(String(line.line_key || ''), actionCode)"
|
||||
:task-running="taskAutomationRunning"
|
||||
@retry-line="() => void retryLineUnified(String(line.line_key || ''))"
|
||||
@close-line="openCloseFulfillmentDialog([String(line.line_key || '')])"
|
||||
@view-fulfillment="toggleFulfillmentDetail(String(line.line_key || ''))"
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
@@ -3569,10 +3478,10 @@ watch(
|
||||
data-testid="review-build-gate-rail"
|
||||
:aria-label="t('chat.shippingOrderReview.workbench.summaryRail')"
|
||||
>
|
||||
<!-- 宽屏侧栏:建单前订单检查;正式 OT 后不挂当前处理/履约摘要重复卡 -->
|
||||
<!-- 宽屏侧栏:建单前订单检查 + 当前处理卡(对象级重试优先于此) -->
|
||||
<div class="hidden space-y-2 xl:block" data-testid="review-primary-blockers-wide">
|
||||
<ReviewCurrentProcessingCard
|
||||
v-if="!hasFormalOt && activeCase?.task_missing"
|
||||
v-if="mountCurrentProcessingCard"
|
||||
:stage-code="currentProcessingStageDisplay.code"
|
||||
:stage-label-key="currentProcessingStageDisplay.labelKey"
|
||||
:stage-inconsistent="currentProcessingStageDisplay.inconsistent"
|
||||
@@ -3581,15 +3490,15 @@ watch(
|
||||
:confirmed-task-id="activeCase?.confirmed_task_id"
|
||||
:show-admin-diagnosis="showAdminTaskMissingDiagnosis"
|
||||
:automation="activeCase?.automation"
|
||||
:show-retry="false"
|
||||
:retrying="progressRetrying"
|
||||
@retry="() => void retryFormalOtAutoProgress()"
|
||||
:show-retry="showObjectRetryOnRail"
|
||||
:retrying="progressRetrying || caseSwitchLoading"
|
||||
@retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"
|
||||
/>
|
||||
<ReviewInventoryIssueFallbackCard
|
||||
v-if="hasFormalOt && activeCase?.inventory_issue_fallback && !activeCase?.line_fulfillment?.has_line_inventory_projection"
|
||||
:fallback="activeCase.inventory_issue_fallback"
|
||||
:busy="Boolean(lineOpsBusyKey)"
|
||||
@retry-preparation="() => void retryLineInventoryRpa('case', 'retry_inventory_preparation')"
|
||||
@retry-preparation="() => void retryCaseInventoryFallback()"
|
||||
/>
|
||||
<ReviewCustomerResolutionPanel
|
||||
v-if="activeCase && !activeCase.customer_resolution?.resolved && showEligibilityAsPrimary"
|
||||
@@ -3845,7 +3754,7 @@ watch(
|
||||
:can-confirm-build="canConfirmBuild"
|
||||
:hide-confirm-because-auto-gate="hideConfirmBecauseAutoGate"
|
||||
:show-auto-gate-hint="showAutoGateHint"
|
||||
:show-stp-retry="showStpRetry"
|
||||
:show-stp-retry="showObjectRetryOnFooter"
|
||||
:auto-gate-hint="t(autoGateHintKey)"
|
||||
:saving="saving"
|
||||
:is-read-only="isReadOnly"
|
||||
@@ -3884,6 +3793,56 @@ watch(
|
||||
@save-and-switch="() => { void saveAndSwitchCase(); }"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="conversationRetryResultOpen && conversationRetryResult"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
|
||||
data-testid="review-conversation-retry-result"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
>
|
||||
<div class="w-full max-w-md rounded-xl border border-slate-200 bg-white p-4 shadow-xl dark:border-slate-700 dark:bg-slate-900">
|
||||
<h2 class="text-sm font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ t('chat.shippingOrderReview.conversationRetry.title') }}
|
||||
</h2>
|
||||
<dl class="mt-3 space-y-1 text-xs text-slate-700 dark:text-slate-200">
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt>{{ t('chat.shippingOrderReview.conversationRetry.retried') }}</dt>
|
||||
<dd data-testid="review-conversation-retry-retried">{{ conversationRetryResult.summary.retried }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt>{{ t('chat.shippingOrderReview.conversationRetry.skipped') }}</dt>
|
||||
<dd data-testid="review-conversation-retry-skipped">{{ conversationRetryResult.summary.skipped }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-3">
|
||||
<dt>{{ t('chat.shippingOrderReview.conversationRetry.failed') }}</dt>
|
||||
<dd data-testid="review-conversation-retry-failed">{{ conversationRetryResult.summary.failed }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<ul
|
||||
v-if="conversationRetryResult.items.some((item) => item.outcome === 'skipped')"
|
||||
class="mt-3 max-h-40 space-y-1 overflow-y-auto text-xs text-slate-600 dark:text-slate-300"
|
||||
data-testid="review-conversation-retry-skip-list"
|
||||
>
|
||||
<li
|
||||
v-for="item in conversationRetryResult.items.filter((row) => row.outcome === 'skipped')"
|
||||
:key="`${item.object_type}:${item.object_ref}`"
|
||||
>
|
||||
{{ item.object_ref }}:{{ conversationRetrySkipReasonLabel(item.reason_code) || t('chat.shippingOrderReview.conversationRetry.skipped') }}
|
||||
</li>
|
||||
</ul>
|
||||
<div class="mt-4 flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded bg-sky-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-sky-500"
|
||||
data-testid="review-conversation-retry-close-refresh"
|
||||
@click="() => void closeConversationRetryResult()"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.conversationRetry.closeAndRefresh') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ReviewActionConfirmDialog
|
||||
v-if="actionDialogOpen && pendingAction"
|
||||
v-model="actionDialogOpen"
|
||||
|
||||
@@ -84,6 +84,22 @@ describe('resolveProcessingActionPresentation', () => {
|
||||
expect([result.primary, result.secondary, ...result.overflow].some((i) => i?.intent === 'refresh')).toBe(false);
|
||||
});
|
||||
|
||||
it('available_actions 乱序 / 大小写空格 / 重复不影响输出按钮顺序', () => {
|
||||
const order1 = resolveProcessingActionPresentation(projection({
|
||||
availableActions: [' Refresh ', 'view_details', 'retry_parse', 'view_details'],
|
||||
}), { surface: 'chat', actionsExecutable: true });
|
||||
const order2 = resolveProcessingActionPresentation(projection({
|
||||
availableActions: ['retry_parse', 'VIEW_DETAILS', 'refresh'],
|
||||
}), { surface: 'chat', actionsExecutable: true });
|
||||
// presentation 主/次/溢出的 intent 序列必须相同,不受后端原始顺序影响。
|
||||
const intentChain = (r: typeof order1) => [
|
||||
r.primary?.intent ?? null,
|
||||
r.secondary?.intent ?? null,
|
||||
...r.overflow.map((o) => o.intent),
|
||||
].join('|');
|
||||
expect(intentChain(order1)).toBe(intentChain(order2));
|
||||
});
|
||||
|
||||
it('maps open_order_review label to processing entry on chat surface', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
availableActions: ['open_order_review'],
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
ShippingProcessingActionIntent,
|
||||
ShippingProcessingProjection,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { normalizeActionCodes } from '@/features/chat/shipping/conversationProcessingProjection';
|
||||
import type { ActionPresentation, ActionPresentationItem, ActionPresentationSurface } from './types';
|
||||
import type { WorkbenchPanelAvailability } from './workbenchActionRegistry';
|
||||
import {
|
||||
@@ -65,6 +66,10 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
|
||||
};
|
||||
|
||||
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
|
||||
const NEEDS_ACTION_STATUSES = new Set([
|
||||
'blocked', 'waiting_review', 'pending_review', 'failed', 'reparse_failed',
|
||||
'manual_upload_pending', 'upload_rpa_failed',
|
||||
]);
|
||||
/** 永不升为主 CTA 的动作码(仍可作次要/溢出)。 */
|
||||
const NEVER_PRIMARY_CODES = new Set(['cancel_task', 'cancel_run', 'view_details']);
|
||||
|
||||
@@ -213,7 +218,9 @@ export function resolveProcessingActionPresentation(
|
||||
};
|
||||
|
||||
pushCode(projection.currentGate?.nextActionCode);
|
||||
for (const action of projection.availableActions || []) {
|
||||
// [ORDER-STABLE] 对 availableActions 标准化(去重 + 字典序排序),确保后端返回顺序不影响前端按钮顺序。
|
||||
const normalizedAvailableActions = normalizeActionCodes(projection.availableActions || []);
|
||||
for (const action of normalizedAvailableActions) {
|
||||
pushCode(action);
|
||||
}
|
||||
|
||||
@@ -243,6 +250,12 @@ export function resolveConversationTaskActionPresentation(
|
||||
if (!task) return empty;
|
||||
|
||||
const surface = options?.surface || 'right';
|
||||
const status = String(task.status_label || '').trim().toLowerCase();
|
||||
const isNeedsAction = task.group === 'needs_action' || NEEDS_ACTION_STATUSES.has(status);
|
||||
const isProcessing = task.group === 'processing' || AUTOMATING_STATUSES.has(status);
|
||||
if (task.group === 'history' || status === 'cancelled') {
|
||||
return empty;
|
||||
}
|
||||
const items: ActionPresentationItem[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
@@ -258,16 +271,27 @@ export function resolveConversationTaskActionPresentation(
|
||||
};
|
||||
|
||||
pushCode(task.primary_action);
|
||||
for (const action of task.available_actions || []) {
|
||||
// [ORDER-STABLE] 对 available_actions 标准化排序,确保后端顺序变化不影响按钮渲染顺序。
|
||||
const normalizedTaskActions = normalizeActionCodes(task.available_actions || []);
|
||||
for (const action of normalizedTaskActions) {
|
||||
pushCode(action);
|
||||
}
|
||||
|
||||
// 无正式业务入口时,默认提供查看进度(focus_task)。
|
||||
// 人工待办禁止伪造查看进度;无明确动作时进入订单处理作为安全兜底。
|
||||
if (isNeedsAction && !items.some((item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()))) {
|
||||
pushCode('open_order_processing');
|
||||
}
|
||||
// 只有系统处理中才允许显示查看进度,且只能作为次要文字链。
|
||||
if (isProcessing && !items.length) pushCode('focus_task');
|
||||
const hasPrimaryCandidate = items.some(
|
||||
(item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()),
|
||||
);
|
||||
if (!hasPrimaryCandidate) {
|
||||
pushCode('focus_task');
|
||||
if (!hasPrimaryCandidate && !isProcessing) {
|
||||
return empty;
|
||||
}
|
||||
if (isProcessing) {
|
||||
const progress = items.find((item) => String(item.actionCode).toLowerCase() === 'focus_task');
|
||||
return { primary: null, secondary: progress || null, overflow: [] };
|
||||
}
|
||||
|
||||
return partitionActionItems(items);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<!--
|
||||
features/shipping-progress/components/ReviewProgressStrip.vue
|
||||
用途:订单处理工作台只读进度——xl 等宽 15 阶;md 横向滚动;窄屏仅 N/15。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、stageNodesAuthority、gateReasonLabel。
|
||||
逻辑:由 ReviewWorkflowProgressPanel 挂载;禁止点击节点;「当前需要」并入标题行文案;
|
||||
「查看流程详情」在标题行右侧;正式 OT 后抑制「请确认建单」;写操作只在 Footer。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、stageNodesAuthority。
|
||||
逻辑:由 ReviewWorkflowProgressPanel 挂载;禁止点击节点;标题只显示「订单处理进度」,
|
||||
不混入等待系统启动/人工处理/失败等自动化文案(归右侧状态卡);
|
||||
「查看流程详情」与标题同行;写操作只在 Footer / 右侧对象级。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from 'vue';
|
||||
@@ -12,19 +13,18 @@ import type {
|
||||
ShippingProcessingProjection,
|
||||
ShippingProcessingStageNodeStatus,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { shippingProcessingStageKey, resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { buildProgressRangeHint } from '../progressWindow';
|
||||
import {
|
||||
readAuthoritativeStageNodes,
|
||||
warnStageNodesUnavailable,
|
||||
} from '../stageNodesAuthority';
|
||||
import { resolveCurrentNeedLabel } from '../gateReasonLabel';
|
||||
|
||||
const props = defineProps<{
|
||||
projection: ShippingProcessingProjection;
|
||||
/** 宿主轮询中提示(显示在标题行)。 */
|
||||
polling?: boolean;
|
||||
/** 正式 OT 已创建时禁止再投影「请确认建单」类当前需要。 */
|
||||
/** 正式 OT 已创建时保留 prop 兼容(进度条不再展示当前需要文案)。 */
|
||||
hasFormalOt?: boolean;
|
||||
}>();
|
||||
|
||||
@@ -36,12 +36,6 @@ const emit = defineEmits<{
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
|
||||
const CONFIRM_BUILD_ACTION_CODES = new Set([
|
||||
'confirm_create',
|
||||
'confirm_build',
|
||||
'open_order_review',
|
||||
'confirm_order',
|
||||
]);
|
||||
const SYSTEM_TECH_ACTION_PREFIXES = ['retry_', 'poll_'];
|
||||
|
||||
/** 权威 15 阶;非法时 null(fail-closed)。 */
|
||||
@@ -50,7 +44,7 @@ const stageNodes = computed(() => readAuthoritativeStageNodes(props.projection))
|
||||
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
|
||||
|
||||
/**
|
||||
* 是否处于系统自动推进(含技术重试/轮询动作,避免被 nextAction 误判为人工待办)。
|
||||
* 是否处于系统自动推进(用于刷新按钮,不进标题文案)。
|
||||
*/
|
||||
const isAutomating = computed(() => {
|
||||
const status = String(props.projection.status || '').trim().toLowerCase();
|
||||
@@ -61,50 +55,19 @@ const isAutomating = computed(() => {
|
||||
return false;
|
||||
});
|
||||
|
||||
const stageLabel = computed(() => resolveShippingProcessingStageLabel(
|
||||
props.projection.stage,
|
||||
te,
|
||||
t,
|
||||
props.projection.stageLabelKey,
|
||||
));
|
||||
/**
|
||||
* 标题仅「订单处理进度」,阶段名由节点/窄屏摘要表达。
|
||||
*/
|
||||
const titleLine = computed(() => t('chat.shippingProcessing.progress.title'));
|
||||
|
||||
/**
|
||||
* 单行标题:自动推进用「系统处理中 · 阶段」;否则「订单处理进度 · 阶段」。
|
||||
* 窄屏当前阶段名:只用 stage code → 阶段 i18n,不用 waiting_system_start 等自动化 label_key。
|
||||
*/
|
||||
const titleLine = computed(() => {
|
||||
const stage = stageLabel.value || '—';
|
||||
if (isAutomating.value) {
|
||||
return t('chat.shippingProcessing.progress.systemProcessingWithStage', { stage });
|
||||
}
|
||||
return t('chat.shippingProcessing.progress.progressTitleWithStage', { stage });
|
||||
});
|
||||
|
||||
/**
|
||||
* 有阻断 Gate 且非自动推进时展示「当前需要」。
|
||||
* 正式 OT 已创建后禁止再显示确认建单类文案。
|
||||
*/
|
||||
const showCurrentNeed = computed(() => {
|
||||
if (isAutomating.value) return false;
|
||||
const gate = props.projection.currentGate;
|
||||
if (!gate) return false;
|
||||
const next = String(gate.nextActionCode || '').trim().toLowerCase();
|
||||
if (props.hasFormalOt && CONFIRM_BUILD_ACTION_CODES.has(next)) return false;
|
||||
if (props.hasFormalOt) {
|
||||
const reason = String(gate.blockingReasonCode || '').trim().toLowerCase();
|
||||
if (reason === 'waiting_review' || reason.includes('confirm')) return false;
|
||||
}
|
||||
return Boolean(
|
||||
String(gate.blockingReasonCode || '').trim()
|
||||
|| String(gate.nextActionCode || '').trim(),
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* 「当前需要」:blockingReasonCode 优先,缺失时回退 nextActionCode(与 Footer 语义对齐)。
|
||||
*/
|
||||
const currentNeed = computed(() => {
|
||||
if (!showCurrentNeed.value) return '';
|
||||
return resolveCurrentNeedLabel(props.projection.currentGate, { t, te });
|
||||
const currentStageName = computed(() => {
|
||||
const stage = String(props.projection.stage || '').trim();
|
||||
if (!stage) return '—';
|
||||
const key = shippingProcessingStageKey(stage);
|
||||
return te(key) ? t(key) : stage;
|
||||
});
|
||||
|
||||
watch(
|
||||
@@ -153,11 +116,10 @@ function nodeShortLabel(stage: string): string {
|
||||
>
|
||||
{{ titleLine }}
|
||||
<span
|
||||
v-if="showCurrentNeed && currentNeed"
|
||||
class="ml-2 font-semibold text-amber-800 dark:text-amber-200"
|
||||
data-testid="review-progress-current-need"
|
||||
class="ml-2 font-normal text-secondary md:hidden"
|
||||
data-testid="review-progress-current-stage-narrow"
|
||||
>
|
||||
· {{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeed }}
|
||||
{{ t('chat.shippingProcessing.progress.currentStage', { stage: currentStageName }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="polling"
|
||||
@@ -189,7 +151,6 @@ function nodeShortLabel(stage: string): string {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- xl:15 阶等宽铺满 -->
|
||||
<div
|
||||
v-if="stageNodes"
|
||||
class="hidden xl:block"
|
||||
@@ -218,7 +179,6 @@ function nodeShortLabel(stage: string): string {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- md–xl:横向滚动、节点等宽 -->
|
||||
<div
|
||||
v-if="stageNodes"
|
||||
class="hidden overflow-x-auto pb-1 md:block xl:hidden"
|
||||
@@ -254,7 +214,6 @@ function nodeShortLabel(stage: string): string {
|
||||
{{ t('chat.shippingProcessing.progress.stageNodesUnavailable') }}
|
||||
</p>
|
||||
|
||||
<!-- <md:仅已完成 N/15 + 标题中的当前阶段 -->
|
||||
<p
|
||||
v-if="rangeHint"
|
||||
class="text-[11px] text-secondary md:hidden"
|
||||
@@ -265,6 +224,5 @@ function nodeShortLabel(stage: string): string {
|
||||
total: rangeHint.total,
|
||||
}) }}
|
||||
</p>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
@@ -1774,7 +1774,8 @@
|
||||
"returnToChat": "Back to chat to view progress",
|
||||
"returnedFocusHint": "Back in chat, focused on task {taskNo} (see In progress on the right)",
|
||||
"retry": "Retry auto-progress",
|
||||
"retryStp": "Retry auto-progress",
|
||||
"retryObject": "Retry",
|
||||
"retryStp": "Retry",
|
||||
"retrySuccess": "Auto-progress re-queued",
|
||||
"retryStpSuccess": "Auto-create re-queued",
|
||||
"status": {
|
||||
@@ -1785,6 +1786,21 @@
|
||||
"unknown": "Status pending confirmation"
|
||||
}
|
||||
},
|
||||
"conversationRetry": {
|
||||
"title": "Conversation retry result",
|
||||
"retried": "Retried",
|
||||
"skipped": "Skipped",
|
||||
"failed": "Failed",
|
||||
"closeAndRefresh": "Close and refresh",
|
||||
"reason": {
|
||||
"already_running": "Already running",
|
||||
"already_completed": "Already completed",
|
||||
"already_confirmed": "Already confirmed",
|
||||
"task_missing": "Formal task missing",
|
||||
"human_blocking": "Manual action required",
|
||||
"not_retryable": "Not retryable"
|
||||
}
|
||||
},
|
||||
"workflowProgress": {
|
||||
"title": "Auto progress",
|
||||
"subtitle": "Continues after confirmation until waiting for manual upload registration; register credentials in the Task Center.",
|
||||
@@ -2025,6 +2041,7 @@
|
||||
"retryRpaUnavailable": "Retry is unavailable for the current inventory state",
|
||||
"retryPreparation": "Retry inventory fetch",
|
||||
"retryMatching": "Retry inventory match",
|
||||
"retry": "Retry",
|
||||
"moreActions": "More actions",
|
||||
"inventorySource": "Inventory source",
|
||||
"inventorySourceStatus": {
|
||||
@@ -2507,6 +2524,14 @@
|
||||
"stageLabel": {
|
||||
"waiting_system_start": "Waiting for system start"
|
||||
},
|
||||
"currentNeed": {
|
||||
"generic": "Continue manual review",
|
||||
"confirmCustomer": "System is waiting for customer confirmation",
|
||||
"resolveFieldConflicts": "System is waiting for field-conflict resolution",
|
||||
"inventoryMatch": "System is waiting for inventory matching",
|
||||
"orderDraft": "An order draft is ready; continue processing",
|
||||
"retry": "Processing failed; check the reason and retry"
|
||||
},
|
||||
"progress": {
|
||||
"completedOfTotal": "{done} / {total} completed",
|
||||
"currentStage": "Current: {stage}",
|
||||
|
||||
@@ -1774,7 +1774,8 @@
|
||||
"returnToChat": "กลับไปแชทเพื่อดูความคืบหน้า",
|
||||
"returnedFocusHint": "กลับสู่แชทแล้ว และโฟกัสงาน {taskNo} (ดูที่แถบด้านขวา)",
|
||||
"retry": "ลองดำเนินการอัตโนมัติอีกครั้ง",
|
||||
"retryStp": "ลองดำเนินการอัตโนมัติอีกครั้ง",
|
||||
"retryObject": "ลองใหม่",
|
||||
"retryStp": "ลองใหม่",
|
||||
"retrySuccess": "จัดคิวดำเนินการอัตโนมัติใหม่แล้ว",
|
||||
"retryStpSuccess": "จัดคิวสร้างออเดอร์อัตโนมัติใหม่แล้ว",
|
||||
"status": {
|
||||
@@ -1785,6 +1786,21 @@
|
||||
"unknown": "รอยืนยันสถานะ"
|
||||
}
|
||||
},
|
||||
"conversationRetry": {
|
||||
"title": "ผลการลองใหม่ระดับบทสนทนา",
|
||||
"retried": "ลองใหม่แล้ว",
|
||||
"skipped": "ข้ามแล้ว",
|
||||
"failed": "ล้มเหลว",
|
||||
"closeAndRefresh": "ปิดและรีเฟรช",
|
||||
"reason": {
|
||||
"already_running": "กำลังดำเนินการอยู่แล้ว",
|
||||
"already_completed": "เสร็จแล้ว ไม่ต้องลองใหม่",
|
||||
"already_confirmed": "ยืนยันสร้างออเดอร์แล้ว",
|
||||
"task_missing": "ไม่พบงานอย่างเป็นทางการ",
|
||||
"human_blocking": "ต้องดำเนินการโดยเจ้าหน้าที่",
|
||||
"not_retryable": "ตอนนี้ลองใหม่ไม่ได้"
|
||||
}
|
||||
},
|
||||
"workflowProgress": {
|
||||
"title": "ความคืบหน้าอัตโนมัติ",
|
||||
"subtitle": "หลังยืนยันจะเดินหน้าจนถึงรอลงทะเบียนอัปโหลดด้วยตนเอง โปรดลงทะเบียนหลักฐานที่โต๊ะงาน",
|
||||
@@ -2025,6 +2041,7 @@
|
||||
"retryRpaUnavailable": "สถานะสต็อกปัจจุบันไม่รองรับการลองใหม่",
|
||||
"retryPreparation": "ลองดึงสต็อกอีกครั้ง",
|
||||
"retryMatching": "ลองจับคู่สต็อกอีกครั้ง",
|
||||
"retry": "ลองใหม่",
|
||||
"moreActions": "การดำเนินการเพิ่มเติม",
|
||||
"inventorySource": "แหล่งสต็อก",
|
||||
"inventorySourceStatus": {
|
||||
@@ -2507,6 +2524,14 @@
|
||||
"stageLabel": {
|
||||
"waiting_system_start": "รอระบบเริ่ม"
|
||||
},
|
||||
"currentNeed": {
|
||||
"generic": "ดำเนินการตรวจสอบด้วยตนเองต่อ",
|
||||
"confirmCustomer": "ระบบกำลังรอการยืนยันลูกค้า",
|
||||
"resolveFieldConflicts": "ระบบกำลังรอการแก้ไขข้อขัดแย้งของฟิลด์",
|
||||
"inventoryMatch": "ระบบกำลังรอการจับคู่สินค้าคงคลัง",
|
||||
"orderDraft": "ระบบสร้างร่างคำสั่งซื้อแล้ว โปรดดำเนินการต่อ",
|
||||
"retry": "การประมวลผลล้มเหลว โปรดตรวจสอบสาเหตุแล้วลองใหม่"
|
||||
},
|
||||
"progress": {
|
||||
"completedOfTotal": "เสร็จแล้ว {done} / {total}",
|
||||
"currentStage": "ปัจจุบัน: {stage}",
|
||||
|
||||
@@ -1808,7 +1808,8 @@
|
||||
"returnToChat": "返回对话查看进度",
|
||||
"returnedFocusHint": "已返回对话,并聚焦任务 {taskNo}(见右侧「本次处理中」)",
|
||||
"retry": "重试自动推进",
|
||||
"retryStp": "重试自动推进",
|
||||
"retryObject": "重试",
|
||||
"retryStp": "重试",
|
||||
"retrySuccess": "已重新入队自动推进",
|
||||
"retryStpSuccess": "已重新入队自动建单",
|
||||
"status": {
|
||||
@@ -1819,6 +1820,21 @@
|
||||
"unknown": "状态待确认"
|
||||
}
|
||||
},
|
||||
"conversationRetry": {
|
||||
"title": "对话重试结果",
|
||||
"retried": "已重试",
|
||||
"skipped": "已跳过",
|
||||
"failed": "失败",
|
||||
"closeAndRefresh": "关闭并刷新",
|
||||
"reason": {
|
||||
"already_running": "已在处理中",
|
||||
"already_completed": "已完成,无需重试",
|
||||
"already_confirmed": "已确认建单",
|
||||
"task_missing": "正式任务缺失",
|
||||
"human_blocking": "需人工处理",
|
||||
"not_retryable": "当前不可重试"
|
||||
}
|
||||
},
|
||||
"workflowProgress": {
|
||||
"title": "自动进度",
|
||||
"subtitle": "确认后持续推进至货代平台上传;进度以统一 ShippingProcessing 为准。",
|
||||
@@ -2055,6 +2071,7 @@
|
||||
"noSourceOptions": "暂无可用库存源",
|
||||
"retryPreparation": "重试获取库存",
|
||||
"retryMatching": "重新匹配库存",
|
||||
"retry": "重试",
|
||||
"moreActions": "更多操作",
|
||||
"retryRpa": "重试获取库存",
|
||||
"retryRpaSubmitted": "已提交库存 RPA 重试",
|
||||
@@ -2508,6 +2525,14 @@
|
||||
"stageLabel": {
|
||||
"waiting_system_start": "等待系统启动"
|
||||
},
|
||||
"currentNeed": {
|
||||
"generic": "继续完成人工复核",
|
||||
"confirmCustomer": "系统等待你确认客户信息",
|
||||
"resolveFieldConflicts": "系统等待你处理字段冲突",
|
||||
"inventoryMatch": "系统等待你完成库存匹配",
|
||||
"orderDraft": "系统已生成订单草稿,等待你继续处理",
|
||||
"retry": "当前处理失败,请检查原因后重试"
|
||||
},
|
||||
"progress": {
|
||||
"completedOfTotal": "已完成 {done} / {total}",
|
||||
"currentStage": "当前:{stage}",
|
||||
|
||||
@@ -1774,7 +1774,8 @@
|
||||
"returnToChat": "返回對話查看進度",
|
||||
"returnedFocusHint": "已返回對話,並聚焦任務 {taskNo}(見右側「本次處理中」)",
|
||||
"retry": "重試自動推進",
|
||||
"retryStp": "重試自動推進",
|
||||
"retryObject": "重試",
|
||||
"retryStp": "重試",
|
||||
"retrySuccess": "已重新入隊自動推進",
|
||||
"retryStpSuccess": "已重新入隊自動建單",
|
||||
"status": {
|
||||
@@ -1785,6 +1786,21 @@
|
||||
"unknown": "狀態待確認"
|
||||
}
|
||||
},
|
||||
"conversationRetry": {
|
||||
"title": "對話重試結果",
|
||||
"retried": "已重試",
|
||||
"skipped": "已跳過",
|
||||
"failed": "失敗",
|
||||
"closeAndRefresh": "關閉並重新整理",
|
||||
"reason": {
|
||||
"already_running": "已在處理中",
|
||||
"already_completed": "已完成,無需重試",
|
||||
"already_confirmed": "已確認建單",
|
||||
"task_missing": "正式任務缺失",
|
||||
"human_blocking": "需人工處理",
|
||||
"not_retryable": "目前不可重試"
|
||||
}
|
||||
},
|
||||
"workflowProgress": {
|
||||
"title": "自動進度",
|
||||
"subtitle": "確認後持續推進至待人工上傳登記;請在任務中心登記憑據。",
|
||||
@@ -2025,6 +2041,7 @@
|
||||
"retryRpaUnavailable": "目前庫存處理狀態不支援重試",
|
||||
"retryPreparation": "重試獲取庫存",
|
||||
"retryMatching": "重新匹配庫存",
|
||||
"retry": "重試",
|
||||
"moreActions": "更多操作",
|
||||
"inventorySource": "庫存源",
|
||||
"inventorySourceStatus": {
|
||||
@@ -2507,6 +2524,14 @@
|
||||
"stageLabel": {
|
||||
"waiting_system_start": "等待系統啟動"
|
||||
},
|
||||
"currentNeed": {
|
||||
"generic": "繼續完成人工複核",
|
||||
"confirmCustomer": "系統等待你確認客戶資訊",
|
||||
"resolveFieldConflicts": "系統等待你處理欄位衝突",
|
||||
"inventoryMatch": "系統等待你完成庫存匹配",
|
||||
"orderDraft": "系統已生成訂單草稿,等待你繼續處理",
|
||||
"retry": "目前處理失敗,請檢查原因後重試"
|
||||
},
|
||||
"progress": {
|
||||
"completedOfTotal": "已完成 {done} / {total}",
|
||||
"currentStage": "目前:{stage}",
|
||||
|
||||
Reference in new issue
Block a user