refactor(shipping-notice): 进度信号统一为 15 阶 stage 契约码并透传阻断原因

- 后端进度写入 step_key 全量切换为 15 阶契约 stage 码
- 投影层清除 CheckPoint stepN_* 遗留别名与子串/前缀启发式,阶段信号按契约码精确匹配
- 建单前 Case 摘要透传草稿首要阻断原因
- 前端标签/归一化/处理卡片同步契约码,阻断原因按 i18n 优先展示
- 修复正式下游回看时 activeCase 刻意为空导致队列定位与接收解析上下文静默跳过
- 同步更新投影/门禁/工作台/RPA 流程测试
This commit is contained in:
hugo committed 2026-09-17 15:54:53 +08:00
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 冲突。"""
+2 -2
View File
@@ -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()