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