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