refactor(shipping-notice): 进度信号统一为 15 阶 stage 契约码并透传阻断原因
- 后端进度写入 step_key 全量切换为 15 阶契约 stage 码 - 投影层清除 CheckPoint stepN_* 遗留别名与子串/前缀启发式,阶段信号按契约码精确匹配 - 建单前 Case 摘要透传草稿首要阻断原因 - 前端标签/归一化/处理卡片同步契约码,阻断原因按 i18n 优先展示 - 修复正式下游回看时 activeCase 刻意为空导致队列定位与接收解析上下文静默跳过 - 同步更新投影/门禁/工作台/RPA 流程测试
This commit is contained in:
1 parent
d1adbe5ec5
commit
18af972d20
34 files changed
+903
-111
No files matched your search
@@ -569,7 +569,7 @@ def _trigger_freight_upload_rpa(
|
||||
timeout = _rpa_upload_timeout_seconds()
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step7_upload_freight',
|
||||
stage="freight_uploading",
|
||||
step_title='上传货代',
|
||||
status='running',
|
||||
message=t('workflow.fulfillment.upload_triggered_wait', lang=lang),
|
||||
@@ -1249,7 +1249,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
|
||||
line_result_status = str(match_payload.get('match_status') or 'unfulfillable')
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message=t("workflow.fulfillment.match_running", lang=lang),
|
||||
@@ -1639,7 +1639,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message=t("workflow.fulfillment.match_running", lang=lang),
|
||||
@@ -1731,7 +1731,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
**_match_step_progress_fields(
|
||||
match_status=match_status,
|
||||
@@ -1810,7 +1810,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total)))
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message=t("workflow.fulfillment.match_running", lang=lang),
|
||||
@@ -1867,7 +1867,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
**_match_step_progress_fields(
|
||||
match_status=match_status,
|
||||
@@ -2066,7 +2066,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step6_generate_file",
|
||||
stage="excel_generating",
|
||||
step_title="生成发货文件",
|
||||
status="running",
|
||||
message=t("workflow.fulfillment.generate_running", lang=lang),
|
||||
@@ -2120,7 +2120,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_clear_notice_invalidated_from_stage(task)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step6_generate_file",
|
||||
stage="excel_generating",
|
||||
step_title="生成发货文件",
|
||||
status="completed",
|
||||
message=t("workflow.fulfillment.generate_completed", lang=lang),
|
||||
@@ -2451,7 +2451,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_close_uploaded_task(task, actor_type='rpa', actor_id=None)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
stage="freight_uploading",
|
||||
step_title="上传货代",
|
||||
status="completed",
|
||||
message=t("workflow.fulfillment.rpa_uploaded", lang=lang),
|
||||
@@ -2507,7 +2507,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
stage="freight_uploading",
|
||||
step_title="上传货代",
|
||||
status="needs_human",
|
||||
message=t("workflow.fulfillment.upload_unknown_wait_manual", lang=lang),
|
||||
@@ -2527,7 +2527,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
stage="freight_uploading",
|
||||
step_title="上传货代",
|
||||
status="needs_human",
|
||||
message=t("workflow.fulfillment.upload_failed_wait_manual", lang=lang),
|
||||
|
||||
@@ -695,7 +695,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
|
||||
if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task):
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
stage="inventory_matching",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message="本批库存快照已确认,等待匹配库存",
|
||||
|
||||
@@ -101,7 +101,7 @@ def inventory_loaded_response(
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="completed",
|
||||
message=f"已载入库存 {len(inventory_lines)} 行",
|
||||
|
||||
@@ -1212,7 +1212,7 @@ def ensure_inventory_via_rpa(
|
||||
_set_workflow_error(task, None)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
stage="inventory_fetching",
|
||||
step_title='获取库存',
|
||||
status='running',
|
||||
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
|
||||
@@ -1240,7 +1240,7 @@ def ensure_inventory_via_rpa(
|
||||
poll_read_only = not allow_auto_retry
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
stage="inventory_fetching",
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message='库存 RPA 未能为全部库存源生成结果。',
|
||||
@@ -1353,7 +1353,7 @@ def ensure_inventory_via_rpa(
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message=progress_message,
|
||||
@@ -1403,7 +1403,7 @@ def ensure_inventory_via_rpa(
|
||||
_set_workflow_error(task, human_message[:500])
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=human_message,
|
||||
@@ -1553,7 +1553,7 @@ def _handle_rpa_inventory_skipped(
|
||||
_set_workflow_error(task, None)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="货代系统当前无可用库存",
|
||||
@@ -1600,7 +1600,7 @@ def _handle_rpa_inventory_failed(
|
||||
})
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
stage="inventory_fetching",
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message=_workflow_error(task),
|
||||
@@ -1950,7 +1950,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="RPA 库存文件已返回,正在读取库存快照",
|
||||
|
||||
@@ -132,7 +132,7 @@ def _link_ready_candidate_prep_or_block(
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
stage="inventory_fetching",
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message=t('workflow.inventory.unavailable', lang=lang),
|
||||
@@ -312,7 +312,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
try:
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message=t("workflow.inventory.uploading", lang=lang),
|
||||
@@ -461,7 +461,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
@@ -502,7 +502,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.error_message = None
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="已触发库存获取,等待各库存源回调。",
|
||||
@@ -530,7 +530,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="库存 RPA 未能为全部库存源生成结果。",
|
||||
@@ -556,7 +556,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
@@ -625,7 +625,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
stage="inventory_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
|
||||
@@ -5,7 +5,7 @@ services/shipping_notice/lifecycle_projection.py
|
||||
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
|
||||
逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因;
|
||||
[B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时
|
||||
兜底;无正式事实时保持未分类。兼容 OT.stage 上残留的 step_key 别名。
|
||||
兜底;无正式事实时保持未分类。
|
||||
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
|
||||
"""
|
||||
|
||||
@@ -75,11 +75,6 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
|
||||
'freight_uploading': 'freight_upload',
|
||||
'manual_upload_handoff': 'freight_upload',
|
||||
'completed': 'upload_complete',
|
||||
# 历史 step_key 曾被误写入 OT.stage;投影只读别名,避免工作台掉回接收解析空白页。
|
||||
'step5_match_inventory': 'fulfillment_prep',
|
||||
'step6_generate_file': 'fulfillment_prep',
|
||||
'step3_inventory_prepare': 'fulfillment_prep',
|
||||
'step7_upload_freight': 'freight_upload',
|
||||
}
|
||||
|
||||
def lifecycle_entries(
|
||||
|
||||
@@ -260,25 +260,27 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
|
||||
return ('completed', 'completed')
|
||||
if ps in {'waiting_upload', 'upload_failed', 'uploading'} or projected_upload == 'uploading':
|
||||
return ('automating', 'freight_uploading')
|
||||
if 'upload' in step or step.startswith('step7'):
|
||||
# [契约唯一] current_step 只存 15 阶契约码(CheckPoint stepN_* 遗留键已清除),
|
||||
# 阶段信号按契约码精确匹配,不再做子串/前缀启发式。
|
||||
if step == 'freight_uploading':
|
||||
return ('automating', 'freight_uploading')
|
||||
|
||||
if ps in {'export', 'excel', 'generating_excel'} or 'generate' in step or step.startswith('step6'):
|
||||
if ps in {'export', 'excel', 'generating_excel'} or step == 'excel_generating':
|
||||
return ('automating', 'excel_generating')
|
||||
if ps == 'matched' and export_path:
|
||||
return ('automating', 'excel_generating')
|
||||
|
||||
if ps in {'matching', 'inventory_ready', 'matched'} or 'match' in step:
|
||||
if ps in {'matching', 'inventory_ready', 'matched'} or step == 'inventory_matching':
|
||||
return ('automating', 'inventory_matching')
|
||||
|
||||
# 正式建单后的库存获取:waiting_inventory / parsed → 获取库存(禁止仍映射到 matching)。
|
||||
if ps in {'waiting_inventory', 'parsed'} or 'fetch' in step or step.startswith('step4'):
|
||||
if ps in {'waiting_inventory', 'parsed'} or step == 'inventory_fetching':
|
||||
return ('automating', 'inventory_fetching')
|
||||
|
||||
if ps == 'pending_review':
|
||||
return ('waiting_review', 'waiting_review')
|
||||
|
||||
if ps in {'creating', 'order_creating', 'confirming'} or 'create' in step or step.startswith('step3'):
|
||||
if ps in {'creating', 'order_creating', 'confirming'} or step == 'order_creating':
|
||||
return ('automating', 'order_creating')
|
||||
if ps in {'fetching_inventory', 'inventory_fetching'}:
|
||||
return ('automating', 'inventory_fetching')
|
||||
@@ -687,13 +689,8 @@ _USER_STAGE_TO_CODE: dict[str, str] = {
|
||||
'waiting_review': 'waiting_human_review',
|
||||
'inventory_fetching': 'inventory_fetch',
|
||||
'inventory_matching': 'inventory_match',
|
||||
# step_key 误写入 OT.stage 时的只读别名(与 lifecycle_projection 同源)。
|
||||
'step5_match_inventory': 'inventory_match',
|
||||
'step3_inventory_prepare': 'inventory_fetch',
|
||||
'step6_generate_file': 'excel_generate',
|
||||
'excel_generating': 'excel_generate',
|
||||
'freight_uploading': 'freight_upload',
|
||||
'step7_upload_freight': 'freight_upload',
|
||||
'completed': 'completed',
|
||||
'failed': 'failed_terminal',
|
||||
'cancelled': 'cancelled',
|
||||
|
||||
@@ -44,6 +44,9 @@ from app.models import (
|
||||
ShippingOrderReviewCase,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.error_explainability_contract import (
|
||||
UNKNOWN_BUSINESS_FAILURE_REASON_CODE,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -60,6 +63,11 @@ class BlockingReason(TypedDict, total=False):
|
||||
code: str | None
|
||||
i18n_key: str | None
|
||||
details: dict[str, Any] | None
|
||||
# 建单前资格快照回退透传字段(来自冻结 explainability 契约,
|
||||
# 见 error_explainability_contract.build_explainability_reason;
|
||||
# message 为中文兜底文案,前端优先按 i18n 命名空间解析)。
|
||||
message: str | None
|
||||
next_action: str | None
|
||||
|
||||
|
||||
class CurrentGate(TypedDict, total=False):
|
||||
@@ -723,11 +731,67 @@ def project_case_blocking_reason(automation: dict[str, Any] | None) -> BlockingR
|
||||
return BlockingReason(code=None, i18n_key=None, details=details)
|
||||
i18n_key = _REASON_TO_I18N_KEY.get(raw_code)
|
||||
if i18n_key is None:
|
||||
# fail-closed:给一个通用兜底 key
|
||||
i18n_key = 'shipping.review.blocked_generic'
|
||||
# fail-closed:兜底键必须指向前端真实存在的键;此前指向不存在的
|
||||
# shipping.review.blocked_generic,任何未映射码都会在前端双重落空成
|
||||
# 「当前步骤需要人工处理」。
|
||||
i18n_key = 'chat.shippingProcessing.reasonCode.unknown'
|
||||
return BlockingReason(code=raw_code, i18n_key=i18n_key, details=details)
|
||||
|
||||
|
||||
def _blocking_reason_is_generic(reason: BlockingReason) -> bool:
|
||||
"""
|
||||
判断 blocking_reason 是否未携带具体原因(无码或仅落通用兜底键)。
|
||||
仅此情形才允许回退到资格快照,避免覆盖 automation 侧更精确的裁决。
|
||||
"""
|
||||
if not isinstance(reason, dict):
|
||||
return True
|
||||
code = str(reason.get('code') or '').strip()
|
||||
if not code:
|
||||
return True
|
||||
return str(reason.get('i18n_key') or '').strip() == 'chat.shippingProcessing.reasonCode.unknown'
|
||||
|
||||
|
||||
def _primary_validation_blocking_reason(validation: dict[str, Any] | None) -> BlockingReason | None:
|
||||
"""
|
||||
【AI 触发时机】:automation 无具体原因码,需要从草稿校验快照取首要阻断原因时。
|
||||
核心逻辑:只认 severity=blocking 且 explainability 未降级(非
|
||||
unknown_business_failure)的 issue;透传冻结契约的 message / next_action,
|
||||
本模块不新造文案或映射。无可用 issue 返回 None,由调用方保持既有兜底。
|
||||
"""
|
||||
if not isinstance(validation, dict):
|
||||
return None
|
||||
issues = validation.get('issues')
|
||||
if not isinstance(issues, list):
|
||||
return None
|
||||
for issue in issues:
|
||||
if not isinstance(issue, dict):
|
||||
continue
|
||||
if str(issue.get('severity') or '').strip().lower() != 'blocking':
|
||||
continue
|
||||
explainability = issue.get('explainability') if isinstance(issue.get('explainability'), dict) else {}
|
||||
code = str(
|
||||
explainability.get('reason_code')
|
||||
or issue.get('reason_code')
|
||||
or issue.get('code')
|
||||
or ''
|
||||
).strip()
|
||||
if not code or code == UNKNOWN_BUSINESS_FAILURE_REASON_CODE:
|
||||
continue
|
||||
details = {
|
||||
key: value for key, value in issue.items()
|
||||
if key in {'field_code', 'field_id', 'line_index', 'owning_gate_code'}
|
||||
and value is not None
|
||||
}
|
||||
return BlockingReason(
|
||||
code=code,
|
||||
i18n_key=_REASON_TO_I18N_KEY.get(code),
|
||||
details=details or None,
|
||||
message=str(explainability.get('message') or issue.get('message') or '').strip() or None,
|
||||
next_action=str(explainability.get('next_action') or '').strip() or None,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [5] user_status(F2 六值;默认人工等待 = waiting_human,禁止 idle)
|
||||
# ============================================================
|
||||
@@ -1218,6 +1282,13 @@ def project_review_case_projection_bundle(
|
||||
current_gate = project_case_current_gate(case, automation, available_actions)
|
||||
# [STEP 4] blocking_reason
|
||||
blocking_reason = project_case_blocking_reason(automation)
|
||||
# [STEP 4.1] automation 未携带具体原因时,回退到草稿校验快照的首要 blocking
|
||||
# issue:资格评估落库时已按冻结 explainability 契约附带原因文案与下一步动作,
|
||||
# 此处仅透传,让批次中心/工作台展示「客户尚未确认」等具体原因而非通用兜底。
|
||||
if _blocking_reason_is_generic(blocking_reason):
|
||||
fallback_reason = _primary_validation_blocking_reason(validation)
|
||||
if fallback_reason is not None:
|
||||
blocking_reason = fallback_reason
|
||||
# [STEP 5] user_status
|
||||
user_status = project_case_user_status(case, automation)
|
||||
# [STEP 5.1] 已持久化的正式 Gate 是实时状态唯一裁决源。此前这里用 Case
|
||||
|
||||
@@ -4003,6 +4003,33 @@ def _conversation_processing_from_work_items(
|
||||
}
|
||||
|
||||
|
||||
def _review_case_blocking_reason(
|
||||
case: ShippingOrderReviewCase | None,
|
||||
drafts_by_id: dict[int, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
建单前 Case 摘要叶子的具体阻断原因:回退到草稿校验快照的首要 blocking issue。
|
||||
|
||||
核心逻辑:资格评估落库时已按冻结 explainability 契约附带 code/message/next_action
|
||||
(见 reconciliation_projector._primary_validation_blocking_reason);摘要路径的
|
||||
drafts_by_id 已批量加载,透传零额外查询。无 Draft / 无可用 issue 返回 None,
|
||||
调用方保持 review_case_{status} 状态码兜底。
|
||||
"""
|
||||
if case is None:
|
||||
return None
|
||||
draft_id = getattr(case, 'current_draft_id', None)
|
||||
if draft_id is None:
|
||||
return None
|
||||
draft = drafts_by_id.get(int(draft_id))
|
||||
validation = getattr(draft, 'validation_result_json', None)
|
||||
if not isinstance(validation, dict):
|
||||
return None
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
_primary_validation_blocking_reason,
|
||||
)
|
||||
return _primary_validation_blocking_reason(validation)
|
||||
|
||||
|
||||
def project_conversation_processing_summary(
|
||||
*,
|
||||
user_id: int,
|
||||
@@ -4585,7 +4612,13 @@ def project_conversation_processing_summary(
|
||||
'po_number': candidate_po or None,
|
||||
},
|
||||
'current_gate': current_gate,
|
||||
'blocking_reason': {'code': reason} if reason else None,
|
||||
# v4:建单前 Case 的 review_case_{status} 状态码先回退到资格快照的
|
||||
# 首要阻断 issue(客户尚未确认等具体原因),无可用 issue 才落状态码。
|
||||
'blocking_reason': (
|
||||
_review_case_blocking_reason(case, drafts_by_id)
|
||||
if str(reason or '').startswith('review_case_')
|
||||
else ({'code': reason} if reason else None)
|
||||
),
|
||||
'primary_action': primary_action,
|
||||
'available_actions': available_actions,
|
||||
'intake_parse_authorized': intake_parse_authorized,
|
||||
|
||||
@@ -703,7 +703,7 @@ def replace_task_notice(
|
||||
intake.parse_warnings_json = cleaned_warnings
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
stage="waiting_review",
|
||||
step_title="确认解析",
|
||||
status="needs_human",
|
||||
message="发货通知文本抽取失败",
|
||||
@@ -732,7 +732,7 @@ def replace_task_notice(
|
||||
_reset_notice_edit_downstream(task)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step1_notice_submit",
|
||||
stage="order_creating",
|
||||
step_title="提交通知",
|
||||
status="completed",
|
||||
message="已重新上传发货通知并覆盖当前任务",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/tool_common.py
|
||||
|
||||
用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。
|
||||
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract。
|
||||
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract、progress_audit_contract。
|
||||
逻辑:task_workflow / inventory_workflow / fulfillment_workflow / decision_workflow 共用;
|
||||
log_task_event 对 inventory_rpa_/inventory_source_/export_/notice_replace/
|
||||
freight_cancellation_/STP 事件同步投影到 ShippingAuditEvent;
|
||||
@@ -20,6 +20,10 @@ from flask import current_app
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
SHIPPING_PROCESSING_STAGES,
|
||||
shipping_processing_stage_index,
|
||||
)
|
||||
|
||||
|
||||
def cfg_bool(key: str, default: bool = False) -> bool:
|
||||
@@ -211,7 +215,7 @@ def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]:
|
||||
def set_task_step_progress(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
step_key: str,
|
||||
stage: str,
|
||||
step_title: str,
|
||||
status: str,
|
||||
message: str,
|
||||
@@ -221,13 +225,38 @@ def set_task_step_progress(
|
||||
detail: str | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。"""
|
||||
"""写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。
|
||||
|
||||
【AI 触发时机】履约工作流(库存准备/匹配/Excel/上传/通知重解析)报告阶段内
|
||||
细粒度进度或失败等待人工时调用。
|
||||
|
||||
核心逻辑:``stage`` 必须是冻结 15 阶契约码(SHIPPING_PROCESSING_STAGES 成员),
|
||||
写入 ``current_step`` 与 ``step_payload_json.current_step_progress`` 供投影展示;
|
||||
``OT.stage`` 仅按 15 阶序列【只进不退】推进——空缺时直接写入,已有值仅当新
|
||||
stage 序号不小于旧值才覆盖,保证进度上报永远不会把订单拉回早期阶段。
|
||||
|
||||
Args:
|
||||
stage: 15 阶契约码(如 inventory_fetching / inventory_matching /
|
||||
excel_generating / freight_uploading);禁止传入 CheckPoint 时代
|
||||
stepN_* 遗留键(已全部清除)。
|
||||
step_title: 展示用步骤名。
|
||||
status: 步骤执行态(running/completed/needs_human/failed 等调用方语义)。
|
||||
message: 用户可读进度说明。
|
||||
|
||||
Raises:
|
||||
ValueError: ``stage`` 不是 15 阶契约成员时立即失败(写错阶段码属于代码缺陷)。
|
||||
"""
|
||||
code = str(stage or '').strip()
|
||||
if code not in SHIPPING_PROCESSING_STAGES:
|
||||
raise ValueError(
|
||||
f'set_task_step_progress: stage must be a SHIPPING_PROCESSING_STAGES member, got {stage!r}'
|
||||
)
|
||||
owner = task
|
||||
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
|
||||
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
|
||||
payload = dict(getattr(owner, 'step_payload_json', None) or {})
|
||||
progress: dict[str, Any] = {
|
||||
"step_key": step_key,
|
||||
"stage": code,
|
||||
"step_title": step_title,
|
||||
"status": status,
|
||||
"message": str(message or "").strip(),
|
||||
@@ -244,9 +273,19 @@ def set_task_step_progress(
|
||||
progress["extra"] = extra
|
||||
payload["current_step_progress"] = progress
|
||||
if hasattr(owner, 'current_step'):
|
||||
owner.current_step = step_key
|
||||
owner.current_step = code
|
||||
if hasattr(owner, 'stage'):
|
||||
owner.stage = step_key
|
||||
current_stage = str(getattr(owner, 'stage', None) or '').strip().lower()
|
||||
current_idx = shipping_processing_stage_index(current_stage)
|
||||
target_idx = shipping_processing_stage_index(code)
|
||||
# 只进不退:进度上报只允许推进或停留在既有序列位置,禁止回退
|
||||
# (历史缺陷:进度上报曾把 order_creating 踩回早期码,工作台掉回接收解析)。
|
||||
if (
|
||||
not current_stage
|
||||
or current_idx is None
|
||||
or (target_idx is not None and target_idx >= current_idx)
|
||||
):
|
||||
owner.stage = code
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
owner.step_payload_json = payload
|
||||
|
||||
|
||||
@@ -235,6 +235,180 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
|
||||
assert bundle['user_status'] == 'waiting_human'
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [BR] blocking_reason 资格快照回退:
|
||||
# automation 无具体原因码时,回退到草稿校验快照(validation_result_json)
|
||||
# 中首要 blocking issue 的冻结 explainability 透传(code/message/next_action),
|
||||
# 让批次中心与工作台展示具体原因,而非「当前步骤需要人工处理」兜底。
|
||||
# ============================================================
|
||||
|
||||
def _validation_snapshot_with_issues(issues: list[dict]) -> dict:
|
||||
"""构造与 order_build_eligibility 持久化结构一致的 validation 快照。"""
|
||||
return {'can_build': False, 'can_auto_create': False, 'issues': issues}
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_falls_back_to_primary_validation_issue_when_automation_lacks_reason():
|
||||
"""[BR-1] automation 无具体原因码时,blocking_reason 必须回退到首要 blocking issue。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
'message': '客户尚未确认',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
# 断言意图:透传冻结契约的事实三元组,前端据此展示「客户尚未确认 / 确认客户」
|
||||
assert reason['code'] == 'customer_unresolved'
|
||||
assert reason['message'] == '客户尚未确认'
|
||||
assert reason['next_action'] == 'confirm_customer'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_validation_fallback_skips_degraded_and_non_blocking_issues():
|
||||
"""[BR-2] 降级码(unknown_business_failure)与非 blocking issue 不进入回退。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
# 仅阻断自动建单,不属用户阻断
|
||||
{
|
||||
'code': 'candidate_qualification_blocked',
|
||||
'severity': 'auto_create_blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'llm_path_cannot_auto_freeze',
|
||||
'message': '智能识别结果尚未通过自动建单资格检查',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
# 契约降级码:不透传给用户
|
||||
{
|
||||
'code': 'weird_new_issue',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'unknown_business_failure',
|
||||
'message': '业务处理失败,请凭请求编号联系管理员',
|
||||
'next_action': '',
|
||||
},
|
||||
},
|
||||
# 首个可用 blocking issue
|
||||
{
|
||||
'code': 'required_field_missing',
|
||||
'severity': 'blocking',
|
||||
'field_code': 'reservation_id',
|
||||
'explainability': {
|
||||
'reason_code': 'required_field_missing',
|
||||
'message': '缺少创建订单所需字段',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'required_field_missing'
|
||||
assert reason['next_action'] == 'open_order_review'
|
||||
assert reason['details'].get('field_code') == 'reservation_id'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_keeps_mapped_automation_reason_over_validation_fallback(monkeypatch):
|
||||
"""[BR-3] automation 已有映射的具体原因码时不回退,避免覆盖更精确的裁决。"""
|
||||
from app.services.shipping_notice import reconciliation_projector
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
monkeypatch.setattr(
|
||||
reconciliation_projector,
|
||||
'project_case_automation_status',
|
||||
lambda case, *, validation, post_confirm: {
|
||||
'status': 'manual_fallback',
|
||||
'retryable': False,
|
||||
'reason_code': 'duplicate_decision_required',
|
||||
},
|
||||
)
|
||||
bundle = reconciliation_projector.project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'duplicate_decision_required'
|
||||
assert reason.get('message') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_without_usable_issues_keeps_legacy_blocking_reason():
|
||||
"""[BR-4] 快照无可用 issue 时保持既有兜底行为(不得抛错、不得造原因)。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation={'can_build': True, 'can_auto_create': True, 'issues': []},
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert isinstance(reason, dict)
|
||||
assert reason.get('message') is None
|
||||
assert reason.get('next_action') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_unmapped_automation_reason_uses_existing_generic_i18n_key():
|
||||
"""[BR-5] 未映射原因码的 fail-closed 兜底必须指向前端真实存在的键。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_blocking_reason,
|
||||
)
|
||||
|
||||
reason = project_case_blocking_reason({
|
||||
'status': 'manual_fallback',
|
||||
'reason_code': 'totally_new_unmapped_code',
|
||||
})
|
||||
|
||||
assert reason['code'] == 'totally_new_unmapped_code'
|
||||
# 此前指向不存在的 shipping.review.blocked_generic,任何未映射码都会双重落空
|
||||
assert reason['i18n_key'] == 'chat.shippingProcessing.reasonCode.unknown'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task():
|
||||
"""字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。"""
|
||||
|
||||
@@ -91,7 +91,7 @@ def test_fetch_gate_positions_batched(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
ot_b = ShippingOrderTask(
|
||||
@@ -345,7 +345,7 @@ def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
|
||||
@@ -538,7 +538,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
db.session.refresh(task)
|
||||
|
||||
assert result['status'] == 'ok', result
|
||||
assert result['data']['stage'] == 'step5_match_inventory'
|
||||
assert result['data']['stage'] == 'inventory_matching'
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one()
|
||||
snapshot = db.session.get(ShippingInventoryFile, link.inventory_file_id)
|
||||
assert snapshot is not None
|
||||
|
||||
@@ -372,7 +372,7 @@ def test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step(ap
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
@@ -230,18 +230,18 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
# 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。
|
||||
uploaded = SimpleNamespace(
|
||||
id=None,
|
||||
current_step='step7_upload', upload_status='uploaded', export_file_path=None,
|
||||
current_step='freight_uploading', upload_status='uploaded', export_file_path=None,
|
||||
)
|
||||
# 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
current_step='step7_upload', upload_status='pending', export_file_path='/x.xlsx',
|
||||
current_step='freight_uploading', upload_status='pending', export_file_path='/x.xlsx',
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
|
||||
|
||||
matching = SimpleNamespace(
|
||||
current_step='step5_match', upload_status='', match_status='matching', export_file_path=None,
|
||||
current_step='inventory_matching', upload_status='', match_status='matching', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
|
||||
|
||||
|
||||
@@ -540,7 +540,7 @@ def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None
|
||||
owner_agent_id=int(agent.id),
|
||||
candidate_id=None,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -1660,7 +1660,7 @@ def test_summary_loads_process_execution_by_order_task_id_not_candidate_id(app)
|
||||
intake_id=intake.id,
|
||||
candidate_id=candidate.id,
|
||||
status='waiting_review',
|
||||
stage='step3_inventory_prepare',
|
||||
stage='inventory_fetching',
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
@@ -1876,6 +1876,73 @@ def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> No
|
||||
assert summary_leaf['intake_parse_authorized'] is False
|
||||
|
||||
|
||||
def test_summary_leaf_surfaces_primary_validation_issue_for_open_case(app) -> None:
|
||||
"""摘要叶子对建单前 Case 必须透传首要资格 issue,而非 review_case_{status} 状态码。
|
||||
|
||||
回归:批次进度中心对"客户尚未确认"等具体阻断只显示「订单草稿待处理」状态文案,
|
||||
原因是叶子摘要用 Case 状态拼 blocking_reason.code;资格评估已把冻结
|
||||
explainability(code/message/next_action)持久化进 draft.validation_result_json,
|
||||
摘要路径应透传该裁决(drafts_by_id 已批量加载,零额外查询)。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-LEAF-ISSUE-REASON',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUMMARY-ISSUE-REASON', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='summary-issue-reason',
|
||||
order_extraction_run_id=run.id, is_current_version=True,
|
||||
candidate_status='accepted', po_number='PO-SUMMARY-ISSUE-REASON',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
review_case = ensure_run_review_cases(run=run)[0]
|
||||
review_case.status = 'draft'
|
||||
draft = review_case.current_draft
|
||||
assert draft is not None
|
||||
# 模拟资格评估落库的首要阻断 issue(与 order_build_eligibility 持久化结构一致)
|
||||
draft.validation_result_json = {
|
||||
'can_build': False,
|
||||
'can_auto_create': False,
|
||||
'issues': [{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
'message': '客户尚未确认',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
}],
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
summary_leaf = next(
|
||||
child
|
||||
for rows in payload['conversation_processing']['status_groups'].values()
|
||||
for row in rows
|
||||
for child in row.get('aggregate_children', [])
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
|
||||
reason = summary_leaf['ui_state']['blocking_reason']
|
||||
# 关键断言:透传契约三元组;不得再是 review_case_draft 状态码
|
||||
assert reason['code'] == 'customer_unresolved'
|
||||
assert reason['message'] == '客户尚未确认'
|
||||
assert reason['next_action'] == 'confirm_customer'
|
||||
|
||||
|
||||
def test_summary_leaf_open_case_with_queued_stp_is_running_not_waiting_human(app) -> None:
|
||||
"""开放 Case 若已有 queued STP Job,摘要必须进系统处理中,不得误报待人工。
|
||||
|
||||
@@ -2860,7 +2927,7 @@ def test_single_order_task_work_item_includes_authoritative_lifecycle_ui_state(a
|
||||
conversation_id=session.session_id,
|
||||
intake_id=int(intake.id),
|
||||
extraction_run_id=int(run.id),
|
||||
current_step='step7_upload_freight',
|
||||
current_step='freight_uploading',
|
||||
status='automating',
|
||||
stage='freight_uploading',
|
||||
progress_version=1,
|
||||
@@ -3139,7 +3206,7 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
current_step='step7_upload_freight',
|
||||
current_step='freight_uploading',
|
||||
status='processing',
|
||||
stage='candidate_creating',
|
||||
progress_version=1,
|
||||
|
||||
@@ -36,21 +36,39 @@ def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage():
|
||||
)
|
||||
|
||||
|
||||
def test_legacy_step_key_stage_maps_to_fulfillment_prep():
|
||||
"""OT.stage 若残留 step5_match_inventory,生命周期必须进通知准备而非接收解析。"""
|
||||
def test_stage_mapping_rejects_checkpoint_legacy_keys():
|
||||
"""CheckPoint stepN_* 遗留键已全部清除:阶段映射只认 15 阶契约码。
|
||||
|
||||
历史缺陷:step_key 被写进 OT.stage,靠投影别名兜底;现写路径只产出契约码
|
||||
(set_task_step_progress 校验 + 存量迁移清洗),别名不得再存在。
|
||||
"""
|
||||
legacy_keys = [
|
||||
'step1_notice_submit',
|
||||
'step2_parse_confirm',
|
||||
'step3_inventory_prepare',
|
||||
'step5_match_inventory',
|
||||
'step6_generate_file',
|
||||
'step7_upload_freight',
|
||||
]
|
||||
for key in legacy_keys:
|
||||
assert key not in LIFECYCLE_STAGE_BY_PROCESSING_STAGE, (
|
||||
f"CheckPoint 遗留键 {key!r} 不得再进入阶段映射"
|
||||
)
|
||||
for stage_code in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
|
||||
assert not str(stage_code).startswith('step'), (
|
||||
f"阶段映射出现非契约键 {stage_code!r}"
|
||||
)
|
||||
# 契约码本身仍能正常映射:库存匹配属通知准备,processing_stage 权威生效。
|
||||
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
|
||||
|
||||
result = project_lifecycle(
|
||||
current_gate={'gate_code': 'task_creation', 'status': 'invalidated'},
|
||||
blocking_reason={'code': 'gate_invalidated'},
|
||||
has_candidate_context=True,
|
||||
processing_stage='step5_match_inventory',
|
||||
processing_stage='inventory_matching',
|
||||
)
|
||||
# processing_stage 权威高于错误的 task_creation 门禁。
|
||||
assert result['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert result['lifecycle_authority'] == 'processing_stage'
|
||||
current = next(e for e in result['lifecycle_entries'] if e['state'] == 'current')
|
||||
assert current['code'] == 'fulfillment_prep'
|
||||
|
||||
|
||||
def test_fifteen_stages_inventory_source_before_review():
|
||||
|
||||
@@ -283,7 +283,7 @@ def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(m
|
||||
id=1,
|
||||
order_task_id=9,
|
||||
upload_status='uploaded',
|
||||
current_step='step6_generate_file',
|
||||
current_step='excel_generating',
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
)
|
||||
|
||||
@@ -76,7 +76,7 @@ def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app):
|
||||
extraction_run_id=int(run.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
|
||||
@@ -91,7 +91,7 @@ def test_service_chain_customer_confirm_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.review_status = 'pending_confirm'
|
||||
notice.current_step = 'step4_match_inventory'
|
||||
notice.current_step = 'inventory_matching'
|
||||
notice.customer_id = 1
|
||||
db.session.commit()
|
||||
|
||||
@@ -112,7 +112,7 @@ def test_service_chain_inventory_match_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.match_status = 'matched'
|
||||
notice.current_step = 'step4_match_inventory'
|
||||
notice.current_step = 'inventory_matching'
|
||||
db.session.commit()
|
||||
|
||||
before, projection = _project_after_sync(notice, order_task, run)
|
||||
@@ -130,7 +130,7 @@ def test_service_chain_excel_generate_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.upload_status = 'pending'
|
||||
notice.current_step = 'step7_upload_freight'
|
||||
notice.current_step = 'freight_uploading'
|
||||
notice.export_file_path = '/tmp/fake-shipping.xlsx'
|
||||
db.session.commit()
|
||||
|
||||
@@ -148,7 +148,7 @@ def test_service_chain_freight_upload_retry_projection(app, workbench_chain_ids)
|
||||
"""
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.current_step = 'step7_upload_freight'
|
||||
notice.current_step = 'freight_uploading'
|
||||
notice.upload_status = 'failed'
|
||||
notice.export_file_path = '/tmp/fake-shipping.xlsx'
|
||||
db.session.commit()
|
||||
|
||||
+54
@@ -22,6 +22,7 @@ const i18n = createI18n({
|
||||
actionCodes: {
|
||||
reload_inventory_result: '重新读取库存结果',
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
confirm_customer: '确认客户',
|
||||
},
|
||||
inventoryActions: {
|
||||
reloadInventoryResult: '重新读取库存结果',
|
||||
@@ -337,4 +338,57 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
// 关键断言:无 statusDetail 时说明行完全不渲染,不留空壳。
|
||||
expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders the suggested next action instead of the reason text when next_action is present', () => {
|
||||
// v4 语义分离:「下一步」给建议动作(确认客户),原因文案(客户尚未确认)
|
||||
// 属于阻塞原因位,不得再挤进下一步槽位。
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
blockingReason: {
|
||||
code: 'customer_unresolved',
|
||||
message: '客户尚未确认',
|
||||
nextAction: 'confirm_customer',
|
||||
} as any,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('确认客户');
|
||||
});
|
||||
|
||||
it('hides the generic run-level status detail when a specific blocking reason is shown', () => {
|
||||
// v4 去重:具体阻断原因已由「下一步」承载时,泛化的「当前步骤需要人工处理」属纯重复。
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
blockingReason: {
|
||||
code: 'customer_unresolved',
|
||||
message: '客户尚未确认',
|
||||
nextAction: 'confirm_customer',
|
||||
} as any,
|
||||
statusDetail: { text: '当前步骤需要人工处理' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the run-level status detail when the blocking reason is generic', () => {
|
||||
// 无具体原因(未知码、无契约文案)时,Run 级等待说明仍是唯一信息,必须保留。
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
blockingReason: { code: 'internal_gate_reason' } as any,
|
||||
statusDetail: { text: '当前步骤需要人工处理' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-status-detail"]').text()).toBe('当前步骤需要人工处理');
|
||||
});
|
||||
});
|
||||
+27
-6
@@ -10,7 +10,9 @@
|
||||
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
|
||||
loading 仅在挂载期抑制可执行动作,等权威投影到达后再放行(fail-closed);
|
||||
由 ShippingOrderReviewView 在 mountCurrentProcessingCard 时挂载;
|
||||
v2 新增 statusDetail:状态块内嵌动态说明(隐藏裁决在视图侧,见 spec §5.2)。
|
||||
v2 新增 statusDetail:状态块内嵌动态说明(隐藏裁决在视图侧,见 spec §5.2);
|
||||
v4 语义分离:下一步优先消费 blocking_reason.next_action 的建议动作文案,
|
||||
且具体阻断原因在场时隐藏泛化 statusDetail(防同卡三行「待人工」空话)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -20,7 +22,10 @@ import type {
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingPrimaryAction,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import {
|
||||
isGenericBlockingReason,
|
||||
resolveShippingProcessingStageLabel,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
|
||||
import { lookupWorkbenchAction, shouldRenderWorkbenchAction } from '@/features/shipping-progress/workbenchActionRegistry';
|
||||
import { inventoryActionLabelKey, isInternalInventoryAction } from '@/features/shipping-progress/actionPresentation';
|
||||
@@ -147,9 +152,15 @@ const nextStepText = computed(() => {
|
||||
// 其余按 user_status/blocking_reason 照常渲染,空态自然落在「状态待确认」,不做骨架二次刷新。
|
||||
const automationMessage = props.loading ? safeMessage(props.automation?.message) : '';
|
||||
if (automationMessage) return automationMessage;
|
||||
// 1) blocking_reason → 用后端给的 i18n_key 渲染具体阻断
|
||||
// 1) blocking_reason → 先给契约注册的「建议动作」(下一步=做什么),
|
||||
// 再回退原因文案(i18n_key / Gate 命名空间);禁止裸露内部原因码。
|
||||
const br = props.blockingReason;
|
||||
if (br) {
|
||||
const nextAction = String(br.nextAction || br.next_action || '').trim();
|
||||
const actionKey = nextAction
|
||||
? `workspace.shippingNotice.processGate.actionCodes.${nextAction}`
|
||||
: '';
|
||||
if (actionKey && te(actionKey)) return t(actionKey);
|
||||
const i18nKey = String(br.i18nKey || '').trim();
|
||||
if (i18nKey && te(i18nKey)) {
|
||||
return t(i18nKey);
|
||||
@@ -205,6 +216,15 @@ const showNextStep = computed(() => {
|
||||
return !['completed', 'cancelled'].includes(status);
|
||||
});
|
||||
|
||||
/**
|
||||
* 状态块内嵌动态说明的显隐:具体阻断原因已由「下一步」承载时,
|
||||
* Run 级泛化等待说明(如「当前步骤需要人工处理」)属纯重复,隐藏。
|
||||
*/
|
||||
const showStatusDetail = computed(() => {
|
||||
if (!props.statusDetail?.text) return false;
|
||||
return isGenericBlockingReason(props.blockingReason, te);
|
||||
});
|
||||
|
||||
/**
|
||||
* 判断当前工作台是否应隐藏后端下发的纯导航动作。
|
||||
* 批次中心可用它打开工作台;进入工作台后必须复用注册表规则,避免当前阶段再次显示
|
||||
@@ -382,13 +402,14 @@ type ReviewCurrentUserStatus =
|
||||
/>
|
||||
{{ statusLabel }}
|
||||
</dd>
|
||||
<!-- v2:状态块内嵌动态说明(弱文本一行,不加标题/图标/区块;显隐裁决在视图侧)。 -->
|
||||
<!-- v2:状态块内嵌动态说明(弱文本一行,不加标题/图标/区块;
|
||||
v4:blocking_reason 已含具体原因时隐藏,避免与「下一步」重复)。 -->
|
||||
<p
|
||||
v-if="statusDetail?.text"
|
||||
v-if="showStatusDetail"
|
||||
class="w-full text-[11px] leading-4 text-muted"
|
||||
data-testid="review-current-task-status-detail"
|
||||
aria-live="polite"
|
||||
>{{ statusDetail.text }}</p>
|
||||
>{{ statusDetail?.text }}</p>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
|
||||
+82
@@ -1184,4 +1184,86 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-10"]');
|
||||
expect(row.findAll('button')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('shows a specific blocking reason once per waiting-human card without header duplication', async () => {
|
||||
// v4 去重:具体原因由文件行页脚独家承载;任务卡头不再重复同一句。
|
||||
// ui_state 挂在任务条目上(与后端 EML 聚合下发形态一致:任务级为代表子项原因)。
|
||||
const projection = buildProjection();
|
||||
setStatusGroup(projection, 'waiting_human', [{
|
||||
user_task_no: 'OT-REASON-ONCE', group: 'waiting_human', status_label: 'pending_review',
|
||||
file_count: 1, run_no: 'RUN-REASON-ONCE', can_append: false,
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'customer_unresolved', message: '客户尚未确认' },
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
objects: [{
|
||||
kind: 'document', object_key: 'DOC-REASON', label: 'reason.pdf', filename: 'reason.pdf',
|
||||
document_id: 91, root_document_id: 91, status_label: 'pending_review',
|
||||
}],
|
||||
}]);
|
||||
const workItem = buildWorkItem('OT-REASON-ONCE', {
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'reason.pdf', documentId: 91,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-REASON',
|
||||
},
|
||||
status: 'waiting_human',
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'customer_unresolved', message: '客户尚未确认' },
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [workItem], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:具体原因全文只出现一次,且带「阻塞原因:」前缀落在文件行页脚。
|
||||
const matches = wrapper.text().match(/客户尚未确认/g) || [];
|
||||
expect(matches.length).toBe(1);
|
||||
expect(wrapper.text()).toContain('阻塞原因:客户尚未确认');
|
||||
});
|
||||
|
||||
it('hides the blocker line when the backend only provides a generic fallback reason', async () => {
|
||||
// v4:未知原因码不得渲染成「当前步骤需要人工处理」空话;状态芯片已表达待人工。
|
||||
const projection = buildProjection();
|
||||
setStatusGroup(projection, 'waiting_human', [{
|
||||
user_task_no: 'OT-REASON-GENERIC', group: 'waiting_human', status_label: 'pending_review',
|
||||
file_count: 1, run_no: 'RUN-REASON-GENERIC', can_append: false,
|
||||
objects: [{
|
||||
kind: 'document', object_key: 'DOC-GENERIC', label: 'generic.pdf', filename: 'generic.pdf',
|
||||
document_id: 92, root_document_id: 92, status_label: 'pending_review',
|
||||
}],
|
||||
}]);
|
||||
const workItem = buildWorkItem('OT-REASON-GENERIC', {
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'generic.pdf', documentId: 92,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-GENERIC',
|
||||
},
|
||||
status: 'waiting_human',
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'mystery_internal_code' },
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [workItem], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.text()).not.toContain('阻塞原因');
|
||||
expect(wrapper.text()).not.toContain('当前步骤需要人工处理');
|
||||
});
|
||||
});
|
||||
+16
-7
@@ -30,8 +30,8 @@ import {
|
||||
toggleTaskDetails,
|
||||
} from '@/features/chat/shipping/conversationProcessingState';
|
||||
import {
|
||||
resolveBlockingReasonText,
|
||||
resolveShippingProcessingMessage,
|
||||
resolveShippingProcessingReasonLabel,
|
||||
resolveShippingProcessingStageLabel,
|
||||
resolveShippingProcessingStatusLabel,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
@@ -593,7 +593,8 @@ function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessin
|
||||
const reason = file.projection.uiState
|
||||
? file.projection.uiState.blocking_reason
|
||||
: file.projection.blockingReason;
|
||||
return resolveShippingProcessingReasonLabel(reason, te, t);
|
||||
// v4:具体原因才展示(Gate 命名空间/契约 message 可解析),通用兜底返回空串隐藏。
|
||||
return resolveBlockingReasonText(reason, te, t);
|
||||
}
|
||||
return taskReasonLabel(task);
|
||||
}
|
||||
@@ -686,12 +687,20 @@ function stageLabel(task: ConversationProcessingUserTask): string {
|
||||
return intakeStageLabel(projection);
|
||||
}
|
||||
|
||||
/** 展示后端 ui_state 已裁决的阻断原因;i18n 仅负责翻译,不映射或猜测业务原因。 */
|
||||
/** 展示后端 ui_state 已裁决的阻断原因;v4:具体原因才展示,通用兜底返回空串。 */
|
||||
function taskReasonLabel(task: ConversationProcessingUserTask): string {
|
||||
const reason = task.uiState
|
||||
? task.uiState.blocking_reason
|
||||
: task.blockingReason;
|
||||
return resolveShippingProcessingReasonLabel(reason, te, t);
|
||||
return resolveBlockingReasonText(reason, te, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务卡头原因行显隐:workbench 模式下文件行页脚已逐文件承载原因,
|
||||
* 卡头不再重复同一句;非 workbench(折叠聚合卡)仍由卡头独家展示。
|
||||
*/
|
||||
function taskHeaderReasonVisible(task: ConversationProcessingUserTask): boolean {
|
||||
return !props.workbenchMode || visibleWorkbenchFileRows(task).length === 0;
|
||||
}
|
||||
|
||||
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
|
||||
@@ -960,7 +969,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
<div v-if="taskHeaderReasonVisible(task) && taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
{{ taskReasonLabel(task) }}
|
||||
</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
|
||||
@@ -1056,7 +1065,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
|
||||
<div v-if="taskHeaderReasonVisible(task) && taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
|
||||
</button>
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-amber-200/70 pt-2">
|
||||
@@ -1323,7 +1332,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
<div v-if="taskHeaderReasonVisible(task) && taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
{{ taskReasonLabel(task) }}
|
||||
</div>
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-emerald-200/70 pt-2">
|
||||
|
||||
@@ -649,6 +649,42 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
expect(review.intakeParseLoadFailed.value).toBe(true);
|
||||
});
|
||||
|
||||
it('loads intake parse context for a formal-downstream Case while activeCase stays unloaded', async () => {
|
||||
// 选法 2:正式下游(货代上传等)切 PDF 不拉 Case/Evidence,activeCase 保持 null。
|
||||
// 关键断言:接收解析工作面回看已完成阶段时,上下文仍必须按 requestedCaseNo 拉取,
|
||||
// 不得因 activeCase 为 null 静默跳过(否则面板渲染成空白)。
|
||||
api.getQueue.mockResolvedValue({
|
||||
summary: { total: 1, needs_action: 0, processing: 0, completed: 1 },
|
||||
items: [{
|
||||
case_no: 'CASE-2', document_id: 2, status: 'confirmed',
|
||||
has_formal_ot: true,
|
||||
lifecycle_stage: 'freight_upload',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available' },
|
||||
{ code: 'order_review', state: 'available' },
|
||||
{ code: 'fulfillment_prep', state: 'available' },
|
||||
{ code: 'freight_upload', state: 'current' },
|
||||
],
|
||||
}],
|
||||
});
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-2');
|
||||
|
||||
api.getCase.mockClear();
|
||||
api.getEvidence.mockClear();
|
||||
await review.selectCase('CASE-2');
|
||||
// 选法 2 关键断言:正式下游切换不拉复核 Case/Evidence,activeCase 为空。
|
||||
expect(api.getCase).not.toHaveBeenCalled();
|
||||
expect(review.activeCase.value).toBeNull();
|
||||
expect(review.requestedCaseNo.value).toBe('CASE-2');
|
||||
|
||||
await expect(review.ensureIntakeParseContextLoaded('CASE-2')).resolves.toBe(true);
|
||||
expect(api.getIntakeParseContext).toHaveBeenLastCalledWith('CASE-2');
|
||||
expect(review.intakeParseContext.value?.case_no).toBe('CASE-2');
|
||||
expect(review.intakeParseLoading.value).toBe(false);
|
||||
expect(review.intakeParseLoadFailed.value).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the latest same-Case intake context when an older success resolves last', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
|
||||
@@ -993,10 +993,13 @@ export function useShippingOrderReview(options: {
|
||||
/**
|
||||
* 仅在用户打开接收解析工作面时按需读取当前 Case 的附件与邮件正文。
|
||||
* Case/代次双校验避免迟到响应把旧附件或 EML 写回当前工作面;失败保持空上下文。
|
||||
* 选法 2(正式下游)下 activeCase 刻意为 null,此时以 requestedCaseNo 校验目标,
|
||||
* 与 ensurePreviewLoaded 的兜底口径一致;否则回看已完成接收解析阶段会静默跳过加载。
|
||||
*/
|
||||
const ensureIntakeParseContextLoaded = async (caseNo: string): Promise<boolean> => {
|
||||
const target = String(caseNo || '').trim();
|
||||
if (!target || activeCase.value?.case_no !== target) {
|
||||
const expectedCaseNo = String(requestedCaseNo.value || activeCase.value?.case_no || '').trim();
|
||||
if (!target || target !== expectedCaseNo) {
|
||||
++intakeParseRequestGeneration;
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
@@ -1014,7 +1017,7 @@ export function useShippingOrderReview(options: {
|
||||
if (
|
||||
requestGeneration !== intakeParseRequestGeneration
|
||||
|| generation !== caseLoadGeneration
|
||||
|| activeCase.value?.case_no !== target
|
||||
|| String(requestedCaseNo.value || activeCase.value?.case_no || '').trim() !== target
|
||||
) return false;
|
||||
intakeParseContext.value = context;
|
||||
return true;
|
||||
@@ -1022,7 +1025,7 @@ export function useShippingOrderReview(options: {
|
||||
if (
|
||||
requestGeneration === intakeParseRequestGeneration
|
||||
&& generation === caseLoadGeneration
|
||||
&& activeCase.value?.case_no === target
|
||||
&& String(requestedCaseNo.value || activeCase.value?.case_no || '').trim() === target
|
||||
) {
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoadFailed.value = true;
|
||||
@@ -1032,7 +1035,7 @@ export function useShippingOrderReview(options: {
|
||||
if (
|
||||
requestGeneration === intakeParseRequestGeneration
|
||||
&& generation === caseLoadGeneration
|
||||
&& activeCase.value?.case_no === target
|
||||
&& String(requestedCaseNo.value || activeCase.value?.case_no || '').trim() === target
|
||||
) {
|
||||
intakeParseLoading.value = false;
|
||||
}
|
||||
|
||||
@@ -108,6 +108,46 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('preserves explainability message and next_action on blocking_reason', () => {
|
||||
// v4 阻塞原因具体化:冻结 explainability 契约透传的 message / next_action
|
||||
// 是「阻塞原因行」与「下一步建议动作」的数据源,归一化不得剥离。
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'OT-REASON',
|
||||
work_item_type: 'order_task',
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
ui_state: {
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: {
|
||||
code: 'customer_unresolved',
|
||||
message: '客户尚未确认',
|
||||
next_action: 'confirm_customer',
|
||||
},
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
source_summary: {
|
||||
email_subject: null,
|
||||
filename: 'reason.pdf',
|
||||
document_id: 91,
|
||||
document_count: 1,
|
||||
parsed_document_count: 1,
|
||||
candidate_count: 1,
|
||||
customer_name: null,
|
||||
po_number: null,
|
||||
failure_reason_code: null,
|
||||
parse_attempt_count: 0,
|
||||
asset_status: 'ready',
|
||||
},
|
||||
child_order_tasks: [],
|
||||
});
|
||||
const reason = normalized?.uiState?.blocking_reason;
|
||||
expect(reason?.code).toBe('customer_unresolved');
|
||||
expect(reason?.message).toBe('客户尚未确认');
|
||||
expect(reason?.nextAction).toBe('confirm_customer');
|
||||
});
|
||||
|
||||
it('normalizes the EML status-partition file count', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'INTAKE:SNI-EML',
|
||||
|
||||
@@ -108,12 +108,16 @@ function normalizeStageNode(raw: unknown): ShippingProcessingStageNode | null {
|
||||
|
||||
/**
|
||||
* [T9 用户态 Projection] 规范 blocking_reason(后端 snake_case {code, i18n_key, details})。
|
||||
* v4:保留冻结 explainability 契约透传的 message(中文兜底文案)与
|
||||
* next_action(下一步建议动作码,camel/snake 兼容),供「阻塞原因行」与
|
||||
* 「下一步」槽位消费;禁止剥离,否则 UI 退化为通用状态文案。
|
||||
*/
|
||||
function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const code = String(item.code ?? '').trim();
|
||||
if (!code) return null;
|
||||
const nextAction = item.next_action ?? item.nextAction;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
|
||||
@@ -121,6 +125,8 @@ function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason
|
||||
typeof item.details === 'object' && item.details != null
|
||||
? (item.details as Record<string, unknown>)
|
||||
: {},
|
||||
message: item.message != null ? String(item.message) : null,
|
||||
nextAction: nextAction != null ? String(nextAction) : null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
extractExtractionProgressReasonCode,
|
||||
isGenericBlockingReason,
|
||||
isRedundantExtractionDetail,
|
||||
resolveBlockingReasonText,
|
||||
resolveExtractionActivityMessage,
|
||||
resolveRunLifecycleUserStatus,
|
||||
resolveShippingProcessingReasonLabel,
|
||||
@@ -175,3 +177,38 @@ describe('extraction lifecycle display (v2 状态展示统一)', () => {
|
||||
expect(isRedundantExtractionDetail('', 'waiting_human')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('blocking reason text resolution (v4 阻塞原因具体化)', () => {
|
||||
// 仅登记通用兜底与一个 Gate 命名空间码,验证解析链与隐藏判定
|
||||
const REASON_TEXT: Record<string, string> = {
|
||||
'chat.shippingProcessing.reasonCode.unknown': '当前步骤需要人工处理',
|
||||
'workspace.shippingNotice.processGate.reasons.customer_unresolved': '客户尚未确认',
|
||||
};
|
||||
const te = (key: string) => key in REASON_TEXT;
|
||||
const t = (key: string) => REASON_TEXT[key] ?? key;
|
||||
|
||||
it('resolveBlockingReasonText:Gate 命名空间可解析的原因码返回具体文案', () => {
|
||||
expect(resolveBlockingReasonText({ code: 'customer_unresolved' }, te, t)).toBe('客户尚未确认');
|
||||
});
|
||||
|
||||
it('resolveBlockingReasonText:命名空间未命中时回退契约透传 message', () => {
|
||||
// 关键断言:后端 explainability.message 是 i18n 之后的最后兜底,不是首选
|
||||
expect(resolveBlockingReasonText({
|
||||
code: 'budget_stopped',
|
||||
message: '订单识别预算已用尽,请检查文档后进入复核',
|
||||
}, te, t)).toBe('订单识别预算已用尽,请检查文档后进入复核');
|
||||
});
|
||||
|
||||
it('resolveBlockingReasonText:通用兜底返回空串,调用方据此隐藏原因行', () => {
|
||||
expect(resolveBlockingReasonText({ code: 'internal_gate_reason' }, te, t)).toBe('');
|
||||
expect(resolveBlockingReasonText(null, te, t)).toBe('');
|
||||
expect(resolveBlockingReasonText(undefined, te, t)).toBe('');
|
||||
});
|
||||
|
||||
it('isGenericBlockingReason:Gate 命名空间可解析即非通用;仅未知码为通用', () => {
|
||||
// 关键断言:i18n 命名空间可解析(四语言齐备)才算具体原因
|
||||
expect(isGenericBlockingReason({ code: 'customer_unresolved' }, te)).toBe(false);
|
||||
expect(isGenericBlockingReason({ code: 'internal_gate_reason' }, te)).toBe(true);
|
||||
expect(isGenericBlockingReason(null, te)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -87,6 +87,44 @@ export function resolveShippingProcessingReasonLabel(
|
||||
return te(unknownKey) ? t(unknownKey) : '当前步骤需要人工处理';
|
||||
}
|
||||
|
||||
/** Gate 原因码的多命名空间查找键(与 resolveGateReasonLabel 保持同源顺序)。 */
|
||||
function gateReasonNamespaceKeys(code: string): string[] {
|
||||
return [
|
||||
`chat.shippingProcessing.gateReasons.${code}`,
|
||||
`workspace.shippingNotice.workflowReasons.${code}`,
|
||||
`workspace.shippingNotice.processGate.reasons.${code}`,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析批次中心行内「阻塞原因」文案;通用兜底返回空串(调用方隐藏原因行)。
|
||||
* 核心逻辑:i18n_key → reasonCode 专用键 → Gate 三命名空间 → 契约透传 message;
|
||||
* 与 isGenericBlockingReason 同一判据,保证「隐藏的」与「展示的」口径一致。
|
||||
*/
|
||||
export function resolveBlockingReasonText(
|
||||
reason: {
|
||||
code?: string | null;
|
||||
i18nKey?: string | null;
|
||||
i18n_key?: string | null;
|
||||
message?: string | null;
|
||||
} | null | undefined,
|
||||
te: (key: string) => boolean,
|
||||
t: (key: string) => string,
|
||||
): string {
|
||||
if (isGenericBlockingReason(reason, te)) return '';
|
||||
const i18nKey = String(reason?.i18nKey || reason?.i18n_key || '').trim();
|
||||
if (i18nKey && te(i18nKey)) return t(i18nKey);
|
||||
const code = String(reason?.code || '').trim();
|
||||
if (code) {
|
||||
const reasonCodeKey = `chat.shippingProcessing.reasonCode.${code}`;
|
||||
if (te(reasonCodeKey)) return t(reasonCodeKey);
|
||||
for (const key of gateReasonNamespaceKeys(code)) {
|
||||
if (te(key)) return t(key);
|
||||
}
|
||||
}
|
||||
return String(reason?.message || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析统一处理文案。
|
||||
*
|
||||
@@ -197,22 +235,33 @@ export function resolveShippingLifecycleStageLabel(
|
||||
/**
|
||||
* 判定阻塞原因是否为「通用兜底」(应在行内隐藏,避免与状态芯片重复)。
|
||||
*
|
||||
* 三方约定:仅当下发到具体、非兜底的阻塞原因(有真实 i18n 文案)才展示原因行;
|
||||
* 进到 reasonCode.unknown / 无 i18n_key 的通用码一律视为重复信息。
|
||||
* 三方约定:仅当下发到具体、非兜底的阻塞原因才展示原因行。具体判据:
|
||||
* i18n_key 命中、reasonCode 专用键命中、Gate 三命名空间任一命中
|
||||
* (四语言齐备),或契约透传了具体 message(无命名空间时的最后兜底)。
|
||||
* 进到 unknown / 全部未命中的一律视为重复信息。
|
||||
*
|
||||
* @param reason - 后端 blocking_reason(code / i18n_key)
|
||||
* @param reason - 后端 blocking_reason(code / i18n_key / message)
|
||||
* @param te - i18n te
|
||||
* @returns true=通用兜底(应隐藏)
|
||||
*/
|
||||
export function isGenericBlockingReason(
|
||||
reason: { code?: string | null; i18nKey?: string | null; i18n_key?: string | null } | null | undefined,
|
||||
reason: {
|
||||
code?: string | null;
|
||||
i18nKey?: string | null;
|
||||
i18n_key?: string | null;
|
||||
message?: string | null;
|
||||
} | null | undefined,
|
||||
te: (key: string) => boolean,
|
||||
): boolean {
|
||||
if (!reason) return true;
|
||||
const i18nKey = String(reason.i18nKey || reason.i18n_key || '').trim();
|
||||
if (i18nKey && te(i18nKey)) return false;
|
||||
const code = String(reason.code || '').trim();
|
||||
if (code && code !== 'unknown' && te(`chat.shippingProcessing.reasonCode.${code}`)) return false;
|
||||
if (code && code !== 'unknown') {
|
||||
if (te(`chat.shippingProcessing.reasonCode.${code}`)) return false;
|
||||
if (gateReasonNamespaceKeys(code).some((key) => te(key))) return false;
|
||||
}
|
||||
if (String(reason.message || '').trim()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -167,6 +167,11 @@ export interface ShippingProcessingBlockingReason {
|
||||
code: string;
|
||||
i18nKey?: string | null;
|
||||
details?: Record<string, unknown>;
|
||||
/** 建单前资格快照回退透传(冻结 explainability 契约):中文兜底文案,前端优先 i18n。 */
|
||||
message?: string | null;
|
||||
/** 契约注册的下一步动作码(processGate.actionCodes.*),camel/snake 兼容读取。 */
|
||||
nextAction?: string | null;
|
||||
next_action?: string | null;
|
||||
}
|
||||
/**
|
||||
* 用户态统一 Projection 主动作(T8 决策 F2;后端对象 {code, i18n_key, parameters})。
|
||||
@@ -955,7 +960,8 @@ export interface ShippingRpaRuntime {
|
||||
}
|
||||
|
||||
export interface ShippingCurrentStepProgress {
|
||||
step_key?: string;
|
||||
/** 15 阶契约阶段码(CheckPoint 时代 stepN_* 遗留键已清除)。 */
|
||||
stage?: string;
|
||||
step_title?: string;
|
||||
status?: 'running' | 'completed' | 'needs_human' | 'pending' | string;
|
||||
message?: string;
|
||||
|
||||
@@ -993,6 +993,47 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('reloads the intake parse context by requested Case when activeCase is unloaded (formal downstream)', async () => {
|
||||
// 用户场景:正式下游文件(货代上传 · 已创建任务)切进后 activeCase 为 null(选法 2),
|
||||
// 此时回看「接收解析」已完成阶段,上下文必须按 requestedCaseNo 发起请求;
|
||||
// 静默跳过会让 ReviewIntakeParsePanel 以空 context 渲染成整块空白。
|
||||
const originalQueue = reviewQueue.value;
|
||||
const originalActiveCase = activeCase.value;
|
||||
const originalRequested = requestedCaseNo.value;
|
||||
try {
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0],
|
||||
has_formal_ot: true,
|
||||
lifecycle_stage: 'freight_upload',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available' },
|
||||
{ code: 'order_review', state: 'available' },
|
||||
{ code: 'fulfillment_prep', state: 'available' },
|
||||
{ code: 'freight_upload', state: 'current' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
activeCase.value = null;
|
||||
requestedCaseNo.value = 'CASE-1';
|
||||
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
|
||||
|
||||
ensureIntakeParseContextLoaded.mockClear();
|
||||
await (wrapper.vm as any).selectLifecycleStage('intake_parse');
|
||||
await flushPromises();
|
||||
|
||||
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
|
||||
.toBe('intake_parse');
|
||||
// 关键断言:activeCase 为 null 时不得跳过上下文加载,且以目标 Case 请求。
|
||||
expect(ensureIntakeParseContextLoaded).toHaveBeenCalledWith('CASE-1');
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
activeCase.value = originalActiveCase;
|
||||
requestedCaseNo.value = originalRequested;
|
||||
}
|
||||
});
|
||||
|
||||
it('stops the pending reparse navigation when the user selects another PDF', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
|
||||
@@ -326,7 +326,9 @@ const lifecycleUiState = computed(() => {
|
||||
};
|
||||
}
|
||||
// [STEP 3] 建单前:Run/Queue 项仍由后端下发生命周期入口。
|
||||
const currentCaseNo = String(activeCase.value?.case_no || '').trim();
|
||||
// 选法 2(正式下游回看)下 activeCase 刻意为 null,此时以切换管线的 requestedCaseNo
|
||||
// 定位队列项,否则 entries 永远为空、阶段导航整体退化为 blocked。
|
||||
const currentCaseNo = String(activeCase.value?.case_no || requestedCaseNo.value || '').trim();
|
||||
const reviewEntry = (reviewQueue.value?.items || reviewRun.value?.items || []).find(
|
||||
(item) => String(item.case_no || '').trim() === currentCaseNo,
|
||||
);
|
||||
@@ -399,6 +401,13 @@ const intakeParseContextAuthorized = computed(() => {
|
||||
|| lifecycleEntryIsEnterable(entry)
|
||||
);
|
||||
});
|
||||
/**
|
||||
* 接收解析工作面的目标 Case:选法 2(正式下游回看)下 activeCase 刻意为 null,
|
||||
* 必须以切换管线的 requestedCaseNo 兜底,否则上下文加载会被静默跳过(面板空白)。
|
||||
*/
|
||||
const intakeTargetCaseNo = computed(() => (
|
||||
String(activeCase.value?.case_no || requestedCaseNo.value || '').trim()
|
||||
));
|
||||
const lifecycleStageItems = computed<ReviewLifecycleStageItem[]>(() => {
|
||||
const blocker = lifecycleUiState.value.blocker;
|
||||
const entries = lifecycleUiState.value.entries;
|
||||
@@ -484,8 +493,8 @@ async function retryCurrentIntakeParse(): Promise<void> {
|
||||
await Promise.all([
|
||||
reloadLatestDraft(),
|
||||
refreshShippingProcessing(),
|
||||
activeCase.value?.case_no
|
||||
? ensureIntakeParseContextLoaded(activeCase.value.case_no)
|
||||
intakeTargetCaseNo.value
|
||||
? ensureIntakeParseContextLoaded(intakeTargetCaseNo.value)
|
||||
: Promise.resolve(false),
|
||||
]);
|
||||
} catch (error) {
|
||||
@@ -576,8 +585,8 @@ async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { r
|
||||
pendingReleaseAutoAdvanceCaseNo.value = null;
|
||||
}
|
||||
}
|
||||
if (code === 'intake_parse' && intakeParseContextAuthorized.value && activeCase.value?.case_no) {
|
||||
void ensureIntakeParseContextLoaded(activeCase.value.case_no);
|
||||
if (code === 'intake_parse' && intakeParseContextAuthorized.value && intakeTargetCaseNo.value) {
|
||||
void ensureIntakeParseContextLoaded(intakeTargetCaseNo.value);
|
||||
}
|
||||
const mode: ReviewWorkbenchMode = code === 'order_review' || code === 'intake_parse'
|
||||
? 'standard'
|
||||
@@ -4445,8 +4454,8 @@ watch(
|
||||
// surface 反向成为前端阶段裁决。
|
||||
if (code === null) return;
|
||||
syncLifecycleWorkbenchMode(code);
|
||||
if (code === 'intake_parse' && intakeAuthorized && activeCase.value?.case_no) {
|
||||
void ensureIntakeParseContextLoaded(activeCase.value.case_no);
|
||||
if (code === 'intake_parse' && intakeAuthorized && intakeTargetCaseNo.value) {
|
||||
void ensureIntakeParseContextLoaded(intakeTargetCaseNo.value);
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
@@ -4527,10 +4536,15 @@ function retryFormalTaskDetail() {
|
||||
*/
|
||||
const REVIEW_EDITOR_NEEDED_STAGES: ReviewLifecycleStageCode[] = ['intake_parse', 'order_review', 'fulfillment_prep'];
|
||||
watch(
|
||||
lifecycleCurrentStageCode,
|
||||
// 用户查看面(含回看已完成阶段)驱动 Case 懒加载:选法 2 正式下游切 PDF 后 activeCase
|
||||
// 为 null,回看接收解析/订单复核/通知准备时必须按需补拉目标 Case,否则这些工作面
|
||||
// 只能渲染空白或残留上一份 PDF 的数据。
|
||||
lifecycleActiveStageCode,
|
||||
(stage) => {
|
||||
if (!stage || !REVIEW_EDITOR_NEEDED_STAGES.includes(stage)) return;
|
||||
const caseNo = String(displayCase.value?.case_no || '').trim();
|
||||
// 禁止使用 displayCase 兜底:它可能停留在上一份 PDF 的快照上造成串味;
|
||||
// 目标一律取当前工作面的 activeCase 或切换管线的 requestedCaseNo。
|
||||
const caseNo = String(activeCase.value?.case_no || requestedCaseNo.value || '').trim();
|
||||
if (!caseNo) return;
|
||||
if (stage === 'fulfillment_prep') {
|
||||
if (activeCase.value) return;
|
||||
@@ -5119,8 +5133,8 @@ watch(
|
||||
:load-failed="intakeParseLoadFailed"
|
||||
:preview-url="previewUrl || null"
|
||||
:preview-loading="previewLoading"
|
||||
@retry-context="() => { if (activeCase?.case_no) void ensureIntakeParseContextLoaded(activeCase.case_no); }"
|
||||
@load-preview="() => { if (activeCase?.case_no) void ensurePreviewLoaded(activeCase.case_no); }"
|
||||
@retry-context="() => { if (intakeTargetCaseNo) void ensureIntakeParseContextLoaded(intakeTargetCaseNo); }"
|
||||
@load-preview="() => { if (intakeTargetCaseNo) void ensurePreviewLoaded(intakeTargetCaseNo); }"
|
||||
/>
|
||||
<!-- 仅「固定为侧栏」时 PDF 占网格列;默认浮窗挂在根节点,不挤压订单区。 -->
|
||||
<div
|
||||
|
||||
Reference in new issue
Block a user