feat(shipping-notice): 完善库存源聚合与订单模板匹配
- 优化订单模板匹配、重放及库存配置测试 - 新增库存 RPA 源合并设计与相关测试 - 更新库存管理页面及四语言文案 - 同步需求、技术文档与测试配置
This commit is contained in:
1 parent
2bb7822247
commit
6052c46d88
14 files changed
+1056
-86
No files matched your search
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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
|
||||
+1
-1
@@ -200,7 +200,7 @@
|
||||
- **RPA 旁路**:RPA Profile 只用于定时库存导出、用户手动刷新和配置测试;排程以 `source_codes` 为目标,按 Profile 分组复用登录,但每个文件必须独立记录 Source。
|
||||
- **配置归属**:连接配置只保存登录地址、加密凭据和连接级登录配置;库存源只持久化 `report_path_json` 与 `query_parameters_json`。DBS 路径为业务组/业务项目/报表分组/报表名;参数支持单选、文本多值、列表多选。订单到库存站点的选择只由版本化路由规则决定。
|
||||
- **解析方案直接绑定(一期)**:停用库存站点在编辑表单直接选择已发布的库存文件解析方案,随“保存更改”一次提交;批量绑定仍执行全量预检并写追加式前后快照审计。管理员无需填写绑定原因;已启用站点、草稿/退役方案及发货模板库存字段不兼容时必须拒绝。绑定递增站点配置版本,使旧测试证据失效。
|
||||
- **自动启用(二期)**:当前绑定的已发布解析方案通过本次配置测试(或已绑定解析的查询成功但无库存)后,后端复用同一正式门禁自动启用站点;必要条件缺失时绝不启用。前端不提供“确认绑定”或“启用站点”二次操作,只显示当前唯一阻塞项及其操作。Dify 无需配置变更。
|
||||
- **自动启用(二期)**:当前绑定的已发布解析方案通过本次配置测试(或已绑定解析的查询成功但无库存)后,后端复用同一正式门禁自动启用站点;必要条件缺失时绝不启用。首次启用不提供“确认绑定”二次操作,只显示当前唯一阻塞项及其操作。站点停用后若正式门禁仍满足,管理端提供“启用库存站点”按钮(调用既有 activate API);也可再次测试导出以触发自动启用。Dify 无需配置变更。
|
||||
- **空库存语义(二期)**:RPA 查询成功但无库存是有效业务结果,不得显示为连接或导出失败。站点验证区分“连接/查询已验证”与“数据行待首次非空文件验证”;已绑定 published 方案及发货模板的站点可继续启用。行级解析验证与外部仓库映射均不阻断启用:前者在首次非空文件到达时验证,后者只在实际调拨前要求维护。调度空结果写入不可匹配的 `empty` 快照审计,绝不链接任务、参与库存匹配或生成发货 Excel。
|
||||
- **字段隔离**:订单行仅使用 `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。
|
||||
|
||||
@@ -3173,6 +3173,7 @@ API 层
|
||||
- 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`。
|
||||
- 自动启用不放宽任何门禁:缺少发货模板、模板字段不兼容、配置/连接版本已变更时均保持停用;外部仓库映射和首次非空文件的数据行验证仍属于后续流程,不阻断站点启用。Dify 无需修改配置。
|
||||
- **停用后再启用**:停用后若 `activation.ready` 仍为真,管理端显示“启用库存站点”并调用既有 `POST /sources/{id}/activate`(与自动启用同一门禁);表单有未保存修改时禁用该按钮。也可再次测试导出以触发 `activate_source_if_ready`。
|
||||
|
||||
### 6.3 快照复用规则
|
||||
|
||||
|
||||
@@ -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>
|
||||
</section>
|
||||
</template>
|
||||
<footer v-if="source.enabled" class="readiness-footer">
|
||||
<button type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
|
||||
<footer v-if="source.enabled || source.activation?.ready" class="readiness-footer">
|
||||
<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>
|
||||
</section>
|
||||
<div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div>
|
||||
@@ -460,6 +468,7 @@ import {
|
||||
deleteShippingInventoryParsingProfile,
|
||||
deleteShippingInventoryRule,
|
||||
deleteShippingInventorySource,
|
||||
activateShippingInventorySource,
|
||||
deactivateShippingInventorySource,
|
||||
deleteShippingRpaProfile,
|
||||
getShippingInventoryConfig,
|
||||
@@ -527,7 +536,7 @@ const orderSchemaPublished = ref(false);
|
||||
const saving = ref(false);
|
||||
const confirmation = reactive({
|
||||
visible: false,
|
||||
action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'deactivateSource' | 'replaceInventorySample' | '',
|
||||
action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'activateSource' | 'deactivateSource' | 'replaceInventorySample' | '',
|
||||
title: '',
|
||||
message: '',
|
||||
confirmText: '',
|
||||
@@ -1248,7 +1257,7 @@ function openConfirmation(action: Exclude<typeof confirmation.action, ''>, messa
|
||||
confirmation.visible = true;
|
||||
}
|
||||
|
||||
/** 执行用户在统一确认弹窗中确认的删除或归档动作。 */
|
||||
/** 执行用户在统一确认弹窗中确认的删除、启停或归档动作。 */
|
||||
async function confirmPendingAction(): Promise<void> {
|
||||
if (!selectedId.value || !confirmation.action) return;
|
||||
const action = confirmation.action;
|
||||
@@ -1258,6 +1267,11 @@ async function confirmPendingAction(): Promise<void> {
|
||||
if (action === 'retireTemplate') await retireShippingExcelTemplate(selectedId.value);
|
||||
if (action === 'retireParsing') await retireShippingInventoryParsingProfile(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 === 'replaceInventorySample') { sampleReplacementConfirmed.value = true; await saveCurrent(); return; }
|
||||
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 = ''; }
|
||||
|
||||
/**
|
||||
* 停用后条件仍满足时,经确认弹窗调用已有 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 {
|
||||
confirmation.visible = true;
|
||||
|
||||
@@ -920,9 +920,9 @@
|
||||
"saveBeforeReadinessAction": "Save the current inventory-site changes before taking this action.",
|
||||
"activationReady": "The inventory site is enabled and can run in production.",
|
||||
"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.",
|
||||
"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.",
|
||||
"activationRequirement": {
|
||||
"rpa_profile": "System connection is available",
|
||||
|
||||
@@ -920,9 +920,9 @@
|
||||
"saveBeforeReadinessAction": "โปรดบันทึกการเปลี่ยนแปลงไซต์สต็อกปัจจุบันก่อนดำเนินการนี้",
|
||||
"activationReady": "เปิดใช้งานไซต์สต็อกแล้วและพร้อมใช้งานจริง",
|
||||
"activationDraft": "ไซต์สต็อกยังปิดใช้งาน โปรดทำรายการต่อไปนี้ให้เสร็จก่อนเปิดใช้งาน",
|
||||
"activationCanEnable": "ผ่านทุกเงื่อนไขแล้ว ระบบกำลังเปิดใช้งานไซต์สต็อกโดยอัตโนมัติ",
|
||||
"activationCanEnable": "ผ่านทุกเงื่อนไขแล้ว สามารถเปิดใช้งานไซต์สต็อกนี้ได้",
|
||||
"activationEnabledHint": "ไซต์นี้เข้าร่วมการทำงานสต็อกจริงแล้ว",
|
||||
"activationCanEnableHint": "ไซต์จะเริ่มทำงานจริงโดยอัตโนมัติหลังการทดสอบการตั้งค่าปัจจุบันผ่านครั้งถัดไป",
|
||||
"activationCanEnableHint": "คลิกเปิดใช้งานไซต์สต็อกเพื่อเริ่มใช้งานจริง หรือทดสอบส่งออกอีกครั้ง ระบบจะเปิดใช้งานอัตโนมัติเมื่อผ่าน",
|
||||
"activationMissingHint": "ทำเฉพาะเงื่อนไขการเปิดใช้งานที่ยังไม่ผ่าน การเตรียมภายหลังไม่ขัดขวางการเปิดใช้งาน",
|
||||
"activationRequirement": {
|
||||
"rpa_profile": "การเชื่อมต่อระบบพร้อมใช้งาน",
|
||||
|
||||
@@ -1049,9 +1049,9 @@
|
||||
"saveBeforeReadinessAction": "请先保存当前库存站点更改,再执行此操作。",
|
||||
"activationReady": "库存站点已启用,可进入正式库存运行。",
|
||||
"activationDraft": "库存站点当前停用;完成以下项目后才可启用。",
|
||||
"activationCanEnable": "启用条件已满足,系统正在自动启用站点。",
|
||||
"activationCanEnable": "启用条件已满足,可启用该库存站点。",
|
||||
"activationEnabledHint": "站点已参与正式库存运行。",
|
||||
"activationCanEnableHint": "下一次当前配置测试通过后,站点会自动投入正式运行。",
|
||||
"activationCanEnableHint": "点击“启用库存站点”即可投入正式运行;也可再次测试导出,通过后仍会自动启用。",
|
||||
"activationMissingHint": "仅需完成“启用条件”中的未通过项目;后续准备不影响启用。",
|
||||
"activationRequirement": {
|
||||
"rpa_profile": "系统连接可用",
|
||||
|
||||
@@ -920,9 +920,9 @@
|
||||
"saveBeforeReadinessAction": "請先儲存目前庫存站點的變更,再執行此操作。",
|
||||
"activationReady": "庫存站點已啟用,可進入正式庫存執行。",
|
||||
"activationDraft": "庫存站點目前停用;完成以下項目後才可啟用。",
|
||||
"activationCanEnable": "已符合啟用條件,系統正在自動啟用站點。",
|
||||
"activationCanEnable": "已符合啟用條件,可啟用此庫存站點。",
|
||||
"activationEnabledHint": "站點已參與正式庫存執行。",
|
||||
"activationCanEnableHint": "下一次目前設定測試通過後,站點會自動投入正式執行。",
|
||||
"activationCanEnableHint": "點選「啟用庫存站點」即可投入正式執行;也可再次測試匯出,通過後仍會自動啟用。",
|
||||
"activationMissingHint": "只需完成「啟用條件」中未通過的項目;後續準備不影響啟用。",
|
||||
"activationRequirement": {
|
||||
"rpa_profile": "系統連線可用",
|
||||
|
||||
Reference in new issue
Block a user