- 客户主数据新增 odm_ids 白名单字段(含 Alembic 迁移),表单与管理端支持维护 - 导出库存命中行按客户白名单与整单 ODM 裁决收敛,新增 notice_odm_choice_service - 工作台新增 odm-options / odm-choice 接口,投影行级候选并持久化用户选择 - 修复复核工作台跨 Run 切换时接收解析上下文残留 - 同步四语言 i18n、测试用例、funclist 与 shipping-notice 技术文档
348 lines
14 KiB
Python
348 lines
14 KiB
Python
"""
|
||
Reservation ID 专用证据区域解析器。
|
||
|
||
用途:从已启用的 Vendor Comments→Terms 锚点窗提取 Reservation ID 与可选行号,
|
||
并投影到验证证据 / 订单归属契约。
|
||
依赖:reservation_id 格式校验、coordinate_region_text 视觉行序。
|
||
逻辑:reservation_id_region 仅作启用标记;画布预览、盲测、正式解析共用本模块的
|
||
锚点扫描与 apply/project,不再按保存矩形截取正式值;行号含 line# / L# / LN#。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from dataclasses import dataclass
|
||
from typing import Any
|
||
|
||
from app.services.shipping_notice.document_layout.coordinate_region_text import visual_text_lines
|
||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||
|
||
|
||
_ID_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)")
|
||
# 行号写法:Line 1 / line#1 / for line#1 / Hyve 缩写 L#1、LN#1。
|
||
_LINE_RE = re.compile(
|
||
r"(?:"
|
||
r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b"
|
||
r"|\bfor\s+line\s*#?\s*(\d+)\b"
|
||
r"|\bl(?:n)?\s*#\s*(\d+)\b"
|
||
r")",
|
||
re.I,
|
||
)
|
||
_RESERVATION_LABEL_RE = re.compile(r"\breservation\b\s*(?:id)?\s*(?:#|:|-)?", re.I)
|
||
_VENDOR_COMMENTS_HEADING_RE = re.compile(r'^\s*vendor\s+comments?\b', re.I)
|
||
_TERMS_AND_CONDITIONS_HEADING_RE = re.compile(
|
||
r'^\s*(?:\d+[\.\)]\s*)?terms?\s*(?:&|and)\s*conditions?\b',
|
||
re.I,
|
||
)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ReservationRegionCandidate:
|
||
value: str
|
||
line_no: int | None
|
||
scope: str
|
||
raw_text: str
|
||
status: str
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ReservationRegionApplication:
|
||
"""Reservation 区域候选的统一业务归属结果。"""
|
||
|
||
header_value: str | None
|
||
line_values: dict[int, str]
|
||
needs_review: bool
|
||
review_reasons: tuple[str, ...]
|
||
|
||
|
||
def extract_reservation_from_region(text: str) -> 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()
|
||
# A selected comments area can also contain customer numbers, quantities,
|
||
# and dates. Only a value on a Reservation-labelled line is evidence.
|
||
if not line or not _RESERVATION_LABEL_RE.search(line):
|
||
continue
|
||
ids = [validated_reservation_id(m.group(1)) for m in _ID_RE.finditer(line)]
|
||
ids = [value for value in ids if value]
|
||
if not ids:
|
||
continue
|
||
line_match = _LINE_RE.search(line)
|
||
line_no = None
|
||
if line_match:
|
||
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):
|
||
candidates.append(ReservationRegionCandidate(value, line_no, scope, line, status))
|
||
return candidates
|
||
|
||
|
||
def extract_reservation_from_region_text(text: str) -> list[dict[str, object]]:
|
||
"""返回 API/预览可直接序列化的统一候选 DTO。"""
|
||
return [
|
||
{
|
||
'value': item.value,
|
||
'line_no': item.line_no,
|
||
'scope': item.scope,
|
||
'raw_text': item.raw_text,
|
||
'status': item.status,
|
||
}
|
||
for item in extract_reservation_from_region(text)
|
||
]
|
||
|
||
|
||
def extract_reservation_from_vendor_comments_pages(
|
||
pages: list[tuple[int, list[dict[str, Any]]]],
|
||
) -> tuple[list[dict[str, object]], str | None]:
|
||
"""从跨页 Vendor Comments 区块提取 Reservation;仅首个 Terms 标题前的文字有效。
|
||
|
||
核心逻辑:Reservation 专区已启用时,页面坐标只是提供稳定阅读顺序,不能作为固定
|
||
页码或矩形取值依据。起止标题按行首短语匹配(允许「Terms and Conditions of …」等
|
||
加长标题);缺少起始锚点时不扫描;缺少结束锚点时仍返回已累计窗内候选,但附带稳
|
||
定原因,由调用方标 Review,禁止当成可自动建单封闭证据。
|
||
"""
|
||
started = False
|
||
window_lines: list[str] = []
|
||
for _page_no, glyphs in sorted(pages, key=lambda item: item[0]):
|
||
for line in visual_text_lines(glyphs):
|
||
if not started:
|
||
if _VENDOR_COMMENTS_HEADING_RE.match(line):
|
||
started = True
|
||
continue
|
||
if _TERMS_AND_CONDITIONS_HEADING_RE.match(line):
|
||
return extract_reservation_from_region_text('\n'.join(window_lines)), None
|
||
window_lines.append(line)
|
||
if not started:
|
||
return [], 'vendor_comments_anchor_missing'
|
||
# 结束锚点缺失:保留窗内候选供验证/盲测展示与人工复核,不能假装封闭成功。
|
||
return extract_reservation_from_region_text('\n'.join(window_lines)), 'terms_and_conditions_anchor_missing'
|
||
|
||
|
||
def reservation_region_candidates_from_layout(
|
||
*,
|
||
definition: dict[str, Any] | None,
|
||
layout: dict[str, Any] | None,
|
||
) -> dict[str, Any]:
|
||
"""仅当模板标注了 reservation_id_region 时,按 Vendor Comments→Terms 提取候选。
|
||
|
||
核心逻辑:page_no/region 只表示专区已启用,正式取值必须与画布预览、盲测、
|
||
正式解析共用同一锚点窗,禁止再按保存矩形截取。
|
||
|
||
Args:
|
||
definition: Profile definition;无 reservation_id_region 时不扫描。
|
||
layout: 含 coordinate_evidence.page_glyphs 的版面快照。
|
||
|
||
Returns:
|
||
``{'candidates': [...], 'reason': str | None}``;reason 非空表示锚点异常。
|
||
"""
|
||
raw = definition if isinstance(definition, dict) else {}
|
||
if not isinstance(raw.get('reservation_id_region'), dict):
|
||
return {'candidates': [], 'reason': None}
|
||
evidence = layout.get('coordinate_evidence') if isinstance(layout, dict) else None
|
||
evidence = evidence if isinstance(evidence, dict) else {}
|
||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||
pages = [
|
||
(int(page_no), glyphs)
|
||
for page_no, glyphs in page_glyphs.items()
|
||
if str(page_no).isdigit() and isinstance(glyphs, list)
|
||
]
|
||
candidates, reason = extract_reservation_from_vendor_comments_pages(pages)
|
||
return {'candidates': candidates, 'reason': reason}
|
||
|
||
|
||
def project_reservation_onto_validation_evidence(
|
||
evidence: dict[str, Any],
|
||
*,
|
||
candidates: list[dict[str, object]],
|
||
reason: str | None,
|
||
schema_fields: dict[str, dict[str, Any]],
|
||
) -> dict[str, Any]:
|
||
"""将专区候选投影到验证页共用的 header_fields / lines 证据 DTO。
|
||
|
||
核心逻辑:复用 apply_reservation_region_candidates 归属契约;锚点缺失或冲突时
|
||
写入 reservation_region_*,不臆造字段值。
|
||
|
||
Args:
|
||
evidence: 现有 validation_evidence。
|
||
candidates: 锚点窗候选。
|
||
reason: 锚点扫描失败原因;有值时强制 needs_review。
|
||
schema_fields: field_id → Schema 字段(须含 enabled reservation_id)。
|
||
|
||
Returns:
|
||
新的 evidence 字典;未启用专区字段时仅透传或附加 review 元数据。
|
||
"""
|
||
projected = {
|
||
'header_fields': [
|
||
dict(item) for item in (evidence.get('header_fields') or []) if isinstance(item, dict)
|
||
],
|
||
'lines': [
|
||
{
|
||
'row_index': int(line.get('row_index') or index),
|
||
'fields': [
|
||
dict(field) for field in (line.get('fields') or []) if isinstance(field, dict)
|
||
],
|
||
}
|
||
for index, line in enumerate(evidence.get('lines') or [])
|
||
if isinstance(line, dict)
|
||
],
|
||
'cross_checks': dict(evidence.get('cross_checks') or {}),
|
||
}
|
||
reservation_scope = {
|
||
str(item.get('scope') or ''): item
|
||
for item in schema_fields.values()
|
||
if isinstance(item, dict) and str(item.get('field_code') or '') == 'reservation_id'
|
||
}
|
||
if reason:
|
||
projected['reservation_region_status'] = 'needs_review'
|
||
projected['reservation_region_review_reasons'] = [str(reason)]
|
||
if not candidates and not reason:
|
||
return projected
|
||
|
||
applied = apply_reservation_region_candidates(
|
||
candidates=candidates,
|
||
header_field_id=str((reservation_scope.get('header') or {}).get('field_id') or '') or None,
|
||
line_field_id=str((reservation_scope.get('line') or {}).get('field_id') or '') or None,
|
||
line_count=len(projected['lines']),
|
||
line_numbers=resolve_candidate_line_numbers([
|
||
next(
|
||
(
|
||
field.get('normalized_value') or field.get('raw_value')
|
||
for field in line.get('fields') or []
|
||
if isinstance(field, dict) and str(field.get('field_code') or '') == 'customer_po_line_no'
|
||
),
|
||
None,
|
||
)
|
||
for line in projected['lines']
|
||
]),
|
||
)
|
||
header_target = reservation_scope.get('header')
|
||
if applied.header_value and header_target:
|
||
projected['header_fields'] = [
|
||
item for item in projected['header_fields']
|
||
if str(item.get('field_code') or '') != 'reservation_id'
|
||
] + [{
|
||
'field_id': str(header_target.get('field_id') or ''),
|
||
'field_code': 'reservation_id',
|
||
'raw_value': applied.header_value,
|
||
'normalized_value': applied.header_value,
|
||
'status': 'passed',
|
||
'issues': [],
|
||
}]
|
||
line_target = reservation_scope.get('line')
|
||
if line_target:
|
||
for line_no, value in applied.line_values.items():
|
||
if line_no < 1 or line_no > len(projected['lines']):
|
||
continue
|
||
line = projected['lines'][line_no - 1]
|
||
line['fields'] = [
|
||
item for item in line['fields']
|
||
if str(item.get('field_code') or '') != 'reservation_id'
|
||
] + [{
|
||
'field_id': str(line_target.get('field_id') or ''),
|
||
'field_code': 'reservation_id',
|
||
'raw_value': value,
|
||
'normalized_value': value,
|
||
'status': 'passed',
|
||
'issues': [],
|
||
}]
|
||
if applied.needs_review:
|
||
projected['reservation_region_status'] = 'needs_review'
|
||
projected['reservation_region_review_reasons'] = list(applied.review_reasons)
|
||
return projected
|
||
|
||
|
||
def resolve_candidate_line_numbers(values: list[object]) -> list[int | None] | None:
|
||
"""把按逻辑行顺序给出的 Customer PO 行号(LN 列)取值整理为候选定位表。
|
||
|
||
核心逻辑:Reservation 注释里的 ``L#n`` 引用的是单据上印刷的行号,必须按 LN 值
|
||
定位逻辑行;LN 非连续(如部分行已拆单)时按位置写入会错配并误报越界。
|
||
任一行解析出有效行号才返回定位表;完全没有行号取值时返回 None,
|
||
由调用方保持历史位置序行为以兼容无 LN 字段的旧 Schema。
|
||
"""
|
||
numbers: list[int | None] = []
|
||
has_number = False
|
||
for value in values:
|
||
try:
|
||
number = int(str(value).strip())
|
||
except (TypeError, ValueError):
|
||
number = None
|
||
else:
|
||
has_number = True
|
||
numbers.append(number)
|
||
return numbers if has_number else None
|
||
|
||
|
||
def apply_reservation_region_candidates(
|
||
*, candidates: list[dict[str, object]], header_field_id: str | None,
|
||
line_field_id: str | None, line_count: int,
|
||
line_numbers: list[int | None] | None = None,
|
||
) -> ReservationRegionApplication:
|
||
"""按固定契约将专用区域候选归属到订单头和逻辑明细行。
|
||
|
||
无行号 Reservation 是整单事实,最多接受一个不同值;带行号的值仅在
|
||
Schema 启用明细 Reservation 字段时写入对应逻辑行。冲突、越界行号或
|
||
多个不同整单值必须转人工复核,不能静默猜测。
|
||
|
||
``line_numbers`` 为各逻辑行的 Customer PO 行号(LN 列,1 起始);提供时候选
|
||
``line_no`` 按 LN 值定位逻辑行,被引用行号不存在则记 ``line_out_of_range``。
|
||
未提供时保持历史位置序写入,仅兼容无 LN 字段的旧 Schema。
|
||
"""
|
||
_ = header_field_id
|
||
header_values: list[str] = []
|
||
line_values_by_no: dict[int, list[str]] = {}
|
||
reasons: list[str] = []
|
||
line_target_by_number: dict[int, int] = {}
|
||
if line_numbers is not None:
|
||
for index, number in enumerate(line_numbers):
|
||
if isinstance(number, int) and number > 0:
|
||
line_target_by_number.setdefault(number, index + 1)
|
||
for item in candidates:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
value = str(item.get('value') or '')
|
||
if not value:
|
||
continue
|
||
if item.get('scope') == 'header':
|
||
header_values.append(value)
|
||
continue
|
||
if item.get('scope') != 'line' or item.get('line_no') is None:
|
||
continue
|
||
try:
|
||
line_no = int(item['line_no'])
|
||
except (TypeError, ValueError):
|
||
reasons.append('line_out_of_range')
|
||
continue
|
||
if line_numbers is not None:
|
||
line_no = line_target_by_number.get(line_no, 0)
|
||
if line_no < 1 or line_no > line_count:
|
||
reasons.append('line_out_of_range')
|
||
continue
|
||
if line_field_id:
|
||
line_values_by_no.setdefault(line_no, []).append(value)
|
||
else:
|
||
reasons.append('line_field_unavailable')
|
||
|
||
unique_headers = list(dict.fromkeys(header_values))
|
||
if len(unique_headers) > 1:
|
||
reasons.append('conflicting_header_value')
|
||
resolved_lines: dict[int, str] = {}
|
||
for line_no, values in line_values_by_no.items():
|
||
unique_values = list(dict.fromkeys(values))
|
||
if len(unique_values) > 1:
|
||
reasons.append('conflicting_line_value')
|
||
continue
|
||
resolved_lines[line_no] = unique_values[0]
|
||
return ReservationRegionApplication(
|
||
header_value=unique_headers[0] if len(unique_headers) == 1 else None,
|
||
line_values=resolved_lines,
|
||
needs_review=bool(reasons),
|
||
review_reasons=tuple(dict.fromkeys(reasons)),
|
||
)
|