feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3a9fbac2fc
commit
d2b3d74def
571 files changed
+78064
-24681
No files matched your search
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_document_layout.py
|
||||
|
||||
用途:独立执行单份 ShippingNoticeDocument 的 MinerU 布局解析任务。
|
||||
用途:独立执行单份 ShippingOrderDocument 的 MinerU 布局解析任务。
|
||||
依赖:Layout lifecycle/runtime、FileAsset、通用 Job queue、audit_service、workflow_ledger(尽力引用)。
|
||||
逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本;
|
||||
起止与异常轻量写统一审计(若能定位 WorkflowItem 则带软引用)。
|
||||
@@ -144,13 +144,75 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
if job.started_at and job.created_at else 0,
|
||||
'asset_read_ms': round((perf_counter() - asset_started) * 1000),
|
||||
}
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename=str(document.filename or asset.original_filename or 'document.pdf'),
|
||||
content=content,
|
||||
document_id=document.id,
|
||||
content_hash=document.content_hash,
|
||||
timings=timings,
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import (
|
||||
analyze_xfa_pdf,
|
||||
persist_xfa_structure_analysis,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import default_xfa_resource_limits
|
||||
|
||||
xfa_started = perf_counter()
|
||||
xfa_outcome = None
|
||||
if str(document.filename or '').lower().endswith('.pdf') and content.startswith(b'%PDF'):
|
||||
_layout_job_audit(
|
||||
event_type='xfa_parse_started',
|
||||
job=job,
|
||||
version=version,
|
||||
metadata={'document_id': int(document.id)},
|
||||
)
|
||||
xfa_outcome = analyze_xfa_pdf(content, limits=default_xfa_resource_limits())
|
||||
timings['xfa_analysis_ms'] = round((perf_counter() - xfa_started) * 1000)
|
||||
|
||||
snapshot = None
|
||||
if (
|
||||
xfa_outcome is not None
|
||||
and xfa_outcome.packet_result is not None
|
||||
and xfa_outcome.packet_result.document_kind not in {'plain_pdf', 'acroform'}
|
||||
):
|
||||
snapshot = dict(xfa_outcome.snapshot)
|
||||
persist_xfa_structure_analysis(
|
||||
document_id=int(document.id),
|
||||
layout_version_id=int(version.id),
|
||||
source_content_hash=str(document.content_hash or ''),
|
||||
outcome=xfa_outcome,
|
||||
)
|
||||
if xfa_outcome.error_code == 'XFA_UNSAFE_XML':
|
||||
_layout_job_audit(
|
||||
event_type='xfa_parse_rejected_unsafe',
|
||||
job=job,
|
||||
version=version,
|
||||
result='failure',
|
||||
error_code=xfa_outcome.error_code,
|
||||
)
|
||||
elif snapshot.get('status') == 'ready':
|
||||
_layout_job_audit(
|
||||
event_type='xfa_structure_analysis_ready',
|
||||
job=job,
|
||||
version=version,
|
||||
metadata={
|
||||
'document_kind': snapshot.get('document_kind'),
|
||||
'structure_analysis_id': (
|
||||
(snapshot.get('xfa_capability') or {}).get('structure_analysis_id')
|
||||
),
|
||||
},
|
||||
)
|
||||
_layout_job_audit(event_type='xfa_parse_completed', job=job, version=version)
|
||||
else:
|
||||
_layout_job_audit(
|
||||
event_type='xfa_parse_failed',
|
||||
job=job,
|
||||
version=version,
|
||||
result='failure',
|
||||
error_code=xfa_outcome.error_code,
|
||||
metadata={'route_reason': xfa_outcome.route_reason},
|
||||
)
|
||||
if snapshot is None:
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename=str(document.filename or asset.original_filename or 'document.pdf'),
|
||||
content=content,
|
||||
document_id=document.id,
|
||||
content_hash=document.content_hash,
|
||||
timings=timings,
|
||||
)
|
||||
timings['snapshot_build_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
if snapshot is None:
|
||||
snapshot = {
|
||||
@@ -170,7 +232,8 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
finish_job(
|
||||
job.id, result={
|
||||
'status': str(snapshot.get('status') or 'failed'),
|
||||
'status': final_status,
|
||||
'provider_status': str(snapshot.get('status') or 'failed'),
|
||||
'timings': {key: int(value) for key, value in timings.items()},
|
||||
},
|
||||
message=(
|
||||
@@ -197,7 +260,7 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
event_type='document_layout_job_failed',
|
||||
job=job,
|
||||
version=version,
|
||||
result='error',
|
||||
result='failure',
|
||||
error_code=LAYOUT_JOB_ERROR,
|
||||
metadata={'error': str(exc)[:200]},
|
||||
)
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import FileAsset, Job, ShippingNoticeIntake
|
||||
from app.models import FileAsset, Job, ShippingOrderIntake
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
fail_intake_with_stage2_cleanup,
|
||||
run_intake_parse,
|
||||
@@ -69,7 +69,7 @@ def _claim_intake_for_parsing(
|
||||
*,
|
||||
job_id: int | None,
|
||||
owned_attempt: int | None,
|
||||
) -> tuple[ShippingNoticeIntake, str] | None:
|
||||
) -> tuple[ShippingOrderIntake, str] | None:
|
||||
"""
|
||||
原子领取 Intake 并轮转 parse_lease。
|
||||
|
||||
@@ -81,13 +81,13 @@ def _claim_intake_for_parsing(
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
lease = _build_parse_lease(job_id=job_id, owned_attempt=owned_attempt)
|
||||
claim_predicate = ShippingNoticeIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
|
||||
claim_predicate = ShippingOrderIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
|
||||
if job_id is not None:
|
||||
claim_predicate = or_(
|
||||
claim_predicate,
|
||||
and_(
|
||||
ShippingNoticeIntake.parse_status == 'parsing',
|
||||
ShippingNoticeIntake.parse_job_id == int(job_id),
|
||||
ShippingOrderIntake.parse_status == 'parsing',
|
||||
ShippingOrderIntake.parse_job_id == int(job_id),
|
||||
),
|
||||
)
|
||||
values: dict = {
|
||||
@@ -98,9 +98,9 @@ def _claim_intake_for_parsing(
|
||||
if job_id is not None:
|
||||
values['parse_job_id'] = int(job_id)
|
||||
stmt = (
|
||||
update(ShippingNoticeIntake)
|
||||
update(ShippingOrderIntake)
|
||||
.where(
|
||||
ShippingNoticeIntake.intake_no == intake_no,
|
||||
ShippingOrderIntake.intake_no == intake_no,
|
||||
claim_predicate,
|
||||
)
|
||||
.values(**values)
|
||||
@@ -111,7 +111,7 @@ def _claim_intake_for_parsing(
|
||||
return None
|
||||
db.session.commit()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter_by(intake_no=intake_no)
|
||||
.first()
|
||||
)
|
||||
@@ -156,7 +156,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
return
|
||||
|
||||
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
intake = db.session.query(ShippingOrderIntake).filter_by(intake_no=intake_no).first()
|
||||
if not intake:
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
@@ -198,7 +198,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
intake_no, job_id=job_id, owned_attempt=owned_attempt
|
||||
)
|
||||
if claimed is None:
|
||||
current = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
current = db.session.query(ShippingOrderIntake).filter_by(intake_no=intake_no).first()
|
||||
if job_id is not None:
|
||||
finish_job(
|
||||
job_id,
|
||||
|
||||
@@ -3,9 +3,12 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取 Run,使用固定模板/通用确定性解析并持久化可复核结果。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、
|
||||
ensure_workflow_items_for_run(物化后兜底建 Item)。
|
||||
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_*;
|
||||
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,16 +26,18 @@ from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderProcessingPlan,
|
||||
ShippingOrderRouteDecision,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderProcessingUnit,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
begin_input_freeze,
|
||||
complete_input_freeze,
|
||||
mark_order_extraction_persistence_started,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
materialize_order_extraction_run_inputs,
|
||||
@@ -62,6 +67,31 @@ EXPANDABLE_UNIT_REVIEW_REASON_CODES = {
|
||||
}
|
||||
|
||||
|
||||
def _intake_source_types(intake_ids: set[int]) -> dict[int, str | None]:
|
||||
"""
|
||||
批量读取 Intake.source_type,供 merge 阶段分流 direct_pdf / eml。
|
||||
|
||||
核心逻辑:按主键加载 ShippingOrderIntake;缺失 id 不入结果。
|
||||
|
||||
Args:
|
||||
intake_ids: 待查询的 Intake 主键集合。
|
||||
|
||||
Returns:
|
||||
intake_id → source_type(eml|direct_pdf|None)映射。
|
||||
"""
|
||||
if not intake_ids:
|
||||
return {}
|
||||
rows = (
|
||||
ShippingOrderIntake.query
|
||||
.filter(ShippingOrderIntake.id.in_(sorted(intake_ids)))
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
int(row.id): (str(row.source_type).strip() if row.source_type else None)
|
||||
for row in rows
|
||||
}
|
||||
|
||||
|
||||
def _json_safe_order_payload(value: Any) -> Any:
|
||||
"""将坐标解析的 Decimal/date 递归转为 JSON 标量后写入 Unit 快照。
|
||||
|
||||
@@ -101,7 +131,7 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
'route_decision': str(decision.get('route_decision') or ''),
|
||||
'policy_versions': decision.get('policy_versions') if isinstance(decision.get('policy_versions'), dict) else {},
|
||||
}
|
||||
db.session.add(ShippingOrderExtractionRouteDecision(
|
||||
db.session.add(ShippingOrderRouteDecision(
|
||||
run_id=run.id, unit_id=unit.id, job_id=job.id, attempt_no=attempt_no,
|
||||
decision=route_result.execution_mode,
|
||||
match_status=str(decision.get('match_status') or 'no_match'),
|
||||
@@ -145,7 +175,7 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
)
|
||||
|
||||
|
||||
def _result_requires_review(*, units: list[ShippingOrderExtractionUnit], result: dict) -> bool:
|
||||
def _result_requires_review(*, units: list[ShippingOrderProcessingUnit], result: dict) -> bool:
|
||||
"""汇总人工复核、未接受候选、技术失败和自动冻结阻断,避免不完整 Run 被标记完成。"""
|
||||
return bool(
|
||||
result.get('pending_count')
|
||||
@@ -154,7 +184,7 @@ def _result_requires_review(*, units: list[ShippingOrderExtractionUnit], result:
|
||||
)
|
||||
|
||||
|
||||
def _selection_progress_summary(run: ShippingOrderExtractionRun) -> dict[str, int]:
|
||||
def _selection_progress_summary(run: ShippingOrderProcessingRun) -> dict[str, int]:
|
||||
"""从冻结选择计划提取首轮预算摘要,供 Run 级事件和卡片文案直接使用。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
|
||||
@@ -175,7 +205,7 @@ def _selection_progress_summary(run: ShippingOrderExtractionRun) -> dict[str, in
|
||||
}
|
||||
|
||||
|
||||
def _units_for_batch(plan: ShippingOrderExtractionPlan, *, selection_batch: int) -> list[ShippingOrderExtractionUnit]:
|
||||
def _units_for_batch(plan: ShippingOrderProcessingPlan, *, selection_batch: int) -> list[ShippingOrderProcessingUnit]:
|
||||
"""按批次读取计划单元;未标批次的普通文件视为首轮。"""
|
||||
normalized_batch = int(selection_batch or 1)
|
||||
return [
|
||||
@@ -184,7 +214,7 @@ def _units_for_batch(plan: ShippingOrderExtractionPlan, *, selection_batch: int)
|
||||
]
|
||||
|
||||
|
||||
def _next_existing_batch(plan: ShippingOrderExtractionPlan, *, after_batch: int) -> int | None:
|
||||
def _next_existing_batch(plan: ShippingOrderProcessingPlan, *, after_batch: int) -> int | None:
|
||||
"""返回计划中已存在但尚未轮到的下一批。"""
|
||||
candidates = sorted({
|
||||
int(unit.selection_batch or 1)
|
||||
@@ -194,7 +224,7 @@ def _next_existing_batch(plan: ShippingOrderExtractionPlan, *, after_batch: int)
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
|
||||
def _pending_snapshot_batches(run: ShippingOrderExtractionRun, plan: ShippingOrderExtractionPlan) -> list[int]:
|
||||
def _pending_snapshot_batches(run: ShippingOrderProcessingRun, plan: ShippingOrderProcessingPlan) -> list[int]:
|
||||
"""从冻结选择计划中找出尚未激活为执行单元的后续批次。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
|
||||
@@ -211,14 +241,14 @@ def _pending_snapshot_batches(run: ShippingOrderExtractionRun, plan: ShippingOrd
|
||||
return [batch for batch in planned_batches if batch not in existing_batches]
|
||||
|
||||
|
||||
def _should_expand_after_wave(*, wave_units: list[ShippingOrderExtractionUnit], wave_orders: list[dict]) -> bool:
|
||||
def _should_expand_after_wave(*, wave_units: list[ShippingOrderProcessingUnit], wave_orders: list[dict]) -> bool:
|
||||
"""仅在可通过更多附件补证的业务缺口出现时才扩下一轮。"""
|
||||
return bool(_expansion_trigger_reason_codes(wave_units=wave_units, wave_orders=wave_orders))
|
||||
|
||||
|
||||
def _expansion_trigger_reason_codes(
|
||||
*,
|
||||
wave_units: list[ShippingOrderExtractionUnit],
|
||||
wave_units: list[ShippingOrderProcessingUnit],
|
||||
wave_orders: list[dict],
|
||||
) -> list[str]:
|
||||
"""汇总当前批次触发扩批的业务原因码,供事件与工作台共享。"""
|
||||
@@ -244,7 +274,7 @@ def _expansion_trigger_reason_codes(
|
||||
return sorted(code for code in reason_codes if code)
|
||||
|
||||
|
||||
def _schema_field_ids_by_code(run: ShippingOrderExtractionRun) -> dict[str, set[str]]:
|
||||
def _schema_field_ids_by_code(run: ShippingOrderProcessingRun) -> dict[str, set[str]]:
|
||||
"""读取冻结 Schema 中稳定 field_code -> field_id 集合,供业务缺口判定复用。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
@@ -284,7 +314,7 @@ def _order_requires_expansion(order: dict[str, Any]) -> bool:
|
||||
|
||||
|
||||
def _mark_expandable_business_gaps(
|
||||
run: ShippingOrderExtractionRun,
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -306,7 +336,7 @@ def _mark_expandable_business_gaps(
|
||||
|
||||
|
||||
def _wave_orders_for_expansion(
|
||||
run: ShippingOrderExtractionRun,
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -334,10 +364,10 @@ def _wave_orders_for_expansion(
|
||||
|
||||
def _activate_expansion_batch(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
plan: ShippingOrderExtractionPlan,
|
||||
run: ShippingOrderProcessingRun,
|
||||
plan: ShippingOrderProcessingPlan,
|
||||
selection_batch: int,
|
||||
) -> list[ShippingOrderExtractionUnit]:
|
||||
) -> list[ShippingOrderProcessingUnit]:
|
||||
"""按冻结批次计划补物化附件并追加执行单元;重复触发保持幂等。"""
|
||||
from app.services.shipping_notice.order_extraction_materialization import ensure_order_extraction_input_documents
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan_batch
|
||||
@@ -351,9 +381,9 @@ def _activate_expansion_batch(
|
||||
if isinstance(item, dict) and item.get('intake_id') is not None
|
||||
]
|
||||
intakes = (
|
||||
ShippingNoticeIntake.query
|
||||
.filter(ShippingNoticeIntake.id.in_(intake_ids))
|
||||
.order_by(ShippingNoticeIntake.id.asc())
|
||||
ShippingOrderIntake.query
|
||||
.filter(ShippingOrderIntake.id.in_(intake_ids))
|
||||
.order_by(ShippingOrderIntake.id.asc())
|
||||
.all()
|
||||
) if intake_ids else []
|
||||
ensure_order_extraction_input_documents(
|
||||
@@ -365,10 +395,10 @@ def _activate_expansion_batch(
|
||||
return ensure_order_extraction_plan_batch(run, selection_batch=int(selection_batch))
|
||||
|
||||
|
||||
def _reload_run_and_unit(*, run_id: int, unit_id: int) -> tuple[ShippingOrderExtractionRun, ShippingOrderExtractionUnit]:
|
||||
def _reload_run_and_unit(*, run_id: int, unit_id: int) -> tuple[ShippingOrderProcessingRun, ShippingOrderProcessingUnit]:
|
||||
"""在单元异常回滚后重新加载实体,避免继续使用失效会话对象。"""
|
||||
run = ShippingOrderExtractionRun.query.filter_by(id=run_id).with_for_update().first()
|
||||
unit = db.session.get(ShippingOrderExtractionUnit, int(unit_id))
|
||||
run = ShippingOrderProcessingRun.query.filter_by(id=run_id).with_for_update().first()
|
||||
unit = db.session.get(ShippingOrderProcessingUnit, int(unit_id))
|
||||
if run is None or unit is None:
|
||||
raise RuntimeError('order extraction run or unit disappeared during retry handling')
|
||||
return run, unit
|
||||
@@ -415,6 +445,9 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
"""
|
||||
独立处理一个附件单元;技术失败最多自动重试 2 次,不影响其他单元继续执行。
|
||||
|
||||
核心逻辑:正常从 pending 开始;若进程/事务异常遗留 routing、matching_profile、extracting
|
||||
或 merging_supplement,则先经 failed→pending 恢复稳定检查点,再开启新的确定性尝试。
|
||||
|
||||
Returns:
|
||||
`list[dict]`: 当前单元产出的订单数组(确定性成功)。
|
||||
`None`: 当前单元进入 review_required、最终技术失败或取消中止。
|
||||
@@ -432,6 +465,13 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
return None
|
||||
if unit.status in {'routing', 'matching_profile', 'extracting', 'merging_supplement'}:
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_WORKER_RECOVERY',
|
||||
error_message='Interrupted order extraction unit reset before worker retry',
|
||||
)
|
||||
if unit.status == 'failed':
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
if unit.status in {'review_required', 'candidate_ready', 'cancelled'}:
|
||||
@@ -596,7 +636,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
if job is None:
|
||||
return
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
if run is None:
|
||||
fail_job(job.id, error='order extraction run not found', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
@@ -609,6 +649,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
# [STEP 0][BE-F03] 物化前先 open→freezing,阻断并发追加窗口。
|
||||
begin_input_freeze(run)
|
||||
db.session.commit()
|
||||
run = ShippingOrderProcessingRun.query.filter_by(id=int(run.id)).with_for_update().first()
|
||||
if run is None:
|
||||
fail_job(job.id, error='order extraction run missing after freeze', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
# [STEP 1] 邮件附件先物化成 Document,再排布局 Job;发送阶段没有 PDF Document。
|
||||
# 必须落在本 try 内:MinerU 关闭/排程失败时 ValidationError 需同步收口 Run,避免 Job 重试耗尽前 UI 一直 queued。
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
@@ -619,12 +667,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
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}, 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',
|
||||
@@ -644,6 +694,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
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)
|
||||
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
|
||||
@@ -731,7 +783,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
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(ShippingOrderExtractionUnit, int(unit.id))
|
||||
unit = db.session.get(ShippingOrderProcessingUnit, int(unit.id))
|
||||
if unit is None or not unit_orders or unit.status != 'merging_supplement':
|
||||
continue
|
||||
unit_orders_by_id[int(unit.id)] = unit_orders
|
||||
@@ -769,7 +821,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
next_batch = pending_batches[0]
|
||||
created_units = _activate_expansion_batch(run=run, plan=plan, selection_batch=next_batch)
|
||||
db.session.flush()
|
||||
plan = ShippingOrderExtractionPlan.query.filter_by(id=plan.id).first() or plan
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(id=plan.id).first() or plan
|
||||
if created_units or _units_for_batch(plan, selection_batch=next_batch):
|
||||
record_run_progress(
|
||||
run=run,
|
||||
@@ -790,35 +842,123 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
continue
|
||||
break
|
||||
|
||||
units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderExtractionUnit.position.asc()).all()
|
||||
units = ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderProcessingUnit.position.asc()).all()
|
||||
|
||||
schema_snapshot = run.input_snapshot_json.get('schema') or {}
|
||||
orders_to_merge = [
|
||||
order
|
||||
for unit_id in pending_merge_unit_ids
|
||||
for order in unit_orders_by_id.get(unit_id, [])
|
||||
if isinstance(order, dict)
|
||||
schema_definition = schema_snapshot.get('definition') or {}
|
||||
pending_unit_id_set = {int(unit_id) for unit_id in pending_merge_unit_ids}
|
||||
pending_units = [
|
||||
unit for unit in units
|
||||
if int(unit.id) in pending_unit_id_set and unit.status == 'merging_supplement'
|
||||
]
|
||||
orders_to_merge = merge_unit_orders(orders=orders_to_merge, schema_definition=schema_snapshot.get('definition') or {})
|
||||
# [STEP] 阶段 2:按 Intake.source_type 分流;direct_pdf 跳过邮件补充与裁决审计。
|
||||
pending_intake_ids = {
|
||||
int(unit.intake_id) for unit in pending_units if unit.intake_id is not None
|
||||
}
|
||||
run_intake_ids = {
|
||||
int(item.get('intake_id'))
|
||||
for item in (run.input_snapshot_json.get('intakes') or [])
|
||||
if isinstance(item, dict) and item.get('intake_id') is not None
|
||||
}
|
||||
source_by_intake = _intake_source_types(pending_intake_ids | run_intake_ids)
|
||||
all_run_direct_pdf = bool(run_intake_ids) and all(
|
||||
source_by_intake.get(intake_id) == 'direct_pdf' for intake_id in run_intake_ids
|
||||
)
|
||||
|
||||
def _unit_is_direct_pdf(unit: ShippingOrderProcessingUnit) -> bool:
|
||||
"""Unit 所属 Intake 为 direct_pdf,或本 Run 全部 Intake 均为 direct_pdf。"""
|
||||
if all_run_direct_pdf:
|
||||
return True
|
||||
return source_by_intake.get(int(unit.intake_id or 0)) == 'direct_pdf'
|
||||
|
||||
direct_pdf_units = [unit for unit in pending_units if _unit_is_direct_pdf(unit)]
|
||||
eml_units = [unit for unit in pending_units if not _unit_is_direct_pdf(unit)]
|
||||
|
||||
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
|
||||
supplements_by_intake = {
|
||||
int(intake.get('intake_id') or 0): supplement
|
||||
for intake in run.input_snapshot_json.get('intakes') or [] if isinstance(intake, dict)
|
||||
for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict)
|
||||
}
|
||||
merged_orders = merge_email_supplements(
|
||||
orders=orders_to_merge,
|
||||
supplements_by_intake=supplements_by_intake,
|
||||
schema_definition=schema_snapshot.get('definition') or {},
|
||||
)
|
||||
offset = 0
|
||||
merged_by_unit_id: dict[int, list[dict[str, Any]]] = {}
|
||||
|
||||
def _merge_group_orders(
|
||||
group_units: list[ShippingOrderProcessingUnit],
|
||||
*,
|
||||
apply_email_supplements: bool,
|
||||
) -> None:
|
||||
"""
|
||||
对同路径 Unit 批量 merge;可选跳过 email_supplements。
|
||||
|
||||
Args:
|
||||
group_units: 同路径(direct_pdf 或 eml)且保持 plan 顺序的 Unit。
|
||||
apply_email_supplements: False 时直接 PDF 跳过正文补充合并。
|
||||
"""
|
||||
if not group_units:
|
||||
return
|
||||
orders_to_merge = [
|
||||
order
|
||||
for unit in group_units
|
||||
for order in unit_orders_by_id.get(int(unit.id), [])
|
||||
if isinstance(order, dict)
|
||||
]
|
||||
merged = merge_unit_orders(
|
||||
orders=orders_to_merge,
|
||||
schema_definition=schema_definition,
|
||||
keep_primary_documents_separate=True,
|
||||
)
|
||||
if apply_email_supplements:
|
||||
merged = merge_email_supplements(
|
||||
orders=merged,
|
||||
supplements_by_intake=supplements_by_intake,
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
offset = 0
|
||||
for unit in group_units:
|
||||
count = len(unit_orders_by_id.get(int(unit.id), []))
|
||||
merged_by_unit_id[int(unit.id)] = [
|
||||
item for item in merged[offset:offset + count] if isinstance(item, dict)
|
||||
]
|
||||
offset += count
|
||||
|
||||
_merge_group_orders(direct_pdf_units, apply_email_supplements=False)
|
||||
if eml_units:
|
||||
append_shipping_audit_event(
|
||||
event_type='ORDER_EMAIL_ADJUDICATION_STARTED',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run.id),
|
||||
run_no=run.run_no,
|
||||
actor_type='system',
|
||||
source='shipping_order_extraction',
|
||||
metadata={
|
||||
'unit_count': len(eml_units),
|
||||
'source_type': 'eml',
|
||||
'decision_rule_version': 'pdf-priority-v1',
|
||||
},
|
||||
)
|
||||
_merge_group_orders(eml_units, apply_email_supplements=True)
|
||||
append_shipping_audit_event(
|
||||
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run.id),
|
||||
run_no=run.run_no,
|
||||
actor_type='system',
|
||||
source='shipping_order_extraction',
|
||||
result='success',
|
||||
metadata={
|
||||
'unit_count': len(eml_units),
|
||||
'source_type': 'eml',
|
||||
'decision_rule_version': 'pdf-priority-v1',
|
||||
},
|
||||
)
|
||||
|
||||
merged_orders: list[dict[str, Any]] = []
|
||||
for unit in units:
|
||||
unit_orders = unit_orders_by_id.get(int(unit.id), [])
|
||||
if unit.status != 'merging_supplement':
|
||||
continue
|
||||
count = len(unit_orders)
|
||||
merged_unit_orders = merged_orders[offset:offset + count]
|
||||
offset += count
|
||||
merged_unit_orders = merged_by_unit_id.get(int(unit.id), list(unit_orders))
|
||||
merged_orders.extend(merged_unit_orders)
|
||||
relation_codes = sorted({
|
||||
str(order.get('_hxops_email_supplement_relation') or '').strip()
|
||||
for order in merged_unit_orders
|
||||
@@ -1020,12 +1160,12 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
if run is not None and run.status in {'queued', 'processing', 'failed'}:
|
||||
running_unit = ShippingOrderExtractionUnit.query.join(ShippingOrderExtractionPlan).filter(
|
||||
ShippingOrderExtractionPlan.run_id == run.id,
|
||||
ShippingOrderExtractionUnit.status.in_(['routing', 'matching_profile', 'extracting', 'merging_supplement']),
|
||||
running_unit = ShippingOrderProcessingUnit.query.join(ShippingOrderProcessingPlan).filter(
|
||||
ShippingOrderProcessingPlan.run_id == run.id,
|
||||
ShippingOrderProcessingUnit.status.in_(['routing', 'matching_profile', 'extracting', 'merging_supplement']),
|
||||
).first()
|
||||
if running_unit is not None:
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
@@ -143,7 +143,7 @@ def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
|
||||
if status != "running":
|
||||
return False
|
||||
|
||||
from app.models import ShippingNoticeIntake
|
||||
from app.models import ShippingOrderIntake
|
||||
|
||||
intake_no = str(
|
||||
(cancelled_job.payload_json or {}).get("intake_no")
|
||||
@@ -154,8 +154,8 @@ def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
|
||||
if not intake_no:
|
||||
return False
|
||||
locked = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == intake_no)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(ShippingOrderIntake.intake_no == intake_no)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
@@ -210,7 +210,7 @@ def _retarget_intake_parse_job_after_supersede(
|
||||
"""
|
||||
if not _subject_to_parse_queued_unique(str(cancelled_job.job_type or "")):
|
||||
return
|
||||
from app.models import ShippingNoticeIntake
|
||||
from app.models import ShippingOrderIntake
|
||||
|
||||
intake_no = str(
|
||||
(cancelled_job.payload_json or {}).get("intake_no")
|
||||
@@ -227,8 +227,8 @@ def _retarget_intake_parse_job_after_supersede(
|
||||
return
|
||||
|
||||
locked = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == intake_no)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(ShippingOrderIntake.intake_no == intake_no)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
|
||||
Reference in new issue
Block a user