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

@@ -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()