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(
|
||||
|
||||
Reference in new issue
Block a user