Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-09-10 09:58:43 +08:00
commit 93b8c68256
23 files changed
+1356 -129

No files matched your search

@@ -13,7 +13,7 @@ from __future__ import annotations
import json
import re
import zipfile
from datetime import datetime
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -23,6 +23,7 @@ from app import db
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingInventoryFile
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
@@ -52,26 +53,38 @@ def get_inventory_archive_dir() -> str:
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
"""
推导企微/下载展示名中的时刻。
推导企微/下载展示名中的当地时刻。
核心逻辑:优先 started_at → created_at → finished_at;再尝试解析 RUN{yyyyMMddHHmmss}*;
最后回退 utcnow。完整 run_no 仍留在卡片与磁盘归档键,不塞进展示名。
核心逻辑:started_at → created_at → finished_at → 解析 RUN{yyyyMMddHHmmss}* → utcnow;
上述时刻在库内均为 UTC naive(含 run_no 时间戳),格式化前转到任务
schedule_timezone(缺省 Asia/Shanghai)。完整 run_no 仍留在卡片与磁盘归档键。
"""
when_utc: datetime | None = None
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()
when_utc = value
break
if when_utc is None:
match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip())
if match:
try:
when_utc = datetime.strptime(match.group(1), "%Y%m%d%H%M%S")
except ValueError:
when_utc = None
if when_utc is None:
when_utc = datetime.now(timezone.utc).replace(tzinfo=None)
task = getattr(run, "task", None)
tz_name = getattr(task, "schedule_timezone", None) if task is not None else None
tz = resolve_schedule_tzinfo(tz_name)
if when_utc.tzinfo is None:
when_utc = when_utc.replace(tzinfo=timezone.utc)
return when_utc.astimezone(tz)
def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}。
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
Args:
run: 排程执行记录。
@@ -5,6 +5,9 @@ services/shipping_notice/document_layout/order_profile_matcher.py
依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠;
无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient;
身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
@@ -46,6 +49,8 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义,
# 避免无意义的版本兼容分支。
LAYOUT_MATCHING_FEATURES_VERSION = 'v1'
# 多表时签名表头原子交集占比达到该阈值才优先于纯 bbox 重叠选主表。
_PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM = 0.5
def _anchor_comparable_text(value: Any) -> str:
@@ -286,7 +291,12 @@ def match_frozen_coordinate_profiles(
candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6)
if not hard_valid:
if any('profile_coordinate_evidence_unavailable' in item.reason_codes for item in rendered):
# [STEP] 仅当全部候选都缺关键坐标结构时才抬升 evidence_insufficient;
# 禁止无关远亲候选的坐标码掩盖近亲模板的真实 header/topology 冲突。
if rendered and all(
'profile_coordinate_evidence_unavailable' in item.reason_codes
for item in rendered
):
return ProfileMatchResult(
status='evidence_insufficient', candidates=rendered,
top1_score=top1_score, top2_score=top2_score, margin=margin,
@@ -1006,6 +1016,7 @@ def _score_header_semantic_position(
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
_HEADER_ATOM_MIN_LEN = 3
_HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]')
def _sanitize_signature_table_identity(
@@ -1069,14 +1080,16 @@ def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
"""
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
核心逻辑:去撇号后按非字母数字切分;过滤过短词与虚词,避免 Q'TY/No. 噪声。
核心逻辑:先拼接 token 再去掉括号注记(通用印刷 gloss,跨 token 空格切开时
仍可剥除),再去撇号并按非字母数字切分;过滤过短词与虚词。签名侧与运行时共用。
"""
joined = ' '.join(str(token) for token in tokens)
normalized = _HEADER_PAREN_GLOSS.sub(' ', joined.casefold())
normalized = re.sub(r"['’]", '', normalized)
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)
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)
@@ -1321,10 +1334,11 @@ def _observe_layout_features(
if width > 0 and height > 0:
aspect_ratio = width / height
# [STEP 1] 与签名生成一致,按签名表区选择实际业务表;MinerU 的 tables[0]
# 可能是抬头/元数据表,不能作为运行时默认主表。
# [STEP 1] 与签名生成一致,按签名表头亲和度与表区选择实际业务表;MinerU 的
# tables[0] 可能是抬头/元数据 KV 表,不能作为运行时默认主表。
primary_bbox = _select_signature_primary_table_bbox(
tables=tables, pages=pages, signature=signature,
page_glyphs=page_glyphs, glyph_tables=glyph_tables,
)
# [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。
primary_bbox = _clip_observed_primary_table_bbox(
@@ -1470,9 +1484,21 @@ def _select_persisted_header_candidate(
def _select_signature_primary_table_bbox(
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
*,
tables: list[dict[str, Any]],
pages: dict[str, Any],
signature: dict[str, Any] | None,
page_glyphs: dict[str, Any] | None = None,
glyph_tables: dict[str, Any] | None = None,
) -> list[float] | None:
"""按签名表区选取重叠最大的实际表;无可用签名时才保持首表兼容行为。"""
"""
选取运行时主表框:签名表头亲和度优先,其次表区重叠;无签名时首表兼容。
核心逻辑:MinerU 常把右上角 ORDER DATE/NO 等 KV 块拆成独立表且排在 tables[0];
仅靠 bbox 重叠在全页 glyphs 场景下仍可能读错表头。对每个候选表顶部观测 header
atoms,与签名 identity header 算交集占比;占比 ≥ 阈值时优先该表,并列再比
table_patterns.bbox.median 重叠。
"""
normalized_tables: list[list[float]] = []
for table in tables:
page = pages.get(str(table.get('page_no') or 1)) or pages.get(table.get('page_no') or 1)
@@ -1498,22 +1524,99 @@ def _select_signature_primary_table_bbox(
and isinstance(item['bbox'].get('median'), list)
and len(item['bbox']['median']) == 4
]
if not patterns:
return normalized_tables[0]
best_bbox = normalized_tables[0]
best_overlap = -1.0
for candidate in normalized_tables:
expected_atoms = _header_token_atoms(_signature_identity_header_tokens(signature))
glyph_pages = page_glyphs if isinstance(page_glyphs, dict) else {}
table_glyph_map = glyph_tables if isinstance(glyph_tables, dict) else {}
def _best_pattern_overlap(candidate: list[float]) -> float:
best = -1.0
for pattern in patterns:
try:
expected = [float(value) for value in pattern['bbox']['median']]
except (TypeError, ValueError):
continue
overlap = _bbox_overlap(expected, candidate)
if overlap > best_overlap:
best_overlap, best_bbox = overlap, candidate
best = max(best, _bbox_overlap(expected, candidate))
return best
if expected_atoms and (glyph_pages or table_glyph_map):
affinity_scored: list[tuple[float, float, list[float]]] = []
for candidate in normalized_tables:
tokens = _header_tokens_for_table_bbox(
bbox=candidate,
tables=tables,
pages=pages,
page_glyphs=glyph_pages,
glyph_tables=table_glyph_map,
)
observed_atoms = _header_token_atoms(tokens)
affinity = (
len(observed_atoms & expected_atoms) / len(expected_atoms)
if expected_atoms else 0.0
)
affinity_scored.append((affinity, _best_pattern_overlap(candidate), candidate))
affinity_scored.sort(key=lambda item: (item[0], item[1]))
best_affinity, best_overlap, best_bbox = affinity_scored[-1]
if best_affinity >= _PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM:
return best_bbox
if not patterns:
return best_bbox if best_affinity > 0 else normalized_tables[0]
if not patterns:
return normalized_tables[0]
best_bbox = normalized_tables[0]
best_overlap = -1.0
for candidate in normalized_tables:
overlap = _best_pattern_overlap(candidate)
if overlap > best_overlap:
best_overlap, best_bbox = overlap, candidate
return best_bbox
def _header_tokens_for_table_bbox(
*,
bbox: list[float],
tables: list[dict[str, Any]],
pages: dict[str, Any],
page_glyphs: dict[str, Any],
glyph_tables: dict[str, Any],
) -> list[str]:
"""
在候选表顶部条带观测表头 token,供主表亲和度打分。
核心逻辑:取相对坐标表框顶边向下 max(6%, 18% 表高) 的条带,用页级 glyphs
(不足时回退 table glyphs)拼 token;不做折行合并,仅服务选表。
"""
if not isinstance(bbox, list) or len(bbox) != 4:
return []
page_no, page = _page_for_primary_table_bbox(bbox, tables=tables, pages=pages)
if not isinstance(page, dict):
return []
glyphs = None
if page_no is not None:
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
if not isinstance(glyphs, list) or not glyphs:
glyphs = page_glyphs.get('1') or page_glyphs.get(1) or []
if not isinstance(glyphs, list) or not glyphs:
glyphs = []
for table_glyphs in glyph_tables.values():
if isinstance(table_glyphs, list):
glyphs.extend(table_glyphs)
if not glyphs:
return []
region = {
'x0': float(bbox[0]),
'y0': float(bbox[1]),
'x1': float(bbox[2]),
'y1': float(bbox[1]) + max(0.06, (float(bbox[3]) - float(bbox[1])) * 0.18),
}
header_glyphs = _glyphs_in_relative_region(glyphs, page=page, region=region)
spans = [
item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False)
if _usable_observed_header_token(str(item.get('text') or ''))
][:32]
return [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
def _clip_observed_primary_table_bbox(
primary_bbox: list[float] | None,
*,
@@ -1616,21 +1719,62 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float:
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
def _band_headers_match_signature(
*, band_tokens: list[str], signature: dict[str, Any] | None,
) -> bool:
"""判断冻结表头带读到的 token 是否足以代表签名表头。
def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None:
"""读取签名首个可用 table_patterns.bbox.median(归一化四点)。"""
for pattern in (signature or {}).get('table_patterns') or []:
if not isinstance(pattern, dict):
continue
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
if not isinstance(bbox, dict):
continue
median = bbox.get('median')
if isinstance(median, list) and len(median) == 4:
try:
return [float(item) for item in median]
except (TypeError, ValueError):
continue
return None
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
需要回退到表体顶部的结构搜索。期望侧先截断折行副标签污染。
def _align_signature_header_bbox_to_primary(
*,
signature: dict[str, Any] | None,
primary_bbox: list[float],
) -> list[float] | None:
"""
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]
matched = sum(1 for token in expected if token in observed)
return matched / len(expected) >= 0.5
将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。
核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0
平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。
"""
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
return None
header_bbox = _signature_header_bbox(signature)
if header_bbox is None:
return None
table_median = _signature_table_bbox_median(signature)
try:
hx0, hy0, hx1, hy1 = (float(header_bbox[i]) for i in range(4))
py0, py1 = float(primary_bbox[1]), float(primary_bbox[3])
except (TypeError, ValueError, IndexError):
return None
if hy1 <= hy0 or py1 <= py0:
return None
delta_y = 0.0
if table_median is not None:
try:
delta_y = py0 - float(table_median[1])
except (TypeError, ValueError, IndexError):
delta_y = 0.0
aligned_y0 = hy0 + delta_y
aligned_y1 = hy1 + delta_y
# [STEP] 夹在主表内;保持最小可读高度。
height = max(0.02, aligned_y1 - aligned_y0)
clipped_y0 = min(max(aligned_y0, py0), max(py0, py1 - height))
clipped_y1 = min(clipped_y0 + height, py1)
if clipped_y1 <= clipped_y0:
return None
return [hx0, clipped_y0, hx1, clipped_y1]
def _observe_primary_table_header(
@@ -1641,10 +1785,12 @@ def _observe_primary_table_header(
primary_bbox: list[float] | None,
signature: dict[str, Any] | None,
) -> tuple[list[str], list[float], list[float]]:
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
"""
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用。
若固定带失准,则基于表体顶部做表头行搜索。单逻辑表头时把折行副标签按 x 并入所属列。
核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框
时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行
宽带搜索,避免印刷括号注记污染身份原子。
"""
if not primary_bbox or len(primary_bbox) != 4:
return [], [], []
@@ -1657,14 +1803,23 @@ def _observe_primary_table_header(
page = pages.get('1') or pages.get(1)
if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict):
return [], [], []
header_bbox = _signature_header_bbox(signature)
region = (
{'x0': header_bbox[0], 'y0': header_bbox[1], 'x1': header_bbox[2], 'y1': header_bbox[3]}
if header_bbox is not None else {
'x0': primary_bbox[0], 'y0': primary_bbox[1], 'x1': primary_bbox[2],
'y1': primary_bbox[1] + max(0.06, (primary_bbox[3] - primary_bbox[1]) * 0.18),
}
aligned = _align_signature_header_bbox_to_primary(
signature=signature, primary_bbox=primary_bbox,
)
if aligned is not None:
region = {
'x0': float(aligned[0]), 'y0': float(aligned[1]),
'x1': float(aligned[2]), 'y1': float(aligned[3]),
}
else:
region = {
'x0': float(primary_bbox[0]),
'y0': float(primary_bbox[1]),
'x1': float(primary_bbox[2]),
'y1': float(primary_bbox[1]) + max(
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
),
}
width = float(page.get('width') or 0)
if width <= 0:
return [], [], []
@@ -1675,38 +1830,19 @@ def _observe_primary_table_header(
][:32]
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
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:
table_span = max(float(primary_bbox[2]) - float(primary_bbox[0]), 0.0001)
band_widths = [
round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans
]
if _signature_single_logical_header(signature):
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
# 固定带失准 → 表体顶部候选行;单逻辑表头时把下一视觉行折行副标签并入。
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
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 (
[str(item).casefold() for item in merged_tokens],
list(merged_centers or []),
list(merged_widths or []),
)
return band_tokens, band_centers, band_widths
@@ -6,6 +6,7 @@ services/shipping_notice/document_layout/order_profile_signature.py
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
单逻辑表头行将格内折行副标签按 x 并入所属列,保留文案、不拆成新身份列。
table_patterns 仅纳入 business_lines;line_field_supplement 不进匹配身份。
"""
from __future__ import annotations
@@ -198,8 +199,9 @@ def build_layout_signature(
"""
生成版面签名快照;相同输入必须得到相同 checksum。
核心逻辑:解析模板表区/表头/字段关系 → 从样本区域读取固定文字 → 多样本聚合
中位数与容差 → 过滤动态值与单样本噪声 → 计算稳定 checksum。
核心逻辑:解析模板表区/表头/字段关系 → 仅对 business_lines 建 table_patterns →
从样本区域读取固定文字 → 多样本聚合中位数与容差 → 过滤动态值与单样本噪声 →
计算稳定 checksum。line_field_supplement 只服务按 LN 补料号,不进匹配身份。
Args:
definition: 当前草稿或冻结 Profile 定义 JSON。
@@ -225,11 +227,15 @@ def build_layout_signature(
order_field_layouts=definition.get('order_field_layouts') or [],
)
# [STEP 2] 页面与表区几何模式
# [STEP 2] 页面与主表明细几何模式(排除 line_field_supplement)
page_patterns = _build_page_patterns(sample_layouts=sample_layouts)
matching_tables = [
table for table in profile.table_regions
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
]
table_patterns = [
_build_table_pattern(table=table, sample_layouts=sample_layouts)
for table in profile.table_regions
for table in matching_tables
]
field_relation_graph = _build_field_relation_graph(profile, sample_layouts=sample_layouts)
evidence_quality = _build_evidence_quality(
@@ -356,8 +356,20 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow()
db.session.commit()
return _payload(run)
path = Path(str(payload.get('file_path') or ''))
if not path.is_file():
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
# SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
raw_file_path = str(payload.get('file_path') or '').strip()
path: Path | None = None
from app.services.shipping_notice.rpa import inventory_drop_dir
from app.services.shipping_notice.inventory_rpa_workflow import _resolve_shared_inventory_drop_file
drop_root = inventory_drop_dir()
if drop_root is not None:
path = _resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root)
if path is None:
candidate = Path(raw_file_path)
if candidate.is_file():
path = candidate
if path is None or not path.is_file():
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
db.session.commit()
return _payload(run)
@@ -1204,6 +1204,43 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool:
_EXTRACT_DONE_UNIT_STATUSES = frozenset({
'candidate_ready', 'review_required', 'failed', 'cancelled',
})
# layout 与 extraction 共 shipping 队列且默认 priority=0;resume 抬高后才能插队,
# 否则「单文件版式完成」的 extraction 仍排在剩余 layout FIFO 之后。
_ORDER_EXTRACTION_READY_PRIORITY = 10
def _enqueue_ready_order_extraction_job(
run: ShippingOrderProcessingRun, *, message: str,
) -> int:
"""
为已有 ready 活的 Run 入队(或复用)extraction Job,并抬高 queued 优先级以便插队。
核心逻辑:enqueue 去重可能返回仍在排队的早建 Job;必须把其 priority 提到
_ORDER_EXTRACTION_READY_PRIORITY,否则 claim 仍按 created_at 先消化 layout。
"""
from app.jobs.queue import enqueue
from app.jobs.types import JobType
job_id = enqueue(
JobType.SHIPPING_ORDER_EXTRACTION,
{'run_no': run.run_no},
domain='shipping_notice',
business_ref=run.run_no,
created_by_id=run.user_id,
priority=_ORDER_EXTRACTION_READY_PRIORITY,
max_attempts=3,
message=message,
commit=False,
)
job = db.session.get(Job, int(job_id))
if (
job is not None
and str(job.status or '') == 'queued'
and int(job.priority or 0) < _ORDER_EXTRACTION_READY_PRIORITY
):
job.priority = _ORDER_EXTRACTION_READY_PRIORITY
job.message = message
return int(job_id)
def order_extraction_ready_document_ids(run: ShippingOrderProcessingRun) -> set[int]:
@@ -1360,12 +1397,9 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
单份附件布局完成后唤醒仍等待版式的 Run。
核心逻辑:不再要求 Run 内全部 PDF 版式就绪;只要存在可抽取的 ready Document,
即入队(或复用活跃)shipping_order_extraction。无 ready 活且无 pending、仅有失败版式、
且尚未抽出任何 Unit 时,整 Run 失败收口。
即以抬高 priority 入队(或复用活跃)shipping_order_extraction,避免被剩余 layout
FIFO 堵住。无 ready 活且无 pending、仅有失败版式、且尚未抽出任何 Unit 时整 Run 失败。
"""
from app.jobs.queue import enqueue
from app.jobs.types import JobType
resumed = 0
# processing + waiting_layout:部分 Unit 已抽完、仍等兄弟文件版式。
runs = (
@@ -1380,11 +1414,8 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
if int(document_id) not in _run_snapshot_document_ids(run):
continue
if order_extraction_has_extractable_ready_work(run):
job_id = enqueue(
JobType.SHIPPING_ORDER_EXTRACTION,
{'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no,
created_by_id=run.user_id, max_attempts=3,
message='附件解析完成,等待订单识别', commit=False,
job_id = _enqueue_ready_order_extraction_job(
run, message='附件解析完成,等待订单识别',
)
run.current_job_id = job_id
# 仍有兄弟 layout pending 时保持 waiting_layout,便于再次 resume;
@@ -1410,11 +1441,8 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
)
if progressed:
# 已有 Unit 成功/复核:再入队一次让 Worker 收口,禁止整 Run 抹掉部分成果。
job_id = enqueue(
JobType.SHIPPING_ORDER_EXTRACTION,
{'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no,
created_by_id=run.user_id, max_attempts=3,
message='部分附件版式失败,等待订单识别收口', commit=False,
job_id = _enqueue_ready_order_extraction_job(
run, message='部分附件版式失败,等待订单识别收口',
)
run.current_job_id = job_id
run.phase = 'queued'
+1
View File
@@ -1,5 +1,6 @@
[pytest]
markers =
integration: optional integration tests that require external services or local DB snapshots
pure_unit: skip Flask app/DB creation unless the test requests the app fixture
auto_rpa: enable shipping notice auto RPA / auto progress in test config
inventory_source_gate: skip default Dublin destination injection for inventory source gate tests
@@ -165,6 +165,45 @@ def test_dsv_report_inventory_rows_returns_false_when_no_data_within_deadline(mo
assert worker._wait_dsv_report_inventory_rows(page=object(), timeout_ms=2_500) is False
def test_ensure_dsv_inventory_rows_retries_view_report_then_allows_export_fallback(monkeypatch):
"""DOM 无行时重试 View Report;仍无行不得抛空,应继续导出由 Excel 判空。"""
worker = _load_dsv_report_export()
clicks: list[str] = []
waits: list[int] = []
row_outcomes = iter([False, False])
monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000)
monkeypatch.setattr(
worker,
"_wait_dsv_report_inventory_rows",
lambda page_arg, timeout_ms: (waits.append(timeout_ms) or next(row_outcomes, False)),
)
monkeypatch.setattr(
worker,
"_click_dsv_view_report",
lambda page_arg: clicks.append("view"),
)
monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms: None)
worker._ensure_dsv_inventory_rows_or_export_fallback(page=object(), report_name="On Hand Inventory by Location")
assert clicks == ["view"]
assert waits == [5_000, 5_000]
def test_ensure_dsv_inventory_rows_skips_retry_when_rows_already_visible(monkeypatch):
"""首次轮询已有明细行时不得再点 View Report。"""
worker = _load_dsv_report_export()
clicks: list[str] = []
monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000)
monkeypatch.setattr(worker, "_wait_dsv_report_inventory_rows", lambda page_arg, timeout_ms: True)
monkeypatch.setattr(worker, "_click_dsv_view_report", lambda page_arg: clicks.append("view"))
worker._ensure_dsv_inventory_rows_or_export_fallback(page=object(), report_name="On Hand Inventory by Location")
assert clicks == []
def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
"""单票 DSV 导出应走与批量相同的 session + export 函数。"""
worker = _load_worker()
@@ -145,6 +145,29 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp
assert ShippingInventoryConfigurationTestRun.query.count() == 1
def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app, tmp_path):
"""Worker 回传 Windows drop 路径时,必须映射到 Linux 共享目录再分析,不能报「文件不存在」。"""
drop_dir = tmp_path / 'inventory_drop'
drop_dir.mkdir()
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
result_file = drop_dir / f"inventory_{started['run_no']}_DSV360_BYAWSPRD01.xlsx"
_workbook(result_file)
windows_path = rf'C:\HxopsRpaTest\data\inventory_drop\{result_file.name}'
completed = inventory_configuration_test.report_test_export({
'run_no': started['run_no'], 'status': 'success', 'file_path': windows_path,
})
assert completed['status'] == 'completed'
assert completed.get('error_message') in (None, '')
assert not ShippingInventoryFile.query.count()
def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
@@ -10,6 +10,7 @@ from __future__ import annotations
import json
import zipfile
from datetime import datetime
from io import BytesIO
from pathlib import Path
from urllib.parse import quote
@@ -28,6 +29,7 @@ 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_attachment_stem,
inventory_rpa_result_excel_name,
persist_inventory_rpa_raw_zip_archive,
resolve_inventory_raw_zip_download,
@@ -544,6 +546,23 @@ def test_build_zip_entry_name_prefers_source_code():
) == "003_AWSSG.xlsx"
def test_inventory_rpa_attachment_stem_converts_utc_to_schedule_timezone(app):
"""展示名 HHmm 必须用业务时区,不能直接用库内 UTC naive / run_no 内嵌时刻。"""
with app.app_context():
run = _make_inventory_run_with_created(
schedule_no="ARCH-TZ-STEM",
username="arch_tz_stem",
created=[],
)
# UTC 06:27 → Asia/Shanghai 14:27
run.started_at = datetime(2026, 9, 9, 6, 27, 17)
run.task.schedule_timezone = "Asia/Shanghai"
db.session.commit()
assert inventory_rpa_attachment_stem(run) == "库存RPA-20260909-1427"
assert inventory_rpa_result_excel_name(run) == "库存RPA-20260909-1427-结果.xlsx"
assert inventory_raw_zip_download_name(run) == "库存RPA-20260909-1427-库存.zip"
def test_get_inventory_raw_zip_returns_404_when_archive_unavailable(
client,
app,
@@ -786,7 +786,10 @@ def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app):
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 1
db.session.refresh(run)
first_job_id = run.current_job_id
assert db.session.get(Job, first_job_id) is not None
first_job = db.session.get(Job, first_job_id)
assert first_job is not None
# 关键断言:抬高 priority,避免被同队列剩余 layout FIFO 堵住。
assert int(first_job.priority or 0) >= 10
assert run.phase == 'waiting_layout'
layouts[1].status = 'ready'
@@ -799,6 +802,7 @@ def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app):
assert run.phase == 'queued'
assert job is not None
assert job.job_type == 'shipping_order_extraction'
assert int(job.priority or 0) >= 10
def test_pdf_without_ready_coordinate_layout_is_a_prerequisite_failure(app):
@@ -690,6 +690,124 @@ def test_profile_matcher_selects_signature_main_table_when_metadata_table_preced
assert result.candidates[0].dimension_scores.column_topology >= 0.75
def _header_glyphs_at(*, text: str, y0: float, y1: float, x0: float = 10.0, step: float = 4.0) -> list[dict]:
"""在指定纵坐标生成带空格边界的表头字符证据。"""
return [
{
'text': char,
'bbox': {'x0': x0 + index * step, 'y0': y0, 'x1': x0 + index * step + 3, 'y1': y1},
'boundary_before': 'space' if index and text[index - 1] == ' ' else 'none',
}
for index, char in enumerate(text)
if char != ' '
]
def _foxconn_dual_table_layout() -> dict:
"""模拟 4210012210:右上角 ORDER DATE KV 小表 + 下方明细表,全页均有 glyphs。"""
layout = _layout('PLANT NAME: FACTORY A', header_text='ITEM NO QTY')
meta_header = 'ORDER DATE ORDER NO BU CODE CURRENCY'
main_header = 'ITEM NO MATERIAL DESCRIPTION UNIT QTY DELIVERY DATE UNIT PRICE TOTAL PRICE'
meta_glyphs = _header_glyphs_at(text=meta_header, y0=70, y1=82, x0=120.0)
main_glyphs = _header_glyphs_at(text=main_header, y0=150, y1=162, x0=10.0)
layout['tables'] = [
{
'table_id': 'order-meta',
'page_no': 1,
# 绝对点坐标:与 pages width/height=200/280 一致,贴近真实 MinerU 右上角 KV 表。
'bbox': {'x0': 120.0, 'y0': 55.0, 'x1': 195.0, 'y1': 100.0},
},
{
'table_id': 'line-items',
'page_no': 1,
'bbox': {'x0': 10.0, 'y0': 140.0, 'x1': 190.0, 'y1': 250.0},
},
]
layout['coordinate_evidence']['tables'] = {
'order-meta': meta_glyphs,
'line-items': main_glyphs,
}
# 锚点 glyphs + 两表表头均写入页级证据,再现「全页 glyphs 非空」场景。
layout['coordinate_evidence']['page_glyphs']['1'] = [
*layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')],
*meta_glyphs,
*main_glyphs,
]
return layout
def test_profile_matcher_prefers_line_table_when_order_meta_table_precedes_it():
"""全页 glyphs 下须按签名表头亲和度选明细表,不能被前置 ORDER DATE KV 小表抢走。"""
layout = _foxconn_dual_table_layout()
profile = _profile('FOX_MX')
profile['definition']['document_match']['required_anchors'] = []
main_region = {'x0': 0.05, 'y0': 0.50, 'x1': 0.95, 'y1': 0.90}
profile['definition']['table_regions'][0]['region'] = main_region
profile['definition']['table_regions'][0]['line_layouts'][0]['region'] = main_region
# 签名只在明细表布局上冻结,模拟已发布 FOX MX。
sign_layout = _layout('PLANT NAME: FACTORY A', header_text='ITEM NO MATERIAL DESCRIPTION UNIT QTY DELIVERY DATE UNIT PRICE TOTAL PRICE')
sign_layout['tables'] = [layout['tables'][1]]
sign_layout['coordinate_evidence']['tables'] = {'line-items': layout['coordinate_evidence']['tables']['line-items']}
sign_layout['coordinate_evidence']['page_glyphs']['1'] = [
*sign_layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')],
*layout['coordinate_evidence']['tables']['line-items'],
]
profile = _with_signature(profile, sign_layout)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
# 关键断言:双表全页 glyphs 仍唯一命中明细模板,不得因 KV 小表落到 evidence_insufficient。
assert result.status == 'unique_match'
assert result.profile_code == 'FOX_MX'
assert result.candidates[0].hard_match is True
assert 'profile_header_discriminator_conflict' not in result.candidates[0].reason_codes
assert 'profile_coordinate_evidence_unavailable' not in result.candidates[0].reason_codes
def test_profile_matcher_does_not_escalate_unrelated_coordinate_unavailable(monkeypatch):
"""近亲 header 冲突时,远亲候选的坐标不可用不得把整单抬成 evidence_insufficient。"""
from app.services.shipping_notice.document_layout import order_profile_matcher as matcher
line_layout = _layout(
'PLANT NAME: FACTORY A',
header_text='ITEM NO MATERIAL DESCRIPTION UNIT QTY',
)
near = _profile_without_required_anchors('NEAR_TWIN', _layout(
header_text='PART NUMBER AMOUNT CURRENCY INVOICE CODE',
))
far = _profile_without_required_anchors('FAR_EMPTY', _layout(
header_text='VENDOR INVOICE TOTAL AMOUNT',
))
real_observe = matcher._observe_layout_features
def fake_observe(*, signature, **kwargs):
"""远亲强制空表头观测,稳定触发 profile_coordinate_evidence_unavailable。"""
observed = real_observe(signature=signature, **kwargs)
tokens = matcher._signature_identity_header_tokens(signature)
atoms = matcher._header_token_atoms([str(item) for item in tokens])
if 'vendor' in atoms:
return {
**observed,
'header_tokens': [],
'column_centers': [],
'column_width_ratios': [],
'column_count': 0,
}
return observed
monkeypatch.setattr(matcher, '_observe_layout_features', fake_observe)
result = match_frozen_coordinate_profiles(profiles=[near, far], layout=line_layout)
# 关键断言:不得因远亲坐标码把整单抬成 evidence_insufficient。
assert result.status != 'evidence_insufficient'
near_cand = next(item for item in result.candidates if item.profile_code == 'NEAR_TWIN')
far_cand = next(item for item in result.candidates if item.profile_code == 'FAR_EMPTY')
assert 'profile_header_discriminator_conflict' in near_cand.reason_codes
assert 'profile_coordinate_evidence_unavailable' in far_cand.reason_codes
def test_profile_matcher_excludes_below_threshold_hard_candidate_from_uniqueness():
"""硬门禁通过但得分或证据覆盖不合格的候选,不得阻塞唯一合格模板。"""
layout = _layout('PLANT NAME: FACTORY A')
@@ -812,6 +930,207 @@ def _profile_without_required_anchors(code: str, layout: dict) -> dict:
return profile
def test_header_token_atoms_ignore_parenthetical_gloss():
"""括号印刷注记经统一归一化后不得改变表头原子(不依赖 vat 特判停用词)。"""
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_header_discriminator_atoms_conflict,
_header_token_atoms,
)
expected = [
'Item', 'Parts No.& Description', 'REV.', 'UNIT', "Q'TY",
'Delivery Date', 'Unit', 'Total', 'Price',
]
observed = [
'item 项次', 'parts no.& description 料号', 'rev.', 'unit', "q'ty",
'delivery date', 'unit', 'price (vat excluded)', 'total', 'price',
]
assert _header_token_atoms(expected) == _header_token_atoms(observed)
assert 'vat' not in _header_token_atoms(observed)
assert _header_discriminator_atoms_conflict(
signature={'table_patterns': [{'header_tokens': expected}]},
observed={'header_tokens': observed},
) is False
# 近亲多出的 ECCN 仍须硬杀。
assert _header_discriminator_atoms_conflict(
signature={'table_patterns': [{'header_tokens': expected + ['ECCN']}]},
observed={'header_tokens': observed},
) is True
def _profile_with_header_band(
code: str,
layout: dict,
*,
header_region: dict,
required_anchors: bool = True,
) -> dict:
"""构造带 header_layouts 的 Profile,使签名冻结合法 header_bbox。"""
profile = _profile(code)
if not required_anchors:
profile['definition']['document_match']['required_anchors'] = []
bbox = layout['tables'][0]['bbox']
table = profile['definition']['table_regions'][0]
table['region'] = {
'x0': float(bbox['x0']), 'y0': float(bbox['y0']),
'x1': float(bbox['x1']), 'y1': float(bbox['y1']),
}
table['header_layouts'] = [{
'layout_id': 'hdr',
'region': header_region,
'field_regions': [_field_region(region=header_region)],
}]
# 明细行区必须与表头带不重叠,否则 OrderCoordinateProfile 校验失败。
line_region = {
'x0': float(bbox['x0']),
'y0': float(header_region['y1']),
'x1': float(bbox['x1']),
'y1': float(bbox['y1']),
}
table['line_layouts'][0]['region'] = line_region
table['line_layouts'][0]['field_regions'] = [_field_region(region=line_region)]
return _with_signature(profile, layout)
def test_observe_header_ignores_vat_row_outside_aligned_header_band():
"""身份观测不得用表顶宽带读入签名表头框外的 Unit Price (VAT Excluded) 行。"""
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_extract_matching_signature,
_header_token_atoms,
_observe_layout_features,
)
header_text = 'ITEM NO QTY'
layout = _layout(header_text=header_text, bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95})
# 表顶 18% 内、但低于紧表头带:放入 VAT 注记行。
vat_text = 'Unit Price (VAT Excluded)'
vat_glyphs = [
{
'text': char,
'bbox': {'x0': 10 + index * 5, 'y0': 100, 'x1': 14 + index * 5, 'y1': 112},
'boundary_before': 'space' if index and vat_text[index - 1] == ' ' else 'none',
}
for index, char in enumerate(vat_text)
if char != ' '
]
layout['coordinate_evidence']['page_glyphs']['1'].extend(vat_glyphs)
header_region = {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.32}
profile = _profile_with_header_band('PO_BAND', layout, header_region=header_region)
signature_body, _ = _extract_matching_signature(profile)
evidence = layout['coordinate_evidence']
observed = _observe_layout_features(
layout=layout,
tables=layout['tables'],
pages=evidence['pages'],
glyph_tables=evidence['tables'],
page_glyphs=evidence['page_glyphs'],
signature=signature_body,
)
atoms = _header_token_atoms([str(item) for item in (observed.get('header_tokens') or [])])
# 关键断言:框外 VAT 行不得进入身份原子。
assert 'vat' not in atoms
assert 'excluded' not in atoms
assert 'item' in atoms or 'qty' in atoms
def test_aligned_header_band_unique_match_after_table_delta_y():
"""主表相对签名整体下移时,表头框 deltaY 对齐后仍应 unique_match。"""
baseline = _layout(
header_text='ITEM NO MATERIAL QTY',
bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95},
)
header_region = {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.32}
profile = _profile_with_header_band(
'PO_SHIFT', baseline, header_region=header_region, required_anchors=False,
)
shifted = _layout(
header_text='ITEM NO MATERIAL QTY',
bbox={'x0': 0.05, 'y0': 0.40, 'x1': 0.95, 'y1': 0.95},
)
# 默认表头 glyphs 按 y≈0.27 生成;整体下移与主表顶边一致。
# table-1 与 page_glyphs 共享同一 glyph 对象,只平移一次。
delta = (0.40 - 0.25) * 280
for glyph in shifted['coordinate_evidence']['page_glyphs']['1']:
if glyph['bbox']['y0'] >= 50:
glyph['bbox']['y0'] += delta
glyph['bbox']['y1'] += delta
result = match_frozen_coordinate_profiles(profiles=[profile], layout=shifted)
assert result.status == 'unique_match'
assert result.profile_code == 'PO_SHIFT'
def test_in_band_parenthetical_vat_aligns_without_stopwords():
"""框内印刷括号注记时仅靠括号归一化与无括号签名对齐(无 vat 停用词)。"""
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_extract_matching_signature,
_header_discriminator_atoms_conflict,
_header_token_atoms,
_observe_layout_features,
_signature_identity_header_tokens,
)
clean = _layout(
header_text='ITEM Unit Price Total',
bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95},
)
header_region = {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.34}
profile = _profile_with_header_band(
'PO_PAREN', clean, header_region=header_region, required_anchors=False,
)
# 紧凑字形间距,避免长括号注记超出表头带 x 范围被截断。
with_gloss = _layout(
header_text='ITEM Unit Price (VAT Excluded) Total',
bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95},
)
gloss_text = 'ITEM Unit Price (VAT Excluded) Total'
header_glyphs = [
{
'text': char,
'bbox': {'x0': 10 + index * 5, 'y0': 76, 'x1': 13 + index * 5, 'y1': 88},
'boundary_before': 'space' if index and gloss_text[index - 1] == ' ' else 'none',
}
for index, char in enumerate(gloss_text)
if char != ' '
]
with_gloss['coordinate_evidence']['tables']['table-1'] = header_glyphs
anchor_glyphs = [
glyph for glyph in clean['coordinate_evidence']['page_glyphs']['1']
if float(glyph['bbox']['y0']) < 50
]
with_gloss['coordinate_evidence']['page_glyphs']['1'] = [*anchor_glyphs, *header_glyphs]
signature_body, _ = _extract_matching_signature(profile)
evidence = with_gloss['coordinate_evidence']
observed = _observe_layout_features(
layout=with_gloss,
tables=with_gloss['tables'],
pages=evidence['pages'],
glyph_tables=evidence['tables'],
page_glyphs=evidence['page_glyphs'],
signature=signature_body,
)
expected_tokens = _signature_identity_header_tokens(signature_body)
observed_tokens = [str(item) for item in (observed.get('header_tokens') or [])]
assert _header_token_atoms(expected_tokens) == _header_token_atoms(observed_tokens)
assert 'vat' not in _header_token_atoms(observed_tokens)
assert _header_discriminator_atoms_conflict(
signature=signature_body, observed=observed,
) is False
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_score_header_semantic_position,
)
header_score = _score_header_semantic_position(
signature=signature_body,
observed=observed,
required_hits=[],
enforce_atom_discriminator=True,
)
assert header_score.state == 'matched'
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'
@@ -0,0 +1,251 @@
"""
tests/test_shipping_order_profile_matcher_replay.py
用途:回放本地库历史 unique_match 冻结快照,验证收紧表头身份读取不回归已发布模板。
依赖:SQLAlchemy、match_frozen_coordinate_profiles、shipping_order_route_decisions 表。
逻辑:只读查询 Run 冻结 input_snapshot_json;无 DB/快照时 skip;失败样本按 profile 汇总。
"""
from __future__ import annotations
import json
import os
from collections import defaultdict
from typing import Any
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.engine import Engine
from app.services.shipping_notice.document_layout.order_profile_matcher import (
match_frozen_coordinate_profiles,
)
_REPLAY_DB_URL = os.environ.get(
'HXOPS_PROFILE_REPLAY_DATABASE_URL',
os.environ.get('DATABASE_URL', 'postgresql://postgres:postgres@127.0.0.1:5432/hxops_db'),
)
_MAX_PER_PROFILE = int(os.environ.get('HXOPS_PROFILE_REPLAY_MAX_PER_PROFILE', '20'))
_EXTRA_DOC_IDS = {
int(item.strip())
for item in os.environ.get('HXOPS_PROFILE_REPLAY_DOC_IDS', '194').split(',')
if item.strip().isdigit()
}
def _can_connect(url: str) -> bool:
"""探测回放库是否可连;连不上则整条集成测试 skip。"""
try:
engine = create_engine(url)
with engine.connect() as conn:
conn.execute(text('SELECT 1'))
return True
except Exception:
return False
@pytest.fixture(scope='module')
def replay_engine() -> Engine:
"""模块级只读引擎;本地无 hxops_db 时跳过。"""
if not _can_connect(_REPLAY_DB_URL):
pytest.skip(f'Replay database unavailable: {_REPLAY_DB_URL}')
return create_engine(_REPLAY_DB_URL)
def _document_from_snapshot(
snapshot: dict[str, Any],
*,
document_id: int,
intake_id: int,
) -> dict[str, Any] | None:
"""在冻结 intake 列表中定位 document 及其 layout_snapshot。"""
for intake in snapshot.get('intakes') or []:
if not isinstance(intake, dict) or int(intake.get('intake_id') or 0) != int(intake_id):
continue
for document in intake.get('documents') or []:
if not isinstance(document, dict):
continue
if int(document.get('document_id') or 0) == int(document_id):
return document
return None
def _layout_ready(layout: dict[str, Any] | None) -> bool:
"""layout 须 ready 且具备 matcher 所需坐标证据。"""
if not isinstance(layout, dict) or layout.get('status') != 'ready':
return False
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
return bool(pages and (page_glyphs or glyph_tables or tables))
def _frozen_profiles(snapshot: dict[str, Any], *, schema_version_id: int) -> list[dict[str, Any]]:
"""与 Worker 一致:仅取与 Run schema_version_id 对齐的冻结模板。"""
profiles = snapshot.get('order_document_profiles')
if not isinstance(profiles, list):
profiles = snapshot.get('profiles') if isinstance(snapshot.get('profiles'), list) else []
return [
item for item in profiles
if isinstance(item, dict)
and int(item.get('schema_version_id') or 0) == int(schema_version_id)
]
def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
"""
拉取 unique_match 路由样本;每个 profile_code 最多保留最近 N 条。
Returns:
含 route/run/unit/document/profile 期望字段的字典列表。
"""
query = text("""
SELECT
r.id AS route_id,
r.run_id,
r.unit_id,
r.selected_profile_code,
r.selected_profile_version,
r.selected_profile_checksum,
run.input_snapshot_json,
run.schema_version_id,
u.document_id,
u.intake_id
FROM shipping_order_route_decisions r
JOIN shipping_order_processing_runs run ON run.id = r.run_id
JOIN shipping_order_processing_units u ON u.id = r.unit_id
WHERE r.match_status = 'unique_match'
AND r.selected_profile_code IS NOT NULL
AND run.input_snapshot_json IS NOT NULL
ORDER BY r.selected_profile_code ASC, r.id DESC
""")
rows: list[dict[str, Any]] = []
per_profile: dict[str, int] = defaultdict(int)
with engine.connect() as conn:
for row in conn.execute(query).mappings():
code = str(row['selected_profile_code'] or '')
if per_profile[code] >= _MAX_PER_PROFILE:
continue
snapshot = row['input_snapshot_json']
if isinstance(snapshot, str):
snapshot = json.loads(snapshot)
if not isinstance(snapshot, dict):
continue
document = _document_from_snapshot(
snapshot,
document_id=int(row['document_id'] or 0),
intake_id=int(row['intake_id'] or 0),
)
layout = document.get('layout_snapshot') if isinstance(document, dict) else None
if not _layout_ready(layout if isinstance(layout, dict) else None):
continue
profiles = _frozen_profiles(snapshot, schema_version_id=int(row['schema_version_id'] or 0))
if not profiles:
continue
per_profile[code] += 1
rows.append({
'route_id': int(row['route_id']),
'run_id': int(row['run_id']),
'unit_id': int(row['unit_id']),
'document_id': int(row['document_id']),
'expected_profile_code': code,
'expected_profile_version': int(row['selected_profile_version'] or 0),
'expected_profile_checksum': str(row['selected_profile_checksum'] or ''),
'profiles': profiles,
'layout': layout,
})
return rows
def test_replay_published_unique_match_snapshots(replay_engine: Engine) -> None:
"""历史 unique_match 样本回放后仍应命中同一 profile(收紧表头带回归门禁)。"""
samples = _load_replay_samples(replay_engine)
if not samples:
pytest.skip('No replayable unique_match snapshots in database')
failures: list[str] = []
summary: dict[str, dict[str, int]] = defaultdict(lambda: {'pass': 0, 'fail': 0})
for sample in samples:
code = sample['expected_profile_code']
result = match_frozen_coordinate_profiles(
profiles=sample['profiles'],
layout=sample['layout'],
)
ok = (
result.status == 'unique_match'
and result.profile_code == sample['expected_profile_code']
and (
not sample['expected_profile_version']
or int(result.version or 0) == int(sample['expected_profile_version'])
)
)
if ok:
summary[code]['pass'] += 1
else:
summary[code]['fail'] += 1
failures.append(
f"{code} route={sample['route_id']} run={sample['run_id']} "
f"doc={sample['document_id']}: expected {sample['expected_profile_code']}"
f"/v{sample['expected_profile_version']}, got {result.status}"
f"/{result.profile_code}/v{result.version}"
)
if failures:
lines = [
'Published unique_match replay failures:',
*[f' - {item}' for item in failures[:50]],
'Per-profile summary:',
]
for profile_code, counts in sorted(summary.items()):
lines.append(f' {profile_code}: pass={counts["pass"]} fail={counts["fail"]}')
pytest.fail('\n'.join(lines))
@pytest.mark.parametrize('document_id', sorted(_EXTRA_DOC_IDS))
def test_replay_specific_document_rematch_after_header_band(replay_engine: Engine, document_id: int) -> None:
"""
对指定 document(默认 194 / 4210012210)用最新 Run 冻结快照重匹配。
历史路由可能失败;本断言验证收紧表头带后应 FOX MX unique_match。
"""
query = text("""
SELECT
run.id AS run_id,
run.input_snapshot_json,
run.schema_version_id,
u.document_id,
u.intake_id
FROM shipping_order_processing_units u
JOIN shipping_order_processing_plans p ON p.id = u.plan_id
JOIN shipping_order_processing_runs run ON run.id = p.run_id
WHERE u.document_id = :document_id
ORDER BY run.id DESC
LIMIT 1
""")
with replay_engine.connect() as conn:
row = conn.execute(query, {'document_id': document_id}).mappings().first()
if row is None:
pytest.skip(f'No processing run for document_id={document_id}')
snapshot = row['input_snapshot_json']
if isinstance(snapshot, str):
snapshot = json.loads(snapshot)
document = _document_from_snapshot(
snapshot,
document_id=int(row['document_id']),
intake_id=int(row['intake_id']),
)
layout = document.get('layout_snapshot') if isinstance(document, dict) else None
if not _layout_ready(layout if isinstance(layout, dict) else None):
pytest.skip(f'Layout not replayable for document_id={document_id}')
profiles = _frozen_profiles(snapshot, schema_version_id=int(row['schema_version_id'] or 0))
result = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
assert result.status == 'unique_match'
if document_id == 194:
assert result.profile_code == 'ODP-20260824-2C542346805B'
else:
assert result.profile_code
@@ -74,6 +74,67 @@ def test_same_input_produces_same_checksum():
assert signature_checksum(first['signature']) == first['signature_checksum']
def test_layout_signature_excludes_line_field_supplement_table_patterns():
"""
补充表不得进入匹配签名 table_patterns。
关键断言:即便补充区样本含料号行文案,签名 identity 也只保留 business_lines,
避免 line_field_supplement 污染表头原子硬互斥。
"""
definition = _minimal_definition()
definition['table_regions'][0]['region_role'] = 'business_lines'
definition['table_regions'][0]['region'] = {'x0': 0, 'y0': 0.2, 'x1': 1, 'y1': 0.55}
definition['table_regions'][0]['line_layouts'][0]['region'] = {
'x0': 0, 'y0': 0.35, 'x1': 1, 'y1': 0.55,
}
definition['table_regions'].append({
'region_id': 'line_supplement',
'region_role': 'line_field_supplement',
'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9},
'line_layouts': [{
'layout_id': 'supp_main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{
'field_id': 'supp-ln',
'field_code': 'customer_po_line_no',
'scope': 'line',
'region': {'x0': 0.05, 'y0': 0.1, 'x1': 0.2, 'y1': 0.4},
'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'supp-pn',
'field_code': 'part_number',
'scope': 'line',
'region': {'x0': 0.25, 'y0': 0.1, 'x1': 0.8, 'y1': 0.4},
'allowed_sources': ['pdf_coordinate'],
},
],
}],
})
layout = _sample_layout(header_text='ITEM NO QTY')
# 补充表区高度内放入料号正文,模拟 HYVE 脏表头污染场景。
dirty = 'WTP-B3-A08AR11000001 CN,TH,JP'
for index, char in enumerate(dirty):
layout['coordinate_evidence']['page_glyphs']['1'].append({
'text': char,
'bbox': {'x0': 10 + index * 3, 'y0': 190, 'x1': 12 + index * 3, 'y1': 202},
})
snapshot = build_layout_signature(definition=definition, sample_layouts=[layout])
patterns = snapshot['signature']['table_patterns']
region_ids = [item.get('region_id') for item in patterns]
assert region_ids == ['lines']
joined = ' '.join(
str(token)
for pattern in patterns
for token in (pattern.get('header_tokens') or [])
).upper()
assert 'WTP-B3-A08AR11000001' not in joined
assert 'CN,TH,JP' not in joined
def test_different_samples_produce_different_checksum():
"""不同表头样本应产生不同 checksum。"""
definition = _minimal_definition()