feat(shipping-notice): 收敛复核阶段同源投影与 OT 后履约推进
统一 Case/Progress 阶段 label_key、修复 Job 成功未推进 OT 的可重试失败投影与写路径,并落地 OT 后行级匹配/波次履约与版面诊断开关。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
74270adc22
commit
fd6a23f870
100 files changed
+12138
-1017
No files matched your search
@@ -16,6 +16,8 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
shipping_order_extraction,
|
||||
shipping_process_gate,
|
||||
shipping_stp_auto_create,
|
||||
shipping_line_auto_fulfill,
|
||||
shipping_post_ot_wave_progress,
|
||||
shipping_xfa_ocr_automark,
|
||||
wecom_directory_sync,
|
||||
)
|
||||
@@ -2,9 +2,11 @@
|
||||
backend/app/jobs/handlers/shipping_document_layout.py
|
||||
|
||||
用途:独立执行单份 ShippingOrderDocument 的 MinerU 布局解析任务。
|
||||
依赖:Layout lifecycle/runtime、FileAsset、通用 Job queue、audit_service、workflow_ledger(尽力引用)。
|
||||
依赖:Layout lifecycle/runtime、layout_diagnostics、FileAsset、通用 Job queue、audit_service、
|
||||
workflow_ledger(尽力引用)。
|
||||
逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本;
|
||||
起止与异常轻量写统一审计(若能定位 WorkflowItem 则带软引用)。
|
||||
起止与异常轻量写统一审计(若能定位 WorkflowItem 则带软引用);
|
||||
PR-0 将脱敏 timings/counts 写入 Job result 与 worker 日志,不进 layout snapshot。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +20,12 @@ from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import FileAsset, Job, ShippingDocumentLayoutVersion
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.document_layout.layout_diagnostics import (
|
||||
empty_layout_counts,
|
||||
empty_layout_timings,
|
||||
freeze_layout_diagnostics,
|
||||
ocr_engine_is_warm,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
claim_layout_version,
|
||||
complete_layout_version,
|
||||
@@ -139,11 +147,14 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
total_started = perf_counter()
|
||||
asset_started = perf_counter()
|
||||
content = read_asset_bytes(asset)
|
||||
timings = {
|
||||
'queue_wait_ms': max(round((job.started_at - job.created_at).total_seconds() * 1000), 0)
|
||||
if job.started_at and job.created_at else 0,
|
||||
'asset_read_ms': round((perf_counter() - asset_started) * 1000),
|
||||
}
|
||||
# [STEP 1] 初始化全量诊断键;ocr_engine_warm 在任何 OCR 之前读取进程状态。
|
||||
timings = empty_layout_timings()
|
||||
counts = empty_layout_counts()
|
||||
counts['ocr_engine_warm'] = ocr_engine_is_warm()
|
||||
timings['queue_wait_ms'] = max(
|
||||
round((job.started_at - job.created_at).total_seconds() * 1000), 0,
|
||||
) if job.started_at and job.created_at else 0
|
||||
timings['asset_read_ms'] = round((perf_counter() - asset_started) * 1000)
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import (
|
||||
analyze_xfa_pdf,
|
||||
persist_xfa_structure_analysis,
|
||||
@@ -169,6 +180,11 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
and xfa_outcome.packet_result.document_kind not in {'plain_pdf', 'acroform'}
|
||||
):
|
||||
snapshot = dict(xfa_outcome.snapshot)
|
||||
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
|
||||
try:
|
||||
counts['page_count'] = int(capability.get('page_count') or 0)
|
||||
except (TypeError, ValueError):
|
||||
counts['page_count'] = 0
|
||||
persist_xfa_structure_analysis(
|
||||
document_id=int(document.id),
|
||||
layout_version_id=int(version.id),
|
||||
@@ -212,6 +228,7 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
document_id=document.id,
|
||||
content_hash=document.content_hash,
|
||||
timings=timings,
|
||||
counts=counts,
|
||||
)
|
||||
timings['snapshot_build_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
if snapshot is None:
|
||||
@@ -230,11 +247,14 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
version=version,
|
||||
metadata={'status': str(snapshot.get('status') or 'failed')},
|
||||
)
|
||||
timings['total_handler_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
frozen_timings, frozen_counts = freeze_layout_diagnostics(timings, counts)
|
||||
finish_job(
|
||||
job.id, result={
|
||||
'status': final_status,
|
||||
'provider_status': str(snapshot.get('status') or 'failed'),
|
||||
'timings': {key: int(value) for key, value in timings.items()},
|
||||
'timings': frozen_timings,
|
||||
'counts': frozen_counts,
|
||||
},
|
||||
message=(
|
||||
'文档版面解析完成' if final_status in {'ready', 'needs_review'}
|
||||
@@ -244,11 +264,13 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout
|
||||
|
||||
resume_runs_waiting_for_layout(document_id=int(document.id))
|
||||
timings['total_handler_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
else:
|
||||
timings['total_handler_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
if ctx.logger is not None:
|
||||
frozen_timings, frozen_counts = freeze_layout_diagnostics(timings, counts)
|
||||
ctx.logger.info(
|
||||
'shipping_document_layout_timing job_id=%s version_id=%s document_id=%s timings=%s',
|
||||
job.id, version.id, document.id, timings,
|
||||
'shipping_document_layout_timing job_id=%s version_id=%s document_id=%s timings=%s counts=%s',
|
||||
job.id, version.id, document.id, frozen_timings, frozen_counts,
|
||||
)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_line_auto_fulfill.py
|
||||
|
||||
用途:消费 OT 后行级自动履约协调 Job。
|
||||
依赖:JobContext、line_auto_fulfill_coordinator、query_service.get_task_by_ref。
|
||||
逻辑:shipping worker 领取;flag 关闭或无 eligible 时 finish 为 skipped;失败可重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
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 Job
|
||||
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
|
||||
coordinate_post_ot_auto_fulfill,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_LINE_AUTO_FULFILL)
|
||||
def handle_shipping_line_auto_fulfill(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行 OT 后行级自动履约协调。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id;业务字段以 Job.payload_json 为准(task_no/trigger)。
|
||||
"""
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
raise RuntimeError('missing_line_auto_fulfill_job_id')
|
||||
|
||||
job_id = int(job.id)
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
frozen = dict(job.payload_json or {})
|
||||
task_no = str(frozen.get('task_no') or '').strip()
|
||||
trigger = str(frozen.get('trigger') or 'inventory_ready').strip()
|
||||
task = get_task_by_ref(task_no) if task_no else None
|
||||
if task is None:
|
||||
fail_job(
|
||||
job_id,
|
||||
error='task_not_found',
|
||||
result={'status': 'failed', 'error_code': 'SHIPPING.TASK_NOT_FOUND'},
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
try:
|
||||
result = coordinate_post_ot_auto_fulfill(task=task, trigger=trigger)
|
||||
db.session.commit()
|
||||
if result.get('status') == 'failed':
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(result.get('error') or 'auto_fulfill_failed'),
|
||||
result=result,
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
finish_job(
|
||||
job_id,
|
||||
result=result,
|
||||
message=str(result.get('status') or 'ok'),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
db.session.rollback()
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed'},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_post_ot_wave_progress.py
|
||||
|
||||
用途:消费 post-OT wave 专用 Excel/RPA 推进 Job。
|
||||
依赖:JobContext、post_ot_wave_progress_service、fulfillment_workflow.generate_excel。
|
||||
逻辑:按 task_no+wave_no 推进;失败只标记 progress_failed,不回滚已提交 wave。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
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 Job
|
||||
from app.services.shipping_notice.post_ot_wave_progress_service import (
|
||||
mark_post_ot_wave_progress_result,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_POST_OT_WAVE_PROGRESS)
|
||||
def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行本 wave 的 Excel 生成推进(RPA 链路由 generate_excel 后续状态机承接)。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id;业务字段以 Job.payload_json 为准。
|
||||
"""
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
raise RuntimeError('missing_post_ot_wave_progress_job_id')
|
||||
|
||||
job_id = int(job.id)
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
frozen = dict(job.payload_json or {})
|
||||
task_no = str(frozen.get('task_no') or '').strip()
|
||||
wave_no = frozen.get('wave_no')
|
||||
idem_row_id = frozen.get('idempotency_row_id')
|
||||
progress_key = frozen.get('progress_idempotency_key')
|
||||
task = get_task_by_ref(task_no) if task_no else None
|
||||
if task is None:
|
||||
mark_post_ot_wave_progress_result(
|
||||
idempotency_row_id=idem_row_id,
|
||||
progress_idempotency_key=progress_key,
|
||||
ok=False,
|
||||
error='task_not_found',
|
||||
)
|
||||
db.session.commit()
|
||||
fail_job(
|
||||
job_id,
|
||||
error='task_not_found',
|
||||
result={'status': 'failed', 'wave_no': wave_no},
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.fulfillment_workflow import generate_excel
|
||||
|
||||
# [STEP] 为本 OT 生成/刷新发货 Excel;wave_no 写入上下文供审计与后续过滤。
|
||||
gen = generate_excel({
|
||||
'task_id': task.task_no,
|
||||
'wave_no': wave_no,
|
||||
'line_keys': list(frozen.get('line_keys') or []),
|
||||
'post_ot_wave': True,
|
||||
})
|
||||
status = str((gen or {}).get('status') or '').strip().lower()
|
||||
if status in {'failed', 'error'}:
|
||||
err = str((gen or {}).get('message') or (gen or {}).get('error') or 'excel_failed')
|
||||
mark_post_ot_wave_progress_result(
|
||||
idempotency_row_id=idem_row_id,
|
||||
progress_idempotency_key=progress_key,
|
||||
ok=False,
|
||||
error=err,
|
||||
)
|
||||
db.session.commit()
|
||||
fail_job(
|
||||
job_id,
|
||||
error=err[:500],
|
||||
result={'status': 'failed', 'wave_no': wave_no, 'generate_excel': gen},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
mark_post_ot_wave_progress_result(
|
||||
idempotency_row_id=idem_row_id,
|
||||
progress_idempotency_key=progress_key,
|
||||
ok=True,
|
||||
)
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job_id,
|
||||
result={'status': 'ok', 'wave_no': wave_no, 'generate_excel': gen},
|
||||
message='post_ot_wave_progress_ok',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
db.session.rollback()
|
||||
# [STEP] 下游失败:重新打开会话标记 progress_failed,wave 业务事实保留。
|
||||
mark_post_ot_wave_progress_result(
|
||||
idempotency_row_id=idem_row_id,
|
||||
progress_idempotency_key=progress_key,
|
||||
ok=False,
|
||||
error=str(exc)[:1000],
|
||||
)
|
||||
db.session.commit()
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed', 'wave_no': wave_no},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -10,37 +10,65 @@ backend/app/jobs/handlers/shipping_stp_auto_create.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
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 Job
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
execute_stp_auto_create_job,
|
||||
)
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_STP_AUTO_CREATE)
|
||||
def handle_shipping_stp_auto_create(ctx: JobContext) -> None:
|
||||
def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行 STP 自动建单 Job。
|
||||
|
||||
核心逻辑:委托 execute_stp_auto_create_job;成功 finish,业务拒绝/异常 fail。
|
||||
核心逻辑:按 Worker 传入的 job_id 读取冻结 payload 与执行代次;委托
|
||||
execute_stp_auto_create_job;成功 finish,业务拒绝/异常按当前代次 fail。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文;当前执行体不依赖请求上下文。
|
||||
payload: Worker 载荷,必须含 job_id;业务字段以 Job.payload_json 为准。
|
||||
|
||||
Returns:
|
||||
None。
|
||||
"""
|
||||
payload = ctx.payload if isinstance(ctx.payload, dict) else {}
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
raise RuntimeError('missing_stp_auto_create_job_id')
|
||||
|
||||
job_id = int(job.id)
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
frozen = dict(job.payload_json or {})
|
||||
frozen.setdefault('job_id', job_id)
|
||||
try:
|
||||
result = execute_stp_auto_create_job(payload=payload, job_id=int(ctx.job_id))
|
||||
result = execute_stp_auto_create_job(payload=frozen, job_id=job_id)
|
||||
if result.get('ok'):
|
||||
finish_job(int(ctx.job_id), message=str(result.get('message') or 'STP 自动建单完成'))
|
||||
finish_job(
|
||||
job_id,
|
||||
result=result,
|
||||
message=str(result.get('message') or 'STP 自动建单完成'),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
fail_job(
|
||||
int(ctx.job_id),
|
||||
error_code=str(result.get('error_code') or 'STP_AUTO_CREATE_FAILED'),
|
||||
message=str(result.get('message') or 'STP 自动建单失败'),
|
||||
job_id,
|
||||
error=str(result.get('message') or result.get('error_code') or 'STP 自动建单失败'),
|
||||
result=result,
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
fail_job(
|
||||
int(ctx.job_id),
|
||||
error_code='STP_AUTO_CREATE_EXCEPTION',
|
||||
message=str(exc)[:500],
|
||||
job_id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed', 'error_code': 'SHIPPING.STP_AUTO_CREATE_FAILED'},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
Reference in new issue
Block a user