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 json
import re import re
import zipfile import zipfile
from datetime import datetime from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
@@ -23,6 +23,7 @@ from app import db
from app.core.errors import NotFoundError from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingInventoryFile from app.models import ScheduleRun, ShippingInventoryFile
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task 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 = "原始库存包不存在,请重新执行或联系管理员" _RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
@@ -52,26 +53,38 @@ def get_inventory_archive_dir() -> str:
def _attachment_when_from_run(run: ScheduleRun) -> datetime: def _attachment_when_from_run(run: ScheduleRun) -> datetime:
""" """
推导企微/下载展示名中的时刻。 推导企微/下载展示名中的当地时刻。
核心逻辑:优先 started_at → created_at → finished_at;再尝试解析 RUN{yyyyMMddHHmmss}*; 核心逻辑:started_at → created_at → finished_at → 解析 RUN{yyyyMMddHHmmss}* → utcnow;
最后回退 utcnow。完整 run_no 仍留在卡片与磁盘归档键,不塞进展示名。 上述时刻在库内均为 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): for value in (run.started_at, run.created_at, run.finished_at):
if isinstance(value, datetime): if isinstance(value, datetime):
return value when_utc = value
match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip()) break
if match: if when_utc is None:
try: match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip())
return datetime.strptime(match.group(1), "%Y%m%d%H%M%S") if match:
except ValueError: try:
pass when_utc = datetime.strptime(match.group(1), "%Y%m%d%H%M%S")
return datetime.utcnow() 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: def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
""" """
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}。 库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
Args: Args:
run: 排程执行记录。 run: 排程执行记录。
@@ -5,6 +5,9 @@ services/shipping_notice/document_layout/order_profile_matcher.py
依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。 依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜; 逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column; table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠;
无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient;
身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表; 主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁; 无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。 单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
@@ -46,6 +49,8 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义, # 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义,
# 避免无意义的版本兼容分支。 # 避免无意义的版本兼容分支。
LAYOUT_MATCHING_FEATURES_VERSION = 'v1' LAYOUT_MATCHING_FEATURES_VERSION = 'v1'
# 多表时签名表头原子交集占比达到该阈值才优先于纯 bbox 重叠选主表。
_PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM = 0.5
def _anchor_comparable_text(value: Any) -> str: 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) candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6)
if not hard_valid: 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( return ProfileMatchResult(
status='evidence_insufficient', candidates=rendered, status='evidence_insufficient', candidates=rendered,
top1_score=top1_score, top2_score=top2_score, margin=margin, 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_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
_HEADER_ATOM_MIN_LEN = 3 _HEADER_ATOM_MIN_LEN = 3
_HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]')
def _sanitize_signature_table_identity( def _sanitize_signature_table_identity(
@@ -1069,14 +1080,16 @@ def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
""" """
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。 将表头 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() atoms: set[str] = set()
for token in tokens: for part in re.split(r'[^a-z0-9]+', normalized):
normalized = re.sub(r"['’]", '', str(token).casefold()) if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
for part in re.split(r'[^a-z0-9]+', normalized): atoms.add(part)
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
atoms.add(part)
return frozenset(atoms) return frozenset(atoms)
@@ -1321,10 +1334,11 @@ def _observe_layout_features(
if width > 0 and height > 0: if width > 0 and height > 0:
aspect_ratio = width / height aspect_ratio = width / height
# [STEP 1] 与签名生成一致,按签名表区选择实际业务表;MinerU 的 tables[0] # [STEP 1] 与签名生成一致,按签名表头亲和度与表区选择实际业务表;MinerU 的
# 可能是抬头/元数据表,不能作为运行时默认主表。 # tables[0] 可能是抬头/元数据 KV 表,不能作为运行时默认主表。
primary_bbox = _select_signature_primary_table_bbox( primary_bbox = _select_signature_primary_table_bbox(
tables=tables, pages=pages, signature=signature, tables=tables, pages=pages, signature=signature,
page_glyphs=page_glyphs, glyph_tables=glyph_tables,
) )
# [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。 # [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。
primary_bbox = _clip_observed_primary_table_bbox( primary_bbox = _clip_observed_primary_table_bbox(
@@ -1470,9 +1484,21 @@ def _select_persisted_header_candidate(
def _select_signature_primary_table_bbox( 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: ) -> 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]] = [] normalized_tables: list[list[float]] = []
for table in tables: for table in tables:
page = pages.get(str(table.get('page_no') or 1)) or pages.get(table.get('page_no') or 1) 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 isinstance(item['bbox'].get('median'), list)
and len(item['bbox']['median']) == 4 and len(item['bbox']['median']) == 4
] ]
if not patterns: expected_atoms = _header_token_atoms(_signature_identity_header_tokens(signature))
return normalized_tables[0] glyph_pages = page_glyphs if isinstance(page_glyphs, dict) else {}
best_bbox = normalized_tables[0] table_glyph_map = glyph_tables if isinstance(glyph_tables, dict) else {}
best_overlap = -1.0
for candidate in normalized_tables: def _best_pattern_overlap(candidate: list[float]) -> float:
best = -1.0
for pattern in patterns: for pattern in patterns:
try: try:
expected = [float(value) for value in pattern['bbox']['median']] expected = [float(value) for value in pattern['bbox']['median']]
except (TypeError, ValueError): except (TypeError, ValueError):
continue continue
overlap = _bbox_overlap(expected, candidate) best = max(best, _bbox_overlap(expected, candidate))
if overlap > best_overlap: return best
best_overlap, best_bbox = overlap, candidate
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 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( def _clip_observed_primary_table_bbox(
primary_bbox: list[float] | None, 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|/]+') _HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
def _band_headers_match_signature( def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None:
*, band_tokens: list[str], signature: dict[str, Any] | None, """读取签名首个可用 table_patterns.bbox.median(归一化四点)。"""
) -> bool: for pattern in (signature or {}).get('table_patterns') or []:
"""判断冻结表头带读到的 token 是否足以代表签名表头。 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)] 将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。
if not expected or not band_tokens:
return False 核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0
observed = [str(token).casefold() for token in band_tokens] 平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。
matched = sum(1 for token in expected if token in observed) """
return matched / len(expected) >= 0.5 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( def _observe_primary_table_header(
@@ -1641,10 +1785,12 @@ def _observe_primary_table_header(
primary_bbox: list[float] | None, primary_bbox: list[float] | None,
signature: dict[str, Any] | None, signature: dict[str, Any] | None,
) -> tuple[list[str], list[float], list[float]]: ) -> tuple[list[str], list[float], list[float]]:
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。 """
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用。 核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框
若固定带失准,则基于表体顶部做表头行搜索。单逻辑表头时把折行副标签按 x 并入所属列。 时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行
宽带搜索,避免印刷括号注记污染身份原子。
""" """
if not primary_bbox or len(primary_bbox) != 4: if not primary_bbox or len(primary_bbox) != 4:
return [], [], [] return [], [], []
@@ -1657,14 +1803,23 @@ def _observe_primary_table_header(
page = pages.get('1') or pages.get(1) page = pages.get('1') or pages.get(1)
if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict): if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict):
return [], [], [] return [], [], []
header_bbox = _signature_header_bbox(signature) aligned = _align_signature_header_bbox_to_primary(
region = ( signature=signature, primary_bbox=primary_bbox,
{'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),
}
) )
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) width = float(page.get('width') or 0)
if width <= 0: if width <= 0:
return [], [], [] return [], [], []
@@ -1675,38 +1830,19 @@ def _observe_primary_table_header(
][:32] ][:32]
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans] 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] 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) 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] band_widths = [
single_logical = _signature_single_logical_header(signature) round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans
if single_logical: ]
if _signature_single_logical_header(signature):
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens( merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
band_tokens, band_centers, band_widths, band_tokens, band_centers, band_widths,
) )
band_tokens = [str(item).casefold() for item in merged_tokens] return (
band_centers = list(merged_centers or []) [str(item).casefold() for item in merged_tokens],
band_widths = list(merged_widths or []) list(merged_centers or []),
# 固定带有效 → 直接沿用。 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 band_tokens, band_centers, band_widths return band_tokens, band_centers, band_widths
@@ -6,6 +6,7 @@ services/shipping_notice/document_layout/order_profile_signature.py
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。 逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。 另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
单逻辑表头行将格内折行副标签按 x 并入所属列,保留文案、不拆成新身份列。 单逻辑表头行将格内折行副标签按 x 并入所属列,保留文案、不拆成新身份列。
table_patterns 仅纳入 business_lines;line_field_supplement 不进匹配身份。
""" """
from __future__ import annotations from __future__ import annotations
@@ -198,8 +199,9 @@ def build_layout_signature(
""" """
生成版面签名快照;相同输入必须得到相同 checksum。 生成版面签名快照;相同输入必须得到相同 checksum。
核心逻辑:解析模板表区/表头/字段关系 → 从样本区域读取固定文字 → 多样本聚合 核心逻辑:解析模板表区/表头/字段关系 → 仅对 business_lines 建 table_patterns →
中位数与容差 → 过滤动态值与单样本噪声 → 计算稳定 checksum。 从样本区域读取固定文字 → 多样本聚合中位数与容差 → 过滤动态值与单样本噪声 →
计算稳定 checksum。line_field_supplement 只服务按 LN 补料号,不进匹配身份。
Args: Args:
definition: 当前草稿或冻结 Profile 定义 JSON。 definition: 当前草稿或冻结 Profile 定义 JSON。
@@ -225,11 +227,15 @@ def build_layout_signature(
order_field_layouts=definition.get('order_field_layouts') or [], 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) 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 = [ table_patterns = [
_build_table_pattern(table=table, sample_layouts=sample_layouts) _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) field_relation_graph = _build_field_relation_graph(profile, sample_layouts=sample_layouts)
evidence_quality = _build_evidence_quality( 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() run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow()
db.session.commit() db.session.commit()
return _payload(run) return _payload(run)
path = Path(str(payload.get('file_path') or '')) # Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
if not path.is_file(): # 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() run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
db.session.commit() db.session.commit()
return _payload(run) return _payload(run)
@@ -1204,6 +1204,43 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool:
_EXTRACT_DONE_UNIT_STATUSES = frozenset({ _EXTRACT_DONE_UNIT_STATUSES = frozenset({
'candidate_ready', 'review_required', 'failed', 'cancelled', '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]: 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。
核心逻辑:不再要求 Run 内全部 PDF 版式就绪;只要存在可抽取的 ready Document, 核心逻辑:不再要求 Run 内全部 PDF 版式就绪;只要存在可抽取的 ready Document,
即入队(或复用活跃)shipping_order_extraction。无 ready 活且无 pending、仅有失败版式、 即以抬高 priority 入队(或复用活跃)shipping_order_extraction,避免被剩余 layout
且尚未抽出任何 Unit 时,整 Run 失败收口。 FIFO 堵住。无 ready 活且无 pending、仅有失败版式、且尚未抽出任何 Unit 时整 Run 失败。
""" """
from app.jobs.queue import enqueue
from app.jobs.types import JobType
resumed = 0 resumed = 0
# processing + waiting_layout:部分 Unit 已抽完、仍等兄弟文件版式。 # processing + waiting_layout:部分 Unit 已抽完、仍等兄弟文件版式。
runs = ( 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): if int(document_id) not in _run_snapshot_document_ids(run):
continue continue
if order_extraction_has_extractable_ready_work(run): if order_extraction_has_extractable_ready_work(run):
job_id = enqueue( job_id = _enqueue_ready_order_extraction_job(
JobType.SHIPPING_ORDER_EXTRACTION, run, message='附件解析完成,等待订单识别',
{'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,
) )
run.current_job_id = job_id run.current_job_id = job_id
# 仍有兄弟 layout pending 时保持 waiting_layout,便于再次 resume; # 仍有兄弟 layout pending 时保持 waiting_layout,便于再次 resume;
@@ -1410,11 +1441,8 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
) )
if progressed: if progressed:
# 已有 Unit 成功/复核:再入队一次让 Worker 收口,禁止整 Run 抹掉部分成果。 # 已有 Unit 成功/复核:再入队一次让 Worker 收口,禁止整 Run 抹掉部分成果。
job_id = enqueue( job_id = _enqueue_ready_order_extraction_job(
JobType.SHIPPING_ORDER_EXTRACTION, run, message='部分附件版式失败,等待订单识别收口',
{'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,
) )
run.current_job_id = job_id run.current_job_id = job_id
run.phase = 'queued' run.phase = 'queued'
+1
View File
@@ -1,5 +1,6 @@
[pytest] [pytest]
markers = 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 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 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 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 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): def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
"""单票 DSV 导出应走与批量相同的 session + export 函数。""" """单票 DSV 导出应走与批量相同的 session + export 函数。"""
worker = _load_worker() worker = _load_worker()
@@ -145,6 +145,29 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp
assert ShippingInventoryConfigurationTestRun.query.count() == 1 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): def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。""" """已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
@@ -10,6 +10,7 @@ from __future__ import annotations
import json import json
import zipfile import zipfile
from datetime import datetime
from io import BytesIO from io import BytesIO
from pathlib import Path from pathlib import Path
from urllib.parse import quote 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 ( from app.services.schedule.shipping_inventory_rpa_archive import (
inventory_raw_zip_available_from_summary, inventory_raw_zip_available_from_summary,
inventory_raw_zip_download_name, inventory_raw_zip_download_name,
inventory_rpa_attachment_stem,
inventory_rpa_result_excel_name, inventory_rpa_result_excel_name,
persist_inventory_rpa_raw_zip_archive, persist_inventory_rpa_raw_zip_archive,
resolve_inventory_raw_zip_download, resolve_inventory_raw_zip_download,
@@ -544,6 +546,23 @@ def test_build_zip_entry_name_prefers_source_code():
) == "003_AWSSG.xlsx" ) == "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( def test_get_inventory_raw_zip_returns_404_when_archive_unavailable(
client, client,
app, 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 assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 1
db.session.refresh(run) db.session.refresh(run)
first_job_id = run.current_job_id 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' assert run.phase == 'waiting_layout'
layouts[1].status = 'ready' 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 run.phase == 'queued'
assert job is not None assert job is not None
assert job.job_type == 'shipping_order_extraction' 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): 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 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(): def test_profile_matcher_excludes_below_threshold_hard_candidate_from_uniqueness():
"""硬门禁通过但得分或证据覆盖不合格的候选,不得阻塞唯一合格模板。""" """硬门禁通过但得分或证据覆盖不合格的候选,不得阻塞唯一合格模板。"""
layout = _layout('PLANT NAME: FACTORY A') layout = _layout('PLANT NAME: FACTORY A')
@@ -812,6 +930,207 @@ def _profile_without_required_anchors(code: str, layout: dict) -> dict:
return profile 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(): def test_near_twin_header_discriminator_makes_unique_match():
"""无必选锚点的近亲模板仅差表头原子时,须硬互斥成 unique_match。""" """无必选锚点的近亲模板仅差表头原子时,须硬互斥成 unique_match。"""
mx_header = 'Item Parts No Description REV UNIT QTY Delivery Date Unit Total Price' 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'] 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(): def test_different_samples_produce_different_checksum():
"""不同表头样本应产生不同 checksum。""" """不同表头样本应产生不同 checksum。"""
definition = _minimal_definition() definition = _minimal_definition()
+1 -1
View File
@@ -200,7 +200,7 @@
- **RPA 旁路**:RPA Profile 只用于定时库存导出、用户手动刷新和配置测试;排程以 `source_codes` 为目标,按 Profile 分组复用登录,但每个文件必须独立记录 Source。 - **RPA 旁路**:RPA Profile 只用于定时库存导出、用户手动刷新和配置测试;排程以 `source_codes` 为目标,按 Profile 分组复用登录,但每个文件必须独立记录 Source。
- **配置归属**:连接配置只保存登录地址、加密凭据和连接级登录配置;库存源只持久化 `report_path_json` 与 `query_parameters_json`。DBS 路径为业务组/业务项目/报表分组/报表名;参数支持单选、文本多值、列表多选。订单到库存站点的选择只由版本化路由规则决定。 - **配置归属**:连接配置只保存登录地址、加密凭据和连接级登录配置;库存源只持久化 `report_path_json` 与 `query_parameters_json`。DBS 路径为业务组/业务项目/报表分组/报表名;参数支持单选、文本多值、列表多选。订单到库存站点的选择只由版本化路由规则决定。
- **解析方案直接绑定(一期)**:停用库存站点在编辑表单直接选择已发布的库存文件解析方案,随“保存更改”一次提交;批量绑定仍执行全量预检并写追加式前后快照审计。管理员无需填写绑定原因;已启用站点、草稿/退役方案及发货模板库存字段不兼容时必须拒绝。绑定递增站点配置版本,使旧测试证据失效。 - **解析方案直接绑定(一期)**:停用库存站点在编辑表单直接选择已发布的库存文件解析方案,随“保存更改”一次提交;批量绑定仍执行全量预检并写追加式前后快照审计。管理员无需填写绑定原因;已启用站点、草稿/退役方案及发货模板库存字段不兼容时必须拒绝。绑定递增站点配置版本,使旧测试证据失效。
- **自动启用(二期)**:当前绑定的已发布解析方案通过本次配置测试(或已绑定解析的查询成功但无库存)后,后端复用同一正式门禁自动启用站点;必要条件缺失时绝不启用。前端不提供“确认绑定”或“启用站点”二次操作,只显示当前唯一阻塞项及其操作。Dify 无需配置变更。 - **自动启用(二期)**:当前绑定的已发布解析方案通过本次配置测试(或已绑定解析的查询成功但无库存)后,后端复用同一正式门禁自动启用站点;必要条件缺失时绝不启用。首次启用不提供“确认绑定”二次操作,只显示当前唯一阻塞项及其操作。站点停用后若正式门禁仍满足,管理端提供“启用库存站点”按钮(调用既有 activate API);也可再次测试导出以触发自动启用。Dify 无需配置变更。
- **空库存语义(二期)**:RPA 查询成功但无库存是有效业务结果,不得显示为连接或导出失败。站点验证区分“连接/查询已验证”与“数据行待首次非空文件验证”;已绑定 published 方案及发货模板的站点可继续启用。行级解析验证与外部仓库映射均不阻断启用:前者在首次非空文件到达时验证,后者只在实际调拨前要求维护。调度空结果写入不可匹配的 `empty` 快照审计,绝不链接任务、参与库存匹配或生成发货 Excel。 - **空库存语义(二期)**:RPA 查询成功但无库存是有效业务结果,不得显示为连接或导出失败。站点验证区分“连接/查询已验证”与“数据行待首次非空文件验证”;已绑定 published 方案及发货模板的站点可继续启用。行级解析验证与外部仓库映射均不阻断启用:前者在首次非空文件到达时验证,后者只在实际调拨前要求维护。调度空结果写入不可匹配的 `empty` 快照审计,绝不链接任务、参与库存匹配或生成发货 Excel。
- **字段隔离**:订单行仅使用 `inventory_source_hint` 保存可选路由线索;`connector_type` 仅允许 `dbs` / `crane` 并用于 Driver 分发,不得复用 `ShippingTask.source_type`;不再使用 `site_id`。 - **字段隔离**:订单行仅使用 `inventory_source_hint` 保存可选路由线索;`connector_type` 仅允许 `dbs` / `crane` 并用于 Driver 分发,不得复用 `ShippingTask.source_type`;不再使用 `site_id`。
- **Warehouse**:固定 Source 直接使用配置 Warehouse;动态 Source(Crane)以 `reservation_id + part_number` 从库存行取得 Warehouse,不维护 Crane Warehouse 清单。Warehouse 未解析或冲突时不得生成 Excel。 - **Warehouse**:固定 Source 直接使用配置 Warehouse;动态 Source(Crane)以 `reservation_id + part_number` 从库存行取得 Warehouse,不维护 Crane Warehouse 清单。Warehouse 未解析或冲突时不得生成 Excel。
+5 -3
View File
@@ -1188,8 +1188,6 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工
| `pending` / `document_queued` | `pending` / `document_queued` | 已接收,排队等待处理 | | `pending` / `document_queued` | `pending` / `document_queued` | 已接收,排队等待处理 |
| `waiting_layout` / `layout_parsing_started` | `waiting_layout` / `layout_parsing_started` | 正在预处理文档结构 | | `waiting_layout` / `layout_parsing_started` | `waiting_layout` / `layout_parsing_started` | 正在预处理文档结构 |
| `routing` | `routing` | 正在识别文件类型与处理规则 | | `routing` | `routing` | 正在识别文件类型与处理规则 |
> **版式→抽取放行(Unit 级,2026-09-08)**:`waiting_layout` 表示 Run 内仍有 PDF 版式未完成,不再要求全部 layout 就绪才开始订单抽取。任一 PDF layout ready 即可抽取对应 Unit 并 `progress_ready_extraction_unit`;兄弟文件继续等待。Run 终态仍须等全部 Unit 收敛。
| `matching_profile` / `profile_matching` | `matching_profile` | 正在匹配订单解析模板 | | `matching_profile` / `profile_matching` | `matching_profile` | 正在匹配订单解析模板 |
| `extracting` / `table_reconstructed` / `order_fields_extracted` | `extracting` | 正在提取订单信息 | | `extracting` / `table_reconstructed` / `order_fields_extracted` | `extracting` | 正在提取订单信息 |
| `merging_supplement` / `email_supplement_merged` | `merging_supplement` | 正在合并邮件正文补充信息 | | `merging_supplement` / `email_supplement_merged` | `merging_supplement` | 正在合并邮件正文补充信息 |
@@ -1201,6 +1199,8 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工
| `cancelled` / `unit_cancelled` / `cancellation_completed` | `cancelled` | 已取消 | | `cancelled` / `unit_cancelled` / `cancellation_completed` | `cancelled` | 已取消 |
| Run/Unit 成功终态 | `completed` | 处理完成 | | Run/Unit 成功终态 | `completed` | 处理完成 |
> **版式→抽取放行(Unit 级,2026-09-08)**:`waiting_layout` 表示 Run 内仍有 PDF 版式未完成,不再要求全部 layout 就绪才开始订单抽取。任一 PDF layout ready 即可抽取对应 Unit 并 `progress_ready_extraction_unit`;兄弟文件继续等待。Run 终态仍须等全部 Unit 收敛。layout 与 extraction 共 shipping 队列时,resume 入队的 extraction 使用抬高的 `priority`,避免被剩余 layout FIFO 堵住。
- 投影字段冻结:`user_visible_stage`、`queue_position`(仅排队 Unit)、`elapsed_seconds`、`last_activity_at`、`health_tips[]`、`cancellation`、`available_actions`、`handling_items[]`(Run 级待补/冲突/冻结/复核/失败/预算停扩)、`primary_notice`、`progress_version`(Run)/`activity_version`(Unit)。 - 投影字段冻结:`user_visible_stage`、`queue_position`(仅排队 Unit)、`elapsed_seconds`、`last_activity_at`、`health_tips[]`、`cancellation`、`available_actions`、`handling_items[]`(Run 级待补/冲突/冻结/复核/失败/预算停扩)、`primary_notice`、`progress_version`(Run)/`activity_version`(Unit)。
- Run 收口 `result_json` 保留受控处理事实:`pending_orders`(候选号/原因/缺失字段)、`auto_freeze.blocked_tasks`、`budget_stopped`;聊天卡与右侧「本次处理」按 `handling_items.category` 展示原因码、`affected_refs`(任务号/候选号/受限附件)与 `primary_action` 跳转,禁止仅用 `partially_completed`/`review_required` 笼统提示。聊天消息持久化去重签名包含 `handling_items`/`primary_notice`,保证历史会话恢复最新处理说明。 - Run 收口 `result_json` 保留受控处理事实:`pending_orders`(候选号/原因/缺失字段)、`auto_freeze.blocked_tasks`、`budget_stopped`;聊天卡与右侧「本次处理」按 `handling_items.category` 展示原因码、`affected_refs`(任务号/候选号/受限附件)与 `primary_action` 跳转,禁止仅用 `partially_completed`/`review_required` 笼统提示。聊天消息持久化去重签名包含 `handling_items`/`primary_notice`,保证历史会话恢复最新处理说明。
- 健康提示阈值(后端统一计算,前端禁止本地臆造):连续 60 秒无新活动 → `processing_slow`;排队超过 5 分钟 → `queue_backlog`;处理超过 30 分钟 → `processing_attention`。 - 健康提示阈值(后端统一计算,前端禁止本地臆造):连续 60 秒无新活动 → `processing_slow`;排队超过 5 分钟 → `queue_backlog`;处理超过 30 分钟 → `processing_attention`。
@@ -3173,6 +3173,7 @@ API 层
- RPA 配置测试回调只在当前绑定方案为本次文件的 `exact`/`compatible` 候选时,写入 `current_profile_verified` 证据;候选为其他方案时只提示管理员在表单选择、保存并重新测试,绝不自动替换绑定。 - RPA 配置测试回调只在当前绑定方案为本次文件的 `exact`/`compatible` 候选时,写入 `current_profile_verified` 证据;候选为其他方案时只提示管理员在表单选择、保存并重新测试,绝不自动替换绑定。
- 对于当前绑定 published 方案,非空测试验证成功或空库存查询成功后,`inventory_configuration_test.report_test_export` 在同一事务调用 `shipping_inventory_service.activate_source_if_ready`。该函数复用 `get_source_activation_status`,仅当连接、解析方案、发货模板、模板字段契约及当前版本测试证据全部通过时设置 `source.enabled=True`。 - 对于当前绑定 published 方案,非空测试验证成功或空库存查询成功后,`inventory_configuration_test.report_test_export` 在同一事务调用 `shipping_inventory_service.activate_source_if_ready`。该函数复用 `get_source_activation_status`,仅当连接、解析方案、发货模板、模板字段契约及当前版本测试证据全部通过时设置 `source.enabled=True`。
- 自动启用不放宽任何门禁:缺少发货模板、模板字段不兼容、配置/连接版本已变更时均保持停用;外部仓库映射和首次非空文件的数据行验证仍属于后续流程,不阻断站点启用。Dify 无需修改配置。 - 自动启用不放宽任何门禁:缺少发货模板、模板字段不兼容、配置/连接版本已变更时均保持停用;外部仓库映射和首次非空文件的数据行验证仍属于后续流程,不阻断站点启用。Dify 无需修改配置。
- **停用后再启用**:停用后若 `activation.ready` 仍为真,管理端显示“启用库存站点”并调用既有 `POST /sources/{id}/activate`(与自动启用同一门禁);表单有未保存修改时禁用该按钮。也可再次测试导出以触发 `activate_source_if_ready`。
### 6.3 快照复用规则 ### 6.3 快照复用规则
@@ -3191,13 +3192,14 @@ API 层
- **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值) - **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值)
- **报表控件模板**(2026-08-26):同一参数名在不同报表的 SSRS 控件长相不同(`On Hand Inventory By Location 3lv` 的 Warehouse 是原生 select `ddValue`,JDA 版 `On Hand Inventory by Location` 是 txtValue/toggle/divDropDown 多选框下拉)。控件差异由 Worker 按归一化报表名登记在 `dsv_report_parameters._DSV_REPORT_PARAM_TEMPLATES`,填参时把 `report_name` 透传到模块解析;`selector_env/selectors` 继续不进入数据库,未登记报表回退参数名默认值。填参失败会输出参数区控件探针日志(`[dsv-filter] ... control probe`),便于定位控件 ID/类型漂移。 - **报表控件模板**(2026-08-26):同一参数名在不同报表的 SSRS 控件长相不同(`On Hand Inventory By Location 3lv` 的 Warehouse 是原生 select `ddValue`,JDA 版 `On Hand Inventory by Location` 是 txtValue/toggle/divDropDown 多选框下拉)。控件差异由 Worker 按归一化报表名登记在 `dsv_report_parameters._DSV_REPORT_PARAM_TEMPLATES`,填参时把 `report_name` 透传到模块解析;`selector_env/selectors` 继续不进入数据库,未登记报表回退参数名默认值。填参失败会输出参数区控件探针日志(`[dsv-filter] ... control probe`),便于定位控件 ID/类型漂移。
- Worker:`scripts/rpa/inventory/inventory_rpa_worker.py` → `_handle_inventory_batch_trigger` - Worker:`scripts/rpa/inventory/inventory_rpa_worker.py` → `_handle_inventory_batch_trigger`
- **DOM 假空兜底**(2026-09-09):`result_ready` 后 DOM 明细行探测仅作加速;无行时重试一次 View Report,仍无行则继续 Excel 导出。真空只在落盘 Excel「有 Supplier ID/AWS Sku 表头但无明细」时记 `NoInventoryDataError`/`no_inventory_data`,避免 Salt Lake 等慢报表假 skip。
- 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready` - 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready`
- **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts/<callback_id>/`、创建 `shipping_inventory_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。 - **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts/<callback_id>/`、创建 `shipping_inventory_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。
- **单票身份与失败收口**(2026-08-20):首次自动库存准备和用户重试均必须经 `ensure_all_required_sources_prepared` 创建逐源 Attempt;禁止写缺少 `source_run_no / lease_token / candidate_set_id / execution_id / gate_id` 的旧 task 级 trigger。Worker 发现 `trigger_identity_invalid` 时必须在 `results[]` 回传可用的 source 身份片段;后端按已定位的 Attempt 立即标记失败、同步 PreparationSourceAttempt、`inventory_preparation` Gate 与 `step3_inventory_prepare=needs_human`,不得等待库存轮询超时。 - **单票身份与失败收口**(2026-08-20):首次自动库存准备和用户重试均必须经 `ensure_all_required_sources_prepared` 创建逐源 Attempt;禁止写缺少 `source_run_no / lease_token / candidate_set_id / execution_id / gate_id` 的旧 task 级 trigger。Worker 发现 `trigger_identity_invalid` 时必须在 `results[]` 回传可用的 source 身份片段;后端按已定位的 Attempt 立即标记失败、同步 PreparationSourceAttempt、`inventory_preparation` Gate 与 `step3_inventory_prepare=needs_human`,不得等待库存轮询超时。
- 定时排程:`schedule_type=platform_job`,`platform_api_path=shipping-inventory-rpa`,`data_source_type=null`;建议 cron `0 3 * * *`(Asia/Shanghai) - 定时排程:`schedule_type=platform_job`,`platform_api_path=shipping-inventory-rpa`,`data_source_type=null`;建议 cron `0 3 * * *`(Asia/Shanghai)
- 排程语义:`data_source_type` 仅用于 `schedule_type=data_pipeline`(`database` | `external_api`);平台任务通过 Job Registry 注册,由 `platform_api_path` 引用 job key - 排程语义:`data_source_type` 仅用于 `schedule_type=data_pipeline`(`database` | `external_api`);平台任务通过 Job Registry 注册,由 `platform_api_path` 引用 job key
- **排程完成企微通知门禁**(`_notify_schedule_run_wecom`,2026-08-26 排障确认):finalize 成功后按序检查 ① `response_summary_json.domain_notification_managed`(领域自管时跳过)→ ② `WECOM_NOTIFY_ENABLED`(默认 true,被本地 `.env.local` 覆盖为 false 会静默拦截并写 `schedule_runs.wecom_notify_error='WECOM_NOTIFY_ENABLED=false'`)→ ③ `schedule_completed` ∈ `WECOM_NOTIFY_EVENTS`(本地覆盖列表漏掉它时同样拦截)→ ④ 任务 `notify_enabled` 且 `notify_user_ids_json` 非空 → ⑤ 用户已绑 `wecom_userid`。任一环节不满足都不发消息;排障先查 `schedule_runs.wecom_notified / wecom_notify_error`,再对 `app_settings`(DB 权威源)与 `.env.<env>` 的合并结果核对 ②③(DB 优先于 env 文件)。 - **排程完成企微通知门禁**(`_notify_schedule_run_wecom`,2026-08-26 排障确认):finalize 成功后按序检查 ① `response_summary_json.domain_notification_managed`(领域自管时跳过)→ ② `WECOM_NOTIFY_ENABLED`(默认 true,被本地 `.env.local` 覆盖为 false 会静默拦截并写 `schedule_runs.wecom_notify_error='WECOM_NOTIFY_ENABLED=false'`)→ ③ `schedule_completed` ∈ `WECOM_NOTIFY_EVENTS`(本地覆盖列表漏掉它时同样拦截)→ ④ 任务 `notify_enabled` 且 `notify_user_ids_json` 非空 → ⑤ 用户已绑 `wecom_userid`。任一环节不满足都不发消息;排障先查 `schedule_runs.wecom_notified / wecom_notify_error`,再对 `app_settings`(DB 权威源)与 `.env.<env>` 的合并结果核对 ②③(DB 优先于 env 文件)。
- **库存 RPA 企微/下载文件名**(2026-09-09):展示名统一为 `库存RPA-{yyyyMMdd}-{HHmm}-结果.xlsx` 与 `库存RPA-{yyyyMMdd}-{HHmm}-库存.zip`;完整 `run_no` 只留在 textcard 与磁盘归档键 `{run_no}.zip`。ZIP 包内条目为 `{序号}_{source_code}.xlsx`(无 source_code 时回退仓码);`warehouse_id` / `inventory_file_no` 仅写入 `manifest.json`。 - **库存 RPA 企微/下载文件名**(2026-09-09):展示名统一为 `库存RPA-{yyyyMMdd}-{HHmm}-结果.xlsx` 与 `库存RPA-{yyyyMMdd}-{HHmm}-库存.zip`(`HHmm` 按任务 `schedule_timezone`,缺省 Asia/Shanghai,勿直接用 UTC/`run_no` 内嵌时刻);完整 `run_no` 只留在 textcard 与磁盘归档键 `{run_no}.zip`。ZIP 包内条目为 `{序号}_{source_code}.xlsx`(无 source_code 时回退仓码);`warehouse_id` / `inventory_file_no` 仅写入 `manifest.json`。
- **空快照状态约束**(2026-08-26):`create_empty_rpa_inventory_snapshot` 写入 `snapshot_status='empty'`(no_inventory_data 审计快照),依赖迁移 `hq0r1s2t3u4v` 把 `ck_shipping_inventory_files_snapshot_status` 检查约束从 `('ready','failed','expired')` 放宽为含 `'empty'`;未执行该迁移(或回退版本)时,批量回调插入空快照会触发 CheckViolation 导致整笔 Job 事务回滚、ScheduleRun 停在 awaiting 后被超时回收为 failed。 - **空快照状态约束**(2026-08-26):`create_empty_rpa_inventory_snapshot` 写入 `snapshot_status='empty'`(no_inventory_data 审计快照),依赖迁移 `hq0r1s2t3u4v` 把 `ck_shipping_inventory_files_snapshot_status` 检查约束从 `('ready','failed','expired')` 放宽为含 `'empty'`;未执行该迁移(或回退版本)时,批量回调插入空快照会触发 CheckViolation 导致整笔 Job 事务回滚、ScheduleRun 停在 awaiting 后被超时回收为 failed。
### 6.5 审计字段 ### 6.5 审计字段
@@ -0,0 +1,199 @@
# 库存 RPA 跨订单按源合并(Source Coalesce)设计
> 日期:2026-09-10
> 状态:已确认(brainstorming)
> 范围:货代发货通知 · 库存准备 / 按需 RPA trigger 去重
> 相关实现:`per_source_rpa_service.py`、`inventory_workflow.py`、`inventory_rpa_workflow.py`、`rpa.py`、`ShippingTaskInventoryRpaAttempt`
---
## 1. 问题
订单解析后自动推进库存准备时,若无可复用库存快照,会按单触发 RPA 并写入 trigger 文件。
当**尚未跑过定时批次 RPA**,且**一次提交解析大量订单**时:
- 多单常依赖同一 `source_code`(同仓/同站点)
- 每单各自写一份(或单源 batch 包装的)trigger
- Worker 对同一源重复登录、导出,吞吐差、外部站点压力大
单票内「多源合并为一个 batch trigger」已存在(`ensure_all_required_sources_prepared`);缺口是 **跨订单、按源去重**。
---
## 2. 目标与非目标
### 目标
1. **快照优先**:未过期 ready 源级快照直接复用,零 RPA。
2. **跨单按源合并**:同一 `source_code` 同时最多一次活动导出(一个 Leader + 一个 trigger)。
3. **挂等**:其它订单以 Follower 挂到同一 `source_run_no`,不写 trigger。
4. **成功唤醒**:回调落源级快照后,唤醒挂等单走「复用快照」路径续跑(避免海量空转轮询)。
5. **失败同败**:Leader 失败/超时 → 同组 Follower 一并失败;不自动连环重试。
6. **人工强制重抓**:`retry_rpa` 跳过复用与挂等,强制新开 Leader。
### 非目标
- 不新建「全局 Fetch」大表(在现有 Attempt 上扩展角色即可)。
- 不改 Worker 导出协议 / 一次登录导全世界的新能力。
- 不以长防抖窗口作为主路径。
- 不禁止按需自动 RPA(仍自动推进;只去重)。
---
## 3. 已定决策
| # | 决策 | 选择 |
| --- | --- | --- |
| D1 | 优先级 | 未过期快照 → 再跨单按源合并 |
| D2 | 已有 in-flight | `auto` 挂等;`retry_rpa` 强制新开 |
| D3 | 同时缺快照如何合成一次 | **源级租约**:抢到锁的写 trigger,其余立刻挂等 |
| D4 | 成功后如何推进挂等单 | **混合**:源级落快照 + 唤醒 `auto_progress`/`ensure_inventory`,内部仍走复用路径 |
| D5 | Leader 失败 | **同败**:挂等单一并失败,各自提供 retry/上传入口 |
| D6 | 实现路线 | 方案一:源级租约 + Leader/Follower Attempt |
---
## 4. 架构与数据模型
### 4.1 角色
| 角色 | 含义 |
| --- | --- |
| **Leader Attempt** | 抢到源级租约的订单:写 trigger,持有 Worker 身份键(`source_run_no` / `lease_token` 等) |
| **Follower Attempt** | 挂等订单:同 `source_code` + 同 `source_run_no`,**不写** trigger,不进 trigger 文件的 `inventory_sources[]` |
### 4.2 Attempt 扩展(建议字段)
在 `ShippingTaskInventoryRpaAttempt` 上增加(名称可在实现计划中微调,语义固定):
- `role`:`leader` | `follower`(历史行默认视为 `leader`)
- `leader_task_no`:Follower 指向 Leader 的 `task_no`(Leader 自身可空或自指)
- `coalesce_group_id`:与共享的 `source_run_no` 对齐(或直接约定 `coalesce_group_id == source_run_no`,避免双键漂移)
保留现有逐单 Attempt 审计、Gate/UI 对 `(task_no, source_code)` 状态的消费方式。
### 4.3 并发约束
1. **源级**:同一 `source_code` 同时最多 1 个 Leader(`status IN ('queued','running')`)——部分唯一索引或等价行锁。
2. **单级**:保留现有 `(task_no, source_code)` 活动唯一,防止同单双点。
3. **抢锁失败**:立即转 Follower,禁止自旋写盘。
4. **定时批次**:若 scheduled 已是同源活动 Leader,按需 `auto` 只当 Follower。
### 4.4 多源订单
按源独立决策:源 X 可挂等、源 Y 可本单当 Leader;全部 required 源 `prepared` 后才进入匹配。
---
## 5. 数据流
### 5.1 `ensure_all_required_sources_prepared`(按源)
```text
[1] mode != retry_rpa 且存在未过期 ready 快照
→ prepared
[2] 查同源是否已有活动 Leader(任意 task,queued|running)
→ 本单建 Follower Attempt(同 source_run_no)
→ pending,不写 trigger
[3] 否则抢源级租约
→ 成功:建 Leader Attempt,加入本轮待写 trigger 列表
→ 失败:回到 [2] 挂成 Follower
[4] 循环结束
→ 仅本轮 Leader 源合并写入一个 batch trigger(延续单票内合并)
→ Follower 不出现在 trigger 文件中
```
`retry_rpa`:跳过 [1][2],对本单该源强制新 Leader;可按现语义将旧活动 Attempt 标 `superseded`。
若其它单的 Follower 挂在被 supersede 的 `source_run_no` 上,跟随失败/被取代(见 §6)。
### 5.2 成功回调
```text
Worker 回调 → 以 Leader 身份键命中
→ ingest 源级快照
→ Leader → succeeded
→ 同 coalesce_group 的 Follower → succeeded(共享 inventory_file_no)
→ 对受影响 task_no 去重后入队 auto_progress / ensure_inventory
└─ 内部走复用快照,禁止二次写 trigger
```
### 5.3 失败回调 / 超时
```text
Leader failed | timeout
→ 同组 Follower 一并 failed(同 error_code / message)
→ 各单走现有失败收口(retry_rpa / 上传)
→ 不自动连环重试
```
### 5.4 与轮询关系
- 推进主路径:回调唤醒(D4)。
- `poll` / `allow_auto_retry=False`:只读 Attempt 与快照事实,禁止新建 Attempt、禁止写 trigger。
- UI 挂等期间可继续展示 `running`(有 Follower Attempt 事实)。
---
## 6. 错误处理与边界
| 场景 | 行为 |
| --- | --- |
| Leader 回调失败 / 超时 | 同组 Follower 同败;现有 timeout/exhausted 恢复动作 |
| 迟到回调(旧 `source_run_no`) | `superseded`;不覆盖已消费状态;不二次唤醒 |
| Leader 写 trigger 失败 | Leader + 本轮拟挂 Follower → `failed/trigger_not_written` |
| Worker 离线 | 现有心跳门禁;不抢租约、不写 trigger |
| `retry_rpa` | 仅该单该源新 Leader;不踢掉无关单的活动 Attempt;挂在被取代 `source_run_no` 上的 Follower 随组失败/取代 |
| 唤醒后快照已过期 | 重新走 [2][3],不假定一次成功永续 |
| 唤醒入队 | 同一回调对同一 `task_no` 只入队一次(job dedupe) |
---
## 7. 组件落点(实现指引,非本 spec 任务拆解)
| 区域 | 变更要点 |
| --- | --- |
| `ShippingTaskInventoryRpaAttempt` + 迁移 | `role` / `leader_task_no`(及源级 Leader 唯一约束) |
| `per_source_rpa_service.ensure_all_required_sources_prepared` | 快照 → 查跨单 Leader → 租约 → Leader/Follower 分流;trigger 仅含 Leader |
| 库存 RPA 回调路径 | 成功/失败扇出同组 Attempt;成功后唤醒受影响任务 |
| `queue_service` / auto_progress 入队 | 回调唤醒去重 |
| 测试 | 见 §8 |
Worker 与 batch v2 trigger 契约保持不变;Follower 身份不进入 Worker 输入。
---
## 8. 测试要点
1. **快照优先**:同源未过期快照 → 0 trigger,多单 prepared。
2. **跨单挂等**:A 为 Leader,B/C `auto` → 仅 1 个 trigger;B/C 为 Follower。
3. **成功扇出**:回调后 A/B/C 均可复用快照且被唤醒(断言入队次数)。
4. **失败同败**:Leader fail → Followers 同 `error_code`。
5. **并发抢租约**:双请求同时缺快照 → 1 Leader + 1 Follower,1 个 trigger。
6. **retry_rpa**:强制新 Leader/新 trigger,不复用旧快照。
7. **多源混合**:X 挂等、Y 本单 Leader → trigger 仅含 Y。
8. **poll 只读**:`allow_auto_retry=False` 不新建 Attempt、不写 trigger。
---
## 9. 验收标准
- 大批量解析且多单同仓、无预热快照时:同源活动导出次数 ≈ 1(而非 ≈ 订单数)。
- 有未过期快照时:不因解析批量而写 trigger。
- 挂等单在 Leader 成功后能自动续跑,无需依赖高频空转 poll。
- Leader 失败时挂等单可解释地进入现有人工恢复,且无自动重试打爆。
- `retry_rpa` 仍可绕过挂等强制重抓。
---
## 10. 开放实现细节(计划阶段拍板即可)
以下不影响本设计语义,留给 implementation plan:
- `coalesce_group_id` 是否物理列,或直接等于 `source_run_no`。
- 源级 Leader 唯一用 PostgreSQL 部分唯一索引 vs 独立租约行。
- 唤醒调用 `submit_auto_progress` 还是直接 `ensure_inventory` 的精确入口。
- 历史 Attempt 回填:`role` 默认 `leader` 的迁移策略。
@@ -171,8 +171,16 @@
<p v-if="!configurationTest.result?.current_profile_verified && !(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p> <p v-if="!configurationTest.result?.current_profile_verified && !(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section> </section>
</template> </template>
<footer v-if="source.enabled" class="readiness-footer"> <footer v-if="source.enabled || source.activation?.ready" class="readiness-footer">
<button type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button> <button v-if="source.enabled" type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
<button
v-else
type="button"
class="btn-primary btn-sm"
:disabled="sourceDirty"
:title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined"
@click="requestSourceActivation"
>{{ t('admin.shippingInventory.activateSource') }}</button>
</footer> </footer>
</section> </section>
<div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div> <div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div>
@@ -460,6 +468,7 @@ import {
deleteShippingInventoryParsingProfile, deleteShippingInventoryParsingProfile,
deleteShippingInventoryRule, deleteShippingInventoryRule,
deleteShippingInventorySource, deleteShippingInventorySource,
activateShippingInventorySource,
deactivateShippingInventorySource, deactivateShippingInventorySource,
deleteShippingRpaProfile, deleteShippingRpaProfile,
getShippingInventoryConfig, getShippingInventoryConfig,
@@ -527,7 +536,7 @@ const orderSchemaPublished = ref(false);
const saving = ref(false); const saving = ref(false);
const confirmation = reactive({ const confirmation = reactive({
visible: false, visible: false,
action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'deactivateSource' | 'replaceInventorySample' | '', action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'activateSource' | 'deactivateSource' | 'replaceInventorySample' | '',
title: '', title: '',
message: '', message: '',
confirmText: '', confirmText: '',
@@ -1248,7 +1257,7 @@ function openConfirmation(action: Exclude<typeof confirmation.action, ''>, messa
confirmation.visible = true; confirmation.visible = true;
} }
/** 执行用户在统一确认弹窗中确认的删除或归档动作。 */ /** 执行用户在统一确认弹窗中确认的删除、启停或归档动作。 */
async function confirmPendingAction(): Promise<void> { async function confirmPendingAction(): Promise<void> {
if (!selectedId.value || !confirmation.action) return; if (!selectedId.value || !confirmation.action) return;
const action = confirmation.action; const action = confirmation.action;
@@ -1258,6 +1267,11 @@ async function confirmPendingAction(): Promise<void> {
if (action === 'retireTemplate') await retireShippingExcelTemplate(selectedId.value); if (action === 'retireTemplate') await retireShippingExcelTemplate(selectedId.value);
if (action === 'retireParsing') await retireShippingInventoryParsingProfile(selectedId.value); if (action === 'retireParsing') await retireShippingInventoryParsingProfile(selectedId.value);
if (action === 'retireInventoryField') await retireShippingInventoryField(selectedId.value); if (action === 'retireInventoryField') await retireShippingInventoryField(selectedId.value);
if (action === 'activateSource') {
await activateShippingInventorySource(selectedId.value);
await refreshSelectedSource();
return;
}
if (action === 'deactivateSource') await deactivateShippingInventorySource(selectedId.value); if (action === 'deactivateSource') await deactivateShippingInventorySource(selectedId.value);
if (action === 'replaceInventorySample') { sampleReplacementConfirmed.value = true; await saveCurrent(); return; } if (action === 'replaceInventorySample') { sampleReplacementConfirmed.value = true; await saveCurrent(); return; }
if (action === 'delete' && activeTab.value === 'profiles') await deleteShippingRpaProfile(selectedId.value); if (action === 'delete' && activeTab.value === 'profiles') await deleteShippingRpaProfile(selectedId.value);
@@ -1274,6 +1288,20 @@ async function confirmPendingAction(): Promise<void> {
function clearConfirmation(): void { confirmation.visible = false; confirmation.action = ''; } function clearConfirmation(): void { confirmation.visible = false; confirmation.action = ''; }
/**
* 停用后条件仍满足时,经确认弹窗调用已有 activate API 再次启用。
* 核心逻辑:未保存编辑一律阻断;服务端仍复用正式门禁,前端不放宽启用条件。
*/
function requestSourceActivation(): void {
if (!selectedId.value || sourceDirty.value || !source.activation?.ready) return;
confirmation.visible = true;
confirmation.action = 'activateSource';
confirmation.title = t('admin.shippingInventory.activateSource');
confirmation.message = t('admin.shippingInventory.activateSourceConfirm');
confirmation.confirmText = t('admin.shippingInventory.activateSource');
confirmation.tone = 'primary';
}
/** 停用动作使用平台确认弹窗,防止误将正在运行的库存站点下线。 */ /** 停用动作使用平台确认弹窗,防止误将正在运行的库存站点下线。 */
function requestSourceDeactivation(): void { function requestSourceDeactivation(): void {
confirmation.visible = true; confirmation.visible = true;
+2 -2
View File
@@ -920,9 +920,9 @@
"saveBeforeReadinessAction": "Save the current inventory-site changes before taking this action.", "saveBeforeReadinessAction": "Save the current inventory-site changes before taking this action.",
"activationReady": "The inventory site is enabled and can run in production.", "activationReady": "The inventory site is enabled and can run in production.",
"activationDraft": "The inventory site is disabled. Complete the following items before activation.", "activationDraft": "The inventory site is disabled. Complete the following items before activation.",
"activationCanEnable": "All enablement conditions pass. The system is enabling this inventory site automatically.", "activationCanEnable": "All enablement conditions pass. You can enable this inventory site.",
"activationEnabledHint": "This site participates in production inventory runs.", "activationEnabledHint": "This site participates in production inventory runs.",
"activationCanEnableHint": "The site starts production runs automatically after the next successful test of this configuration.", "activationCanEnableHint": "Click Enable Inventory Site to start production runs, or run another successful test export to auto-enable.",
"activationMissingHint": "Complete only the unfinished required items. Later preparation does not block enablement.", "activationMissingHint": "Complete only the unfinished required items. Later preparation does not block enablement.",
"activationRequirement": { "activationRequirement": {
"rpa_profile": "System connection is available", "rpa_profile": "System connection is available",
+2 -2
View File
@@ -920,9 +920,9 @@
"saveBeforeReadinessAction": "โปรดบันทึกการเปลี่ยนแปลงไซต์สต็อกปัจจุบันก่อนดำเนินการนี้", "saveBeforeReadinessAction": "โปรดบันทึกการเปลี่ยนแปลงไซต์สต็อกปัจจุบันก่อนดำเนินการนี้",
"activationReady": "เปิดใช้งานไซต์สต็อกแล้วและพร้อมใช้งานจริง", "activationReady": "เปิดใช้งานไซต์สต็อกแล้วและพร้อมใช้งานจริง",
"activationDraft": "ไซต์สต็อกยังปิดใช้งาน โปรดทำรายการต่อไปนี้ให้เสร็จก่อนเปิดใช้งาน", "activationDraft": "ไซต์สต็อกยังปิดใช้งาน โปรดทำรายการต่อไปนี้ให้เสร็จก่อนเปิดใช้งาน",
"activationCanEnable": "ผ่านทุกเงื่อนไขแล้ว ระบบกำลังเปิดใช้งานไซต์สต็อกโดยอัตโนมัติ", "activationCanEnable": "ผ่านทุกเงื่อนไขแล้ว สามารถเปิดใช้งานไซต์สต็อกนี้ได้",
"activationEnabledHint": "ไซต์นี้เข้าร่วมการทำงานสต็อกจริงแล้ว", "activationEnabledHint": "ไซต์นี้เข้าร่วมการทำงานสต็อกจริงแล้ว",
"activationCanEnableHint": "ไซต์จะเริ่มทำงานจริงโดยอัตโนมัติหลังการทดสอบการตั้งค่าปัจจุบันผ่านครั้งถัดไป", "activationCanEnableHint": "คลิกเปิดใช้งานไซต์สต็อกเพื่อเริ่มใช้งานจริง หรือทดสอบส่งออกอีกครั้ง ระบบจะเปิดใช้งานอัตโนมัติเมื่อผ่าน",
"activationMissingHint": "ทำเฉพาะเงื่อนไขการเปิดใช้งานที่ยังไม่ผ่าน การเตรียมภายหลังไม่ขัดขวางการเปิดใช้งาน", "activationMissingHint": "ทำเฉพาะเงื่อนไขการเปิดใช้งานที่ยังไม่ผ่าน การเตรียมภายหลังไม่ขัดขวางการเปิดใช้งาน",
"activationRequirement": { "activationRequirement": {
"rpa_profile": "การเชื่อมต่อระบบพร้อมใช้งาน", "rpa_profile": "การเชื่อมต่อระบบพร้อมใช้งาน",
+2 -2
View File
@@ -1049,9 +1049,9 @@
"saveBeforeReadinessAction": "请先保存当前库存站点更改,再执行此操作。", "saveBeforeReadinessAction": "请先保存当前库存站点更改,再执行此操作。",
"activationReady": "库存站点已启用,可进入正式库存运行。", "activationReady": "库存站点已启用,可进入正式库存运行。",
"activationDraft": "库存站点当前停用;完成以下项目后才可启用。", "activationDraft": "库存站点当前停用;完成以下项目后才可启用。",
"activationCanEnable": "启用条件已满足,系统正在自动启用站点。", "activationCanEnable": "启用条件已满足,可启用该库存站点。",
"activationEnabledHint": "站点已参与正式库存运行。", "activationEnabledHint": "站点已参与正式库存运行。",
"activationCanEnableHint": "下一次当前配置测试通过后,站点会自动投入正式运行。", "activationCanEnableHint": "点击“启用库存站点”即可投入正式运行;也可再次测试导出,通过后仍会自动启用。",
"activationMissingHint": "仅需完成“启用条件”中的未通过项目;后续准备不影响启用。", "activationMissingHint": "仅需完成“启用条件”中的未通过项目;后续准备不影响启用。",
"activationRequirement": { "activationRequirement": {
"rpa_profile": "系统连接可用", "rpa_profile": "系统连接可用",
+2 -2
View File
@@ -920,9 +920,9 @@
"saveBeforeReadinessAction": "請先儲存目前庫存站點的變更,再執行此操作。", "saveBeforeReadinessAction": "請先儲存目前庫存站點的變更,再執行此操作。",
"activationReady": "庫存站點已啟用,可進入正式庫存執行。", "activationReady": "庫存站點已啟用,可進入正式庫存執行。",
"activationDraft": "庫存站點目前停用;完成以下項目後才可啟用。", "activationDraft": "庫存站點目前停用;完成以下項目後才可啟用。",
"activationCanEnable": "已符合啟用條件,系統正在自動啟用站點。", "activationCanEnable": "已符合啟用條件,可啟用此庫存站點。",
"activationEnabledHint": "站點已參與正式庫存執行。", "activationEnabledHint": "站點已參與正式庫存執行。",
"activationCanEnableHint": "下一次目前設定測試通過後,站點會自動投入正式執行。", "activationCanEnableHint": "點選「啟用庫存站點」即可投入正式執行;也可再次測試匯出,通過後仍會自動啟用。",
"activationMissingHint": "只需完成「啟用條件」中未通過的項目;後續準備不影響啟用。", "activationMissingHint": "只需完成「啟用條件」中未通過的項目;後續準備不影響啟用。",
"activationRequirement": { "activationRequirement": {
"rpa_profile": "系統連線可用", "rpa_profile": "系統連線可用",
@@ -3,7 +3,8 @@ scripts/rpa/dsv_report_export.py
用途:DSV 360 填参、View Report、Excel 导出与 batch 编排。 用途:DSV 360 填参、View Report、Excel 导出与 batch 编排。
依赖:rpa_common、dsv_debug、dsv_navigation、dsv_session、dsv_report_parameters。 依赖:rpa_common、dsv_debug、dsv_navigation、dsv_session、dsv_report_parameters。
逻辑:worker connector_type=dsv360 时委托本模块。 逻辑:worker connector_type=dsv360 时委托本模块;DOM 明细行探测仅作加速,
无行时重试 View Report 一次后仍导出,真空由落盘 Excel 判定。
""" """
from __future__ import annotations from __future__ import annotations
@@ -860,8 +861,8 @@ def _wait_dsv_report_inventory_rows(page: Any, *, timeout_ms: int) -> bool:
条件轮询等待 SSRS 结果页出现真实库存明细行。 条件轮询等待 SSRS 结果页出现真实库存明细行。
核心逻辑:result_ready(分页/导出按钮状态)先就绪,但当前页明细行是异步渲染进 DOM 的, 核心逻辑:result_ready(分页/导出按钮状态)先就绪,但当前页明细行是异步渲染进 DOM 的,
单次快照可能撞上"分页已出、行未渲染"的窗口,把有数据的报表误判为无数据; 单次快照可能撞上"分页已出、行未渲染"的窗口;这里以 1s 间隔轮询。
这里以 1s 间隔轮询,直到明细行出现或超时,再交给调用方决定 success/skip。 返回 False 时调用方不得直接 skip——应重试 View Report / 导出 Excel 用文件判空。
""" """
deadline = time.monotonic() + max(1.0, timeout_ms / 1000) deadline = time.monotonic() + max(1.0, timeout_ms / 1000)
while time.monotonic() < deadline: while time.monotonic() < deadline:
@@ -871,6 +872,34 @@ def _wait_dsv_report_inventory_rows(page: Any, *, timeout_ms: int) -> bool:
return False return False
def _ensure_dsv_inventory_rows_or_export_fallback(page: Any, *, report_name: str) -> None:
"""
DOM 有行则继续;无行则重试一次 View Report,仍无行也不抛空——交给 Excel 判空。
核心逻辑:DOM 探测是加速优化,不是库存真相源。Salt Lake 等慢报表会出现
result_ready 后 45s 内行仍未渲染、但 Excel 导出有数据的假空(AWSSL 2026-09-09)。
"""
row_wait_ms = min(_browser_timeout_ms(), 45_000)
if _wait_dsv_report_inventory_rows(page, timeout_ms=row_wait_ms):
return
print(
f"[dsv-report] inventory rows not visible after ready reportName={report_name!r}; "
"retry View Report once",
file=sys.stderr,
)
_click_dsv_view_report(page)
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
if _wait_dsv_report_inventory_rows(page, timeout_ms=row_wait_ms):
return
print(
f"[dsv-report] inventory rows still missing after View Report retry "
f"reportName={report_name!r}; proceed to Excel export fallback",
file=sys.stderr,
)
def _fill_dsv_filter_if_needed( def _fill_dsv_filter_if_needed(
page: Any, page: Any,
selector_env: str, selector_env: str,
@@ -1323,10 +1352,9 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
# [STEP 1] DSV 页面会维持长连接;等待 networkidle 不能说明 SSRS 已可导出, # [STEP 1] DSV 页面会维持长连接;等待 networkidle 不能说明 SSRS 已可导出,
# 反而可能额外消耗十秒。直接等待现有的报表业务就绪条件。 # 反而可能额外消耗十秒。直接等待现有的报表业务就绪条件。
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms()) _wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
# [STEP 2] result_ready 只代表分页/导出状态就绪,明细行异步渲染可能晚几秒; # [STEP 2] DOM 明细行仅作加速;无行时重试 View Report,仍无则继续导出,
# 用条件轮询等待真实数据行,避免把"有数据但行未渲染"误判成 skip。 # 真空由落盘 Excel 判定(避免慢渲染假空 skip)。
if not _wait_dsv_report_inventory_rows(page, timeout_ms=min(_browser_timeout_ms(), 45_000)): _ensure_dsv_inventory_rows_or_export_fallback(page, report_name=report_name)
raise NoInventoryDataError("DSV report has no inventory data")
except Exception as exc: except Exception as exc:
_report_dsv_chain_stage( _report_dsv_chain_stage(
"report_result_ready", "error", started_at=result_started_at, "report_result_ready", "error", started_at=result_started_at,
@@ -1488,6 +1516,8 @@ find_dsv_report_result_frame = _find_dsv_report_result_frame
wait_for_dsv_report_result_ready = _wait_for_dsv_report_result_ready wait_for_dsv_report_result_ready = _wait_for_dsv_report_result_ready
wait_dsv_report_ready = _wait_dsv_report_ready wait_dsv_report_ready = _wait_dsv_report_ready
dsv_report_has_inventory_data_rows = _dsv_report_has_inventory_data_rows dsv_report_has_inventory_data_rows = _dsv_report_has_inventory_data_rows
wait_dsv_report_inventory_rows = _wait_dsv_report_inventory_rows
ensure_dsv_inventory_rows_or_export_fallback = _ensure_dsv_inventory_rows_or_export_fallback
fill_dsv_filter_if_needed = _fill_dsv_filter_if_needed fill_dsv_filter_if_needed = _fill_dsv_filter_if_needed
fill_dsv_multi_select = _fill_dsv_multi_select fill_dsv_multi_select = _fill_dsv_multi_select
fill_report_parameter = _fill_report_parameter fill_report_parameter = _fill_report_parameter
@@ -697,6 +697,60 @@ def _validate_inventory_excel(path: Path) -> None:
) )
def _dsv_inventory_excel_has_detail_rows(path: Path) -> bool | None:
"""
判断 DSV 风格库存 Excel 表头之后是否有明细行。
核心逻辑:仅当识别到 Supplier ID + AWS Sku 表头时判空;其他格式返回 None(不拦截)。
DOM 假空兜底后,Excel 才是 skip/no_inventory_data 的真相源。
Returns:
True: 有明细;False: DSV 表头存在但无明细;None: 非 DSV 表头形态,跳过本门禁。
"""
try:
from openpyxl import load_workbook
except ImportError:
return None
try:
workbook = load_workbook(path, read_only=True, data_only=True)
except Exception:
return None
try:
worksheet = workbook.active
if worksheet is None:
return None
header_idx: int | None = None
for idx, row in enumerate(worksheet.iter_rows(max_row=120, values_only=True), start=1):
cells = [str(cell).strip() for cell in row if cell is not None and str(cell).strip()]
if not cells:
continue
joined = " | ".join(cells).lower()
if header_idx is None:
if "supplier id" in joined and "aws sku" in joined:
header_idx = idx
continue
if idx > header_idx:
return True
if header_idx is None:
return None
return False
finally:
workbook.close()
def _enforce_inventory_excel_not_empty(path: Path) -> None:
"""
DSV Excel 有表头无明细时记为无库存(NoInventoryDataError → skipped)。
核心逻辑:配合导出路径「DOM 无行仍导出」;真真空才 skip,避免 DOM 慢渲染假空。
"""
detail = _dsv_inventory_excel_has_detail_rows(path)
if detail is False:
raise NoInventoryDataError("DSV report has no inventory data")
def _download_dir_baseline_names(drop_dir: Path) -> set[str]: def _download_dir_baseline_names(drop_dir: Path) -> set[str]:
""" """
导出前拍摄下载目录已有文件名,供目录兜底识别“本次新文件”。 导出前拍摄下载目录已有文件名,供目录兜底识别“本次新文件”。
@@ -775,6 +829,7 @@ def _save_download(
) )
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}: if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
_validate_inventory_excel(dest) _validate_inventory_excel(dest)
_enforce_inventory_excel_not_empty(dest)
return dest return dest
@@ -817,6 +872,7 @@ def _save_batch_download(
) )
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}: if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
_validate_inventory_excel(dest) _validate_inventory_excel(dest)
_enforce_inventory_excel_not_empty(dest)
return dest return dest