Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-09-08 15:36:47 +08:00
commit a2931e0095
37 files changed
+1790 -126

No files matched your search

@@ -1965,14 +1965,25 @@ def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str)
def _is_structured_part_identifier(raw: str) -> bool:
"""仅将带数字或连接符的料号作为纠偏证据,普通描述词保持原框位。"""
"""
判断文本是否可作为内部料号纠偏证据。
核心逻辑:去首尾空白后仍须是无空格的紧凑标识(字母数字 + ._:/-),且含数字或
连接符;含空格的贸易条款/描述串一律拒绝,避免去空格后误匹配。
Args:
raw: 候选原文。
Returns:
True 表示可作为 structured 料号证据。
"""
value = str(raw or '').strip()
compact = re.sub(r'\s+', '', value)
if not value or re.search(r'\s', value):
return False
return bool(
not re.match(r'^(?:revision|rev)\s*:', value, re.IGNORECASE)
and
re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', compact)
and re.search(r'\d|[._:/-]', compact)
not re.match(r'^(?:revision|rev):', value, re.IGNORECASE)
and re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', value)
and re.search(r'\d|[._:/-]', value)
)
@@ -1983,11 +1994,22 @@ def _resolve_shifted_part_number_candidates(
table_bbox: LayoutBBox,
line_start_field_code: str,
) -> list[CoordinateProfileLogicalRow]:
"""在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。
"""
在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。
固定/自适应/动态三种重建都可能先把描述折行绑定到内部料号框;这里复核当前
逻辑记录的后续候选,唯一高置信候选才替换,多个候选则保留 Review,避免改变
没有折行的其他模板。
核心逻辑:仅当当前位置读到的值不是 structured 料号(多为描述折行)时,才扫描
后续视觉行;唯一高置信候选可替换,多候选则 Review。当前位置已是 structured
时保持原值,禁止被后续条款行无条件覆盖。
Args:
rows: 三种重建模式产出的逻辑明细。
glyphs: 表区内带索引的字符。
ordered_layouts: 按 row_offset 排序的子行布局。
table_bbox: 重建坐标系下的表/页框。
line_start_field_code: 起行锚点字段编码。
Returns:
纠偏后的逻辑明细列表(原地更新 fields/issues)。
"""
part_fields = [
field for layout in ordered_layouts
@@ -2025,6 +2047,9 @@ def _resolve_shifted_part_number_candidates(
current = str(row.fields.get('part_number') or '').strip()
if not current or not row.source_row_indices:
continue
# 当前位置已是结构化料号:纠偏只服务描述折行,不得再扫后续条款行覆盖。
if _is_structured_part_identifier(current):
continue
record_start = min(row.source_row_indices)
record_end = (
min(min(next_row.source_row_indices) for next_row in rows[row_position + 1:])
@@ -5,7 +5,7 @@ backend/app/services/shipping_notice/document_layout/order_profile.py
依赖:Pydantic、坐标 bbox 契约、订单字段规则和已注册解析器。
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
matching_signature 供运行时硬门禁与维度比对。
matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。
"""
from __future__ import annotations
@@ -329,10 +329,10 @@ SCORING_DIMENSION_KEYS = (
'optional_static_text',
'trusted_business_context',
)
# table_geometry 保留为软分;MinerU 脏高度不得作为自动决胜硬门禁。
CRITICAL_STRUCTURE_DIMENSION_KEYS = (
'header_semantic_position',
'column_topology',
'table_geometry',
)
# 历史 v1 权重键 → v2 键;供 model_validator 迁移旧模板配置。
_LEGACY_SCORING_WEIGHT_KEYS: dict[str, str] = {
@@ -4,7 +4,9 @@ services/shipping_notice/document_layout/order_profile_matcher.py
用途:以冻结版面签名与坐标证据唯一匹配订单坐标模板,按统一七维权重做确定性综合评分。
依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
页存在≠page_structure 命中;line_layout 存在≠结构匹配;缺失锚点/客户提示不得满分。
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁。
"""
from __future__ import annotations
@@ -34,6 +36,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
)
from app.services.shipping_notice.document_layout.order_profile_signature import (
MATCHER_POLICY_ID,
clip_table_bbox_to_business_rows,
signature_checksum,
)
@@ -167,6 +170,8 @@ def match_frozen_coordinate_profiles(
observed = _observe_layout_features(
layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables,
page_glyphs=page_glyphs, signature=observed_signature,
termination_rules=_profile_termination_rules(profile),
exclusion_regions=_profile_exclusion_regions(profile),
)
if signature_body is None:
reason_codes.append('profile_signature_missing')
@@ -882,11 +887,20 @@ def _compute_dimension_results(
results: dict[str, MatchDimensionResult] = {}
# [STEP 1] header_semantic_position:表头语义和位置必须独立于锚点硬门禁。
# 有 required_anchors 时不做表头原子硬互斥——唯一身份由锚点承担,避免噪声表头误杀。
enforce_header_atoms = _should_enforce_header_atom_discriminator(required_hits)
header_result = _score_header_semantic_position(
signature=signature, observed=observed, required_hits=required_hits,
enforce_atom_discriminator=enforce_header_atoms,
)
results['header_semantic_position'] = header_result
if (
enforce_header_atoms
and header_result.state == 'mismatched'
and _header_discriminator_atoms_conflict(signature=signature, observed=observed)
):
hard_conflicts.append('profile_header_discriminator_conflict')
elif (
header_result.state == 'mismatched'
and signature
and signature.get('table_patterns')
@@ -926,13 +940,27 @@ def _compute_dimension_results(
return results, hard_conflicts
def _should_enforce_header_atom_discriminator(required_hits: list[bool]) -> bool:
"""
判断是否启用表头原子硬互斥。
核心逻辑:模板若已配置必选锚点,身份由锚点门禁承担,不再用表头原子硬杀;
仅「无必选锚点」的近亲模板才启用原子互斥。
"""
return not required_hits
def _score_header_semantic_position(
*,
signature: dict[str, Any] | None,
observed: dict[str, Any],
required_hits: list[bool],
enforce_atom_discriminator: bool = True,
) -> MatchDimensionResult:
"""比对真实表头 token、横向顺序和位置;锚点命中不替代表头结构证据。"""
"""比对真实表头 token、横向顺序和位置。
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
"""
if signature is None:
return MatchDimensionResult(state='unavailable', score=0.0)
expected_tokens: list[str] = []
@@ -951,6 +979,11 @@ def _score_header_semantic_position(
)
if not observed_tokens:
return MatchDimensionResult(state='unavailable', score=0.0)
if (
enforce_atom_discriminator
and _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens)
):
return MatchDimensionResult(state='mismatched', score=0.0)
matched = sum(1 for token in expected_tokens if token in observed_tokens)
token_ratio = matched / len(expected_tokens)
expected_order = [str(item).casefold() for table in signature.get('table_patterns') or [] if isinstance(table, dict) for item in table.get('header_order') or []]
@@ -971,6 +1004,43 @@ def _score_header_semantic_position(
)
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
_HEADER_ATOM_MIN_LEN = 3
def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
"""
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
核心逻辑:去撇号后按非字母数字切分;过滤过短词与虚词,避免 Q'TY/No. 噪声。
"""
atoms: set[str] = set()
for token in tokens:
normalized = re.sub(r"['’]", '', str(token).casefold())
for part in re.split(r'[^a-z0-9]+', normalized):
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
atoms.add(part)
return frozenset(atoms)
def _header_discriminator_atoms_conflict(
*,
signature: dict[str, Any] | None,
observed: dict[str, Any],
) -> bool:
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
if signature is None or not signature.get('table_patterns'):
return False
expected_tokens: list[str] = []
for table in signature.get('table_patterns') or []:
if isinstance(table, dict):
expected_tokens.extend(str(item) for item in table.get('header_tokens') or [])
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if not expected_tokens or not observed_tokens:
return False
return _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens)
def _score_column_topology(
*,
signature: dict[str, Any] | None,
@@ -1025,7 +1095,8 @@ def _score_table_geometry(
observed: dict[str, Any],
profile: OrderCoordinateProfile,
) -> MatchDimensionResult:
"""比对表区 bbox 中位数与容差。"""
"""比对主表身份几何:顶边与左右宽度;忽略底边高度(MinerU 粘连备注会拉高 y1)。"""
_ = profile
if signature is None:
return MatchDimensionResult(state='unavailable', score=0.0)
patterns = [item for item in signature.get('table_patterns') or [] if isinstance(item, dict)]
@@ -1045,11 +1116,30 @@ def _score_table_geometry(
if isinstance(tolerance, list) and len(tolerance) == 4
else [float(tolerance[0]) if isinstance(tolerance, list) and tolerance else 0.05] * 4
)
best = max(best, _bbox_similarity(median, reference_bbox, tolerances=tolerances))
best = max(
best,
_identity_table_geometry_similarity(
median, reference_bbox, tolerances=tolerances,
),
)
score = round(best, 6)
return MatchDimensionResult(state='matched' if score >= 0.65 else 'mismatched', score=score)
def _identity_table_geometry_similarity(
expected: list[float], observed: list[float], *, tolerances: list[float],
) -> float:
"""只比较 x0/y0/x1(顶边+宽度);y1 不参与身份分,避免脏表高绑架模板匹配。"""
# indices: 0=x0, 1=y0, 2=x1, 3=y1(忽略)
identity_indices = (0, 1, 2)
hits = 0
for index in identity_indices:
tolerance = float(tolerances[index]) if index < len(tolerances) else 0.05
if abs(float(expected[index]) - float(observed[index])) <= tolerance:
hits += 1
return round(hits / len(identity_indices), 6)
def _score_page_structure(
*,
signature: dict[str, Any] | None,
@@ -1140,15 +1230,6 @@ def _score_trusted_business_context(
)
def _bbox_similarity(expected: list[float], observed: list[float], *, tolerances: list[float]) -> float:
"""分别使用 x0/y0/x1/y1 容差评估表区几何。"""
deltas = [abs(float(a) - float(b)) for a, b in zip(expected, observed)]
if not deltas:
return 0.0
within = sum(1 for delta, tolerance in zip(deltas, tolerances) if delta <= tolerance)
return round(within / len(deltas), 6)
def _observe_layout_features(
*,
layout: dict[str, Any],
@@ -1157,6 +1238,8 @@ def _observe_layout_features(
glyph_tables: dict[str, Any],
page_glyphs: dict[str, Any],
signature: dict[str, Any] | None,
termination_rules: list[dict[str, Any]] | None = None,
exclusion_regions: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""从冻结 layout 聚合非敏感结构特征供维度比对。"""
persisted = layout.get('matching_features')
@@ -1183,6 +1266,16 @@ def _observe_layout_features(
primary_bbox = _select_signature_primary_table_bbox(
tables=tables, pages=pages, signature=signature,
)
# [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。
primary_bbox = _clip_observed_primary_table_bbox(
primary_bbox,
tables=tables,
pages=pages,
page_glyphs=page_glyphs,
signature=signature,
termination_rules=termination_rules,
exclusion_regions=exclusion_regions,
)
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
@@ -1371,6 +1464,96 @@ def _select_signature_primary_table_bbox(
return best_bbox
def _clip_observed_primary_table_bbox(
primary_bbox: list[float] | None,
*,
tables: list[dict[str, Any]],
pages: dict[str, Any],
page_glyphs: dict[str, Any],
signature: dict[str, Any] | None,
termination_rules: list[dict[str, Any]] | None = None,
exclusion_regions: list[dict[str, Any]] | None = None,
) -> list[float] | None:
"""对运行时主表框做业务行裁剪;无模板终止声明或定位失败时 fail-open。"""
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
return primary_bbox
page_no, page = _page_for_primary_table_bbox(
primary_bbox, tables=tables, pages=pages,
)
if not isinstance(page, dict):
return primary_bbox
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no) or []
header_y1 = None
for pattern in (signature or {}).get('table_patterns') or []:
if not isinstance(pattern, dict):
continue
header_bbox = pattern.get('header_bbox')
if isinstance(header_bbox, list) and len(header_bbox) == 4:
try:
header_y1 = float(header_bbox[3])
except (TypeError, ValueError):
header_y1 = None
break
clipped = clip_table_bbox_to_business_rows(
primary_bbox,
page=page,
glyphs=glyphs if isinstance(glyphs, list) else None,
header_y1=header_y1,
termination_rules=termination_rules,
exclusion_regions=exclusion_regions,
)
return clipped if isinstance(clipped, list) else primary_bbox
def _profile_termination_rules(profile: OrderCoordinateProfile) -> list[dict[str, Any]]:
"""汇总模板全部表区的终止规则,供主表几何裁剪复用抽取侧契约。"""
return [
rule.model_dump()
for table in profile.table_regions
for rule in table.termination_rules
]
def _profile_exclusion_regions(profile: OrderCoordinateProfile) -> list[dict[str, Any]]:
"""汇总模板全部表区的排除框。"""
return [
region.model_dump()
for table in profile.table_regions
for region in table.exclusion_regions
]
def _page_for_primary_table_bbox(
primary_bbox: list[float],
*,
tables: list[dict[str, Any]],
pages: dict[str, Any],
) -> tuple[Any, dict[str, Any] | None]:
"""按与主表框重叠最大的 layout 表定位页对象。"""
best: tuple[float, Any, dict[str, Any]] | None = None
for table in tables:
page_no = table.get('page_no') or 1
page = pages.get(str(page_no)) or pages.get(page_no)
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
if not isinstance(page, dict) or not isinstance(bbox, dict):
continue
try:
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
except (KeyError, TypeError, ValueError):
continue
if width <= 0 or height <= 0 or raw[2] <= raw[0] or raw[3] <= raw[1]:
continue
normalized = raw if max(raw) <= 1 else [raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height]
overlap = _bbox_overlap(primary_bbox, normalized)
if best is None or overlap > best[0]:
best = (overlap, page_no, page)
if best is None:
fallback = pages.get('1') or pages.get(1)
return 1, fallback if isinstance(fallback, dict) else None
return best[1], best[2]
def _bbox_overlap(left: list[float], right: list[float]) -> float:
"""计算两个归一化矩形的 IoU,供签名表区与实际表选择使用。"""
x0, y0 = max(left[0], right[0]), max(left[1], right[1])
@@ -4,6 +4,7 @@ services/shipping_notice/document_layout/order_profile_signature.py
用途:从模板定义与冻结样本坐标证据生成不可变版面签名(统计摘要,不含正文/URL)。
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
"""
from __future__ import annotations
@@ -17,6 +18,7 @@ from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import (
positioned_token_spans,
read_coordinate_region_text,
visual_glyph_rows,
)
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile, RelativeRegion
from app.services.shipping_notice.order_extraction_route_contract import PROFILE_SCORING_POLICY_ID
@@ -27,15 +29,162 @@ LAYOUT_SIGNATURE_ID = 'order-profile-layout-signature'
MATCHER_POLICY_ID = PROFILE_SCORING_POLICY_ID
# 动态业务值不得进入表头签名;仅保留多样本稳定出现的固定文字。
# 最后一条只匹配「标签 + 显式分隔符/空白数字」的粘连值(如 Qty: 24、Qty 24),
# 不得误杀 Qty.Req / Qty Req 这类列名(点号或纯字母后缀不是业务值)。
_DYNAMIC_TOKEN_PATTERNS = (
re.compile(r'^\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}$'),
re.compile(r'^\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4}$'),
re.compile(r'^[A-Z]{0,4}\d{5,}[A-Z0-9\-]*$', re.IGNORECASE),
re.compile(r'^\d+([.,]\d+)?$'),
re.compile(r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)\s*[:#-]?\s*\S+', re.IGNORECASE),
re.compile(
r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)'
r'(?:\s*[:#=\-]\s*\S+|\s+\d)',
re.IGNORECASE,
),
)
def clip_table_bbox_to_business_rows(
bbox: list[float] | None,
*,
page: dict[str, Any],
glyphs: list[dict[str, Any]] | None,
header_y1: float | None = None,
termination_rules: list[dict[str, Any]] | None = None,
exclusion_regions: list[dict[str, Any]] | None = None,
) -> list[float] | None:
"""
将主表 bbox 底边裁到业务明细结束处,去掉 MinerU 粘连的表外备注区。
核心逻辑:只使用模板声明的 termination_rules 锚点文案与 exclusion_regions;
在表框内、表头下方命中最早终止点则裁 y1。无模板声明或未命中时 fail-open。
Args:
bbox: 归一化 [x0, y0, x1, y1]。
page: 含 width/height 的页对象。
glyphs: 该页 page_glyphs。
header_y1: 可选表头下沿(归一化)。
termination_rules: 表区 termination_rules 的 dict 列表(含 anchor.text/match_mode/region)。
exclusion_regions: 表区 exclusion_regions 的相对框 dict 列表。
Returns:
裁剪后的 bbox,或无法裁剪时的原 bbox。
"""
if not isinstance(bbox, list) or len(bbox) != 4:
return bbox
try:
x0, y0, x1, y1 = (float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3]))
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
except (TypeError, ValueError):
return bbox
if width <= 0 or height <= 0 or x1 <= x0 or y1 <= y0:
return bbox
floor = float(header_y1) if header_y1 is not None else (y0 + max(0.02, (y1 - y0) * 0.08))
floor = min(max(floor, y0), y1)
stop_ys: list[float] = []
for region in exclusion_regions or []:
if not isinstance(region, dict):
continue
try:
ey0 = float(region['y0'])
ex0, ex1 = float(region['x0']), float(region['x1'])
except (KeyError, TypeError, ValueError):
continue
if ey0 <= floor or ey0 >= y1:
continue
if ex1 < x0 or ex0 > x1:
continue
stop_ys.append(ey0)
rules = [item for item in (termination_rules or []) if isinstance(item, dict)]
if rules and isinstance(glyphs, list) and glyphs:
for row in visual_glyph_rows(glyphs):
row_meta = _normalized_glyph_row(row, width=width, height=height)
if row_meta is None:
continue
row_y, row_x0, row_x1, text = row_meta
if row_y <= floor or row_y >= y1:
continue
if row_x1 < x0 or row_x0 > x1:
continue
if _row_matches_termination_rules(
text=text, row_y=row_y, table_bbox=[x0, y0, x1, y1], rules=rules,
):
stop_ys.append(row_y)
if not stop_ys:
return bbox
clipped_y1 = max(floor + 1e-3, min(stop_ys) - 0.008)
if clipped_y1 >= y1 - 1e-3:
return bbox
return [x0, y0, x1, round(clipped_y1, 6)]
def _normalized_glyph_row(
row: list[dict[str, Any]], *, width: float, height: float,
) -> tuple[float, float, float, str] | None:
"""将视觉行折叠为归一化 y/x 范围与拼接文本。"""
xs: list[float] = []
ys: list[float] = []
texts: list[str] = []
for glyph in row:
box = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
if not box:
continue
try:
gx0, gy0, gx1, gy1 = float(box['x0']), float(box['y0']), float(box['x1']), float(box['y1'])
except (KeyError, TypeError, ValueError):
continue
xs.extend((gx0 / width, gx1 / width))
ys.append(((gy0 + gy1) / 2) / height)
texts.append(str(glyph.get('text') or ''))
if not xs or not ys:
return None
return sum(ys) / len(ys), min(xs), max(xs), ''.join(texts)
def _row_matches_termination_rules(
*,
text: str,
row_y: float,
table_bbox: list[float],
rules: list[dict[str, Any]],
) -> bool:
"""按模板 termination_rules 判断视觉行是否为业务表结束锚点。"""
compact = ' '.join(text.split())
if not compact:
return False
compact_key = compact.casefold().replace(' ', '')
x0, y0, x1, y1 = table_bbox
for rule in rules:
anchor = rule.get('anchor') if isinstance(rule.get('anchor'), dict) else None
if not isinstance(anchor, dict):
continue
expected = str(anchor.get('text') or '').strip()
if not expected:
continue
region = anchor.get('region')
if isinstance(region, dict):
try:
# region 相对表区;换算到页面归一化 y 再约束命中带。
ry0 = y0 + (y1 - y0) * float(region['y0'])
ry1 = y0 + (y1 - y0) * float(region['y1'])
except (KeyError, TypeError, ValueError):
continue
if not ry0 <= row_y <= ry1:
continue
mode = str(anchor.get('match_mode') or 'contains')
expected_key = expected.casefold().replace(' ', '')
if mode == 'exact':
if compact == expected or compact_key == expected_key:
return True
elif expected in compact or (expected_key and expected_key in compact_key):
return True
return False
def build_layout_signature(
*,
definition: dict[str, Any],
@@ -206,7 +355,10 @@ def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) ->
for layout in sample_layouts:
observed = _observe_sample_table(
layout, target_region=region, header_region=header_region,
layout,
target_region=region,
header_region=header_region,
table_region=table,
)
if observed is None:
continue
@@ -280,6 +432,7 @@ def _build_field_relation_graph(
def _observe_sample_table(
layout: dict[str, Any], *, target_region: RelativeRegion,
header_region: RelativeRegion | None,
table_region: Any | None = None,
) -> dict[str, Any] | None:
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
@@ -318,8 +471,25 @@ def _observe_sample_table(
header_tokens, centers, widths = _header_observation(
header_glyphs, page=page, bbox=bbox,
)
header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None
termination_rules = [
rule.model_dump() if hasattr(rule, 'model_dump') else rule
for rule in (getattr(table_region, 'termination_rules', None) or [])
]
exclusion_regions = [
region.model_dump() if hasattr(region, 'model_dump') else region
for region in (getattr(table_region, 'exclusion_regions', None) or [])
]
clipped = clip_table_bbox_to_business_rows(
bbox,
page=page,
glyphs=glyphs if isinstance(glyphs, list) else None,
header_y1=header_y1,
termination_rules=termination_rules or None,
exclusion_regions=exclusion_regions or None,
)
return {
'bbox': bbox,
'bbox': clipped if isinstance(clipped, list) else bbox,
'header_tokens': header_tokens,
'column_centers': centers,
'column_width_ratios': widths,
@@ -528,7 +698,12 @@ def _split_header_tokens(text: str) -> list[str]:
def _is_dynamic_token(token: str) -> bool:
"""判断 token 是否像 PO/日期/数量等动态值。"""
"""
判断 token 是否像 PO/日期/数量等动态值。
核心逻辑:日期、料号型编码、纯数字,以及「Qty:/PO: + 值」粘连串视为动态;
Qty.Req 等列名不含显式分隔后的值或空白数字,不得判动态。
"""
compact = token.strip()
if not compact or len(compact) <= 1:
return True
@@ -3,6 +3,8 @@
依赖:受控 HTML 网格解析、冻结订单 Schema 表头契约、PO/Reservation 标准化。
逻辑:订单字段表头只复用 Run/当前发布 Schema 的显式别名;邮件专属的分配事实
仍使用受控固定列。表格歧义或缺 PO 保留原因,不将正文直接转成订单。
非法非 PO 字段跳过本列并记 issue,避免可选列拖垮 Reservation/库存源线索。
多表按文档顺序叠行:靠前为新,同行身份键先到为准;旧表仅补全新表未覆盖的行。
"""
from __future__ import annotations
@@ -31,10 +33,46 @@ def _schema_configs(schema_definition: dict[str, Any]) -> dict[str, dict[str, An
}
def _supplement_row_identity(row: dict[str, Any]) -> tuple[str, str, str] | None:
"""返回补充行跨表去重键;无次级身份时返回 None(不可安全覆盖,原样保留)。
核心逻辑:PO 必选;次级键按 reservation_id → allocation_id → part_number →
customer_part_number 择一,避免把同 PO 不同明细误合成一行。
Args:
row: 已规范化的补充行(含 PO 与可选明细身份字段)。
Returns:
``(po, field_code, value)``;缺 PO 或无可覆盖次级键时为 None。
"""
po_number = normalize_po_number(row.get('customer_po_number') or row.get('po_number'))
if not po_number:
return None
po_key = po_number.upper()
for field_code in ('reservation_id', 'allocation_id', 'part_number', 'customer_part_number'):
value = str(row.get(field_code) or '').strip().upper()
if value:
return (po_key, field_code, value)
return None
def _normalize_schema_row(
values: dict[str, str], *, schema_definition: dict[str, Any], issues: list[str],
) -> dict[str, Any] | None:
"""按冻结 Schema 规范化并校验 EML 单元格;非法字段不参与任何补充裁决。"""
"""按冻结 Schema 规范化并校验 EML 单元格;非法非 PO 字段跳过,不拖垮整行。
核心逻辑:PO 仍是行身份门槛;其余字段解析/校验失败只记
``email_supplement_field_invalid`` 并省略该字段,避免可选列(如 PO Date)
非法时把 Reservation / 库存源线索一并丢掉。
Args:
values: 表头映射后的 field_code → 原始单元格文本。
schema_definition: Run 冻结 Schema。
issues: 可追加的问题码列表(调用方持有,本函数原地写入)。
Returns:
规范化后的补充行;缺有效 PO 时返回 None。
"""
configs = _schema_configs(schema_definition)
normalized: dict[str, Any] = {}
for field_code, raw_value in values.items():
@@ -42,14 +80,15 @@ def _normalize_schema_row(
if config is None:
normalized[field_code] = raw_value
continue
# [STEP] 非 PO 字段失败只跳过本列;PO 失败则稍后由 po 门槛统一拒行。
try:
value = normalize_order_field_value(raw_value, config)
except Exception:
issues.append('email_supplement_field_invalid')
return None
continue
if value is None or not validate_order_field_value(value, config):
issues.append('email_supplement_field_invalid')
return None
continue
normalized[field_code] = value
po_code = 'customer_po_number' if 'customer_po_number' in normalized else 'po_number'
po_number = normalize_po_number(normalized.get(po_code))
@@ -128,10 +167,23 @@ def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]:
def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str, schema_definition: dict[str, Any]) -> dict[str, Any]:
"""输出正文补充行和 DOM 单元格证据;订单字段别名必须来自冻结 Schema。"""
"""输出正文补充行和 DOM 单元格证据;订单字段别名必须来自冻结 Schema。
核心逻辑:按 HTML 出现顺序扫描全部可映射分配表;同行身份键以先到(更新)为准,
旧表仅补全新表未覆盖的行,避免局部修订丢行或与旧单价假冲突。
Args:
html_tables: Intake 清洗后的顶层 HTML table 片段列表(文档顺序)。
content_hash: 正文 Document 内容哈希,用于稳定 cell_id。
schema_definition: Run 冻结 Schema。
Returns:
email-supplement.v1 结果(rows / issues / version)。
"""
result = empty_email_supplement_result()
rows: list[dict[str, Any]] = []
issues: list[str] = []
seen_identities: set[tuple[str, str, str]] = set()
for table_index, html in enumerate(html_tables):
try:
grid = parse_html_grid(str(html or ''), table_id=f'email-supplement:{content_hash}:{table_index}')
@@ -161,10 +213,18 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str,
)
if normalized is None:
continue
rows.append({
row = {
**normalized, 'evidence': evidence, 'table_index': table_index,
'row_index': row_index,
})
}
# [STEP] 有身份键则先到为准;无次级键无法跨表覆盖,整行保留。
identity = _supplement_row_identity(row)
if identity is not None:
if identity in seen_identities:
issues.append('email_supplement_older_row_superseded')
continue
seen_identities.add(identity)
rows.append(row)
result.update({'rows': rows, 'issues': sorted(set(issues))})
return result
@@ -3306,6 +3306,8 @@ def list_order_extraction_run_summaries(
核心逻辑:列表端只需定位最新 Run 与展示摘要,故用标量列投影直接绕过 ORM 实体;
`input_snapshot_json` / `request_snapshot_json` 只能由单 Run 详情路径按需读取。
会话短列表(非分页)优先返回带 client_submission_id 的 submission primary,
避免一次多 Intake 拆出的 sibling 因 created_at 更新被误选为恢复锚点。
Args:
user_id: 当前用户主键。
@@ -3341,8 +3343,19 @@ def list_order_extraction_run_summaries(
ShippingOrderProcessingRun.last_activity_at,
ShippingOrderProcessingRun.created_at,
ShippingOrderProcessingRun.updated_at,
ShippingOrderProcessingRun.client_submission_id,
)
statement = select(*columns).where(*filters).order_by(ShippingOrderProcessingRun.created_at.desc())
# [STEP] 会话恢复短列表:primary(有 client_submission_id)排前,再按创建时间倒序。
# 分页任务中心仍按纯时间序,避免 sibling 被隐藏。
if conversation_id and page is None and page_size is None:
statement = select(*columns).where(*filters).order_by(
ShippingOrderProcessingRun.client_submission_id.isnot(None).desc(),
ShippingOrderProcessingRun.created_at.desc(),
)
else:
statement = select(*columns).where(*filters).order_by(
ShippingOrderProcessingRun.created_at.desc(),
)
if page is None and page_size is None:
return list(db.session.execute(
statement.limit(min(max(int(limit or 50), 1), 100)),
@@ -3613,6 +3626,8 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str,
if isinstance(run.input_snapshot_json, dict)
else None
),
# 仅 submission primary 有值;sibling Run 为空。聊天恢复必须锚定 primary,禁止用 sibling 再建卡。
'client_submission_id': str(run.client_submission_id or '').strip() or None,
'schema_version_id': run.schema_version_id,
'schema_version': schema_snapshot.get('version'),
'schema_checksum': schema_snapshot.get('checksum'),
@@ -3662,6 +3677,9 @@ def serialize_order_extraction_run_list_item(run: Any) -> dict[str, Any]:
'conversation_id': row['conversation_id'],
'status': str(row['status'] or 'queued'),
'phase': str(row['phase'] or row['status'] or 'queued'),
'client_submission_id': (
str(row.get('client_submission_id') or '').strip() or None
),
'summary': {
'total_documents': int(progress_summary.get('total_documents') or 0),
'pending_documents': int(progress_summary.get('pending_documents') or 0),
@@ -565,11 +565,23 @@ def _physical_table_targets_profile_region(
reference_page_frame: dict[str, Any] | None = None,
coordinate_transform: dict[str, Any] | None = None,
) -> bool:
"""判断物理表是否属于当前页模板的明细区域;未知几何保守保留为候选。
"""
判断物理表是否属于当前页模板的明细区域;未知几何保守保留为候选。
同页的页脚汇总、签章等 MinerU 物理表不属于订单明细模板,不能因其无法重建
而阻断已成功的目标表。虚拟页、缺失 bbox 或页尺寸异常时维持既有整页坐标回退,
避免表检测遗漏被错误跳过。
核心逻辑:同页页脚/签章等非目标 MinerU 表不得因重建失败阻断已成功目标表。
当前页已配置专属表区但全部没有 ``line_layouts``(仅表头壳)时明确跳过,
避免空重建产出 ``PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION`` 污染整单。
虚拟页、缺失 bbox 或页尺寸异常时仍 fail-open,避免表检测遗漏被错误跳过。
Args:
raw_table: 物理表身份、页码与 bbox。
table_regions: 冻结 Profile 的表区列表(含 page_scope / line_layouts)。
page_size: 当前页宽高;缺失时保守保留候选。
reference_page_frame: 可选参考页框,用于相对坐标投影。
coordinate_transform: matcher 已确认的平移;可为 None。
Returns:
True 表示应进入坐标行重建;False 表示跳过该物理表。
"""
page_no = int(raw_table.get('page_no') or 1)
if str(raw_table.get('table_id') or '') == f'page-{page_no}':
@@ -588,15 +600,23 @@ def _physical_table_targets_profile_region(
active_region_ids = set(select_runtime_region_ids(
table_regions=table_regions, page_no=page_no,
))
active_regions = [
# [STEP 1] 当前页被选中的表区(不论是否含明细子行)
page_regions = [
region for region in table_regions
if isinstance(region, dict)
and str(region.get('region_id') or '') in active_region_ids
and isinstance(region.get('region'), dict)
and region.get('line_layouts')
]
if not page_regions:
# 本页无模板表区配置:保守保留,供虚拟页/漏检回退。
return True
# [STEP 2] 仅含 line_layouts 的明细区才是重建目标;纯表头壳直接跳过。
active_regions = [
region for region in page_regions
if region.get('line_layouts')
]
if not active_regions:
return True
return False
for region in active_regions:
projected = apply_coordinate_transform_to_region(
region['region'], coordinate_transform=coordinate_transform,
@@ -48,8 +48,18 @@ def compute_effective_reservation_id(
def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
"""按冻结字段类型解析候选值,同时保留原始文本大小写。
`uppercase_trim` / `lowercase_trim` 仅可用于比较、索引和规则匹配,不能改写
PDF/邮件证据对应的业务展示值;否则料号、客户名称、地址和币种会偏离原文件。
核心逻辑:按 value_type 做确定性解析;文本类 normalizer 不得改写展示值。
日期仅接受显式布局,禁止把自由文本猜成日期。
Args:
value: 原始候选值(PDF/邮件单元格或 Observation)。
config: 冻结 Schema 字段配置(须含 value_type;可选 normalizer_key)。
Returns:
规范化后的业务值;空输入返回 None。
Raises:
ValidationError: 类型无法按显式规则解析时失败。
"""
if value in (None, ''):
return None
@@ -75,6 +85,9 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
# ISO date, so downstream validators receive one type.
'%m/%d/%y', '%m-%d-%y', '%m.%d.%y',
'%d-%b-%Y', '%d-%B-%Y',
# [PARAM_TUNING] 2026-09-08: EML 分配表 PO Date 常见 ``12-Jun-26``;
# 仅有四位年 ``%d-%b-%Y`` 时整行补充被 fail-closed 丢弃,库存源线索/预约号一并落空。
'%d-%b-%y', '%d-%B-%y',
):
try:
return datetime.strptime(text, pattern).date()
@@ -3978,6 +3978,10 @@ def project_conversation_processing_summary(
ProcessExecution / ShippingProcessGate 必须按 OT.id(非 candidate_id)批量加载;
否则 Gate 查空后叶子会退化,批次中心同时丢失五阶段入口与门禁主按钮。
建单前五阶段权威与 order-review-queue 对齐:开放 Case 只认 Case.candidate_id
绑定的可复核 Candidate;不得用「Case 存在」或「文档上另有未绑定 Candidate」
抬升 candidate_count / waiting_review→order_review。
"""
del agent_id
normalized = str(conversation_id or '').strip()
@@ -4039,10 +4043,16 @@ def project_conversation_processing_summary(
ShippingOrderCandidate.primary_document_id,
ShippingOrderCandidate.order_extraction_run_id,
ShippingOrderCandidate.po_number,
ShippingOrderCandidate.candidate_status,
ShippingOrderCandidate.is_current_version,
)).filter(
ShippingOrderCandidate.intake_id.in_(intake_ids) if intake_ids else False,
ShippingOrderCandidate.is_current_version.is_(True),
).all()
candidate_by_id = {
int(candidate.id): candidate
for candidate in candidates
}
candidate_by_document_id = {
int(candidate.primary_document_id): candidate
for candidate in candidates
@@ -4158,6 +4168,7 @@ def project_conversation_processing_summary(
ShippingOrderReviewCase.status,
ShippingOrderReviewCase.current_draft_id,
ShippingOrderReviewCase.confirmed_task_id,
ShippingOrderReviewCase.candidate_id,
)).filter(
ShippingOrderReviewStream.document_id.in_(document_ids) if document_ids else False,
).all()
@@ -4234,11 +4245,33 @@ def project_conversation_processing_summary(
user_status, stage, reason = _status(document, task, case, current_gate)
group = 'processing' if user_status == 'running' else user_status
task_no = str(task.task_no).strip() if task is not None else None
candidate = candidate_by_document_id.get(int(document.id))
candidate_po = str(getattr(candidate, 'po_number', None) or '').strip() if candidate is not None else ''
# 摘要只信任 Candidate 的规范化 PO 列;结构化抽取 JSON 仅在详情接口按需读取。
# 候选存在不等于关键字段已完成解析;没有 PO 时仍停留在接收解析阶段。
if not candidate_po and stage in {'waiting_review', 'order_review'}:
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
# [AUTHORITY] 与 order-review-queue / EML 详情叶子一致:
# Case 已物化时只认 Case.candidate_id 绑定的可复核 Candidate;
# 文档上另有未绑定 Candidate(即便带 PO)不能抬升到订单复核。
# Case 尚未物化时,才回退到文档当前 Candidate,保留建单前安全入口。
document_candidate = candidate_by_document_id.get(int(document.id))
case_candidate = (
candidate_by_id.get(int(case.candidate_id))
if case is not None and getattr(case, 'candidate_id', None) is not None
else None
)
candidate = case_candidate if case is not None else document_candidate
has_current_candidate = bool(
is_current_reviewable_candidate(candidate)
and int(getattr(candidate, 'primary_document_id', 0) or 0) == int(document.id)
)
candidate_po = (
str(getattr(candidate, 'po_number', None) or '').strip()
if has_current_candidate else ''
)
# 摘要只信任可复核 Candidate 的规范化 PO 列;结构化抽取 JSON 仅在详情接口按需读取。
# 空/未绑定 Candidate 的开放 Case 必须降回接收解析,与工作台队列同判词。
if case is not None and case.confirmed_task_id is None and not has_current_candidate:
if stage in {'waiting_review', 'order_review'}:
stage = 'candidate_creating'
elif not candidate_po and stage in {'waiting_review', 'order_review'}:
stage = 'candidate_creating'
case_status = str(getattr(case, 'status', None) or '').strip().lower()
terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}
@@ -4263,8 +4296,8 @@ def project_conversation_processing_summary(
}
intake_parse_authorized = True
elif case is not None and not terminal_case:
if candidate is not None:
# 当前 Candidate 已生成后,Case 进入订单复核;仅用已批量读取的
if has_current_candidate:
# Case 已绑定可复核 Candidate 后进入订单复核;仅用已批量读取的
# current_draft_id 恢复权威业务动作,避免摘要路径逐文件加载 Case 详情。
available_actions = ['edit_draft' if case.current_draft_id else 'create_draft']
primary_action = project_case_primary_action(
@@ -4280,7 +4313,8 @@ def project_conversation_processing_summary(
primary_action = _intake_parse_case_primary_action(
reparse_authorized=True,
)
elif task is not None or candidate_by_document_id.get(int(document.id)) is not None:
intake_parse_authorized = True
elif task is not None or has_current_candidate:
# Candidate 已形成但 Case 尚未物化时,仍保留进入订单生命周期的安全入口;
# 详情页会显示当前事实并在服务端决定是否可继续编辑。
available_actions = ['open_order_review']
@@ -4330,7 +4364,9 @@ def project_conversation_processing_summary(
'attachment_key': str(document.attachment_key or '').strip() or None,
'document_count': 1,
'parsed_document_count': int(str(document.parse_status or '').strip().lower() == 'parsed'),
'candidate_count': 1 if candidate is not None or task is not None or case is not None else 0,
# 禁止用 Case 存在抬升 candidate_count;否则 has_candidate_context 会
# 错误开放订单复核入口,与工作台队列判词分叉。
'candidate_count': 1 if has_current_candidate or task is not None else 0,
'po_number': candidate_po or None,
},
'current_gate': current_gate,
@@ -432,6 +432,194 @@ def test_email_supplement_requires_frozen_schema_alias_for_order_headers():
assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']}
def test_email_supplement_inventec_po_date_two_digit_year_keeps_source_location():
"""Inventec 分配表 PO Date=12-Jun-26 时仍须保留 Source Location / 预约号。
回归:order_date 别名命中 PO date 后,两位年英文月曾整行 fail-closed,
导致 inventory_source_hint 与 External reservation ID 同时落空。
"""
schema = {
'fields': [
{
'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header',
'aliases': ['PO number', 'PO Number'],
},
{
'field_id': 'date', 'field_code': 'order_date', 'scope': 'header',
'value_type': 'date', 'aliases': ['PO Date', 'Order Date'],
},
{
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line',
'aliases': ['MPN'],
},
{
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
'aliases': ['External reservation ID'],
},
{
'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line',
'aliases': ['Source Type', 'Source Location'],
},
],
}
html = '''<table><tr>
<th>External reservation ID</th><th>Source type</th><th>Source Location</th>
<th>MPN</th><th>PO date</th><th>PO number</th>
</tr><tr>
<td>3000099143</td><td>DBS SIN</td><td>VMI-SIN</td>
<td>D4-AR1200163A1</td><td>12-Jun-26</td><td>4518814838</td>
</tr></table>'''
supplement = parse_email_allocation_tables(
content_hash='i' * 64, html_tables=[html], schema_definition=schema,
)
# 关键断言:补充行必须产出;库存源按别名优先级取 Source Type;预约号与 PO 日期均保留。
assert supplement['rows'], supplement
row = supplement['rows'][0]
assert row['customer_po_number'] == '4518814838'
assert row['reservation_id'] == '3000099143'
assert row['inventory_source_hint'] == 'DBS SIN'
assert row['order_date'].isoformat() == '2026-06-12'
assert 'email_supplement_field_invalid' not in supplement['issues']
def test_email_supplement_skips_invalid_optional_field_without_dropping_row():
"""可选列非法时只跳过该列,不得丢弃同行走的库存源线索。"""
schema = {
'fields': [
{
'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header',
'aliases': ['PO Number'],
},
{
'field_id': 'date', 'field_code': 'order_date', 'scope': 'header',
'value_type': 'date', 'aliases': ['PO Date'],
},
{
'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line',
'aliases': ['Source Location'],
},
],
}
html = '''<table><tr><th>PO Number</th><th>PO Date</th><th>Source Location</th></tr>
<tr><td>4518814838</td><td>not-a-date</td><td>VMI-SIN</td></tr></table>'''
supplement = parse_email_allocation_tables(
content_hash='j' * 64, html_tables=[html], schema_definition=schema,
)
# 关键断言:日期列记 invalid,但行仍保留 PO 与库存源线索。
assert supplement['issues'] == ['email_supplement_field_invalid']
assert len(supplement['rows']) == 1
assert supplement['rows'][0]['customer_po_number'] == '4518814838'
assert supplement['rows'][0]['inventory_source_hint'] == 'VMI-SIN'
assert 'order_date' not in supplement['rows'][0]
def test_email_supplement_uses_only_first_valid_allocation_table():
"""同行身份键以靠前新表为准,旧表同键单价不得制造冲突。
回归:Inventec 修订邮件顶部表 U/P=563.79,引用区旧表 U/P=450.8300;
同 reservation 只保留新价。
"""
schema = {
'fields': [
{
'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header',
'aliases': ['PO number', 'PO Number'],
},
{
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line',
'aliases': ['MPN'],
},
{
'field_id': 'price', 'field_code': 'unit_price', 'scope': 'line',
'value_type': 'decimal', 'aliases': ['U/P', 'Unit Price'],
},
{
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
'aliases': ['External reservation ID'],
},
],
}
latest = '''<table><tr><th>External reservation ID</th><th>MPN</th><th>PO number</th><th>U/P</th></tr>
<tr><td>3000099143</td><td>D4-AR1200163A1</td><td>4518814838</td><td>563.79</td></tr></table>'''
quoted = '''<table><tr><th>External reservation ID</th><th>MPN</th><th>PO number</th><th>U/P</th></tr>
<tr><td>3000099143</td><td>D4-AR1200163A1</td><td>4518814838</td><td>450.8300</td></tr></table>'''
supplement = parse_email_allocation_tables(
content_hash='k' * 64,
html_tables=[latest, quoted, '<table><tr><td></td></tr></table>'],
schema_definition=schema,
)
# 关键断言:同 reservation 只留新表行;旧表被 supersede。
assert len(supplement['rows']) == 1
assert supplement['rows'][0]['table_index'] == 0
assert str(supplement['rows'][0]['unit_price']) == '563.79'
assert 'email_supplement_older_row_superseded' in supplement['issues']
order = {
'_hxops_intake_id': 1,
'header_fields': [{'field_id': 'po', 'observations': [{'value': '4518814838'}]}],
'lines': [{'fields': [
{'field_id': 'part', 'observations': [{'value': 'D4-AR1200163A1'}]},
{'field_id': 'price', 'observations': [{'value': '563.79'}]},
]}],
'conflicts': [],
}
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: {**supplement, 'document_id': 44}},
schema_definition=schema,
)[0]
assert not any(item.get('field') == 'unit_price' for item in merged.get('conflicts') or [])
assert _value(merged['lines'][0]['fields'], 'price') == '563.79'
def test_email_supplement_partial_revision_keeps_unrevised_old_rows():
"""新表只修正一行时,旧表中未覆盖的其它行仍须保留。"""
schema = {
'fields': [
{
'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header',
'aliases': ['PO Number'],
},
{
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line',
'aliases': ['MPN'],
},
{
'field_id': 'price', 'field_code': 'unit_price', 'scope': 'line',
'value_type': 'decimal', 'aliases': ['U/P'],
},
{
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
'aliases': ['External reservation ID'],
},
],
}
revised = '''<table><tr><th>External reservation ID</th><th>MPN</th><th>PO Number</th><th>U/P</th></tr>
<tr><td>3000099143</td><td>D4-AR1200163A1</td><td>4518814838</td><td>563.79</td></tr></table>'''
older = '''<table><tr><th>External reservation ID</th><th>MPN</th><th>PO Number</th><th>U/P</th></tr>
<tr><td>3000099143</td><td>D4-AR1200163A1</td><td>4518814838</td><td>450.8300</td></tr>
<tr><td>3000099999</td><td>D4-OTHER00001</td><td>4518814838</td><td>10.00</td></tr></table>'''
supplement = parse_email_allocation_tables(
content_hash='l' * 64, html_tables=[revised, older], schema_definition=schema,
)
# 关键断言:修订行用新价;旧表另一 reservation 行仍在。
assert len(supplement['rows']) == 2
by_reservation = {str(row['reservation_id']): row for row in supplement['rows']}
assert str(by_reservation['3000099143']['unit_price']) == '563.79'
assert by_reservation['3000099143']['table_index'] == 0
assert str(by_reservation['3000099999']['unit_price']) == '10.00'
assert by_reservation['3000099999']['table_index'] == 1
assert 'email_supplement_older_row_superseded' in supplement['issues']
def test_email_supplement_pn_matching_customer_part_number_does_not_false_conflict():
"""邮件 PN 列的值为客户件号(MPN)时不得与 PDF 内部件号产生误判 part_number 冲突。
@@ -13,6 +13,7 @@ from pydantic import ValidationError
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
coordinate_profile_character_candidates,
_is_structured_part_identifier,
_text_in_region,
_text_in_horizontal_region,
reconstruction_exclusion_regions,
@@ -1334,12 +1335,13 @@ def test_two_subrow_layout_rescans_numeric_description_wrap_before_part_number(r
def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
"""额外视觉行中出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。"""
"""描述折行后出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('CUSTOMER-A', 55)],
[('PART-A', 55)],
[('00020', 10), ('CUSTOMER-B', 55)],
[('WRAPPED DESC', 55)],
[('ALT-1', 55)],
[('ALT-2', 55)],
),
@@ -1356,6 +1358,56 @@ def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
assert 'coordinate_profile_field_band_ambiguous:part_number' in rows[1].issues
@pytest.mark.parametrize('raw,expected', [
('D4-AR1200163A', True),
('D4-AR1200163A1', True),
('PART-A', True),
('A EXW AWS HUB-DB', False),
('48U AR1.2', False),
('BUSBAR', False),
('', False),
])
def test_is_structured_part_identifier_rejects_whitespace(raw, expected):
"""结构化料号纠偏证据不得含空格,避免贸易条款串被当成料号。"""
assert _is_structured_part_identifier(raw) is expected
@pytest.mark.parametrize('row_reconstruction_mode', [
'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns',
])
def test_two_subrow_layout_keeps_structured_part_number_against_later_incoterm_band(
row_reconstruction_mode,
):
"""续行已读到结构化内部料号时,不得被后续 Incoterms/条款视觉行无条件覆盖。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 10), ('40', 80), ('6Y17B2493101', 130)],
[('D4-AR1200163A', 130)],
[('A EXW AWS HUB-DB', 130)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
line_layouts=[
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
]},
{'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
]},
],
row_reconstruction_mode=row_reconstruction_mode,
schema_field_metadata=[
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
],
)
assert rows[0].fields['part_number'] == 'D4-AR1200163A'
def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary():
"""脱敏回放 4518838152:配置区内删除标记废弃 00010,合计后的记录不允许泄漏。"""
rows = reconstruct_coordinate_profile_rows(
@@ -60,6 +60,31 @@ def test_physical_table_outside_profile_region_is_not_a_parse_target():
) is False
def test_header_only_exact_page_region_is_not_a_parse_target():
"""专属页只有无 line_layouts 的壳表区时,不得进入重建并把 NO_VALID 污染到已成功页。"""
regions = [
{
'region_id': 'main_lines_page_1', 'page_scope': 'exact_page', 'page_no': 1,
'region': {'x0': .01, 'y0': .43, 'x1': .97, 'y1': .48},
'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'field_regions': []}],
},
{
'region_id': 'main_lines_page_2', 'page_scope': 'exact_page', 'page_no': 2,
'region': {'x0': .01, 'y0': .12, 'x1': .97, 'y1': .20},
'line_layouts': [],
},
]
page = {'width': 792, 'height': 612}
assert _physical_table_targets_profile_region(
raw_table={
'table_id': 'mineru-page2-header', 'page_no': 2,
'bbox': {'x0': 5, 'y0': 80, 'x1': 760, 'y1': 120},
},
table_regions=regions, page_size=page,
) is False
def test_empty_virtual_page_does_not_block_a_successful_target_table():
"""无物理表的续页仅用于补漏;没有行时不得覆盖已成功的目标表。"""
assert _virtual_page_without_rows_is_nonblocking(
@@ -58,6 +58,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
materialize_order_extraction_run_inputs,
serialize_order_extraction_message_state,
serialize_order_extraction_run,
submit_order_extraction,
synchronize_order_extraction_expansion_snapshot,
transition_order_extraction_run,
)
@@ -1983,6 +1984,56 @@ def test_run_list_does_not_select_large_input_snapshots(app, client):
assert all('input_snapshot_json' not in statement for statement in statements)
def test_conversation_run_list_prefers_submission_primary_over_newer_sibling(app, client):
"""会话短列表须把带 client_submission_id 的 primary 排在更新的 sibling 之前,避免恢复误建第二张卡。"""
with app.app_context():
owner, agent, session, first_intake, _document = _seed_run_input(suffix='LIST-PRIMARY-A')
_, _, _, second_intake, _ = _seed_run_input(
suffix='LIST-PRIMARY-B',
agent_code='shipping_notice_list_primary_b',
)
second_intake.user_id = owner.id
second_intake.conversation_id = session.session_id
db.session.commit()
payload = submit_order_extraction(
user=owner,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[first_intake.intake_no, second_intake.intake_no],
submission_id='SUB-LIST-PRIMARY-ORDER',
)
db.session.commit()
primary_run_no = str(payload['run_no'])
runs = (
ShippingOrderProcessingRun.query
.filter_by(conversation_id=session.session_id)
.order_by(ShippingOrderProcessingRun.id.asc())
.all()
)
assert len(runs) == 2
primary = next(row for row in runs if row.run_no == primary_run_no)
sibling = next(row for row in runs if row.run_no != primary_run_no)
assert primary.client_submission_id == 'SUB-LIST-PRIMARY-ORDER'
assert not sibling.client_submission_id
sibling_run_no = str(sibling.run_no)
# 模拟 sibling 更晚创建/更新:列表若按纯时间会把它排到第一。
sibling.created_at = (primary.created_at or datetime.utcnow()) + timedelta(minutes=30)
db.session.commit()
token = issue_local_access_token(owner)
conversation_id = session.session_id
response = client.get(
f'/api/workspace/shipping-notice/order-extraction-runs?conversation_id={conversation_id}&limit=20',
headers={'Authorization': f'Bearer {token}'},
)
assert response.status_code == 200
items = response.get_json()['data']['items']
assert items[0]['run_no'] == primary_run_no
assert items[0]['client_submission_id'] == 'SUB-LIST-PRIMARY-ORDER'
assert any(item['run_no'] == sibling_run_no and not item.get('client_submission_id') for item in items)
def test_run_api_requires_upload_batch_id(app, client):
"""发送端缺少服务端上传批次时必须拒绝,不能回退为全会话 Intake 选择。"""
with app.app_context():
@@ -2,12 +2,15 @@
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_extract_matching_signature,
_observe_layout_features,
_resolve_coordinate_transform,
match_frozen_coordinate_profiles,
)
from app.services.shipping_notice.document_layout.order_profile_signature import (
MATCHER_POLICY_ID,
build_layout_signature,
clip_table_bbox_to_business_rows,
)
@@ -47,8 +50,13 @@ def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None
}}
def _layout(text: str = 'PLANT NAME: FACTORY A', *, bbox: dict | None = None) -> dict:
"""构造页眉锨点与表内表头分离的最小坐标证据。"""
def _layout(
text: str = 'PLANT NAME: FACTORY A',
*,
bbox: dict | None = None,
header_text: str = 'ITEM NO QTY',
) -> dict:
"""构造页眉锚点与表内表头分离的最小坐标证据。"""
table = {
'table_id': 'table-1',
'page_no': 1,
@@ -58,7 +66,6 @@ def _layout(text: str = 'PLANT NAME: FACTORY A', *, bbox: dict | None = None) ->
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate(text)
]
header_text = 'ITEM NO QTY'
header_glyphs = [
{
'text': char,
@@ -796,3 +803,184 @@ def test_profile_table_candidates_virtual_empty_page_does_not_block(monkeypatch)
assert result['matched'] is True
# 虚拟空页应被跳过,只有第 1 页业务表进入结果。
assert len(result.get('tables') or []) == 1
def _profile_without_required_anchors(code: str, layout: dict) -> dict:
"""模拟 FOX 类近亲:无必选锚点,身份只能靠表头结构互斥。"""
profile = _with_signature(_profile(code), layout)
profile['definition']['document_match']['required_anchors'] = []
return profile
def test_near_twin_header_discriminator_makes_unique_match():
"""无必选锚点的近亲模板仅差表头原子时,须硬互斥成 unique_match。"""
mx_header = 'Item Parts No Description REV UNIT QTY Delivery Date Unit Total Price'
tw_header = 'Item Parts No ECCN Description REV UNIT QTY Delivery Date Unit Total Price'
mx_layout = _layout(header_text=mx_header)
tw_layout = _layout(header_text=tw_header)
mx = _profile_without_required_anchors('FOX_MX', mx_layout)
tw = _profile_without_required_anchors('FOX_TW', tw_layout)
mx_result = match_frozen_coordinate_profiles(profiles=[mx, tw], layout=mx_layout)
assert mx_result.status == 'unique_match'
assert mx_result.profile_code == 'FOX_MX'
tw_on_mx = next(item for item in mx_result.candidates if item.profile_code == 'FOX_TW')
assert tw_on_mx.hard_match is False
assert 'profile_header_discriminator_conflict' in tw_on_mx.reason_codes
tw_result = match_frozen_coordinate_profiles(profiles=[mx, tw], layout=tw_layout)
assert tw_result.status == 'unique_match'
assert tw_result.profile_code == 'FOX_TW'
mx_on_tw = next(item for item in tw_result.candidates if item.profile_code == 'FOX_MX')
assert mx_on_tw.hard_match is False
assert 'profile_header_discriminator_conflict' in mx_on_tw.reason_codes
def test_required_anchors_skip_header_atom_hard_mutex():
"""已配置必选锚点时,表头原子差异不得再硬杀;身份交给锚点门禁。"""
mx_header = 'Item Parts No Description REV UNIT QTY Delivery Date Unit Total Price'
tw_header = 'Item Parts No ECCN Description REV UNIT QTY Delivery Date Unit Total Price'
signed = _layout(header_text=mx_header)
observed = _layout(header_text=tw_header)
profile = _with_signature(_profile('INVENTECH_TW'), signed)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=observed)
candidate = result.candidates[0]
# 关键断言:有必选锚点后禁止表头原子硬互斥,不得再出现 discriminator 原因码。
assert 'profile_header_discriminator_conflict' not in candidate.reason_codes
assert candidate.hard_match is True
def test_table_geometry_ignores_mineru_sticky_footer_height():
"""MinerU 把备注粘进主表拉高 y1 时,身份几何仍应按顶边/宽度命中,不得掉到 0.75。"""
clean = _layout(bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.55})
dirty = _layout(bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95})
profile = _with_signature(_profile('PO_A', score=0.0, margin=0.0), clean)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=dirty)
assert result.status == 'unique_match'
candidate = result.candidates[0]
assert candidate.dimension_scores is not None
# 关键断言:底边被脏框拉高后,table_geometry 仍须保持高分(忽略 y1)。
assert candidate.dimension_scores.table_geometry >= 0.99
def test_auto_select_tolerates_dirty_table_height_when_top_width_match():
"""近亲双 hard_match 时,脏高度不得把原本可决胜的 Top1 压进 ambiguous。"""
clean = _layout('PLANT NAME: FACTORY A TYPE: UM17', bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.55})
dirty = _layout('PLANT NAME: FACTORY A TYPE: UM17', bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95})
stronger = _with_signature(_profile('PO_A', optional=['UM17']), clean)
weaker = _with_signature(_profile('PO_B', optional=['MISSING_TAG']), clean)
weaker['definition']['table_regions'][0]['region']['y1'] = 0.5
weaker['definition']['table_regions'][0]['line_layouts'][0]['region']['y1'] = 0.5
weaker['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['y1'] = 0.5
for item in (stronger, weaker):
item['definition']['document_match']['minimum_margin'] = 0.05
item['definition']['document_match']['scoring_thresholds'] = {
'auto_select_minimum_score': 0.80,
'auto_select_minimum_margin': 0.05,
'evidence_coverage_minimum': 0.60,
'critical_structure_minimum': 0.70,
}
weaker_sig = build_layout_signature(definition=weaker['definition'], sample_layouts=[clean])
weaker['matching_signature'] = weaker_sig
weaker['matching_signature_checksum'] = weaker_sig['signature_checksum']
clean_result = match_frozen_coordinate_profiles(profiles=[stronger, weaker], layout=clean)
dirty_result = match_frozen_coordinate_profiles(profiles=[stronger, weaker], layout=dirty)
assert clean_result.status == 'selected_by_score'
assert dirty_result.status == 'selected_by_score'
assert dirty_result.profile_code == 'PO_A'
dirty_top = next(item for item in dirty_result.candidates if item.profile_code == 'PO_A')
assert dirty_top.dimension_scores is not None
assert dirty_top.dimension_scores.table_geometry >= 0.99
def _layout_with_sticky_payment_footer(*, table_y1: float = 0.95) -> dict:
"""主表框被备注拉高;页字符含结束文案,须由模板 termination_rules 声明后才裁剪。"""
layout = _layout(bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': table_y1})
footer = 'Payment Terms'
footer_glyphs = [
{
'text': char,
'bbox': {
'x0': 12 + index * 6,
'y0': 0.58 * 280,
'x1': 16 + index * 6,
'y1': 0.58 * 280 + 10,
},
'boundary_before': 'space' if index and footer[index - 1] == ' ' else 'none',
}
for index, char in enumerate(footer)
if char != ' '
]
layout['coordinate_evidence']['page_glyphs']['1'].extend(footer_glyphs)
return layout
def _payment_termination_rule() -> dict:
"""测试用:模板声明的业务表终止锚点(非代码硬编码词表)。"""
return {
'rule_id': 'payment_terms',
'anchor': {
'anchor_id': 'payment_terms',
'text': 'Payment Terms',
'match_mode': 'contains',
},
}
def test_clip_table_bbox_cuts_sticky_payment_footer():
"""业务行裁剪只认模板 termination_rules;无声明则 fail-open 保持原框。"""
page = {'width': 200, 'height': 280}
dirty = [0.05, 0.25, 0.95, 0.95]
layout = _layout_with_sticky_payment_footer()
glyphs = layout['coordinate_evidence']['page_glyphs']['1']
rules = [_payment_termination_rule()]
# 无模板终止声明 → 不裁剪
assert clip_table_bbox_to_business_rows(dirty, page=page, glyphs=glyphs) == dirty
clipped = clip_table_bbox_to_business_rows(
dirty, page=page, glyphs=glyphs, termination_rules=rules,
)
assert clipped is not None
assert clipped[0] == dirty[0] and clipped[1] == dirty[1] and clipped[2] == dirty[2]
# 关键断言:有模板终止规则时,底边裁到声明锚点附近。
assert clipped[3] < 0.62
assert clipped[3] > 0.50
unchanged = clip_table_bbox_to_business_rows(
dirty,
page=page,
glyphs=layout['coordinate_evidence']['page_glyphs']['1'][:5],
termination_rules=rules,
)
assert unchanged == dirty
def test_observe_layout_features_applies_business_row_clip():
"""运行时主表观测须按模板 termination_rules 裁剪粘连备注。"""
layout = _layout_with_sticky_payment_footer()
profile = _with_signature(_profile('PO_A', score=0.0, margin=0.0), _layout(
bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.55},
))
signature_body, _meta = _extract_matching_signature(profile)
pages = layout['coordinate_evidence']['pages']
page_glyphs = layout['coordinate_evidence']['page_glyphs']
glyph_tables = layout['coordinate_evidence']['tables']
observed = _observe_layout_features(
layout=layout,
tables=layout['tables'],
pages=pages,
glyph_tables=glyph_tables,
page_glyphs=page_glyphs,
signature=signature_body,
termination_rules=[_payment_termination_rule()],
)
bbox = observed['primary_table_bbox']
assert bbox is not None
assert bbox[3] < 0.62
assert bbox[3] > 0.50
@@ -2,6 +2,7 @@
from app.services.shipping_notice.document_layout.order_profile_signature import (
LAYOUT_SIGNATURE_ID,
_is_dynamic_token,
build_layout_signature,
signature_checksum,
signature_is_safe_for_audit,
@@ -115,6 +116,30 @@ def test_dynamic_tokens_filtered_from_header_signature():
assert '2026-08-04' not in joined
def test_qty_req_header_label_is_not_dynamic_token():
"""ZT 列名 Qty.Req / Qty Req 是稳定表头,不得被「Qty + 值」规则误杀。"""
# 断言:列名保留;带分隔符或数字的业务值仍判动态。
assert _is_dynamic_token('Qty.Req') is False
assert _is_dynamic_token('Qty Req') is False
assert _is_dynamic_token('QTY') is False
assert _is_dynamic_token('Qty: 24') is True
assert _is_dynamic_token('Qty 24') is True
assert _is_dynamic_token('Qty-24') is True
def test_qty_req_preserved_in_header_signature():
"""签名构建必须保留 Qty.Req,同时仍过滤 Qty: 24 这类粘连业务值。"""
definition = _minimal_definition()
layout = _sample_layout(header_text='Itm Qty.Req Item Number Qty: 24')
tokens = build_layout_signature(
definition=definition, sample_layouts=[layout],
)['signature']['table_patterns'][0]['header_tokens']
joined = ' '.join(tokens)
assert 'Qty.Req' in joined
assert 'Qty: 24' not in joined
assert '24' not in joined
def test_header_signature_preserves_visual_line_order_and_token_positions():
"""表头字符即使源顺序交错,也必须按视觉行和行内坐标生成签名。"""
definition = _minimal_definition()
@@ -98,6 +98,18 @@ def test_date_normalizer_accepts_explicit_english_month_abbreviation():
assert validate_order_field_value(value, {'value_type': 'date', 'validator_keys': ['iso_date']})
def test_date_normalizer_accepts_two_digit_year_english_month_abbreviation():
"""EML 分配表 PO Date(如 12-Jun-26)必须收敛为 ISO 日期,不能拖垮正文补充行。"""
value = normalize_order_field_value(
'12-Jun-26',
{'field_code': 'order_date', 'value_type': 'date', 'normalizer_key': 'iso_date'},
)
# 关键断言:两位年英文月格式与四位年同属显式布局,须进入正式 date 值。
assert value.isoformat() == '2026-06-12'
assert validate_order_field_value(value, {'value_type': 'date', 'validator_keys': ['iso_date']})
def test_field_rules_accept_line_number_and_compute_effective_reservation():
"""订单项次按 integer 归一化;有效 Reservation 按行优先回退头,二者均可空。"""
assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'integer'}) == 10
@@ -1626,6 +1626,74 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -
# 首屏摘要不得把阶段导航 open_order_review 冒充为业务主动作;
# 否则前端隐藏导航后,用户将失去真实的重解析入口。
assert summary_leaf['ui_state']['primary_action']['code'] == 'reparse'
# 批次进度中心与全生命周期工作台必须共用同一阶段权威:空 Candidate Case
# 只能停在接收解析,不能因 Case 存在就投影成订单复核。
assert summary_leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
assert summary_leaf['source_summary']['candidate_count'] == 0
assert summary_leaf['intake_parse_authorized'] is True
assert summary_leaf['ui_state']['lifecycle_entries'][0] == {
'code': 'intake_parse',
'state': 'current',
'target_surface': 'order_lifecycle_workbench',
}
assert summary_leaf['ui_state']['lifecycle_entries'][1]['state'] == 'unavailable'
def test_summary_leaf_ignores_unbound_document_candidate_for_empty_case(app) -> None:
"""文档上有带 PO 的当前 Candidate,但 Case 未绑定时,摘要不得升到订单复核。
回归:批次进度中心曾用「文档 Candidate / Case 存在」抬升 waiting_review→order_review,
而 order-review-queue 只认 Case.candidate_id 的可复核 Candidate,导致两侧阶段不一致。
"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
from app.services.shipping_notice.order_review_projection import _serialize_review_case_summary
user, agent, session, intake, document = _seed_run_input(
suffix='SUMMARY-UNBOUND-CANDIDATE',
)
intake.source_type = 'eml'
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
unit.status = 'review_required'
unit.reason_code = 'generic_extraction_disabled'
review_case = ensure_review_case_for_unit(run=run, unit=unit)
# 文档已有当前 Candidate+PO,但故意不绑到 Case:模拟摘要误升订单复核的脏数据形态。
assert review_case.candidate_id is None
db.session.add(ShippingOrderCandidate(
candidate_no='CAND-SUMMARY-UNBOUND',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='summary-unbound',
order_extraction_run_id=run.id,
is_current_version=True,
candidate_status='provisional',
po_number='4518814494',
))
db.session.commit()
summary_payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
summary_leaf = next(
child
for rows in summary_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
)
queue_item = _serialize_review_case_summary(review_case, run=run)
# 关键断言:摘要与队列对同一 Case 给出相同生命周期阶段。
assert summary_leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
assert queue_item['lifecycle_stage'] == 'intake_parse'
assert summary_leaf['intake_parse_authorized'] is True
assert queue_item['intake_parse_authorized'] is True
assert summary_leaf['source_summary']['candidate_count'] == 0
assert summary_leaf['ui_state']['primary_action']['code'] == 'reparse'
def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> None:
@@ -1668,6 +1736,9 @@ def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> No
assert summary_leaf['ui_state']['primary_action']['code'] == 'edit_draft'
assert 'edit_draft' in summary_leaf['available_actions']
assert 'reparse' not in summary_leaf['available_actions']
assert summary_leaf['ui_state']['lifecycle_stage'] == 'order_review'
assert summary_leaf['source_summary']['candidate_count'] == 1
assert summary_leaf['intake_parse_authorized'] is False
def test_summary_leaf_uses_current_review_case_run_for_intake_parse_navigation(app) -> None: