feat(shipping-notice): 完善订单解析、模板管理与库存 RPA 流程
- 优化订单文档解析、补充合并与坐标重建 - 完善订单模板校验、发布及前端管理界面 - 改进库存 RPA 下载回退与工作流处理 - 补充后端、前端及 RPA 自动化测试 - 更新 Shipping Notice 技术文档与四语言文案
This commit is contained in:
1 parent
c4a27324c8
commit
8f2f568f92
46 files changed
+1745
-265
No files matched your search
@@ -4,10 +4,11 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
用途:消费订单抽取 Run,使用固定模板/通用确定性解析并持久化可复核结果。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、
|
||||
ensure_workflow_items_for_run(物化后兜底建 Item)、order_extraction_merge、
|
||||
order_supplement_merge(仅 eml)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行;每个 Unit 按 STP route_decision
|
||||
直通或落 provisional;needs_review 剥离验收标记;不调用 Dify 主链。
|
||||
阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
|
||||
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进,
|
||||
兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout;
|
||||
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
|
||||
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
|
||||
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
|
||||
"""
|
||||
|
||||
@@ -44,6 +45,8 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
complete_input_freeze,
|
||||
mark_order_extraction_persistence_started,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
order_extraction_layouts_pending,
|
||||
order_extraction_ready_document_ids,
|
||||
materialize_order_extraction_run_inputs,
|
||||
ensure_workflow_items_for_run,
|
||||
progress_ready_extraction_unit,
|
||||
@@ -661,7 +664,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行一次纯确定性订单抽取 Job。
|
||||
|
||||
核心逻辑:物化附件与排版面 Job 纳入主 try;排程 ValidationError(如 MinerU 关闭)非重试,同步将 Run 标为 failed。
|
||||
核心逻辑:物化附件与排版面 Job 纳入主 try;有 ready PDF 时按 Unit 抽取并立刻下游推进;
|
||||
仍有 layout pending 时 Job 成功收口并回到 waiting_layout,不终态 Run。
|
||||
排程 ValidationError(如 MinerU 关闭)非重试,同步将 Run 标为 failed。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文,仅用于安全日志。
|
||||
@@ -703,47 +708,72 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
ensure_workflow_items_for_run(run, stage_when_ready='extracting')
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
# [STEP 2] 按 Unit 放行:仅当零 ready PDF 时整 Job defer;有 ready 则抽 ready Unit。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
if 'layout_pending' in layout_issues.values():
|
||||
# 布局等待期已进入 freezing;仍禁止追加,待布局就绪后完成冻结。
|
||||
run.phase = 'waiting_layout'
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': True,
|
||||
'handoff_status': 'deferred_to_layout',
|
||||
},
|
||||
message='已转交附件版面解析,完成后自动创建后继订单识别任务',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
if layout_issues:
|
||||
complete_input_freeze(run)
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_prerequisite_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message='Order PDF layout prerequisites are incomplete',
|
||||
)
|
||||
record_run_progress(
|
||||
run=run, event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
summary={'document_count': len(layout_issues)}, job_id=job.id, commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'layout_issues': layout_issues}, message='订单附件解析条件不完整', owned_attempt=owned_attempt)
|
||||
return
|
||||
pending_layout_ids = {
|
||||
document_id
|
||||
for document_id, code in layout_issues.items()
|
||||
if code == 'layout_pending'
|
||||
}
|
||||
hard_layout_issues = {
|
||||
document_id: code
|
||||
for document_id, code in layout_issues.items()
|
||||
if code != 'layout_pending'
|
||||
}
|
||||
ready_document_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_document_ids:
|
||||
if pending_layout_ids:
|
||||
# 布局等待期已进入 freezing;仍禁止追加,待任一布局就绪后再抽。
|
||||
run.phase = 'waiting_layout'
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': True,
|
||||
'handoff_status': 'deferred_to_layout',
|
||||
},
|
||||
message='已转交附件版面解析,完成后自动创建后继订单识别任务',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
if hard_layout_issues:
|
||||
complete_input_freeze(run)
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_prerequisite_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message='Order PDF layout prerequisites are incomplete',
|
||||
)
|
||||
record_run_progress(
|
||||
run=run, event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
summary={'document_count': len(hard_layout_issues)}, job_id=job.id, commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'run_no': run.run_no, 'layout_issues': hard_layout_issues},
|
||||
message='订单附件解析条件不完整',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
# [STEP 3] 所有 PDF 布局就绪后重建快照,此时才冻结带坐标证据的执行计划。
|
||||
# [STEP 3] 至少一个 PDF 版式就绪即可建 Plan 并冻结输入;未 ready 的 Unit 留 pending。
|
||||
plan = materialize_order_extraction_run_inputs(run)
|
||||
if plan is None:
|
||||
raise RuntimeError('order extraction plan was not finalized')
|
||||
# [BE-F03] 物化完成 → frozen,再进入 processing。
|
||||
complete_input_freeze(run)
|
||||
# 物化可能回填刚就绪的坐标证据;按最新前置条件决定本轮抽哪些 Unit。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
pending_layout_ids = {
|
||||
document_id
|
||||
for document_id, code in layout_issues.items()
|
||||
if code == 'layout_pending'
|
||||
}
|
||||
ready_document_ids = order_extraction_ready_document_ids(run)
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
@@ -751,6 +781,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
selection = (run.input_snapshot_json or {}).get('attachment_selection') or {}
|
||||
max_runtime_seconds = max(0, int(selection.get('max_runtime_seconds') or 0))
|
||||
runtime_budget_stopped = False
|
||||
layout_blocked_in_wave = False
|
||||
run.current_job_id = job.id
|
||||
run.attempt_count = owned_attempt
|
||||
record_run_progress(
|
||||
@@ -759,6 +790,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
summary={
|
||||
**_selection_progress_summary(run),
|
||||
'unit_count': int(getattr(plan, 'unit_count', 0) or 0),
|
||||
'ready_document_count': len(ready_document_ids),
|
||||
'pending_layout_count': len(pending_layout_ids),
|
||||
'job_attempt': owned_attempt,
|
||||
},
|
||||
job_id=job.id,
|
||||
@@ -829,6 +862,29 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
continue
|
||||
if unit.status == 'review_required':
|
||||
continue
|
||||
unit_layout_issue = layout_issues.get(int(unit.document_id or 0))
|
||||
if unit_layout_issue == 'layout_pending':
|
||||
layout_blocked_in_wave = True
|
||||
continue
|
||||
if unit_layout_issue:
|
||||
# 硬前置失败:pending→routing→failed,避免 Unit 永久挂起阻塞收口。
|
||||
if str(unit.status or '') == 'pending':
|
||||
transition_order_extraction_unit(unit, target_status='routing')
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message=f'layout prerequisite: {unit_layout_issue}',
|
||||
)
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
summary={'layout_issue': unit_layout_issue},
|
||||
job_id=job.id,
|
||||
)
|
||||
continue
|
||||
unit_orders = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=owned_attempt)
|
||||
db.session.expire_all()
|
||||
unit = db.session.get(ShippingOrderProcessingUnit, int(unit.id))
|
||||
@@ -839,6 +895,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
wave_orders.extend(unit_orders)
|
||||
if runtime_budget_stopped:
|
||||
break
|
||||
# 同批仍有 layout pending 的 Unit:禁止扩附,交 partial defer。
|
||||
if layout_blocked_in_wave:
|
||||
break
|
||||
wave_orders = _wave_orders_for_expansion(run, orders=wave_orders)
|
||||
expansion_reason_codes = _expansion_trigger_reason_codes(wave_units=units, wave_orders=wave_orders)
|
||||
|
||||
@@ -1094,6 +1153,23 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
job_id=job.id,
|
||||
)
|
||||
raise
|
||||
# [STEP] 仍有兄弟文件版式未完成:已抽 Unit 保留,Job 成功收口并回到 waiting_layout,禁止 Run 终态。
|
||||
if layout_blocked_in_wave or order_extraction_layouts_pending(run):
|
||||
run.phase = 'waiting_layout'
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': True,
|
||||
'handoff_status': 'partial_units_done',
|
||||
'merged_unit_count': len(pending_merge_unit_ids),
|
||||
'ready_document_ids': sorted(ready_document_ids),
|
||||
},
|
||||
message='已完成就绪附件的订单识别,其余附件版面解析完成后继续',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
orders = persisted_orders + merged_orders
|
||||
execution = {
|
||||
'mode': 'deterministic',
|
||||
|
||||
+19
-13
@@ -153,10 +153,13 @@ def reconstruct_coordinate_profile_rows_with_strategy(
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
page_no: int = 1,
|
||||
) -> tuple[list['CoordinateProfileLogicalRow'], Any]:
|
||||
"""统一评估 fixed/adaptive/dynamic,并返回唯一安全的坐标明细结果。"""
|
||||
from app.services.shipping_notice.document_layout.runtime_parse_strategy import (
|
||||
resolve_runtime_parse_strategy,
|
||||
)
|
||||
"""统一评估 fixed/adaptive/dynamic,并返回坐标明细与策略结果。
|
||||
|
||||
核心逻辑:三种重建模式都跑一遍再交给策略裁决;``selected`` 时只返回被选中模式。
|
||||
策略为 ``needs_review`` 时仍返回 fixed→adaptive→dynamic 的最佳努力明细,供盲测/
|
||||
验证人工核对;正式自动建单路径必须自行检查 ``strategy.status == 'selected'``。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout import runtime_parse_strategy as parse_strategy
|
||||
|
||||
fixed_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
|
||||
@@ -197,20 +200,23 @@ def reconstruct_coordinate_profile_rows_with_strategy(
|
||||
for row in rows
|
||||
]
|
||||
|
||||
strategy = resolve_runtime_parse_strategy(
|
||||
strategy = parse_strategy.resolve_runtime_parse_strategy(
|
||||
page_glyphs={str(page_no): characters},
|
||||
fixed_rows=strategy_rows(fixed_rows),
|
||||
adaptive_rows=strategy_rows(adaptive_rows),
|
||||
dynamic_rows=strategy_rows(dynamic_rows),
|
||||
)
|
||||
if strategy.status != 'selected' or strategy.row_mode is None:
|
||||
return [], strategy
|
||||
return (
|
||||
fixed_rows if strategy.row_mode == 'fixed_subrows'
|
||||
else adaptive_rows if strategy.row_mode == 'adaptive_record_columns'
|
||||
else dynamic_rows,
|
||||
strategy,
|
||||
)
|
||||
if strategy.status == 'selected' and strategy.row_mode is not None:
|
||||
return (
|
||||
fixed_rows if strategy.row_mode == 'fixed_subrows'
|
||||
else adaptive_rows if strategy.row_mode == 'adaptive_record_columns'
|
||||
else dynamic_rows,
|
||||
strategy,
|
||||
)
|
||||
# 策略需复核时仍返回最佳努力明细,供盲测/验证人工核对;正式自动建单仍以
|
||||
# strategy.status == 'selected' 为准,不得把 fallback 当成可自动建单结果。
|
||||
fallback = fixed_rows or adaptive_rows or dynamic_rows
|
||||
return fallback, strategy
|
||||
|
||||
|
||||
def resolve_line_start_field_code(value: Any = None) -> str:
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
services/shipping_notice/document_profile_quality_service.py
|
||||
|
||||
用途:治理订单文档 Profile 的盲测候选、样本、执行结果和确定性自动建单资格。
|
||||
依赖:Profile 服务、MinerU 当前布局快照、XFA 结构分析、xfa_validation 指标、Profile 纯解析器与质量 ORM 模型。
|
||||
依赖:Profile 服务、MinerU 当前布局快照、XFA 结构分析、xfa_validation 指标、坐标重建与运行时策略、Profile 纯解析器与质量 ORM 模型。
|
||||
逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;
|
||||
共同坐标回放完成视觉证据,末端值源 adapter 再补充正式字段和结构校验;
|
||||
策略需复核时仍展示最佳努力明细供人工核对,正式自动建单仍要求策略 selected;
|
||||
盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。
|
||||
"""
|
||||
|
||||
@@ -41,7 +42,6 @@ from app.services.shipping_notice.document_layout.runtime_parse_strategy import
|
||||
from app.services.shipping_notice.document_layout.order_field_extraction import (
|
||||
_is_placeholder_anchor_text, extract_order_fields,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
@@ -51,7 +51,7 @@ from app.services.shipping_notice.order_document_profile_service import (
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
|
||||
from app.services.shipping_notice.reservation_region import (
|
||||
apply_reservation_region_candidates,
|
||||
extract_reservation_from_region_text,
|
||||
reservation_region_candidates_from_layout,
|
||||
)
|
||||
|
||||
|
||||
@@ -378,6 +378,17 @@ def _candidate_for_sample(
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
if not isinstance((evidence.get('tables') or {}).get(str(table_id)), list):
|
||||
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
# 明细页坐标可能尚未因订单头字段补齐;盲测重建前先确保表所在页有整页证据。
|
||||
if isinstance(raw_table, dict):
|
||||
try:
|
||||
table_page_no = int(raw_table.get('page_no') or 1)
|
||||
except (TypeError, ValueError):
|
||||
table_page_no = 1
|
||||
if table_page_no > 0:
|
||||
layout = _ensure_page_coordinate_evidence(
|
||||
document=document, layout=layout, page_no=table_page_no,
|
||||
)
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
if not any(isinstance(value, list) and value for value in page_glyphs.values()):
|
||||
@@ -450,8 +461,8 @@ def _candidate_for_sample(
|
||||
line_start_field_code=region.line_start_field_code,
|
||||
schema_field_metadata=list(schema_fields.values()),
|
||||
)
|
||||
if strategy.status == 'selected':
|
||||
rows.extend(item.fields for item in chosen_rows if not item.issues)
|
||||
# selected 与 needs_review 的 fallback 明细都要展示;后者仅供盲测人工复核。
|
||||
rows.extend(item.fields for item in chosen_rows if not item.issues)
|
||||
order_fields = [
|
||||
{
|
||||
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
|
||||
@@ -465,54 +476,52 @@ def _candidate_for_sample(
|
||||
allow_fixed_region_confirmation=True,
|
||||
)
|
||||
]
|
||||
# 盲测与正式解析共用 Reservation 区域解析和归属契约;区域页可以不同于明细页。
|
||||
# 盲测与正式解析共用 Vendor Comments→Terms 锚点;page_no/region 仅表示专区已启用。
|
||||
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
reservation_region = profile_definition.get('reservation_id_region')
|
||||
if isinstance(reservation_region, dict):
|
||||
region = reservation_region.get('region')
|
||||
try:
|
||||
reservation_page_no = int(reservation_region.get('page_no') or 0)
|
||||
except (TypeError, ValueError):
|
||||
reservation_page_no = 0
|
||||
if isinstance(region, dict) and reservation_page_no > 0:
|
||||
layout = _ensure_page_coordinate_evidence(
|
||||
document=document, layout=layout, page_no=reservation_page_no,
|
||||
if isinstance(profile_definition.get('reservation_id_region'), dict):
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=layout, page_nos=None,
|
||||
)
|
||||
reservation = reservation_region_candidates_from_layout(
|
||||
definition=profile_definition, layout=layout,
|
||||
)
|
||||
candidates = list(reservation.get('candidates') or [])
|
||||
reservation_reason = reservation.get('reason')
|
||||
reservation_fields = {
|
||||
str(field.get('scope') or ''): field
|
||||
for field in schema_fields.values()
|
||||
if str(field.get('field_code') or '') == 'reservation_id'
|
||||
}
|
||||
review_reasons: list[str] = [str(reservation_reason)] if reservation_reason else []
|
||||
if candidates:
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=candidates,
|
||||
header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None,
|
||||
line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None,
|
||||
line_count=len(rows),
|
||||
)
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
page = (evidence.get('pages') or {}).get(str(reservation_page_no))
|
||||
glyphs = (evidence.get('page_glyphs') or {}).get(str(reservation_page_no))
|
||||
if isinstance(page, dict) and isinstance(glyphs, list):
|
||||
candidates = extract_reservation_from_region_text(
|
||||
read_coordinate_region_text(glyphs=glyphs, page=page, region=region),
|
||||
)
|
||||
reservation_fields = {
|
||||
str(field.get('scope') or ''): field
|
||||
for field in schema_fields.values()
|
||||
if str(field.get('field_code') or '') == 'reservation_id'
|
||||
}
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=candidates,
|
||||
header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None,
|
||||
line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None,
|
||||
line_count=len(rows),
|
||||
)
|
||||
if applied.header_value and reservation_fields.get('header'):
|
||||
header = reservation_fields['header']
|
||||
order_fields.append({
|
||||
'field_code': str(header.get('field_code') or ''), 'value': applied.header_value,
|
||||
'status': 'confirmed', 'field_id': str(header.get('field_id') or ''), 'scope': 'header',
|
||||
'page_no': reservation_page_no, 'issues': [],
|
||||
})
|
||||
if reservation_fields.get('line'):
|
||||
for line_no, value in applied.line_values.items():
|
||||
if isinstance(rows[line_no - 1], dict):
|
||||
rows[line_no - 1]['reservation_id'] = value
|
||||
if applied.needs_review:
|
||||
return {
|
||||
'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(applied.review_reasons),
|
||||
}
|
||||
if applied.header_value and reservation_fields.get('header'):
|
||||
header = reservation_fields['header']
|
||||
order_fields.append({
|
||||
'field_code': str(header.get('field_code') or ''), 'value': applied.header_value,
|
||||
'status': 'confirmed', 'field_id': str(header.get('field_id') or ''), 'scope': 'header',
|
||||
'page_no': 1, 'issues': [],
|
||||
})
|
||||
if reservation_fields.get('line'):
|
||||
for line_no, value in applied.line_values.items():
|
||||
if isinstance(rows[line_no - 1], dict):
|
||||
rows[line_no - 1]['reservation_id'] = value
|
||||
if applied.needs_review:
|
||||
review_reasons.extend(list(applied.review_reasons))
|
||||
if review_reasons:
|
||||
return {
|
||||
'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)),
|
||||
}
|
||||
return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields}
|
||||
raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
|
||||
|
||||
@@ -5,7 +5,8 @@ services/shipping_notice/inventory_rpa_workflow.py
|
||||
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、
|
||||
inventory_mapping_workflow、query_service、动态订单字段、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
|
||||
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取。
|
||||
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取;
|
||||
复用 ready 快照走 link_snapshot_to_task_for_preparation(动态仓未决可 pending_matching)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -148,7 +149,8 @@ def _try_reuse_inventory_snapshot(
|
||||
优先复用未过期库存快照,避免重复触发 RPA。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。
|
||||
|
||||
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入待匹配状态。
|
||||
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则用
|
||||
preparation 软绑定并进入待匹配状态(动态仓未决不视为缺文件)。
|
||||
retry_rpa 必须跳过缓存强制重新导出。
|
||||
"""
|
||||
if mode == "retry_rpa":
|
||||
@@ -163,7 +165,7 @@ def _try_reuse_inventory_snapshot(
|
||||
if not snapshot:
|
||||
return None
|
||||
|
||||
link = link_snapshot_to_task(
|
||||
link = link_snapshot_to_task_for_preparation(
|
||||
task,
|
||||
snapshot,
|
||||
reason="reuse_latest",
|
||||
|
||||
@@ -6,7 +6,8 @@ services/shipping_notice/inventory_workflow.py
|
||||
inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。
|
||||
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除;
|
||||
payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓);
|
||||
STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File。
|
||||
STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File;
|
||||
动态仓复用走 link_snapshot_to_task_for_preparation,仓未决不得谎称库存文件缺失。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -65,8 +66,9 @@ def _link_ready_candidate_prep_or_block(
|
||||
STP 候选库存 ready 后,确保 OT 已绑定有效库存文件再允许写回解析结果。
|
||||
|
||||
核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded
|
||||
快照并 ``link_snapshot_to_task``(与单源 reuse 对齐)。绑定失败返回 needs_human,
|
||||
禁止抛出「未绑定库存文件」ValueError 把 Gate Job 打成 technical_failure。
|
||||
快照并 ``link_snapshot_to_task_for_preparation``。动态仓仓库识别失败时仍保留文件绑定
|
||||
(pending_matching),仓/匹配问题留给 inventory_matching,禁止把「有文件」投影成
|
||||
inventory_file_missing。仅当真的无法绑定文件时才 needs_human。
|
||||
|
||||
Args:
|
||||
task: 已冻结候选源的订单任务。
|
||||
@@ -78,7 +80,9 @@ def _link_ready_candidate_prep_or_block(
|
||||
"""
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
link_snapshot_to_task_for_preparation,
|
||||
)
|
||||
|
||||
# [STEP 1] 已绑定则无需重复 link。
|
||||
if active_inventory_file_for_task(task) is not None:
|
||||
@@ -109,11 +113,12 @@ def _link_ready_candidate_prep_or_block(
|
||||
)
|
||||
link = None
|
||||
if inv_file is not None:
|
||||
link = link_snapshot_to_task(
|
||||
# [STEP] 与 RPA 回调同权:文件事实先挂 OT;动态仓未决 → pending_matching,
|
||||
# 不因 warehouse_configuration_invalid 谎称「库存文件未准备」。
|
||||
link = link_snapshot_to_task_for_preparation(
|
||||
task,
|
||||
inv_file,
|
||||
reason='stp_candidate_prep',
|
||||
role='owner',
|
||||
audit_payload={
|
||||
'candidate_set_id': prep.get('candidate_set_id'),
|
||||
'loaded_source_codes': list(prep.get('loaded_source_codes') or []),
|
||||
@@ -123,7 +128,7 @@ def _link_ready_candidate_prep_or_block(
|
||||
db.session.flush()
|
||||
return None
|
||||
|
||||
# [STEP 3] 无法绑定:软阻断,留给人工重试/上传,勿让 Gate Job 因 ValueError 失败。
|
||||
# [STEP 3] 真的没有可绑定文件:软阻断,勿让 Gate Job 因 ValueError 失败。
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
|
||||
+12
-2
@@ -265,14 +265,21 @@ def _resolve_overlap_run(
|
||||
|
||||
|
||||
def _blocking_from_overlap(summary: dict[str, Any] | None, overlap_run: ShippingOrderDocumentProfileValidationRun | None, revision: ShippingOrderDocumentProfileDraftRevision) -> list[dict[str, Any]]:
|
||||
"""将重叠验证摘要转为发布阻断项。"""
|
||||
"""
|
||||
将重叠验证摘要转为发布阻断项。
|
||||
|
||||
核心逻辑:仅在 definition_checksum 漂移时标为 stale;当前草稿上的 failed 运行
|
||||
必须展开真实门禁(如 self_match_not_unique),禁止误报“验证已过期”。
|
||||
"""
|
||||
blocking: list[dict[str, Any]] = []
|
||||
if overlap_run is None:
|
||||
blocking.append({'key': 'overlap_validation_required', 'message': 'Cross-template overlap validation is required.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
return blocking
|
||||
if overlap_run.definition_checksum != revision.definition_checksum or overlap_run.status != 'passed':
|
||||
# [STEP 1] checksum 漂移才是 stale;failed≠过期。
|
||||
if overlap_run.definition_checksum != revision.definition_checksum:
|
||||
blocking.append({'key': 'overlap_validation_stale', 'message': 'Cross-template overlap validation is stale.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
return blocking
|
||||
# [STEP 2] 当前草稿的 passed/failed 一律按摘要指标展开,避免掩盖真实阻断原因。
|
||||
summary = summary or dict(overlap_run.summary_json or {})
|
||||
snapshot = dict(overlap_run.result_snapshot_json or {})
|
||||
if float(summary.get('self_unique_hit_rate_training') or 0) < 1.0:
|
||||
@@ -303,6 +310,9 @@ def _blocking_from_overlap(summary: dict[str, Any] | None, overlap_run: Shipping
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED',
|
||||
'conflict_profiles': list(snapshot.get('conflict_profiles') or []),
|
||||
})
|
||||
# [STEP 3] failed 但摘要未给出可映射指标时,回落为明确失败文案,禁止冒充 stale。
|
||||
if not blocking and overlap_run.status != 'passed':
|
||||
blocking.append({'key': 'overlap_validation_failed', 'message': 'Cross-template overlap validation failed.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
return blocking
|
||||
|
||||
|
||||
|
||||
@@ -75,7 +75,6 @@ from app.services.shipping_notice.order_profile_value_adapter import (
|
||||
OrderProfileValueAdapter,
|
||||
get_value_adapter,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text
|
||||
|
||||
|
||||
PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
@@ -1155,7 +1154,22 @@ def read_preview_page_region_text(
|
||||
db.session.commit()
|
||||
result = {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'}
|
||||
if data.get('purpose') == 'reservation_id_region':
|
||||
result['reservation_candidates'] = extract_reservation_from_region_text(text)
|
||||
# 画布预览候选与正式解析共用 Vendor Comments→Terms;矩形 text 仅作圈选回显。
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_region import reservation_region_candidates_from_layout
|
||||
|
||||
full_layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=_document_layout(document), page_nos=None,
|
||||
)
|
||||
scanned = reservation_region_candidates_from_layout(
|
||||
definition={'reservation_id_region': {'page_no': int(page_no), 'region': region}},
|
||||
layout=full_layout,
|
||||
)
|
||||
result['reservation_candidates'] = scanned.get('candidates') or []
|
||||
if scanned.get('reason'):
|
||||
result['reservation_region_reason'] = scanned['reason']
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
services/shipping_notice/order_document_profile_validation_service.py
|
||||
|
||||
用途:执行订单文档 Profile 草稿的不可变即时检查、当前样本试运行、版面/XFA 结构签名与跨模板唯一性验证。
|
||||
依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、Profile 保存服务及编辑租约服务。
|
||||
逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;XFA current-sample 另附脱敏字段级 Header/Line;
|
||||
签名成功后更新 Profile 轻量引用;跨模板重叠验证消费已发布快照与统一 matcher;
|
||||
查询时根据当前 checksum 派生 stale,绝不改写历史运行。
|
||||
依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、
|
||||
Profile 保存服务、编辑租约服务、Reservation 专区锚点投影。
|
||||
逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;坐标 current-sample 在表格/
|
||||
表头试读后投影 Vendor Comments Reservation;XFA current-sample 另附脱敏字段级
|
||||
Header/Line;签名成功后更新 Profile 轻量引用;查询时根据当前 checksum 派生 stale。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -344,6 +345,14 @@ def _extract_coordinate_current_sample(
|
||||
actor_id: int | None,
|
||||
) -> tuple[str, dict[str, Any], dict[str, Any]]:
|
||||
"""通过 coordinate value adapter 生成与 XFA 相同的当前样本结果 DTO。"""
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_region import (
|
||||
project_reservation_onto_validation_evidence,
|
||||
reservation_region_candidates_from_layout,
|
||||
)
|
||||
|
||||
table_id = profile_service.resolve_profile_sample_table_id(profile, sample)
|
||||
preview = profile_service.preview_profile_region(profile.id, data={
|
||||
'document_id': sample.document_id, 'table_id': table_id,
|
||||
@@ -385,11 +394,32 @@ def _extract_coordinate_current_sample(
|
||||
header_required_missing_count=len(required_header_ids - readable_header_ids),
|
||||
sample_role=sample.sample_role,
|
||||
)
|
||||
summary['validation_evidence'] = _build_coordinate_validation_evidence(
|
||||
evidence = _build_coordinate_validation_evidence(
|
||||
rows=list(rows[1:]) if isinstance(rows, list) else [],
|
||||
field_codes=list(fields or []),
|
||||
header_fields=list(header_fields),
|
||||
)
|
||||
# [STEP] Reservation 专区与正式解析共用 Vendor Comments 锚点;验证页必须展示同一结果。
|
||||
if isinstance(definition.get('reservation_id_region'), dict):
|
||||
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,
|
||||
)
|
||||
reservation = reservation_region_candidates_from_layout(definition=definition, layout=layout)
|
||||
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')
|
||||
}
|
||||
evidence = project_reservation_onto_validation_evidence(
|
||||
evidence,
|
||||
candidates=list(reservation.get('candidates') or []),
|
||||
reason=reservation.get('reason'),
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
summary['validation_evidence'] = evidence
|
||||
return status, summary, snapshot
|
||||
|
||||
|
||||
|
||||
@@ -1201,6 +1201,51 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool:
|
||||
return 'layout_pending' in order_extraction_layout_prerequisite_issues(run).values()
|
||||
|
||||
|
||||
_EXTRACT_DONE_UNIT_STATUSES = frozenset({
|
||||
'candidate_ready', 'review_required', 'failed', 'cancelled',
|
||||
})
|
||||
|
||||
|
||||
def order_extraction_ready_document_ids(run: ShippingOrderProcessingRun) -> set[int]:
|
||||
"""
|
||||
返回本 Run 快照中已通过版面前置条件、可立即抽取的订单 PDF Document ID。
|
||||
|
||||
核心逻辑:复用 order_extraction_layout_prerequisite_issues;未出现在 issues 中的 PDF
|
||||
视为 ready。非 PDF 不参与。
|
||||
"""
|
||||
issues = order_extraction_layout_prerequisite_issues(run)
|
||||
ready: set[int] = set()
|
||||
for document in _run_layout_documents(run):
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
continue
|
||||
document_id = int(document.id)
|
||||
if document_id not in issues:
|
||||
ready.add(document_id)
|
||||
return ready
|
||||
|
||||
|
||||
def order_extraction_has_extractable_ready_work(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""
|
||||
判断是否存在「版式已就绪、Unit 尚未收口」的可抽取工作。
|
||||
|
||||
核心逻辑:有 ready PDF 且(尚无 Plan / Plan 为空 → 需要建计划抽取;或存在对应
|
||||
Unit 未到 candidate_ready/review_required/failed/cancelled)。
|
||||
"""
|
||||
ready_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_ids:
|
||||
return False
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
if plan is None or int(plan.unit_count or 0) <= 0:
|
||||
return True
|
||||
units = ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all()
|
||||
for unit in units:
|
||||
if int(unit.document_id or 0) not in ready_ids:
|
||||
continue
|
||||
if str(unit.status or '') not in _EXTRACT_DONE_UNIT_STATUSES:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def order_extraction_layouts_failed(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""判断当前应消费的布局是否最终失败;历史失败版本不得污染后续成功重识别。
|
||||
|
||||
@@ -1311,17 +1356,72 @@ def schedule_order_extraction_layouts(
|
||||
|
||||
|
||||
def resume_runs_waiting_for_layout(*, document_id: int) -> int:
|
||||
"""布局任务完成后唤醒所有已具备完整布局的 Run,确保订单任务不会早于版面快照执行。"""
|
||||
"""
|
||||
单份附件布局完成后唤醒仍等待版式的 Run。
|
||||
|
||||
核心逻辑:不再要求 Run 内全部 PDF 版式就绪;只要存在可抽取的 ready Document,
|
||||
即入队(或复用活跃)shipping_order_extraction。无 ready 活且无 pending、仅有失败版式、
|
||||
且尚未抽出任何 Unit 时,整 Run 失败收口。
|
||||
"""
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
resumed = 0
|
||||
runs = ShippingOrderProcessingRun.query.filter_by(status='queued', phase='waiting_layout').with_for_update().all()
|
||||
# processing + waiting_layout:部分 Unit 已抽完、仍等兄弟文件版式。
|
||||
runs = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.status.in_(('queued', 'processing')),
|
||||
ShippingOrderProcessingRun.phase == 'waiting_layout',
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
for run in runs:
|
||||
if int(document_id) not in _run_snapshot_document_ids(run) or order_extraction_layouts_pending(run):
|
||||
if int(document_id) not in _run_snapshot_document_ids(run):
|
||||
continue
|
||||
if order_extraction_has_extractable_ready_work(run):
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no,
|
||||
created_by_id=run.user_id, max_attempts=3,
|
||||
message='附件解析完成,等待订单识别', commit=False,
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
# 仍有兄弟 layout pending 时保持 waiting_layout,便于再次 resume;
|
||||
# 已无 pending 则改为 queued,表示本轮可抽尽。
|
||||
run.phase = 'waiting_layout' if order_extraction_layouts_pending(run) else 'queued'
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='layout_parsing_completed',
|
||||
summary={'document_id': int(document_id), 'partial': order_extraction_layouts_pending(run)},
|
||||
commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
continue
|
||||
if order_extraction_layouts_pending(run):
|
||||
continue
|
||||
if order_extraction_layouts_failed(run):
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_failed')
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
progressed = False
|
||||
if plan is not None:
|
||||
progressed = any(
|
||||
str(unit.status or '') in _EXTRACT_DONE_UNIT_STATUSES
|
||||
for unit in ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all()
|
||||
)
|
||||
if progressed:
|
||||
# 已有 Unit 成功/复核:再入队一次让 Worker 收口,禁止整 Run 抹掉部分成果。
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no,
|
||||
created_by_id=run.user_id, max_attempts=3,
|
||||
message='部分附件版式失败,等待订单识别收口', commit=False,
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
run.phase = 'queued'
|
||||
resumed += 1
|
||||
continue
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED',
|
||||
@@ -1332,16 +1432,6 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED', commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
continue
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no,
|
||||
created_by_id=run.user_id, max_attempts=3, message='附件解析完成,等待订单识别', commit=False,
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
run.phase = 'queued'
|
||||
record_run_progress(run=run, event_code='layout_parsing_completed', commit=False)
|
||||
resumed += 1
|
||||
if resumed:
|
||||
db.session.commit()
|
||||
return resumed
|
||||
@@ -1355,7 +1445,8 @@ def materialize_order_extraction_run_inputs(
|
||||
|
||||
AI 触发时机:仅订单抽取 Job 开始时调用;HTTP 发送路径严禁调用。
|
||||
核心逻辑:使用创建时冻结的 Schema/附件选择和 Intake 标识,先物化首轮;
|
||||
布局任务尚未完成时只刷新 Document 快照,待布局就绪后再冻结计划。
|
||||
允许在部分 PDF 版式仍 pending 时 finalize Plan(未 ready 的 Unit 挂 pending),
|
||||
供按 Unit 流水线抽取;已存在 Plan 时只刷新各 Document 的当前布局证据。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
|
||||
@@ -2266,8 +2357,8 @@ def create_order_extraction_run(
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
# 立即建立 Job 保持 Run 的可追踪性;Handler 发现 waiting_layout 后只安全收口,
|
||||
# 绝不开始订单提取。最后一份布局完成会创建真正可执行的后继 Job。
|
||||
# 立即建立 Job 保持 Run 的可追踪性;Handler 在零 ready 时只安全收口,
|
||||
# 有 ready PDF 时按 Unit 抽取。任一布局完成即可 resume 后继 Job(无需等齐)。
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no},
|
||||
|
||||
@@ -58,7 +58,6 @@ from app.services.shipping_notice.order_profile_value_adapter import get_value_a
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
|
||||
from app.services.shipping_notice.reservation_region import (
|
||||
apply_reservation_region_candidates,
|
||||
extract_reservation_from_vendor_comments_pages,
|
||||
)
|
||||
|
||||
|
||||
@@ -1876,19 +1875,10 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfile:
|
||||
|
||||
def _reservation_region_candidates(*, raw_profile: dict[str, Any], layout: dict[str, Any]) -> dict[str, Any]:
|
||||
"""仅对已标注专区的模板,跨页读取 Vendor Comments 到首次 Terms 标题间的候选。"""
|
||||
from app.services.shipping_notice.reservation_region import reservation_region_candidates_from_layout
|
||||
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
configured = definition.get('reservation_id_region')
|
||||
if not isinstance(configured, dict):
|
||||
return {'candidates': [], 'reason': 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 = [
|
||||
(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}
|
||||
return reservation_region_candidates_from_layout(definition=definition, layout=layout)
|
||||
|
||||
|
||||
def _build_approved_profile_order_result(
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""把冻结 EML 正文补充事实保守合并到 PDF 确定性订单。
|
||||
|
||||
依赖:Run 冻结 Schema、正文补充表契约和 PO 标准化。
|
||||
逻辑:优先 PO+MPN;仅唯一 Reservation 的 PO 可降级广播,歧义只写复核原因。
|
||||
依赖:Run 冻结 Schema、正文补充表契约、PO 标准化、Reservation ID 校验。
|
||||
逻辑:优先 PO+MPN;其次同 PO+合法 reservation_id 对齐;仅唯一签名的 PO 可降级广播;
|
||||
歧义只写复核原因。reservation 对齐与「PO+料号灌预约号」同趟单次合并,不互相重入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,6 +12,7 @@ from typing import Any
|
||||
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
|
||||
from app.services.shipping_notice.po_number import normalize_atomic_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
def _values(fields: Any, code: str, codes: dict[str, str]) -> set[str]:
|
||||
@@ -51,6 +53,27 @@ def _schema_field_values(row: dict[str, Any], field_codes: set[str]) -> set[str]
|
||||
}
|
||||
|
||||
|
||||
def _validated_reservation_set(values: set[str]) -> set[str]:
|
||||
"""将原始预约号集合收成合法 5/10 位数字键;非法值不参与对齐。"""
|
||||
return {
|
||||
reservation
|
||||
for raw in values
|
||||
if (reservation := validated_reservation_id(raw))
|
||||
}
|
||||
|
||||
|
||||
def _line_reservation_values(line: dict[str, Any], ids: dict[str, str]) -> set[str]:
|
||||
"""读取 PDF 行上已抽取的合法 reservation_id 集合。"""
|
||||
return _validated_reservation_set(
|
||||
_values(line.get('fields'), 'reservation_id', {v: k for k, v in ids.items()}),
|
||||
)
|
||||
|
||||
|
||||
def _row_reservation_value(row: dict[str, Any]) -> str:
|
||||
"""读取邮件补充行的合法 reservation_id;非法或空返回空串。"""
|
||||
return validated_reservation_id(row.get('reservation_id'))
|
||||
|
||||
|
||||
def _canonical_field_value(value: Any, config: dict[str, Any]) -> Any:
|
||||
"""返回冻结 Schema 下用于跨来源比较的字段规范值,保留调用方持有的原始证据值。
|
||||
|
||||
@@ -250,7 +273,12 @@ def _supplement_multi_value_conflict(
|
||||
|
||||
|
||||
def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。"""
|
||||
"""
|
||||
按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。
|
||||
|
||||
核心逻辑:同趟单次合并,优先级为 po_mpn → po_reservation → po_fallback → mpn_fallback;
|
||||
不因写入 reservation 再重入。po_reservation 按行对齐合法预约号,用于灌入库存源线索等。
|
||||
"""
|
||||
configs = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in schema_definition.get('fields') or []
|
||||
@@ -280,6 +308,19 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
exact = [row for row in candidates if _schema_field_values(row, part_codes) & order_part_values]
|
||||
selected = exact
|
||||
relation = 'po_mpn'
|
||||
# [STEP] 料号对不上时,用 PDF 已有合法预约号与邮件行对齐(allocation 表常见 APN≠MPN)。
|
||||
if not selected and candidates:
|
||||
order_reservation_values: set[str] = set()
|
||||
for line in order.get('lines') or []:
|
||||
if isinstance(line, dict):
|
||||
order_reservation_values.update(_line_reservation_values(line, ids))
|
||||
reservation_exact = [
|
||||
row for row in candidates
|
||||
if (reservation := _row_reservation_value(row)) and reservation in order_reservation_values
|
||||
]
|
||||
if reservation_exact:
|
||||
selected = reservation_exact
|
||||
relation = 'po_reservation'
|
||||
if not selected and candidates:
|
||||
row_signatures = {tuple(str(row.get(code) or '').strip().upper() for code in configs if code not in {'customer_po_number', 'po_number'}) for row in candidates}
|
||||
if len(row_signatures) == 1:
|
||||
@@ -307,12 +348,19 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
continue
|
||||
for source_row in selected:
|
||||
row_part_values = _schema_field_values(source_row, part_codes)
|
||||
row_reservation = _row_reservation_value(source_row)
|
||||
indexed_target_lines = [
|
||||
(index, line)
|
||||
for index, line in enumerate(order.get('lines') or [])
|
||||
if isinstance(line, dict)
|
||||
]
|
||||
if relation != 'po_fallback':
|
||||
if relation == 'po_reservation':
|
||||
# 预约号精确命中只写入同 reservation 的 PDF 行,禁止跨行广播多站点线索。
|
||||
indexed_target_lines = [
|
||||
(index, line) for index, line in indexed_target_lines
|
||||
if row_reservation and row_reservation in _line_reservation_values(line, ids)
|
||||
]
|
||||
elif relation != 'po_fallback':
|
||||
# 精确料号命中(含 PN/AMPN × 内部/客户料号四种组合)只写入交集行。
|
||||
indexed_target_lines = [
|
||||
(index, line) for index, line in indexed_target_lines
|
||||
@@ -324,7 +372,6 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
if not indexed_target_lines:
|
||||
order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'})
|
||||
continue
|
||||
target_lines = [line for _, line in indexed_target_lines]
|
||||
for target_code, config in configs.items():
|
||||
target_groups = (
|
||||
[(-1, order.get('header_fields'))]
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
Reservation ID 专用证据区域解析器。
|
||||
|
||||
用途:从管理员圈选的 Vendor Comments 区域提取 Reservation ID 和可选行号。
|
||||
依赖:reservation_id 的统一格式校验。
|
||||
逻辑:只消费区域文字,不依赖客户名称、固定坐标或旧的三来源映射;无行号仅标记为未归属,最终由 Schema scope 决定表头写入或明细复核。
|
||||
用途:从已启用的 Vendor Comments→Terms 锚点窗提取 Reservation ID 与可选行号,
|
||||
并投影到验证证据 / 订单归属契约。
|
||||
依赖:reservation_id 格式校验、coordinate_region_text 视觉行序。
|
||||
逻辑:reservation_id_region 仅作启用标记;画布预览、盲测、正式解析共用本模块的
|
||||
锚点扫描与 apply/project,不再按保存矩形截取正式值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,8 +21,11 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
_ID_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)")
|
||||
_LINE_RE = re.compile(r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b|\bfor\s+line\s*#?\s*(\d+)\b", 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?\s*:?\s*$', re.I)
|
||||
_TERMS_AND_CONDITIONS_HEADING_RE = re.compile(r'^\s*terms?\s+and\s+conditions?\s*:?\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)
|
||||
@@ -86,22 +91,147 @@ def extract_reservation_from_vendor_comments_pages(
|
||||
"""从跨页 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.fullmatch(line):
|
||||
if _VENDOR_COMMENTS_HEADING_RE.match(line):
|
||||
started = True
|
||||
continue
|
||||
if _TERMS_AND_CONDITIONS_HEADING_RE.fullmatch(line):
|
||||
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 [], 'terms_and_conditions_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']),
|
||||
)
|
||||
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 apply_reservation_region_candidates(
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""验证 EML 正文补充表的确定性解析、关联和数量保护。
|
||||
|
||||
依赖:正文补充解析器与合并服务。
|
||||
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威,歧义稳定进入复核。
|
||||
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威;关联优先 PO+料号,
|
||||
其次 PO+预约号,歧义稳定进入复核。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -345,6 +346,81 @@ def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_po_reservation_injects_hint_when_parts_do_not_match():
|
||||
"""同 PO 下 PDF 已有预约号、邮件仅 APN 不对料号时,按 reservation 对齐灌入库存源线索。
|
||||
|
||||
回归:AWS allocation 表 Component APN 对不上 Wistron MPN 时,不得因缺 po_mpn
|
||||
把多行 VMI-* 线索整单丢掉。
|
||||
"""
|
||||
order = {
|
||||
'_hxops_intake_id': 1,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': '16776707'}]}],
|
||||
'lines': [
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000002'}]},
|
||||
{'field_id': 'reservation', 'observations': [{'value': '2000484577'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 30}]},
|
||||
]},
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]},
|
||||
{'field_id': 'reservation', 'observations': [{'value': '2000484578'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 24}]},
|
||||
]},
|
||||
],
|
||||
'conflicts': [],
|
||||
}
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{
|
||||
'customer_po_number': '16776707',
|
||||
'part_number': '504-006055-001',
|
||||
'reservation_id': '2000484577',
|
||||
'inventory_source_hint': 'VMI-RTM01',
|
||||
'evidence': {'inventory_source_hint': {'raw_value': 'VMI-RTM01'}},
|
||||
},
|
||||
{
|
||||
'customer_po_number': '16776707',
|
||||
'part_number': '504-006056-001',
|
||||
'reservation_id': '2000484578',
|
||||
'inventory_source_hint': 'VMI-DUB',
|
||||
'evidence': {'inventory_source_hint': {'raw_value': 'VMI-DUB'}},
|
||||
},
|
||||
],
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
# 关键断言:关联码为 po_reservation;两行分别灌入对应线索,数量不被覆盖。
|
||||
assert merged['_hxops_email_supplement_relation'] == 'po_reservation'
|
||||
assert _value(merged['lines'][0]['fields'], 'source') == 'VMI-RTM01'
|
||||
assert _value(merged['lines'][1]['fields'], 'source') == 'VMI-DUB'
|
||||
assert _value(merged['lines'][0]['fields'], 'qty') == 30
|
||||
assert _value(merged['lines'][1]['fields'], 'qty') == 24
|
||||
assert not any(item.get('reason') == 'supplement_relation_ambiguous' for item in merged['conflicts'])
|
||||
|
||||
|
||||
def test_email_supplement_po_mpn_still_preferred_over_po_reservation():
|
||||
"""料号能精确命中时仍走 po_mpn,不得因两边都有预约号改走 reservation 档。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'reservation', 'observations': [{'value': '2000484577'}],
|
||||
})
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'customer_po_number': '4518738152',
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577',
|
||||
'inventory_source_hint': 'DSB CMH',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert merged['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
assert _value(merged['lines'][0]['fields'], 'source') == 'DSB CMH'
|
||||
|
||||
|
||||
def test_email_supplement_po_fallback_writes_unique_reservation_without_part_match():
|
||||
"""唯一 PO 兜底不得在写入阶段重新要求邮件料号匹配。"""
|
||||
result = merge_email_supplements(
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
inventory RPA:Playwright Download.save_as 因浏览器关闭失败时,应按 downloads_path 目录兜底落盘。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _load_worker():
|
||||
module_path = (
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
)
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
sys.path.insert(0, scripts_dir)
|
||||
# common/ 需可 import download_artifact_fallback
|
||||
common_dir = str(module_path.parent.parent / "common")
|
||||
if common_dir not in sys.path:
|
||||
sys.path.insert(0, common_dir)
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_save_fallback_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class _ClosedBrowserDownload:
|
||||
"""模拟 Playwright Download:save_as 时浏览器已关闭。"""
|
||||
|
||||
suggested_filename = "OnHandInventory.xlsx"
|
||||
|
||||
def save_as(self, dest: str) -> None:
|
||||
raise RuntimeError("Download.save_as: Target page, context or browser has been closed")
|
||||
|
||||
|
||||
def test_save_batch_download_falls_back_when_browser_closed(monkeypatch):
|
||||
"""save_as 因浏览器关闭失败、目录已有稳定 xlsx 时,应改名落盘并返回规范路径。"""
|
||||
worker = _load_worker()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
drop_dir = Path(tmp) / "drop"
|
||||
drop_dir.mkdir()
|
||||
(drop_dir / "noise.txt").write_text("old", encoding="utf-8")
|
||||
landed = drop_dir / "chromium_download.xlsx"
|
||||
landed.write_bytes(b"PK" + b"0" * 600)
|
||||
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
|
||||
out = worker._save_batch_download(
|
||||
_ClosedBrowserDownload(),
|
||||
drop_dir,
|
||||
"BATCH-RUN-1",
|
||||
{"source_code": "DSV360_AWSSG", "warehouse_id": "AWSSG"},
|
||||
baseline_names={"noise.txt"},
|
||||
)
|
||||
|
||||
assert out.exists()
|
||||
assert out.parent == drop_dir
|
||||
assert "DSV360_AWSSG" in out.name
|
||||
assert "AWSSG" in out.name
|
||||
assert out.suffix == ".xlsx"
|
||||
assert not landed.exists()
|
||||
|
||||
|
||||
def test_save_batch_download_reraises_when_fallback_missing(monkeypatch):
|
||||
"""浏览器关闭且目录无新文件时,应继续抛出原 save_as 错误。"""
|
||||
worker = _load_worker()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
drop_dir = Path(tmp) / "drop"
|
||||
drop_dir.mkdir()
|
||||
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_wait_for_new_download_file",
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
try:
|
||||
worker._save_batch_download(
|
||||
_ClosedBrowserDownload(),
|
||||
drop_dir,
|
||||
"BATCH-RUN-2",
|
||||
{"source_code": "DSV360_AWSSG", "warehouse_id": "AWSSG"},
|
||||
baseline_names=set(),
|
||||
fallback_timeout_seconds=0.1,
|
||||
)
|
||||
raise AssertionError("expected RuntimeError")
|
||||
except RuntimeError as exc:
|
||||
# 断言:错误信息仍指向浏览器关闭,避免被吞成模糊失败
|
||||
assert "has been closed" in str(exc).lower()
|
||||
|
||||
|
||||
def test_save_download_falls_back_when_browser_closed(monkeypatch):
|
||||
"""单票路径同样在 save_as 浏览器关闭后走目录兜底。"""
|
||||
worker = _load_worker()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
drop_dir = Path(tmp) / "drop"
|
||||
drop_dir.mkdir()
|
||||
landed = drop_dir / "raw.xlsx"
|
||||
landed.write_bytes(b"PK" + b"0" * 600)
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
|
||||
out = worker._save_download(
|
||||
_ClosedBrowserDownload(),
|
||||
drop_dir,
|
||||
"OT-1",
|
||||
"DSV360_AWSSG",
|
||||
baseline_names=set(),
|
||||
)
|
||||
|
||||
assert out.exists()
|
||||
assert "DSV360_AWSSG" in out.name
|
||||
assert not landed.exists()
|
||||
@@ -14,6 +14,7 @@ from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileValidationRun,
|
||||
User,
|
||||
)
|
||||
@@ -196,12 +197,19 @@ def test_report_ignores_submitted_pre_hydration_signature(app, monkeypatch):
|
||||
|
||||
|
||||
def test_report_blocks_when_overlap_failed(app, monkeypatch):
|
||||
"""关键断言:重叠验证 failed 时报告写入 overlap 阻断项与 conflict 引用。"""
|
||||
"""关键断言:当前草稿上的 overlap failed 展开真实门禁,不得误报 overlap_validation_stale。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
|
||||
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-overlap-create')
|
||||
lease = _lease(draft['id']); run = _passing_run(draft); _signature_run(draft)
|
||||
failed_overlap = _overlap_run(draft, status='failed')
|
||||
failed_overlap.summary_json = {
|
||||
**dict(failed_overlap.summary_json or {}),
|
||||
'self_unique_hit_rate_training': 0.0,
|
||||
'training_sample_count': 2,
|
||||
'blind_sample_count': 0,
|
||||
}
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
validation_service, 'run_cross_template_overlap',
|
||||
lambda *args, **kwargs: {'id': failed_overlap.id, 'status': 'failed', 'stored_status': 'failed'},
|
||||
@@ -211,10 +219,37 @@ def test_report_blocks_when_overlap_failed(app, monkeypatch):
|
||||
actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-overlap-report',
|
||||
)
|
||||
keys = {str(item.get('key')) for item in report['blocking_items']}
|
||||
assert 'overlap_validation_stale' in keys or 'overlap_validation_required' in keys or 'self_match_not_unique' in keys
|
||||
assert 'self_match_not_unique' in keys
|
||||
assert 'overlap_validation_stale' not in keys
|
||||
assert report['overlap_validation_run_id'] == failed_overlap.id
|
||||
|
||||
|
||||
def test_blocking_from_overlap_marks_stale_only_on_checksum_drift(app):
|
||||
"""关键断言:仅 definition_checksum 漂移才标 stale;同 checksum 的 failed 展开指标。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-stale-vs-failed')
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=draft['id'], revision_no=draft['draft_revision']['revision_no'],
|
||||
).one()
|
||||
stale_run = _overlap_run(draft, status='passed')
|
||||
stale_run.definition_checksum = 'not-current-checksum'
|
||||
db.session.commit()
|
||||
stale_keys = {item['key'] for item in checks._blocking_from_overlap(None, stale_run, revision)}
|
||||
assert stale_keys == {'overlap_validation_stale'}
|
||||
|
||||
failed_run = _overlap_run(draft, status='failed')
|
||||
failed_run.summary_json = {
|
||||
**dict(failed_run.summary_json or {}),
|
||||
'self_unique_hit_rate_training': 0.0,
|
||||
'training_sample_count': 1,
|
||||
}
|
||||
db.session.commit()
|
||||
failed_keys = {item['key'] for item in checks._blocking_from_overlap(dict(failed_run.summary_json), failed_run, revision)}
|
||||
assert 'self_match_not_unique' in failed_keys
|
||||
assert 'overlap_validation_stale' not in failed_keys
|
||||
|
||||
|
||||
def test_report_invalidates_when_signature_cleared(app, monkeypatch):
|
||||
"""关键断言:草稿签名引用清空后既有报告查询即 invalidated。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -160,13 +160,22 @@ def test_profile_without_reservation_region_does_not_scan_vendor_comments():
|
||||
|
||||
|
||||
def test_enabled_reservation_region_requires_review_when_terms_heading_is_missing():
|
||||
"""专区缺少结束锚点时,不得把未封闭文本区的值当成可自动建单证据。"""
|
||||
"""专区缺少结束锚点时,窗内候选可展示/归属,但订单必须标 needs_review。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]},
|
||||
reservation_region_candidates=[{
|
||||
'value': '1000143920', 'scope': 'line', 'line_no': 1,
|
||||
'raw_text': 'DBS Reservation Line 1: 1000143920', 'status': 'mapped',
|
||||
}],
|
||||
reservation_region_reason='terms_and_conditions_anchor_missing',
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
|
||||
assert (orders or [])[0]['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing']
|
||||
order = (orders or [])[0]
|
||||
assert order['reservation_region_status'] == 'needs_review'
|
||||
assert order['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing']
|
||||
assert any(
|
||||
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == '1000143920'
|
||||
for item in order['lines'][0]['fields']
|
||||
)
|
||||
@@ -1717,3 +1717,37 @@ def test_table_region_profile_freezes_confirmed_visual_geometry_source_only():
|
||||
}).visual_evidence_source == 'acroform_widget_geometry'
|
||||
with pytest.raises(ValueError, match='visual_evidence_source'):
|
||||
TableRegionProfile.model_validate({**payload, 'visual_evidence_source': 'xfa_dataset'})
|
||||
|
||||
|
||||
def test_strategy_needs_review_still_returns_best_effort_rows_for_display(monkeypatch):
|
||||
"""策略需复核时仍返回最佳努力明细,盲测/验证才能展示,不能整表吞掉。"""
|
||||
from app.services.shipping_notice.document_layout import runtime_parse_strategy as strategy_module
|
||||
from app.services.shipping_notice.document_layout.runtime_parse_strategy import RuntimeParseStrategy
|
||||
|
||||
def _force_review(**_kwargs):
|
||||
return RuntimeParseStrategy('needs_review', (1,), None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',))
|
||||
|
||||
monkeypatch.setattr(strategy_module, 'resolve_runtime_parse_strategy', _force_review)
|
||||
rows, strategy = reconstruct_coordinate_profile_rows_with_strategy(
|
||||
characters=_glyphs(
|
||||
[('1', 10), ('PART-A', 80)],
|
||||
[('2', 10), ('PART-B', 80)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
line_layouts=[{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
],
|
||||
}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
)
|
||||
|
||||
assert strategy.status == 'needs_review'
|
||||
assert [row.fields for row in rows] == [
|
||||
{'customer_po_line_no': '1', 'part_number': 'PART-A'},
|
||||
{'customer_po_line_no': '2', 'part_number': 'PART-B'},
|
||||
]
|
||||
@@ -710,6 +710,59 @@ def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app):
|
||||
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_coordinate_blind_candidate_keeps_rows_when_strategy_needs_review(app, monkeypatch):
|
||||
"""关键断言:策略需复核时盲测预览仍展示最佳努力明细,不能整表吞掉。"""
|
||||
from app.services.shipping_notice.document_layout.runtime_parse_strategy import RuntimeParseStrategy
|
||||
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
profile.definition_json = {
|
||||
'document_match': {'required_anchors': []},
|
||||
'table_regions': [{
|
||||
'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
||||
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
}],
|
||||
}], 'order_field_layouts': [],
|
||||
}
|
||||
glyphs = [
|
||||
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}}
|
||||
for index, char in enumerate('20')
|
||||
] + [
|
||||
{'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}}
|
||||
for index, char in enumerate('PART-A')
|
||||
]
|
||||
record_inline_layout_snapshot(documents[1], {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
||||
'coordinate_evidence': {
|
||||
'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
def _force_review(**_kwargs):
|
||||
return RuntimeParseStrategy('needs_review', (1,), None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',))
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.runtime_parse_strategy.resolve_runtime_parse_strategy',
|
||||
_force_review,
|
||||
)
|
||||
candidate = quality._candidate_for_sample(
|
||||
profile=profile, document_id=documents[1].id, table_id='table-1',
|
||||
)
|
||||
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -2409,7 +2409,7 @@ def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch,
|
||||
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
|
||||
)
|
||||
|
||||
def _fake_link(actual_task, inv_file, *, reason, role='member', audit_payload=None):
|
||||
def _fake_link(actual_task, inv_file, *, reason, audit_payload=None):
|
||||
call_order.append(f'link:{reason}')
|
||||
assert actual_task is task
|
||||
assert inv_file is snapshot
|
||||
@@ -2424,7 +2424,7 @@ def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch,
|
||||
return {'status': 'ok', 'message': 'linked-and-loaded'}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation',
|
||||
_fake_link,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -2495,7 +2495,7 @@ def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app):
|
||||
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation',
|
||||
lambda *_a, **_k: None,
|
||||
)
|
||||
|
||||
@@ -2516,3 +2516,85 @@ def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app):
|
||||
|
||||
assert result['status'] == 'needs_human'
|
||||
assert result['data']['blocking_reason']['code'] == 'inventory_file_missing'
|
||||
|
||||
|
||||
def test_stp_candidate_ready_uses_preparation_link_when_warehouse_pending(monkeypatch, app):
|
||||
"""[断言] 动态仓未决时 preparation 软绑定仍推进,不得投影 inventory_file_missing。"""
|
||||
from app.services.shipping_notice import inventory_workflow
|
||||
|
||||
task = SimpleNamespace(
|
||||
task_no='OT-STP-SOFT-LINK',
|
||||
id=703,
|
||||
inventory_lines_json=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
active_inventory_candidate_set_id=11,
|
||||
)
|
||||
snapshot = SimpleNamespace(inventory_file_no='INV-WH-PENDING', source_code='CRANE', warehouse_id=None)
|
||||
call_order: list[str] = []
|
||||
|
||||
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
|
||||
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {})
|
||||
monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs)
|
||||
monkeypatch.setattr(inventory_workflow.db.session, 'flush', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['CRANE'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
|
||||
lambda _task: {
|
||||
'status': 'ready',
|
||||
'candidate_set_id': 11,
|
||||
'lines': [{'part_number': 'P1', '__source_code': 'CRANE', '__inventory_file_no': 'INV-WH-PENDING'}],
|
||||
'missing_source_codes': [],
|
||||
'loaded_source_codes': ['CRANE'],
|
||||
'evidence': [{
|
||||
'source_code': 'CRANE',
|
||||
'status': 'loaded',
|
||||
'inventory_file_no': 'INV-WH-PENDING',
|
||||
'line_count': 1,
|
||||
'required': True,
|
||||
}],
|
||||
'required_source_codes': ['CRANE'],
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ShippingInventoryFile,
|
||||
'query',
|
||||
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
|
||||
)
|
||||
|
||||
def _fake_prep_link(actual_task, inv_file, *, reason, audit_payload=None):
|
||||
call_order.append(f'prep:{reason}')
|
||||
assert reason == 'stp_candidate_prep'
|
||||
assert inv_file is snapshot
|
||||
return SimpleNamespace(id=99, identity_check_status='pending_matching')
|
||||
|
||||
def _fake_loaded(actual_task, lines, **kwargs):
|
||||
call_order.append('loaded')
|
||||
assert kwargs.get('persist_lines') is False
|
||||
return {'status': 'ok', 'message': 'soft-linked'}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation',
|
||||
_fake_prep_link,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response',
|
||||
_fake_loaded,
|
||||
)
|
||||
monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _fake_loaded)
|
||||
|
||||
result = inventory_workflow.ensure_inventory({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'auto',
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
})
|
||||
|
||||
assert result['status'] == 'ok'
|
||||
assert call_order == ['prep:stp_candidate_prep', 'loaded']
|
||||
@@ -8,6 +8,8 @@ from app.services.shipping_notice.reservation_region import (
|
||||
apply_reservation_region_candidates,
|
||||
extract_reservation_from_region_text,
|
||||
extract_reservation_from_vendor_comments_pages,
|
||||
project_reservation_onto_validation_evidence,
|
||||
reservation_region_candidates_from_layout,
|
||||
)
|
||||
|
||||
|
||||
@@ -106,8 +108,23 @@ def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading()
|
||||
assert [item['value'] for item in candidates] == ['33008', '3000098851']
|
||||
|
||||
|
||||
def test_terms_heading_matches_when_phrase_is_only_part_of_title():
|
||||
"""结束锚点只需标题含 Terms and Conditions,不要求整行仅有该短语。"""
|
||||
candidates, reason = extract_reservation_from_vendor_comments_pages([
|
||||
(1, _glyph_lines(
|
||||
'Vendor Comments',
|
||||
'DBS Reservation Line 1: 1000143920',
|
||||
'7. Terms and Conditions of Sale',
|
||||
'Reservation#99999',
|
||||
)),
|
||||
])
|
||||
|
||||
assert reason is None
|
||||
assert [item['value'] for item in candidates] == ['1000143920']
|
||||
|
||||
|
||||
def test_vendor_comments_window_requires_start_and_end_headings():
|
||||
"""缺少任一边界时不能把全文中的 Reservation 当作专区证据。"""
|
||||
"""缺少起始锚点时不得扫描全文;缺少结束锚点时仍返回窗内候选但必须带复核原因。"""
|
||||
candidates, reason = extract_reservation_from_vendor_comments_pages([
|
||||
(1, _glyph_lines('Reservation#33008')),
|
||||
])
|
||||
@@ -115,6 +132,18 @@ def test_vendor_comments_window_requires_start_and_end_headings():
|
||||
assert candidates == []
|
||||
assert reason == 'vendor_comments_anchor_missing'
|
||||
|
||||
open_candidates, open_reason = extract_reservation_from_vendor_comments_pages([
|
||||
(1, _glyph_lines(
|
||||
'Vendor Comments:',
|
||||
'DBS Reservation Line 1: 1000143920',
|
||||
'End Customer: D1',
|
||||
)),
|
||||
])
|
||||
assert open_reason == 'terms_and_conditions_anchor_missing'
|
||||
assert [item['value'] for item in open_candidates] == ['1000143920']
|
||||
assert open_candidates[0]['scope'] == 'line'
|
||||
assert open_candidates[0]['line_no'] == 1
|
||||
|
||||
|
||||
def test_reservation_region_applies_header_and_line_override_together():
|
||||
"""整单值是默认值,指定行的 Reservation 仅覆盖对应明细。"""
|
||||
@@ -165,3 +194,71 @@ def test_reservation_gate_blocks_empty_and_malformed_order_lines():
|
||||
|
||||
assert reservation_gate_issues([])[0]["reason"] == "missing_order_lines"
|
||||
assert reservation_gate_issues(["invalid-line"])[0]["reason"] == "invalid_order_line"
|
||||
|
||||
|
||||
def test_reservation_region_candidates_from_layout_requires_configured_region():
|
||||
"""未标注专区时不得扫描 Vendor Comments;标注后必须走锚点窗而非 page_no/region。"""
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 800, 'height': 600}},
|
||||
'page_glyphs': {
|
||||
'1': _glyph_lines(
|
||||
'Vendor Comments:',
|
||||
'DBS Reservation Line 1: 1000143920',
|
||||
'Terms and Conditions:',
|
||||
),
|
||||
},
|
||||
},
|
||||
}
|
||||
assert reservation_region_candidates_from_layout(definition={}, layout=layout) == {
|
||||
'candidates': [], 'reason': None,
|
||||
}
|
||||
result = reservation_region_candidates_from_layout(
|
||||
definition={'reservation_id_region': {'page_no': 9, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}}},
|
||||
layout=layout,
|
||||
)
|
||||
assert result['reason'] is None
|
||||
assert [item['value'] for item in result['candidates']] == ['1000143920']
|
||||
assert result['candidates'][0]['scope'] == 'line'
|
||||
assert result['candidates'][0]['line_no'] == 1
|
||||
|
||||
|
||||
def test_project_reservation_onto_validation_evidence_writes_line_and_review_reason():
|
||||
"""验证证据必须落入与正式解析相同的 header/line 字段,并保留锚点缺失原因。"""
|
||||
evidence = {
|
||||
'header_fields': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_number', 'raw_value': 'PO-1',
|
||||
'normalized_value': 'PO-1', 'status': 'passed', 'issues': [],
|
||||
}],
|
||||
'lines': [{'row_index': 0, 'fields': [{
|
||||
'field_id': 'f-part', 'field_code': 'part_number', 'raw_value': 'P-1',
|
||||
'normalized_value': 'P-1', 'status': 'passed', 'issues': [],
|
||||
}]}],
|
||||
'cross_checks': {},
|
||||
}
|
||||
projected = project_reservation_onto_validation_evidence(
|
||||
evidence,
|
||||
candidates=[{
|
||||
'value': '1000143920', 'line_no': 1, 'scope': 'line',
|
||||
'raw_text': 'DBS Reservation Line 1: 1000143920', 'status': 'mapped',
|
||||
}],
|
||||
reason=None,
|
||||
schema_fields={
|
||||
'header-reservation': {
|
||||
'field_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header',
|
||||
},
|
||||
'line-reservation': {
|
||||
'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
},
|
||||
},
|
||||
)
|
||||
assert projected['lines'][0]['fields'][-1] == {
|
||||
'field_id': 'line-reservation', 'field_code': 'reservation_id',
|
||||
'raw_value': '1000143920', 'normalized_value': '1000143920',
|
||||
'status': 'passed', 'issues': [],
|
||||
}
|
||||
missing = project_reservation_onto_validation_evidence(
|
||||
evidence, candidates=[], reason='vendor_comments_anchor_missing', schema_fields={},
|
||||
)
|
||||
assert missing['reservation_region_status'] == 'needs_review'
|
||||
assert missing['reservation_region_review_reasons'] == ['vendor_comments_anchor_missing']
|
||||
@@ -676,7 +676,7 @@ def test_create_run_scopes_to_selected_intakes_only(app):
|
||||
|
||||
@pytest.mark.parametrize('layout_status', ['queued', 'running'])
|
||||
def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction(app, layout_status):
|
||||
"""发送后必须先完成版面解析;订单 Job 不得与布局 Job 并行抢跑。"""
|
||||
"""发送后若 PDF 版式仍在进行,Run 进入 waiting_layout;不得对未 ready 的 PDF 抽取。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, document = _seed_run_input(suffix=f'LAYOUT-{layout_status.upper()}')
|
||||
@@ -750,14 +750,14 @@ def test_create_run_accepts_a_reused_layout_from_an_identical_document(app):
|
||||
assert run.status == 'queued'
|
||||
|
||||
|
||||
def test_last_layout_completion_enqueues_waiting_run_once(app):
|
||||
"""最后一份附件布局完成才唤醒 Run,提前完成其中一份不能启动订单提取。"""
|
||||
def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app):
|
||||
"""任一份附件布局完成即可唤醒 Run;无需等齐全部版式。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='WAIT-ALL')
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='WAIT-PARTIAL')
|
||||
second = ShippingOrderDocument(
|
||||
intake_id=intake.id, asset_id=first.asset_id, document_type='attachment',
|
||||
attachment_key='orders-WAIT-ALL-2.pdf', filename='orders-WAIT-ALL-2.pdf',
|
||||
attachment_key='orders-WAIT-PARTIAL-2.pdf', filename='orders-WAIT-PARTIAL-2.pdf',
|
||||
content_hash='b' * 64, classification='order_notice', parse_status='parsed', extracted_text='PO 2',
|
||||
)
|
||||
db.session.add(second)
|
||||
@@ -770,12 +770,28 @@ def test_last_layout_completion_enqueues_waiting_run_once(app):
|
||||
ShippingDocumentLayoutVersion.document_id.in_([first.id, second.id]),
|
||||
).all()
|
||||
assert len(layouts) == 2
|
||||
ready_payload = {
|
||||
'status': 'ready',
|
||||
'layout_candidate': {},
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
},
|
||||
}
|
||||
layouts[0].status = 'ready'
|
||||
layouts[0].payload_json = dict(ready_payload)
|
||||
first.current_layout_version_id = layouts[0].id
|
||||
db.session.commit()
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 0
|
||||
assert db.session.get(Job, run.current_job_id) is not None
|
||||
# 关键断言:第一份 ready 即可 resume(活跃 Job 去重仍只保留一条 extraction)。
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 1
|
||||
db.session.refresh(run)
|
||||
first_job_id = run.current_job_id
|
||||
assert db.session.get(Job, first_job_id) is not None
|
||||
assert run.phase == 'waiting_layout'
|
||||
|
||||
layouts[1].status = 'ready'
|
||||
layouts[1].payload_json = dict(ready_payload)
|
||||
second.current_layout_version_id = layouts[1].id
|
||||
db.session.commit()
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[1].document_id) == 1
|
||||
db.session.refresh(run)
|
||||
|
||||
@@ -67,6 +67,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
monkeypatch.setattr(handler, 'materialize_order_extraction_run_inputs', fake_materialize)
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda _run, *, created_by_id: events.append('schedule') or False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {1})
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: events.append('units') or [])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda _plan, *, after_batch: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda _run, _plan: [])
|
||||
@@ -113,6 +114,7 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
lambda _run, *, created_by_id: events.append('schedule') or True,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {357: 'layout_pending'})
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: set())
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('waiting'))
|
||||
def fake_finish_job(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
@@ -134,6 +136,116 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
assert finished['message'] == '已转交附件版面解析,完成后自动创建后继订单识别任务'
|
||||
|
||||
|
||||
def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(monkeypatch):
|
||||
"""部分 PDF 版式就绪时只抽 ready Unit,Job 以 partial_units_done 收口且不终态 Run。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
finished: dict = {}
|
||||
run = SimpleNamespace(
|
||||
id=4, user_id=9, run_no='SNER-WORKER-PARTIAL', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
|
||||
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
|
||||
execution_result_json=None, extraction_completed_at=None,
|
||||
)
|
||||
job = SimpleNamespace(id=4, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
ready_unit = SimpleNamespace(
|
||||
id=41, document_id=101, intake_id=1, status='pending', result_json=None, position=1,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
pending_unit = SimpleNamespace(
|
||||
id=42, document_id=102, intake_id=1, status='pending', result_json=None, position=2,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
plan = SimpleNamespace(id=4, unit_count=2, units=[ready_unit, pending_unit])
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else ready_unit)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderProcessingRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
status=SimpleNamespace(in_=lambda *_a, **_k: True),
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: [ready_unit, pending_unit]),
|
||||
),
|
||||
),
|
||||
))
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
|
||||
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: events.append('freeze_begin'))
|
||||
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: events.append('freeze_complete'))
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: events.append('finalize' if finalize_plan else 'materialize') or (plan if finalize_plan else None),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: events.append('schedule') or False)
|
||||
monkeypatch.setattr(
|
||||
handler, 'order_extraction_layout_prerequisite_issues',
|
||||
lambda _run: {102: 'layout_pending'},
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {101})
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [ready_unit, pending_unit])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
|
||||
|
||||
def _fake_transition(unit, *, target_status, **_kwargs):
|
||||
unit.status = target_status
|
||||
events.append(f'transition:{target_status}')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
|
||||
_fake_transition,
|
||||
)
|
||||
|
||||
def _process(**_kwargs):
|
||||
events.append('processed')
|
||||
ready_unit.status = 'merging_supplement'
|
||||
return [{'po_number': 'PO-1', '_hxops_intake_id': 1}]
|
||||
|
||||
monkeypatch.setattr(handler, '_process_unit_with_retries', _process)
|
||||
monkeypatch.setattr(
|
||||
handler, 'merge_unit_orders',
|
||||
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {})
|
||||
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
|
||||
|
||||
def fake_finish(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
finished.update(kwargs)
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', fake_finish)
|
||||
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)
|
||||
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 4})
|
||||
|
||||
assert 'processed' in events
|
||||
assert 'progressed' in events
|
||||
assert 'terminalized' not in events
|
||||
assert 'persist_started' not in events
|
||||
assert run.phase == 'waiting_layout'
|
||||
assert run.status == 'processing'
|
||||
assert finished['result']['handoff_status'] == 'partial_units_done'
|
||||
assert finished['result']['waiting_layout'] is True
|
||||
|
||||
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user