feat(shipping-notice): 完善订单模板解析与库存 RPA 调度流程

- 新增行字段补充合并与订单模板匹配能力
- 优化运行时解析策略、签名校验及资料验证
- 完善库存 RPA 归档、收尾与 Worker 启动流程
- 补充前后端测试、多语言文案及功能文档
This commit is contained in:
hugo committed 2026-09-09 14:32:43 +08:00
1 parent 8f2f568f92
commit dabf140e41
45 files changed
+2007 -151

No files matched your search

@@ -1,10 +1,11 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_archive.py
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)。
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
query_service 只读 summary;api/schedule/runs 按 raw_inventory_zip_path send_file。
企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」;
完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。
"""
from __future__ import annotations
@@ -12,6 +13,7 @@ from __future__ import annotations
import json
import re
import zipfile
from datetime import datetime
from pathlib import Path
from typing import Any
@@ -48,9 +50,51 @@ def get_inventory_archive_dir() -> str:
return str(archive_dir)
def inventory_raw_zip_download_name(run_no: str) -> str:
"""浏览器下载时使用的 ZIP 文件名。"""
return f"inventory-rpa-raw-{run_no}.zip"
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
"""
推导企微/下载展示名中的时刻。
核心逻辑:优先 started_at → created_at → finished_at;再尝试解析 RUN{yyyyMMddHHmmss}*;
最后回退 utcnow。完整 run_no 仍留在卡片与磁盘归档键,不塞进展示名。
"""
for value in (run.started_at, run.created_at, run.finished_at):
if isinstance(value, datetime):
return value
match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip())
if match:
try:
return datetime.strptime(match.group(1), "%Y%m%d%H%M%S")
except ValueError:
pass
return datetime.utcnow()
def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}。
Args:
run: 排程执行记录。
Returns:
不含角色后缀与扩展名的展示名前缀。
"""
when = _attachment_when_from_run(run)
return f"库存RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
def inventory_rpa_result_excel_name(run: ScheduleRun) -> str:
"""库存 RPA 结果 Excel 的企微/下载展示名。"""
return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx"
def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
"""
库存 ZIP 的企微/浏览器下载展示名。
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f"{inventory_rpa_attachment_stem(run)}-库存.zip"
def _inventory_raw_zip_archive_path(run_no: str) -> Path:
@@ -157,7 +201,6 @@ def persist_inventory_rpa_raw_zip_archive(
index=zip_index,
source_code=source_code,
warehouse_id=warehouse_id,
inventory_file_no=inventory_file_no,
original_suffix=storage_path.suffix or ".xlsx",
)
archive.write(storage_path, arcname=entry_name)
@@ -236,7 +279,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
if not _is_allowed_inventory_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), inventory_raw_zip_download_name(run.run_no)
return zip_path.resolve(), inventory_raw_zip_download_name(run)
def _sanitize_zip_segment(value: str) -> str:
@@ -245,25 +288,33 @@ def _sanitize_zip_segment(value: str) -> str:
return cleaned or "unknown"
def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str:
"""
包内短标签:优先 source_code(库存站点业务键,Crane 等无固定仓码也能辨认)。
warehouse_id / inventory_file_no 已写入 manifest.json;条目名不必再叠仓码。
"""
source = str(source_code or "").strip()
if source:
return source
warehouse = str(warehouse_id or "").strip()
if warehouse and warehouse.lower() != "unknown":
return warehouse
return "inventory"
def _build_zip_entry_name(
*,
index: int,
source_code: str,
warehouse_id: str,
inventory_file_no: str,
original_suffix: str,
) -> str:
"""生成 ZIP 内单文件条目名(不含目录)。"""
base = "_".join(
filter(
None,
[
f"{index:03d}",
_sanitize_zip_segment(source_code),
_sanitize_zip_segment(warehouse_id),
_sanitize_zip_segment(inventory_file_no),
],
)
)
"""
生成 ZIP 内单文件条目名(不含目录)。
核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。
"""
label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id))
suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}"
return f"{base}{suffix}"
return f"{index:03d}_{label}{suffix}"
@@ -493,6 +493,11 @@ def _finalize_shipping_inventory_schedule_run_impl(
errors.append(f"Excel导出失败: {excel_exc}")
if status == "success":
status = "partial_failed"
else:
# 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name
file_name = inventory_rpa_result_excel_name(run)
step_logs = list(run.step_logs or [])
step_logs.append({
@@ -3,13 +3,61 @@ services/shipping_notice/document_layout/coordinate_region_text.py
用途:统一从页面坐标字符中读取受控区域文字,并恢复可靠的原始文本流空白。
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约、PositionedCharacter 可选边界字段。
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则。
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则;
另提供单逻辑表头折行合并(x 回退副标签并入最近列,不拆成新身份列)。
"""
from __future__ import annotations
from typing import Any, Literal
# 单逻辑表头:列中心相对页宽回退超过该阈值,视为同列折行副标签。
_HEADER_CENTER_X_REGRESSION_TOLERANCE = 0.02
def merge_header_identity_wrap_tokens(
tokens: list[str],
centers: list[float] | None,
widths: list[float] | None = None,
) -> tuple[list[str], list[float] | None, list[float] | None]:
"""
将单逻辑表头中的折行副标签并入所属列,保留文案、不新增身份列。
核心逻辑:主行列中心近似单调递增;若下一 token 的中心明显回退,则并入与其
x 最近的已有列(如 Part Number 下 Vendor Item#、Requested Arrival 下 Date)。
多行正式表头不要调用本函数。
Args:
tokens: 按阅读序的 header_tokens(可含第二视觉行)。
centers: 与 tokens 对齐的列中心(0..1);缺失或长度不一致时原样返回。
widths: 可选列宽比;对齐时随列保留(被并入列沿用主行宽度)。
Returns:
合并后的 (tokens, centers, widths)。
"""
if not tokens or not centers or len(centers) != len(tokens):
return tokens, centers, widths
has_widths = isinstance(widths, list) and len(widths) == len(tokens)
merged_tokens: list[str] = []
merged_centers: list[float] = []
merged_widths: list[float] | None = [] if has_widths else None
max_center = float('-inf')
for index, token in enumerate(tokens):
center = float(centers[index])
if merged_centers and center < max_center - _HEADER_CENTER_X_REGRESSION_TOLERANCE:
parent = min(
range(len(merged_centers)),
key=lambda item: abs(merged_centers[item] - center),
)
merged_tokens[parent] = f'{merged_tokens[parent]} {token}'.strip()
continue
merged_tokens.append(str(token))
merged_centers.append(center)
if merged_widths is not None:
merged_widths.append(float(widths[index]))
max_center = max(max_center, center)
return merged_tokens, merged_centers, merged_widths
def render_positioned_row(
glyphs: list[Any], *, geometry_gap_limit: float | None = None,
@@ -6,6 +6,7 @@ backend/app/services/shipping_notice/document_layout/order_profile.py
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。
表区 region_role 区分主明细与同文档 LN 补料号补充表(line_field_supplement)。
"""
from __future__ import annotations
@@ -259,6 +260,8 @@ class TableRegionProfile(OrderProfileModel):
page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages'
page_no: int | None = Field(default=None, ge=1)
region: RelativeRegion
# business_lines=主明细命中源;line_field_supplement=同文档按 LN 补料号(如 COO),不进业务表匹配。
region_role: Literal['business_lines', 'line_field_supplement'] = 'business_lines'
# 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。
line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
@@ -304,6 +307,22 @@ class TableRegionProfile(OrderProfileModel):
field.field_code for field in self.line_layouts[0].field_regions
}:
raise ValueError('main line layout must bind the configured line-start field')
if self.region_role == 'line_field_supplement':
# 补充表只允许起行 + 客户料号/Vendor,禁止绑数量金额等以免误当业务明细。
bound = {
field.field_code
for item in self.line_layouts
for field in item.field_regions
}
if not self.line_start_field_code or self.line_start_field_code not in bound:
raise ValueError('line_field_supplement requires the configured line-start field')
allowed = {self.line_start_field_code, 'customer_part_number', 'part_number'}
extra = sorted(bound - allowed)
if extra:
raise ValueError(
'line_field_supplement may only bind line-start and part number fields; '
f'unexpected: {", ".join(extra)}'
)
# A physical text band must have exactly one layout interpretation. Allowing
# overlapping header/line regions would reintroduce the cross-row ambiguity
# that v2 coordinate profiles are intended to eliminate.
@@ -505,6 +524,11 @@ class OrderCoordinateProfile(OrderProfileModel):
ids = [item.region_id for item in self.table_regions]
if len(ids) != len(set(ids)):
raise ValueError('table region ids must be unique')
if not any(
str(getattr(item, 'region_role', None) or 'business_lines') == 'business_lines'
for item in self.table_regions
):
raise ValueError('at least one business_lines table region is required')
for index, left in enumerate(self.table_regions):
for right in self.table_regions[index + 1:]:
# Different exact pages may use identical coordinates without competing at runtime.
@@ -6,7 +6,8 @@ services/shipping_notice/document_layout/order_profile_matcher.py
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁。
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
"""
from __future__ import annotations
@@ -19,6 +20,7 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.coordinate_region_text import (
merge_header_identity_wrap_tokens,
positioned_token_spans,
read_coordinate_region_text,
visual_glyph_rows,
@@ -960,13 +962,11 @@ def _score_header_semantic_position(
"""比对真实表头 token、横向顺序和位置。
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
期望侧先截断单逻辑表头的折行副标签污染。
"""
if signature is None:
return MatchDimensionResult(state='unavailable', score=0.0)
expected_tokens: list[str] = []
for table in signature.get('table_patterns') or []:
if isinstance(table, dict):
expected_tokens.extend(str(item).casefold() for item in table.get('header_tokens') or [])
expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0
if not expected_tokens:
@@ -986,7 +986,7 @@ def _score_header_semantic_position(
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 []]
expected_order = [str(item).casefold() for item in _signature_identity_header_order(signature)]
observed_order = observed.get('header_tokens') or []
shared = [item for item in expected_order if item in observed_order]
order_ratio = 1.0
@@ -1008,6 +1008,63 @@ _HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with
_HEADER_ATOM_MIN_LEN = 3
def _sanitize_signature_table_identity(
pattern: dict[str, Any],
) -> tuple[list[str], list[float] | None, list[float] | None]:
"""
按需合并单逻辑表头签名中的折行副标签。
核心逻辑:header_row_count==1 时按 column_centers 回退把副标签并入最近列;
多行正式表头原样返回。兼容尚未重冻、仍把 Vendor Item#/Date 列为独立 token 的旧签名。
"""
raw_tokens = [str(item) for item in pattern.get('header_tokens') or []]
centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else None
widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else None
try:
center_values = [float(item) for item in centers] if centers is not None else None
except (TypeError, ValueError):
center_values = None
try:
width_values = [float(item) for item in widths] if widths is not None else None
except (TypeError, ValueError):
width_values = None
if int(pattern.get('header_row_count') or 1) > 1:
return raw_tokens, center_values, width_values
return merge_header_identity_wrap_tokens(raw_tokens, center_values, width_values)
def _signature_identity_header_tokens(signature: dict[str, Any] | None) -> list[str]:
"""读取截断折行副标签后的签名表头身份 token。"""
tokens: list[str] = []
for pattern in (signature or {}).get('table_patterns') or []:
if isinstance(pattern, dict):
trimmed, _, _ = _sanitize_signature_table_identity(pattern)
tokens.extend(trimmed)
return tokens
def _signature_identity_header_order(signature: dict[str, Any] | None) -> list[str]:
"""读取合并折行后的 header_order;与身份 token 对齐。"""
ordered: list[str] = []
for pattern in (signature or {}).get('table_patterns') or []:
if not isinstance(pattern, dict):
continue
tokens, _, _ = _sanitize_signature_table_identity(pattern)
ordered.extend(tokens)
return ordered
def _signature_single_logical_header(signature: dict[str, Any] | None) -> bool:
"""签名是否全部为逻辑一行表头(可含格内折行)。"""
patterns = [
item for item in (signature or {}).get('table_patterns') or []
if isinstance(item, dict)
]
if not patterns:
return True
return all(int(item.get('header_row_count') or 1) <= 1 for item in patterns)
def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
"""
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
@@ -1031,10 +1088,7 @@ def _header_discriminator_atoms_conflict(
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
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 [])
expected_tokens = _signature_identity_header_tokens(signature)
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if not expected_tokens or not observed_tokens:
return False
@@ -1075,9 +1129,15 @@ def _score_column_topology(
for pattern, expected in zip(patterns, expected_counts):
if expected <= 0:
continue
count_score = min(observed_count, expected) / max(observed_count, expected)
expected_centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else []
expected_widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else []
tokens, expected_centers_raw, expected_widths_raw = _sanitize_signature_table_identity(pattern)
expected_identity_count = len(tokens) or expected
count_score = min(observed_count, expected_identity_count) / max(observed_count, expected_identity_count)
expected_centers = expected_centers_raw if isinstance(expected_centers_raw, list) else []
expected_widths = expected_widths_raw if isinstance(expected_widths_raw, list) else []
if not expected_centers and isinstance(pattern.get('column_centers'), list):
expected_centers = pattern.get('column_centers') or []
if not expected_widths and isinstance(pattern.get('column_width_ratios'), list):
expected_widths = pattern.get('column_width_ratios') or []
if expected_centers and observed_centers:
center_score = _sequence_similarity(expected_centers, observed_centers, tolerance=0.08)
width_score = _sequence_similarity(expected_widths, observed_widths, tolerance=0.16) if expected_widths and observed_widths else 0.0
@@ -1373,18 +1433,8 @@ def _select_persisted_header_candidate(
*, candidates: list[dict[str, Any]], signature: dict[str, Any] | None,
) -> tuple[dict[str, Any], list[float]] | None:
"""按冻结签名联合选择投影表头,证据不足时返回 None 而非按列数猜测。"""
expected_tokens = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_tokens') or []
]
expected_order = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_order') or []
]
expected_tokens = [str(token).casefold() for token in _signature_identity_header_tokens(signature)]
expected_order = [str(token).casefold() for token in _signature_identity_header_order(signature)]
expected_centers = _signature_column_values(signature or {}, 'column_centers')
expected_widths = _signature_column_values(signature or {}, 'column_width_ratios')
if not expected_tokens or not expected_centers:
@@ -1573,14 +1623,9 @@ def _band_headers_match_signature(
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
需要回退到表体顶部的结构搜索。
需要回退到表体顶部的结构搜索。期望侧先截断折行副标签污染。
"""
expected = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_tokens') or []
]
expected = [str(token).casefold() for token in _signature_identity_header_tokens(signature)]
if not expected or not band_tokens:
return False
observed = [str(token).casefold() for token in band_tokens]
@@ -1598,10 +1643,8 @@ def _observe_primary_table_header(
) -> tuple[list[str], list[float], list[float]]:
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为,
不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到
错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑),
从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用。
若固定带失准,则基于表体顶部做表头行搜索。单逻辑表头时把折行副标签按 x 并入所属列。
"""
if not primary_bbox or len(primary_bbox) != 4:
return [], [], []
@@ -1634,26 +1677,85 @@ def _observe_primary_table_header(
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001)
band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
# 固定带有效 → 直接沿用(对正常模板零影响)。
single_logical = _signature_single_logical_header(signature)
if single_logical:
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
band_tokens, band_centers, band_widths,
)
band_tokens = [str(item).casefold() for item in merged_tokens]
band_centers = list(merged_centers or [])
band_widths = list(merged_widths or [])
# 固定带有效 → 直接沿用。
if _band_headers_match_signature(band_tokens=band_tokens, signature=signature):
return band_tokens, band_centers, band_widths
# 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。
candidates = [{
'bbox': primary_bbox,
'header_candidates': _observe_header_candidates(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
),
}]
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
# 固定带失准 → 表体顶部候选行;单逻辑表头时把下一视觉行折行副标签并入。
header_candidates = _observe_header_candidates(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
)
selected = _select_persisted_header_candidate(
candidates=[{'bbox': primary_bbox, 'header_candidates': header_candidates}],
signature=signature,
)
if selected is not None:
header, _ = selected
return (
[str(token).casefold() for token in header['header_tokens']],
header['column_centers'], header['column_width_ratios'],
)
tokens = [str(token).casefold() for token in header['header_tokens']]
centers = list(header['column_centers'])
widths = list(header['column_width_ratios'])
if single_logical:
tokens, centers, widths = _merge_following_wrap_candidate(
header=header,
header_candidates=header_candidates,
)
return tokens, centers, widths
return band_tokens, band_centers, band_widths
def _merge_following_wrap_candidate(
*,
header: dict[str, Any],
header_candidates: list[dict[str, Any]],
) -> tuple[list[str], list[float], list[float]]:
"""
将选中主表头行与紧邻下一视觉行合并(折行副标签)。
核心逻辑:下一行 token 的列中心若相对主行回退,merge_header_identity_wrap_tokens
会把它们并入所属列;若不构成回退则合并结果与主行等价或略增列,仍可安全返回。
"""
tokens = [str(token).casefold() for token in header.get('header_tokens') or []]
centers = [float(item) for item in header.get('column_centers') or []]
widths = [float(item) for item in header.get('column_width_ratios') or []]
header_y1 = float((header.get('bbox') or [0, 0, 0, 0])[3])
following = None
for candidate in header_candidates:
if candidate is header:
continue
bbox = candidate.get('bbox') if isinstance(candidate.get('bbox'), list) else None
if not bbox or len(bbox) != 4:
continue
y0 = float(bbox[1])
if y0 + 1e-6 < header_y1:
continue
if following is None or y0 < float(following['bbox'][1]):
following = candidate
if following is None:
return tokens, centers, widths
wrap_tokens = [str(token).casefold() for token in following.get('header_tokens') or []]
wrap_centers = [float(item) for item in following.get('column_centers') or []]
wrap_widths = [float(item) for item in following.get('column_width_ratios') or []]
if not wrap_tokens or len(wrap_tokens) != len(wrap_centers):
return tokens, centers, widths
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
tokens + wrap_tokens,
centers + wrap_centers,
widths + wrap_widths if len(widths) == len(tokens) else None,
)
return (
[str(item).casefold() for item in merged_tokens],
list(merged_centers or []),
list(merged_widths or []),
)
def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None:
"""读取候选签名冻结的表头标注区域;每个候选独立取证,禁止共享整页猜测结果。"""
for pattern in (signature or {}).get('table_patterns') or []:
@@ -1690,9 +1792,15 @@ def _usable_observed_header_token(token: str) -> bool:
def _signature_column_values(signature: dict[str, Any], key: str) -> list[float]:
"""读取签名中首个可用表格的列结构向量。"""
"""读取签名中首个可用表格的列结构向量,单逻辑表头时合并折行副标签后再取。"""
for pattern in signature.get('table_patterns') or []:
if isinstance(pattern, dict) and isinstance(pattern.get(key), list):
if not isinstance(pattern, dict):
continue
_, centers, widths = _sanitize_signature_table_identity(pattern)
selected = centers if key == 'column_centers' else widths if key == 'column_width_ratios' else None
if isinstance(selected, list) and selected:
return list(selected)
if isinstance(pattern.get(key), list):
try:
return [float(item) for item in pattern[key]]
except (TypeError, ValueError):
@@ -5,6 +5,7 @@ services/shipping_notice/document_layout/order_profile_parse_validation.py
依赖:OrderCoordinateProfile、coordinate_region_text、order_profile 契约。
逻辑:由 order_extraction_workflow 在 matcher 硬门禁后调用;确定性/idempotent;
返回 passed/reason_codes/metrics 供 unique_match 二次裁决。
类型 sanity 接受 MM/DD/YY;字段覆盖仅统计 business_lines。
"""
from __future__ import annotations
@@ -26,8 +27,9 @@ from app.services.shipping_notice.document_layout.coordinate_table_reconstructio
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
# Hyve 等 PO 常见 MM/DD/YY;亦接受 YYYY-MM-DD / MM/DD/YYYY。
_DATE_PATTERN = re.compile(
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{4})$',
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4})$',
)
@@ -94,8 +96,13 @@ def validate_profile_parse_candidate(
)
# [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报)
# 补充表不参与发布解析门禁的字段覆盖/类型检查(正式路径另行按 LN 合并)。
business_tables = [
table for table in profile.table_regions
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
]
line_fields = [
field for table in profile.table_regions for layout in table.line_layouts
field for table in business_tables for layout in table.line_layouts
for field in layout.field_regions if field.scope == 'line'
]
line_coverage = _line_region_coverage_shift_tolerant(
@@ -130,7 +137,7 @@ def validate_profile_parse_candidate(
required_line_codes = {
field.field_code
for table in profile.table_regions
for table in business_tables
for layout in table.line_layouts
for field in layout.field_regions
if field.scope == 'line'
@@ -245,8 +252,13 @@ def _line_region_coverage_shift_tolerant(
"""
if not profile.table_regions:
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
business_tables = [
table for table in profile.table_regions
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
]
tables_for_lines = business_tables or list(profile.table_regions)
line_fields = [
field for table in profile.table_regions for layout_item in table.line_layouts
field for table in tables_for_lines for layout_item in table.line_layouts
for field in layout_item.field_regions if field.scope == 'line'
]
if not line_fields:
@@ -254,9 +266,9 @@ def _line_region_coverage_shift_tolerant(
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
# 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。
# 定位与主表区(首个 business_lines 且含 line_layouts)重叠且在 page 上的物理表;取重叠面积最大者。
primary_region = next(
(table for table in profile.table_regions if table.line_layouts), None,
(table for table in tables_for_lines if table.line_layouts), None,
)
raw_table = _locate_overlapping_raw_table(
primary_region=primary_region, layout=layout, page=page, profile=profile,
@@ -5,6 +5,7 @@ services/shipping_notice/document_layout/order_profile_signature.py
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
单逻辑表头行将格内折行副标签按 x 并入所属列,保留文案、不拆成新身份列。
"""
from __future__ import annotations
@@ -16,6 +17,7 @@ import statistics
from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import (
merge_header_identity_wrap_tokens,
positioned_token_spans,
read_coordinate_region_text,
visual_glyph_rows,
@@ -353,12 +355,15 @@ def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) ->
default=0,
)
# 1 个 header_layout = 逻辑一行表头(可含格内折行);多 layout 才是多行正式表头。
single_logical_header_row = len(header_layouts) <= 1
for layout in sample_layouts:
observed = _observe_sample_table(
layout,
target_region=region,
header_region=header_region,
table_region=table,
single_logical_header_row=single_logical_header_row,
)
if observed is None:
continue
@@ -433,6 +438,7 @@ def _observe_sample_table(
layout: dict[str, Any], *, target_region: RelativeRegion,
header_region: RelativeRegion | None,
table_region: Any | None = None,
single_logical_header_row: bool = True,
) -> dict[str, Any] | None:
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
@@ -469,7 +475,10 @@ def _observe_sample_table(
table_glyphs, page=page, bbox=bbox, header_bbox=header_bbox,
)
header_tokens, centers, widths = _header_observation(
header_glyphs, page=page, bbox=bbox,
header_glyphs,
page=page,
bbox=bbox,
single_logical_header_row=single_logical_header_row,
)
header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None
termination_rules = [
@@ -556,9 +565,18 @@ def _union_relative_regions(regions: list[RelativeRegion]) -> RelativeRegion | N
def _header_observation(
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float],
glyphs: list[dict[str, Any]],
*,
page: dict[str, Any],
bbox: list[float],
single_logical_header_row: bool = True,
) -> tuple[list[str], list[float], list[float]]:
"""从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。"""
"""
从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。
核心逻辑:读出带内全部视觉行后,对逻辑一行表头按列中心回退把折行副标签并入
所属列(保留 Vendor Item# / Date 文案);多行正式表头不做合并。
"""
try:
page_width = float(page['width'])
except (KeyError, TypeError, ValueError):
@@ -571,6 +589,15 @@ def _header_observation(
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / page_width, 4) for item in spans]
span = max(bbox[2] - bbox[0], 0.0001)
widths = [round((float(item['x1']) - float(item['x0'])) / page_width / span, 4) for item in spans]
if single_logical_header_row:
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
tokens, centers, widths,
)
return (
list(merged_tokens),
list(merged_centers or []),
list(merged_widths or []),
)
return tokens, centers, widths
@@ -3,7 +3,8 @@ services/shipping_notice/document_layout/runtime_parse_strategy.py
用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。
依赖:仅标准库;由正式抽取与模板质量验证共同调用。
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用;
二者业务值冲突时,若动态列能单侧确认其一则采用该侧(或更完整的动态结果),否则转 Review。
"""
from __future__ import annotations
@@ -75,6 +76,15 @@ def resolve_runtime_parse_strategy(
baseline_rows = fixed_valid
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
else:
# [STEP] 固定/自适应业务值冲突:不得静默猜一侧;若动态列能单侧确认,再落选。
resolved = _resolve_fixed_adaptive_ambiguity_with_dynamic(
page_nos=page_nos,
fixed_rows=fixed_valid,
adaptive_rows=adaptive_valid,
dynamic_rows=dynamic_valid,
)
if resolved is not None:
return resolved
return RuntimeParseStrategy(
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
)
@@ -103,6 +113,67 @@ def resolve_runtime_parse_strategy(
)
def _resolve_fixed_adaptive_ambiguity_with_dynamic(
*,
page_nos: tuple[int, ...],
fixed_rows: list[dict[str, Any]],
adaptive_rows: list[dict[str, Any]],
dynamic_rows: list[dict[str, Any]],
) -> RuntimeParseStrategy | None:
"""
固定与自适应冲突时,用动态列做单侧确认。
核心逻辑:动态相对某一侧可覆盖(baseline/dynamic preferred),且相对另一侧
仍 ambiguous,则采用被确认的一侧;两侧都被动态确认且动态更完整时采用动态。
无动态证据或仍双边不清时返回 None,由调用方转 Review。
Args:
page_nos: 当前有坐标证据的页码。
fixed_rows: 有效固定子行。
adaptive_rows: 有效自适应行。
dynamic_rows: 有效动态列行;空则无法仲裁。
Returns:
可安全选中的策略;无法仲裁时为 None。
"""
if not dynamic_rows:
return None
fixed_vs_dyn = _compare_dynamic_row_coverage(
baseline_rows=fixed_rows, dynamic_rows=dynamic_rows,
)
adaptive_vs_dyn = _compare_dynamic_row_coverage(
baseline_rows=adaptive_rows, dynamic_rows=dynamic_rows,
)
fixed_ok = fixed_vs_dyn != 'ambiguous'
adaptive_ok = adaptive_vs_dyn != 'ambiguous'
if fixed_ok and adaptive_ok:
if fixed_vs_dyn == 'dynamic_preferred' or adaptive_vs_dyn == 'dynamic_preferred':
return RuntimeParseStrategy(
'selected', page_nos, 'dynamic_x_columns',
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
)
# 动态完整覆盖两侧且无额外行:冲突本身未消除,不能借动态消歧。
return None
if fixed_ok and not adaptive_ok:
if fixed_vs_dyn == 'dynamic_preferred':
return RuntimeParseStrategy(
'selected', page_nos, 'dynamic_x_columns',
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
)
return RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
if adaptive_ok and not fixed_ok:
if adaptive_vs_dyn == 'dynamic_preferred':
return RuntimeParseStrategy(
'selected', page_nos, 'dynamic_x_columns',
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
)
return RuntimeParseStrategy(
'selected', page_nos, 'adaptive_record_columns',
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
)
return None
def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]:
"""为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。
@@ -210,29 +281,33 @@ def _compare_row_field_completeness(
def _compare_dynamic_row_coverage(
*, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]],
) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']:
"""仅当动态结果无冲突地覆盖基线每条记录并额外恢复记录时才切换策略。"""
"""仅当动态结果无冲突地覆盖基线,并额外恢复记录或严格加长字段值时才切换策略。"""
if len(dynamic_rows) < len(baseline_rows):
return 'baseline_preferred'
remaining = [_row_fields(row) for row in dynamic_rows]
extended = False
for baseline in baseline_rows:
baseline_fields = _row_fields(baseline)
matches = []
for index, dynamic_fields in enumerate(remaining):
if not baseline_fields.keys() <= dynamic_fields.keys():
continue
if all(
dynamic_fields[code] == value
or (
dynamic_fields[code].startswith(value)
and len(dynamic_fields[code]) > len(value)
)
for code, value in baseline_fields.items()
):
compatible = True
for code, value in baseline_fields.items():
dyn_value = dynamic_fields[code]
if dyn_value == value:
continue
if dyn_value.startswith(value) and len(dyn_value) > len(value):
extended = True
continue
compatible = False
break
if compatible:
matches.append(index)
if len(matches) != 1:
return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred'
remaining.pop(matches[0])
return 'dynamic_preferred' if remaining else 'baseline_preferred'
return 'dynamic_preferred' if remaining or extended else 'baseline_preferred'
def _row_fields(row: dict[str, Any]) -> dict[str, str]:
@@ -6,6 +6,7 @@ services/shipping_notice/document_profile_quality_service.py
逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;
共同坐标回放完成视觉证据,末端值源 adapter 再补充正式字段和结构校验;
策略需复核时仍展示最佳努力明细供人工核对,正式自动建单仍要求策略 selected;
盲测主明细仅 business_lines,随后按 LN 合并 line_field_supplement 料号;
盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。
"""
@@ -399,6 +400,9 @@ def _candidate_for_sample(
# layout. They are valid template regions, but cannot reconstruct rows.
if not region.line_layouts:
continue
# COO 等补充表不进入盲测主明细行;稍后按 LN 合并料号。
if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
continue
# ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中
# 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。
eligible_pages = [
@@ -463,6 +467,30 @@ def _candidate_for_sample(
)
# selected 与 needs_review 的 fallback 明细都要展示;后者仅供盲测人工复核。
rows.extend(item.fields for item in chosen_rows if not item.issues)
# 与正式解析共用:按 LN 合并 line_field_supplement(如 COO)料号。
from app.services.shipping_notice.order_extraction_workflow import (
_reconstruct_line_field_supplement_rows,
)
from app.services.shipping_notice.line_field_supplement_merge import (
merge_line_field_supplement,
)
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
raw_profile={
'definition': profile.definition_json if isinstance(profile.definition_json, dict) else {},
'profile_code': profile.profile_code,
'version': profile.version,
'checksum': profile.checksum,
},
layout=layout,
schema_fields=schema_fields,
)
supplement_reasons: list[str] = []
if supplement_rows:
rows, supplement_reasons = merge_line_field_supplement(
rows,
supplement_rows,
line_start_field_code=line_start or 'customer_po_line_no',
)
order_fields = [
{
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
@@ -521,8 +549,13 @@ def _candidate_for_sample(
'document_id': document.id, 'table_id': str(table_id), 'rows': rows,
'order_fields': order_fields, 'reservation_region_status': 'needs_review',
'reservation_region_review_reasons': list(dict.fromkeys(review_reasons)),
'line_field_supplement_reasons': list(supplement_reasons),
}
return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields}
return {
'document_id': document.id, 'table_id': str(table_id), 'rows': rows,
'order_fields': order_fields,
'line_field_supplement_reasons': list(supplement_reasons),
}
raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
@@ -0,0 +1,278 @@
"""
services/shipping_notice/line_field_supplement_merge.py
用途:将同文档「明细字段补充表」(如 Hyve COO)按 LN 保守合并进主表明细。
依赖:无外部 IO;仅字符串规范化与行字典读写。
逻辑:由正式解析 / 盲测 / 验证在主表重建后调用;只补 customer_part_number、part_number;
空值直补、主表为补充值前缀则补全、冲突不覆盖并写稳定 reason。不改数量/单价/金额。
``REASON_APPLIED`` 仅写入表级 reasons 审计,不进入行 ``issues``(成功补齐不得触发 row_needs_review)。
"""
from __future__ import annotations
import copy
import re
from typing import Any
LINE_FIELD_SUPPLEMENT_CODES = frozenset({'customer_part_number', 'part_number'})
DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no'
REASON_APPLIED = 'line_field_supplement_applied'
REASON_CONFLICT = 'line_field_supplement_conflict'
REASON_LN_AMBIGUOUS = 'line_field_supplement_ln_ambiguous'
REASON_LN_MISSING = 'line_field_supplement_ln_missing'
# 表级审计码:不得当作行级缺陷拦截确定性建单。
NON_BLOCKING_ROW_ISSUE_CODES = frozenset({REASON_APPLIED})
def normalize_line_start_key(raw: Any) -> str:
"""
将行号规范为对齐键:去空白;纯数字去掉无意义前导零(保留至少一位)。
Args:
raw: 主表或补充表上的起行字段值。
Returns:
非空对齐键;无法规范化时返回空串。
"""
text = re.sub(r'\s+', '', str(raw or '')).strip()
if not text:
return ''
if text.isdigit():
return str(int(text))
return text
def normalize_part_value(raw: Any) -> str:
"""料号比较用:去掉空白,保留连字符等符号。"""
return re.sub(r'\s+', '', str(raw or '')).strip()
def _row_field_map(row: dict[str, Any]) -> dict[str, str]:
"""将扁平行或 workflow ``fields`` 列表统一为 field_code -> 文本值。"""
if not isinstance(row, dict):
return {}
fields = row.get('fields')
if isinstance(fields, list):
result: dict[str, str] = {}
for item in fields:
if not isinstance(item, dict):
continue
code = str(item.get('field_code') or '').strip()
if not code:
continue
result[code] = str(item.get('value') or '').strip()
return result
return {
str(key): str(value or '').strip()
for key, value in row.items()
if key not in {'fields', 'issues', 'status', 'row_index', 'role', 'source_row_indices'}
and not str(key).startswith('_')
}
def _set_row_field(row: dict[str, Any], field_code: str, value: str) -> None:
"""按行形态写回字段值;workflow 行写入 ``fields`` 列表。"""
fields = row.get('fields')
if isinstance(fields, list):
target = next(
(
item for item in fields
if isinstance(item, dict) and str(item.get('field_code') or '') == field_code
),
None,
)
if target is None:
fields.append({'field_code': field_code, 'value': value})
else:
target['value'] = value
return
row[field_code] = value
def _append_row_issue(row: dict[str, Any], code: str) -> None:
"""为 workflow 行追加 issue;扁平行写入 ``issues`` 列表供调用方读取。"""
issues = row.get('issues')
if not isinstance(issues, list):
row['issues'] = [code]
return
if code not in issues:
issues.append(code)
def _index_rows_by_line(
rows: list[dict[str, Any]],
*,
line_start_field_code: str,
) -> tuple[dict[str, dict[str, Any]], set[str], list[str]]:
"""
按规范化 LN 建唯一索引。
Returns:
(唯一行映射, 重复 LN 集合, 缺 LN 的全局 reasons)
"""
buckets: dict[str, list[dict[str, Any]]] = {}
missing_reasons: list[str] = []
for row in rows:
key = normalize_line_start_key(_row_field_map(row).get(line_start_field_code))
if not key:
missing_reasons.append(REASON_LN_MISSING)
continue
buckets.setdefault(key, []).append(row)
unique: dict[str, dict[str, Any]] = {}
ambiguous: set[str] = set()
for key, items in buckets.items():
if len(items) != 1:
ambiguous.add(key)
continue
unique[key] = items[0]
return unique, ambiguous, missing_reasons
def merge_line_field_supplement(
main_rows: list[dict[str, Any]],
supplement_rows: list[dict[str, Any]],
*,
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
field_codes: frozenset[str] = LINE_FIELD_SUPPLEMENT_CODES,
) -> tuple[list[dict[str, Any]], list[str]]:
"""
按 LN 将补充表料号合并进主表明细。
核心逻辑:只处理 ``field_codes``;空值直补;主表规范化值是补充值前缀则补全;
两边完整且不同则写冲突 reason 且不覆盖;补充侧或主侧 LN 重复/缺失则跳过该键。
成功补齐仅写入返回的 reasons(``REASON_APPLIED``),不写入行 ``issues``。
Args:
main_rows: 主表明细(扁平 dict 或含 ``fields`` 的 workflow 行)。
supplement_rows: 补充表重建行,形态同主表。
line_start_field_code: 对齐用起行字段,默认 customer_po_line_no。
field_codes: 允许补齐的字段集合。
Returns:
(合并后的主表行深拷贝, 稳定 reason 列表;可含表级审计码与行级冲突码)
"""
if not main_rows or not supplement_rows:
return [copy.deepcopy(row) for row in main_rows], []
merged = [copy.deepcopy(row) for row in main_rows]
main_index, main_ambiguous, main_missing = _index_rows_by_line(
merged, line_start_field_code=line_start_field_code,
)
supplement_index, supplement_ambiguous, supplement_missing = _index_rows_by_line(
supplement_rows, line_start_field_code=line_start_field_code,
)
reasons: list[str] = []
reasons.extend(main_missing)
reasons.extend(supplement_missing)
for key in sorted(main_ambiguous | supplement_ambiguous):
reasons.append(REASON_LN_AMBIGUOUS)
if key in main_index:
_append_row_issue(main_index[key], REASON_LN_AMBIGUOUS)
for row in merged:
if normalize_line_start_key(_row_field_map(row).get(line_start_field_code)) == key:
_append_row_issue(row, REASON_LN_AMBIGUOUS)
for line_key, main_row in main_index.items():
if line_key in main_ambiguous or line_key in supplement_ambiguous:
continue
supplement_row = supplement_index.get(line_key)
if supplement_row is None:
continue
main_fields = _row_field_map(main_row)
supplement_fields = _row_field_map(supplement_row)
for code in sorted(field_codes):
supplement_raw = supplement_fields.get(code) or ''
if not supplement_raw:
continue
main_raw = main_fields.get(code) or ''
main_norm = normalize_part_value(main_raw)
supplement_norm = normalize_part_value(supplement_raw)
if not supplement_norm:
continue
if not main_norm:
# [STEP] 成功直补:只记表级审计,不写行 issues(避免误判 row_needs_review)。
_set_row_field(main_row, code, supplement_raw)
reasons.append(REASON_APPLIED)
continue
if main_norm == supplement_norm:
continue
if supplement_norm.startswith(main_norm) and len(supplement_norm) > len(main_norm):
# [STEP] 前缀补全成功:同上,审计进 reasons,不写入 issues。
_set_row_field(main_row, code, supplement_raw)
reasons.append(REASON_APPLIED)
continue
_append_row_issue(main_row, REASON_CONFLICT)
reasons.append(REASON_CONFLICT)
# 保持 reason 顺序稳定且去重保留首次出现,便于审计对照。
deduped: list[str] = []
seen: set[str] = set()
for code in reasons:
if code in seen:
continue
seen.add(code)
deduped.append(code)
return merged, deduped
def project_line_field_supplement_onto_validation_evidence(
evidence: dict[str, Any],
*,
supplement_rows: list[dict[str, Any]],
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
) -> tuple[dict[str, Any], list[str]]:
"""
将补充表合并结果写回验证证据的 lines 字段。
Args:
evidence: 含 header_fields / lines 的验证 DTO。
supplement_rows: workflow 或扁平行。
line_start_field_code: LN 对齐字段。
Returns:
(更新后的 evidence 深拷贝, reason 列表)
"""
if not isinstance(evidence, dict) or not supplement_rows:
return copy.deepcopy(evidence) if isinstance(evidence, dict) else {}, []
result = copy.deepcopy(evidence)
lines = result.get('lines') if isinstance(result.get('lines'), list) else []
main_rows: list[dict[str, Any]] = []
for line in lines:
if not isinstance(line, dict):
continue
fields = []
for item in line.get('fields') or []:
if not isinstance(item, dict):
continue
fields.append({
'field_code': str(item.get('field_code') or ''),
'value': str(item.get('raw_value') or item.get('normalized_value') or ''),
})
main_rows.append({'fields': fields, 'issues': []})
if not main_rows:
return result, []
merged, reasons = merge_line_field_supplement(
main_rows, supplement_rows, line_start_field_code=line_start_field_code,
)
for index, row in enumerate(merged):
if index >= len(lines) or not isinstance(lines[index], dict):
continue
values = _row_field_map(row)
issues = list(row.get('issues') or [])
for field in lines[index].get('fields') or []:
if not isinstance(field, dict):
continue
code = str(field.get('field_code') or '')
if code not in LINE_FIELD_SUPPLEMENT_CODES or code not in values:
continue
value = values[code]
field['raw_value'] = value or None
field['normalized_value'] = value or None
field['status'] = 'passed' if value else field.get('status') or 'missing'
if issues:
field['issues'] = list(dict.fromkeys([*(field.get('issues') or []), *issues]))
result['line_field_supplement_reasons'] = list(reasons)
return result, reasons
@@ -1289,6 +1289,9 @@ def preview_profile_region(
# Header-only pages document column semantics but must never emit data rows.
if not table_region.line_layouts:
continue
# 补充表不进入预览主网格;验证/正式路径另行按 LN 合并。
if str(getattr(table_region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
continue
# 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema
# 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。
reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump())
@@ -3,10 +3,11 @@ services/shipping_notice/order_document_profile_validation_service.py
用途:执行订单文档 Profile 草稿的不可变即时检查、当前样本试运行、版面/XFA 结构签名与跨模板唯一性验证。
依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、
Profile 保存服务、编辑租约服务、Reservation 专区锚点投影。
Profile 保存服务、编辑租约服务、Reservation 专区锚点投影、line_field_supplement_merge。
逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;坐标 current-sample 在表格/
表头试读后投影 Vendor Comments Reservation;XFA current-sample 另附脱敏字段级
Header/Line;签名成功后更新 Profile 轻量引用;查询时根据当前 checksum 派生 stale。
表头试读后投影 Vendor Comments Reservation,并按 LN 合并 COO 等补充表料号;
XFA current-sample 另附脱敏字段级 Header/Line;签名成功后更新 Profile 轻量引用;
查询时根据当前 checksum 派生 stale。
"""
from __future__ import annotations
@@ -419,6 +420,44 @@ def _extract_coordinate_current_sample(
reason=reservation.get('reason'),
schema_fields=schema_fields,
)
# [STEP] COO 等明细字段补充表按 LN 合并进验证 lines(与正式/盲测同契约)。
if any(
isinstance(item, dict) and str(item.get('region_role') or '') == 'line_field_supplement'
for item in definition.get('table_regions') or []
):
from app.services.shipping_notice.line_field_supplement_merge import (
project_line_field_supplement_onto_validation_evidence,
)
from app.services.shipping_notice.order_extraction_workflow import (
_reconstruct_line_field_supplement_rows,
)
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
layout = _load_sample_layout(sample) if document is not None else {}
if document is not None and isinstance(layout, dict):
layout = ensure_on_demand_coordinate_evidence(
document=document, layout=layout, page_nos=None,
)
schema_fields = {
str(item.get('field_id') or ''): item
for item in (profile.schema_version.definition_json or {}).get('fields') or []
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
}
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
raw_profile={
'definition': definition,
'profile_code': profile.profile_code,
'version': profile.version,
'checksum': profile.checksum,
},
layout=layout if isinstance(layout, dict) else {},
schema_fields=schema_fields,
)
if supplement_rows:
evidence, _reasons = project_line_field_supplement_onto_validation_evidence(
evidence,
supplement_rows=supplement_rows,
line_start_field_code=line_start or 'customer_po_line_no',
)
summary['validation_evidence'] = evidence
return status, summary, snapshot
@@ -3,11 +3,12 @@ backend/app/services/shipping_notice/order_extraction_workflow.py
用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。
依赖:MinerU 紧凑快照、订单 Profile(coordinate / xfa_dataset)、Schema 校验、
order_extraction_route_contract、xfa_profile_*、统一错误类型。
order_extraction_route_contract、xfa_profile_*、line_field_supplement_merge、统一错误类型。
逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值;
datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review;
唯一 PO 提升到 Header 后从明细剥离,避免 persist 因 scope 不匹配失败;
路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格;
主明细仅来自 region_role=business_lines;line_field_supplement 按 LN 补料号;
模板 auto_create_approved 仅作解析器质量痕迹;主链不调用 Dify。
"""
@@ -38,6 +39,10 @@ from app.services.shipping_notice.document_layout.runtime_parse_strategy import
resolve_runtime_parse_strategy,
select_runtime_region_ids,
)
from app.services.shipping_notice.line_field_supplement_merge import (
NON_BLOCKING_ROW_ISSUE_CODES,
merge_line_field_supplement,
)
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchResult,
@@ -379,6 +384,9 @@ def _coordinate_profile_rows(
# 的坐标、起行字段与行重建结果裁决,不能仅依赖历史 page_scope 自动建单。
if region.region_id not in runtime_region_ids:
continue
# 补充表不参与主明细重建,避免 COO 等副表进入 matches / multiple_business_tables。
if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
continue
# A continuation page may carry column headers only; it is not a data layout.
if not region.line_layouts:
continue
@@ -469,6 +477,239 @@ def _coordinate_profile_rows(
return rows
def _pick_overlapping_layout_table(
*,
layout_tables: list[Any],
page_no: int,
region_relative: dict[str, Any],
page_size: dict[str, Any],
reference_page_frame: dict[str, Any] | None = None,
coordinate_transform: dict[str, Any] | None = None,
) -> tuple[str | None, dict[str, float] | None]:
"""
在同页 layout.tables 中选取与补充表相对区重叠的物理表。
核心逻辑:将相对区投影为页绝对框后与 MinerU 表求交,取纵向重叠面积最大者。
用于样本仅 1 行 COO 时,盲测多行仍能纵向扩到整张物理表读 glyph。
Args:
layout_tables: layout.tables 列表。
page_no: 当前页号。
region_relative: 补充表区相对 bbox。
page_size: 当前页宽高。
reference_page_frame: 可选参考页框;缺省用 page_size。
coordinate_transform: 可选坐标变换。
Returns:
(table_id, 绝对 bbox) 或 (None, None)。
"""
projected = apply_coordinate_transform_to_region(
region_relative, coordinate_transform=coordinate_transform,
)
if projected is None:
return None, None
try:
ref_w = float(reference_page_frame['width']) if reference_page_frame is not None else float(page_size['width'])
ref_h = float(reference_page_frame['height']) if reference_page_frame is not None else float(page_size['height'])
region_bbox = {
'x0': float(projected['x0']) * ref_w,
'y0': float(projected['y0']) * ref_h,
'x1': float(projected['x1']) * ref_w,
'y1': float(projected['y1']) * ref_h,
}
except (KeyError, TypeError, ValueError):
return None, None
best_id: str | None = None
best_bbox: dict[str, float] | None = None
best_overlap = 0.0
for item in layout_tables:
if not isinstance(item, dict):
continue
if int(item.get('page_no') or 1) != int(page_no):
continue
bbox = item.get('bbox')
if not isinstance(bbox, dict):
continue
try:
x0, y0, x1, y1 = float(bbox['x0']), float(bbox['y0']), float(bbox['x1']), float(bbox['y1'])
except (KeyError, TypeError, ValueError):
continue
if not (x0 < region_bbox['x1'] and x1 > region_bbox['x0'] and y0 < region_bbox['y1'] and y1 > region_bbox['y0']):
continue
overlap_h = max(0.0, min(x1, region_bbox['x1']) - max(x0, region_bbox['x0']))
overlap_v = max(0.0, min(y1, region_bbox['y1']) - max(y0, region_bbox['y0']))
overlap_area = overlap_h * overlap_v
if overlap_area <= best_overlap:
continue
best_overlap = overlap_area
best_id = str(item.get('table_id') or '') or None
best_bbox = {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
return best_id, best_bbox
def _reconstruct_line_field_supplement_rows(
*,
raw_profile: dict[str, Any],
layout: dict[str, Any],
schema_fields: dict[str, dict[str, Any]],
coordinate_transform: dict[str, Any] | None = None,
) -> tuple[list[dict[str, Any]], str | None]:
"""
从 Profile 的 line_field_supplement 表区按页坐标重建补充行(如 COO)。
核心逻辑:不把补充表当作业务表命中源;在补充区相对框内读 page_glyphs。
若同页存在与标注区重叠的 MinerU 物理表,则用其 bbox 纵向扩展字符范围
(样本单行 / 盲测多行时仍能读到整张 COO)。再以 with_strategy 取最佳努力行供 LN 合并。
Returns:
(workflow 形态行列表, line_start_field_code 或 None)
"""
try:
profile = _frozen_coordinate_profile(raw_profile)
except (TypeError, ValueError, ValidationError):
return [], None
supplement_regions = [
region for region in profile.table_regions
if str(getattr(region, 'region_role', None) or '') == 'line_field_supplement'
and region.line_layouts
]
if not supplement_regions:
return [], None
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
layout_tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
rows: list[dict[str, Any]] = []
line_start = None
for region in supplement_regions:
line_start = region.line_start_field_code or 'customer_po_line_no'
runtime_ids = set(select_runtime_region_ids(
table_regions=[_coordinate_object_mapping(item) for item in profile.table_regions],
page_no=int(region.page_no or 1) if region.page_scope == 'exact_page' else 1,
))
# exact_page 补充区按其页;all_pages/first_page 扫有 glyph 的页。
if region.page_scope == 'exact_page':
candidate_pages = [int(region.page_no or 1)]
else:
candidate_pages = sorted(
int(page_no) for page_no in page_glyphs
if str(page_no).isdigit() and isinstance(page_glyphs.get(str(page_no)), list)
)
if region.page_scope == 'first_page':
candidate_pages = [page for page in candidate_pages if page == 1] or [1]
for page_no in candidate_pages:
if region.page_scope == 'exact_page' and region.region_id not in runtime_ids and str(page_no) not in {str(region.page_no)}:
continue
page_size = pages.get(str(page_no))
characters = page_glyphs.get(str(page_no))
if not isinstance(page_size, dict) or not isinstance(characters, list) or not characters:
continue
try:
page_bbox = {
'x0': 0, 'y0': 0,
'x1': float(page_size['width']), 'y1': float(page_size['height']),
}
except (KeyError, TypeError, ValueError):
continue
reference_page_frames = getattr(profile, 'reference_page_frames', {})
reference_page_frame = (
reference_page_frames.get(page_no)
if isinstance(reference_page_frames, dict) else None
)
reconstruction_page_bbox = (
{
'x0': 0, 'y0': 0,
'x1': reference_page_frame.width, 'y1': reference_page_frame.height,
}
if reference_page_frame is not None else page_bbox
)
relative_region = _coordinate_region_mapping(region.region)
if relative_region is None:
continue
ref_frame_mapping = (
_coordinate_object_mapping(reference_page_frame)
if reference_page_frame is not None else None
)
# [STEP 1] 样本单行标注的相对框常盖不住盲测多行;重叠物理表纵向扩 glyph。
overlap_table_id, overlap_table_bbox = _pick_overlapping_layout_table(
layout_tables=layout_tables,
page_no=page_no,
region_relative=_coordinate_object_mapping(region.region),
page_size=page_size,
reference_page_frame=ref_frame_mapping,
coordinate_transform=coordinate_transform,
)
filtered, _ = coordinate_profile_character_candidates(
table_region=_coordinate_object_mapping(region.region),
page_size=page_size,
reference_page_frame=ref_frame_mapping,
page_characters=characters,
table_characters=None,
raw_table_bbox=overlap_table_bbox,
table_id=overlap_table_id,
page_no=page_no,
coordinate_transform=coordinate_transform,
allow_table_fallback=False,
)
if not isinstance(filtered, list) or not filtered:
continue
chosen_rows, _strategy = reconstruct_coordinate_profile_rows_with_strategy(
characters=[item for item in filtered if isinstance(item, dict)],
table_bbox=reconstruction_page_bbox,
line_layouts=[_coordinate_object_mapping(item) for item in region.line_layouts],
table_region=relative_region,
termination_rules=[_coordinate_object_mapping(item) for item in region.termination_rules],
exclusion_regions=reconstruction_exclusion_regions(_coordinate_object_mapping(region)),
line_start_field_code=region.line_start_field_code,
schema_field_metadata=list(schema_fields.values()),
coordinate_transform=coordinate_transform,
page_no=page_no,
)
for reconstructed in chosen_rows:
values = [
{'field_code': code, 'value': str(raw or '')}
for code, raw in reconstructed.fields.items()
]
rows.append({
'fields': values,
'issues': list(reconstructed.issues),
'page_no': page_no,
})
return rows, line_start
def _apply_line_field_supplement(
*,
raw_profile: dict[str, Any],
layout: dict[str, Any],
parsed_rows: list[dict[str, Any]],
schema_fields: dict[str, dict[str, Any]],
coordinate_transform: dict[str, Any] | None = None,
) -> tuple[list[dict[str, Any]], list[str]]:
"""主表明细重建后,按 LN 合并 line_field_supplement 料号。"""
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
raw_profile=raw_profile,
layout=layout,
schema_fields=schema_fields,
coordinate_transform=coordinate_transform,
)
if not supplement_rows:
return parsed_rows, []
merged, reasons = merge_line_field_supplement(
parsed_rows,
supplement_rows,
line_start_field_code=line_start or 'customer_po_line_no',
)
for row in merged:
issue_list = row.get('issues') if isinstance(row.get('issues'), list) else []
if any(
code in {'line_field_supplement_conflict', 'line_field_supplement_ln_ambiguous'}
for code in issue_list
):
row['status'] = 'needs_review'
return merged, reasons
def _selected_coordinate_transform(
*, profile_match: dict[str, Any], raw_profile: dict[str, Any],
) -> dict[str, Any] | None:
@@ -620,10 +861,11 @@ def _physical_table_targets_profile_region(
):
return False
return True
# [STEP 2] 仅含 line_layouts 的明细区才是重建目标;纯表头壳直接跳过。
# [STEP 2] 仅含 line_layouts 的业务明细区才是重建目标;纯表头壳与补充表直接跳过。
active_regions = [
region for region in page_regions
if region.get('line_layouts')
and str(region.get('region_role') or 'business_lines') != 'line_field_supplement'
]
if not active_regions:
return False
@@ -1042,6 +1284,18 @@ def _profile_table_candidates(
issues.append('order_profile_multiple_matches')
continue
raw_profile, parsed = matches[0]
coordinate_transform = _selected_coordinate_transform(
profile_match=profile_match, raw_profile=raw_profile,
)
parsed, supplement_reasons = _apply_line_field_supplement(
raw_profile=raw_profile,
layout=layout,
parsed_rows=parsed,
schema_fields=schema_fields,
coordinate_transform=coordinate_transform,
)
if any(code.endswith('_conflict') or code.endswith('_ambiguous') for code in supplement_reasons):
issues.extend(supplement_reasons)
reservation_region = _reservation_region_candidates(raw_profile=raw_profile, layout=layout)
result_tables.append({
'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'),
@@ -1052,6 +1306,7 @@ def _profile_table_candidates(
'page_no': int(raw_table.get('page_no') or 1),
'auto_create_approved': bool(raw_profile.get('auto_create_approved')),
'rows': parsed,
'line_field_supplement_reasons': list(supplement_reasons),
'reservation_region_candidates': reservation_region['candidates'],
'reservation_region_reason': reservation_region['reason'],
'runtime_parse_strategy': {
@@ -1925,7 +2180,13 @@ def _build_approved_profile_order_result(
# Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。
if not isinstance(row, dict) or row.get('status') == 'deleted':
continue
if row.get('status') != 'parsed' or row.get('issues'):
# [STEP] 忽略成功补料号等非阻塞审计码;仅真实缺陷才触发 row_needs_review。
raw_issues = row.get('issues') if isinstance(row.get('issues'), list) else []
blocking_issues = [
code for code in raw_issues
if str(code or '').strip() and str(code) not in NON_BLOCKING_ROW_ISSUE_CODES
]
if row.get('status') != 'parsed' or blocking_issues:
if not allow_manual_review:
return None, 'row_needs_review'
has_review_rows = True
@@ -5,7 +5,7 @@ Reservation ID 专用证据区域解析器。
并投影到验证证据 / 订单归属契约。
依赖:reservation_id 格式校验、coordinate_region_text 视觉行序。
逻辑:reservation_id_region 仅作启用标记;画布预览、盲测、正式解析共用本模块的
锚点扫描与 apply/project,不再按保存矩形截取正式值。
锚点扫描与 apply/project,不再按保存矩形截取正式值;行号含 line# / L# / LN#。
"""
from __future__ import annotations
@@ -19,7 +19,15 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
_ID_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)")
_LINE_RE = re.compile(r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b|\bfor\s+line\s*#?\s*(\d+)\b", re.I)
# 行号写法:Line 1 / line#1 / for line#1 / Hyve 缩写 L#1、LN#1。
_LINE_RE = re.compile(
r"(?:"
r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b"
r"|\bfor\s+line\s*#?\s*(\d+)\b"
r"|\bl(?:n)?\s*#\s*(\d+)\b"
r")",
re.I,
)
_RESERVATION_LABEL_RE = re.compile(r"\breservation\b\s*(?:id)?\s*(?:#|:|-)?", re.I)
_VENDOR_COMMENTS_HEADING_RE = re.compile(r'^\s*vendor\s+comments?\b', re.I)
_TERMS_AND_CONDITIONS_HEADING_RE = re.compile(
@@ -48,7 +56,11 @@ class ReservationRegionApplication:
def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidate]:
"""从区域原文提取候选;有行号归明细,无行号归订单头。"""
"""从区域原文提取候选;有行号归明细,无行号归订单头。
核心逻辑:同行须含 Reservation 标签;行号支持 ``line#1`` / ``for line#1`` /
``L#1`` / ``LN#1`` 等写法,命中后 scope=line,禁止误写入订单头。
"""
candidates: list[ReservationRegionCandidate] = []
for raw_line in (str(text or '').splitlines() or [str(text or '')]):
line = raw_line.strip()
@@ -63,7 +75,8 @@ def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidat
line_match = _LINE_RE.search(line)
line_no = None
if line_match:
line_no = int(line_match.group(1) or line_match.group(2))
captured = next((group for group in line_match.groups() if group is not None), None)
line_no = int(captured) if captured is not None else None
scope = 'line' if line_no is not None else 'header'
status = 'mapped' if line_no is not None else 'header'
for value in dict.fromkeys(ids):
+51
View File
@@ -323,6 +323,57 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
assert not (failed_dir / trigger_path.name).exists()
def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tmp_path):
"""配置测试无订单 Attempt/Gate 身份:不得 trigger_identity_invalid,须回调专用 ready。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
failed_dir = trigger_dir / "failed"
trigger_dir.mkdir()
drop_dir.mkdir()
run_no = "CONFIG-DSV360_AWSBI_BYAWSPRD01-20260909020428918536"
trigger_path = trigger_dir / f"inventory_export_batch_{run_no}.json"
# 与 inventory_configuration_test.start_test_export 写入形状一致:
# trigger_type=configuration_test,无 task_no / gate_id / execution_id 等生产身份。
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"{run_no}:batch:C1",
"batch_run_no": run_no,
"run_no": run_no,
"trigger_type": "configuration_test",
"configuration_test_run_id": 42,
"requested_at": "2026-09-09T02:04:28.918536",
"inventory_sources": [{
"source_code": "DSV360_AWSBI_BYAWSPRD01",
"connector_type": "dbs",
"worker_connector_type": "dsv360",
"warehouse_id": "BYAWSPRD01",
"login_url": "https://s360.dbschenker.com/",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {},
"parameters": [],
"query": {},
"credential_envelope": {},
}],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
assert not any(body.get("error_code") == "trigger_identity_invalid" for _, body in callbacks)
ready = next(body for path, body in callbacks if path.endswith("/inventory-configuration-test-ready"))
assert ready["run_no"] == run_no
assert ready["status"] == "success"
assert ready.get("file_path")
assert not any(path.endswith("/inventory-batch-ready") for path, _ in callbacks)
assert (processed_dir / trigger_path.name).is_file()
assert not (failed_dir / trigger_path.name).exists()
def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup(monkeypatch, tmp_path):
"""Ctrl+C 中断导出时不回调或移动 trigger,且清理异常不能阻止停止 Playwright。"""
worker = _load_freight_rpa_worker()
@@ -0,0 +1,309 @@
"""
tests/test_line_field_supplement_merge.py
用途:覆盖同文档 COO/明细字段补充表按 LN 合并的契约。
依赖:line_field_supplement_merge、order_profile.TableRegionProfile、
order_extraction_workflow._pick_overlapping_layout_table。
逻辑:断言空补、前缀补全、冲突不覆盖、LN 歧义/缺失与禁止改 qty;
成功补齐仅表级 reasons、不写入 issues;以及补充区与 MinerU 表重叠时的物理表选取。
"""
from __future__ import annotations
import pytest
from pydantic import ValidationError
from app.services.shipping_notice.document_layout.order_profile import TableRegionProfile
from app.services.shipping_notice.line_field_supplement_merge import (
REASON_APPLIED,
REASON_CONFLICT,
REASON_LN_AMBIGUOUS,
merge_line_field_supplement,
normalize_line_start_key,
normalize_part_value,
)
from app.services.shipping_notice.order_extraction_workflow import (
_pick_overlapping_layout_table,
)
def test_normalize_line_start_and_part_values():
"""关键断言:行号去前导零对齐;料号仅去空白。"""
assert normalize_line_start_key(' 02 ') == '2'
assert normalize_line_start_key('00010') == '10'
assert normalize_part_value('WTP-B3- A08') == 'WTP-B3-A08'
def test_merge_fills_empty_and_prefix_without_touching_qty():
"""空值直补、截断前缀补全,数量保持主表原值。"""
main = [
{'customer_po_line_no': '1', 'customer_part_number': '', 'part_number': 'B3-', 'qty': '30'},
{
'customer_po_line_no': '2',
'customer_part_number': 'WTP-B3-',
'part_number': '',
'qty': '3',
},
]
supplement = [
{
'customer_po_line_no': '1',
'customer_part_number': 'WTP-B3-A08AR11000001',
'part_number': 'B3-A08AR11000001',
},
{
'customer_po_line_no': '2',
'customer_part_number': 'WTP-B3-A08AR10000017-A6',
'part_number': 'B3-A08AR10000017-A6',
},
]
merged, reasons = merge_line_field_supplement(main, supplement)
assert merged[0]['customer_part_number'] == 'WTP-B3-A08AR11000001'
assert merged[0]['part_number'] == 'B3-A08AR11000001'
assert merged[0]['qty'] == '30'
assert merged[1]['customer_part_number'] == 'WTP-B3-A08AR10000017-A6'
assert merged[1]['part_number'] == 'B3-A08AR10000017-A6'
assert merged[1]['qty'] == '3'
assert REASON_APPLIED in reasons
assert REASON_CONFLICT not in reasons
# 关键断言:成功补齐不得进入行 issues,否则正式建单会被误判为 row_needs_review。
assert REASON_APPLIED not in (merged[0].get('issues') or [])
assert REASON_APPLIED not in (merged[1].get('issues') or [])
def test_merge_conflict_does_not_overwrite():
"""两边完整且不同时保留主表并记冲突。"""
main = [{'customer_po_line_no': '1', 'part_number': 'MAIN-ONLY', 'qty': '1'}]
supplement = [{'customer_po_line_no': '1', 'part_number': 'COO-OTHER'}]
merged, reasons = merge_line_field_supplement(main, supplement)
assert merged[0]['part_number'] == 'MAIN-ONLY'
assert merged[0]['qty'] == '1'
assert REASON_CONFLICT in reasons
assert REASON_CONFLICT in merged[0]['issues']
def test_merge_skips_ambiguous_line_numbers():
"""主表或补充表 LN 重复时不补该键。"""
main = [
{'customer_po_line_no': '1', 'part_number': ''},
{'customer_po_line_no': '1', 'part_number': ''},
]
supplement = [{'customer_po_line_no': '1', 'part_number': 'B3-A08'}]
merged, reasons = merge_line_field_supplement(main, supplement)
assert merged[0]['part_number'] == ''
assert merged[1]['part_number'] == ''
assert REASON_LN_AMBIGUOUS in reasons
def test_merge_workflow_shaped_rows():
"""workflow fields 列表形态同样可补齐。"""
main = [{
'status': 'needs_review',
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-'},
{'field_code': 'qty', 'value': '3'},
],
'issues': [],
}]
supplement = [{
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'},
{'field_code': 'part_number', 'value': 'B3-A08AR10000017-A6'},
],
}]
merged, reasons = merge_line_field_supplement(main, supplement)
values = {item['field_code']: item['value'] for item in merged[0]['fields']}
assert values['customer_part_number'] == 'WTP-B3-A08AR10000017-A6'
assert values['part_number'] == 'B3-A08AR10000017-A6'
assert values['qty'] == '3'
assert REASON_APPLIED in reasons
assert REASON_APPLIED not in (merged[0].get('issues') or [])
def test_apply_line_field_supplement_uses_reconstructed_coo_rows(monkeypatch):
"""关键断言:正式路径在主表截断后用补充表重建行补全料号。"""
from app.services.shipping_notice import order_extraction_workflow as workflow
def _fake_reconstruct(**_kwargs):
return (
[{
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'},
{'field_code': 'part_number', 'value': 'B3-A08AR10000017-A6'},
],
'issues': [],
}],
'customer_po_line_no',
)
monkeypatch.setattr(workflow, '_reconstruct_line_field_supplement_rows', _fake_reconstruct)
parsed = [{
'status': 'parsed',
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-'},
{'field_code': 'part_number', 'value': ''},
{'field_code': 'qty', 'value': '3'},
],
'issues': [],
}]
merged, reasons = workflow._apply_line_field_supplement(
raw_profile={'definition': {}},
layout={},
parsed_rows=parsed,
schema_fields={},
)
values = {item['field_code']: item['value'] for item in merged[0]['fields']}
assert values['customer_part_number'] == 'WTP-B3-A08AR10000017-A6'
assert values['part_number'] == 'B3-A08AR10000017-A6'
assert values['qty'] == '3'
assert REASON_APPLIED in reasons
def test_project_supplement_onto_validation_evidence():
"""关键断言:验证证据 lines 可被 COO 补齐且保留其它列。"""
from app.services.shipping_notice.line_field_supplement_merge import (
project_line_field_supplement_onto_validation_evidence,
)
evidence = {
'header_fields': [],
'lines': [{
'row_index': 0,
'fields': [
{'field_code': 'customer_po_line_no', 'raw_value': '2', 'normalized_value': '2', 'status': 'passed', 'issues': []},
{'field_code': 'customer_part_number', 'raw_value': 'WTP-B3-', 'normalized_value': 'WTP-B3-', 'status': 'passed', 'issues': []},
{'field_code': 'qty', 'raw_value': '3', 'normalized_value': '3', 'status': 'passed', 'issues': []},
],
}],
'cross_checks': {},
}
updated, reasons = project_line_field_supplement_onto_validation_evidence(
evidence,
supplement_rows=[{
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'},
],
}],
)
part = next(item for item in updated['lines'][0]['fields'] if item['field_code'] == 'customer_part_number')
qty = next(item for item in updated['lines'][0]['fields'] if item['field_code'] == 'qty')
assert part['raw_value'] == 'WTP-B3-A08AR10000017-A6'
assert qty['raw_value'] == '3'
assert REASON_APPLIED in reasons
def test_line_field_supplement_region_rejects_non_part_bindings():
"""补充表绑定数量等业务字段必须失败。"""
payload = {
'region_id': 'coo_lines',
'page_scope': 'exact_page',
'page_no': 1,
'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9},
'region_role': 'line_field_supplement',
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{
'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line',
'region': {'x0': .2, 'y0': 0, 'x1': .4, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
],
}],
}
with pytest.raises(ValidationError, match='line_field_supplement may only bind'):
TableRegionProfile.model_validate(payload)
def test_line_field_supplement_region_accepts_part_bindings():
"""补充表仅绑 LN + 料号字段可通过。"""
region = TableRegionProfile.model_validate({
'region_id': 'coo_lines',
'page_scope': 'exact_page',
'page_no': 1,
'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9},
'region_role': 'line_field_supplement',
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{
'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'cpn', 'field_code': 'customer_part_number', 'scope': 'line',
'region': {'x0': .2, 'y0': 0, 'x1': .6, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'pn', 'field_code': 'part_number', 'scope': 'line',
'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
],
}],
})
assert region.region_role == 'line_field_supplement'
def test_pick_overlapping_layout_table_prefers_max_vertical_overlap():
"""关键断言:同页重叠表取纵向重叠面积最大者;无重叠返回空。"""
page_size = {'width': 100.0, 'height': 100.0}
region = {'x0': 0.05, 'y0': 0.67, 'x1': 0.9, 'y1': 0.70}
tables = [
{
'table_id': 'header-ish',
'page_no': 1,
'bbox': {'x0': 5.0, 'y0': 10.0, 'x1': 90.0, 'y1': 40.0},
},
{
'table_id': 'coo-table',
'page_no': 1,
'bbox': {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0},
},
{
'table_id': 'other-page',
'page_no': 2,
'bbox': {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0},
},
]
table_id, bbox = _pick_overlapping_layout_table(
layout_tables=tables,
page_no=1,
region_relative=region,
page_size=page_size,
)
assert table_id == 'coo-table'
assert bbox == {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0}
empty_id, empty_bbox = _pick_overlapping_layout_table(
layout_tables=tables,
page_no=1,
region_relative={'x0': 0.05, 'y0': 0.90, 'x1': 0.9, 'y1': 0.95},
page_size=page_size,
)
assert empty_id is None
assert empty_bbox is None
@@ -64,6 +64,18 @@ def _two_page_layout() -> dict:
}
def test_approved_pdf_ignores_line_field_supplement_applied_issue():
"""关键断言:COO 成功补齐的审计码不得触发 row_needs_review。"""
row = _row('PO-1', 'P-1')
row['issues'] = ['line_field_supplement_applied']
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=DEFINITION, table={'rows': [row]},
)
assert reason is None
assert len(orders or []) == 1
def test_approved_pdf_rejects_multiple_pos_in_one_pdf():
"""同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。"""
orders, reason = _build_approved_profile_order_result(
@@ -12,6 +12,7 @@ import json
import zipfile
from io import BytesIO
from pathlib import Path
from urllib.parse import quote
import pytest
@@ -27,8 +28,10 @@ from app.services.schedule.scheduler_service import (
from app.services.schedule.shipping_inventory_rpa_archive import (
inventory_raw_zip_available_from_summary,
inventory_raw_zip_download_name,
inventory_rpa_result_excel_name,
persist_inventory_rpa_raw_zip_archive,
resolve_inventory_raw_zip_download,
_build_zip_entry_name,
)
from tests.conftest import parse_api_error
from tests.test_shipping_notice_inventory_schedule import _make_inventory_schedule_task
@@ -160,10 +163,12 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p
with zipfile.ZipFile(zip_path) as archive:
names = archive.namelist()
assert "manifest.json" in names
assert any(name.endswith(".xlsx") for name in names)
xlsx_names = [name for name in names if name.endswith(".xlsx")]
assert xlsx_names == ["001_DSV360_AWSBI_BYAWSCMH01.xlsx"]
manifest = json.loads(archive.read("manifest.json").decode("utf-8"))
assert manifest["run_no"] == run.run_no
assert manifest["files"][0]["inventory_file_no"] == "SIF-20260710-ARCH01"
assert manifest["files"][0]["file_name"] == "001_DSV360_AWSBI_BYAWSCMH01.xlsx"
def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
@@ -230,7 +235,9 @@ def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path)
zip_path, file_name = resolve_inventory_raw_zip_download(run)
assert zip_path.is_file()
assert file_name == inventory_raw_zip_download_name(run.run_no)
assert file_name == inventory_raw_zip_download_name(run)
assert file_name.endswith("-库存.zip")
assert file_name.startswith("库存RPA-")
def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app):
@@ -431,7 +438,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
task.notify_enabled = True
task.notify_user_ids_json = [user.id]
run.excel_file_data = b"schedule excel"
run.excel_file_name = "schedule.xlsx"
run.excel_file_name = inventory_rpa_result_excel_name(run)
db.session.commit()
_notify_schedule_run_wecom(task, run)
@@ -442,8 +449,8 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
assert "run_id=" in captured[0]
assert "raw_zip=1" in captured[0]
assert "download=inventory_raw_zip" in captured[0]
assert "schedule.xlsx" in media_uploads
assert inventory_raw_zip_download_name("RUN-ARCH-NOTIFY-1") in media_uploads
assert any(name.endswith("-结果.xlsx") for name in media_uploads)
assert any(name.endswith("-库存.zip") for name in media_uploads)
assert file_sends == ["media-1", "media-2"]
@@ -471,7 +478,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
admin_jwt_headers,
tmp_path,
):
"""admin 鉴权通过时应返回 application/zip 且文件名与 run_no 一致。"""
"""admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。"""
archive_dir = tmp_path / "inventory_archives"
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
xlsx = tmp_path / "inventory.xlsx"
@@ -497,7 +504,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
run.response_summary_json = persist_inventory_rpa_raw_zip_archive(run)
db.session.commit()
run_id = run.id
expected_name = inventory_raw_zip_download_name(run.run_no)
expected_name = inventory_raw_zip_download_name(run)
res = client.get(
f'/api/admin/schedule-runs/{run_id}/inventory-raw-zip',
@@ -505,12 +512,36 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
)
assert res.status_code == 200
assert res.mimetype == 'application/zip'
assert expected_name in res.headers.get('Content-Disposition', '')
# Werkzeug ASCII filename 会剥掉中文;真实下载名在 filename*=UTF-8'' 段。
disposition = res.headers.get('Content-Disposition', '')
assert quote(expected_name) in disposition
with zipfile.ZipFile(BytesIO(res.data)) as archive:
names = archive.namelist()
assert 'manifest.json' in names
assert any(name.endswith('.xlsx') for name in names)
assert '001_DSV360_AWSBI_BYAWSCMH01.xlsx' in names
def test_build_zip_entry_name_prefers_source_code():
"""包内条目优先 source_code;无 source 时才回退仓码。"""
assert _build_zip_entry_name(
index=2,
source_code="DSV360_AWSBI_BYAWSCMH01",
warehouse_id="BYAWSCMH01",
original_suffix=".xlsx",
) == "002_DSV360_AWSBI_BYAWSCMH01.xlsx"
assert _build_zip_entry_name(
index=1,
source_code="CRANE_FOOTPRINT",
warehouse_id="unknown",
original_suffix=".xlsx",
) == "001_CRANE_FOOTPRINT.xlsx"
assert _build_zip_entry_name(
index=3,
source_code="",
warehouse_id="AWSSG",
original_suffix=".xlsx",
) == "003_AWSSG.xlsx"
def test_get_inventory_raw_zip_returns_404_when_archive_unavailable(
@@ -84,6 +84,18 @@ def test_reservation_region_maps_line_when_reservation_label_and_line_number_are
}]
def test_reservation_region_maps_hyve_l_hash_abbreviation_to_line():
"""关键断言:Hyve ``Reservation L#1: 1000153133`` 必须归明细行,不得写入单头。"""
assert extract_reservation_from_region_text("Reservation L#1: 1000153133") == [{
'value': '1000153133', 'line_no': 1, 'scope': 'line',
'raw_text': 'Reservation L#1: 1000153133', 'status': 'mapped',
}]
assert extract_reservation_from_region_text("Reservation LN#2: 1000153134") == [{
'value': '1000153134', 'line_no': 2, 'scope': 'line',
'raw_text': 'Reservation LN#2: 1000153134', 'status': 'mapped',
}]
def test_reservation_region_assigns_reservation_without_line_to_header():
"""无行号 Reservation 是整单事实,写 Header 后由既有回退规则应用给全部明细。"""
assert extract_reservation_from_region_text("MDW hub order.Reservation#33008") == [{
@@ -836,6 +836,89 @@ def test_near_twin_header_discriminator_makes_unique_match():
assert 'profile_header_discriminator_conflict' in mx_on_tw.reason_codes
def test_single_logical_header_wrap_pollution_sanitized_for_identity():
"""单逻辑表头旧签名含折行副标签时,须并入所属列后再比身份(文案保留)。"""
from app.services.shipping_notice.document_layout.coordinate_region_text import (
merge_header_identity_wrap_tokens,
)
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_header_discriminator_atoms_conflict,
_signature_identity_header_tokens,
)
# Hyve 旧签名:主行 + 折行副标签 Vendor Item# / Date(centers 回退)。
signature = {
'table_patterns': [{
'header_row_count': 1,
'header_tokens': [
'LN', 'Quantity', 'Part', 'Number', 'Description',
'Requested Arrival', 'Unit', 'Price', 'Extension', 'Vendor Item#', 'Date',
],
'column_centers': [
0.0727, 0.1372, 0.2144, 0.2542, 0.3671, 0.561, 0.6532, 0.6841, 0.801,
0.2418, 0.5217,
],
}],
}
identity = _signature_identity_header_tokens(signature)
joined = ' '.join(identity)
# 关键断言:副标签文案仍在;不再作为独立尾列。
assert 'Vendor Item#' in joined
assert 'Date' in joined
assert identity[-1] != 'Date'
assert identity[-1] != 'Vendor Item#'
assert len(identity) == 9
observed_tokens, observed_centers, _ = merge_header_identity_wrap_tokens(
[
'ln', 'quantity', 'part', 'number', 'description',
'requested arrival', 'unit', 'price', 'extension', 'vendor item#', 'date',
],
[
0.0727, 0.1372, 0.2144, 0.2542, 0.3671, 0.561, 0.6532, 0.6841, 0.801,
0.2418, 0.5217,
],
)
assert _header_discriminator_atoms_conflict(
signature=signature,
observed={'header_tokens': observed_tokens},
) is False
# 近亲缺 ECCN 仍须硬杀。
twin_signature = {
'table_patterns': [{
'header_row_count': 1,
'header_tokens': [
'Item', 'Parts', 'No', 'ECCN', 'Description', 'REV', 'UNIT', 'QTY',
],
'column_centers': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8],
}],
}
twin_observed = {
'header_tokens': ['Item', 'Parts', 'No', 'Description', 'REV', 'UNIT', 'QTY'],
}
assert _header_discriminator_atoms_conflict(signature=twin_signature, observed=twin_observed) is True
def test_multi_row_header_signature_keeps_secondary_row_identity():
"""真多行表头(header_row_count>1)不得做折行合并。"""
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_signature_identity_header_tokens,
)
signature = {
'table_patterns': [{
'header_row_count': 3,
'header_tokens': ['Item', 'Qty', 'Price', 'Amount', 'PR_Number'],
# 故意造 x 回退:多行正式表头不得合并掉 PR_Number。
'column_centers': [0.1, 0.3, 0.5, 0.7, 0.2],
}],
}
assert _signature_identity_header_tokens(signature) == [
'Item', 'Qty', 'Price', 'Amount', 'PR_Number',
]
def test_required_anchors_skip_header_atom_hard_mutex():
"""已配置必选锚点时,表头原子差异不得再硬杀;身份交给锚点门禁。"""
mx_header = 'Item Parts No Description REV UNIT QTY Delivery Date Unit Total Price'
@@ -166,6 +166,39 @@ def test_parse_validation_accepts_month_day_year_date_format():
assert result['metrics']['type_issue_count'] == 0
def test_parse_validation_accepts_two_digit_year_dates():
"""关键断言:MM/DD/YY 通过类型 sanity,不得误杀 Hyve 等 PO 日期。"""
profile = _minimal_profile_snapshot(line_regions=[
{
'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0.05, 'y0': 0.4, 'x1': 0.09, 'y1': 0.5},
'allowed_sources': ['pdf_coordinate'],
'target_fields': [{
'scope': 'line', 'field_code': 'customer_po_line_no', 'field_id': 'line-id',
}],
},
{
'field_id': 'date-id', 'field_code': 'requested_receipt_date', 'scope': 'line',
'region': {'x0': 0.10, 'y0': 0.4, 'x1': 0.6, 'y1': 0.5},
'allowed_sources': ['pdf_coordinate'],
'target_fields': [{
'scope': 'line', 'field_code': 'requested_receipt_date', 'field_id': 'date-id',
}],
},
])
result = validate_profile_parse_candidate(
profile_snapshot=profile,
layout=_layout_with_line_text('06/16/26'),
definition={'fields': [{
'field_code': 'requested_receipt_date', 'enabled': True, 'value_type': 'date',
}]},
)
assert 'profile_parse_type_sanity_failed' not in result['reason_codes']
assert result['metrics'].get('type_issue_count', 0) == 0
def _layout_with_shifted_line_text(*, text: str = '001 PART-A 10') -> dict:
"""构造明细区文字被纵向位移到冻结字段带之下的 layout。
@@ -182,3 +182,98 @@ def test_signature_relation_graph_uses_anchor_text_contract():
snapshot = build_layout_signature(definition=definition, sample_layouts=[_sample_layout()])
assert isinstance(snapshot['signature']['field_relation_graph'], list)
def test_single_logical_header_wrap_excludes_secondary_visual_line_from_identity():
"""逻辑一行表头框住折行时,副标签并入所属列,不得拆成新身份列。"""
definition = _minimal_definition()
# 表头框盖住主行 + 折行副标签(与 Hyve 标注同构)。
definition['table_regions'][0]['header_layouts'][0]['region'] = {
'x0': 0, 'y0': 0.20, 'x1': 1, 'y1': 0.32,
}
page_h = 280.0
main_y0, main_y1 = 60.0, 72.0
wrap_y0, wrap_y1 = 76.0, 88.0
glyphs = []
# 主行:LN Quantity Part
x = 10.0
for word in ('LN', 'Quantity', 'Part'):
for char in word:
glyphs.append({
'text': char,
'bbox': {'x0': x, 'y0': main_y0, 'x1': x + 3, 'y1': main_y1},
'boundary_before': 'none',
})
x += 3.5
x += 8
# 折行副标签:Vendor(落在 Part 列下方)
x = 40.0
for char in 'Vendor':
glyphs.append({
'text': char,
'bbox': {'x0': x, 'y0': wrap_y0, 'x1': x + 3, 'y1': wrap_y1},
'boundary_before': 'none',
})
x += 3.5
layout = {
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 200, 'y1': 200}}],
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': page_h}},
'page_glyphs': {'1': glyphs},
'tables': {'table-1': glyphs},
},
}
pattern = build_layout_signature(definition=definition, sample_layouts=[layout])['signature']['table_patterns'][0]
tokens = [str(item) for item in pattern['header_tokens']]
assert pattern['header_row_count'] == 1
joined = ' '.join(tokens).casefold()
# 关键断言:Vendor 文案保留并入所属列,不得作为独立尾列。
assert 'ln' in joined
assert 'quantity' in joined
assert 'part' in joined
assert 'vendor' in joined
assert tokens[-1].casefold() != 'vendor'
assert len(tokens) == len(pattern['column_centers'])
assert len(tokens) <= 3
def test_multi_header_layouts_keep_both_visual_rows_in_identity():
"""多个 header_layout(真多行表头)须保留各行身份 token,不做折行合并。"""
definition = _minimal_definition()
definition['table_regions'][0]['header_layouts'] = [
{
'layout_id': 'header_r1', 'region': {'x0': 0, 'y0': 0.20, 'x1': 1, 'y1': 0.26},
'field_regions': [{
'field_id': 'hdr-item', 'field_code': 'item_no', 'scope': 'header',
'region': {'x0': 0.05, 'y0': 0.21, 'x1': 0.2, 'y1': 0.25},
'allowed_sources': ['pdf_coordinate'],
}],
},
{
'layout_id': 'header_r2', 'region': {'x0': 0, 'y0': 0.27, 'x1': 1, 'y1': 0.33},
'field_regions': [{
'field_id': 'hdr-pr', 'field_code': 'pr_number', 'scope': 'header',
'region': {'x0': 0.05, 'y0': 0.28, 'x1': 0.3, 'y1': 0.32},
'allowed_sources': ['pdf_coordinate'],
}],
},
]
glyphs = []
for index, char in enumerate('ITEM'):
glyphs.append({'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 60, 'x1': 13 + index * 4, 'y1': 72}})
for index, char in enumerate('PRNO'):
glyphs.append({'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 80, 'x1': 13 + index * 4, 'y1': 92}})
layout = {
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 200, 'y1': 200}}],
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 280}},
'page_glyphs': {'1': glyphs},
'tables': {'table-1': glyphs},
},
}
pattern = build_layout_signature(definition=definition, sample_layouts=[layout])['signature']['table_patterns'][0]
joined = ' '.join(str(item) for item in pattern['header_tokens']).upper()
assert pattern['header_row_count'] == 2
# 关键断言:两行正式表头都进入身份,不被折行合并误伤。
assert 'ITEM' in joined
assert 'PRNO' in joined
@@ -97,6 +97,74 @@ def test_runtime_strategy_requires_review_when_two_valid_modes_disagree_on_busin
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
def test_runtime_strategy_uses_dynamic_to_confirm_fixed_when_adaptive_conflicts():
"""关键断言:固定/自适应料号冲突时,动态列单侧覆盖固定则可落选;加长字段时升级动态列。"""
fixed = _row(line_no='1', part_no='B3-A08AR11000001')
fixed['fields'].append({'field_code': 'customer_part_number', 'value': 'WTP-B3-'})
adaptive = _row(line_no='1', part_no='WTP-B3-')
adaptive['fields'].append({'field_code': 'customer_part_number', 'value': 'WTP-B3-'})
dynamic = _row(line_no='1', part_no='B3-A08AR11000001')
dynamic['fields'].append({
'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR11000001',
})
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[fixed],
adaptive_rows=[adaptive],
dynamic_rows=[dynamic],
)
assert result.status == 'selected'
assert result.row_mode == 'dynamic_x_columns'
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
def test_runtime_strategy_uses_dynamic_to_confirm_adaptive_when_fixed_conflicts():
"""动态只与自适应一致时,应落选自适应而非继续 Review。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[_row(line_no='1', part_no='PART-WRONG')],
adaptive_rows=[_row(line_no='1', part_no='PART-RIGHT')],
dynamic_rows=[_row(line_no='1', part_no='PART-RIGHT')],
)
assert result.status == 'selected'
assert result.row_mode == 'adaptive_record_columns'
assert result.reason_codes == ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',)
def test_runtime_strategy_prefers_dynamic_when_it_extends_baseline_field_values():
"""动态无额外行但字段值严格加长时,也应升级动态列,避免截断料号。"""
fixed = _row(line_no='1', part_no='B3-A08')
dynamic = _row(line_no='1', part_no='B3-A08AR11000001')
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[fixed], adaptive_rows=[], dynamic_rows=[dynamic],
)
assert result.status == 'selected'
assert result.row_mode == 'dynamic_x_columns'
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
def test_runtime_strategy_prefers_dynamic_when_it_confirms_fixed_and_recovers_extra_row():
"""动态确认固定侧且额外恢复记录时,应升级为动态列。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[_row(line_no='20', part_no='PART-B')],
adaptive_rows=[_row(line_no='20', part_no='PART-X')],
dynamic_rows=[
_row(line_no='10', part_no='PART-A'),
_row(line_no='20', part_no='PART-B'),
],
)
assert result.status == 'selected'
assert result.row_mode == 'dynamic_x_columns'
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
def test_runtime_strategy_requires_review_when_two_modes_disagree_on_non_key_business_value():
"""同项次料号但数量不同仍是业务冲突,不能因主键一致而静默采用固定子行。"""
fixed = _row(line_no='10', part_no='PART-A')