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: