feat(shipping-notice): 实现对话级批量重试自动推进功能,优化库存与PDF匹配逻辑

- 新增对话级批量重试自动推进的完整链路:后端服务、API、数据投影逻辑
- 前端新增对话级重试按钮、多语言国际化支持与API类型定义
- 优化行级库存重试控制,新增retryable字段统一管控重试按钮展示,清理废弃的view_fulfillment_detail动作,标准化前端动作码排序逻辑
- 修复PDF坐标匹配的fail-close防护逻辑,避免生成伪精确匹配分数
- 调整订单确认后流程,提前进入库存获取阶段,移除冗余的确认建单按钮,优化用户流转体验
- 新增对应单元测试用例覆盖核心业务逻辑
This commit is contained in:
hugo committed 2026-08-07 16:30:45 +08:00
1 parent fd6a23f870
commit 1008911a7e
41 files changed
+3956 -1256

No files matched your search

@@ -13,15 +13,29 @@ def _coordinate_mapping(value: Any) -> dict[str, Any]:
return dict(value) if isinstance(value, dict) else {}
def _append_issue(layout: dict[str, Any], issue: str) -> None:
"""稳定追加坐标恢复失败码,不改变原 issues 相对顺序。"""
existing = layout.get('issues') if isinstance(layout.get('issues'), list) else []
issues = [str(item) for item in existing]
if issue not in issues:
issues.append(issue)
layout['issues'] = issues
def ensure_on_demand_coordinate_evidence(
*, document: ShippingOrderDocument, layout: dict[str, Any], page_nos: set[int] | None,
table_by_page: dict[int, dict[str, Any] | list[dict[str, Any]]] | None = None,
) -> dict[str, Any]:
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。"""
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。
【AI/调用方触发时机】:
- 订单字段重放、模板匹配或明细重建前,为当前 snapshot 恢复缺失页的真实坐标。
- 失败不静默;任何 PDFium/OCR 失败都会在 layout['issues'] 追加稳定失败码,
上游可据此将 matcher 从 no_match 转为 evidence_insufficient。
"""
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
return layout
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
# 兼容历史布局快照:布局任务曾将坐标证据写在顶层,正式抽取仍需复用它。
if not evidence:
legacy_keys = ('pages', 'page_glyphs', 'sources', 'tables')
evidence = {
@@ -29,7 +43,6 @@ def ensure_on_demand_coordinate_evidence(
for key in legacy_keys
if isinstance(layout.get(key), dict)
}
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
current_version = getattr(document, 'current_layout_version', None)
current_payload = getattr(current_version, 'payload_json', None)
if isinstance(current_payload, dict):
@@ -44,7 +57,15 @@ def ensure_on_demand_coordinate_evidence(
sources = _coordinate_mapping(evidence.get('sources'))
source_pages = _coordinate_mapping(sources.get('pages'))
tables = _coordinate_mapping(evidence.get('tables'))
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
# [FAIL-CLOSED GATE] page_glyphs 必须对所需页真实存在;不能用 pages 元数据或
# 非数字脏键来假装已恢复。MinerU HTML 表 + 空 page_glyphs 的组合必须继续走
# 真实 PDFium/OCR 抽取,否则会退化为"伪精确匹配分数"。
present_pages = {
int(key) for key in page_glyphs
if str(key).isdigit() and isinstance(page_glyphs.get(key), list) and len(page_glyphs.get(key) or []) > 0
}
needs_recovery = bool(page_nos is None) or not page_nos.issubset(present_pages)
if not needs_recovery:
return layout
tables_by_page: dict[int, list[dict[str, Any]]] = {}
for raw_table in layout.get('tables') or []:
@@ -70,11 +91,15 @@ def ensure_on_demand_coordinate_evidence(
)
asset = db.session.get(FileAsset, int(document.asset_id))
if asset is None:
_append_issue(layout, 'coordinate_evidence_asset_missing')
return layout
try:
native_pages = extract_native_pdf_pages(read_asset_bytes(asset))
except Exception:
# [FAIL-CLOSED] PDFium 级异常必须显式上报;禁止用 MinerU HTML 列名顶替坐标。
_append_issue(layout, 'coordinate_evidence_native_pdf_unavailable')
return layout
recovered_any_page = False
for page in native_pages:
if page_nos is not None and int(page.page_no) not in page_nos:
continue
@@ -87,12 +112,14 @@ def ensure_on_demand_coordinate_evidence(
source = 'ocr_coordinate'
except Exception:
glyphs = []
_append_issue(layout, f'coordinate_evidence_ocr_failed_page_{page.page_no}')
if not glyphs:
continue
page_key = str(page.page_no)
pages[page_key] = {'width': page.width, 'height': page.height}
page_glyphs[page_key] = glyphs
source_pages[page_key] = source
recovered_any_page = True
for table in tables_by_page.get(int(page.page_no), []):
table_id = str(table.get('table_id') or '')
chars = _native_characters_in_table(
@@ -107,6 +134,8 @@ def ensure_on_demand_coordinate_evidence(
chars = []
if table_id and chars:
tables[table_id] = chars
if page_nos is not None and not recovered_any_page:
_append_issue(layout, 'coordinate_evidence_no_page_recovered')
next_layout = dict(layout)
next_layout['coordinate_evidence'] = {
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
@@ -119,7 +119,22 @@ def match_frozen_coordinate_profiles(
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
if not pages or (not glyph_tables and not page_glyphs and not tables):
# [FAIL-CLOSED GATE] 第零层:on-demand 坐标恢复显式失败时直接拒绝匹配。
# 任何 coordinate_evidence_* 失败码都意味着正式证据不可用,MinerU HTML 列名
# 不得作为坐标模板匹配的替代事实源。
layout_issues = {str(item) for item in (layout.get('issues') or []) if str(item)}
coordinate_failure_issues = {
code for code in layout_issues if code.startswith('coordinate_evidence_')
}
if coordinate_failure_issues:
return ProfileMatchResult(status='evidence_insufficient')
# [FAIL-CLOSED GATE] 第一层:坐标字符证据必须至少有一种来源。
# MinerU HTML tables(layout['tables'])只有结构化列名、没有绝对坐标/bbox,
# 严禁单独充当坐标模板的匹配证据。否则会出现"MinerU 有列名但 matcher
# header_tokens=空、column_count=0、evidence_coverage 伪分数"的分裂。
if not pages:
return ProfileMatchResult(status='evidence_insufficient')
if not glyph_tables and not page_glyphs:
return ProfileMatchResult(status='evidence_insufficient')
page_text = _layout_page_text(
@@ -201,6 +216,25 @@ def match_frozen_coordinate_profiles(
)
reason_codes.extend(hard_conflict_codes)
# [FAIL-CLOSED GATE] 第二层:身份证据缺失时,结构/几何维度不得独立构成模板命中。
# 用户场景:page_glyphs 虽有字符但观测不到 header_tokens 或
# column_centers;若签名冻结了核心列身份证据,就必须以身份优先、
# 结构辅助。否则 table_geometry + page_structure 的弱证据会掩盖
# "列名证据没有进入匹配器" 的真正问题。
signature_patterns = (
[item for item in (signature_body or {}).get('table_patterns') or [] if isinstance(item, dict)]
if signature_body is not None else []
)
signature_expects_identity = any(
bool(p.get('header_tokens') or p.get('column_centers') or (p.get('column_count') or 0) > 0)
for p in signature_patterns
)
observed_header = [str(item) for item in (observed.get('header_tokens') or []) if str(item).strip()]
observed_col_count = int(observed.get('column_count') or 0)
observed_has_identity = bool(observed_header) or observed_col_count > 0
if signature_expects_identity and not observed_has_identity:
reason_codes.append('profile_core_column_evidence_missing')
weights = profile.document_match.scoring_weights
score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results)
hard_match = not reason_codes
@@ -256,6 +290,19 @@ def match_frozen_coordinate_profiles(
status='no_match', candidates=rendered,
top1_score=top1_score, top2_score=top2_score, margin=margin,
)
# [FAIL-CLOSED GATE] 第三层:全局证据不足优先于 no_match / layout_drift。
# 当所有候选要么缺签名身份证据、要么观测不到核心列名/列坐标时,必须
# evidence_insufficient,禁止把"没证据"误报成"模板都不匹配"。
global_identity_missing = all(
'profile_core_column_evidence_missing' in item.reason_codes
or 'profile_signature_missing' in item.reason_codes
for item in rendered
)
if global_identity_missing:
return ProfileMatchResult(
status='evidence_insufficient', candidates=rendered,
top1_score=None, top2_score=None, margin=None,
)
if _any_special_profile_feature(candidates, page_text=page_text):
return ProfileMatchResult(
status='layout_drift', candidates=rendered,
@@ -500,10 +500,12 @@ def _native_pdf_fallback_snapshot(
layout_payload=layout_payload_preview,
)
evidence_started = perf_counter()
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
# [FAIL-CLOSED OVERRIDE] Fallback 快照即使是 PDFium 文本回退,也必须默认
# 保存整页 glyph。否则一旦 on-demand 恢复异常(如 asset_id 丢失或 PDFium 崩
# 溃),matcher 会看到"MinerU 列名存在 + 空 page_glyphs"的分裂证据,输出
# 伪精确模板分数。坐标预算由后续 compact 负责兜底,初始生成必须包含身份证据。
evidence = _table_coordinate_evidence(
pages=native_pages, tables=tables, include_page_glyphs=False,
pages=native_pages, tables=tables, include_page_glyphs=True,
diagnostics=diagnostics,
)
if diagnostics is not None: