Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-09-15 15:23:24 +08:00
commit 8e644a5707
15 files changed
+461 -63

No files matched your search

@@ -10,7 +10,9 @@ backend/app/jobs/handlers/shipping_order_extraction.py
收口时用 DB 实况判断:有 extractable ready work 则 layout_ready_continue 自交接;
仅 layouts_pending 且无 ready work 时以 partial_units_done 回到 waiting_layout;
运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed;
两处续抽均 continue_from_running,避免复用即将结束的 running Job;
两处续抽须同事务先 finish(commit=False) 再 enqueue(唯一索引含 running,
否则会撞 uq_jobs_shipping_order_extraction_active_ref);continue_from_running
仅对 queued 去重,避免复用已结束 Job;
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
@@ -666,6 +668,62 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
return None
def _handoff_continue_order_extraction(
*,
job: Job,
run: ShippingOrderProcessingRun,
owned_attempt: int,
result: dict[str, Any],
message: str,
enqueue_message: str,
phase: str,
) -> bool:
"""
同事务自交接:当前 running Job → success,再 INSERT 续抽 queued Job。
核心逻辑:finish_job(commit=False) 释放
uq_jobs_shipping_order_extraction_active_ref 槽位后,再
_enqueue_ready_order_extraction_job(continue_from_running=True);
写入 continue_job_id / Run.current_job_id 后一次 commit。
禁止先 enqueue 再 finish(running 仍占唯一索引会 UniqueViolation)。
Args:
job: 当前 running 的抽取 Job。
run: 对应 ProcessingRun。
owned_attempt: Worker 领取代次,传给 finish_job 围栏。
result: 写入旧 Job.result_json 的业务结果(本函数会补 continue_job_id)。
message: 旧 Job 收口说明。
enqueue_message: 新 Job 初始 message。
phase: 交接后 Run.phase(queued / waiting_layout)。
Returns:
True 表示已成功收口并入队;False 表示 finish 未生效(代次失效),调用方应停止。
"""
# [STEP 1] 先释放 active 唯一槽,勿在 running 时 INSERT 后继
if not finish_job(
job.id,
result=result,
message=message,
owned_attempt=owned_attempt,
commit=False,
):
return False
# [STEP 2] 同事务入队续抽;仅对 queued 去重,避免复用已 success 的本 Job
continue_job_id = _enqueue_ready_order_extraction_job(
run,
message=enqueue_message,
continue_from_running=True,
)
result['continue_job_id'] = int(continue_job_id)
run.current_job_id = int(continue_job_id)
run.phase = phase
finished = db.session.get(Job, int(job.id))
if finished is not None:
finished.result_json = dict(result)
db.session.commit()
return True
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
"""
@@ -1167,16 +1225,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
has_ready_work = order_extraction_has_extractable_ready_work(run)
layouts_pending = order_extraction_layouts_pending(run)
if has_ready_work:
continue_job_id = _enqueue_ready_order_extraction_job(
run,
message='附件版面已就绪,继续识别剩余附件',
continue_from_running=True,
)
run.current_job_id = continue_job_id
run.phase = 'waiting_layout' if layouts_pending else 'queued'
db.session.commit()
finish_job(
job.id,
_handoff_continue_order_extraction(
job=job,
run=run,
owned_attempt=owned_attempt,
result={
'run_no': run.run_no,
'waiting_layout': bool(layouts_pending),
@@ -1184,10 +1236,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
'handoff_status': 'layout_ready_continue',
'merged_unit_count': len(pending_merge_unit_ids),
'ready_document_ids': sorted(ready_document_ids),
'continue_job_id': int(continue_job_id),
},
message='附件版面已就绪,已排队继续识别剩余附件',
owned_attempt=owned_attempt,
enqueue_message='附件版面已就绪,继续识别剩余附件',
phase='waiting_layout' if layouts_pending else 'queued',
)
return
if layouts_pending:
@@ -1228,16 +1280,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
job_id=job.id,
commit=False,
)
continue_job_id = _enqueue_ready_order_extraction_job(
run,
message='运行时预算已用尽,继续识别剩余附件',
continue_from_running=True,
)
run.current_job_id = continue_job_id
run.phase = 'waiting_layout'
db.session.commit()
finish_job(
job.id,
_handoff_continue_order_extraction(
job=job,
run=run,
owned_attempt=owned_attempt,
result={
'run_no': run.run_no,
'budget_stopped': True,
@@ -1247,10 +1293,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
'pending_unit_count': sum(
1 for unit in units if str(unit.status or '') == 'pending'
),
'continue_job_id': int(continue_job_id),
},
message='运行时预算已用尽,已排队继续识别剩余附件',
owned_attempt=owned_attempt,
enqueue_message='运行时预算已用尽,继续识别剩余附件',
phase='waiting_layout',
)
return
orders = persisted_orders + merged_orders
+15 -1
View File
@@ -6,6 +6,7 @@ backend/app/jobs/queue.py
shipping_notice Intake 仅在预解析 Job 被 queued 同伴取代时同事务重指 parse_job_id。
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环;
recover 使用 FOR UPDATE SKIP LOCKED + 条件 UPDATE;finish/fail 以 status/attempts 条件 UPDATE;
finish_job(commit=False) 可供与续抽 enqueue 同事务提交;
enqueue 仅在 SAVEPOINT 内 add+flush,唯一冲突回落已有 Job;
running→queued 若撞 shipping_notice_parse queued 唯一索引则标 cancelled;
替代 Job 须 FOR UPDATE;仅 queued 或已真正持有 Intake lease 的 running 可 supersede。
@@ -791,10 +792,22 @@ def finish_job(
result: dict[str, Any] | None = None,
message: str | None = None,
owned_attempt: int | None = None,
commit: bool = True,
) -> bool:
"""
条件收口为 success:仅当 Job 仍为 running(且可选 attempts 匹配)时生效。
核心逻辑:status/attempts 条件 UPDATE;commit=False 时不提交,供调用方与
续抽 enqueue 等同事务提交(避免 shipping_order_extraction 唯一索引仍被
本 Job running 占用时无法 INSERT 后继)。
Args:
job: Job 实例或主键。
result: 写入 result_json 的业务结果。
message: 收口说明。
owned_attempt: 非空时要求 Job.attempts 匹配,防止代次错收口。
commit: False 时仅执行 UPDATE,由调用方统一 commit。
Returns:
是否实际更新到一行(False 表示代次失效或已非 running,调用方应视为 no-op)。
"""
@@ -819,7 +832,8 @@ def finish_job(
)
)
rowcount = int(db.session.execute(stmt).rowcount or 0)
db.session.commit()
if commit:
db.session.commit()
cached = db.session.get(Job, job_id)
if cached is not None:
db.session.expire(cached)
@@ -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))
@@ -1273,14 +1273,16 @@ def _enqueue_ready_order_extraction_job(
核心逻辑:enqueue 去重可能返回仍在排队的早建 Job;必须把其 priority 提到
_ORDER_EXTRACTION_READY_PRIORITY,否则 claim 仍按 created_at 先消化 layout。
自交接续抽(预算耗尽 / layout ready)须 continue_from_running=True,仅对 queued
去重,避免复用即将结束的 running Job。
自交接续抽(预算耗尽 / layout ready)须先 finish(commit=False) 释放
running 唯一槽,再以 continue_from_running=True 仅对 queued 去重入队,
避免复用即将结束的 running Job,也避免 UniqueViolation。
Args:
run: 订单抽取 Run。
message: Job 初始状态说明。
continue_from_running: True 时 dedupe_statuses=('queued',),供当前 running
Job 出口自交接;False(默认)可复用 queued/running,供 layout 完成回调唤醒。
continue_from_running: True 时 dedupe_statuses=('queued',),供当前 Job
已同事务标 success 后的自交接;False(默认)可复用 queued/running,
供 layout 完成回调唤醒。
Returns:
入队或复用的 Job.id。
@@ -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:
+123 -11
View File
@@ -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") == ""
@@ -2,11 +2,16 @@
订单抽取 Worker 单元测试。
覆盖:物化顺序、partial waiting_layout、layout_ready_continue 自交接、
runtime_budget_continue、layout 调度失败收口、以及 continue_from_running 去重。
runtime_budget_continue、layout 调度失败收口、continue_from_running 去重、
以及同事务 finish→enqueue 避免 UniqueViolation。
"""
from datetime import datetime
from types import SimpleNamespace
import pytest
from app import db
from app.core.errors import ServiceUnavailableError, ValidationError
from app.jobs.handlers.shipping_order_extraction import (
_expansion_trigger_reason_codes,
@@ -354,6 +359,7 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
def fake_finish(*_args, **kwargs):
events.append('finished')
finished.update(kwargs)
return True
monkeypatch.setattr(handler, 'finish_job', fake_finish)
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
@@ -374,7 +380,12 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
assert finished['result']['budget_stopped'] is True
assert finished['result']['waiting_continue'] is True
assert finished['result']['handoff_status'] == 'runtime_budget_continue'
assert finished['result']['continue_job_id'] == 999
assert pending_unit.status == 'pending'
# 方案 A:须先 finish(commit=False) 再 enqueue,避免 running 占唯一槽
assert events.index('finished') < next(
i for i, item in enumerate(events) if item.startswith('enqueue:')
)
def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(monkeypatch):
@@ -477,6 +488,7 @@ def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(m
def fake_finish(*_args, **kwargs):
events.append('finished')
finished.update(kwargs)
return True
monkeypatch.setattr(handler, 'finish_job', fake_finish)
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
@@ -502,6 +514,7 @@ def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(m
assert finished['result']['waiting_layout'] is False
assert finished['result']['continue_job_id'] == 1006
assert stale_pending_unit.status == 'pending'
assert events.index('finished') < events.index('enqueue:continue=True')
def test_worker_layout_ready_continue_keeps_waiting_layout_when_siblings_still_pending(monkeypatch):
@@ -595,7 +608,10 @@ def test_worker_layout_ready_continue_keeps_waiting_layout_when_siblings_still_p
handler, '_enqueue_ready_order_extraction_job',
lambda _run, *, message, continue_from_running=False: 1007,
)
monkeypatch.setattr(handler, 'finish_job', lambda *_a, **kwargs: finished.update(kwargs))
monkeypatch.setattr(
handler, 'finish_job',
lambda *_a, **kwargs: finished.update(kwargs) or True,
)
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
@@ -638,6 +654,75 @@ def test_enqueue_ready_order_extraction_job_continue_from_running_dedupes_queued
assert captured.get('business_ref') == 'SNER-DEDUP'
def test_order_extraction_handoff_finish_then_enqueue_same_txn(app):
"""
方案 A:同事务先 finish(commit=False) 再 enqueue,不得撞
uq_jobs_shipping_order_extraction_active_ref。
断言:running 时直接 enqueue 失败;释放槽后同事务 INSERT 成功,旧 Job success。
"""
with app.app_context():
from sqlalchemy.exc import IntegrityError
from app.jobs.queue import enqueue, finish_job
from app.jobs.types import JobType
from app.models import Job
run_no = 'SNER-HANDOFF-ATOMIC'
running = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_ORDER_EXTRACTION.value,
status='running',
business_ref=run_no,
payload_json={'run_no': run_no},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow(),
)
db.session.add(running)
db.session.commit()
running_id = int(running.id)
# 对照:仍 running 时直接 INSERT 必须撞唯一索引
with pytest.raises(IntegrityError):
enqueue(
JobType.SHIPPING_ORDER_EXTRACTION,
{'run_no': run_no},
domain='shipping_notice',
business_ref=run_no,
dedupe_statuses=('queued',),
dedupe_active=True,
commit=True,
)
db.session.rollback()
assert finish_job(
running_id,
result={'handoff_status': 'runtime_budget_continue'},
message='handoff',
owned_attempt=1,
commit=False,
) is True
continue_id = enqueue(
JobType.SHIPPING_ORDER_EXTRACTION,
{'run_no': run_no},
domain='shipping_notice',
business_ref=run_no,
dedupe_statuses=('queued',),
dedupe_active=True,
commit=False,
)
db.session.commit()
db.session.expire_all()
old = db.session.get(Job, running_id)
nxt = db.session.get(Job, int(continue_id))
assert old is not None and old.status == 'success'
assert nxt is not None and nxt.status == 'queued'
assert nxt.id != running_id
assert nxt.business_ref == run_no
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
"""版面 Job 创建失败(如 MinerU 关闭)时必须同步收口 Run,禁止仅失败 Job 而留下 queued。"""
import app.jobs.handlers.shipping_order_extraction as handler
+4 -2
View File
@@ -399,7 +399,7 @@ L1 字段级:目标单元格 + 表头 + 相邻单元格
**版面签名证据一致性(2026-08-04)**:表头签名不再扫描整页顶部或按表高固定比例猜测,而是直接冻结模板既有 `header_layout.region`;运行时对每个候选在同一区域独立取证。新旧 PDF 坐标证据统一按视觉行和纯几何词间距恢复表头词组,避免 `boundary_before` 有无造成同文件签名漂移;列中心和列宽由表头词组边界产生,不再使用全表单字符连续聚类。只有同时达到模板最低分和证据覆盖率的候选才参与唯一性与 Margin 决胜。
**邮件补充重建规则(2026-07-31)**:邮件表头只能按当前 Run 冻结 Schema 的显式别名映射;行级 `reservation_id` 包含真实业务表头 `External reservation ID`。只要 Intake 保留原始 `body_html_tables`,Run 冻结时必须按自己的 Schema 重新解析完整补充表,不能复用上传阶段缺字段但已有部分行的旧结果;没有 HTML 时才复用已有完整结果或安全回退纵向纯文本解析。
**邮件补充重建规则(2026-07-31)**:邮件表头只能按当前 Run 冻结 Schema 的显式别名映射;行级 `reservation_id` 包含真实业务表头 `External reservation ID`。只要 Intake 保留原始 `body_html_tables`,Run 冻结时必须按自己的 Schema 重新解析完整补充表,不能复用上传阶段缺字段但已有部分行的旧结果;没有 HTML 时才复用已有完整结果或安全回退纵向纯文本解析。**关联收紧(2026-09-15)**:`mpn_fallback` 仅适用于补充行 PO 缺失且料号唯一命中;有 PO 且与 PDF 不一致不得补充。预约号允许短数字行序后缀归一(如 `35354-1` → `35354`)。
**`llm_extraction` 回退语义(2026-08-01)**:订单字段标记为 `llm_extraction` 表示“确定性解析无法取值时允许 LLM 补充”,不表示必须使用 LLM。通用解析门禁应依据字段是否已有完整、无冲突的确定性证据裁决;已取得必填 Header/Line 值时可直通,缺失时由 `required_field_missing` 转入 LLM/人工复核。
@@ -3334,7 +3334,9 @@ API 层
邮件正文保持 `email_context`,但其受控 HTML 表会被确定性解析为 PO 级补充事实,而不是订单 Candidate 或订单抽取 Unit。每个补充值冻结 EML Intake、正文 Document、表格/行/列、DOM `cell_id`、原始值与规范化值;Run 仅冻结这项事实,Worker 不会对正文单独执行订单解析。
合并优先使用 `PO + MPN`;其次同 PO 且双方均有合法 `reservation_id` 时以 `po_reservation` 按行对齐(解决 allocation 表 APN 对不上 PDF 料号时仍可补库存源线索);只有同一 PO 的正文行唯一或唯一对应一个 Reservation 时,才能以 `po_fallback` 补齐。正文可覆盖/补齐 Reservation、Allocation 与库存来源提示,但绝不覆盖 PDF 的 PO、料号或数量;`allocated_qty` 仅作审计参考。多 Reservation、多来源、行无法唯一关联和无效表头均添加 `supplement_relation_ambiguous` 或稳定解析原因,并转入人工复核。
合并优先使用 `PO + MPN`;其次同 PO 且双方均有合法 `reservation_id` 时以 `po_reservation` 按行对齐(解决 allocation 表 APN 对不上 PDF 料号时仍可补库存源线索);只有同一 PO 的正文行唯一或唯一对应一个 Reservation 时,才能以 `po_fallback` 补齐。无同 PO 候选时,仅对 **PO 缺失** 行按料号唯一命中走 `mpn_fallback`(可多料号逐行);邮件行上有 PO 但与 PDF 不一致时**禁止**补充。正文可覆盖/补齐 Reservation、Allocation 与库存来源提示,但绝不覆盖 PDF 的 PO、料号或数量;`allocated_qty` 仅作审计参考。多 Reservation、多来源、行无法唯一关联和无效表头均添加 `supplement_relation_ambiguous` 或稳定解析原因,并转入人工复核。
**预约号短数字后缀(2026-09-15)**:统一抽取允许 `35354-1` / `3000112934-2` 等「合法 5/10 位本体 + 一段 `-`/`-`/`_` 数字后缀」,归一为本体后再参与 EML 校验与合并;多段后缀仍拒绝。详见 `docs/superpowers/specs/2026-09-15-email-supplement-po-absent-mpn-design.md`。
#### 阶段 3:PDF 模板解析、PO 拆分与严格拒识(2026-07-27,迁移前历史)
@@ -0,0 +1,57 @@
# EML 补充:PO 缺失料号兜底 + 预约号后缀规范化
**日期**:2026-09-15
**状态**:已定稿,待实现/实现中
## 1. 背景
两例不同断点一并覆盖:
1. **PO 缺失 / 错 PO**:补充表已解析出预约号或库存源线索,但 `merge_email_supplements` 未写入 PDF 行。旧 `mpn_fallback` 在「邮件 PO 打错但料号唯一」时仍会补,与业务裁决冲突。
2. **QUANTA 有 PO 仍缺预约**:`PO#` 与 PDF 已对齐,但 `IR#=35354-1` 不满足旧契约「仅 5/10 位纯数字」,EML 解析校验跳过该列,有效预约号落空。
## 2. 冻结规则
### 2.1 邮件关联(`order_supplement_merge`)
优先级保持:`po_mpn` → `po_reservation` → `po_fallback` → `mpn_fallback`。
| 规则 | 行为 |
|------|------|
| EML 行 PO 有值且规范化后 ∉ PDF PO 集合 | **禁止**补充(即使料号唯一) |
| EML 行 PO 缺失(无列或空) | 允许按料号兜底(`mpn_fallback` 仅扫 absent_po_rows) |
| 单行 EML + 单行订单 | 仍须料号命中;只去掉 PO 依赖 |
| 同料号唯一预约 + PO 缺失 | 按行补 |
| 同料号多个不同预约 | `supplement_relation_ambiguous` |
| 料号对不上 | 不补 |
| 库存源线索 | 只认冻结 Schema 别名映射字段 |
| 正文自由文本 PO | 不做 |
### 2.2 预约号短数字后缀(`reservation_id.extract_reservation_id`)
| 规则 | 行为 |
|------|------|
| `^(5或10位)[--_](\d+)$` | 取左侧本体(例:`35354-1` → `35354`) |
| 括号备注 / `@` 分隔 | 先试既有规则,再试短数字后缀 |
| 左侧非 5/10 位、多段后缀、字母后缀 | 拒绝 |
归一结果仍为 5/10 位纯数字;Schema `normalizer` / EML 校验 / `validated_reservation_id` 共用此抽取。
## 3. 非目标
- 自由文本抽 PO、非 Schema 别名库存源、无视料号单行广播
- 配置化关联决策表、错 PO 专用 Finding、字段冲突 UI 拆分
## 4. 落点
- `backend/app/services/shipping_notice/reservation_id.py`
- `backend/app/services/shipping_notice/order_supplement_merge.py`
- `backend/tests/test_shipping_notice_reservation_id.py`
- `backend/tests/test_email_supplement_merge.py`
- `frontend/src/locales/*/chat.json`(`mpn_fallback`)
- `docs/features/shipping-notice/technical.md`
## 5. 验收
- 错 PO 不补;PO 缺失 + 唯一料号可补;`35354-1` → 有效 `35354`
- `mpn_fallback` 四语言文案可见
+1
View File
@@ -438,6 +438,7 @@
"po_mpn": "Relation: PO + part number",
"po_reservation": "Relation: PO + reservation ID",
"po_fallback": "Relation: matched by PO",
"mpn_fallback": "Relation: missing PO + part number",
"unknown": "Relation pending confirmation"
},
"shippingOrderExtractionEmailSupplementField": {
+1
View File
@@ -438,6 +438,7 @@
"po_mpn": "วิธีเชื่อมโยง: PO + หมายเลขชิ้นส่วน",
"po_reservation": "วิธีเชื่อมโยง: PO + รหัสการจอง",
"po_fallback": "วิธีเชื่อมโยง: จับคู่ด้วย PO",
"mpn_fallback": "วิธีเชื่อมโยง: ไม่มี PO + หมายเลขชิ้นส่วน",
"unknown": "รอยืนยันวิธีเชื่อมโยง"
},
"shippingOrderExtractionEmailSupplementField": {
+1
View File
@@ -472,6 +472,7 @@
"po_mpn": "关联方式:PO + 料号",
"po_reservation": "关联方式:PO + 预约号",
"po_fallback": "关联方式:按 PO 匹配",
"mpn_fallback": "关联方式:PO 缺失 + 料号",
"unknown": "关联方式待确认"
},
"shippingOrderExtractionEmailSupplementField": {
+1
View File
@@ -438,6 +438,7 @@
"po_mpn": "關聯方式:PO + 料號",
"po_reservation": "關聯方式:PO + 預約號",
"po_fallback": "關聯方式:依 PO 配對",
"mpn_fallback": "關聯方式:PO 缺失 + 料號",
"unknown": "關聯方式待確認"
},
"shippingOrderExtractionEmailSupplementField": {