Merge branch 'hugo-shipping-notice' into dev

# Conflicts:
#	backend/app/api/__init__.py
#	backend/app/jobs/types.py
#	backend/app/models/__init__.py
#	backend/app/services/schedule/job_registry.py
#	docs/features/README.md
#	docs/funclist.md
#	docs/tec.md
#	frontend/src/locales/zh-CN/admin.json
This commit is contained in:
hugo committed 2026-09-07 10:15:13 +08:00
commit dac31e48bd
691 files changed
+53341 -14863

No files matched your search

+3
View File
@@ -8,6 +8,9 @@ backend/app/jobs/handlers/__init__.py
from app.jobs.handlers import ( # noqa: F401
contract_payment,
file_check_run,
in_transit_transfer_item,
in_transit_transfer_precheck,
in_transit_transfer_run,
kb_clean,
kb_dify_sync,
procurement_contract_review,
@@ -0,0 +1,29 @@
"""backend/app/jobs/handlers/in_transit_transfer_item.py
用途:Invoice 级执行 Job:对单个明细执行写前复查 + ERP 原子写入。
依赖:execution_service.execute_item、transfer deps、Job 注册表。
逻辑:payload 携带 item_id;单项结果不影响其他项。
"""
from __future__ import annotations
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.execution_service import execute_item
@register_handler(JobType.TRANSFER_ITEM)
def run_in_transit_transfer_item(_ctx, payload: dict) -> None:
"""执行单个 Invoice(异步路径)。
【AI 触发时机】:仅由 Item 入队路径调用;页面直连走 API 同步路径。
"""
payload = payload if isinstance(payload, dict) else {}
item_id = payload.get("item_id")
if item_id is None:
raise RuntimeError("missing_transfer_item_id")
execute_item(
item_id=int(item_id),
deps=transfer_deps.get_transfer_dependencies(),
)
@@ -0,0 +1,55 @@
"""backend/app/jobs/handlers/in_transit_transfer_precheck.py
用途:异步执行在途调拨预检(文件准备 + 只读预检),并更新预检状态。
依赖:Job 注册表、precheck_service、transfer 模型、transfer deps。
逻辑:领取后按 payload.precheck_id 加载预检,运行 run_precheck 并回写
状态/计数/Hash;预检不存在时 fail-closed 抛 RuntimeError。
"""
from __future__ import annotations
from app import db
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import TransferPrecheck
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.precheck_service import run_precheck
@register_handler(JobType.TRANSFER_PRECHECK)
def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
"""执行一次预检 Job 并更新预检状态。
【AI 触发时机】:仅由预检创建异步路径入队;页面直连走 API 同步路径。
"""
payload = payload if isinstance(payload, dict) else {}
precheck_no = str(payload.get("precheck_id") or "").strip()
if not precheck_no:
raise RuntimeError("missing_transfer_precheck_id")
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=precheck_no).first()
if precheck is None:
raise RuntimeError(f"missing_transfer_precheck: {precheck_no}")
deps = transfer_deps.get_transfer_dependencies()
source_codes = list(precheck.scope_json.get("source_codes") or []) if isinstance(
precheck.scope_json, dict
) else []
result = run_precheck(
source_codes=source_codes,
business_date=precheck.business_date,
deps=deps,
run_no=precheck.run.run_no if precheck.run else "RUN-PENDING",
)
summary = result.summary
precheck.status = summary.status
precheck.counts_json = {
"file_invoice_count": summary.counts.file_invoice_count,
"not_matured_count": summary.counts.not_matured_count,
"prechecked_count": summary.counts.prechecked_count,
"executable_count": summary.counts.executable_count,
"blocked_count": summary.counts.blocked_count,
}
precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity
precheck.estimated_erp_write_count = summary.estimated_erp_write_count
precheck.precheck_hash = summary.precheck_hash
db.session.commit()
@@ -0,0 +1,29 @@
"""backend/app/jobs/handlers/in_transit_transfer_run.py
用途:Run 级执行 Job:加载预检并驱动执行服务完成全部可执行项写入。
依赖:execution_service、transfer deps、Job 注册表。
逻辑:payload 携带 precheck_id;执行后预检与 Run 落库终态。
"""
from __future__ import annotations
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.execution_service import execute_precheck
@register_handler(JobType.TRANSFER_RUN)
def run_in_transit_transfer_run(_ctx, payload: dict) -> None:
"""执行一个 Run(异步路径)。
【AI 触发时机】:仅由执行 Run 入队路径调用;页面直连走 API 同步路径。
"""
payload = payload if isinstance(payload, dict) else {}
precheck_id = str(payload.get("precheck_id") or "").strip()
if not precheck_id:
raise RuntimeError("missing_transfer_precheck_id")
execute_precheck(
precheck_id=precheck_id,
deps=transfer_deps.get_transfer_dependencies(),
)
@@ -35,15 +35,24 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
result_data = result.get('data') if isinstance(result, dict) else None
transport_status = str(
result.get('status') if isinstance(result, dict) else ''
).strip().lower()
result_status = str(
(result_data or {}).get('result_status') if isinstance(result_data, dict) else ''
).strip().lower()
if result_status in {'failed', 'partial_failed'}:
if transport_status == 'failed' or 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
from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback
settle_failed_inventory_callback(
dict(job.payload_json or {}),
error=str(first_error or (result or {}).get('message') or 'inventory_callback_processing_failed'),
)
fail_job(
job.id,
error=str(first_error or f'inventory_callback_business_{result_status}'),
error=str(first_error or (result or {}).get('message') or f'inventory_callback_business_{result_status or transport_status}'),
result={'status': 'processed', 'callback_result': result},
retryable=False,
owned_attempt=owned_attempt,
@@ -16,9 +16,9 @@ from datetime import datetime
from sqlalchemy import and_, or_, update
from app import db
from app.core.errors import AppError, NotFoundError
from app.core.errors import NotFoundError
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.queue import _is_retryable_exc, fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import FileAsset, Job, ShippingOrderIntake
@@ -120,15 +120,6 @@ def _claim_intake_for_parsing(
return intake, lease
def _is_retryable_exc(exc: BaseException) -> bool:
"""业务 NotFound / AppError.retryable=False 视为不可再排队。"""
if isinstance(exc, NotFoundError):
return False
if isinstance(exc, AppError):
return bool(getattr(exc, 'retryable', False))
return True
@register_handler(JobType.SHIPPING_NOTICE_PARSE)
def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
"""
@@ -264,7 +255,9 @@ 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 = False
# 失败收口按异常类型分级:业务失败(NotFound/AppError.retryable=False)停排,
# 瞬时基础设施异常才允许重试;不按业务域一刀切。
retryable = _is_retryable_exc(exc)
if job_id is not None:
fail_job(
job_id,
@@ -272,3 +265,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
retryable=retryable,
owned_attempt=owned_attempt,
)
# 重试类异常交由外层运行时统一收口(fail_job 已 requeue);非重试业务失败已直接
# fail_job 为 failed,不再重抛,避免向上滚动。
if retryable:
raise
@@ -67,7 +67,7 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non
gen = generate_excel({
'task_id': task.task_no,
'wave_no': wave_no,
'line_keys': list(frozen.get('line_keys') or []),
'snapshot_line_ids': list(frozen.get('snapshot_line_ids') or []),
'post_ot_wave': True,
'_orchestrator_internal_dispatch': True,
})
@@ -84,6 +84,18 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
attempt_id = int(payload.get('attempt_id') or 0)
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
external_wait_poll_gate_id = int(payload.get('external_wait_poll_gate_id') or 0)
if external_wait_poll_gate_id and job is not None:
from app.services.shipping_notice.process_gate_job_service import run_inventory_external_wait_poll
result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id)
finish_job(job.id, result=result, owned_attempt=int(job.attempts or 0))
if str(result.get('gate_status') or '') == 'waiting_external':
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
if gate is not None and gate.latest_attempt_id:
schedule_waiting_external_poll(attempt_id=int(gate.latest_attempt_id))
db.session.commit()
return
if attempt_id <= 0 or job is None:
raise RuntimeError('missing_attempt_id_or_job_id')
@@ -10,7 +10,8 @@ backend/app/jobs/handlers/shipping_stp_auto_create.py
逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单;
成功 finish,附加 task_no / idempotent_replay;
失败统一走 _classify_stp_result:
- 所有失败 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
- 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
- 临时基础设施异常 → retryable=true(保留普通重试入口)
"""
from __future__ import annotations
@@ -51,11 +52,10 @@ def _classify_stp_job_result(
【AI 触发时机】:Handler 的三条 fail 路径(业务拒绝 ok=False、AppError 兜底、
非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。
核心逻辑(fail-closed):
[STEP 1] build_stp_job_blocked_manual_result:
derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review;
details 合并至 blocking_reason_details。
[STEP 2] 返回三元组(False, normalized_result_dict, next_action)。
核心逻辑:
[STEP 1] temporary_storage_error 走技术失败契约,允许普通重试;
[STEP 2] 其他错误走 build_stp_job_blocked_manual_result,要求人工裁决;
[STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。
Args:
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
@@ -71,6 +71,23 @@ def _classify_stp_job_result(
# 当前执行已停止并应在当前 Gate 选择动作,原文仅保留在 Worker 日志。
if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
message = '自动建单失败,已停止,等待用户选择下一步动作'
if category_hint == 'temporary_storage_error':
next_action = 'retry_stp_auto_create'
return True, {
'status': 'failed',
'retryable': True,
'error_code': str(error_code or '').strip(),
'message': str(message or ''),
'next_action': next_action,
'contract_version': 'shipping-recovery-v1-phase1',
'decision_trace': {
'contract_version': 'shipping-recovery-v1-phase1',
'stage': 'stp_classify_error',
'retryable': True,
'matched_rule': 'temporary_storage_error',
'category_hint': category_hint,
},
}, next_action
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(