Merge branch 'hugo-shipping-notice' into test
This commit is contained in:
commit
6440889bf6
11 files changed
+282
-31
No files matched your search
@@ -4,6 +4,7 @@
|
||||
逻辑:订单字段表头只复用 Run/当前发布 Schema 的显式别名;邮件专属的分配事实
|
||||
仍使用受控固定列。表格歧义或缺 PO 保留原因,不将正文直接转成订单。
|
||||
非法非 PO 字段跳过本列并记 issue,避免可选列拖垮 Reservation/库存源线索。
|
||||
reservation_id 通过安全抽取后写入归一本体(含短数字行序后缀)。
|
||||
多表按文档顺序叠行:靠前为新,同行身份键先到为准;旧表仅补全新表未覆盖的行。
|
||||
"""
|
||||
|
||||
@@ -22,6 +23,7 @@ from app.services.shipping_notice.order_schema.field_rules import (
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import normalize_table_header
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
def _schema_configs(schema_definition: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
@@ -89,6 +91,13 @@ def _normalize_schema_row(
|
||||
if value is None or not validate_order_field_value(value, config):
|
||||
issues.append('email_supplement_field_invalid')
|
||||
continue
|
||||
# [STEP] reservation_id:校验已通过安全抽取后,落库写入归一本体(如 35354-1 → 35354)。
|
||||
if field_code == 'reservation_id':
|
||||
cleaned = validated_reservation_id(raw_value) or validated_reservation_id(value)
|
||||
if not cleaned:
|
||||
issues.append('email_supplement_field_invalid')
|
||||
continue
|
||||
value = cleaned
|
||||
normalized[field_code] = value
|
||||
po_code = 'customer_po_number' if 'customer_po_number' in normalized else 'po_number'
|
||||
po_number = normalize_po_number(normalized.get(po_code))
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
依赖:Run 冻结 Schema、正文补充表契约、PO 标准化、Reservation ID 校验。
|
||||
逻辑:优先 PO+MPN;其次同 PO+合法 reservation_id 对齐;仅唯一签名的 PO 可降级广播;
|
||||
歧义只写复核原因。reservation 对齐与「PO+料号灌预约号」同趟单次合并,不互相重入。
|
||||
无同 PO 候选时仅对「PO 缺失」行做唯一料号兜底(mpn_fallback);有 PO 且与 PDF
|
||||
不一致则禁止补充。歧义只写复核原因。同趟单次合并,不互相重入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -277,6 +278,7 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。
|
||||
|
||||
核心逻辑:同趟单次合并,优先级为 po_mpn → po_reservation → po_fallback → mpn_fallback;
|
||||
mpn_fallback 仅扫描 PO 缺失行上的唯一料号命中,禁止「错 PO + 料号」擅自补充;
|
||||
不因写入 reservation 再重入。po_reservation 按行对齐合法预约号,用于灌入库存源线索等。
|
||||
"""
|
||||
configs = {
|
||||
@@ -327,19 +329,37 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
selected = candidates
|
||||
relation = 'po_fallback'
|
||||
if not selected and not candidates:
|
||||
# 邮件正文的 PO 可能被上游人工录入错误;仅唯一精确 MPN 才能安全补证。
|
||||
mpn_matches = [
|
||||
# [STEP] 无同 PO 候选:仅 PO 缺失行可走料号兜底;有 PO 但与 PDF 不一致则禁止补充。
|
||||
# 按与订单相交的料号分组:每组签名唯一才纳入;任一组多预约/多签名则整单不走本档。
|
||||
absent_po_rows = [
|
||||
row for row in rows
|
||||
if _schema_field_values(row, part_codes) & order_part_values
|
||||
if isinstance(row, dict)
|
||||
and not normalize_atomic_po_number(row.get('customer_po_number') or row.get('po_number'))
|
||||
]
|
||||
distinct_matches = {
|
||||
tuple(str(row.get(field) or '').strip() for field in (
|
||||
*configs.keys(),
|
||||
)): row
|
||||
for row in mpn_matches
|
||||
}
|
||||
if len(distinct_matches) == 1:
|
||||
selected = list(distinct_matches.values())
|
||||
part_groups: dict[frozenset[str], list[dict[str, Any]]] = {}
|
||||
for row in absent_po_rows:
|
||||
hit_parts = frozenset(_schema_field_values(row, part_codes) & order_part_values)
|
||||
if not hit_parts:
|
||||
continue
|
||||
part_groups.setdefault(hit_parts, []).append(row)
|
||||
selected_rows: list[dict[str, Any]] = []
|
||||
part_group_ambiguous = False
|
||||
for group_rows in part_groups.values():
|
||||
distinct = {
|
||||
tuple(str(row.get(field) or '').strip() for field in configs.keys()): row
|
||||
for row in group_rows
|
||||
}
|
||||
if len(distinct) == 1:
|
||||
selected_rows.extend(distinct.values())
|
||||
else:
|
||||
part_group_ambiguous = True
|
||||
break
|
||||
if part_group_ambiguous:
|
||||
order.setdefault('conflicts', []).append({
|
||||
'severity': 'blocking', 'reason': 'supplement_relation_ambiguous',
|
||||
})
|
||||
elif selected_rows:
|
||||
selected = selected_rows
|
||||
relation = 'mpn_fallback'
|
||||
if not selected:
|
||||
if candidates:
|
||||
@@ -382,7 +402,21 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
if not isinstance(fields, list):
|
||||
continue
|
||||
value_by_canonical: dict[Any, tuple[str, dict[str, Any]]] = {}
|
||||
comparable_rows = selected if line_index < 0 or relation == 'po_fallback' else [source_row]
|
||||
# 头字段与 po_fallback:比较全部 selected。
|
||||
# po_mpn / mpn_fallback 行字段:比较所有命中本行料号的 selected,避免同料号多预约先写后冲。
|
||||
if line_index < 0 or relation == 'po_fallback':
|
||||
comparable_rows = selected
|
||||
elif relation in {'po_mpn', 'mpn_fallback'} and part_codes:
|
||||
line_part_values = (
|
||||
_values(fields, 'part_number', {v: k for k, v in ids.items()})
|
||||
| _values(fields, 'customer_part_number', {v: k for k, v in ids.items()})
|
||||
)
|
||||
comparable_rows = [
|
||||
row for row in selected
|
||||
if _schema_field_values(row, part_codes) & line_part_values
|
||||
] or [source_row]
|
||||
else:
|
||||
comparable_rows = [source_row]
|
||||
for item in comparable_rows:
|
||||
raw_value = str(item.get(target_code) or '').strip()
|
||||
if raw_value:
|
||||
@@ -408,6 +442,11 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
field_id = ids.get(target_code)
|
||||
if not value or not field_id:
|
||||
continue
|
||||
# 短数字后缀等:能抽出合法本体则写入本体;抽不出则保留原值走冲突/下游门禁。
|
||||
if target_code == 'reservation_id':
|
||||
normalized_reservation = validated_reservation_id(value)
|
||||
if normalized_reservation:
|
||||
value = normalized_reservation
|
||||
same_code_values = _conflict_canonical_values(
|
||||
fields, target_code, {v: k for k, v in ids.items()}, config,
|
||||
)
|
||||
|
||||
@@ -3,7 +3,8 @@ services/shipping_notice/reservation_id.py
|
||||
|
||||
用途:提取、标准化并校验发货通知与库存中的 Reservation ID。
|
||||
依赖:正则表达式与标准 `typing` 工具。
|
||||
逻辑:由 notice_lines、inventory_snapshot、match、extract 等多个解析/匹配模块复用本文件完成 Reservation ID 归一化。
|
||||
逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用;
|
||||
归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,6 +24,8 @@ INTERNAL_UUID_RE = re.compile(
|
||||
RESERVATION_VALUE_RE = re.compile(r"^(\d{10}|\d{5})(?!\d)\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$")
|
||||
# ``@`` 是预约号与前缀说明的显式分隔,后缀复用 Reservation 值的括号备注契约。
|
||||
RESERVATION_AT_SUFFIX_RE = re.compile(r"@\s*(\d{10}|\d{5})(?!\d)(?=\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$)")
|
||||
# QUANTA IR# 等:合法 5/10 位本体 + 一段短数字行序后缀(- / - / _);多段后缀拒绝。
|
||||
RESERVATION_SHORT_NUMERIC_SUFFIX_RE = re.compile(r"^(\d{10}|\d{5})[--_](\d+)$")
|
||||
PR_NUMBER_LINE_RE = re.compile(
|
||||
r"PR\s*Number\s*[::]?\s*([^\n\r]+)",
|
||||
re.IGNORECASE,
|
||||
@@ -59,25 +62,38 @@ def normalize_reservation_id(value: Any) -> str:
|
||||
|
||||
|
||||
def extract_reservation_id(value: Any) -> str:
|
||||
"""标准化 Reservation ID,并识别 ``@`` 后带可选括号备注的预约号。
|
||||
"""标准化 Reservation ID,并识别括号备注、``@`` 分隔与短数字行序后缀。
|
||||
|
||||
核心逻辑:先匹配纯 5/10 位(可带括号备注);再搜 ``@`` 后本体;最后剥离
|
||||
一段 ``-``/``-``/``_`` + 数字后缀(如 ``35354-1`` → ``35354``)。多段后缀不采纳。
|
||||
|
||||
Args:
|
||||
value: Reservation ID 字段原始值;仅允许整体纯数字,或明确 ``@`` 分隔后可带括号备注的纯数字。
|
||||
value: Reservation ID 字段原始值。
|
||||
|
||||
Returns:
|
||||
str: 已确认的五位或十位纯数字 Reservation ID;普通尾随文本或金额文本返回空字符串。
|
||||
str: 已确认的五位或十位纯数字 Reservation ID;无法安全抽取时返回空字符串。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
# [STEP 1] 整体纯数字(可选括号备注)
|
||||
direct = normalize_reservation_id(text)
|
||||
direct_match = RESERVATION_VALUE_RE.fullmatch(direct)
|
||||
if direct_match:
|
||||
return direct_match.group(1)
|
||||
|
||||
# [STEP 2] 显式 @ 分隔(可带括号备注)
|
||||
match = RESERVATION_AT_SUFFIX_RE.search(text)
|
||||
return match.group(1) if match else ""
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
# [STEP 3] 短数字行序后缀(IR# 35354-1);仅一段后缀
|
||||
suffix_match = RESERVATION_SHORT_NUMERIC_SUFFIX_RE.fullmatch(direct)
|
||||
if suffix_match:
|
||||
return suffix_match.group(1)
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def find_reservation_id_in_document(text: str) -> str:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
依赖:正文补充解析器与合并服务。
|
||||
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威;关联优先 PO+料号,
|
||||
其次 PO+预约号,歧义稳定进入复核。
|
||||
其次 PO+预约号;无同 PO 时仅 PO 缺失行可料号兜底;错 PO 禁止补充。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,7 +23,7 @@ SCHEMA = {'fields': [
|
||||
{'field_id': 'qty', 'field_code': 'qty'},
|
||||
{
|
||||
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'aliases': ['Reservation ID', 'External reservation ID', 'Reservation Number'],
|
||||
'aliases': ['Reservation ID', 'External reservation ID', 'Reservation Number', 'IR#'],
|
||||
},
|
||||
{'field_id': 'allocation', 'field_code': 'allocation_id'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']},
|
||||
@@ -213,7 +213,12 @@ def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review():
|
||||
)[0]
|
||||
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == 'PDF-33873'
|
||||
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
|
||||
assert any(
|
||||
item.get('severity') == 'blocking'
|
||||
and item.get('reason') == 'supplement_field_conflict'
|
||||
and item.get('field') == 'reservation_id'
|
||||
for item in merged['conflicts']
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -337,12 +342,12 @@ def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_
|
||||
order['lines'][0]['fields'][0]['observations'][0]['value'] = value
|
||||
supplement = {'document_id': 44, 'rows': [{
|
||||
'po_number': '4518738152', mail_field: value,
|
||||
'reservation_id': f'30000{index}', 'evidence': {},
|
||||
'reservation_id': f'300000000{index}', 'evidence': {},
|
||||
}]}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == f'30000{index}'
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == f'300000000{index}'
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
@@ -447,17 +452,13 @@ def test_email_supplement_po_fallback_requires_one_reservation():
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in result['conflicts'])
|
||||
|
||||
|
||||
def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
"""邮件 PO 与 PDF 不一致时,唯一完全匹配 MPN 仍可保守补齐预约号。"""
|
||||
def test_email_supplement_unique_mpn_fallback_rejects_mistyped_email_po():
|
||||
"""邮件 PO 有值且与 PDF 不一致时禁止 mpn_fallback,哪怕料号唯一命中。"""
|
||||
order = _order()
|
||||
order['header_fields'][0]['observations'][0]['value'] = '4518838152'
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
@@ -472,10 +473,121 @@ def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
|
||||
assert not any(item['field_id'] == 'reservation' for item in result['lines'][0]['fields'])
|
||||
assert result.get('_hxops_email_supplement_relation') is None
|
||||
|
||||
|
||||
def test_email_supplement_mpn_fallback_when_po_absent_and_part_unique():
|
||||
"""PO 列缺失时,唯一料号命中仍可保守补齐预约号与库存源线索。"""
|
||||
order = _order()
|
||||
result = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577',
|
||||
'inventory_source_hint': 'DBS SIN',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '2000484577'
|
||||
assert _value(result['lines'][0]['fields'], 'source') == 'DBS SIN'
|
||||
assert result['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_single_line_po_absent_still_requires_part_match():
|
||||
"""双边各一行且 PO 缺失时仍须料号对上;对不上不得广播预约号。"""
|
||||
order = _order()
|
||||
result = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'part_number': 'OTHER-PART-0001',
|
||||
'reservation_id': '2000484577',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert not any(item['field_id'] == 'reservation' for item in result['lines'][0]['fields'])
|
||||
assert result.get('_hxops_email_supplement_relation') is None
|
||||
|
||||
|
||||
def test_email_supplement_po_absent_unique_reservation_per_part_merges_rows():
|
||||
"""多行 PO 缺失时按料号唯一预约号逐行补充;同料号多预约则歧义。"""
|
||||
order = {
|
||||
'_hxops_intake_id': 1,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': '4518738152'}]}],
|
||||
'lines': [
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000002'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 1}]},
|
||||
]},
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 2}]},
|
||||
]},
|
||||
],
|
||||
'conflicts': [],
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': '2000484577', 'evidence': {}},
|
||||
{'part_number': 'D4-A08AR12000003', 'reservation_id': '2000484578', 'evidence': {}},
|
||||
]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert merged['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == '2000484577'
|
||||
assert _value(merged['lines'][1]['fields'], 'reservation') == '2000484578'
|
||||
|
||||
ambiguous = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': '2000484577', 'evidence': {}},
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': '2000484579', 'evidence': {}},
|
||||
{'part_number': 'D4-A08AR12000003', 'reservation_id': '2000484578', 'evidence': {}},
|
||||
]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in ambiguous['conflicts'])
|
||||
assert not any(item['field_id'] == 'reservation' for item in ambiguous['lines'][0]['fields'])
|
||||
assert not any(item['field_id'] == 'reservation' for item in ambiguous['lines'][1]['fields'])
|
||||
|
||||
|
||||
def test_email_supplement_normalizes_reservation_short_numeric_suffix_on_merge():
|
||||
"""同 PO 命中后,IR# 形态 35354-1 写入订单行时归一为 35354。"""
|
||||
result = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'customer_po_number': '4518738152',
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '35354-1',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '35354'
|
||||
assert result['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_html_ir_hash_suffix_survives_parse_and_merge():
|
||||
"""解析 IR#=35354-1 不得因非法形态丢列,合并后预约号为 35354。"""
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='i' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>IR#</th></tr>
|
||||
<tr><td>4518738152</td><td>D4-A08AR12000002</td><td>35354-1</td></tr></table>'''],
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
assert supplement['rows'][0]['reservation_id'] == '35354'
|
||||
assert 'email_supplement_field_invalid' not in supplement.get('issues', [])
|
||||
merged = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {**supplement, 'document_id': 44}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == '35354'
|
||||
|
||||
|
||||
def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_body_text():
|
||||
"""Outlook 展平的纵向表头可恢复补充行,尾部邮件正文不会被误当数据。"""
|
||||
supplement = parse_email_allocation_text(
|
||||
|
||||
@@ -71,6 +71,18 @@ def test_validated_reservation_id_strips_optional_parenthesized_note():
|
||||
assert validated_reservation_id("30001129345") == ""
|
||||
|
||||
|
||||
def test_validated_reservation_id_strips_short_numeric_line_suffix():
|
||||
"""QUANTA IR# 等:合法 5/10 位本体 + 一段短数字后缀归一为本体;多段/非法左侧拒绝。"""
|
||||
assert validated_reservation_id("35354-1") == "35354"
|
||||
assert validated_reservation_id("3000112934-2") == "3000112934"
|
||||
assert validated_reservation_id("35354-1") == "35354"
|
||||
assert validated_reservation_id("35354_1") == "35354"
|
||||
assert validated_reservation_id("1234-1") == ""
|
||||
assert validated_reservation_id("35354-1-2") == ""
|
||||
assert validated_reservation_id("35354-a") == ""
|
||||
assert validated_reservation_id("35354123456-1") == ""
|
||||
|
||||
|
||||
def test_validated_reservation_id_rejects_amount_text_as_numeric_token():
|
||||
"""金额行中的五位整数片段不能被当成 Reservation ID。"""
|
||||
assert validated_reservation_id("941.76 28,252.80") == ""
|
||||
|
||||
Reference in new issue
Block a user