feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
No files matched your search
@@ -23,6 +23,5 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
shipping_post_ot_wave_progress,
|
||||
shipping_review_revalidate_progress,
|
||||
shipping_pdf_automark,
|
||||
shipping_xfa_ocr_automark,
|
||||
wecom_directory_sync,
|
||||
)
|
||||
@@ -173,14 +173,16 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
xfa_outcome = analyze_xfa_pdf(content, limits=default_xfa_resource_limits())
|
||||
timings['xfa_analysis_ms'] = round((perf_counter() - xfa_started) * 1000)
|
||||
|
||||
xfa_capability: dict | None = None
|
||||
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)
|
||||
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
|
||||
xfa_snapshot = dict(xfa_outcome.snapshot)
|
||||
capability = xfa_snapshot.get('xfa_capability') if isinstance(xfa_snapshot.get('xfa_capability'), dict) else {}
|
||||
xfa_capability = dict(capability)
|
||||
try:
|
||||
counts['page_count'] = int(capability.get('page_count') or 0)
|
||||
except (TypeError, ValueError):
|
||||
@@ -191,6 +193,11 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
source_content_hash=str(document.content_hash or ''),
|
||||
outcome=xfa_outcome,
|
||||
)
|
||||
# persist_xfa_structure_analysis 将冻结 analysis_id 回填到 outcome 快照;
|
||||
# 重新读取,确保随后合并到统一视觉 Layout 的 capability 可被精确复核。
|
||||
persisted_capability = xfa_outcome.snapshot.get('xfa_capability')
|
||||
if isinstance(persisted_capability, dict):
|
||||
xfa_capability = dict(persisted_capability)
|
||||
if xfa_outcome.error_code == 'XFA_UNSAFE_XML':
|
||||
_layout_job_audit(
|
||||
event_type='xfa_parse_rejected_unsafe',
|
||||
@@ -199,15 +206,15 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
result='failure',
|
||||
error_code=xfa_outcome.error_code,
|
||||
)
|
||||
elif snapshot.get('status') == 'ready':
|
||||
elif xfa_snapshot.get('status') == 'ready':
|
||||
_layout_job_audit(
|
||||
event_type='xfa_structure_analysis_ready',
|
||||
job=job,
|
||||
version=version,
|
||||
metadata={
|
||||
'document_kind': snapshot.get('document_kind'),
|
||||
'document_kind': xfa_snapshot.get('document_kind'),
|
||||
'structure_analysis_id': (
|
||||
(snapshot.get('xfa_capability') or {}).get('structure_analysis_id')
|
||||
(xfa_snapshot.get('xfa_capability') or {}).get('structure_analysis_id')
|
||||
),
|
||||
},
|
||||
)
|
||||
@@ -221,15 +228,19 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
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,
|
||||
counts=counts,
|
||||
)
|
||||
# XFA datasets 与视觉 Layout 是同一文档的两种证据。即使 XFA 结构分析成功,
|
||||
# 也必须继续构建通用表格/坐标 Layout,供统一 main_table_id、标注与验证使用。
|
||||
# datasets capability 仅在末端 value adapter 选择正式取值来源,不能再短路生命周期。
|
||||
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,
|
||||
counts=counts,
|
||||
)
|
||||
if snapshot is not None and xfa_capability is not None:
|
||||
snapshot['xfa_capability'] = xfa_capability
|
||||
timings['snapshot_build_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
if snapshot is None:
|
||||
snapshot = {
|
||||
@@ -286,7 +297,7 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
error_code=LAYOUT_JOB_ERROR,
|
||||
metadata={'error': str(exc)[:200]},
|
||||
)
|
||||
fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=True, owned_attempt=owned_attempt)
|
||||
fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=False, owned_attempt=owned_attempt)
|
||||
sync_layout_after_job_failure(job.id)
|
||||
# 仅当重试已耗尽时版本才会转 failed;此时需要唤醒等待中的 Run,
|
||||
# 让用户看到“附件解析失败”而不是永久停留在“正在解析”。
|
||||
|
||||
@@ -34,6 +34,21 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch
|
||||
|
||||
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
|
||||
result_data = result.get('data') if isinstance(result, dict) else None
|
||||
result_status = str(
|
||||
(result_data or {}).get('result_status') if isinstance(result_data, dict) else ''
|
||||
).strip().lower()
|
||||
if result_status in {'failed', 'partial_failed'}:
|
||||
failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
|
||||
first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(first_error or f'inventory_callback_business_{result_status}'),
|
||||
result={'status': 'processed', 'callback_result': result},
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'status': 'processed', 'callback_result': result},
|
||||
@@ -46,6 +61,6 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
||||
job.id,
|
||||
error=str(exc),
|
||||
result={'status': 'processing_failed', 'error': str(exc)[:1000]},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -58,7 +58,7 @@ def handle_shipping_line_auto_fulfill(ctx: JobContext, payload: dict) -> None:
|
||||
job_id,
|
||||
error=str(result.get('error') or 'auto_fulfill_failed'),
|
||||
result=result,
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
@@ -74,7 +74,7 @@ def handle_shipping_line_auto_fulfill(ctx: JobContext, payload: dict) -> None:
|
||||
job_id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed'},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -264,7 +264,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
# 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回)
|
||||
if str(fail_result.get('reason') or '') == 'stale_parse_lease':
|
||||
return
|
||||
retryable = _is_retryable_exc(exc)
|
||||
retryable = False
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
job_id,
|
||||
@@ -272,5 +272,3 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
if retryable:
|
||||
raise
|
||||
@@ -13,9 +13,13 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import inspect
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
@@ -44,6 +48,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
ensure_workflow_items_for_run,
|
||||
progress_ready_extraction_unit,
|
||||
schedule_order_extraction_layouts,
|
||||
synchronize_order_extraction_expansion_snapshot,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_progress import (
|
||||
@@ -55,7 +60,6 @@ from app.services.shipping_notice.order_extraction_workflow import (
|
||||
validate_unit_orders,
|
||||
)
|
||||
|
||||
MAX_UNIT_TECHNICAL_ATTEMPTS = 3
|
||||
EXPANDABLE_UNIT_REVIEW_REASON_CODES = {
|
||||
'required_anchor_missing',
|
||||
'required_field_missing',
|
||||
@@ -107,13 +111,52 @@ def _json_safe_order_payload(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return {str(key): _json_safe_order_payload(item) for key, item in value.items()}
|
||||
return value
|
||||
|
||||
|
||||
def _route_runtime_diagnostic() -> dict[str, str]:
|
||||
"""
|
||||
返回订单路由代码的最小运行期身份,用于定位 Worker 与本地重放不一致。
|
||||
|
||||
核心逻辑:仅记录解释器和已加载 ``route_deterministic_unit`` 源文件的路径/摘要;
|
||||
不读取或记录 PDF、datasets、坐标文字及订单字段值。
|
||||
|
||||
Returns:
|
||||
脱敏运行期身份字典。源文件不可读时以 ``unavailable`` 明确表示,不能阻断建单。
|
||||
"""
|
||||
source_path = inspect.getsourcefile(route_deterministic_unit)
|
||||
source_digest = 'unavailable'
|
||||
if source_path:
|
||||
try:
|
||||
source_digest = hashlib.sha256(Path(source_path).read_bytes()).hexdigest()
|
||||
except OSError:
|
||||
# 诊断是审计增强,文件暂不可读不能影响已完成的业务路由。
|
||||
pass
|
||||
return {
|
||||
'interpreter': str(sys.executable),
|
||||
'workflow_module_path': str(source_path or 'unavailable'),
|
||||
'workflow_source_sha256': source_digest,
|
||||
}
|
||||
|
||||
|
||||
EXPANDABLE_ORDER_CONFLICT_REASONS = {
|
||||
'supplement_relation_ambiguous',
|
||||
}
|
||||
|
||||
|
||||
def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) -> None:
|
||||
"""追加 Unit 脱敏路由投影及统一审计,尝试号必须区分同一 Job 内的单元重试。"""
|
||||
"""
|
||||
追加 Unit 脱敏路由投影、统一审计和运行期身份,尝试号必须区分同一 Job 内的单元重试。
|
||||
|
||||
核心逻辑:结构化列保存查询字段;审计 metadata 追加不含业务原文的运行期源码身份,
|
||||
使 Worker 结果可与相同冻结 Run 的只读重放逐项比对。
|
||||
|
||||
Args:
|
||||
run: 当前冻结订单抽取 Run。
|
||||
unit: 当前附件处理单元。
|
||||
job: 消费该单元的 Job。
|
||||
attempt_no: Unit 内的执行代次。
|
||||
route_result: 统一确定性路由结果。
|
||||
"""
|
||||
decision = route_result.decision if isinstance(route_result.decision, dict) else {}
|
||||
candidates = decision.get('candidate_summary') if isinstance(decision.get('candidate_summary'), list) else []
|
||||
safe_candidates = [{
|
||||
@@ -171,6 +214,7 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
decision.get('generic_completeness')
|
||||
if isinstance(decision.get('generic_completeness'), dict) else None
|
||||
),
|
||||
'runtime_diagnostic': _route_runtime_diagnostic(),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -397,6 +441,11 @@ def _activate_expansion_batch(
|
||||
schema_definition=schema_definition if isinstance(schema_definition, dict) else {},
|
||||
selection_batches={int(selection_batch)},
|
||||
)
|
||||
synchronize_order_extraction_expansion_snapshot(
|
||||
run,
|
||||
selection_batch=int(selection_batch),
|
||||
)
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
return ensure_order_extraction_plan_batch(run, selection_batch=int(selection_batch))
|
||||
|
||||
|
||||
@@ -410,7 +459,7 @@ def _reload_run_and_unit(*, run_id: int, unit_id: int) -> tuple[ShippingOrderPro
|
||||
|
||||
|
||||
def _record_unit_technical_failure(*, run, unit, job, exc: Exception, retryable: bool) -> None:
|
||||
"""将单元异常收敛为稳定技术失败事实,并在可重试时回到 pending。"""
|
||||
"""将单元异常收敛为稳定技术失败事实;失败即停止,不回到 pending。"""
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
error_code = str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED')
|
||||
@@ -431,24 +480,11 @@ def _record_unit_technical_failure(*, run, unit, job, exc: Exception, retryable:
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
if retryable and int(unit.attempt_count or 0) < MAX_UNIT_TECHNICAL_ATTEMPTS:
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='technical_retrying',
|
||||
reason_code=error_code,
|
||||
summary={
|
||||
'next_attempt_count': int(unit.attempt_count or 0) + 1,
|
||||
'max_attempt_count': MAX_UNIT_TECHNICAL_ATTEMPTS,
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
|
||||
|
||||
def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[dict] | None:
|
||||
"""
|
||||
独立处理一个附件单元;技术失败最多自动重试 2 次,不影响其他单元继续执行。
|
||||
独立处理一个附件单元;技术失败立即停在失败事实,不自动重试。
|
||||
|
||||
核心逻辑:正常从 pending 开始;若进程/事务异常遗留 routing、matching_profile、extracting
|
||||
或 merging_supplement,则先经 failed→pending 恢复稳定检查点,再开启新的确定性尝试。
|
||||
@@ -613,12 +649,10 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
return unit_orders
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
retryable = False
|
||||
run, unit = _reload_run_and_unit(run_id=int(run.id), unit_id=int(unit.id))
|
||||
_record_unit_technical_failure(run=run, unit=unit, job=job, exc=exc, retryable=retryable)
|
||||
db.session.commit()
|
||||
if retryable and int(unit.attempt_count or 0) < MAX_UNIT_TECHNICAL_ATTEMPTS:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
@@ -1177,7 +1211,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
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))
|
||||
retryable = False
|
||||
if run is not None and run.status in {'queued', 'processing', 'failed'}:
|
||||
running_unit = ShippingOrderProcessingUnit.query.join(ShippingOrderProcessingPlan).filter(
|
||||
ShippingOrderProcessingPlan.run_id == run.id,
|
||||
@@ -1198,18 +1232,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
reason_code=str(getattr(exc, 'code', None) or 'technical_failure'),
|
||||
job_id=job.id,
|
||||
)
|
||||
if retryable and owned_attempt < int(job.max_attempts or 1):
|
||||
if run.status == 'processing':
|
||||
if running_unit is not None:
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=running_unit,
|
||||
event_code='technical_retrying',
|
||||
reason_code=str(getattr(exc, 'code', None) or 'technical_failure'),
|
||||
job_id=job.id,
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='queued', phase='retry_queued')
|
||||
elif run.status in {'queued', 'processing'}:
|
||||
if run.status in {'queued', 'processing'}:
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='failing')
|
||||
transition_order_extraction_run(
|
||||
@@ -1219,5 +1242,3 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
db.session.commit()
|
||||
fail_job(job.id, error=str(exc), retryable=retryable, owned_attempt=owned_attempt)
|
||||
if retryable:
|
||||
raise
|
||||
@@ -43,7 +43,7 @@ def run_shipping_pdf_automark(ctx: JobContext, payload: dict) -> None:
|
||||
job.id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed', 'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_FAILED'},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -84,7 +84,7 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non
|
||||
job_id,
|
||||
error=err[:500],
|
||||
result={'status': 'failed', 'wave_no': wave_no, 'generate_excel': gen},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
@@ -115,7 +115,7 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non
|
||||
job_id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed', 'wave_no': wave_no},
|
||||
retryable=True,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -4,13 +4,10 @@ backend/app/jobs/handlers/shipping_review_revalidate_progress.py
|
||||
用途:消费 Review Revalidate Job,在 Case 字段变更后异步刷新校验、
|
||||
重跑 STP 资格判定、推进自动入队协调。
|
||||
依赖:JobContext、order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress、
|
||||
jobs.queue finish/fail、recovery_contract.is_tech_retryable_error。
|
||||
jobs.queue finish/fail。
|
||||
逻辑:由 shipping worker 领取;按 business_ref(case_no)+ 部分唯一索引保证同 Case 不重复入队;
|
||||
成功 finish 写 result_json(包含 enqueue_status / customer_step_status / validate_status);
|
||||
失败统一走错误分类:
|
||||
- AppError.is_tech_retryable_error 命中 → fail_job(retryable=True)
|
||||
- 其它 AppError 业务阻断 → fail_job(retryable=False)
|
||||
- 非预期 Exception → category_hint=temporary_storage_error,默认 retryable=True
|
||||
失败统一终态化,等待用户再次提交明确动作。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,7 +22,6 @@ 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.recovery_contract import is_tech_retryable_error
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -47,16 +43,14 @@ def _classify_revalidate_error(
|
||||
category_hint: str | None = None,
|
||||
) -> tuple[bool, dict[str, Any]]:
|
||||
"""
|
||||
将 Revalidate Job 执行失败按 recovery_contract 统一分类,输出 retryable、合并后的 result。
|
||||
将 Revalidate Job 执行失败统一收口为人工阻断。
|
||||
|
||||
【AI 触发时机】:Handler 的两条 fail 路径(AppError 兜底、非预期 Exception 兜底)
|
||||
统一调用,确保 Job.result_json schema 一致。
|
||||
|
||||
核心逻辑(fail-closed):
|
||||
[STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀
|
||||
→ result.status=failed_transient,retryable=True。
|
||||
[STEP 2] 否则 result.status=blocked_manual,retryable=False。
|
||||
[STEP 3] 返回二元组(retryable, normalized_result_dict)。
|
||||
[STEP 1] 记录稳定失败事实 result.status=blocked_manual、retryable=False。
|
||||
[STEP 2] 返回二元组(False, normalized_result_dict)。
|
||||
|
||||
Args:
|
||||
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
|
||||
@@ -66,8 +60,8 @@ def _classify_revalidate_error(
|
||||
Returns:
|
||||
(retryable: bool, normalized_result: dict)。
|
||||
"""
|
||||
tech = is_tech_retryable_error(error_code, category_hint=category_hint)
|
||||
result_status = 'failed_transient' if tech else 'blocked_manual'
|
||||
tech = False
|
||||
result_status = 'blocked_manual'
|
||||
normalized: dict[str, Any] = {
|
||||
'contract_version': 'shipping-recovery-v1-phase1',
|
||||
'status': result_status,
|
||||
@@ -78,7 +72,7 @@ def _classify_revalidate_error(
|
||||
'contract_version': 'shipping-recovery-v1-phase1',
|
||||
'stage': 'revalidate_classify_error',
|
||||
'retryable': bool(tech),
|
||||
'matched_rule': 'tech_retryable_whitelist' if tech else 'business_blocking_default',
|
||||
'matched_rule': 'failure_stops_for_user_action',
|
||||
'category_hint': category_hint,
|
||||
},
|
||||
}
|
||||
@@ -98,8 +92,7 @@ def handle_shipping_review_revalidate_progress(ctx: JobContext, payload: dict) -
|
||||
[STEP 3] 调用 reconcile_single_case_for_auto_progress(case, trigger='review_revalidate_job', refresh_validation=True)。
|
||||
[STEP 4] 按 enqueue_status / customer_step_status / validate_status 分类:
|
||||
- 全部成功 → finish_job,写 result_json。
|
||||
[STEP 5] AppError:is_tech_retryable_error 命中 → fail_job(retryable=True),否则 retryable=False。
|
||||
[STEP 6] 非预期 Exception:category_hint=temporary_storage_error,retryable=True,最终 re-raise 保持 Worker 心跳。
|
||||
[STEP 5] 任意异常:fail_job(retryable=False),不自动重新入队。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文;当前执行体不依赖请求上下文。
|
||||
@@ -297,4 +290,3 @@ def handle_shipping_review_revalidate_progress(ctx: JobContext, payload: dict) -
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -3,16 +3,14 @@ backend/app/jobs/handlers/shipping_stp_auto_create.py
|
||||
|
||||
用途:消费 STP 自动建单 Job,执行 confirm_review_case 与确认后自动推进入队;
|
||||
按 recovery_contract 统一错误分类,业务阻断(如 NOTICE_EXACT_DUPLICATE)
|
||||
retryable=false + blocked_manual,技术失败白名单 retryable=true。
|
||||
任意失败均收口为 blocked_manual,等待用户选择明确恢复动作。
|
||||
依赖:JobContext、order_stp_auto_create_service.execute_stp_auto_create_job、
|
||||
jobs.queue finish/fail、recovery_contract(is_tech_retryable_error、
|
||||
build_stp_job_blocked_manual_result / build_stp_job_failed_transient_result、
|
||||
jobs.queue finish/fail、recovery_contract(build_stp_job_blocked_manual_result、
|
||||
derive_blocking_next_actions)、fulfillment_audit.emit_stp_auto_create_blocked_manual_audit。
|
||||
逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单;
|
||||
成功 finish,附加 task_no / idempotent_replay;
|
||||
失败统一走 _classify_stp_result:
|
||||
- 技术白名单 → retryable=true(failed_transient)
|
||||
- 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
|
||||
- 所有失败 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,9 +32,7 @@ from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
)
|
||||
from app.services.shipping_notice.recovery_contract import (
|
||||
build_stp_job_blocked_manual_result,
|
||||
build_stp_job_failed_transient_result,
|
||||
derive_blocking_next_actions,
|
||||
is_tech_retryable_error,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -56,12 +52,10 @@ def _classify_stp_job_result(
|
||||
非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。
|
||||
|
||||
核心逻辑(fail-closed):
|
||||
[STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀
|
||||
→ build_stp_job_failed_transient_result,retryable=True。
|
||||
[STEP 2] 否则 build_stp_job_blocked_manual_result:
|
||||
[STEP 1] build_stp_job_blocked_manual_result:
|
||||
derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review;
|
||||
details 合并至 blocking_reason_details。
|
||||
[STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。
|
||||
[STEP 2] 返回三元组(False, normalized_result_dict, next_action)。
|
||||
|
||||
Args:
|
||||
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
|
||||
@@ -73,23 +67,10 @@ def _classify_stp_job_result(
|
||||
Returns:
|
||||
(retryable: bool, normalized_result: dict, next_action: str | None)。
|
||||
"""
|
||||
tech = is_tech_retryable_error(error_code, category_hint=category_hint)
|
||||
if tech:
|
||||
public_message = message
|
||||
if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
|
||||
public_message = '自动建单失败,系统将自动重试'
|
||||
transient: dict[str, Any] = build_stp_job_failed_transient_result(
|
||||
error_code=error_code,
|
||||
message=public_message,
|
||||
category_hint=category_hint,
|
||||
)
|
||||
if details:
|
||||
transient['blocking_reason_details'] = {
|
||||
**dict(transient.get('blocking_reason_details') or {}),
|
||||
**dict(details),
|
||||
}
|
||||
return True, transient, transient.get('next_action')
|
||||
|
||||
# 非预期基础设施异常的原始文本可能包含驱动/SQL 细节;用户只需要知道
|
||||
# 当前执行已停止并应在当前 Gate 选择动作,原文仅保留在 Worker 日志。
|
||||
if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
|
||||
message = '自动建单失败,已停止,等待用户选择下一步动作'
|
||||
actions = derive_blocking_next_actions(blocking_reason=error_code)
|
||||
next_action = actions[0] if actions else 'open_order_review'
|
||||
blocked: dict[str, Any] = build_stp_job_blocked_manual_result(
|
||||
@@ -295,7 +276,7 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
|
||||
# 对外消息必须稳定且可读;原始异常只进入日志/诊断 details,禁止把 SQL/驱动文本写入用户态 Job。
|
||||
retryable, normalized, next_action = _classify_stp_job_result(
|
||||
error_code=raw_code,
|
||||
message='自动建单失败,系统将自动重试',
|
||||
message='自动建单失败,已停止,等待用户选择下一步动作',
|
||||
details=details,
|
||||
category_hint=category_hint,
|
||||
)
|
||||
@@ -309,7 +290,7 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(normalized.get('message') or '自动建单失败,系统将自动重试')[:2000],
|
||||
error=str(normalized.get('message') or '自动建单失败,已停止,等待用户选择下一步动作')[:2000],
|
||||
result=normalized,
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_xfa_ocr_automark.py
|
||||
|
||||
用途:异步执行 XFA OCR 自动标记(原生 PDF/PDFium 页图),产出 suggested visual_bindings(不自动 confirmed)。
|
||||
依赖:Job queue、order_document_profile_xfa_automark_service(执行体)、JobType。
|
||||
逻辑:由 shipping worker 领取;payload 含 profile_id/document_id/preview_render_checksum;
|
||||
不再依赖 /xfa/preview synthetic;空白壳返回空建议成功;OCR 不可用时 fail_job。
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_XFA_OCR_AUTOMARK)
|
||||
def run_shipping_xfa_ocr_automark(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行 XFA OCR 自动标记 Job。
|
||||
|
||||
核心逻辑:读取冻结 Job 载荷 → 委托 automark_service.execute_xfa_ocr_automark_job →
|
||||
finish/fail。OCR 引擎不可用时不可重试(明确业务码)。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文(堆栈仅运维可见)。
|
||||
payload: 须含 job_id;业务字段在 Job.payload_json。
|
||||
|
||||
Returns:
|
||||
None。
|
||||
"""
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
return
|
||||
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
frozen = dict(job.payload_json or {})
|
||||
frozen.setdefault('job_id', int(job.id))
|
||||
|
||||
from app.services.shipping_notice import order_document_profile_xfa_automark_service as automark_service
|
||||
|
||||
try:
|
||||
result = automark_service.execute_xfa_ocr_automark_job(frozen)
|
||||
except automark_service.XfaOcrAutomarkError as exc:
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc.message or exc)[:500],
|
||||
result={
|
||||
'status': 'failed',
|
||||
'error_code': exc.error_code,
|
||||
'preview_render_checksum': frozen.get('preview_render_checksum'),
|
||||
'details': dict(exc.details or {}),
|
||||
},
|
||||
retryable=bool(exc.retryable),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001 — 未知异常走可重试失败
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc)[:500],
|
||||
result={
|
||||
'status': 'failed',
|
||||
'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_AUTOMARK_FAILED',
|
||||
'preview_render_checksum': frozen.get('preview_render_checksum'),
|
||||
},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
finish_job(
|
||||
job.id,
|
||||
result=result,
|
||||
message='XFA OCR automark completed',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -582,7 +582,7 @@ def recover_stale_jobs(
|
||||
sibling: Job | None = None
|
||||
rowcount = 0
|
||||
|
||||
if snap_attempts < max_attempts:
|
||||
if str(domain or '') != 'shipping_notice' and snap_attempts < max_attempts:
|
||||
if _subject_to_parse_queued_unique(str(job.job_type or "")):
|
||||
try:
|
||||
sibling = _resolve_safe_supersede_sibling(
|
||||
@@ -616,7 +616,7 @@ def recover_stale_jobs(
|
||||
)
|
||||
.values(
|
||||
status="queued",
|
||||
message="任务执行超时,已回收等待重试",
|
||||
message="任务执行超时,已停止,等待用户选择下一步动作",
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
@@ -1054,5 +1054,12 @@ def process_next_job(
|
||||
return True, job_type_value
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
fail_job(job_id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
|
||||
# 发货通知失败必须停在当前 Gate,不能由通用 runner 隐式重新入队。
|
||||
# 其它领域维持既有技术重试策略。
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(exc),
|
||||
retryable=(str(domain or '').strip() != 'shipping_notice'),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
raise
|
||||
@@ -146,10 +146,12 @@ def mark_failed(job_id: int, *, message: str, owned_attempt: int | None = None)
|
||||
# 通用 Job 表命中则条件收口(rowcount=0 即代次/状态已变,安全 no-op)
|
||||
generic = db.session.query(Job.id).filter(Job.id == int(job_id)).first()
|
||||
if generic is not None:
|
||||
generic_job = db.session.get(Job, int(job_id))
|
||||
fail_job(
|
||||
int(job_id),
|
||||
error=message[:1000],
|
||||
retryable=True,
|
||||
# 发货通知失败即停止;Runner 的兜底异常也不得绕过业务 Gate 自动重新入队。
|
||||
retryable=False if str(getattr(generic_job, 'domain', '') or '') == 'shipping_notice' else True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -26,8 +26,6 @@ class JobType(StrEnum):
|
||||
SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress'
|
||||
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
||||
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
||||
# 旧 XFA 专用 Job 仅兼容已入队任务;新入口一律使用 SHIPPING_PDF_AUTOMARK。
|
||||
SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark'
|
||||
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
||||
SHIPPING_STP_AUTO_CREATE = 'shipping_stp_auto_create'
|
||||
# OT 后行级自动履约协调(flag 关闭时不入队)
|
||||
@@ -72,7 +70,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({
|
||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark', 'shipping_xfa_ocr_automark',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
|
||||
'shipping_inventory_callback_process',
|
||||
'shipping_auto_progress',
|
||||
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||
|
||||
Reference in new issue
Block a user