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

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

No files matched your search

@@ -1,10 +1,11 @@
""" """
backend/app/services/schedule/shipping_inventory_rpa_archive.py backend/app/services/schedule/shipping_inventory_rpa_archive.py
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)。 用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。 依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary; 逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
query_service 只读 summary;api/schedule/runs 按 raw_inventory_zip_path send_file。 企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」;
完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。
""" """
from __future__ import annotations from __future__ import annotations
@@ -12,6 +13,7 @@ from __future__ import annotations
import json import json
import re import re
import zipfile import zipfile
from datetime import datetime
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
@@ -48,9 +50,51 @@ def get_inventory_archive_dir() -> str:
return str(archive_dir) return str(archive_dir)
def inventory_raw_zip_download_name(run_no: str) -> str: def _attachment_when_from_run(run: ScheduleRun) -> datetime:
"""浏览器下载时使用的 ZIP 文件名。""" """
return f"inventory-rpa-raw-{run_no}.zip" 推导企微/下载展示名中的时刻。
核心逻辑:优先 started_at → created_at → finished_at;再尝试解析 RUN{yyyyMMddHHmmss}*;
最后回退 utcnow。完整 run_no 仍留在卡片与磁盘归档键,不塞进展示名。
"""
for value in (run.started_at, run.created_at, run.finished_at):
if isinstance(value, datetime):
return value
match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip())
if match:
try:
return datetime.strptime(match.group(1), "%Y%m%d%H%M%S")
except ValueError:
pass
return datetime.utcnow()
def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}。
Args:
run: 排程执行记录。
Returns:
不含角色后缀与扩展名的展示名前缀。
"""
when = _attachment_when_from_run(run)
return f"库存RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
def inventory_rpa_result_excel_name(run: ScheduleRun) -> str:
"""库存 RPA 结果 Excel 的企微/下载展示名。"""
return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx"
def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
"""
库存 ZIP 的企微/浏览器下载展示名。
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f"{inventory_rpa_attachment_stem(run)}-库存.zip"
def _inventory_raw_zip_archive_path(run_no: str) -> Path: def _inventory_raw_zip_archive_path(run_no: str) -> Path:
@@ -157,7 +201,6 @@ def persist_inventory_rpa_raw_zip_archive(
index=zip_index, index=zip_index,
source_code=source_code, source_code=source_code,
warehouse_id=warehouse_id, warehouse_id=warehouse_id,
inventory_file_no=inventory_file_no,
original_suffix=storage_path.suffix or ".xlsx", original_suffix=storage_path.suffix or ".xlsx",
) )
archive.write(storage_path, arcname=entry_name) archive.write(storage_path, arcname=entry_name)
@@ -236,7 +279,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
if not _is_allowed_inventory_archive_path(zip_path): if not _is_allowed_inventory_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), inventory_raw_zip_download_name(run.run_no) return zip_path.resolve(), inventory_raw_zip_download_name(run)
def _sanitize_zip_segment(value: str) -> str: def _sanitize_zip_segment(value: str) -> str:
@@ -245,25 +288,33 @@ def _sanitize_zip_segment(value: str) -> str:
return cleaned or "unknown" return cleaned or "unknown"
def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str:
"""
包内短标签:优先 source_code(库存站点业务键,Crane 等无固定仓码也能辨认)。
warehouse_id / inventory_file_no 已写入 manifest.json;条目名不必再叠仓码。
"""
source = str(source_code or "").strip()
if source:
return source
warehouse = str(warehouse_id or "").strip()
if warehouse and warehouse.lower() != "unknown":
return warehouse
return "inventory"
def _build_zip_entry_name( def _build_zip_entry_name(
*, *,
index: int, index: int,
source_code: str, source_code: str,
warehouse_id: str, warehouse_id: str,
inventory_file_no: str,
original_suffix: str, original_suffix: str,
) -> str: ) -> str:
"""生成 ZIP 内单文件条目名(不含目录)。""" """
base = "_".join( 生成 ZIP 内单文件条目名(不含目录)。
filter(
None, 核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。
[ """
f"{index:03d}", label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id))
_sanitize_zip_segment(source_code),
_sanitize_zip_segment(warehouse_id),
_sanitize_zip_segment(inventory_file_no),
],
)
)
suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}" suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}"
return f"{base}{suffix}" return f"{index:03d}_{label}{suffix}"
@@ -493,6 +493,11 @@ def _finalize_shipping_inventory_schedule_run_impl(
errors.append(f"Excel导出失败: {excel_exc}") errors.append(f"Excel导出失败: {excel_exc}")
if status == "success": if status == "success":
status = "partial_failed" status = "partial_failed"
else:
# 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name
file_name = inventory_rpa_result_excel_name(run)
step_logs = list(run.step_logs or []) step_logs = list(run.step_logs or [])
step_logs.append({ step_logs.append({
@@ -3,13 +3,61 @@ services/shipping_notice/document_layout/coordinate_region_text.py
用途:统一从页面坐标字符中读取受控区域文字,并恢复可靠的原始文本流空白。 用途:统一从页面坐标字符中读取受控区域文字,并恢复可靠的原始文本流空白。
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约、PositionedCharacter 可选边界字段。 依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约、PositionedCharacter 可选边界字段。
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则。 逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则;
另提供单逻辑表头折行合并(x 回退副标签并入最近列,不拆成新身份列)。
""" """
from __future__ import annotations from __future__ import annotations
from typing import Any, Literal from typing import Any, Literal
# 单逻辑表头:列中心相对页宽回退超过该阈值,视为同列折行副标签。
_HEADER_CENTER_X_REGRESSION_TOLERANCE = 0.02
def merge_header_identity_wrap_tokens(
tokens: list[str],
centers: list[float] | None,
widths: list[float] | None = None,
) -> tuple[list[str], list[float] | None, list[float] | None]:
"""
将单逻辑表头中的折行副标签并入所属列,保留文案、不新增身份列。
核心逻辑:主行列中心近似单调递增;若下一 token 的中心明显回退,则并入与其
x 最近的已有列(如 Part Number 下 Vendor Item#、Requested Arrival 下 Date)。
多行正式表头不要调用本函数。
Args:
tokens: 按阅读序的 header_tokens(可含第二视觉行)。
centers: 与 tokens 对齐的列中心(0..1);缺失或长度不一致时原样返回。
widths: 可选列宽比;对齐时随列保留(被并入列沿用主行宽度)。
Returns:
合并后的 (tokens, centers, widths)。
"""
if not tokens or not centers or len(centers) != len(tokens):
return tokens, centers, widths
has_widths = isinstance(widths, list) and len(widths) == len(tokens)
merged_tokens: list[str] = []
merged_centers: list[float] = []
merged_widths: list[float] | None = [] if has_widths else None
max_center = float('-inf')
for index, token in enumerate(tokens):
center = float(centers[index])
if merged_centers and center < max_center - _HEADER_CENTER_X_REGRESSION_TOLERANCE:
parent = min(
range(len(merged_centers)),
key=lambda item: abs(merged_centers[item] - center),
)
merged_tokens[parent] = f'{merged_tokens[parent]} {token}'.strip()
continue
merged_tokens.append(str(token))
merged_centers.append(center)
if merged_widths is not None:
merged_widths.append(float(widths[index]))
max_center = max(max_center, center)
return merged_tokens, merged_centers, merged_widths
def render_positioned_row( def render_positioned_row(
glyphs: list[Any], *, geometry_gap_limit: float | None = None, glyphs: list[Any], *, geometry_gap_limit: float | None = None,
@@ -6,6 +6,7 @@ backend/app/services/shipping_notice/document_layout/order_profile.py
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费 逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成 DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。 matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。
表区 region_role 区分主明细与同文档 LN 补料号补充表(line_field_supplement)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -259,6 +260,8 @@ class TableRegionProfile(OrderProfileModel):
page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages' page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages'
page_no: int | None = Field(default=None, ge=1) page_no: int | None = Field(default=None, ge=1)
region: RelativeRegion region: RelativeRegion
# business_lines=主明细命中源;line_field_supplement=同文档按 LN 补料号(如 COO),不进业务表匹配。
region_role: Literal['business_lines', 'line_field_supplement'] = 'business_lines'
# 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。 # 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。
line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$') line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。 # 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
@@ -304,6 +307,22 @@ class TableRegionProfile(OrderProfileModel):
field.field_code for field in self.line_layouts[0].field_regions field.field_code for field in self.line_layouts[0].field_regions
}: }:
raise ValueError('main line layout must bind the configured line-start field') raise ValueError('main line layout must bind the configured line-start field')
if self.region_role == 'line_field_supplement':
# 补充表只允许起行 + 客户料号/Vendor,禁止绑数量金额等以免误当业务明细。
bound = {
field.field_code
for item in self.line_layouts
for field in item.field_regions
}
if not self.line_start_field_code or self.line_start_field_code not in bound:
raise ValueError('line_field_supplement requires the configured line-start field')
allowed = {self.line_start_field_code, 'customer_part_number', 'part_number'}
extra = sorted(bound - allowed)
if extra:
raise ValueError(
'line_field_supplement may only bind line-start and part number fields; '
f'unexpected: {", ".join(extra)}'
)
# A physical text band must have exactly one layout interpretation. Allowing # A physical text band must have exactly one layout interpretation. Allowing
# overlapping header/line regions would reintroduce the cross-row ambiguity # overlapping header/line regions would reintroduce the cross-row ambiguity
# that v2 coordinate profiles are intended to eliminate. # that v2 coordinate profiles are intended to eliminate.
@@ -505,6 +524,11 @@ class OrderCoordinateProfile(OrderProfileModel):
ids = [item.region_id for item in self.table_regions] ids = [item.region_id for item in self.table_regions]
if len(ids) != len(set(ids)): if len(ids) != len(set(ids)):
raise ValueError('table region ids must be unique') raise ValueError('table region ids must be unique')
if not any(
str(getattr(item, 'region_role', None) or 'business_lines') == 'business_lines'
for item in self.table_regions
):
raise ValueError('at least one business_lines table region is required')
for index, left in enumerate(self.table_regions): for index, left in enumerate(self.table_regions):
for right in self.table_regions[index + 1:]: for right in self.table_regions[index + 1:]:
# Different exact pages may use identical coordinates without competing at runtime. # Different exact pages may use identical coordinates without competing at runtime.
@@ -6,7 +6,8 @@ services/shipping_notice/document_layout/order_profile_matcher.py
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜; 逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column; table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表; 主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁。 无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
""" """
from __future__ import annotations from __future__ import annotations
@@ -19,6 +20,7 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.coordinate_region_text import ( from app.services.shipping_notice.document_layout.coordinate_region_text import (
merge_header_identity_wrap_tokens,
positioned_token_spans, positioned_token_spans,
read_coordinate_region_text, read_coordinate_region_text,
visual_glyph_rows, visual_glyph_rows,
@@ -960,13 +962,11 @@ def _score_header_semantic_position(
"""比对真实表头 token、横向顺序和位置。 """比对真实表头 token、横向顺序和位置。
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。 核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
期望侧先截断单逻辑表头的折行副标签污染。
""" """
if signature is None: if signature is None:
return MatchDimensionResult(state='unavailable', score=0.0) return MatchDimensionResult(state='unavailable', score=0.0)
expected_tokens: list[str] = [] expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
for table in signature.get('table_patterns') or []:
if isinstance(table, dict):
expected_tokens.extend(str(item).casefold() for item in table.get('header_tokens') or [])
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []] observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0 required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0
if not expected_tokens: if not expected_tokens:
@@ -986,7 +986,7 @@ def _score_header_semantic_position(
return MatchDimensionResult(state='mismatched', score=0.0) return MatchDimensionResult(state='mismatched', score=0.0)
matched = sum(1 for token in expected_tokens if token in observed_tokens) matched = sum(1 for token in expected_tokens if token in observed_tokens)
token_ratio = matched / len(expected_tokens) token_ratio = matched / len(expected_tokens)
expected_order = [str(item).casefold() for table in signature.get('table_patterns') or [] if isinstance(table, dict) for item in table.get('header_order') or []] expected_order = [str(item).casefold() for item in _signature_identity_header_order(signature)]
observed_order = observed.get('header_tokens') or [] observed_order = observed.get('header_tokens') or []
shared = [item for item in expected_order if item in observed_order] shared = [item for item in expected_order if item in observed_order]
order_ratio = 1.0 order_ratio = 1.0
@@ -1008,6 +1008,63 @@ _HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with
_HEADER_ATOM_MIN_LEN = 3 _HEADER_ATOM_MIN_LEN = 3
def _sanitize_signature_table_identity(
pattern: dict[str, Any],
) -> tuple[list[str], list[float] | None, list[float] | None]:
"""
按需合并单逻辑表头签名中的折行副标签。
核心逻辑:header_row_count==1 时按 column_centers 回退把副标签并入最近列;
多行正式表头原样返回。兼容尚未重冻、仍把 Vendor Item#/Date 列为独立 token 的旧签名。
"""
raw_tokens = [str(item) for item in pattern.get('header_tokens') or []]
centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else None
widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else None
try:
center_values = [float(item) for item in centers] if centers is not None else None
except (TypeError, ValueError):
center_values = None
try:
width_values = [float(item) for item in widths] if widths is not None else None
except (TypeError, ValueError):
width_values = None
if int(pattern.get('header_row_count') or 1) > 1:
return raw_tokens, center_values, width_values
return merge_header_identity_wrap_tokens(raw_tokens, center_values, width_values)
def _signature_identity_header_tokens(signature: dict[str, Any] | None) -> list[str]:
"""读取截断折行副标签后的签名表头身份 token。"""
tokens: list[str] = []
for pattern in (signature or {}).get('table_patterns') or []:
if isinstance(pattern, dict):
trimmed, _, _ = _sanitize_signature_table_identity(pattern)
tokens.extend(trimmed)
return tokens
def _signature_identity_header_order(signature: dict[str, Any] | None) -> list[str]:
"""读取合并折行后的 header_order;与身份 token 对齐。"""
ordered: list[str] = []
for pattern in (signature or {}).get('table_patterns') or []:
if not isinstance(pattern, dict):
continue
tokens, _, _ = _sanitize_signature_table_identity(pattern)
ordered.extend(tokens)
return ordered
def _signature_single_logical_header(signature: dict[str, Any] | None) -> bool:
"""签名是否全部为逻辑一行表头(可含格内折行)。"""
patterns = [
item for item in (signature or {}).get('table_patterns') or []
if isinstance(item, dict)
]
if not patterns:
return True
return all(int(item.get('header_row_count') or 1) <= 1 for item in patterns)
def _header_token_atoms(tokens: list[str]) -> frozenset[str]: def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
""" """
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。 将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
@@ -1031,10 +1088,7 @@ def _header_discriminator_atoms_conflict(
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。""" """签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
if signature is None or not signature.get('table_patterns'): if signature is None or not signature.get('table_patterns'):
return False return False
expected_tokens: list[str] = [] expected_tokens = _signature_identity_header_tokens(signature)
for table in signature.get('table_patterns') or []:
if isinstance(table, dict):
expected_tokens.extend(str(item) for item in table.get('header_tokens') or [])
observed_tokens = [str(item) for item in observed.get('header_tokens') or []] observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if not expected_tokens or not observed_tokens: if not expected_tokens or not observed_tokens:
return False return False
@@ -1075,9 +1129,15 @@ def _score_column_topology(
for pattern, expected in zip(patterns, expected_counts): for pattern, expected in zip(patterns, expected_counts):
if expected <= 0: if expected <= 0:
continue continue
count_score = min(observed_count, expected) / max(observed_count, expected) tokens, expected_centers_raw, expected_widths_raw = _sanitize_signature_table_identity(pattern)
expected_centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else [] expected_identity_count = len(tokens) or expected
expected_widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else [] count_score = min(observed_count, expected_identity_count) / max(observed_count, expected_identity_count)
expected_centers = expected_centers_raw if isinstance(expected_centers_raw, list) else []
expected_widths = expected_widths_raw if isinstance(expected_widths_raw, list) else []
if not expected_centers and isinstance(pattern.get('column_centers'), list):
expected_centers = pattern.get('column_centers') or []
if not expected_widths and isinstance(pattern.get('column_width_ratios'), list):
expected_widths = pattern.get('column_width_ratios') or []
if expected_centers and observed_centers: if expected_centers and observed_centers:
center_score = _sequence_similarity(expected_centers, observed_centers, tolerance=0.08) center_score = _sequence_similarity(expected_centers, observed_centers, tolerance=0.08)
width_score = _sequence_similarity(expected_widths, observed_widths, tolerance=0.16) if expected_widths and observed_widths else 0.0 width_score = _sequence_similarity(expected_widths, observed_widths, tolerance=0.16) if expected_widths and observed_widths else 0.0
@@ -1373,18 +1433,8 @@ def _select_persisted_header_candidate(
*, candidates: list[dict[str, Any]], signature: dict[str, Any] | None, *, candidates: list[dict[str, Any]], signature: dict[str, Any] | None,
) -> tuple[dict[str, Any], list[float]] | None: ) -> tuple[dict[str, Any], list[float]] | None:
"""按冻结签名联合选择投影表头,证据不足时返回 None 而非按列数猜测。""" """按冻结签名联合选择投影表头,证据不足时返回 None 而非按列数猜测。"""
expected_tokens = [ expected_tokens = [str(token).casefold() for token in _signature_identity_header_tokens(signature)]
str(token).casefold() expected_order = [str(token).casefold() for token in _signature_identity_header_order(signature)]
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_tokens') or []
]
expected_order = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_order') or []
]
expected_centers = _signature_column_values(signature or {}, 'column_centers') expected_centers = _signature_column_values(signature or {}, 'column_centers')
expected_widths = _signature_column_values(signature or {}, 'column_width_ratios') expected_widths = _signature_column_values(signature or {}, 'column_width_ratios')
if not expected_tokens or not expected_centers: if not expected_tokens or not expected_centers:
@@ -1573,14 +1623,9 @@ def _band_headers_match_signature(
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”, 只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行) 直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
需要回退到表体顶部的结构搜索。 需要回退到表体顶部的结构搜索。期望侧先截断折行副标签污染。
""" """
expected = [ expected = [str(token).casefold() for token in _signature_identity_header_tokens(signature)]
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_tokens') or []
]
if not expected or not band_tokens: if not expected or not band_tokens:
return False return False
observed = [str(token).casefold() for token in band_tokens] observed = [str(token).casefold() for token in band_tokens]
@@ -1598,10 +1643,8 @@ def _observe_primary_table_header(
) -> tuple[list[str], list[float], list[float]]: ) -> tuple[list[str], list[float], list[float]]:
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。 """从实际主表顶部观测表头,与签名生成保持同一证据口径。
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为, 先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用。
不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到 若固定带失准,则基于表体顶部做表头行搜索。单逻辑表头时把折行副标签按 x 并入所属列。
错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑),
从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。
""" """
if not primary_bbox or len(primary_bbox) != 4: if not primary_bbox or len(primary_bbox) != 4:
return [], [], [] return [], [], []
@@ -1634,26 +1677,85 @@ def _observe_primary_table_header(
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans] 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(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] band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
# 固定带有效 → 直接沿用(对正常模板零影响)。 single_logical = _signature_single_logical_header(signature)
if single_logical:
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
band_tokens, band_centers, band_widths,
)
band_tokens = [str(item).casefold() for item in merged_tokens]
band_centers = list(merged_centers or [])
band_widths = list(merged_widths or [])
# 固定带有效 → 直接沿用。
if _band_headers_match_signature(band_tokens=band_tokens, signature=signature): if _band_headers_match_signature(band_tokens=band_tokens, signature=signature):
return band_tokens, band_centers, band_widths return band_tokens, band_centers, band_widths
# 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。 # 固定带失准 → 表体顶部候选行;单逻辑表头时把下一视觉行折行副标签并入。
candidates = [{ header_candidates = _observe_header_candidates(
'bbox': primary_bbox, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
'header_candidates': _observe_header_candidates( )
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox, selected = _select_persisted_header_candidate(
), candidates=[{'bbox': primary_bbox, 'header_candidates': header_candidates}],
}] signature=signature,
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature) )
if selected is not None: if selected is not None:
header, _ = selected header, _ = selected
return ( tokens = [str(token).casefold() for token in header['header_tokens']]
[str(token).casefold() for token in header['header_tokens']], centers = list(header['column_centers'])
header['column_centers'], header['column_width_ratios'], 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
def _merge_following_wrap_candidate(
*,
header: dict[str, Any],
header_candidates: list[dict[str, Any]],
) -> tuple[list[str], list[float], list[float]]:
"""
将选中主表头行与紧邻下一视觉行合并(折行副标签)。
核心逻辑:下一行 token 的列中心若相对主行回退,merge_header_identity_wrap_tokens
会把它们并入所属列;若不构成回退则合并结果与主行等价或略增列,仍可安全返回。
"""
tokens = [str(token).casefold() for token in header.get('header_tokens') or []]
centers = [float(item) for item in header.get('column_centers') or []]
widths = [float(item) for item in header.get('column_width_ratios') or []]
header_y1 = float((header.get('bbox') or [0, 0, 0, 0])[3])
following = None
for candidate in header_candidates:
if candidate is header:
continue
bbox = candidate.get('bbox') if isinstance(candidate.get('bbox'), list) else None
if not bbox or len(bbox) != 4:
continue
y0 = float(bbox[1])
if y0 + 1e-6 < header_y1:
continue
if following is None or y0 < float(following['bbox'][1]):
following = candidate
if following is None:
return tokens, centers, widths
wrap_tokens = [str(token).casefold() for token in following.get('header_tokens') or []]
wrap_centers = [float(item) for item in following.get('column_centers') or []]
wrap_widths = [float(item) for item in following.get('column_width_ratios') or []]
if not wrap_tokens or len(wrap_tokens) != len(wrap_centers):
return tokens, centers, widths
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
tokens + wrap_tokens,
centers + wrap_centers,
widths + wrap_widths if len(widths) == len(tokens) else None,
)
return (
[str(item).casefold() for item in merged_tokens],
list(merged_centers or []),
list(merged_widths or []),
)
def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None: def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None:
"""读取候选签名冻结的表头标注区域;每个候选独立取证,禁止共享整页猜测结果。""" """读取候选签名冻结的表头标注区域;每个候选独立取证,禁止共享整页猜测结果。"""
for pattern in (signature or {}).get('table_patterns') or []: for pattern in (signature or {}).get('table_patterns') or []:
@@ -1690,9 +1792,15 @@ def _usable_observed_header_token(token: str) -> bool:
def _signature_column_values(signature: dict[str, Any], key: str) -> list[float]: def _signature_column_values(signature: dict[str, Any], key: str) -> list[float]:
"""读取签名中首个可用表格的列结构向量。""" """读取签名中首个可用表格的列结构向量,单逻辑表头时合并折行副标签后再取。"""
for pattern in signature.get('table_patterns') or []: for pattern in signature.get('table_patterns') or []:
if isinstance(pattern, dict) and isinstance(pattern.get(key), list): if not isinstance(pattern, dict):
continue
_, centers, widths = _sanitize_signature_table_identity(pattern)
selected = centers if key == 'column_centers' else widths if key == 'column_width_ratios' else None
if isinstance(selected, list) and selected:
return list(selected)
if isinstance(pattern.get(key), list):
try: try:
return [float(item) for item in pattern[key]] return [float(item) for item in pattern[key]]
except (TypeError, ValueError): except (TypeError, ValueError):
@@ -5,6 +5,7 @@ services/shipping_notice/document_layout/order_profile_parse_validation.py
依赖:OrderCoordinateProfile、coordinate_region_text、order_profile 契约。 依赖:OrderCoordinateProfile、coordinate_region_text、order_profile 契约。
逻辑:由 order_extraction_workflow 在 matcher 硬门禁后调用;确定性/idempotent; 逻辑:由 order_extraction_workflow 在 matcher 硬门禁后调用;确定性/idempotent;
返回 passed/reason_codes/metrics 供 unique_match 二次裁决。 返回 passed/reason_codes/metrics 供 unique_match 二次裁决。
类型 sanity 接受 MM/DD/YY;字段覆盖仅统计 business_lines。
""" """
from __future__ import annotations from __future__ import annotations
@@ -26,8 +27,9 @@ from app.services.shipping_notice.document_layout.coordinate_table_reconstructio
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$') _NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
# Hyve 等 PO 常见 MM/DD/YY;亦接受 YYYY-MM-DD / MM/DD/YYYY。
_DATE_PATTERN = re.compile( _DATE_PATTERN = re.compile(
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{4})$', r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4})$',
) )
@@ -94,8 +96,13 @@ def validate_profile_parse_candidate(
) )
# [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报) # [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报)
# 补充表不参与发布解析门禁的字段覆盖/类型检查(正式路径另行按 LN 合并)。
business_tables = [
table for table in profile.table_regions
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
]
line_fields = [ line_fields = [
field for table in profile.table_regions for layout in table.line_layouts field for table in business_tables for layout in table.line_layouts
for field in layout.field_regions if field.scope == 'line' for field in layout.field_regions if field.scope == 'line'
] ]
line_coverage = _line_region_coverage_shift_tolerant( line_coverage = _line_region_coverage_shift_tolerant(
@@ -130,7 +137,7 @@ def validate_profile_parse_candidate(
required_line_codes = { required_line_codes = {
field.field_code field.field_code
for table in profile.table_regions for table in business_tables
for layout in table.line_layouts for layout in table.line_layouts
for field in layout.field_regions for field in layout.field_regions
if field.scope == 'line' if field.scope == 'line'
@@ -245,8 +252,13 @@ def _line_region_coverage_shift_tolerant(
""" """
if not profile.table_regions: if not profile.table_regions:
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0} return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
business_tables = [
table for table in profile.table_regions
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
]
tables_for_lines = business_tables or list(profile.table_regions)
line_fields = [ line_fields = [
field for table in profile.table_regions for layout_item in table.line_layouts field for table in tables_for_lines for layout_item in table.line_layouts
for field in layout_item.field_regions if field.scope == 'line' for field in layout_item.field_regions if field.scope == 'line'
] ]
if not line_fields: if not line_fields:
@@ -254,9 +266,9 @@ def _line_region_coverage_shift_tolerant(
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
# 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。 # 定位与主表区(首个 business_lines 且含 line_layouts)重叠且在 page 上的物理表;取重叠面积最大者。
primary_region = next( primary_region = next(
(table for table in profile.table_regions if table.line_layouts), None, (table for table in tables_for_lines if table.line_layouts), None,
) )
raw_table = _locate_overlapping_raw_table( raw_table = _locate_overlapping_raw_table(
primary_region=primary_region, layout=layout, page=page, profile=profile, primary_region=primary_region, layout=layout, page=page, profile=profile,
@@ -5,6 +5,7 @@ services/shipping_notice/document_layout/order_profile_signature.py
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。 依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。 逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。 另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
单逻辑表头行将格内折行副标签按 x 并入所属列,保留文案、不拆成新身份列。
""" """
from __future__ import annotations from __future__ import annotations
@@ -16,6 +17,7 @@ import statistics
from typing import Any from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import ( from app.services.shipping_notice.document_layout.coordinate_region_text import (
merge_header_identity_wrap_tokens,
positioned_token_spans, positioned_token_spans,
read_coordinate_region_text, read_coordinate_region_text,
visual_glyph_rows, visual_glyph_rows,
@@ -353,12 +355,15 @@ def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) ->
default=0, default=0,
) )
# 1 个 header_layout = 逻辑一行表头(可含格内折行);多 layout 才是多行正式表头。
single_logical_header_row = len(header_layouts) <= 1
for layout in sample_layouts: for layout in sample_layouts:
observed = _observe_sample_table( observed = _observe_sample_table(
layout, layout,
target_region=region, target_region=region,
header_region=header_region, header_region=header_region,
table_region=table, table_region=table,
single_logical_header_row=single_logical_header_row,
) )
if observed is None: if observed is None:
continue continue
@@ -433,6 +438,7 @@ def _observe_sample_table(
layout: dict[str, Any], *, target_region: RelativeRegion, layout: dict[str, Any], *, target_region: RelativeRegion,
header_region: RelativeRegion | None, header_region: RelativeRegion | None,
table_region: Any | None = None, table_region: Any | None = None,
single_logical_header_row: bool = True,
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。""" """读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)] tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
@@ -469,7 +475,10 @@ def _observe_sample_table(
table_glyphs, page=page, bbox=bbox, header_bbox=header_bbox, table_glyphs, page=page, bbox=bbox, header_bbox=header_bbox,
) )
header_tokens, centers, widths = _header_observation( header_tokens, centers, widths = _header_observation(
header_glyphs, page=page, bbox=bbox, header_glyphs,
page=page,
bbox=bbox,
single_logical_header_row=single_logical_header_row,
) )
header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None
termination_rules = [ termination_rules = [
@@ -556,9 +565,18 @@ def _union_relative_regions(regions: list[RelativeRegion]) -> RelativeRegion | N
def _header_observation( def _header_observation(
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float], glyphs: list[dict[str, Any]],
*,
page: dict[str, Any],
bbox: list[float],
single_logical_header_row: bool = True,
) -> tuple[list[str], list[float], list[float]]: ) -> tuple[list[str], list[float], list[float]]:
"""从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。""" """
从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。
核心逻辑:读出带内全部视觉行后,对逻辑一行表头按列中心回退把折行副标签并入
所属列(保留 Vendor Item# / Date 文案);多行正式表头不做合并。
"""
try: try:
page_width = float(page['width']) page_width = float(page['width'])
except (KeyError, TypeError, ValueError): except (KeyError, TypeError, ValueError):
@@ -571,6 +589,15 @@ def _header_observation(
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / page_width, 4) for item in spans] centers = [round((float(item['x0']) + float(item['x1'])) / 2 / page_width, 4) for item in spans]
span = max(bbox[2] - bbox[0], 0.0001) span = max(bbox[2] - bbox[0], 0.0001)
widths = [round((float(item['x1']) - float(item['x0'])) / page_width / span, 4) for item in spans] widths = [round((float(item['x1']) - float(item['x0'])) / page_width / span, 4) for item in spans]
if single_logical_header_row:
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
tokens, centers, widths,
)
return (
list(merged_tokens),
list(merged_centers or []),
list(merged_widths or []),
)
return tokens, centers, widths return tokens, centers, widths
@@ -3,7 +3,8 @@ services/shipping_notice/document_layout/runtime_parse_strategy.py
用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。 用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。
依赖:仅标准库;由正式抽取与模板质量验证共同调用。 依赖:仅标准库;由正式抽取与模板质量验证共同调用。
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。 逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用;
二者业务值冲突时,若动态列能单侧确认其一则采用该侧(或更完整的动态结果),否则转 Review。
""" """
from __future__ import annotations from __future__ import annotations
@@ -75,6 +76,15 @@ def resolve_runtime_parse_strategy(
baseline_rows = fixed_valid baseline_rows = fixed_valid
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ()) baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
else: else:
# [STEP] 固定/自适应业务值冲突:不得静默猜一侧;若动态列能单侧确认,再落选。
resolved = _resolve_fixed_adaptive_ambiguity_with_dynamic(
page_nos=page_nos,
fixed_rows=fixed_valid,
adaptive_rows=adaptive_valid,
dynamic_rows=dynamic_valid,
)
if resolved is not None:
return resolved
return RuntimeParseStrategy( return RuntimeParseStrategy(
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',), 'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
) )
@@ -103,6 +113,67 @@ def resolve_runtime_parse_strategy(
) )
def _resolve_fixed_adaptive_ambiguity_with_dynamic(
*,
page_nos: tuple[int, ...],
fixed_rows: list[dict[str, Any]],
adaptive_rows: list[dict[str, Any]],
dynamic_rows: list[dict[str, Any]],
) -> RuntimeParseStrategy | None:
"""
固定与自适应冲突时,用动态列做单侧确认。
核心逻辑:动态相对某一侧可覆盖(baseline/dynamic preferred),且相对另一侧
仍 ambiguous,则采用被确认的一侧;两侧都被动态确认且动态更完整时采用动态。
无动态证据或仍双边不清时返回 None,由调用方转 Review。
Args:
page_nos: 当前有坐标证据的页码。
fixed_rows: 有效固定子行。
adaptive_rows: 有效自适应行。
dynamic_rows: 有效动态列行;空则无法仲裁。
Returns:
可安全选中的策略;无法仲裁时为 None。
"""
if not dynamic_rows:
return None
fixed_vs_dyn = _compare_dynamic_row_coverage(
baseline_rows=fixed_rows, dynamic_rows=dynamic_rows,
)
adaptive_vs_dyn = _compare_dynamic_row_coverage(
baseline_rows=adaptive_rows, dynamic_rows=dynamic_rows,
)
fixed_ok = fixed_vs_dyn != 'ambiguous'
adaptive_ok = adaptive_vs_dyn != 'ambiguous'
if fixed_ok and adaptive_ok:
if fixed_vs_dyn == 'dynamic_preferred' or adaptive_vs_dyn == 'dynamic_preferred':
return RuntimeParseStrategy(
'selected', page_nos, 'dynamic_x_columns',
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
)
# 动态完整覆盖两侧且无额外行:冲突本身未消除,不能借动态消歧。
return None
if fixed_ok and not adaptive_ok:
if fixed_vs_dyn == 'dynamic_preferred':
return RuntimeParseStrategy(
'selected', page_nos, 'dynamic_x_columns',
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
)
return RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
if adaptive_ok and not fixed_ok:
if adaptive_vs_dyn == 'dynamic_preferred':
return RuntimeParseStrategy(
'selected', page_nos, 'dynamic_x_columns',
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
)
return RuntimeParseStrategy(
'selected', page_nos, 'adaptive_record_columns',
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
)
return None
def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]: def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]:
"""为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。 """为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。
@@ -210,29 +281,33 @@ def _compare_row_field_completeness(
def _compare_dynamic_row_coverage( def _compare_dynamic_row_coverage(
*, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]], *, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]],
) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']: ) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']:
"""仅当动态结果无冲突地覆盖基线每条记录并额外恢复记录时才切换策略。""" """仅当动态结果无冲突地覆盖基线,并额外恢复记录或严格加长字段值时才切换策略。"""
if len(dynamic_rows) < len(baseline_rows): if len(dynamic_rows) < len(baseline_rows):
return 'baseline_preferred' return 'baseline_preferred'
remaining = [_row_fields(row) for row in dynamic_rows] remaining = [_row_fields(row) for row in dynamic_rows]
extended = False
for baseline in baseline_rows: for baseline in baseline_rows:
baseline_fields = _row_fields(baseline) baseline_fields = _row_fields(baseline)
matches = [] matches = []
for index, dynamic_fields in enumerate(remaining): for index, dynamic_fields in enumerate(remaining):
if not baseline_fields.keys() <= dynamic_fields.keys(): if not baseline_fields.keys() <= dynamic_fields.keys():
continue continue
if all( compatible = True
dynamic_fields[code] == value for code, value in baseline_fields.items():
or ( dyn_value = dynamic_fields[code]
dynamic_fields[code].startswith(value) if dyn_value == value:
and len(dynamic_fields[code]) > len(value) continue
) if dyn_value.startswith(value) and len(dyn_value) > len(value):
for code, value in baseline_fields.items() extended = True
): continue
compatible = False
break
if compatible:
matches.append(index) matches.append(index)
if len(matches) != 1: if len(matches) != 1:
return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred' return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred'
remaining.pop(matches[0]) remaining.pop(matches[0])
return 'dynamic_preferred' if remaining else 'baseline_preferred' return 'dynamic_preferred' if remaining or extended else 'baseline_preferred'
def _row_fields(row: dict[str, Any]) -> dict[str, str]: def _row_fields(row: dict[str, Any]) -> dict[str, str]:
@@ -6,6 +6,7 @@ services/shipping_notice/document_profile_quality_service.py
逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对; 逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;
共同坐标回放完成视觉证据,末端值源 adapter 再补充正式字段和结构校验; 共同坐标回放完成视觉证据,末端值源 adapter 再补充正式字段和结构校验;
策略需复核时仍展示最佳努力明细供人工核对,正式自动建单仍要求策略 selected; 策略需复核时仍展示最佳努力明细供人工核对,正式自动建单仍要求策略 selected;
盲测主明细仅 business_lines,随后按 LN 合并 line_field_supplement 料号;
盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。 盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。
""" """
@@ -399,6 +400,9 @@ def _candidate_for_sample(
# layout. They are valid template regions, but cannot reconstruct rows. # layout. They are valid template regions, but cannot reconstruct rows.
if not region.line_layouts: if not region.line_layouts:
continue continue
# COO 等补充表不进入盲测主明细行;稍后按 LN 合并料号。
if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
continue
# ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中 # ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中
# 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。 # 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。
eligible_pages = [ eligible_pages = [
@@ -463,6 +467,30 @@ def _candidate_for_sample(
) )
# selected 与 needs_review 的 fallback 明细都要展示;后者仅供盲测人工复核。 # selected 与 needs_review 的 fallback 明细都要展示;后者仅供盲测人工复核。
rows.extend(item.fields for item in chosen_rows if not item.issues) rows.extend(item.fields for item in chosen_rows if not item.issues)
# 与正式解析共用:按 LN 合并 line_field_supplement(如 COO)料号。
from app.services.shipping_notice.order_extraction_workflow import (
_reconstruct_line_field_supplement_rows,
)
from app.services.shipping_notice.line_field_supplement_merge import (
merge_line_field_supplement,
)
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
raw_profile={
'definition': profile.definition_json if isinstance(profile.definition_json, dict) else {},
'profile_code': profile.profile_code,
'version': profile.version,
'checksum': profile.checksum,
},
layout=layout,
schema_fields=schema_fields,
)
supplement_reasons: list[str] = []
if supplement_rows:
rows, supplement_reasons = merge_line_field_supplement(
rows,
supplement_rows,
line_start_field_code=line_start or 'customer_po_line_no',
)
order_fields = [ order_fields = [
{ {
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status, 'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
@@ -521,8 +549,13 @@ def _candidate_for_sample(
'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'document_id': document.id, 'table_id': str(table_id), 'rows': rows,
'order_fields': order_fields, 'reservation_region_status': 'needs_review', 'order_fields': order_fields, 'reservation_region_status': 'needs_review',
'reservation_region_review_reasons': list(dict.fromkeys(review_reasons)), 'reservation_region_review_reasons': list(dict.fromkeys(review_reasons)),
'line_field_supplement_reasons': list(supplement_reasons),
} }
return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields} return {
'document_id': document.id, 'table_id': str(table_id), 'rows': rows,
'order_fields': order_fields,
'line_field_supplement_reasons': list(supplement_reasons),
}
raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
@@ -0,0 +1,278 @@
"""
services/shipping_notice/line_field_supplement_merge.py
用途:将同文档「明细字段补充表」(如 Hyve COO)按 LN 保守合并进主表明细。
依赖:无外部 IO;仅字符串规范化与行字典读写。
逻辑:由正式解析 / 盲测 / 验证在主表重建后调用;只补 customer_part_number、part_number;
空值直补、主表为补充值前缀则补全、冲突不覆盖并写稳定 reason。不改数量/单价/金额。
``REASON_APPLIED`` 仅写入表级 reasons 审计,不进入行 ``issues``(成功补齐不得触发 row_needs_review)。
"""
from __future__ import annotations
import copy
import re
from typing import Any
LINE_FIELD_SUPPLEMENT_CODES = frozenset({'customer_part_number', 'part_number'})
DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no'
REASON_APPLIED = 'line_field_supplement_applied'
REASON_CONFLICT = 'line_field_supplement_conflict'
REASON_LN_AMBIGUOUS = 'line_field_supplement_ln_ambiguous'
REASON_LN_MISSING = 'line_field_supplement_ln_missing'
# 表级审计码:不得当作行级缺陷拦截确定性建单。
NON_BLOCKING_ROW_ISSUE_CODES = frozenset({REASON_APPLIED})
def normalize_line_start_key(raw: Any) -> str:
"""
将行号规范为对齐键:去空白;纯数字去掉无意义前导零(保留至少一位)。
Args:
raw: 主表或补充表上的起行字段值。
Returns:
非空对齐键;无法规范化时返回空串。
"""
text = re.sub(r'\s+', '', str(raw or '')).strip()
if not text:
return ''
if text.isdigit():
return str(int(text))
return text
def normalize_part_value(raw: Any) -> str:
"""料号比较用:去掉空白,保留连字符等符号。"""
return re.sub(r'\s+', '', str(raw or '')).strip()
def _row_field_map(row: dict[str, Any]) -> dict[str, str]:
"""将扁平行或 workflow ``fields`` 列表统一为 field_code -> 文本值。"""
if not isinstance(row, dict):
return {}
fields = row.get('fields')
if isinstance(fields, list):
result: dict[str, str] = {}
for item in fields:
if not isinstance(item, dict):
continue
code = str(item.get('field_code') or '').strip()
if not code:
continue
result[code] = str(item.get('value') or '').strip()
return result
return {
str(key): str(value or '').strip()
for key, value in row.items()
if key not in {'fields', 'issues', 'status', 'row_index', 'role', 'source_row_indices'}
and not str(key).startswith('_')
}
def _set_row_field(row: dict[str, Any], field_code: str, value: str) -> None:
"""按行形态写回字段值;workflow 行写入 ``fields`` 列表。"""
fields = row.get('fields')
if isinstance(fields, list):
target = next(
(
item for item in fields
if isinstance(item, dict) and str(item.get('field_code') or '') == field_code
),
None,
)
if target is None:
fields.append({'field_code': field_code, 'value': value})
else:
target['value'] = value
return
row[field_code] = value
def _append_row_issue(row: dict[str, Any], code: str) -> None:
"""为 workflow 行追加 issue;扁平行写入 ``issues`` 列表供调用方读取。"""
issues = row.get('issues')
if not isinstance(issues, list):
row['issues'] = [code]
return
if code not in issues:
issues.append(code)
def _index_rows_by_line(
rows: list[dict[str, Any]],
*,
line_start_field_code: str,
) -> tuple[dict[str, dict[str, Any]], set[str], list[str]]:
"""
按规范化 LN 建唯一索引。
Returns:
(唯一行映射, 重复 LN 集合, 缺 LN 的全局 reasons)
"""
buckets: dict[str, list[dict[str, Any]]] = {}
missing_reasons: list[str] = []
for row in rows:
key = normalize_line_start_key(_row_field_map(row).get(line_start_field_code))
if not key:
missing_reasons.append(REASON_LN_MISSING)
continue
buckets.setdefault(key, []).append(row)
unique: dict[str, dict[str, Any]] = {}
ambiguous: set[str] = set()
for key, items in buckets.items():
if len(items) != 1:
ambiguous.add(key)
continue
unique[key] = items[0]
return unique, ambiguous, missing_reasons
def merge_line_field_supplement(
main_rows: list[dict[str, Any]],
supplement_rows: list[dict[str, Any]],
*,
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
field_codes: frozenset[str] = LINE_FIELD_SUPPLEMENT_CODES,
) -> tuple[list[dict[str, Any]], list[str]]:
"""
按 LN 将补充表料号合并进主表明细。
核心逻辑:只处理 ``field_codes``;空值直补;主表规范化值是补充值前缀则补全;
两边完整且不同则写冲突 reason 且不覆盖;补充侧或主侧 LN 重复/缺失则跳过该键。
成功补齐仅写入返回的 reasons(``REASON_APPLIED``),不写入行 ``issues``。
Args:
main_rows: 主表明细(扁平 dict 或含 ``fields`` 的 workflow 行)。
supplement_rows: 补充表重建行,形态同主表。
line_start_field_code: 对齐用起行字段,默认 customer_po_line_no。
field_codes: 允许补齐的字段集合。
Returns:
(合并后的主表行深拷贝, 稳定 reason 列表;可含表级审计码与行级冲突码)
"""
if not main_rows or not supplement_rows:
return [copy.deepcopy(row) for row in main_rows], []
merged = [copy.deepcopy(row) for row in main_rows]
main_index, main_ambiguous, main_missing = _index_rows_by_line(
merged, line_start_field_code=line_start_field_code,
)
supplement_index, supplement_ambiguous, supplement_missing = _index_rows_by_line(
supplement_rows, line_start_field_code=line_start_field_code,
)
reasons: list[str] = []
reasons.extend(main_missing)
reasons.extend(supplement_missing)
for key in sorted(main_ambiguous | supplement_ambiguous):
reasons.append(REASON_LN_AMBIGUOUS)
if key in main_index:
_append_row_issue(main_index[key], REASON_LN_AMBIGUOUS)
for row in merged:
if normalize_line_start_key(_row_field_map(row).get(line_start_field_code)) == key:
_append_row_issue(row, REASON_LN_AMBIGUOUS)
for line_key, main_row in main_index.items():
if line_key in main_ambiguous or line_key in supplement_ambiguous:
continue
supplement_row = supplement_index.get(line_key)
if supplement_row is None:
continue
main_fields = _row_field_map(main_row)
supplement_fields = _row_field_map(supplement_row)
for code in sorted(field_codes):
supplement_raw = supplement_fields.get(code) or ''
if not supplement_raw:
continue
main_raw = main_fields.get(code) or ''
main_norm = normalize_part_value(main_raw)
supplement_norm = normalize_part_value(supplement_raw)
if not supplement_norm:
continue
if not main_norm:
# [STEP] 成功直补:只记表级审计,不写行 issues(避免误判 row_needs_review)。
_set_row_field(main_row, code, supplement_raw)
reasons.append(REASON_APPLIED)
continue
if main_norm == supplement_norm:
continue
if supplement_norm.startswith(main_norm) and len(supplement_norm) > len(main_norm):
# [STEP] 前缀补全成功:同上,审计进 reasons,不写入 issues。
_set_row_field(main_row, code, supplement_raw)
reasons.append(REASON_APPLIED)
continue
_append_row_issue(main_row, REASON_CONFLICT)
reasons.append(REASON_CONFLICT)
# 保持 reason 顺序稳定且去重保留首次出现,便于审计对照。
deduped: list[str] = []
seen: set[str] = set()
for code in reasons:
if code in seen:
continue
seen.add(code)
deduped.append(code)
return merged, deduped
def project_line_field_supplement_onto_validation_evidence(
evidence: dict[str, Any],
*,
supplement_rows: list[dict[str, Any]],
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
) -> tuple[dict[str, Any], list[str]]:
"""
将补充表合并结果写回验证证据的 lines 字段。
Args:
evidence: 含 header_fields / lines 的验证 DTO。
supplement_rows: workflow 或扁平行。
line_start_field_code: LN 对齐字段。
Returns:
(更新后的 evidence 深拷贝, reason 列表)
"""
if not isinstance(evidence, dict) or not supplement_rows:
return copy.deepcopy(evidence) if isinstance(evidence, dict) else {}, []
result = copy.deepcopy(evidence)
lines = result.get('lines') if isinstance(result.get('lines'), list) else []
main_rows: list[dict[str, Any]] = []
for line in lines:
if not isinstance(line, dict):
continue
fields = []
for item in line.get('fields') or []:
if not isinstance(item, dict):
continue
fields.append({
'field_code': str(item.get('field_code') or ''),
'value': str(item.get('raw_value') or item.get('normalized_value') or ''),
})
main_rows.append({'fields': fields, 'issues': []})
if not main_rows:
return result, []
merged, reasons = merge_line_field_supplement(
main_rows, supplement_rows, line_start_field_code=line_start_field_code,
)
for index, row in enumerate(merged):
if index >= len(lines) or not isinstance(lines[index], dict):
continue
values = _row_field_map(row)
issues = list(row.get('issues') or [])
for field in lines[index].get('fields') or []:
if not isinstance(field, dict):
continue
code = str(field.get('field_code') or '')
if code not in LINE_FIELD_SUPPLEMENT_CODES or code not in values:
continue
value = values[code]
field['raw_value'] = value or None
field['normalized_value'] = value or None
field['status'] = 'passed' if value else field.get('status') or 'missing'
if issues:
field['issues'] = list(dict.fromkeys([*(field.get('issues') or []), *issues]))
result['line_field_supplement_reasons'] = list(reasons)
return result, reasons
@@ -1289,6 +1289,9 @@ def preview_profile_region(
# Header-only pages document column semantics but must never emit data rows. # Header-only pages document column semantics but must never emit data rows.
if not table_region.line_layouts: if not table_region.line_layouts:
continue continue
# 补充表不进入预览主网格;验证/正式路径另行按 LN 合并。
if str(getattr(table_region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
continue
# 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema # 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema
# 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。 # 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。
reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump()) reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump())
@@ -3,10 +3,11 @@ services/shipping_notice/order_document_profile_validation_service.py
用途:执行订单文档 Profile 草稿的不可变即时检查、当前样本试运行、版面/XFA 结构签名与跨模板唯一性验证。 用途:执行订单文档 Profile 草稿的不可变即时检查、当前样本试运行、版面/XFA 结构签名与跨模板唯一性验证。
依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、 依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、
Profile 保存服务、编辑租约服务、Reservation 专区锚点投影。 Profile 保存服务、编辑租约服务、Reservation 专区锚点投影、line_field_supplement_merge。
逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;坐标 current-sample 在表格/ 逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;坐标 current-sample 在表格/
表头试读后投影 Vendor Comments Reservation;XFA current-sample 另附脱敏字段级 表头试读后投影 Vendor Comments Reservation,并按 LN 合并 COO 等补充表料号;
Header/Line;签名成功后更新 Profile 轻量引用;查询时根据当前 checksum 派生 stale。 XFA current-sample 另附脱敏字段级 Header/Line;签名成功后更新 Profile 轻量引用;
查询时根据当前 checksum 派生 stale。
""" """
from __future__ import annotations from __future__ import annotations
@@ -419,6 +420,44 @@ def _extract_coordinate_current_sample(
reason=reservation.get('reason'), reason=reservation.get('reason'),
schema_fields=schema_fields, schema_fields=schema_fields,
) )
# [STEP] COO 等明细字段补充表按 LN 合并进验证 lines(与正式/盲测同契约)。
if any(
isinstance(item, dict) and str(item.get('region_role') or '') == 'line_field_supplement'
for item in definition.get('table_regions') or []
):
from app.services.shipping_notice.line_field_supplement_merge import (
project_line_field_supplement_onto_validation_evidence,
)
from app.services.shipping_notice.order_extraction_workflow import (
_reconstruct_line_field_supplement_rows,
)
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
layout = _load_sample_layout(sample) if document is not None else {}
if document is not None and isinstance(layout, dict):
layout = ensure_on_demand_coordinate_evidence(
document=document, layout=layout, page_nos=None,
)
schema_fields = {
str(item.get('field_id') or ''): item
for item in (profile.schema_version.definition_json or {}).get('fields') or []
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
}
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
raw_profile={
'definition': definition,
'profile_code': profile.profile_code,
'version': profile.version,
'checksum': profile.checksum,
},
layout=layout if isinstance(layout, dict) else {},
schema_fields=schema_fields,
)
if supplement_rows:
evidence, _reasons = project_line_field_supplement_onto_validation_evidence(
evidence,
supplement_rows=supplement_rows,
line_start_field_code=line_start or 'customer_po_line_no',
)
summary['validation_evidence'] = evidence summary['validation_evidence'] = evidence
return status, summary, snapshot return status, summary, snapshot
@@ -3,11 +3,12 @@ backend/app/services/shipping_notice/order_extraction_workflow.py
用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。 用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。
依赖:MinerU 紧凑快照、订单 Profile(coordinate / xfa_dataset)、Schema 校验、 依赖:MinerU 紧凑快照、订单 Profile(coordinate / xfa_dataset)、Schema 校验、
order_extraction_route_contract、xfa_profile_*、统一错误类型。 order_extraction_route_contract、xfa_profile_*、line_field_supplement_merge、统一错误类型。
逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值; 逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值;
datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review; datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review;
唯一 PO 提升到 Header 后从明细剥离,避免 persist 因 scope 不匹配失败; 唯一 PO 提升到 Header 后从明细剥离,避免 persist 因 scope 不匹配失败;
路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格; 路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格;
主明细仅来自 region_role=business_lines;line_field_supplement 按 LN 补料号;
模板 auto_create_approved 仅作解析器质量痕迹;主链不调用 Dify。 模板 auto_create_approved 仅作解析器质量痕迹;主链不调用 Dify。
""" """
@@ -38,6 +39,10 @@ from app.services.shipping_notice.document_layout.runtime_parse_strategy import
resolve_runtime_parse_strategy, resolve_runtime_parse_strategy,
select_runtime_region_ids, select_runtime_region_ids,
) )
from app.services.shipping_notice.line_field_supplement_merge import (
NON_BLOCKING_ROW_ISSUE_CODES,
merge_line_field_supplement,
)
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.document_layout.order_profile_matcher import ( from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchResult, ProfileMatchResult,
@@ -379,6 +384,9 @@ def _coordinate_profile_rows(
# 的坐标、起行字段与行重建结果裁决,不能仅依赖历史 page_scope 自动建单。 # 的坐标、起行字段与行重建结果裁决,不能仅依赖历史 page_scope 自动建单。
if region.region_id not in runtime_region_ids: if region.region_id not in runtime_region_ids:
continue continue
# 补充表不参与主明细重建,避免 COO 等副表进入 matches / multiple_business_tables。
if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
continue
# A continuation page may carry column headers only; it is not a data layout. # A continuation page may carry column headers only; it is not a data layout.
if not region.line_layouts: if not region.line_layouts:
continue continue
@@ -469,6 +477,239 @@ def _coordinate_profile_rows(
return rows return rows
def _pick_overlapping_layout_table(
*,
layout_tables: list[Any],
page_no: int,
region_relative: dict[str, Any],
page_size: dict[str, Any],
reference_page_frame: dict[str, Any] | None = None,
coordinate_transform: dict[str, Any] | None = None,
) -> tuple[str | None, dict[str, float] | None]:
"""
在同页 layout.tables 中选取与补充表相对区重叠的物理表。
核心逻辑:将相对区投影为页绝对框后与 MinerU 表求交,取纵向重叠面积最大者。
用于样本仅 1 行 COO 时,盲测多行仍能纵向扩到整张物理表读 glyph。
Args:
layout_tables: layout.tables 列表。
page_no: 当前页号。
region_relative: 补充表区相对 bbox。
page_size: 当前页宽高。
reference_page_frame: 可选参考页框;缺省用 page_size。
coordinate_transform: 可选坐标变换。
Returns:
(table_id, 绝对 bbox) 或 (None, None)。
"""
projected = apply_coordinate_transform_to_region(
region_relative, coordinate_transform=coordinate_transform,
)
if projected is None:
return None, None
try:
ref_w = float(reference_page_frame['width']) if reference_page_frame is not None else float(page_size['width'])
ref_h = float(reference_page_frame['height']) if reference_page_frame is not None else float(page_size['height'])
region_bbox = {
'x0': float(projected['x0']) * ref_w,
'y0': float(projected['y0']) * ref_h,
'x1': float(projected['x1']) * ref_w,
'y1': float(projected['y1']) * ref_h,
}
except (KeyError, TypeError, ValueError):
return None, None
best_id: str | None = None
best_bbox: dict[str, float] | None = None
best_overlap = 0.0
for item in layout_tables:
if not isinstance(item, dict):
continue
if int(item.get('page_no') or 1) != int(page_no):
continue
bbox = item.get('bbox')
if not isinstance(bbox, dict):
continue
try:
x0, y0, x1, y1 = float(bbox['x0']), float(bbox['y0']), float(bbox['x1']), float(bbox['y1'])
except (KeyError, TypeError, ValueError):
continue
if not (x0 < region_bbox['x1'] and x1 > region_bbox['x0'] and y0 < region_bbox['y1'] and y1 > region_bbox['y0']):
continue
overlap_h = max(0.0, min(x1, region_bbox['x1']) - max(x0, region_bbox['x0']))
overlap_v = max(0.0, min(y1, region_bbox['y1']) - max(y0, region_bbox['y0']))
overlap_area = overlap_h * overlap_v
if overlap_area <= best_overlap:
continue
best_overlap = overlap_area
best_id = str(item.get('table_id') or '') or None
best_bbox = {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
return best_id, best_bbox
def _reconstruct_line_field_supplement_rows(
*,
raw_profile: dict[str, Any],
layout: dict[str, Any],
schema_fields: dict[str, dict[str, Any]],
coordinate_transform: dict[str, Any] | None = None,
) -> tuple[list[dict[str, Any]], str | None]:
"""
从 Profile 的 line_field_supplement 表区按页坐标重建补充行(如 COO)。
核心逻辑:不把补充表当作业务表命中源;在补充区相对框内读 page_glyphs。
若同页存在与标注区重叠的 MinerU 物理表,则用其 bbox 纵向扩展字符范围
(样本单行 / 盲测多行时仍能读到整张 COO)。再以 with_strategy 取最佳努力行供 LN 合并。
Returns:
(workflow 形态行列表, line_start_field_code 或 None)
"""
try:
profile = _frozen_coordinate_profile(raw_profile)
except (TypeError, ValueError, ValidationError):
return [], None
supplement_regions = [
region for region in profile.table_regions
if str(getattr(region, 'region_role', None) or '') == 'line_field_supplement'
and region.line_layouts
]
if not supplement_regions:
return [], None
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
layout_tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
rows: list[dict[str, Any]] = []
line_start = None
for region in supplement_regions:
line_start = region.line_start_field_code or 'customer_po_line_no'
runtime_ids = set(select_runtime_region_ids(
table_regions=[_coordinate_object_mapping(item) for item in profile.table_regions],
page_no=int(region.page_no or 1) if region.page_scope == 'exact_page' else 1,
))
# exact_page 补充区按其页;all_pages/first_page 扫有 glyph 的页。
if region.page_scope == 'exact_page':
candidate_pages = [int(region.page_no or 1)]
else:
candidate_pages = sorted(
int(page_no) for page_no in page_glyphs
if str(page_no).isdigit() and isinstance(page_glyphs.get(str(page_no)), list)
)
if region.page_scope == 'first_page':
candidate_pages = [page for page in candidate_pages if page == 1] or [1]
for page_no in candidate_pages:
if region.page_scope == 'exact_page' and region.region_id not in runtime_ids and str(page_no) not in {str(region.page_no)}:
continue
page_size = pages.get(str(page_no))
characters = page_glyphs.get(str(page_no))
if not isinstance(page_size, dict) or not isinstance(characters, list) or not characters:
continue
try:
page_bbox = {
'x0': 0, 'y0': 0,
'x1': float(page_size['width']), 'y1': float(page_size['height']),
}
except (KeyError, TypeError, ValueError):
continue
reference_page_frames = getattr(profile, 'reference_page_frames', {})
reference_page_frame = (
reference_page_frames.get(page_no)
if isinstance(reference_page_frames, dict) else None
)
reconstruction_page_bbox = (
{
'x0': 0, 'y0': 0,
'x1': reference_page_frame.width, 'y1': reference_page_frame.height,
}
if reference_page_frame is not None else page_bbox
)
relative_region = _coordinate_region_mapping(region.region)
if relative_region is None:
continue
ref_frame_mapping = (
_coordinate_object_mapping(reference_page_frame)
if reference_page_frame is not None else None
)
# [STEP 1] 样本单行标注的相对框常盖不住盲测多行;重叠物理表纵向扩 glyph。
overlap_table_id, overlap_table_bbox = _pick_overlapping_layout_table(
layout_tables=layout_tables,
page_no=page_no,
region_relative=_coordinate_object_mapping(region.region),
page_size=page_size,
reference_page_frame=ref_frame_mapping,
coordinate_transform=coordinate_transform,
)
filtered, _ = coordinate_profile_character_candidates(
table_region=_coordinate_object_mapping(region.region),
page_size=page_size,
reference_page_frame=ref_frame_mapping,
page_characters=characters,
table_characters=None,
raw_table_bbox=overlap_table_bbox,
table_id=overlap_table_id,
page_no=page_no,
coordinate_transform=coordinate_transform,
allow_table_fallback=False,
)
if not isinstance(filtered, list) or not filtered:
continue
chosen_rows, _strategy = reconstruct_coordinate_profile_rows_with_strategy(
characters=[item for item in filtered if isinstance(item, dict)],
table_bbox=reconstruction_page_bbox,
line_layouts=[_coordinate_object_mapping(item) for item in region.line_layouts],
table_region=relative_region,
termination_rules=[_coordinate_object_mapping(item) for item in region.termination_rules],
exclusion_regions=reconstruction_exclusion_regions(_coordinate_object_mapping(region)),
line_start_field_code=region.line_start_field_code,
schema_field_metadata=list(schema_fields.values()),
coordinate_transform=coordinate_transform,
page_no=page_no,
)
for reconstructed in chosen_rows:
values = [
{'field_code': code, 'value': str(raw or '')}
for code, raw in reconstructed.fields.items()
]
rows.append({
'fields': values,
'issues': list(reconstructed.issues),
'page_no': page_no,
})
return rows, line_start
def _apply_line_field_supplement(
*,
raw_profile: dict[str, Any],
layout: dict[str, Any],
parsed_rows: list[dict[str, Any]],
schema_fields: dict[str, dict[str, Any]],
coordinate_transform: dict[str, Any] | None = None,
) -> tuple[list[dict[str, Any]], list[str]]:
"""主表明细重建后,按 LN 合并 line_field_supplement 料号。"""
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
raw_profile=raw_profile,
layout=layout,
schema_fields=schema_fields,
coordinate_transform=coordinate_transform,
)
if not supplement_rows:
return parsed_rows, []
merged, reasons = merge_line_field_supplement(
parsed_rows,
supplement_rows,
line_start_field_code=line_start or 'customer_po_line_no',
)
for row in merged:
issue_list = row.get('issues') if isinstance(row.get('issues'), list) else []
if any(
code in {'line_field_supplement_conflict', 'line_field_supplement_ln_ambiguous'}
for code in issue_list
):
row['status'] = 'needs_review'
return merged, reasons
def _selected_coordinate_transform( def _selected_coordinate_transform(
*, profile_match: dict[str, Any], raw_profile: dict[str, Any], *, profile_match: dict[str, Any], raw_profile: dict[str, Any],
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
@@ -620,10 +861,11 @@ def _physical_table_targets_profile_region(
): ):
return False return False
return True return True
# [STEP 2] 仅含 line_layouts 的明细区才是重建目标;纯表头壳直接跳过。 # [STEP 2] 仅含 line_layouts 的业务明细区才是重建目标;纯表头壳与补充表直接跳过。
active_regions = [ active_regions = [
region for region in page_regions region for region in page_regions
if region.get('line_layouts') if region.get('line_layouts')
and str(region.get('region_role') or 'business_lines') != 'line_field_supplement'
] ]
if not active_regions: if not active_regions:
return False return False
@@ -1042,6 +1284,18 @@ def _profile_table_candidates(
issues.append('order_profile_multiple_matches') issues.append('order_profile_multiple_matches')
continue continue
raw_profile, parsed = matches[0] raw_profile, parsed = matches[0]
coordinate_transform = _selected_coordinate_transform(
profile_match=profile_match, raw_profile=raw_profile,
)
parsed, supplement_reasons = _apply_line_field_supplement(
raw_profile=raw_profile,
layout=layout,
parsed_rows=parsed,
schema_fields=schema_fields,
coordinate_transform=coordinate_transform,
)
if any(code.endswith('_conflict') or code.endswith('_ambiguous') for code in supplement_reasons):
issues.extend(supplement_reasons)
reservation_region = _reservation_region_candidates(raw_profile=raw_profile, layout=layout) reservation_region = _reservation_region_candidates(raw_profile=raw_profile, layout=layout)
result_tables.append({ result_tables.append({
'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'), 'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'),
@@ -1052,6 +1306,7 @@ def _profile_table_candidates(
'page_no': int(raw_table.get('page_no') or 1), 'page_no': int(raw_table.get('page_no') or 1),
'auto_create_approved': bool(raw_profile.get('auto_create_approved')), 'auto_create_approved': bool(raw_profile.get('auto_create_approved')),
'rows': parsed, 'rows': parsed,
'line_field_supplement_reasons': list(supplement_reasons),
'reservation_region_candidates': reservation_region['candidates'], 'reservation_region_candidates': reservation_region['candidates'],
'reservation_region_reason': reservation_region['reason'], 'reservation_region_reason': reservation_region['reason'],
'runtime_parse_strategy': { 'runtime_parse_strategy': {
@@ -1925,7 +2180,13 @@ def _build_approved_profile_order_result(
# Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。 # Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。
if not isinstance(row, dict) or row.get('status') == 'deleted': if not isinstance(row, dict) or row.get('status') == 'deleted':
continue continue
if row.get('status') != 'parsed' or row.get('issues'): # [STEP] 忽略成功补料号等非阻塞审计码;仅真实缺陷才触发 row_needs_review。
raw_issues = row.get('issues') if isinstance(row.get('issues'), list) else []
blocking_issues = [
code for code in raw_issues
if str(code or '').strip() and str(code) not in NON_BLOCKING_ROW_ISSUE_CODES
]
if row.get('status') != 'parsed' or blocking_issues:
if not allow_manual_review: if not allow_manual_review:
return None, 'row_needs_review' return None, 'row_needs_review'
has_review_rows = True has_review_rows = True
@@ -5,7 +5,7 @@ Reservation ID 专用证据区域解析器。
并投影到验证证据 / 订单归属契约。 并投影到验证证据 / 订单归属契约。
依赖:reservation_id 格式校验、coordinate_region_text 视觉行序。 依赖:reservation_id 格式校验、coordinate_region_text 视觉行序。
逻辑:reservation_id_region 仅作启用标记;画布预览、盲测、正式解析共用本模块的 逻辑:reservation_id_region 仅作启用标记;画布预览、盲测、正式解析共用本模块的
锚点扫描与 apply/project,不再按保存矩形截取正式值。 锚点扫描与 apply/project,不再按保存矩形截取正式值;行号含 line# / L# / LN#。
""" """
from __future__ import annotations from __future__ import annotations
@@ -19,7 +19,15 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
_ID_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)") _ID_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)")
_LINE_RE = re.compile(r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b|\bfor\s+line\s*#?\s*(\d+)\b", re.I) # 行号写法:Line 1 / line#1 / for line#1 / Hyve 缩写 L#1、LN#1。
_LINE_RE = re.compile(
r"(?:"
r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b"
r"|\bfor\s+line\s*#?\s*(\d+)\b"
r"|\bl(?:n)?\s*#\s*(\d+)\b"
r")",
re.I,
)
_RESERVATION_LABEL_RE = re.compile(r"\breservation\b\s*(?:id)?\s*(?:#|:|-)?", re.I) _RESERVATION_LABEL_RE = re.compile(r"\breservation\b\s*(?:id)?\s*(?:#|:|-)?", re.I)
_VENDOR_COMMENTS_HEADING_RE = re.compile(r'^\s*vendor\s+comments?\b', re.I) _VENDOR_COMMENTS_HEADING_RE = re.compile(r'^\s*vendor\s+comments?\b', re.I)
_TERMS_AND_CONDITIONS_HEADING_RE = re.compile( _TERMS_AND_CONDITIONS_HEADING_RE = re.compile(
@@ -48,7 +56,11 @@ class ReservationRegionApplication:
def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidate]: def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidate]:
"""从区域原文提取候选;有行号归明细,无行号归订单头。""" """从区域原文提取候选;有行号归明细,无行号归订单头。
核心逻辑:同行须含 Reservation 标签;行号支持 ``line#1`` / ``for line#1`` /
``L#1`` / ``LN#1`` 等写法,命中后 scope=line,禁止误写入订单头。
"""
candidates: list[ReservationRegionCandidate] = [] candidates: list[ReservationRegionCandidate] = []
for raw_line in (str(text or '').splitlines() or [str(text or '')]): for raw_line in (str(text or '').splitlines() or [str(text or '')]):
line = raw_line.strip() line = raw_line.strip()
@@ -63,7 +75,8 @@ def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidat
line_match = _LINE_RE.search(line) line_match = _LINE_RE.search(line)
line_no = None line_no = None
if line_match: if line_match:
line_no = int(line_match.group(1) or line_match.group(2)) captured = next((group for group in line_match.groups() if group is not None), None)
line_no = int(captured) if captured is not None else None
scope = 'line' if line_no is not None else 'header' scope = 'line' if line_no is not None else 'header'
status = 'mapped' if line_no is not None else 'header' status = 'mapped' if line_no is not None else 'header'
for value in dict.fromkeys(ids): for value in dict.fromkeys(ids):
+51
View File
@@ -323,6 +323,57 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
assert not (failed_dir / trigger_path.name).exists() assert not (failed_dir / trigger_path.name).exists()
def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tmp_path):
"""配置测试无订单 Attempt/Gate 身份:不得 trigger_identity_invalid,须回调专用 ready。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
failed_dir = trigger_dir / "failed"
trigger_dir.mkdir()
drop_dir.mkdir()
run_no = "CONFIG-DSV360_AWSBI_BYAWSPRD01-20260909020428918536"
trigger_path = trigger_dir / f"inventory_export_batch_{run_no}.json"
# 与 inventory_configuration_test.start_test_export 写入形状一致:
# trigger_type=configuration_test,无 task_no / gate_id / execution_id 等生产身份。
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"{run_no}:batch:C1",
"batch_run_no": run_no,
"run_no": run_no,
"trigger_type": "configuration_test",
"configuration_test_run_id": 42,
"requested_at": "2026-09-09T02:04:28.918536",
"inventory_sources": [{
"source_code": "DSV360_AWSBI_BYAWSPRD01",
"connector_type": "dbs",
"worker_connector_type": "dsv360",
"warehouse_id": "BYAWSPRD01",
"login_url": "https://s360.dbschenker.com/",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {},
"parameters": [],
"query": {},
"credential_envelope": {},
}],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
assert not any(body.get("error_code") == "trigger_identity_invalid" for _, body in callbacks)
ready = next(body for path, body in callbacks if path.endswith("/inventory-configuration-test-ready"))
assert ready["run_no"] == run_no
assert ready["status"] == "success"
assert ready.get("file_path")
assert not any(path.endswith("/inventory-batch-ready") for path, _ in callbacks)
assert (processed_dir / trigger_path.name).is_file()
assert not (failed_dir / trigger_path.name).exists()
def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup(monkeypatch, tmp_path): def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup(monkeypatch, tmp_path):
"""Ctrl+C 中断导出时不回调或移动 trigger,且清理异常不能阻止停止 Playwright。""" """Ctrl+C 中断导出时不回调或移动 trigger,且清理异常不能阻止停止 Playwright。"""
worker = _load_freight_rpa_worker() worker = _load_freight_rpa_worker()
@@ -0,0 +1,309 @@
"""
tests/test_line_field_supplement_merge.py
用途:覆盖同文档 COO/明细字段补充表按 LN 合并的契约。
依赖:line_field_supplement_merge、order_profile.TableRegionProfile、
order_extraction_workflow._pick_overlapping_layout_table。
逻辑:断言空补、前缀补全、冲突不覆盖、LN 歧义/缺失与禁止改 qty;
成功补齐仅表级 reasons、不写入 issues;以及补充区与 MinerU 表重叠时的物理表选取。
"""
from __future__ import annotations
import pytest
from pydantic import ValidationError
from app.services.shipping_notice.document_layout.order_profile import TableRegionProfile
from app.services.shipping_notice.line_field_supplement_merge import (
REASON_APPLIED,
REASON_CONFLICT,
REASON_LN_AMBIGUOUS,
merge_line_field_supplement,
normalize_line_start_key,
normalize_part_value,
)
from app.services.shipping_notice.order_extraction_workflow import (
_pick_overlapping_layout_table,
)
def test_normalize_line_start_and_part_values():
"""关键断言:行号去前导零对齐;料号仅去空白。"""
assert normalize_line_start_key(' 02 ') == '2'
assert normalize_line_start_key('00010') == '10'
assert normalize_part_value('WTP-B3- A08') == 'WTP-B3-A08'
def test_merge_fills_empty_and_prefix_without_touching_qty():
"""空值直补、截断前缀补全,数量保持主表原值。"""
main = [
{'customer_po_line_no': '1', 'customer_part_number': '', 'part_number': 'B3-', 'qty': '30'},
{
'customer_po_line_no': '2',
'customer_part_number': 'WTP-B3-',
'part_number': '',
'qty': '3',
},
]
supplement = [
{
'customer_po_line_no': '1',
'customer_part_number': 'WTP-B3-A08AR11000001',
'part_number': 'B3-A08AR11000001',
},
{
'customer_po_line_no': '2',
'customer_part_number': 'WTP-B3-A08AR10000017-A6',
'part_number': 'B3-A08AR10000017-A6',
},
]
merged, reasons = merge_line_field_supplement(main, supplement)
assert merged[0]['customer_part_number'] == 'WTP-B3-A08AR11000001'
assert merged[0]['part_number'] == 'B3-A08AR11000001'
assert merged[0]['qty'] == '30'
assert merged[1]['customer_part_number'] == 'WTP-B3-A08AR10000017-A6'
assert merged[1]['part_number'] == 'B3-A08AR10000017-A6'
assert merged[1]['qty'] == '3'
assert REASON_APPLIED in reasons
assert REASON_CONFLICT not in reasons
# 关键断言:成功补齐不得进入行 issues,否则正式建单会被误判为 row_needs_review。
assert REASON_APPLIED not in (merged[0].get('issues') or [])
assert REASON_APPLIED not in (merged[1].get('issues') or [])
def test_merge_conflict_does_not_overwrite():
"""两边完整且不同时保留主表并记冲突。"""
main = [{'customer_po_line_no': '1', 'part_number': 'MAIN-ONLY', 'qty': '1'}]
supplement = [{'customer_po_line_no': '1', 'part_number': 'COO-OTHER'}]
merged, reasons = merge_line_field_supplement(main, supplement)
assert merged[0]['part_number'] == 'MAIN-ONLY'
assert merged[0]['qty'] == '1'
assert REASON_CONFLICT in reasons
assert REASON_CONFLICT in merged[0]['issues']
def test_merge_skips_ambiguous_line_numbers():
"""主表或补充表 LN 重复时不补该键。"""
main = [
{'customer_po_line_no': '1', 'part_number': ''},
{'customer_po_line_no': '1', 'part_number': ''},
]
supplement = [{'customer_po_line_no': '1', 'part_number': 'B3-A08'}]
merged, reasons = merge_line_field_supplement(main, supplement)
assert merged[0]['part_number'] == ''
assert merged[1]['part_number'] == ''
assert REASON_LN_AMBIGUOUS in reasons
def test_merge_workflow_shaped_rows():
"""workflow fields 列表形态同样可补齐。"""
main = [{
'status': 'needs_review',
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-'},
{'field_code': 'qty', 'value': '3'},
],
'issues': [],
}]
supplement = [{
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'},
{'field_code': 'part_number', 'value': 'B3-A08AR10000017-A6'},
],
}]
merged, reasons = merge_line_field_supplement(main, supplement)
values = {item['field_code']: item['value'] for item in merged[0]['fields']}
assert values['customer_part_number'] == 'WTP-B3-A08AR10000017-A6'
assert values['part_number'] == 'B3-A08AR10000017-A6'
assert values['qty'] == '3'
assert REASON_APPLIED in reasons
assert REASON_APPLIED not in (merged[0].get('issues') or [])
def test_apply_line_field_supplement_uses_reconstructed_coo_rows(monkeypatch):
"""关键断言:正式路径在主表截断后用补充表重建行补全料号。"""
from app.services.shipping_notice import order_extraction_workflow as workflow
def _fake_reconstruct(**_kwargs):
return (
[{
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'},
{'field_code': 'part_number', 'value': 'B3-A08AR10000017-A6'},
],
'issues': [],
}],
'customer_po_line_no',
)
monkeypatch.setattr(workflow, '_reconstruct_line_field_supplement_rows', _fake_reconstruct)
parsed = [{
'status': 'parsed',
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-'},
{'field_code': 'part_number', 'value': ''},
{'field_code': 'qty', 'value': '3'},
],
'issues': [],
}]
merged, reasons = workflow._apply_line_field_supplement(
raw_profile={'definition': {}},
layout={},
parsed_rows=parsed,
schema_fields={},
)
values = {item['field_code']: item['value'] for item in merged[0]['fields']}
assert values['customer_part_number'] == 'WTP-B3-A08AR10000017-A6'
assert values['part_number'] == 'B3-A08AR10000017-A6'
assert values['qty'] == '3'
assert REASON_APPLIED in reasons
def test_project_supplement_onto_validation_evidence():
"""关键断言:验证证据 lines 可被 COO 补齐且保留其它列。"""
from app.services.shipping_notice.line_field_supplement_merge import (
project_line_field_supplement_onto_validation_evidence,
)
evidence = {
'header_fields': [],
'lines': [{
'row_index': 0,
'fields': [
{'field_code': 'customer_po_line_no', 'raw_value': '2', 'normalized_value': '2', 'status': 'passed', 'issues': []},
{'field_code': 'customer_part_number', 'raw_value': 'WTP-B3-', 'normalized_value': 'WTP-B3-', 'status': 'passed', 'issues': []},
{'field_code': 'qty', 'raw_value': '3', 'normalized_value': '3', 'status': 'passed', 'issues': []},
],
}],
'cross_checks': {},
}
updated, reasons = project_line_field_supplement_onto_validation_evidence(
evidence,
supplement_rows=[{
'fields': [
{'field_code': 'customer_po_line_no', 'value': '2'},
{'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'},
],
}],
)
part = next(item for item in updated['lines'][0]['fields'] if item['field_code'] == 'customer_part_number')
qty = next(item for item in updated['lines'][0]['fields'] if item['field_code'] == 'qty')
assert part['raw_value'] == 'WTP-B3-A08AR10000017-A6'
assert qty['raw_value'] == '3'
assert REASON_APPLIED in reasons
def test_line_field_supplement_region_rejects_non_part_bindings():
"""补充表绑定数量等业务字段必须失败。"""
payload = {
'region_id': 'coo_lines',
'page_scope': 'exact_page',
'page_no': 1,
'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9},
'region_role': 'line_field_supplement',
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{
'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line',
'region': {'x0': .2, 'y0': 0, 'x1': .4, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
],
}],
}
with pytest.raises(ValidationError, match='line_field_supplement may only bind'):
TableRegionProfile.model_validate(payload)
def test_line_field_supplement_region_accepts_part_bindings():
"""补充表仅绑 LN + 料号字段可通过。"""
region = TableRegionProfile.model_validate({
'region_id': 'coo_lines',
'page_scope': 'exact_page',
'page_no': 1,
'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9},
'region_role': 'line_field_supplement',
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{
'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'cpn', 'field_code': 'customer_part_number', 'scope': 'line',
'region': {'x0': .2, 'y0': 0, 'x1': .6, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'pn', 'field_code': 'part_number', 'scope': 'line',
'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
},
],
}],
})
assert region.region_role == 'line_field_supplement'
def test_pick_overlapping_layout_table_prefers_max_vertical_overlap():
"""关键断言:同页重叠表取纵向重叠面积最大者;无重叠返回空。"""
page_size = {'width': 100.0, 'height': 100.0}
region = {'x0': 0.05, 'y0': 0.67, 'x1': 0.9, 'y1': 0.70}
tables = [
{
'table_id': 'header-ish',
'page_no': 1,
'bbox': {'x0': 5.0, 'y0': 10.0, 'x1': 90.0, 'y1': 40.0},
},
{
'table_id': 'coo-table',
'page_no': 1,
'bbox': {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0},
},
{
'table_id': 'other-page',
'page_no': 2,
'bbox': {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0},
},
]
table_id, bbox = _pick_overlapping_layout_table(
layout_tables=tables,
page_no=1,
region_relative=region,
page_size=page_size,
)
assert table_id == 'coo-table'
assert bbox == {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0}
empty_id, empty_bbox = _pick_overlapping_layout_table(
layout_tables=tables,
page_no=1,
region_relative={'x0': 0.05, 'y0': 0.90, 'x1': 0.9, 'y1': 0.95},
page_size=page_size,
)
assert empty_id is None
assert empty_bbox is None
@@ -64,6 +64,18 @@ def _two_page_layout() -> dict:
} }
def test_approved_pdf_ignores_line_field_supplement_applied_issue():
"""关键断言:COO 成功补齐的审计码不得触发 row_needs_review。"""
row = _row('PO-1', 'P-1')
row['issues'] = ['line_field_supplement_applied']
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=DEFINITION, table={'rows': [row]},
)
assert reason is None
assert len(orders or []) == 1
def test_approved_pdf_rejects_multiple_pos_in_one_pdf(): def test_approved_pdf_rejects_multiple_pos_in_one_pdf():
"""同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。""" """同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。"""
orders, reason = _build_approved_profile_order_result( orders, reason = _build_approved_profile_order_result(
@@ -12,6 +12,7 @@ import json
import zipfile import zipfile
from io import BytesIO from io import BytesIO
from pathlib import Path from pathlib import Path
from urllib.parse import quote
import pytest import pytest
@@ -27,8 +28,10 @@ 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_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,
_build_zip_entry_name,
) )
from tests.conftest import parse_api_error from tests.conftest import parse_api_error
from tests.test_shipping_notice_inventory_schedule import _make_inventory_schedule_task from tests.test_shipping_notice_inventory_schedule import _make_inventory_schedule_task
@@ -160,10 +163,12 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p
with zipfile.ZipFile(zip_path) as archive: with zipfile.ZipFile(zip_path) as archive:
names = archive.namelist() names = archive.namelist()
assert "manifest.json" in names assert "manifest.json" in names
assert any(name.endswith(".xlsx") for name in names) xlsx_names = [name for name in names if name.endswith(".xlsx")]
assert xlsx_names == ["001_DSV360_AWSBI_BYAWSCMH01.xlsx"]
manifest = json.loads(archive.read("manifest.json").decode("utf-8")) manifest = json.loads(archive.read("manifest.json").decode("utf-8"))
assert manifest["run_no"] == run.run_no assert manifest["run_no"] == run.run_no
assert manifest["files"][0]["inventory_file_no"] == "SIF-20260710-ARCH01" assert manifest["files"][0]["inventory_file_no"] == "SIF-20260710-ARCH01"
assert manifest["files"][0]["file_name"] == "001_DSV360_AWSBI_BYAWSCMH01.xlsx"
def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path): def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
@@ -230,7 +235,9 @@ def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path)
zip_path, file_name = resolve_inventory_raw_zip_download(run) zip_path, file_name = resolve_inventory_raw_zip_download(run)
assert zip_path.is_file() assert zip_path.is_file()
assert file_name == inventory_raw_zip_download_name(run.run_no) assert file_name == inventory_raw_zip_download_name(run)
assert file_name.endswith("-库存.zip")
assert file_name.startswith("库存RPA-")
def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app): def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app):
@@ -431,7 +438,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
task.notify_enabled = True task.notify_enabled = True
task.notify_user_ids_json = [user.id] task.notify_user_ids_json = [user.id]
run.excel_file_data = b"schedule excel" run.excel_file_data = b"schedule excel"
run.excel_file_name = "schedule.xlsx" run.excel_file_name = inventory_rpa_result_excel_name(run)
db.session.commit() db.session.commit()
_notify_schedule_run_wecom(task, run) _notify_schedule_run_wecom(task, run)
@@ -442,8 +449,8 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
assert "run_id=" in captured[0] assert "run_id=" in captured[0]
assert "raw_zip=1" in captured[0] assert "raw_zip=1" in captured[0]
assert "download=inventory_raw_zip" in captured[0] assert "download=inventory_raw_zip" in captured[0]
assert "schedule.xlsx" in media_uploads assert any(name.endswith("-结果.xlsx") for name in media_uploads)
assert inventory_raw_zip_download_name("RUN-ARCH-NOTIFY-1") in media_uploads assert any(name.endswith("-库存.zip") for name in media_uploads)
assert file_sends == ["media-1", "media-2"] assert file_sends == ["media-1", "media-2"]
@@ -471,7 +478,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
admin_jwt_headers, admin_jwt_headers,
tmp_path, tmp_path,
): ):
"""admin 鉴权通过时应返回 application/zip 且文件名与 run_no 一致。""" """admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。"""
archive_dir = tmp_path / "inventory_archives" archive_dir = tmp_path / "inventory_archives"
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
xlsx = tmp_path / "inventory.xlsx" xlsx = tmp_path / "inventory.xlsx"
@@ -497,7 +504,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
run.response_summary_json = persist_inventory_rpa_raw_zip_archive(run) run.response_summary_json = persist_inventory_rpa_raw_zip_archive(run)
db.session.commit() db.session.commit()
run_id = run.id run_id = run.id
expected_name = inventory_raw_zip_download_name(run.run_no) expected_name = inventory_raw_zip_download_name(run)
res = client.get( res = client.get(
f'/api/admin/schedule-runs/{run_id}/inventory-raw-zip', f'/api/admin/schedule-runs/{run_id}/inventory-raw-zip',
@@ -505,12 +512,36 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
) )
assert res.status_code == 200 assert res.status_code == 200
assert res.mimetype == 'application/zip' assert res.mimetype == 'application/zip'
assert expected_name in res.headers.get('Content-Disposition', '') # Werkzeug ASCII filename 会剥掉中文;真实下载名在 filename*=UTF-8'' 段。
disposition = res.headers.get('Content-Disposition', '')
assert quote(expected_name) in disposition
with zipfile.ZipFile(BytesIO(res.data)) as archive: with zipfile.ZipFile(BytesIO(res.data)) as archive:
names = archive.namelist() names = archive.namelist()
assert 'manifest.json' in names assert 'manifest.json' in names
assert any(name.endswith('.xlsx') for name in names) assert '001_DSV360_AWSBI_BYAWSCMH01.xlsx' in names
def test_build_zip_entry_name_prefers_source_code():
"""包内条目优先 source_code;无 source 时才回退仓码。"""
assert _build_zip_entry_name(
index=2,
source_code="DSV360_AWSBI_BYAWSCMH01",
warehouse_id="BYAWSCMH01",
original_suffix=".xlsx",
) == "002_DSV360_AWSBI_BYAWSCMH01.xlsx"
assert _build_zip_entry_name(
index=1,
source_code="CRANE_FOOTPRINT",
warehouse_id="unknown",
original_suffix=".xlsx",
) == "001_CRANE_FOOTPRINT.xlsx"
assert _build_zip_entry_name(
index=3,
source_code="",
warehouse_id="AWSSG",
original_suffix=".xlsx",
) == "003_AWSSG.xlsx"
def test_get_inventory_raw_zip_returns_404_when_archive_unavailable( def test_get_inventory_raw_zip_returns_404_when_archive_unavailable(
@@ -84,6 +84,18 @@ def test_reservation_region_maps_line_when_reservation_label_and_line_number_are
}] }]
def test_reservation_region_maps_hyve_l_hash_abbreviation_to_line():
"""关键断言:Hyve ``Reservation L#1: 1000153133`` 必须归明细行,不得写入单头。"""
assert extract_reservation_from_region_text("Reservation L#1: 1000153133") == [{
'value': '1000153133', 'line_no': 1, 'scope': 'line',
'raw_text': 'Reservation L#1: 1000153133', 'status': 'mapped',
}]
assert extract_reservation_from_region_text("Reservation LN#2: 1000153134") == [{
'value': '1000153134', 'line_no': 2, 'scope': 'line',
'raw_text': 'Reservation LN#2: 1000153134', 'status': 'mapped',
}]
def test_reservation_region_assigns_reservation_without_line_to_header(): def test_reservation_region_assigns_reservation_without_line_to_header():
"""无行号 Reservation 是整单事实,写 Header 后由既有回退规则应用给全部明细。""" """无行号 Reservation 是整单事实,写 Header 后由既有回退规则应用给全部明细。"""
assert extract_reservation_from_region_text("MDW hub order.Reservation#33008") == [{ assert extract_reservation_from_region_text("MDW hub order.Reservation#33008") == [{
@@ -836,6 +836,89 @@ def test_near_twin_header_discriminator_makes_unique_match():
assert 'profile_header_discriminator_conflict' in mx_on_tw.reason_codes assert 'profile_header_discriminator_conflict' in mx_on_tw.reason_codes
def test_single_logical_header_wrap_pollution_sanitized_for_identity():
"""单逻辑表头旧签名含折行副标签时,须并入所属列后再比身份(文案保留)。"""
from app.services.shipping_notice.document_layout.coordinate_region_text import (
merge_header_identity_wrap_tokens,
)
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_header_discriminator_atoms_conflict,
_signature_identity_header_tokens,
)
# Hyve 旧签名:主行 + 折行副标签 Vendor Item# / Date(centers 回退)。
signature = {
'table_patterns': [{
'header_row_count': 1,
'header_tokens': [
'LN', 'Quantity', 'Part', 'Number', 'Description',
'Requested Arrival', 'Unit', 'Price', 'Extension', 'Vendor Item#', 'Date',
],
'column_centers': [
0.0727, 0.1372, 0.2144, 0.2542, 0.3671, 0.561, 0.6532, 0.6841, 0.801,
0.2418, 0.5217,
],
}],
}
identity = _signature_identity_header_tokens(signature)
joined = ' '.join(identity)
# 关键断言:副标签文案仍在;不再作为独立尾列。
assert 'Vendor Item#' in joined
assert 'Date' in joined
assert identity[-1] != 'Date'
assert identity[-1] != 'Vendor Item#'
assert len(identity) == 9
observed_tokens, observed_centers, _ = merge_header_identity_wrap_tokens(
[
'ln', 'quantity', 'part', 'number', 'description',
'requested arrival', 'unit', 'price', 'extension', 'vendor item#', 'date',
],
[
0.0727, 0.1372, 0.2144, 0.2542, 0.3671, 0.561, 0.6532, 0.6841, 0.801,
0.2418, 0.5217,
],
)
assert _header_discriminator_atoms_conflict(
signature=signature,
observed={'header_tokens': observed_tokens},
) is False
# 近亲缺 ECCN 仍须硬杀。
twin_signature = {
'table_patterns': [{
'header_row_count': 1,
'header_tokens': [
'Item', 'Parts', 'No', 'ECCN', 'Description', 'REV', 'UNIT', 'QTY',
],
'column_centers': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8],
}],
}
twin_observed = {
'header_tokens': ['Item', 'Parts', 'No', 'Description', 'REV', 'UNIT', 'QTY'],
}
assert _header_discriminator_atoms_conflict(signature=twin_signature, observed=twin_observed) is True
def test_multi_row_header_signature_keeps_secondary_row_identity():
"""真多行表头(header_row_count>1)不得做折行合并。"""
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_signature_identity_header_tokens,
)
signature = {
'table_patterns': [{
'header_row_count': 3,
'header_tokens': ['Item', 'Qty', 'Price', 'Amount', 'PR_Number'],
# 故意造 x 回退:多行正式表头不得合并掉 PR_Number。
'column_centers': [0.1, 0.3, 0.5, 0.7, 0.2],
}],
}
assert _signature_identity_header_tokens(signature) == [
'Item', 'Qty', 'Price', 'Amount', 'PR_Number',
]
def test_required_anchors_skip_header_atom_hard_mutex(): def test_required_anchors_skip_header_atom_hard_mutex():
"""已配置必选锚点时,表头原子差异不得再硬杀;身份交给锚点门禁。""" """已配置必选锚点时,表头原子差异不得再硬杀;身份交给锚点门禁。"""
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'
@@ -166,6 +166,39 @@ def test_parse_validation_accepts_month_day_year_date_format():
assert result['metrics']['type_issue_count'] == 0 assert result['metrics']['type_issue_count'] == 0
def test_parse_validation_accepts_two_digit_year_dates():
"""关键断言:MM/DD/YY 通过类型 sanity,不得误杀 Hyve 等 PO 日期。"""
profile = _minimal_profile_snapshot(line_regions=[
{
'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0.05, 'y0': 0.4, 'x1': 0.09, 'y1': 0.5},
'allowed_sources': ['pdf_coordinate'],
'target_fields': [{
'scope': 'line', 'field_code': 'customer_po_line_no', 'field_id': 'line-id',
}],
},
{
'field_id': 'date-id', 'field_code': 'requested_receipt_date', 'scope': 'line',
'region': {'x0': 0.10, 'y0': 0.4, 'x1': 0.6, 'y1': 0.5},
'allowed_sources': ['pdf_coordinate'],
'target_fields': [{
'scope': 'line', 'field_code': 'requested_receipt_date', 'field_id': 'date-id',
}],
},
])
result = validate_profile_parse_candidate(
profile_snapshot=profile,
layout=_layout_with_line_text('06/16/26'),
definition={'fields': [{
'field_code': 'requested_receipt_date', 'enabled': True, 'value_type': 'date',
}]},
)
assert 'profile_parse_type_sanity_failed' not in result['reason_codes']
assert result['metrics'].get('type_issue_count', 0) == 0
def _layout_with_shifted_line_text(*, text: str = '001 PART-A 10') -> dict: def _layout_with_shifted_line_text(*, text: str = '001 PART-A 10') -> dict:
"""构造明细区文字被纵向位移到冻结字段带之下的 layout。 """构造明细区文字被纵向位移到冻结字段带之下的 layout。
@@ -182,3 +182,98 @@ def test_signature_relation_graph_uses_anchor_text_contract():
snapshot = build_layout_signature(definition=definition, sample_layouts=[_sample_layout()]) snapshot = build_layout_signature(definition=definition, sample_layouts=[_sample_layout()])
assert isinstance(snapshot['signature']['field_relation_graph'], list) assert isinstance(snapshot['signature']['field_relation_graph'], list)
def test_single_logical_header_wrap_excludes_secondary_visual_line_from_identity():
"""逻辑一行表头框住折行时,副标签并入所属列,不得拆成新身份列。"""
definition = _minimal_definition()
# 表头框盖住主行 + 折行副标签(与 Hyve 标注同构)。
definition['table_regions'][0]['header_layouts'][0]['region'] = {
'x0': 0, 'y0': 0.20, 'x1': 1, 'y1': 0.32,
}
page_h = 280.0
main_y0, main_y1 = 60.0, 72.0
wrap_y0, wrap_y1 = 76.0, 88.0
glyphs = []
# 主行:LN Quantity Part
x = 10.0
for word in ('LN', 'Quantity', 'Part'):
for char in word:
glyphs.append({
'text': char,
'bbox': {'x0': x, 'y0': main_y0, 'x1': x + 3, 'y1': main_y1},
'boundary_before': 'none',
})
x += 3.5
x += 8
# 折行副标签:Vendor(落在 Part 列下方)
x = 40.0
for char in 'Vendor':
glyphs.append({
'text': char,
'bbox': {'x0': x, 'y0': wrap_y0, 'x1': x + 3, 'y1': wrap_y1},
'boundary_before': 'none',
})
x += 3.5
layout = {
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 200, 'y1': 200}}],
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': page_h}},
'page_glyphs': {'1': glyphs},
'tables': {'table-1': glyphs},
},
}
pattern = build_layout_signature(definition=definition, sample_layouts=[layout])['signature']['table_patterns'][0]
tokens = [str(item) for item in pattern['header_tokens']]
assert pattern['header_row_count'] == 1
joined = ' '.join(tokens).casefold()
# 关键断言:Vendor 文案保留并入所属列,不得作为独立尾列。
assert 'ln' in joined
assert 'quantity' in joined
assert 'part' in joined
assert 'vendor' in joined
assert tokens[-1].casefold() != 'vendor'
assert len(tokens) == len(pattern['column_centers'])
assert len(tokens) <= 3
def test_multi_header_layouts_keep_both_visual_rows_in_identity():
"""多个 header_layout(真多行表头)须保留各行身份 token,不做折行合并。"""
definition = _minimal_definition()
definition['table_regions'][0]['header_layouts'] = [
{
'layout_id': 'header_r1', 'region': {'x0': 0, 'y0': 0.20, 'x1': 1, 'y1': 0.26},
'field_regions': [{
'field_id': 'hdr-item', 'field_code': 'item_no', 'scope': 'header',
'region': {'x0': 0.05, 'y0': 0.21, 'x1': 0.2, 'y1': 0.25},
'allowed_sources': ['pdf_coordinate'],
}],
},
{
'layout_id': 'header_r2', 'region': {'x0': 0, 'y0': 0.27, 'x1': 1, 'y1': 0.33},
'field_regions': [{
'field_id': 'hdr-pr', 'field_code': 'pr_number', 'scope': 'header',
'region': {'x0': 0.05, 'y0': 0.28, 'x1': 0.3, 'y1': 0.32},
'allowed_sources': ['pdf_coordinate'],
}],
},
]
glyphs = []
for index, char in enumerate('ITEM'):
glyphs.append({'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 60, 'x1': 13 + index * 4, 'y1': 72}})
for index, char in enumerate('PRNO'):
glyphs.append({'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 80, 'x1': 13 + index * 4, 'y1': 92}})
layout = {
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 200, 'y1': 200}}],
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 280}},
'page_glyphs': {'1': glyphs},
'tables': {'table-1': glyphs},
},
}
pattern = build_layout_signature(definition=definition, sample_layouts=[layout])['signature']['table_patterns'][0]
joined = ' '.join(str(item) for item in pattern['header_tokens']).upper()
assert pattern['header_row_count'] == 2
# 关键断言:两行正式表头都进入身份,不被折行合并误伤。
assert 'ITEM' in joined
assert 'PRNO' in joined
@@ -97,6 +97,74 @@ def test_runtime_strategy_requires_review_when_two_valid_modes_disagree_on_busin
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
def test_runtime_strategy_uses_dynamic_to_confirm_fixed_when_adaptive_conflicts():
"""关键断言:固定/自适应料号冲突时,动态列单侧覆盖固定则可落选;加长字段时升级动态列。"""
fixed = _row(line_no='1', part_no='B3-A08AR11000001')
fixed['fields'].append({'field_code': 'customer_part_number', 'value': 'WTP-B3-'})
adaptive = _row(line_no='1', part_no='WTP-B3-')
adaptive['fields'].append({'field_code': 'customer_part_number', 'value': 'WTP-B3-'})
dynamic = _row(line_no='1', part_no='B3-A08AR11000001')
dynamic['fields'].append({
'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR11000001',
})
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[fixed],
adaptive_rows=[adaptive],
dynamic_rows=[dynamic],
)
assert result.status == 'selected'
assert result.row_mode == 'dynamic_x_columns'
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
def test_runtime_strategy_uses_dynamic_to_confirm_adaptive_when_fixed_conflicts():
"""动态只与自适应一致时,应落选自适应而非继续 Review。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[_row(line_no='1', part_no='PART-WRONG')],
adaptive_rows=[_row(line_no='1', part_no='PART-RIGHT')],
dynamic_rows=[_row(line_no='1', part_no='PART-RIGHT')],
)
assert result.status == 'selected'
assert result.row_mode == 'adaptive_record_columns'
assert result.reason_codes == ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',)
def test_runtime_strategy_prefers_dynamic_when_it_extends_baseline_field_values():
"""动态无额外行但字段值严格加长时,也应升级动态列,避免截断料号。"""
fixed = _row(line_no='1', part_no='B3-A08')
dynamic = _row(line_no='1', part_no='B3-A08AR11000001')
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[fixed], adaptive_rows=[], dynamic_rows=[dynamic],
)
assert result.status == 'selected'
assert result.row_mode == 'dynamic_x_columns'
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
def test_runtime_strategy_prefers_dynamic_when_it_confirms_fixed_and_recovers_extra_row():
"""动态确认固定侧且额外恢复记录时,应升级为动态列。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[_row(line_no='20', part_no='PART-B')],
adaptive_rows=[_row(line_no='20', part_no='PART-X')],
dynamic_rows=[
_row(line_no='10', part_no='PART-A'),
_row(line_no='20', part_no='PART-B'),
],
)
assert result.status == 'selected'
assert result.row_mode == 'dynamic_x_columns'
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
def test_runtime_strategy_requires_review_when_two_modes_disagree_on_non_key_business_value(): def test_runtime_strategy_requires_review_when_two_modes_disagree_on_non_key_business_value():
"""同项次料号但数量不同仍是业务冲突,不能因主键一致而静默采用固定子行。""" """同项次料号但数量不同仍是业务冲突,不能因主键一致而静默采用固定子行。"""
fixed = _row(line_no='10', part_no='PART-A') fixed = _row(line_no='10', part_no='PART-A')
+8 -4
View File
@@ -87,6 +87,7 @@
- **模板样本就绪门禁(2026-08-21)**:上传成功只表示 PDF/EML 已物化为 `ShippingOrderDocument`,不表示可自动标注。Draft annotation sample 必须由同一 `refresh_profile_sample_readiness()` 在当前 ready Layout 上验证视觉主表、内容 hash、canonical payload checksum、parser provenance,并冻结 `layout_version_id + layout_payload_checksum` 后,才返回 `automark_ready=true`。保存草稿、样本状态轮询和 `/pdf-automark` 入队共用此服务;一旦主表缺失/歧义、Layout 尚未完成或身份不一致,返回稳定原因码并禁止入队,绝不降级成“配置无效”或猜测。Worker 执行期仍复验 Job 的冻结身份。状态按 `profile_id + annotation sample` 隔离,同一文档被其他 Draft 引用不会影响当前模板。该回填仅更新现有 Draft sample 字段和追加式审计,不新建 Profile 版本、不修改已发布版本。 - **模板样本就绪门禁(2026-08-21)**:上传成功只表示 PDF/EML 已物化为 `ShippingOrderDocument`,不表示可自动标注。Draft annotation sample 必须由同一 `refresh_profile_sample_readiness()` 在当前 ready Layout 上验证视觉主表、内容 hash、canonical payload checksum、parser provenance,并冻结 `layout_version_id + layout_payload_checksum` 后,才返回 `automark_ready=true`。保存草稿、样本状态轮询和 `/pdf-automark` 入队共用此服务;一旦主表缺失/歧义、Layout 尚未完成或身份不一致,返回稳定原因码并禁止入队,绝不降级成“配置无效”或猜测。Worker 执行期仍复验 Job 的冻结身份。状态按 `profile_id + annotation sample` 隔离,同一文档被其他 Draft 引用不会影响当前模板。该回填仅更新现有 Draft sample 字段和追加式审计,不新建 Profile 版本、不修改已发布版本。
- Profile 仅允许 `draft -> published`;发布前必须满足 Schema/字段绑定校验、训练样本、独立盲测、双人批准、冻结样本证据及发布检查。已发布/退役版本只读;演进只能克隆为新 Draft,旧发布版本退役。管理端不提供自动接受、自动批准或自动发布路径。 - Profile 仅允许 `draft -> published`;发布前必须满足 Schema/字段绑定校验、训练样本、独立盲测、双人批准、冻结样本证据及发布检查。已发布/退役版本只读;演进只能克隆为新 Draft,旧发布版本退役。管理端不提供自动接受、自动批准或自动发布路径。
- **盲测预览明细展示(2026-09-09)**:`reconstruct_coordinate_profile_rows_with_strategy` 在运行时策略为 `needs_review` 时仍返回 fixed→adaptive→dynamic 的最佳努力明细,供盲测/验证人工核对;正式自动建单路径仍要求 `strategy.status == 'selected'`,不得把 fallback 当成可自动建单结果。盲测候选重建前还会确保表所在页的整页坐标证据已补齐。 - **盲测预览明细展示(2026-09-09)**:`reconstruct_coordinate_profile_rows_with_strategy` 在运行时策略为 `needs_review` 时仍返回 fixed→adaptive→dynamic 的最佳努力明细,供盲测/验证人工核对;正式自动建单路径仍要求 `strategy.status == 'selected'`,不得把 fallback 当成可自动建单结果。盲测候选重建前还会确保表所在页的整页坐标证据已补齐。
- **明细字段补充表 / COO(2026-09-09)**:`table_regions[].region_role` 区分 `business_lines`(默认,主明细命中源)与 `line_field_supplement`(同文档按 LN 补 `customer_part_number`/`part_number`,如 Hyve COO)。补充表不进入 `matches`/`multiple_business_tables`;合并策略为空值直补、主表为补充值前缀则补全、完整冲突则 Review 不覆盖;正式解析、盲测候选与验证 `current_sample` 共用 `line_field_supplement_merge`。重建时若同页存在与标注区重叠的 MinerU 物理表,则用其 bbox **纵向扩展** glyph 范围,避免样本仅 1 行 COO、盲测多行时相对框偏矮读不到数据行。版面签名 `table_patterns` **排除** `line_field_supplement`,且仅取顶部连续表头带,避免副表/误挂表头污染 `header_tokens` 导致训练样本自命中 0%。
### Dify 手工配置说明 ### Dify 手工配置说明
@@ -1754,7 +1755,7 @@ GET /api/admin/shipping-order-schema/published-contract
- 管理端以结构化行编辑器维护标准库存字段、文件表头与订单行字段匹配键,所有可选项来自后端 `GET /api/admin/shipping-notice/configuration-catalog`,不要求管理员直接编辑 JSON。 - 管理端以结构化行编辑器维护标准库存字段、文件表头与订单行字段匹配键,所有可选项来自后端 `GET /api/admin/shipping-notice/configuration-catalog`,不要求管理员直接编辑 JSON。
- 管理员新建库存文件解析方案时先上传 `.xls/.xlsx/.csv` 样本至 `POST /api/admin/shipping-notice/inventory-structure-analyses`。后端读取所有工作表、候选表头、真实栏位、推断类型、空值率与最多五行脱敏样例;管理端样本完整文件只在即时分析期间存在,分析完成后立即清理。`shipping_inventory_structure_analyses` 保留文件名、checksum、完整结构、统计、结构指纹和脱敏样例;`ShippingInventoryParsingProfile.sample_analysis_id` 绑定草稿和发布版本的样本证据。页面只允许从该证据选择工作表、表头和来源栏位,`POST /inventory-structure-analyses/{id}/create-profile-draft` 用确认后的结果创建草稿,不能以浏览器提交的虚构栏位替代分析结果。解析方案列表 DTO 返回最小化 `sample_evidence`;管理端再次打开草稿时从此恢复候选工作表、表头、来源栏位下拉和脱敏预览,不读取或回传原始文件。草稿替换样本前通过 `POST /parsing-profiles/{profile_id}/sample-replacement-preview/{analysis_id}` 以当前拟保存映射计算新增/缺少栏位、顺序变化、失效映射和格式差异;仅无失效映射且管理员在平台确认弹窗确认后,`create-profile-draft` 才接受 `confirm_sample_replacement=true` 切换证据。旧/新分析 ID、操作者和时间追加到 `sample_evidence_history_json`,已发布版本不可替换样本。Dify 画布不参与此证据绑定流程。 - 管理员新建库存文件解析方案时先上传 `.xls/.xlsx/.csv` 样本至 `POST /api/admin/shipping-notice/inventory-structure-analyses`。后端读取所有工作表、候选表头、真实栏位、推断类型、空值率与最多五行脱敏样例;管理端样本完整文件只在即时分析期间存在,分析完成后立即清理。`shipping_inventory_structure_analyses` 保留文件名、checksum、完整结构、统计、结构指纹和脱敏样例;`ShippingInventoryParsingProfile.sample_analysis_id` 绑定草稿和发布版本的样本证据。页面只允许从该证据选择工作表、表头和来源栏位,`POST /inventory-structure-analyses/{id}/create-profile-draft` 用确认后的结果创建草稿,不能以浏览器提交的虚构栏位替代分析结果。解析方案列表 DTO 返回最小化 `sample_evidence`;管理端再次打开草稿时从此恢复候选工作表、表头、来源栏位下拉和脱敏预览,不读取或回传原始文件。草稿替换样本前通过 `POST /parsing-profiles/{profile_id}/sample-replacement-preview/{analysis_id}` 以当前拟保存映射计算新增/缺少栏位、顺序变化、失效映射和格式差异;仅无失效映射且管理员在平台确认弹窗确认后,`create-profile-draft` 才接受 `confirm_sample_replacement=true` 切换证据。旧/新分析 ID、操作者和时间追加到 `sample_evidence_history_json`,已发布版本不可替换样本。Dify 画布不参与此证据绑定流程。
- 样本分析为文件结构生成精确指纹,解析方案保存同样的不可变结构定义;库存数据和文件名不参与判断。已发布方案的表头完全相同则返回 `exact`;方案实际使用的匹配/数量来源表头仍存在且仅有无关列变化时返回 `compatible` 并列出差异;所需栏位缺失、重复或冲突时不推荐复用。字段显示名称与真实表头标准化后完全相同时可确定性预填,其他陌生表头必须由管理员选择或 Dify 仅给候选。系统不得内置固定业务字段词典或自动创建字段。 - 样本分析为文件结构生成精确指纹,解析方案保存同样的不可变结构定义;库存数据和文件名不参与判断。已发布方案的表头完全相同则返回 `exact`;方案实际使用的匹配/数量来源表头仍存在且仅有无关列变化时返回 `compatible` 并列出差异;所需栏位缺失、重复或冲突时不推荐复用。字段显示名称与真实表头标准化后完全相同时可确定性预填,其他陌生表头必须由管理员选择或 Dify 仅给候选。系统不得内置固定业务字段词典或自动创建字段。
- 停用库存站点通过 `POST /api/admin/shipping-notice/sources/{id}/test-export` 写入 `configuration_test` trigger,Worker 完成后回调 `/api/shipping-notice/rpa/inventory-configuration-test-ready`。该文件只进入结构分析,不创建生产快照或任务链接;管理端轮询 `GET /sources/{id}/test-export/{run_no}` 并通过 `POST .../confirm-profile` 确认解析方案。Dify 不参与该流程。 - 停用库存站点通过 `POST /api/admin/shipping-notice/sources/{id}/test-export` 写入 `configuration_test` trigger,Worker 完成后回调 `/api/shipping-notice/rpa/inventory-configuration-test-ready`。该文件只进入结构分析,不创建生产快照或任务链接;管理端轮询 `GET /sources/{id}/test-export/{run_no}` 并通过 `POST .../confirm-profile` 确认解析方案。Dify 不参与该流程。**身份契约**:`configuration_test` / `configuration_test_batch` 与 `scheduled` 同属按 run 计价模式,不携带订单 `task_no` / Attempt / Gate 等生产身份;Worker 不得对其做逐源 v2 身份 fail-closed(否则会误报 `trigger_identity_invalid` 并错误回调生产 `inventory-batch-ready`)。
- **一期直接绑定**:停用站点可通过 `POST /api/admin/shipping-notice/sources/{id}/bind-parsing-profile` 直接绑定一个 `published` Profile;多站点使用 `POST /api/admin/shipping-notice/sources/bulk-bind-parsing-profile`。`reason` 是可选补充说明;未填写时,服务端自动记录直接或批量绑定动作。服务端先全量检查站点停用、方案已发布及当前 published 发货模板引用的全部库存字段均由方案提供,任一失败则整批不写入。成功后增加 `source.config_version`、写入 `shipping_inventory_source_parsing_binding_audits` 前后快照,但不触发 RPA、不产生快照、不启用站点。管理员可通过 `GET /sources/{id}/parsing-binding-audits` 追溯绑定。**Dify 手动配置说明**:一期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;上述管理 API 不供 Dify 调用。 - **一期直接绑定**:停用站点可通过 `POST /api/admin/shipping-notice/sources/{id}/bind-parsing-profile` 直接绑定一个 `published` Profile;多站点使用 `POST /api/admin/shipping-notice/sources/bulk-bind-parsing-profile`。`reason` 是可选补充说明;未填写时,服务端自动记录直接或批量绑定动作。服务端先全量检查站点停用、方案已发布及当前 published 发货模板引用的全部库存字段均由方案提供,任一失败则整批不写入。成功后增加 `source.config_version`、写入 `shipping_inventory_source_parsing_binding_audits` 前后快照,但不触发 RPA、不产生快照、不启用站点。管理员可通过 `GET /sources/{id}/parsing-binding-audits` 追溯绑定。**Dify 手动配置说明**:一期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;上述管理 API 不供 Dify 调用。
- **二期空库存验证**:Worker 将 `NoInventoryDataError` 作为 `status=empty` 回调,站点验证运行保存为 `completed_empty / empty_data_pending_validation`,而不是 `failed`。只有站点已绑定 `published` Profile 时,空结果才作为当前配置版本的连接/业务查询成功证据;否则仍失败,避免无解析定义时误放行。固定仓的空结果使 `configuration_test` 通过,`parsing_validation` 标为“待首次非空文件验证”但不阻断;动态仓仍阻断 `warehouse_identification`,因为空结果无法证明仓库识别和映射覆盖。定时 RPA 批量回调对 `skip_reason=no_inventory_data` 写入 `shipping_inventory_files.snapshot_status=empty`、`line_count=0` 的幂等审计快照;`find_latest_ready_snapshot`、任务链接与匹配链路只读取 `ready`,因此空快照绝不参与订单匹配或发货。**Dify 手动配置说明**:二期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;Dify 不读取站点验证或空快照状态。 - **二期空库存验证**:Worker 将 `NoInventoryDataError` 作为 `status=empty` 回调,站点验证运行保存为 `completed_empty / empty_data_pending_validation`,而不是 `failed`。只有站点已绑定 `published` Profile 时,空结果才作为当前配置版本的连接/业务查询成功证据;否则仍失败,避免无解析定义时误放行。固定仓的空结果使 `configuration_test` 通过,`parsing_validation` 标为“待首次非空文件验证”但不阻断;动态仓仍阻断 `warehouse_identification`,因为空结果无法证明仓库识别和映射覆盖。定时 RPA 批量回调对 `skip_reason=no_inventory_data` 写入 `shipping_inventory_files.snapshot_status=empty`、`line_count=0` 的幂等审计快照;`find_latest_ready_snapshot`、任务链接与匹配链路只读取 `ready`,因此空快照绝不参与订单匹配或发货。**Dify 手动配置说明**:二期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;Dify 不读取站点验证或空快照状态。
- 库存站点详情的 `activation` 是 HXOPS 后端唯一的上线检查真相,返回 `ready` 与按配置顺序排列的 `checks[]`。每项包含稳定业务编号 `code`、`passed / pending / failed / stale` 状态、`blocking`、推荐 `action` 和非敏感 `evidence`;管理端只负责翻译与引导,不得根据表单值重算启用资格。`missing_requirements` 仅是由阻断 checks 派生的紧凑摘要。 - 库存站点详情的 `activation` 是 HXOPS 后端唯一的上线检查真相,返回 `ready` 与按配置顺序排列的 `checks[]`。每项包含稳定业务编号 `code`、`passed / pending / failed / stale` 状态、`blocking`、推荐 `action` 和非敏感 `evidence`;管理端只负责翻译与引导,不得根据表单值重算启用资格。`missing_requirements` 仅是由阻断 checks 派生的紧凑摘要。
@@ -2035,7 +2036,9 @@ python -m pip install playwright openpyxl pyyaml
python -m playwright install chromium python -m playwright install chromium
``` ```
若使用本机 Edge 浏览器,worker 可配置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`。 **默认使用 Playwright 捆绑 Chromium**(上一步已 `playwright install chromium`)。
勿设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`:Edge 152 + 持久 Profile
在 Excel 下载时会原生崩溃(`Download.save_as: TargetClosed` / 残留 `.crdownload`)。
#### 1.5.5 Windows RPA 主机:临时环境变量与登录测试 #### 1.5.5 Windows RPA 主机:临时环境变量与登录测试
@@ -2056,7 +2059,7 @@ $env:SHIPPING_NOTICE_TOOL_API_KEY = "请替换为测试环境SHIPPING_NOTICE_TOO
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" $env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge" # 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。
$env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" $env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\inventory_triggers" $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\inventory_triggers"
@@ -2462,7 +2465,7 @@ $env:SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = "<本地 RPA 凭据主密钥>"
$env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "dev" $env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "dev"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" $env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge" # 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。
$env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" $env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers" $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory_drop" $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory_drop"
@@ -3194,6 +3197,7 @@ API 层
- 定时排程:`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`。
- **空快照状态约束**(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 审计字段
+1
View File
@@ -118,6 +118,7 @@
| **旧 XFA 合成预览/OCR 专用入口** | 已废弃 | 浏览器不得调用 `/xfa/automark`;内部 XFA 多源执行器由统一 `/pdf-automark` 调用,原生 PDF 页是统一画布。 | | **旧 XFA 合成预览/OCR 专用入口** | 已废弃 | 浏览器不得调用 `/xfa/automark`;内部 XFA 多源执行器由统一 `/pdf-automark` 调用,原生 PDF 页是统一画布。 |
| **XFA 字段拆分映射(历史)** | 已被统一方案接管 | 早期 `stages[]` 流水线与独立映射页能力将在统一方案阶段 1/4 对齐并收口;对照文档:[xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md)。 | | **XFA 字段拆分映射(历史)** | 已被统一方案接管 | 早期 `stages[]` 流水线与独立映射页能力将在统一方案阶段 1/4 对齐并收口;对照文档:[xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md)。 |
| 订单模板录入 UX 重构(阶段 0-7) | 已完成 | 已完成 Draft Revision、Lease、向导、独立草稿编辑器自动保存、不可变验证运行与两步发布报告;样本上传仅负责资产保存和 PDF/EML Document 物化,版面解析作为后台预热且不阻断上传。自动标注另经统一 Draft 样本就绪门禁:当前 ready Layout、唯一视觉主表、内容/hash/checksum/parser 身份均可验证时才幂等冻结样本证据并入队;保存、轮询、入队和 Worker 复验使用同一契约,失败展示可操作原因且不影响其他 Profile。盲测复核区分准备中、兼容性诊断和正式复核:仅 ready Layout 的真实 table_id 可确认,确认时冻结 LayoutVersion/checksum/parser 身份,执行不回读最新布局;临时 PDF 恢复仅作诊断。同模板族历史 annotation/training/新旧 blind test 文档可重新复核复用,当前版本建模样本仍严格排除。编辑器在可见状态自动续租。Dify 无需配置变更。 | | 订单模板录入 UX 重构(阶段 0-7) | 已完成 | 已完成 Draft Revision、Lease、向导、独立草稿编辑器自动保存、不可变验证运行与两步发布报告;样本上传仅负责资产保存和 PDF/EML Document 物化,版面解析作为后台预热且不阻断上传。自动标注另经统一 Draft 样本就绪门禁:当前 ready Layout、唯一视觉主表、内容/hash/checksum/parser 身份均可验证时才幂等冻结样本证据并入队;保存、轮询、入队和 Worker 复验使用同一契约,失败展示可操作原因且不影响其他 Profile。盲测复核区分准备中、兼容性诊断和正式复核:仅 ready Layout 的真实 table_id 可确认,确认时冻结 LayoutVersion/checksum/parser 身份,执行不回读最新布局;临时 PDF 恢复仅作诊断。同模板族历史 annotation/training/新旧 blind test 文档可重新复核复用,当前版本建模样本仍严格排除。编辑器在可见状态自动续租。Dify 无需配置变更。 |
| **明细字段补充表(COO 按 LN 补料号)** | 已实现(2026-09-09) | `table_regions.region_role=line_field_supplement`;仅补 `customer_part_number`/`part_number`;正式解析/盲测/验证共用合并契约;冲突进 Review。见 `technical.md`。 |
| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。字段和明细可按冻结 bbox 定位 PDF 原文(明细按 table/cell 反查),版本历史按需展开;确认后展示 `auto_progress` 真实结果/检查点并可直达任务进度工作台。单 PDF 重识别复用 WorkflowItem 真实状态展示已提交/版面解析/字段提取/草稿生成,完成后自动打开新版;“跳转当前版本”点击时强制刷新工作项,目标未就绪时明确提示。 | | 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。字段和明细可按冻结 bbox 定位 PDF 原文(明细按 table/cell 反查),版本历史按需展开;确认后展示 `auto_progress` 真实结果/检查点并可直达任务进度工作台。单 PDF 重识别复用 WorkflowItem 真实状态展示已提交/版面解析/字段提取/草稿生成,完成后自动打开新版;“跳转当前版本”点击时强制刷新工作项,目标未就绪时明确提示。 |
| **复核工作台布局重构(阶段 0–5)** | 已实现(待真机视觉签署) | 替换旧三栏:主编辑区 + 阻断摘要侧栏;PDF **默认右下角浮动证据面板**(八向 resize、记忆尺寸位置、展开/移侧;用户主动「固定为侧栏」才双栏),不挤占订单网格;Ctrl/Cmd+滚轮与适合宽度/页面;溢出拖拽平移;双击字段定位与证据联动高亮;异常字段 Alt+[/] 导航;真正按需加载;Chat/证据/pdfjs 异步分包;AI/版本历史/完整检查按需抽屉且审计失败阻断展示;确认与自动推进态解耦并可重试;同事务入队 `shipping_notice_run`;单一主滚动 + sticky 底栏。真机三档 viewport 清单见 layout-plan §11.1。权威方案:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md)。 | | **复核工作台布局重构(阶段 0–5)** | 已实现(待真机视觉签署) | 替换旧三栏:主编辑区 + 阻断摘要侧栏;PDF **默认右下角浮动证据面板**(八向 resize、记忆尺寸位置、展开/移侧;用户主动「固定为侧栏」才双栏),不挤占订单网格;Ctrl/Cmd+滚轮与适合宽度/页面;溢出拖拽平移;双击字段定位与证据联动高亮;异常字段 Alt+[/] 导航;真正按需加载;Chat/证据/pdfjs 异步分包;AI/版本历史/完整检查按需抽屉且审计失败阻断展示;确认与自动推进态解耦并可重试;同事务入队 `shipping_notice_run`;单一主滚动 + sticky 底栏。真机三档 viewport 清单见 layout-plan §11.1。权威方案:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md)。 |
| **复核工作台状态隔离(Case/证据/资格/自动化)** | 进行中(正式 OT 后分层已落地) | Case 切换请求代次 + 瞬态清理;正式 OT 后右侧主卡切自动处理、订单检查折叠、系统等待不冒充人工待办;`profile_match` 四态 + `field_completeness`;`completed_checks` 后端投影;`automation.phase` 区分建单前/后文案。契约:[review-workbench-state-isolation-contract.md](features/shipping-notice/review-workbench-state-isolation-contract.md)。 | | **复核工作台状态隔离(Case/证据/资格/自动化)** | 进行中(正式 OT 后分层已落地) | Case 切换请求代次 + 瞬态清理;正式 OT 后右侧主卡切自动处理、订单检查折叠、系统等待不冒充人工待办;`profile_match` 四态 + `field_completeness`;`completed_checks` 后端投影;`automation.phase` 区分建单前/后文案。契约:[review-workbench-state-isolation-contract.md](features/shipping-notice/review-workbench-state-isolation-contract.md)。 |
@@ -294,7 +294,7 @@ export function useScheduleAdminRuns(
const a = document.createElement('a'); const a = document.createElement('a');
a.href = url; a.href = url;
const disposition = res.headers.get('content-disposition'); const disposition = res.headers.get('content-disposition');
a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'inventory-rpa-raw.zip'; a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || '库存RPA-库存.zip';
document.body.appendChild(a); document.body.appendChild(a);
a.click(); a.click();
document.body.removeChild(a); document.body.removeChild(a);
@@ -1115,6 +1115,19 @@ const nextOrderFieldSequence = (targetPageNo: number): number => {
const beginFormEdit = () => { const beginFormEdit = () => {
pendingFormEdit = snapshot(); pendingFormEdit = snapshot();
}; };
/**
* 将选中物理行标记为主明细或 LN 补料号补充表(如 COO)。
* 核心逻辑:写入 tableRegionRole 后走同一 finishFormEdit,保存时按角色拆成两个 table_regions。
*/
const onSelectedLineTableRegionRoleChange = (event: Event): void => {
const target = selectedRegion.value;
if (!target || target.kind !== 'line') return;
const value = (event.target as HTMLSelectElement).value;
target.tableRegionRole = value === 'line_field_supplement'
? 'line_field_supplement'
: 'business_lines';
finishFormEdit();
};
/** /**
* 记录字段改绑前的共同视觉身份。 * 记录字段改绑前的共同视觉身份。
* *
@@ -1549,12 +1562,51 @@ const definition = () => {
.map((item) => item.pageNo), .map((item) => item.pageNo),
)] )]
.sort((left, right) => left - right) .sort((left, right) => left - right)
.map((regionPageNo) => { .flatMap((regionPageNo) => {
const regionSettings = ensureTableRegionSetting(regionPageNo); const regionSettings = ensureTableRegionSetting(regionPageNo);
const pageItems = normalizedRegions.filter( const pageItems = normalizedRegions.filter(
(item) => item.pageNo === regionPageNo, (item) => item.pageNo === regionPageNo,
); );
const lineRegions = pageItems.filter((item) => item.kind === "line"); const roles: Array<'business_lines' | 'line_field_supplement'> = [
'business_lines',
'line_field_supplement',
];
return roles.flatMap((regionRole) => {
const lineRegions = pageItems.filter(
(item) =>
item.kind === "line"
&& (item.tableRegionRole || 'business_lines') === regionRole,
);
const supplementLineRegions = pageItems.filter(
(item) =>
item.kind === "line"
&& (item.tableRegionRole || 'business_lines') === 'line_field_supplement',
);
/** 表头中心点是否落在补充表明细行并集内(含少量纵向余量)。 */
const headerOverlapsSupplement = (header: typeof pageItems[number]): boolean => {
if (!supplementLineRegions.length) return false;
const cy = (header.region.y0 + header.region.y1) / 2;
const cx = (header.region.x0 + header.region.x1) / 2;
return supplementLineRegions.some((line) => {
const pad = Math.max(0.01, (line.region.y1 - line.region.y0) * 0.5);
return (
cx >= line.region.x0
&& cx <= line.region.x1
&& cy >= line.region.y0 - pad
&& cy <= line.region.y1 + pad
);
});
};
// 表头只挂在业务明细区;补充表(COO)不携带 header_layouts。
// 落在补充行附近的表头不得并入 business,否则会污染版面签名 header_tokens。
const pageHeaderItems = regionRole === 'business_lines'
? pageItems.filter(
(item) => item.kind === "header_field" && !headerOverlapsSupplement(item),
)
: [];
if (!lineRegions.length && !pageHeaderItems.length) {
return [];
}
const groupedLineFields = groupUniqueOrderProfileLineFields( const groupedLineFields = groupUniqueOrderProfileLineFields(
pageItems, pageItems,
lineRegions.map((item) => item.id), lineRegions.map((item) => item.id),
@@ -1579,14 +1631,14 @@ const definition = () => {
lineFields.value.map((field) => field.field_code), lineFields.value.map((field) => field.field_code),
); );
}; };
const headerLayouts = pageItems const headerLayouts = pageHeaderItems
.filter((item) => item.kind === "header_field" && item.parentId) .filter((item) => item.parentId)
.reduce<string[]>((layoutIds, item) => { .reduce<string[]>((layoutIds, item) => {
if (!layoutIds.includes(item.parentId!)) layoutIds.push(item.parentId!); if (!layoutIds.includes(item.parentId!)) layoutIds.push(item.parentId!);
return layoutIds; return layoutIds;
}, []) }, [])
.map((layoutId) => { .map((layoutId) => {
const fields = pageItems.filter( const fields = pageHeaderItems.filter(
(item) => (item) =>
item.kind === "header_field" && item.parentId === layoutId, item.kind === "header_field" && item.parentId === layoutId,
); );
@@ -1608,7 +1660,7 @@ const definition = () => {
}); });
const layoutRegions = [ const layoutRegions = [
...lineRegions, ...lineRegions,
...pageItems.filter((item) => item.kind === "header_field"), ...pageHeaderItems,
]; ];
const tableRegion = layoutRegions.length const tableRegion = layoutRegions.length
? { ? {
@@ -1624,12 +1676,15 @@ const definition = () => {
? fieldRegionsFor(firstLineRegion.id).map((item) => item.field_code) ? fieldRegionsFor(firstLineRegion.id).map((item) => item.field_code)
: [], : [],
); );
return { return [{
region_id: `main_lines_page_${regionPageNo}`, region_id: regionRole === 'line_field_supplement'
? `line_supplement_page_${regionPageNo}`
: `main_lines_page_${regionPageNo}`,
// 仅为旧 schema 提供兼容形状;运行时会自动选择适用页范围。 // 仅为旧 schema 提供兼容形状;运行时会自动选择适用页范围。
page_scope: 'exact_page' as const, page_scope: 'exact_page' as const,
page_no: regionPageNo, page_no: regionPageNo,
region: tableRegion, region: tableRegion,
region_role: regionRole,
line_start_field_code: resolveLineStartFieldCode(mainLineFieldCodes), line_start_field_code: resolveLineStartFieldCode(mainLineFieldCodes),
// 仅为旧 schema 提供兼容形状;运行时固定/自适应策略并行评估。 // 仅为旧 schema 提供兼容形状;运行时固定/自适应策略并行评估。
row_reconstruction_mode: 'fixed_subrows' as const, row_reconstruction_mode: 'fixed_subrows' as const,
@@ -1661,6 +1716,7 @@ const definition = () => {
(item) => (item) =>
(item.kind === "field" || item.kind === "header_field") && (item.kind === "field" || item.kind === "header_field") &&
item.parentId && item.parentId &&
lineRegions.some((line) => line.id === item.parentId) &&
(!item.fieldCode || (!item.fieldCode ||
(item.kind === "header_field" && !coordinateFieldScope(item.fieldCode)) || (item.kind === "header_field" && !coordinateFieldScope(item.fieldCode)) ||
(item.kind === "field" && !boundLineFieldRegionIds.has(item.id))), (item.kind === "field" && !boundLineFieldRegionIds.has(item.id))),
@@ -1671,7 +1727,8 @@ const definition = () => {
label: item.label, label: item.label,
region: item.region, region: item.region,
})), })),
}; }];
});
}); });
const visualDefinition: OrderCoordinateProfileDefinition = { const visualDefinition: OrderCoordinateProfileDefinition = {
// 主表身份由创建向导冻结;编辑器保存时随定义原样携带,不能退化为只存 sample.table_id。 // 主表身份由创建向导冻结;编辑器保存时随定义原样携带,不能退化为只存 sample.table_id。
@@ -2727,6 +2784,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
label: item.layout_id, label: item.layout_id,
region: item.region, region: item.region,
pageNo: regionPageNo, pageNo: regionPageNo,
tableRegionRole: table.region_role || 'business_lines',
})), })),
...table.line_layouts.flatMap((line) => ...table.line_layouts.flatMap((line) =>
line.field_regions.map((item, index) => ({ line.field_regions.map((item, index) => ({
@@ -3443,6 +3501,20 @@ onBeforeUnmount(() => {
{{ line.label }} {{ line.label }}
</option> </option>
</select></label </select></label
><label v-if="selectedRegion.kind === 'line'"
>{{ t('admin.shippingOrderProfiles.workbench.tableRegionRole')
}}<select
:value="selectedRegion.tableRegionRole || 'business_lines'"
class="select-field"
:disabled="compactEditor || saveState === 'readonly'"
@focus="beginFormEdit"
@change="onSelectedLineTableRegionRoleChange"
>
<option value="business_lines">{{ t('admin.shippingOrderProfiles.workbench.tableRegionRoles.business_lines') }}</option>
<option value="line_field_supplement">{{ t('admin.shippingOrderProfiles.workbench.tableRegionRoles.line_field_supplement') }}</option>
</select>
<small>{{ t('admin.shippingOrderProfiles.workbench.tableRegionRoleHint') }}</small>
</label
><label v-if="['header_field', 'field', 'order_field'].includes(selectedRegion.kind)" ><label v-if="['header_field', 'field', 'order_field'].includes(selectedRegion.kind)"
>{{ t("admin.shippingOrderProfiles.workbench.schemaField") >{{ t("admin.shippingOrderProfiles.workbench.schemaField")
}}<select }}<select
@@ -11,6 +11,8 @@ export type OrderProfileExtractorKey = 'direct' | 'temp_internal_parts' | 'quant
export type OrderProfileEvidenceLevel = 'coordinate' | 'ocr_coordinate'; export type OrderProfileEvidenceLevel = 'coordinate' | 'ocr_coordinate';
export type OrderProfileAllowedSource = 'pdf_coordinate' | 'ocr_coordinate'; export type OrderProfileAllowedSource = 'pdf_coordinate' | 'ocr_coordinate';
export type OrderProfileRowReconstructionMode = 'fixed_subrows' | 'adaptive_record_columns'; export type OrderProfileRowReconstructionMode = 'fixed_subrows' | 'adaptive_record_columns';
/** 主明细命中源 vs 同文档按 LN 补料号的补充表(如 COO)。 */
export type OrderProfileTableRegionRole = 'business_lines' | 'line_field_supplement';
export type OrderProfileChangeSource = 'wizard_created' | 'manual_save' | 'autosave' | 'restore' | 'sample_changed'; export type OrderProfileChangeSource = 'wizard_created' | 'manual_save' | 'autosave' | 'restore' | 'sample_changed';
export type OrderProfileLeaseState = 'active' | 'expired' | 'released' | 'taken_over'; export type OrderProfileLeaseState = 'active' | 'expired' | 'released' | 'taken_over';
export type OrderProfileValidationRunType = 'instant_check' | 'current_sample' | 'blind_test' | 'scenario_coverage' | 'schema_compatibility' | 'layout_signature' | 'cross_template_overlap' | 'xfa_structure_signature'; export type OrderProfileValidationRunType = 'instant_check' | 'current_sample' | 'blind_test' | 'scenario_coverage' | 'schema_compatibility' | 'layout_signature' | 'cross_template_overlap' | 'xfa_structure_signature';
@@ -72,7 +74,26 @@ export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: str
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; } export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
export interface OrderProfileHeaderLayout { layout_id: string; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; } export interface OrderProfileHeaderLayout { layout_id: string; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; }
export interface OrderProfileLineLayout { layout_id: string; row_offset: number; role: 'main' | 'continuation'; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; new_line_anchor?: OrderProfileAnchorRule | null; continuation_conditions: OrderProfileAnchorRule[]; required_fields: string[]; allowed_empty_fields: string[]; } export interface OrderProfileLineLayout { layout_id: string; row_offset: number; role: 'main' | 'continuation'; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; new_line_anchor?: OrderProfileAnchorRule | null; continuation_conditions: OrderProfileAnchorRule[]; required_fields: string[]; allowed_empty_fields: string[]; }
export interface OrderProfileTableRegion { region_id: string; page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page'; page_no?: number | null; region: OrderProfileRelativeRegion; /** 逻辑明细起行锚点;默认 customer_po_line_no;line_no 为可识别内部项次亦可绑定。 */ line_start_field_code?: string; /** 默认固定子行;仅显式启用时允许在同一逻辑明细内跨视觉行按列重建。 */ row_reconstruction_mode?: OrderProfileRowReconstructionMode; /** 管理员确认的视觉行结构来源;审计用途,不是字段正式值源。 */ visual_evidence_source?: 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry' | null; header_layouts: OrderProfileHeaderLayout[]; line_layouts: OrderProfileLineLayout[]; continuation_rule: { allow_cross_page: boolean; required_anchor_ids: string[] }; termination_rules: Array<{ rule_id: string; anchor: OrderProfileAnchorRule }>; exclusion_regions: OrderProfileRelativeRegion[]; draft_unbound_field_regions?: Array<{ region_id: string; parent_layout_id: string; label: string; region: OrderProfileRelativeRegion }>; } export interface OrderProfileTableRegion {
region_id: string;
page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page';
page_no?: number | null;
region: OrderProfileRelativeRegion;
/** 主明细命中源(默认)或同文档 LN 补料号补充表。 */
region_role?: OrderProfileTableRegionRole;
/** 逻辑明细起行锚点;默认 customer_po_line_no;line_no 为可识别内部项次亦可绑定。 */
line_start_field_code?: string;
/** 默认固定子行;仅显式启用时允许在同一逻辑明细内跨视觉行按列重建。 */
row_reconstruction_mode?: OrderProfileRowReconstructionMode;
/** 管理员确认的视觉行结构来源;审计用途,不是字段正式值源。 */
visual_evidence_source?: 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry' | null;
header_layouts: OrderProfileHeaderLayout[];
line_layouts: OrderProfileLineLayout[];
continuation_rule: { allow_cross_page: boolean; required_anchor_ids: string[] };
termination_rules: Array<{ rule_id: string; anchor: OrderProfileAnchorRule }>;
exclusion_regions: OrderProfileRelativeRegion[];
draft_unbound_field_regions?: Array<{ region_id: string; parent_layout_id: string; label: string; region: OrderProfileRelativeRegion }>;
}
export interface OrderProfileDocumentMatch { document_type: 'purchase_order'; page_pattern: 'one_or_more'; required_anchors: OrderProfileDocumentMatchAnchor[]; optional_anchors: OrderProfileDocumentMatchAnchor[]; minimum_score: number; minimum_margin: number; } export interface OrderProfileDocumentMatch { document_type: 'purchase_order'; page_pattern: 'one_or_more'; required_anchors: OrderProfileDocumentMatchAnchor[]; optional_anchors: OrderProfileDocumentMatchAnchor[]; minimum_score: number; minimum_margin: number; }
/** /**
@@ -968,6 +989,8 @@ export interface OrderProfileCanvasRegion {
stopAnchorText?: string | null; stopAnchorText?: string | null;
/** 标记所属文档页;画布切页时仅渲染当前页的区域。 */ /** 标记所属文档页;画布切页时仅渲染当前页的区域。 */
pageNo: number; pageNo: number;
/** 物理行所属表区角色;补充表(如 COO)保存为 line_field_supplement。 */
tableRegionRole?: OrderProfileTableRegionRole;
/** datasets adapter 可附加的视觉证据确认状态,不影响共同画布区域种类。 */ /** datasets adapter 可附加的视觉证据确认状态,不影响共同画布区域种类。 */
visualBindingStatus?: XfaVisualBindingStatus; visualBindingStatus?: XfaVisualBindingStatus;
/** 工作台待确认候选的临时视觉标记;不会进入 Profile 保存 payload。 */ /** 工作台待确认候选的临时视觉标记;不会进入 Profile 保存 payload。 */
@@ -18,7 +18,9 @@ const i18n = createI18n({
title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板', title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板',
expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板', expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板',
routeType: '路由类型', executionMode: '执行模式', routeType: '路由类型', executionMode: '执行模式',
extractionBlocked: '模板已命中,但字段提取仍被安全门禁阻断', extractionBlockedReason: '阻断原因:{reasons}', extractionBlocked: '模板已命中,但字段提取仍被安全门禁阻断',
extractionBlockedNoMatch: '模板未唯一命中,字段提取被阻断',
extractionBlockedReason: '阻断原因:{reasons}',
coordinateModel: { coordinateModel: {
anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移', anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移',
translateY: '纵向平移', reasonCodes: '原因码', translateY: '纵向平移', reasonCodes: '原因码',
@@ -122,6 +124,30 @@ describe('ReviewProfileMatchPanel', () => {
// 关键断言:唯一模板命中不等于字段已提取,必须明确暴露下游阻断原因。 // 关键断言:唯一模板命中不等于字段已提取,必须明确暴露下游阻断原因。
expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text()) expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text())
.toContain('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS'); .toContain('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS');
expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text())
.toContain('模板已命中');
});
it('未选定模板时阻断文案不得再写模板已命中', () => {
const wrapper = mount(ReviewProfileMatchPanel, {
props: {
profileMatch: {
available: true,
visibility: 'admin',
status: 'evidence_insufficient',
needs_review: true,
selected_profile: null,
candidates: [],
fallback_reason_codes: ['coordinate_evidence_unavailable'],
},
},
global: { plugins: [i18n] },
});
const blocked = wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text();
expect(blocked).toContain('模板未唯一命中');
expect(blocked).not.toContain('模板已命中');
expect(blocked).toContain('coordinate_evidence_unavailable');
}); });
it('管理员技术详情展示锚点框架平移和稳定原因码,不展示原始正文或完整坐标', async () => { it('管理员技术详情展示锚点框架平移和稳定原因码,不展示原始正文或完整坐标', async () => {
@@ -43,10 +43,20 @@ const selectedCoordinateTransform = computed(() => {
const coordinateTransformReasonCodes = computed(() => ( const coordinateTransformReasonCodes = computed(() => (
selectedCoordinateTransform.value?.reason_codes || [] selectedCoordinateTransform.value?.reason_codes || []
)); ));
/** 唯一命中仅证明版式身份;下游字段/明细恢复若受门禁阻断,必须在同卡明确说明。 */ /** 唯一命中仅证明版式身份;下游字段/明细恢复若受门禁阻断,必须在同卡明确说明。
* 未选定模板时不得再写「模板已命中」,避免与上方「未选定模板」矛盾。 */
const extractionBlockReasons = computed(() => ( const extractionBlockReasons = computed(() => (
(props.profileMatch?.fallback_reason_codes || []).filter((code) => String(code).trim()) (props.profileMatch?.fallback_reason_codes || []).filter((code) => String(code).trim())
)); ));
const hasSelectedProfile = computed(() => Boolean(
String(props.profileMatch?.selected_profile?.profile_code || '').trim()
|| String(props.profileMatch?.selected_profile?.display_name || '').trim(),
));
const extractionBlockedTitle = computed(() => (
hasSelectedProfile.value
? t('chat.shippingOrderReview.profileMatch.extractionBlocked')
: t('chat.shippingOrderReview.profileMatch.extractionBlockedNoMatch')
));
watch( watch(
() => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`, () => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`,
@@ -117,7 +127,7 @@ const selectedLabel = computed(() => {
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100" class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-profile-match-extraction-blocked" data-testid="review-profile-match-extraction-blocked"
> >
<p class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.extractionBlocked') }}</p> <p class="font-medium">{{ extractionBlockedTitle }}</p>
<p class="mt-1 text-amber-800 dark:text-amber-200"> <p class="mt-1 text-amber-800 dark:text-amber-200">
{{ t('chat.shippingOrderReview.profileMatch.extractionBlockedReason', { reasons: extractionBlockReasons.join(', ') }) }} {{ t('chat.shippingOrderReview.profileMatch.extractionBlockedReason', { reasons: extractionBlockReasons.join(', ') }) }}
</p> </p>
+6
View File
@@ -3699,6 +3699,12 @@
"noIssues": "No blocking configuration issue.", "noIssues": "No blocking configuration issue.",
"currentConfiguration": "Current configuration", "currentConfiguration": "Current configuration",
"tableRegionSettings": "Line table settings", "tableRegionSettings": "Line table settings",
"tableRegionRole": "Table region role",
"tableRegionRoles": {
"business_lines": "Business line table (primary)",
"line_field_supplement": "Line-field supplement (e.g. COO, fill part numbers by LN)"
},
"tableRegionRoleHint": "Supplement tables must bind line number plus part fields; they are not business-line hits. Formal parse, blind test, and validation merge by LN.",
"coordinateModelTitle": "Coordinate value model", "coordinateModelTitle": "Coordinate value model",
"coordinateModelHint": "Legacy frozen absolute coordinates are used by default. Enable this only for bounded translation with stable static anchors.", "coordinateModelHint": "Legacy frozen absolute coordinates are used by default. Enable this only for bounded translation with stable static anchors.",
"coordinateModelType": "Coordinate model", "coordinateModelType": "Coordinate model",
+1
View File
@@ -2462,6 +2462,7 @@
"routeType": "Route type", "routeType": "Route type",
"executionMode": "Execution mode", "executionMode": "Execution mode",
"extractionBlocked": "The template matched, but a safety gate still blocked field extraction", "extractionBlocked": "The template matched, but a safety gate still blocked field extraction",
"extractionBlockedNoMatch": "No unique template match; field extraction was blocked",
"extractionBlockedReason": "Blocking reason: {reasons}", "extractionBlockedReason": "Blocking reason: {reasons}",
"score": "Score {score}", "score": "Score {score}",
"reselectHint": "If the template is wrong or the layout drifted, use “Reparse this PDF” at the top. Gate re-route is on the recovery card below.", "reselectHint": "If the template is wrong or the layout drifted, use “Reparse this PDF” at the top. Gate re-route is on the recovery card below.",
+6
View File
@@ -3568,6 +3568,12 @@
"noIssues": "ไม่มีปัญหาการตั้งค่าที่ขัดขวาง", "noIssues": "ไม่มีปัญหาการตั้งค่าที่ขัดขวาง",
"currentConfiguration": "การตั้งค่าปัจจุบัน", "currentConfiguration": "การตั้งค่าปัจจุบัน",
"tableRegionSettings": "การตั้งค่าตารางรายละเอียด", "tableRegionSettings": "การตั้งค่าตารางรายละเอียด",
"tableRegionRole": "บทบาทของตาราง",
"tableRegionRoles": {
"business_lines": "ตารางรายละเอียดธุรกิจ (หลัก)",
"line_field_supplement": "ตารางเสริมฟิลด์รายการ (เช่น COO เติมเลขชิ้นส่วนตาม LN)"
},
"tableRegionRoleHint": "ตารางเสริมต้องผูกเลขบรรทัดและฟิลด์เลขชิ้นส่วน ไม่ใช่แหล่ง hit รายละเอียดหลัก การ parse / ทดสอบตาบอด / ตรวจยืนยัน จะรวมตาม LN",
"coordinateModelTitle": "โมเดลค่าพิกัด", "coordinateModelTitle": "โมเดลค่าพิกัด",
"coordinateModelHint": "ค่าเริ่มต้นใช้พิกัดสัมบูรณ์ที่แช่แข็ง เปิดใช้งานเฉพาะเมื่อมีการเลื่อนที่จำกัดและจุดยึดคงที่เท่านั้น", "coordinateModelHint": "ค่าเริ่มต้นใช้พิกัดสัมบูรณ์ที่แช่แข็ง เปิดใช้งานเฉพาะเมื่อมีการเลื่อนที่จำกัดและจุดยึดคงที่เท่านั้น",
"coordinateModelType": "โมเดลพิกัด", "coordinateModelType": "โมเดลพิกัด",
+1
View File
@@ -2462,6 +2462,7 @@
"routeType": "ประเภทเส้นทาง", "routeType": "ประเภทเส้นทาง",
"executionMode": "โหมดการทำงาน", "executionMode": "โหมดการทำงาน",
"extractionBlocked": "พบเทมเพลตแล้ว แต่การดึงข้อมูลฟิลด์ยังถูกบล็อกโดยเกตความปลอดภัย", "extractionBlocked": "พบเทมเพลตแล้ว แต่การดึงข้อมูลฟิลด์ยังถูกบล็อกโดยเกตความปลอดภัย",
"extractionBlockedNoMatch": "ยังไม่จับคู่เทมเพลตแบบเฉพาะเจาะจง การดึงข้อมูลฟิลด์ถูกบล็อก",
"extractionBlockedReason": "สาเหตุที่บล็อก: {reasons}", "extractionBlockedReason": "สาเหตุที่บล็อก: {reasons}",
"score": "คะแนน {score}", "score": "คะแนน {score}",
"reselectHint": "หากเทมเพลตผิดหรือเลย์เอาต์เพี้ยน ใช้ “ระบุ PDF นี้อีกครั้ง” ด้านบน การเปลี่ยนเส้นทางเกตอยู่ในการ์ดกู้คืนด้านล่าง", "reselectHint": "หากเทมเพลตผิดหรือเลย์เอาต์เพี้ยน ใช้ “ระบุ PDF นี้อีกครั้ง” ด้านบน การเปลี่ยนเส้นทางเกตอยู่ในการ์ดกู้คืนด้านล่าง",
+6
View File
@@ -3811,6 +3811,12 @@
"noIssues": "没有阻断配置问题。", "noIssues": "没有阻断配置问题。",
"currentConfiguration": "当前配置", "currentConfiguration": "当前配置",
"tableRegionSettings": "明细表区设置", "tableRegionSettings": "明细表区设置",
"tableRegionRole": "表区角色",
"tableRegionRoles": {
"business_lines": "业务明细表(主表)",
"line_field_supplement": "明细字段补充表(如 COO,按 LN 补料号)"
},
"tableRegionRoleHint": "补充表须绑定行号与待补料号字段,不参与主表明细命中;正式/盲测/验证按 LN 合并。",
"coordinateModelTitle": "坐标取值模型", "coordinateModelTitle": "坐标取值模型",
"coordinateModelHint": "默认使用冻结绝对坐标;仅在版式存在受限平移且有稳定静态锚点时启用。", "coordinateModelHint": "默认使用冻结绝对坐标;仅在版式存在受限平移且有稳定静态锚点时启用。",
"coordinateModelType": "坐标模型", "coordinateModelType": "坐标模型",
+1
View File
@@ -2581,6 +2581,7 @@
"routeType": "路由类型", "routeType": "路由类型",
"executionMode": "执行模式", "executionMode": "执行模式",
"extractionBlocked": "模板已命中,但字段提取仍被安全门禁阻断", "extractionBlocked": "模板已命中,但字段提取仍被安全门禁阻断",
"extractionBlockedNoMatch": "模板未唯一命中,字段提取被阻断",
"extractionBlockedReason": "阻断原因:{reasons}", "extractionBlockedReason": "阻断原因:{reasons}",
"score": "得分 {score}", "score": "得分 {score}",
"reselectHint": "若模板不对或版面漂移,请使用顶部「重新识别此 PDF」;门禁重路由见下方恢复卡片。", "reselectHint": "若模板不对或版面漂移,请使用顶部「重新识别此 PDF」;门禁重路由见下方恢复卡片。",
+6
View File
@@ -3573,6 +3573,12 @@
"noIssues": "沒有阻斷設定問題。", "noIssues": "沒有阻斷設定問題。",
"currentConfiguration": "目前設定", "currentConfiguration": "目前設定",
"tableRegionSettings": "明細表區設定", "tableRegionSettings": "明細表區設定",
"tableRegionRole": "表區角色",
"tableRegionRoles": {
"business_lines": "業務明細表(主表)",
"line_field_supplement": "明細欄位補充表(如 COO,依 LN 補料號)"
},
"tableRegionRoleHint": "補充表須綁定行號與待補料號欄位,不參與主表明細命中;正式/盲測/驗證依 LN 合併。",
"coordinateModelTitle": "座標取值模型", "coordinateModelTitle": "座標取值模型",
"coordinateModelHint": "預設使用凍結絕對座標;僅在版式存在受限平移且有穩定靜態錨點時啟用。", "coordinateModelHint": "預設使用凍結絕對座標;僅在版式存在受限平移且有穩定靜態錨點時啟用。",
"coordinateModelType": "座標模型", "coordinateModelType": "座標模型",
+1
View File
@@ -2462,6 +2462,7 @@
"routeType": "路由類型", "routeType": "路由類型",
"executionMode": "執行模式", "executionMode": "執行模式",
"extractionBlocked": "範本已命中,但欄位擷取仍被安全閘門阻擋", "extractionBlocked": "範本已命中,但欄位擷取仍被安全閘門阻擋",
"extractionBlockedNoMatch": "範本未唯一命中,欄位擷取被阻擋",
"extractionBlockedReason": "阻擋原因:{reasons}", "extractionBlockedReason": "阻擋原因:{reasons}",
"score": "得分 {score}", "score": "得分 {score}",
"reselectHint": "若範本不對或版面漂移,請使用頂部「重新識別此 PDF」;門禁重路由見下方恢復卡片。", "reselectHint": "若範本不對或版面漂移,請使用頂部「重新識別此 PDF」;門禁重路由見下方恢復卡片。",
+9 -4
View File
@@ -844,7 +844,10 @@ python -m pip install playwright openpyxl pyyaml
python -m playwright install chromium python -m playwright install chromium
``` ```
若 Worker 复用项目完整依赖,也可执行 `python -m pip install -r <项目仓库>\backend\requirements.txt playwright`。使用本机 Edge 时设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`。 若 Worker 复用项目完整依赖,也可执行 `python -m pip install -r <项目仓库>\backend\requirements.txt playwright`。
**默认使用 Playwright 捆绑 Chromium**(`python -m playwright install chromium`)。
勿默认设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`:Edge 152 + 持久 Profile
在 Excel 下载时会原生崩溃(`Download.save_as: TargetClosed` / 残留 `.crdownload`)。
### 1.5 Windows RPA 临时变量、登录测试与心跳 ### 1.5 Windows RPA 临时变量、登录测试与心跳
@@ -859,7 +862,7 @@ $env:SHIPPING_NOTICE_TOOL_API_KEY = "请替换为测试环境Key"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" $env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge" # 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。
$env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" $env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
$env:SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20" $env:SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20"
$env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "test" $env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "test"
@@ -1095,7 +1098,9 @@ python -m pip install playwright
python -m playwright install chromium python -m playwright install chromium
``` ```
如使用本机 Edge,可设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`,无需让 Worker 下载 Chromium;仍建议保留 Playwright Python 包。 **默认使用 Playwright 捆绑 Chromium**(上一步 `playwright install chromium`)。
勿设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`:Edge 152 + 持久 Profile
下载会原生崩溃(`TargetClosed` / `.crdownload`)。
#### 3. 配置当前 PowerShell 会话并启动 Worker #### 3. 配置当前 PowerShell 会话并启动 Worker
@@ -1114,7 +1119,7 @@ $env:SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = "<本地 RPA 凭据主密钥>"
$env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "dev" $env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "dev"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" $env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge" # 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。
$env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" $env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers" $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers"
@@ -37,8 +37,7 @@ def main() -> int:
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile", "backend/data/shipping_notice/freight_rpa/browser_profile",
) )
if not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") and not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH"): # 不默认 msedge:未设置 CHANNEL 时走 Playwright 捆绑 Chromium(需先 playwright install chromium)。
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
worker = _load_worker() worker = _load_worker()
username = worker._env("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME") username = worker._env("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME")
@@ -37,9 +37,7 @@ def main() -> int:
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile", "backend/data/shipping_notice/freight_rpa/browser_profile",
) )
# Playwright 自带 Chromium 未安装时,回退到本机 Edge(Windows 开发机常见情况)。 # 不默认 msedge:未设置 CHANNEL 时走 Playwright 捆绑 Chromium(需先 playwright install chromium)。
if not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") and not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
worker = _load_worker() worker = _load_worker()
username = worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") username = worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME")
+26 -7
View File
@@ -22,7 +22,8 @@ Optional:
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE=true SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE=true
# legacy alias: SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE # legacy alias: SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE
SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge # 默认不设 CHANNEL → Playwright 捆绑 Chromium;禁止默认 msedge(Edge 152 持久 Profile 下载崩溃)。
# SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge # 不推荐
SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log SHIPPING_NOTICE_RPA_WORKER_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log
SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES=10485760 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES=10485760
@@ -1475,6 +1476,18 @@ def _emit_batch_progress(body: dict[str, Any], run_no: str, results: list[dict[s
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None: def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
"""
消费 inventory_export_batch trigger:按 Profile 分组导出并回调后端。
核心逻辑:先按 trigger_type 做身份门禁——scheduled / configuration_test(_batch)
只校验信封字段;按需单票保持逐源 Attempt/Gate fail-closed。导出后按类型路由到
inventory-batch-ready 或 inventory-configuration-test(-batch)-ready。
Args:
trigger_path: 待处理的 batch trigger JSON 路径。
drop_dir: 下载落盘目录。
processed_dir: 成功处理后的 trigger 归档目录。
"""
body = json.loads(trigger_path.read_text(encoding="utf-8")) body = json.loads(trigger_path.read_text(encoding="utf-8"))
run_no = str(body.get("batch_run_no") or body.get("run_no") or trigger_path.stem).strip() run_no = str(body.get("batch_run_no") or body.get("run_no") or trigger_path.stem).strip()
task_no = str(body.get("task_no") or "").strip() task_no = str(body.get("task_no") or "").strip()
@@ -1491,17 +1504,23 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
identity_errors.append("schema_version") identity_errors.append("schema_version")
if body.get("callback_id") is None or (isinstance(body.get("callback_id"), str) and not body.get("callback_id").strip()): if body.get("callback_id") is None or (isinstance(body.get("callback_id"), str) and not body.get("callback_id").strip()):
identity_errors.append("callback_id") identity_errors.append("callback_id")
# 定时排程批量触发是按 run 计价的:只携带 run_no/schedule_run_id,没有逐源 # [STEP] 身份校验按 trigger_type 取值:
# Attempt/Gate 身份。身份校验按模式取值:scheduled 只强制信封与站点分发字段, # - scheduled:按 run 计价,仅 run_no/schedule_run_id,无逐源 Attempt/Gate。
# 业务终态由后端按 schedule_run_id + DB 配置校验;其余模式保持逐源身份 fail-closed。 # - configuration_test / configuration_test_batch:管理端停用站点连通性验证,
is_scheduled_batch = str(body.get("trigger_type") or "").strip() == "scheduled" # 不创建订单 Attempt/Gate,故意不写 task_no/source_run_no 等生产身份;
# 终态走 inventory-configuration-test(-batch)-ready,不得用生产身份 fail-closed。
# - 其余(按需单票/多源准备):保持逐源身份 fail-closed。
trigger_type = str(body.get("trigger_type") or "").strip()
is_run_scoped_batch = trigger_type in {
"scheduled", "configuration_test", "configuration_test_batch",
}
source_required = set(_INVENTORY_V2_REQUIRED_FIELDS) - {"schema_version", "task_no", "callback_id"} source_required = set(_INVENTORY_V2_REQUIRED_FIELDS) - {"schema_version", "task_no", "callback_id"}
if is_scheduled_batch: if is_run_scoped_batch:
source_required -= { source_required -= {
"task_no", "source_run_no", "attempt_no", "lease_token", "candidate_set_id", "task_no", "source_run_no", "attempt_no", "lease_token", "candidate_set_id",
"execution_id", "gate_id", "callback_id", "expected_warehouse_id", "execution_id", "gate_id", "callback_id", "expected_warehouse_id",
} }
if not is_scheduled_batch and ( if not is_run_scoped_batch and (
body.get("task_no") is None or (isinstance(body.get("task_no"), str) and not body.get("task_no").strip()) body.get("task_no") is None or (isinstance(body.get("task_no"), str) and not body.get("task_no").strip())
): ):
identity_errors.append("task_no") identity_errors.append("task_no")
@@ -55,8 +55,7 @@ def main() -> int:
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "true") os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "true")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "backend/data/shipping_notice/freight_rpa/browser_profile") os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "backend/data/shipping_notice/freight_rpa/browser_profile")
if not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") and not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH"): # 不默认 msedge:Edge 152 + 持久 Profile 下载会原生崩溃;未设置 CHANNEL 时走 Playwright Chromium。
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052") os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052")
if not os.environ.get("SHIPPING_NOTICE_TOOL_API_KEY"): if not os.environ.get("SHIPPING_NOTICE_TOOL_API_KEY"):
print("[batch-run] SHIPPING_NOTICE_TOOL_API_KEY is required") print("[batch-run] SHIPPING_NOTICE_TOOL_API_KEY is required")
@@ -84,7 +84,8 @@ $processVars = [ordered]@{
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" }) SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" }) SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" })
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE = $sessionReuse SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE = $sessionReuse
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge" # 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium。
# Edge 152 + 持久 Profile 下载会原生崩溃(TargetClosed / .crdownload),禁止默认 msedge。
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $dataRoot "inventory_triggers" SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $dataRoot "inventory_triggers"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $dataRoot "inventory_drop" SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $dataRoot "inventory_drop"
+1 -1
View File
@@ -40,7 +40,7 @@ $processVars = [ordered]@{
SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = $Environment SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = $Environment
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' }) SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' }) SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = 'msedge' # 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3' SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers' SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop' SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop'