feat(shipping-notice): 增强订单抽取与审计功能,支持取消与保留策略
- 在环境配置中新增进度细化、订单提取取消与审计导出相关的开关 - 实现订单抽取运行的取消功能,允许管理员在运行中进行操作 - 引入审计事件的保留策略,支持三年保留期的自动清理 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 增强文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
c85997884b
commit
95cdfe66b0
158 files changed
+19005
-1201
No files matched your search
@@ -2,8 +2,8 @@
|
||||
backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取 Run,使用固定模板确定性解析并持久化可复核结果。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务。
|
||||
逻辑:每个 Unit 先持久化脱敏路由,再确定性解析或标记人工复核;不调用 Dify、Provider 或 Runtime Binding。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行,失败时同步收口 Run;每个 Unit 再确定性解析或标记人工复核;不调用 Dify、Provider 或 Runtime Binding。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -402,14 +402,24 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
|
||||
Returns:
|
||||
`list[dict]`: 当前单元产出的订单数组(确定性成功)。
|
||||
`None`: 当前单元进入 review_required 或最终技术失败。
|
||||
`None`: 当前单元进入 review_required、最终技术失败或取消中止。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
should_abort_unit_for_cancellation,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
while True:
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(unit)
|
||||
if should_abort_unit_for_cancellation(run=run, unit=unit):
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
return None
|
||||
if unit.status == 'failed':
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
if unit.status in {'review_required', 'candidate_ready'}:
|
||||
if unit.status in {'review_required', 'candidate_ready', 'cancelled'}:
|
||||
return None
|
||||
transition_order_extraction_unit(unit, target_status='routing')
|
||||
record_unit_progress(run=run, unit=unit, event_code='document_queued', job_id=job.id)
|
||||
@@ -417,6 +427,12 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
record_unit_progress(run=run, unit=unit, event_code='profile_matching', job_id=job.id)
|
||||
db.session.commit()
|
||||
try:
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(unit)
|
||||
if should_abort_unit_for_cancellation(run=run, unit=unit):
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
return None
|
||||
route_result = route_deterministic_unit(run, unit=unit)
|
||||
_append_route_decision(
|
||||
run=run,
|
||||
@@ -488,12 +504,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行一次纯确定性订单抽取 Job。
|
||||
|
||||
核心逻辑:物化附件与排版面 Job 纳入主 try;排程 ValidationError(如 MinerU 关闭)非重试,同步将 Run 标为 failed。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文,仅用于安全日志。
|
||||
payload: 必须包含 job_id;Run 身份只从 Job.business_ref 读取。
|
||||
|
||||
Raises:
|
||||
Exception: 技术故障交给 Job 队列重试;模板、证据和业务歧义不抛出为技术失败。
|
||||
Exception: 可重试技术故障交给 Job 队列重试;模板、证据和业务歧义不抛出为技术失败。
|
||||
"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
@@ -511,36 +529,37 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
fail_job(job.id, error=f'run status is not executable: {run.status}', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
# [STEP 1] 邮件附件先物化成 Document,再排布局 Job;发送阶段没有 PDF Document。
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
if 'layout_pending' in layout_issues.values():
|
||||
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:
|
||||
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
|
||||
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
# [STEP 1] 邮件附件先物化成 Document,再排布局 Job;发送阶段没有 PDF Document。
|
||||
# 必须落在本 try 内:MinerU 关闭/排程失败时 ValidationError 需同步收口 Run,避免 Job 重试耗尽前 UI 一直 queued。
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
if 'layout_pending' in layout_issues.values():
|
||||
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:
|
||||
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
|
||||
|
||||
# [STEP 3] 所有 PDF 布局就绪后重建快照,此时才冻结带坐标证据的执行计划。
|
||||
plan = materialize_order_extraction_run_inputs(run)
|
||||
if plan is None:
|
||||
@@ -574,6 +593,15 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
|
||||
# [STEP 1] 每个文档独立路由;当前批次未完整收敛时,再按冻结计划激活下一批附件。
|
||||
while True:
|
||||
db.session.refresh(run)
|
||||
if run.cancellation_requested_at is not None:
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
)
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
if run.status == 'cancelled':
|
||||
break
|
||||
if max_runtime_seconds and time.perf_counter() - started >= max_runtime_seconds:
|
||||
runtime_budget_stopped = True
|
||||
record_run_progress(
|
||||
@@ -584,6 +612,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
units = _units_for_batch(plan, selection_batch=current_batch)
|
||||
wave_orders: list[dict] = []
|
||||
for unit in units:
|
||||
db.session.refresh(run)
|
||||
if run.cancellation_requested_at is not None:
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
should_abort_unit_for_cancellation,
|
||||
)
|
||||
if should_abort_unit_for_cancellation(run=run, unit=unit) or unit.status == 'pending':
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
continue
|
||||
# 总时限不能中断正在进行的外部解析,但禁止在到期后启动新的 Unit。
|
||||
if max_runtime_seconds and time.perf_counter() - started >= max_runtime_seconds:
|
||||
runtime_budget_stopped = True
|
||||
@@ -749,6 +787,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
job_id=job.id,
|
||||
)
|
||||
# [STEP] 每 PDF 独立下游:立刻物化 Candidate / STP 建单,不阻塞同批其它 Unit。
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(unit)
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
should_abort_unit_for_cancellation,
|
||||
)
|
||||
if should_abort_unit_for_cancellation(run=run, unit=unit):
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
continue
|
||||
try:
|
||||
unit_persist = progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=merged_unit_orders,
|
||||
@@ -791,6 +839,44 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
mark_order_extraction_persistence_started(run)
|
||||
result = submit_order_extraction_run_result(run=run, orders=orders)
|
||||
requires_review = runtime_budget_stopped or _result_requires_review(units=units, result=result)
|
||||
pending_orders = [
|
||||
{
|
||||
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
|
||||
'po_number': str(item.get('po_number') or '').strip() or None,
|
||||
'reasons': [
|
||||
str(code).strip()[:96]
|
||||
for code in (item.get('reasons') or [])
|
||||
if str(code or '').strip()
|
||||
][:12],
|
||||
'missing_fields': [
|
||||
str(field).strip()
|
||||
for field in (item.get('missing_fields') or [])
|
||||
if str(field or '').strip()
|
||||
][:20],
|
||||
'duplicate_status': str(item.get('duplicate_status') or '').strip() or None,
|
||||
}
|
||||
for item in (result.get('pending_orders') or [])
|
||||
if isinstance(item, dict)
|
||||
][:50]
|
||||
auto_freeze = result.get('auto_freeze') if isinstance(result.get('auto_freeze'), dict) else {}
|
||||
blocked_tasks = [
|
||||
{
|
||||
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
|
||||
'task_no': str(item.get('task_no') or '').strip() or None,
|
||||
'code': str(item.get('code') or '').strip() or None,
|
||||
}
|
||||
for item in (auto_freeze.get('blocked_tasks') or [])
|
||||
if isinstance(item, dict)
|
||||
][:30]
|
||||
selection_summary = _selection_progress_summary(run)
|
||||
budget_stopped = bool(
|
||||
runtime_budget_stopped
|
||||
or (
|
||||
selection_summary.get('budget_limited_attachment_count', 0) > 0
|
||||
and bool(requires_review)
|
||||
)
|
||||
)
|
||||
# 收口摘要保留可投影的处理事实,供 Run 级 handling_items 区分待补/冲突/冻结/复核。
|
||||
summary = {
|
||||
'run_no': run.run_no, 'batch_no': result.get('batch_no'),
|
||||
'created_count': int(result.get('created_count') or 0),
|
||||
@@ -798,6 +884,13 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
'pending_count': int(result.get('pending_count') or 0),
|
||||
'non_shipping_count': int(result.get('non_shipping_count') or 0),
|
||||
'execution': execution, 'requires_review': requires_review,
|
||||
'pending_orders': pending_orders,
|
||||
'auto_freeze': {
|
||||
'frozen_task_count': len(auto_freeze.get('frozen_task_nos') or []),
|
||||
'blocked_task_count': len(blocked_tasks),
|
||||
'blocked_tasks': blocked_tasks,
|
||||
},
|
||||
'budget_stopped': budget_stopped,
|
||||
}
|
||||
final_status = (
|
||||
'failed'
|
||||
@@ -808,7 +901,22 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
if requires_review
|
||||
else 'completed'
|
||||
)
|
||||
selection_summary = _selection_progress_summary(run)
|
||||
db.session.refresh(run)
|
||||
if run.cancellation_requested_at is not None:
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
finalize_run_cancellation_if_ready,
|
||||
)
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
finalize_run_cancellation_if_ready(
|
||||
run=run,
|
||||
actor_type='system',
|
||||
actor_id='shipping_order_extraction_worker',
|
||||
)
|
||||
db.session.commit()
|
||||
if run.status == 'cancelled':
|
||||
finish_job(job.id, result={'cancelled': True, 'run_no': run.run_no}, message='订单抽取已取消', owned_attempt=owned_attempt)
|
||||
return
|
||||
if selection_summary['budget_limited_attachment_count'] > 0 and final_status != 'completed':
|
||||
budget_stop_reason_codes = _expansion_trigger_reason_codes(
|
||||
wave_units=units,
|
||||
|
||||
Reference in new issue
Block a user