feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口

完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
This commit is contained in:
hugo committed 2026-08-11 14:04:39 +08:00
1 parent 8e0bbf7a81
commit c94d173f92
181 files changed
+12947 -1724

No files matched your search

@@ -0,0 +1,57 @@
"""
APX 历史运行时只读清点。
用途:在正式 20-Gate 单轨切换前,统计数据库中仍处于运行态的 APX Execution/Job。
依赖:ShippingProcessExecution、Job ORM 模型。
逻辑:仅执行 SELECT,区分运行态与历史终态;调用方据此决定迁移或人工关闭,不在本模块修改数据。
"""
from __future__ import annotations
from app.models import Job, ShippingProcessExecution
_EXECUTION_RUNTIME_STATUSES = ('active', 'blocked', 'waiting_external')
_JOB_RUNTIME_STATUSES = ('queued', 'running', 'active')
def audit_apx_runtime_state() -> dict[str, object]:
"""只读统计 APX Execution/Job 运行态与历史态数量。
Returns:
包含 execution/job 两组计数。APX Job 通过 execution_no、business_ref 或
payload 中的 execution_id 关联;任何写操作都不在此函数执行。
"""
apx_executions = ShippingProcessExecution.query.filter(
ShippingProcessExecution.execution_no.ilike('APX-%')
).all()
runtime_execution_ids = {
int(row.id) for row in apx_executions
if str(row.status or '').lower() in _EXECUTION_RUNTIME_STATUSES
}
apx_jobs = Job.query.filter(
Job.domain == 'shipping_notice',
Job.status.in_(_JOB_RUNTIME_STATUSES),
).all()
runtime_job_count = 0
for job in apx_jobs:
if int(job.execution_id or 0) in runtime_execution_ids:
runtime_job_count += 1
continue
if str(job.business_ref or '').upper().find('APX-') >= 0:
runtime_job_count += 1
continue
payload = job.payload_json if isinstance(job.payload_json, dict) else {}
if str(payload.get('execution_no') or '').upper().startswith('APX-'):
runtime_job_count += 1
return {
'execution': {
'active_count': len(runtime_execution_ids),
'historical_count': len(apx_executions) - len(runtime_execution_ids),
},
'job': {
'active_count': runtime_job_count,
},
}
@@ -10,13 +10,15 @@ services/shipping_notice/auto_progress_controller.py
from __future__ import annotations
import uuid
from datetime import datetime
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from app import db
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.tool_common import log_task_event
@@ -33,6 +35,24 @@ _ACTIVE_JOB_STATUSES = ('queued', 'running')
_CANCELLED_TASK_STATUSES = frozenset({'cancelled', 'canceled', 'closed', 'rejected'})
def audit_legacy_forwarded_entrypoint(
*, task: ShippingNotice, action_code: str, actor_id: int | None = None,
request_id: str | None = None,
) -> None:
"""记录旧工作台入口已转发至正式 Gate Orchestrator 的审计事实。"""
log_task_event(
task,
'shipping_legacy_entrypoint_forwarded',
{
'entrypoint': 'legacy_forwarded',
'action_code': str(action_code or '').strip(),
},
actor_id=actor_id,
request_id=request_id,
source='workspace_api',
)
def _utc_now() -> datetime:
"""返回仓库统一使用的 naive UTC 时间。"""
return datetime.utcnow()
@@ -43,6 +63,43 @@ def _task_is_cancelled(task: ShippingNotice) -> bool:
return str(getattr(task, 'process_status', '') or '').strip().lower() in _CANCELLED_TASK_STATUSES
def _recover_stale_active_job(job: Job) -> bool:
"""
在用户触发入口原子回收超时的 AutoProgress running Job。
核心逻辑:仅处理 started_at 已超过通用发货 Job 超时的 running 行;旧 Job
终态保留审计,关联 running/queued Gate 改为 blocked_retryable,使当前事务可重新入队。
Args:
job: 已由 submit_auto_progress 锁定的活动 Job。
Returns:
True 表示旧 Job 已回收,调用方应继续创建新 Job;False 表示仍有效并复用。
"""
if str(job.status or '') != 'running' or job.started_at is None:
return False
timeout_seconds = float(
current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 420) or 420
)
if job.started_at >= _utc_now() - timedelta(seconds=timeout_seconds):
return False
now = _utc_now()
job.status = 'failed'
job.message = f'自动推进任务执行超时(超过 {int(timeout_seconds)}s),已允许重新入队'
job.error_message = 'shipping_auto_progress_timeout'
job.finished_at = now
job.locked_by = None
job.locked_at = None
job.updated_at = now
gate = db.session.get(ShippingProcessGate, int(job.gate_id)) if job.gate_id else None
if gate is not None and gate.status in {'queued', 'running'}:
gate.status = 'blocked_retryable'
gate.blocking_reason_code = 'technical_retry_exhausted'
gate.updated_at = now
db.session.flush()
return True
def _new_execution_no() -> str:
"""生成可读的 P0-3 Execution 编号。"""
return f'APX-{_utc_now().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}'
@@ -50,28 +107,111 @@ def _new_execution_no() -> str:
def _create_execution(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
"""
为当前 Task/CandidateSet 创建独立六 Gate 链。
禁止创建 APX 六 Gate Execution。
核心逻辑:不复用旧 20 Gate Execution,避免旧 skipped/waiting_external 语义污染 P0-3 的严格顺序。
APX 仅保留历史数据兼容;新任务和恢复入口必须通过正式 20-Gate
``ensure_execution_for_workflow_version`` 创建 Execution。
"""
execution = ShippingProcessExecution(
execution_no=_new_execution_no(), task_id=int(task.id), candidate_set_id=candidate_set_id,
execution_revision=1, status='active', current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1,
raise RuntimeError('shipping_apx_creation_disabled')
def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool:
"""按完整 20-Gate 合同识别正式 Execution;Task-only 正式链同样有效。"""
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
gate_codes = {
str(item.gate_code)
for item in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all()
}
return gate_codes == set(PROCESS_GATE_CODES)
def determine_formal_start_gate(
task: ShippingNotice,
*,
candidate_set: Any | None = None,
) -> str:
"""根据持久化 Task/CandidateSet 事实选择正式 20-Gate 的首个 Gate。
未确认的解析、冻结或候选事实一律回退到最早缺失 Gate,禁止由调用入口
直接跳过前置 Contract;仅完整冻结订单和 frozen CandidateSet 可进入库存准备。
"""
if not getattr(task, 'current_order_extraction_id', None):
return 'document_materialization'
if not getattr(task, 'order_snapshot_id', None):
return 'order_freeze_readiness'
# 仅当服务端已明确记录 pending/failed 时阻断客户确认;None 保留给历史
# Task-only 兼容构造,不能把缺失的可选字段误当成失败事实。
customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower()
if customer_status in {'pending', 'needs_review', 'failed', 'unresolved'}:
return 'customer_resolution'
# 字段冲突是独立的正式 Gate,必须先于候选冻结和库存准备处理。
if any(str(getattr(row, 'status', '') or '').strip().lower() == 'open' for row in (getattr(task, 'field_conflicts', None) or [])):
return 'field_conflict_resolution'
candidate = candidate_set if candidate_set is not None else get_active_candidate_set(task)
if candidate is None or str(getattr(candidate, 'lifecycle_status', '') or '').lower() != 'frozen':
return 'inventory_source_routing'
return 'inventory_preparation'
def _create_formal_execution_for_task(
task: ShippingNotice,
*,
candidate_set_id: int | None,
) -> ShippingProcessExecution:
"""为无正式链的已建 Task 创建唯一 20-Gate Execution,禁止新建 APX。"""
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
execution = ensure_execution_for_workflow_version(
task_id=int(task.id),
actor_type='system',
start_gate_code=determine_formal_start_gate(task),
)
db.session.add(execution)
db.session.flush()
for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1):
db.session.add(ShippingProcessGate(
execution_id=int(execution.id), gate_code=gate_code, sequence_no=sequence_no,
status='pending', evaluation_version=1, lock_version=1,
))
execution.candidate_set_id = candidate_set_id
task.active_process_execution_id = int(execution.id)
db.session.flush()
return execution
def _supersede_duplicate_execution(
execution: ShippingProcessExecution,
*,
replacement: ShippingProcessExecution,
) -> None:
"""收敛重复活动链;保留审计记录,不删除历史 Attempt/Job。"""
if execution.id == replacement.id or execution.status in {'completed', 'cancelled', 'superseded'}:
return
execution.status = 'superseded'
execution.updated_at = _utc_now()
ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(execution.id),
ShippingProcessGate.status.in_(
('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'invalidated'),
),
).update(
{'status': 'cancelled', 'updated_at': _utc_now()},
synchronize_session=False,
)
def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
"""锁定并取得当前 Execution;候选版本变化时旧链 superseded 后创建新链。"""
"""
锁定并取得当前唯一活动 Execution。
核心逻辑:正式 20-Gate 链是唯一运行时状态机;历史 APX 仅可读,
不得被重新激活或继续排队。候选版本变化仍按原规则 superseded。
"""
all_active = (
ShippingProcessExecution.query
.filter(
ShippingProcessExecution.task_id == int(task.id),
ShippingProcessExecution.status.in_(('active', 'blocked', 'waiting_external')),
)
.with_for_update()
.order_by(ShippingProcessExecution.id.asc())
.all()
)
formal = next((item for item in all_active if _is_formal_process_execution(item)), None)
current_id = getattr(task, 'active_process_execution_id', None)
execution = db.session.get(ShippingProcessExecution, int(current_id)) if current_id else None
if execution is not None:
@@ -80,6 +220,14 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
)
if execution is not None and int(getattr(execution, 'task_id', 0) or 0) != int(task.id):
execution = None
if formal is not None:
for duplicate in all_active:
if duplicate.id != formal.id:
_supersede_duplicate_execution(duplicate, replacement=formal)
task.active_process_execution_id = int(formal.id)
formal.updated_at = _utc_now()
db.session.flush()
return formal
if execution is not None and int(getattr(execution, 'candidate_set_id', 0) or 0) != int(candidate_set_id or 0):
# 旧链永不覆盖:未完成 Gate 取消,Execution 留审计后由新 CandidateSet 建链。
execution.status = 'superseded'
@@ -88,7 +236,17 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')),
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
execution = None
return execution or _create_execution(task, candidate_set_id=candidate_set_id)
# APX 仅作为历史数据兼容:新任务或无正式链 Task 一律创建正式 20-Gate。
if execution is not None:
execution.status = 'superseded'
execution.updated_at = _utc_now()
ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(execution.id),
ShippingProcessGate.status.in_(
('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'invalidated'),
),
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
return _create_formal_execution_for_task(task, candidate_set_id=candidate_set_id)
def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None:
@@ -101,14 +259,37 @@ def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None
if execution_id:
execution = ShippingProcessExecution.query.filter_by(id=int(execution_id)).with_for_update().first()
if execution is not None and execution.status not in {'completed', 'cancelled', 'superseded'}:
# Attempt 是不可变执行历史,但候选版本切换后其 queued/running 状态
# 必须显式终止,避免旧 Attempt 被 Worker 领取并污染新 CandidateSet。
ShippingProcessGateAttempt.query.filter(
ShippingProcessGateAttempt.gate_id.in_(
db.session.query(ShippingProcessGate.id).filter(
ShippingProcessGate.execution_id == int(execution.id),
)
),
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
).update(
{
'status': 'superseded',
'finished_at': _utc_now(),
'error_code': 'candidate_set_refrozen',
'error_summary': 'CandidateSet 已重冻结,旧 GateAttempt 终止',
},
synchronize_session=False,
)
execution.status = 'superseded'
ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(execution.id),
ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')),
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
Job.query.filter(
Job.domain == 'shipping_notice', Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value,
Job.task_id == int(task.id), Job.status == 'queued',
Job.domain == 'shipping_notice',
Job.job_type.in_((
JobType.SHIPPING_AUTO_PROGRESS.value,
JobType.SHIPPING_PROCESS_GATE.value,
)),
Job.task_id == int(task.id),
Job.status == 'queued',
).update({'status': 'cancelled', 'finished_at': _utc_now(), 'message': '候选版本已重冻结'}, synchronize_session=False)
@@ -122,7 +303,11 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
ShippingProcessGate.query.filter_by(execution_id=int(execution.id))
.order_by(ShippingProcessGate.sequence_no.asc()).with_for_update().all()
)
expected = list(AUTO_PROGRESS_GATE_CODES)
# 正式运行时只接受 20-Gate 合同;AUTO_PROGRESS_GATE_CODES 仅保留给历史
# APX 数据读取/迁移测试,不能再作为新任务的状态机校验来源。
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
expected = list(PROCESS_GATE_CODES)
if [item.gate_code for item in gates] != expected:
return None, 'projection_data_inconsistent'
pending_seen = False
@@ -145,172 +330,191 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
def submit_auto_progress(
*, task: ShippingNotice, trigger: str, operator_id: int | None = None,
resume_gate_code: str | None = None, commit: bool = True,
recovery_plan_id: int | None = None,
recovery_attempt_id: int | None = None,
resume_after_gate: str | None = None,
) -> dict[str, Any]:
"""
接收任何自动/用户触发并安全入队当前 Gate。
普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。
"""
locked_task = ShippingNotice.query.filter_by(id=int(task.id)).with_for_update().first()
# ShippingNotice.shipping_case 使用 joined eager load,会产生 LEFT OUTER JOIN;
# PostgreSQL 禁止对外连接可空侧执行无目标 FOR UPDATE,因此仅锁主表。
locked_task = (
ShippingNotice.query
.filter_by(id=int(task.id))
.with_for_update(of=ShippingNotice)
.first()
)
if locked_task is None:
return {'status': 'not_found'}
if _task_is_cancelled(locked_task):
return {'status': 'cancelled', 'task_no': locked_task.task_no}
# 只复用正式 ProcessGate Job。遗留 APX Job 已下线,不能阻塞或劫持正式链入队。
# 先查活动 Job,再读取/改写 Candidate 或 Execution 指针。这样候选重冻结与重复点击
# 无法把一个仍 running 的旧 Job 错绑到新链。
# 无法把一个仍 running 的正式 Job 错绑到新链。
active = (
Job.query.filter(
Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value,
Job.job_type == JobType.SHIPPING_PROCESS_GATE.value,
Job.task_id == int(locked_task.id),
Job.status.in_(_ACTIVE_JOB_STATUSES),
).with_for_update().order_by(Job.id.desc()).first()
)
if active is not None:
if commit:
db.session.commit()
return {
'status': 'queued' if active.status == 'queued' else 'running',
'job_id': int(active.id), 'execution_id': active.execution_id,
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True,
}
if not _recover_stale_active_job(active):
if commit:
db.session.commit()
return {
'status': 'queued' if active.status == 'queued' else 'running',
'job_id': int(active.id), 'execution_id': active.execution_id,
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True,
}
log_task_event(locked_task, 'auto_progress_stale_job_recovered', {
'stale_job_id': int(active.id),
'execution_id': active.execution_id,
'gate_id': active.gate_id,
'trigger': trigger,
}, actor_id=operator_id, source=trigger)
candidate = get_active_candidate_set(locked_task)
candidate_set_id = int(candidate.id) if candidate is not None else None
execution = _active_execution_for_task(locked_task, candidate_set_id=candidate_set_id)
gate, inconsistency = _earliest_runnable_gate(execution)
if inconsistency:
execution.status = 'blocked'
execution.current_gate_code = None
log_task_event(locked_task, 'auto_progress_projection_inconsistent', {
'execution_id': execution.id, 'reason_code': inconsistency,
}, actor_id=operator_id, source=trigger)
if _is_formal_process_execution(execution):
# 正式 Case 的 20 Gate Execution 是唯一业务真相;APX 六 Gate 仅兼容
# 无 Case 的旧 Task。先同步已落库事实,再把当前技术 Gate 交给唯一
# ProcessGate Job/Attempt 通道;不得在此同步执行或退回 APX 六 Gate Job。
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.process_gate_contract import is_technical_gate_party
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=operator_id,
)
db.session.flush()
execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one()
current_gate = str(execution.current_gate_code or '').strip() or None
gate = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id), gate_code=current_gate)
.with_for_update()
.first()
if current_gate else None
)
active_attempt = (
ShippingProcessGateAttempt.query
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
)
.order_by(ShippingProcessGateAttempt.attempt_no.desc())
.first()
if gate is not None else None
)
if active_attempt is not None and active_attempt.job_id:
if commit:
db.session.commit()
return {
'status': 'queued' if active_attempt.status == 'queued' else 'running',
'job_id': int(active_attempt.job_id),
'attempt_id': int(active_attempt.id),
'execution_id': int(execution.id),
'gate_code': gate.gate_code,
'reused': True,
}
action_code = str(getattr(gate, 'next_action_code', '') or '').strip()
# 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的
# system/worker Gate 才可自动创建 Attempt 并入队。
if gate is not None and action_code and is_technical_gate_party(execution.responsible_party):
attempt = queue_gate_attempt(
execution_no=str(execution.execution_no),
gate_code=str(gate.gate_code),
trigger_type='auto',
actor_type='system',
actor_id=operator_id,
idempotency_key=(
f'shipping-auto-progress:{locked_task.id}:{execution.id}:'
f'{gate.id}:{gate.evaluation_version}'
),
expected_gate_version=int(gate.evaluation_version),
input_snapshot={
'action_code': action_code,
'payload': {
'candidate_set_id': candidate_set_id,
'fencing_token': uuid.uuid4().hex,
'trigger': trigger,
'recovery_plan_id': recovery_plan_id,
'recovery_attempt_id': recovery_attempt_id,
'resume_after_gate': resume_after_gate,
},
},
)
job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=operator_id)
log_task_event(locked_task, 'auto_progress_gate_attempt_queued', {
'job_id': job_id,
'attempt_id': int(attempt.id),
'attempt_no': int(attempt.attempt_no),
'execution_id': int(execution.id),
'candidate_set_id': candidate_set_id,
'gate_id': int(gate.id),
'gate_code': gate.gate_code,
'trigger': trigger,
}, actor_id=operator_id, source=trigger)
if commit:
db.session.commit()
return {
'status': 'queued',
'job_id': int(job_id),
'attempt_id': int(attempt.id),
'execution_id': int(execution.id),
'gate_code': gate.gate_code,
'reused': bool(attempt.status != 'queued'),
}
result = {
'status': 'waiting_human' if execution.status == 'blocked' else execution.status,
'execution_id': int(execution.id),
'gate_code': current_gate,
'reused': True,
}
if commit:
db.session.commit()
return {'status': 'waiting_human', 'reason_code': inconsistency, 'execution_id': execution.id}
if gate is None:
return result
# 理论上 _active_execution_for_task 已将活动 APX 收敛为正式链;若仍出现
# 非正式 Execution,必须 fail-closed,禁止重新创建旧 APX Job。
if not _is_formal_process_execution(execution):
if commit:
db.session.commit()
return {'status': 'waiting_human' if execution.status == 'blocked' else 'completed', 'execution_id': execution.id}
business_ref = f'auto-progress:{int(locked_task.id)}'
token = uuid.uuid4().hex
job_id = enqueue(
JobType.SHIPPING_AUTO_PROGRESS,
{'task_no': locked_task.task_no, 'task_id': int(locked_task.id), 'execution_id': int(execution.id),
'candidate_set_id': candidate_set_id, 'gate_id': int(gate.id), 'gate_code': gate.gate_code,
'trigger': trigger, 'requested_resume_gate_code': resume_gate_code, 'fencing_token': token},
domain='shipping_notice', business_ref=business_ref, created_by_id=operator_id,
message=f'等待执行正式 Gate:{gate.gate_code}', max_attempts=1, commit=False,
task_id=int(locked_task.id), execution_id=int(execution.id), gate_id=int(gate.id),
candidate_set_id=candidate_set_id, fencing_token=token,
)
execution.current_gate_code = gate.gate_code
log_task_event(locked_task, 'auto_progress_job_queued', {
'job_id': job_id, 'execution_id': execution.id, 'candidate_set_id': candidate_set_id,
'gate_id': gate.id, 'gate_code': gate.gate_code, 'trigger': trigger,
}, actor_id=operator_id, source=trigger)
if commit:
db.session.commit()
return {'status': 'queued', 'job_id': int(job_id), 'execution_id': int(execution.id), 'gate_code': gate.gate_code}
def _gate_outcome(task: ShippingNotice, gate: ShippingProcessGate) -> tuple[str, str | None, dict[str, Any]]:
"""仅执行一个 Gate 并把现有业务服务结果归一为正式 Gate 结果。"""
code = gate.gate_code
candidate = get_active_candidate_set(task)
if code == 'inventory_candidates_calculated':
return ('passed', None, {}) if candidate is not None else ('blocked_manual', 'inventory_candidates_required', {})
if code == 'inventory_candidates_frozen':
frozen = candidate is not None and str(candidate.lifecycle_status) == 'frozen'
return ('passed', None, {}) if frozen else ('blocked_manual', 'inventory_candidates_frozen_required', {})
if code == 'inventory_snapshots_ready':
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
result = ensure_all_required_sources_prepared(task, mode='auto')
if result.all_prepared:
return 'passed', None, {'prepared_sources': result.prepared_source_codes}
if result.failed_source_codes:
return 'blocked_manual', 'inventory_snapshot_prepare_failed', {'failed_sources': result.failed_source_codes}
return 'blocked_retryable', 'inventory_snapshots_pending', {'pending_sources': result.pending_source_codes}
if code == 'inventory_matched':
from app.services.shipping_notice.fulfillment_workflow import match_inventory
result = match_inventory({'task_id': task.task_no, '_orchestrator_internal_dispatch': True})
status = str((result or {}).get('status') or '')
if status in {'ok', 'completed'}:
return 'passed', None, {}
return 'blocked_manual' if status == 'needs_human' else 'blocked_retryable', 'inventory_match_not_ready', {'legacy_status': status}
if code == 'excel_generated':
from app.services.shipping_notice.fulfillment_workflow import generate_excel
result = generate_excel({'task_id': task.task_no, '_orchestrator_internal_dispatch': True})
if str((result or {}).get('status') or '') == 'ok' and task.export_file_path:
return 'passed', None, {'export_file_path': task.export_file_path}
return 'blocked_retryable', 'excel_generation_not_ready', {'legacy_status': (result or {}).get('status')}
receipt = getattr(task, 'upload_receipt_json', None)
if receipt or str(getattr(task, 'process_status', '') or '').lower() in {'uploaded', 'completed'}:
return 'passed', None, {}
return 'blocked_manual', 'manual_upload_receipt_required', {}
return {
'status': 'legacy_readonly',
'reason_code': 'shipping_apx_runtime_disabled',
'execution_id': int(execution.id),
}
def run_auto_progress_job(*, job_id: int, worker_id: str) -> dict[str, Any]:
"""
Worker 执行一个且仅一个 Gate,并以 Job outbox 原子提交 Gate 成功和下一个 Job。
将历史 APX AutoProgress Job 终态化,禁止六 Gate 状态机继续运行。
所有围栏、Task 取消和 Candidate/Execution identity 都在外部调用前复查;不匹配的迟到 Job 只终态审计。
APX 已下线为只读历史兼容。Worker 仍消费遗留 queued/running Job,
但只能取消并保留审计,绝不能触发库存、匹配、Excel 或下一 Gate。
"""
job = Job.query.filter_by(id=int(job_id)).with_for_update().first()
if job is None or job.status != 'running':
return {'status': 'noop'}
payload = dict(job.payload_json or {})
task = ShippingNotice.query.filter_by(id=int(job.task_id or 0)).with_for_update().first()
execution = ShippingProcessExecution.query.filter_by(id=int(job.execution_id or 0)).with_for_update().first()
now = _utc_now()
gate = ShippingProcessGate.query.filter_by(id=int(job.gate_id or 0)).with_for_update().first()
stale = (
task is None or execution is None or gate is None or _task_is_cancelled(task)
or int(getattr(task, 'active_process_execution_id', 0) or 0) != int(execution.id)
or int(getattr(execution, 'candidate_set_id', 0) or 0) != int(job.candidate_set_id or 0)
or int(gate.execution_id) != int(execution.id)
or str(job.fencing_token or '') != str(payload.get('fencing_token') or '')
)
if stale:
job.status = 'cancelled'; job.finished_at = _utc_now(); job.message = '任务已取消或版本围栏不匹配'
if gate is not None and gate.status in {'pending', 'queued', 'running'}:
gate.status = 'cancelled'
db.session.commit()
return {'status': 'cancelled'}
runnable, inconsistency = _earliest_runnable_gate(execution)
if inconsistency or runnable is None or int(runnable.id) != int(gate.id):
gate.status = 'blocked_manual'; gate.blocking_reason_code = inconsistency or 'projection_data_inconsistent'
execution.status = 'blocked'; job.status = 'success'; job.finished_at = _utc_now()
db.session.commit()
return {'status': 'waiting_human', 'reason_code': gate.blocking_reason_code}
gate.status = 'running'; gate.updated_at = _utc_now(); db.session.flush()
outcome, reason_code, details = _gate_outcome(task, gate)
gate.status = outcome; gate.blocking_reason_code = reason_code; gate.effective_result_json = details
gate.updated_at = _utc_now(); job.status = 'success'; job.finished_at = _utc_now(); job.message = f'Gate {outcome}'
if outcome != 'passed':
execution.status = 'blocked'; execution.current_gate_code = gate.gate_code
log_task_event(task, 'auto_progress_gate_blocked', {'gate_code': gate.gate_code, 'reason_code': reason_code}, source='worker')
db.session.commit()
return {'status': outcome, 'gate_code': gate.gate_code, 'reason_code': reason_code}
gate.passed_at = _utc_now(); execution.last_passed_gate_code = gate.gate_code
# 先 flush 当前 Job 成功态,释放 Task 级 active partial unique;后继 Job 与 Gate passed
# 仍处在同一外层事务,commit 前对 Worker 不可见。
db.session.flush()
next_gate, consistency_error = _earliest_runnable_gate(execution)
if consistency_error:
execution.status = 'blocked'; execution.current_gate_code = None
elif next_gate is None:
execution.status = 'completed'; execution.current_gate_code = None
elif next_gate.gate_code == 'upload_receipt_recorded':
# 上传自动化关闭时,Excel 后明确等人工登记回执,不擅自跨越此 Gate。
execution.status = 'blocked'; execution.current_gate_code = next_gate.gate_code
next_gate.status = 'blocked_manual'; next_gate.blocking_reason_code = 'manual_upload_receipt_required'
else:
execution.status = 'active'; execution.current_gate_code = next_gate.gate_code
submit_auto_progress(task=task, trigger='gate_passed', commit=False)
log_task_event(task, 'auto_progress_gate_passed', {'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code}, source='worker')
job.status = 'cancelled'
job.finished_at = now
job.message = 'APX historical auto-progress runtime disabled'
if gate is not None and gate.status in {'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual'}:
gate.status = 'cancelled'
gate.updated_at = now
db.session.commit()
return {
'status': 'passed', 'execution_id': int(execution.id),
'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code,
'status': 'legacy_readonly',
'reason_code': 'shipping_apx_runtime_disabled',
'execution_id': int(job.execution_id) if job.execution_id else None,
}
@@ -163,11 +163,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
and not getattr(task, "inventory_lines_json", None)
and pending_reason == PH_RPA_PENDING
):
# A pending task already has an explicit RPA attempt. Poll its timeout
# state through the RPA workflow; normal auto-progress must not start RPA.
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
# PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
result = ensure_inventory_via_rpa(task, mode="auto")
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
if current_app:
current_app.logger.info(
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
@@ -356,10 +356,10 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING:
# This is a poll of an existing request, never an implicit new RPA run.
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
# 轮询既有请求仍只提交正式库存准备 Gate,由 Executor 读取 Attempt 状态。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
result = ensure_inventory_via_rpa(task, mode="auto")
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
status = str(result.get("status") or "").strip().lower()
if status in {"ok", "running", "needs_human"}:
started += 1
@@ -48,6 +48,34 @@ _FORCE_RETRYABLE_BLOCKING_CODES = frozenset({
'SHIPPING.profile_schema_mismatch',
})
# needs_human 并不总是终止态:库存快照/RPA 暂态失败仍可由统一重试决策器
# 重新触发库存准备;重复、短缺、冲突等业务裁决原因不得自动放行。
_INVENTORY_RETRYABLE_HUMAN_CODES = frozenset({
'inventory_snapshot_prepare_failed',
'inventory_snapshots_pending',
'inventory_rpa_failed',
'inventory_rpa_exhausted',
'inventory_file_missing',
'rpa_failed',
'trigger_not_claimed_missing',
'trigger_not_claimed_timeout',
'inventory_trigger_missing',
'inventory_trigger_write_failed',
# 库存门禁/匹配阻断属于可重新检查的技术中间态;对话级重试不得直接跳过。
'inventory_candidates_required',
'inventory_candidates_frozen_required',
'inventory_snapshot_prepare_failed',
'inventory_snapshots_pending',
'inventory_match_not_ready',
'inventory_match_incomplete',
})
_BUSINESS_HUMAN_CODES = frozenset({
'inventory_shortage',
'inventory_source_conflict',
'inventory_source_candidates_need_human',
'duplicate_decision_required',
})
def project_conversation_allowed_actions(
*,
@@ -428,12 +456,75 @@ def _skip_reason_from_automation(automation: dict[str, Any], *, task_missing: bo
if status in {'completed', 'succeeded'}:
return 'already_completed'
if status == 'needs_human':
return 'human_blocking'
# 库存准备失败是“需要人工关注但仍可技术重试”的中间态;只有
# retryable=true 且原因码在白名单内才允许继续到正式 OT 决策器。
reason_candidates = (
automation.get('reason_code'),
automation.get('blocking_reason_code'),
automation.get('error_code'),
)
reason_codes = {
str(item or '').strip().lower()
for item in reason_candidates
if str(item or '').strip()
}
if reason_codes & _DUPLICATE_BLOCKING_CODES:
return 'human_blocking'
if reason_codes & _BUSINESS_HUMAN_CODES:
return 'human_blocking'
if bool(automation.get('retryable')) and reason_codes & _INVENTORY_RETRYABLE_HUMAN_CODES:
return None
# 正式 OT 的 needs_human 可能只是上一轮匹配/门禁结果;对话级“重试自动推进”
# 的职责是重新读取当前库存事实并重新检查。只有重复订单等明确业务裁决才跳过。
return None
if not bool(automation.get('retryable')):
return 'not_retryable'
return None
def _formal_task_has_retryable_inventory_trigger_failure(task_no: str) -> bool:
"""读取正式 OT 最新逐源 Attempt,识别 Trigger 缺失等可强制重发的技术失败。"""
try:
from app.services.shipping_notice.task_retry_decision_service import (
summarize_inventory_rpa_latest_attempts,
)
task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first()
if task is None:
return False
summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
technical_codes = {
'trigger_not_claimed_missing',
'trigger_not_claimed_timeout',
'inventory_trigger_missing',
'inventory_trigger_write_failed',
}
return any(
str((item or {}).get('error_code') or '').strip().lower() in technical_codes
and str((item or {}).get('status') or '').strip().lower() in {'failed', 'exhausted'}
for item in (summary.get('latest_attempts') or {}).values()
)
except Exception: # noqa: BLE001
_LOGGER.exception('inventory trigger failure lookup failed task_no=%s', task_no)
return False
def _formal_task_has_active_attempt(task_no: str) -> bool:
"""按正式 Attempt + Job 双重事实判断任务是否真的仍在执行。"""
try:
from app.services.shipping_notice.task_retry_decision_service import (
summarize_inventory_rpa_latest_attempts,
)
task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first()
if task is None:
return False
summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
return int(summary.get('active_attempt_count') or 0) > 0
except Exception: # noqa: BLE001
_LOGGER.exception('active attempt lookup failed task_no=%s', task_no)
# 状态无法确认时 fail-closed,禁止重复执行。
return True
def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, Any]:
"""
对单个 Case 执行重试或跳过。
@@ -476,6 +567,17 @@ def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str,
if task_no:
skip = _skip_reason_from_automation(automation, task_missing=task_missing)
# Automation 是展示投影,可能滞后于正式 Job。只有 Attempt 与 Job 都仍活动时
# 才能返回 already_running;Job 已失败的 queued Attempt 是待恢复残留。
if skip == 'already_running' and not _formal_task_has_active_attempt(task_no):
skip = None
# Trigger 缺失/未领取是库存 RPA 的正式技术失败事实;不得被
# automation 投影中的历史 completed/not_retryable/human_blocking 覆盖。
# 只要当前没有 queued/running Attempt,就必须重新进入 retry_rpa。
if skip not in {None, 'already_running', 'task_missing'} and _formal_task_has_retryable_inventory_trigger_failure(task_no):
# Automation 可能仍被历史 Job 的错误码污染;逐源 Attempt 是库存 Trigger
# 的正式事实,技术领取失败必须重新进入 retry_rpa,而不是继续 skipped。
skip = None
if skip:
return {
'object_type': OBJECT_FORMAL_TASK,
@@ -821,7 +923,9 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': action,
'outcome': 'skipped',
# 对话级重试已实际重新检查;门禁仍阻断时应归为失败/需处理,
# 不能计入“已跳过”,否则用户无法区分未执行与执行后被阻断。
'outcome': 'failed',
'reason_code': str((result or {}).get('reason_code') or 'human_blocking'),
'metadata': {'p13_category': 'e_formal_ot'},
}
@@ -873,13 +977,15 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]:
"""汇总逐对象结果。"""
retried = skipped = failed = 0
retried = skipped = failed = blocked = 0
for item in items:
outcome = str(item.get('outcome') or '').strip().lower()
if outcome == 'queued':
retried += 1
elif outcome == 'failed':
failed += 1
elif outcome == 'blocked':
blocked += 1
else:
skipped += 1
return {
@@ -887,4 +993,5 @@ def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]:
'retried': retried,
'skipped': skipped,
'failed': failed,
'blocked': blocked,
}
@@ -24,9 +24,8 @@ from app.services.shipping_notice.constants import (
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.fulfillment_workflow import match_completed, match_inventory
from app.services.shipping_notice.fulfillment_workflow import match_completed
from app.services.shipping_notice.task_order_field_editor import retire_current_order_extraction
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
adjudicate_and_apply_inventory_source,
@@ -68,6 +67,13 @@ def _reset_inventory_state_for_forced_rpa(task) -> None:
task.freight_ref_no = None
task.upload_status = None
task.upload_mode = None
def _request_formal_gate_action(**kwargs):
"""决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。"""
from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request
return _request(**kwargs)
task.upload_error_message = None
task.upload_receipt_json = None
task.review_status = None
@@ -94,8 +100,8 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、重匹配或重解析等分支;
rematch 会同步调用 match_inventory 完成重算;工作台入口须注入 operator_id 以保证审计非匿名。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、正式 Gate
Recovery 或重解析等分支;工作台入口须注入 operator_id 以保证审计非匿名。
Args:
payload: 必须包含任务定位信息与 decision;可选 comment、lang、operator_id/actor_id。
@@ -431,12 +437,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
after=task_lifecycle_audit_snapshot(task),
)
db.session.flush()
retry_payload = merge_tool_payload(
task,
payload,
extra={"mode": "retry_rpa", "manual_retry_round": True},
return _request_formal_gate_action(
task=task,
action_code='retry_inventory_preparation',
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
idempotency_key=str(payload.get('idempotency_key') or f'decision-retry-rpa:{task.task_no}:{task.order_data_version}'),
trigger=event_source,
)
return ensure_inventory(retry_payload)
if decision == "rematch":
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
@@ -453,16 +460,15 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
# flush 即可:清状态与 match_inventory 的最终 commit 同属一次连续写入,避免中间态落库。
# flush 即可:状态清理与正式 Gate Action 入队同属一次连续写入,避免中间态落库。
db.session.flush()
# [STEP 3.1] 重新匹配须同步完成库存计算,避免退回 ready_to_match 后再让用户点 match_inventory。
match_result = match_inventory(merge_tool_payload(task, payload))
if match_result.get("status") != "failed":
match_result = prepend_tool_message(
match_result,
t("workflow.decision.rematch_done", lang=lang),
)
return match_result
return _request_formal_gate_action(
task=task,
action_code='retry_inventory_from_matching',
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
idempotency_key=str(payload.get('idempotency_key') or f'decision-rematch:{task.task_no}:{task.order_data_version}'),
trigger=event_source,
)
# [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。
if decision == "reparse":
@@ -410,6 +410,37 @@ def _meta(party: str, action: str, message_zh: str) -> dict[str, str]:
# next_action 必须属于 PROCESS_GATE_ACTION_CODES,或为空串表示无可执行动作。
EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
UNKNOWN_BUSINESS_FAILURE_REASON_CODE: _meta('system', '', '业务处理失败,请凭请求编号联系管理员'),
# Gate 契约中未进入分层集合的订单资格 / XFA 诊断码;必须仍有稳定用户文案与下一步。
'budget_stopped': _meta('owner', 'open_order_review', '订单识别预算已用尽,请检查文档后进入复核'),
'business_scenario_not_configured': _meta('admin', 'open_order_review', '业务场景尚未配置,请联系管理员配置后重试'),
'business_scenario_out_of_scope': _meta('owner', 'open_order_review', '当前业务场景不在系统支持范围内,请进入复核'),
'business_scenario_unmatched': _meta('owner', 'open_order_review', '未识别出适用的业务场景,请进入复核确认'),
'customer_confirmation_required': _meta('owner', 'confirm_customer', '客户身份需要确认'),
'customer_scope_not_configured': _meta('admin', 'open_order_review', '客户业务范围尚未配置,请联系管理员'),
'customer_scope_out_of_scope': _meta('owner', 'open_order_review', '客户不在当前业务范围内,请进入复核处理'),
'customer_scope_unmatched': _meta('owner', 'confirm_customer', '未能匹配到当前订单对应的客户'),
'extraction_emergency_stop': _meta('owner', 'retry_order_extraction', '订单识别已被安全策略停止,请检查文档后重试'),
'generic_auto_freeze_disabled': _meta('admin', 'open_order_review', '通用自动建单未启用,请联系管理员'),
'lease_conflict': _meta('system', 'recheck_freeze_readiness', '当前任务正在被其他执行占用,请稍后刷新'),
'llm_path_cannot_auto_freeze': _meta('owner', 'open_order_review', '智能识别结果尚未通过自动建单资格检查'),
'multiple_customers_detected': _meta('owner', 'confirm_customer', '检测到多个候选客户,请确认正确客户'),
'multiple_profiles_detected': _meta('owner', 'open_profile_review', '检测到多个候选模板,请确认适用模板'),
'not_recoverable': _meta('admin', 'open_order_review', '当前失败不可自动恢复,请联系管理员处理'),
'pending_orders_present': _meta('owner', 'open_order_review', '仍有订单未完成处理,请先完成订单复核'),
'profile_auto_freeze_qualification_missing': _meta('owner', 'open_order_review', '订单模板尚未通过自动建单资格检查'),
'profile_auto_freeze_suspended': _meta('admin', 'open_order_review', '当前模板自动建单已暂停,请联系管理员'),
'profile_manual_confirmation_required': _meta('owner', 'open_profile_review', '订单模板需要人工确认后才能继续'),
'run_cancelled': _meta('owner', 'retry_order_extraction', '订单识别已取消,请重新发起处理'),
'run_failed': _meta('worker', 'retry_order_extraction', '订单识别运行失败,请重试或进入复核'),
'unit_review_required': _meta('owner', 'open_order_review', '存在文档单元需要人工复核'),
'version_conflict': _meta('owner', 'open_order_review', '数据版本已变化,请刷新后重新提交'),
'xfa_evidence_retention_insufficient': _meta('owner', 'open_order_review', 'XFA 证据留存不足,请进入复核补充证据'),
'xfa_mirror_consistency_insufficient': _meta('owner', 'open_order_review', 'XFA 镜像明细一致性不足,请进入复核'),
'xfa_profile_checksum_mismatch': _meta('admin', 'open_profile_review', 'XFA 模板校验和不一致,请联系管理员检查模板版本'),
'xfa_visual_binding_incomplete': _meta('owner', 'open_profile_review', 'XFA 可视化字段绑定不完整,请补充模板绑定'),
'xfa_visual_bindings_required': _meta('owner', 'open_profile_review', 'XFA 尚未完成可视化字段绑定'),
'xfa_visual_coverage_insufficient': _meta('owner', 'open_profile_review', 'XFA 可视化字段覆盖不足,请补充模板映射'),
'xfa_visual_not_publishable': _meta('admin', 'open_profile_review', 'XFA 可视化模板未达到发布条件,请检查模板质量'),
# 附件
'attachment_format_unsupported': _meta('owner', 'rematerialize_document', '附件格式不支持'),
'attachment_size_exceeded': _meta('owner', 'rematerialize_document', '附件超过系统大小限制'),
@@ -570,8 +601,6 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'),
'excel_input_incomplete': _meta('owner', 'recheck_excel_readiness', '生成 Excel 所需输入不完整'),
'artifact_validation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 产物校验失败'),
'upload_rpa_login_failed': _meta('admin', 'regenerate_manual_upload_todo', '货代平台登录失败'),
'upload_platform_rejected': _meta('owner', 'regenerate_manual_upload_todo', '货代平台拒绝本次上传'),
'inventory_required_column_missing': _meta('owner', 'confirm_inventory_field_mapping', '库存文件缺少必填列'),
'inventory_column_ambiguous': _meta('owner', 'confirm_inventory_field_mapping', '库存列映射存在歧义'),
'inventory_sku_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 SKU'),
+99 -14
View File
@@ -21,6 +21,7 @@ from zoneinfo import ZoneInfo
from flask import current_app
from openpyxl import load_workbook
from openpyxl.cell.cell import MergedCell
from sqlalchemy import func
from app import db
from app.models import (
@@ -29,6 +30,7 @@ from app.models import (
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderSnapshot,
ShippingOrderField,
ShippingNotice,
)
from app.path_utils import resolve_backend_relative_path
@@ -59,7 +61,39 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
return header, lines
def _system_fact(task: ShippingNotice, key: str, *, export_sequence: int | None = None) -> Any:
def _excel_business_no(task: ShippingNotice, *, export_date: date | None = None) -> str | None:
"""生成本次 Excel 使用的 Pull Request Number;不回写业务单主编号。"""
case = task.shipping_case
if case is None or not case.business_no:
return None
business_no = str(case.business_no).strip()
prefix = business_no[:-8] if len(business_no) > 8 else business_no
sequence = business_no[-2:] if len(business_no) >= 2 and business_no[-2:].isdigit() else ''
if not sequence and case.sequence_value:
sequence = f'{int(case.sequence_value):02d}'
if not sequence:
return None
export_date = export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date()
return f'{prefix}{export_date.strftime("%y%m%d")}{sequence}'
def _clear_template_data_rows(ws: Any, start_row: int) -> None:
"""清除模板数据起始行之后的所有单元格值,保留模板表头与样式。"""
for row_index in range(start_row, ws.max_row + 1):
for column_index in range(1, ws.max_column + 1):
cell = ws.cell(row_index, column_index)
if not isinstance(cell, MergedCell):
cell.value = None
def _system_fact(
task: ShippingNotice,
key: str,
*,
export_sequence: int | None = None,
excel_business_no: str | None = None,
export_date: date | None = None,
) -> Any:
"""
读取受控任务事实,模板不能通过任意属性路径访问 ORM。
@@ -73,10 +107,10 @@ def _system_fact(task: ShippingNotice, key: str, *, export_sequence: int | None
"""
values = {
'task_no': task.task_no,
'business_no': task.shipping_case.business_no if task.shipping_case else None,
'business_no': excel_business_no or (task.shipping_case.business_no if task.shipping_case else None),
'warehouse_id': task.inventory_warehouse_id,
'inventory_source_code': task.inventory_source_code,
'export_date': datetime.now(ZoneInfo('Asia/Shanghai')).date(),
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
'export_sequence': export_sequence,
}
return values.get(key)
@@ -110,6 +144,8 @@ def _format_value(value: Any, formatter: str) -> Any:
def _mapping_value(
mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any],
header_values: dict[str, Any] | None = None, export_sequence: int | None = None,
excel_business_no: str | None = None,
export_date: date | None = None,
) -> Any:
"""
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
@@ -132,6 +168,16 @@ def _mapping_value(
key = mapping['source_key']
if kind == 'order_field':
value = order_values.get(key)
field = db.session.get(ShippingOrderField, key) if key else None
field_code = str(field.field_code or '') if field else ''
if value in (None, '') and field_code == 'line_no' and export_sequence is not None:
value = export_sequence
if value in (None, '') and field_code == 'line_amount_with_tax':
value = order_values.get('__line_amount')
qty = order_values.get('__qty')
unit_price = order_values.get('__unit_price')
if value in (None, '') and qty not in (None, '') and unit_price not in (None, ''):
value = Decimal(str(qty)) * Decimal(str(unit_price))
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key)
elif kind == 'inventory_field':
@@ -140,6 +186,8 @@ def _mapping_value(
value = _system_fact(
task, key,
export_sequence=export_sequence if key == 'export_sequence' else None,
excel_business_no=excel_business_no,
export_date=export_date,
)
if key == 'export_sequence' and value is None:
value = order_values.get('__export_sequence')
@@ -174,6 +222,17 @@ def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) ->
return {str(item.id) for item in rows}
def _inventory_field_user_label(field_id: str) -> str:
"""把库存字段主键转换为用户可读中文名,禁止在业务错误中直接暴露「字段 6」。"""
normalized = str(field_id or '').strip()
if normalized.isdigit():
row = ShippingInventoryField.query.filter_by(id=int(normalized)).first()
display_name = str(getattr(row, 'display_name', '') or '').strip() if row else ''
if display_name:
return display_name
return f'库存字段(编号 {normalized or "未知"})'
def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]:
"""多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。"""
if not rows:
@@ -182,7 +241,8 @@ def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set
for field in required_fields:
values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))}
if len(values) > 1:
raise ValueError(f'订单行匹配到多个库存记录,字段 {field} 的值不一致')
label = _inventory_field_user_label(field)
raise ValueError(f'订单行匹配到多个库存记录,库存字段“{label}”的值不一致,请检查库存映射或库存文件')
if values:
resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field)))
return resolved
@@ -252,7 +312,12 @@ def _safe_filename(name: str) -> str:
return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx'
def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
def _filename(
task: ShippingNotice,
template: ShippingExcelTemplate,
*,
excel_business_no: str | None = None,
) -> str:
"""按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。"""
pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip()
if not pattern:
@@ -263,7 +328,7 @@ def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
shipping_case = task.shipping_case
values = {
'task_no': task.task_no,
'business_no': shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no,
'business_no': excel_business_no or (shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no),
'source_code': task.inventory_source_code or '',
'ts': now,
'date': now[:8],
@@ -280,14 +345,15 @@ def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
def _input_checksum(
task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate,
snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
) -> str:
"""计算完整生成输入指纹,供审计和重复生成差异判断。"""
"""以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。"""
payload = {
'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
'order_header': header, 'order_lines': lines, 'inventory_lines': task.inventory_lines_json or [],
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
}
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
@@ -388,6 +454,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
excel_business_no = _excel_business_no(task, export_date=export_date)
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
reserve_available_for_artifact,
@@ -398,10 +466,17 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
for line, values in zip(snapshot.lines, all_line_values, strict=True):
if line.id not in available_line_ids:
continue
line_values.append(dict(values))
row = dict(values)
row['__qty'] = line.qty
row['__unit_price'] = line.unit_price
row['__line_amount'] = line.amount
line_values.append(row)
for index, row in enumerate(line_values, start=1):
row['__export_sequence'] = index
inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)]
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
# [STEP 2] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
inventory_lines = resolve_inventory_lines_for_execution(task)
definition = template.definition_json or {}
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
if not mappings:
@@ -415,7 +490,7 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
filename = _filename(task, template)
filename = _filename(task, template, excel_business_no=excel_business_no)
artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}'
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no
directory.mkdir(parents=True, exist_ok=True)
@@ -427,6 +502,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
path.write_bytes(template_bytes)
wb = load_workbook(path)
try:
data_start_rows = {
str(sheet): min(int(item['start_row']) for item in mappings if item['sheet'] == sheet)
for sheet in {str(item['sheet']) for item in mappings}
}
for sheet, start_row in data_start_rows.items():
_clear_template_data_rows(wb[sheet], start_row)
for mapping in mappings:
ws = wb[mapping['sheet']]
start_row = int(mapping['start_row'])
@@ -434,11 +515,11 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
if mapping['row_mode'] == 'header':
ws.cell(start_row, column).value = _mapping_value(
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
excel_business_no=excel_business_no,
export_date=export_date,
)
continue
row_count = max(len(line_values), 1)
for row_index in range(start_row, max(ws.max_row, start_row + row_count - 1) + 1):
ws.cell(row_index, column).value = None
for index in range(row_count):
order_line = line_values[index] if index < len(line_values) else {}
inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {}
@@ -446,6 +527,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
header_values=header_values,
export_sequence=int(order_line.get('__export_sequence') or (index + 1)),
excel_business_no=excel_business_no,
export_date=export_date,
)
wb.save(path)
finally:
@@ -458,7 +541,9 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
artifact_no=artifact_no, task_id=task.id, template_id=template.id,
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
input_checksum=_input_checksum(task, source, template, snapshot, header_values, line_values),
input_checksum=_input_checksum(
task, source, template, snapshot, header_values, line_values, inventory_lines,
),
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
file_size=len(content), status='ready',
)
@@ -30,7 +30,7 @@ from app.core.errors import ConflictError, ServiceUnavailableError, ValidationEr
from app.models import ShippingNotice
from app.services.shipping_notice.constants import CP_UPLOADED
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
from app.services.shipping_notice.inventory_workflow import (
ensure_inventory,
parse_inventory_lines,
@@ -902,11 +902,9 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str,
if extraction_gate is not None:
return extraction_gate
# [STEP 1] inventory snapshot
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
task.inventory_lines_json = inventory_lines
else:
inventory_lines = active_inventory_lines_for_task(task)
inventory_lines = resolve_inventory_lines_for_execution(
task, legacy_payload_lines=parse_inventory_lines(payload),
)
if not inventory_lines:
# 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义)
inv_payload: dict[str, Any] = {"task_id": task.task_no, 'line_key': target_key}
@@ -1197,6 +1195,49 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]:
return list(task.line_results_json or [])
def _profile_match_persistence_payload(
line_results: list[dict[str, Any]],
*,
inventory_source_code: str | None,
) -> dict[str, list[dict[str, Any]]]:
"""
将单源 Profile 匹配结果转换为结构化行事实写入载荷。
核心逻辑:按结果稳定行序补齐 line_index;resolutions 不写临时 line-N,
由持久化层使用同一行序关联 Case 草稿的真实 line_key。
Args:
line_results: match_notice_lines 返回的逐行结果。
inventory_source_code: 当前正式库存源编码。
Returns:
含 line_results 与 resolutions 的持久化载荷。
"""
return {
'line_results': [
{
**row,
'line_index': index,
'disposition': 'ok' if row.get('line_status') == 'ok' else 'shortage',
}
for index, row in enumerate(line_results)
],
'resolutions': [
{
'line_index': index,
# 让持久化层按 Case 草稿的 line_key(如 machine-1)解析;
# 不写入临时 line-N,避免 Review Projection 无法关联事实。
'line_key': row.get('line_key'),
'part_number': row.get('part_number'),
'effective_reservation_id': row.get('reservation_id'),
'disposition': 'ok' if row.get('line_status') == 'ok' else 'shortage',
'resolved_inventory_source_code': inventory_source_code,
}
for index, row in enumerate(line_results)
],
}
def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""
将发货通知订单行与库存快照进行 Reservation ID 匹配,并按结果推进任务状态。
@@ -1280,11 +1321,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
return extraction_gate
# [STEP 1] 正式库存已在载入阶段按 published Profile 校验;这里只确认库存快照是否就绪。
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
task.inventory_lines_json = inventory_lines
else:
inventory_lines = active_inventory_lines_for_task(task)
inventory_lines = resolve_inventory_lines_for_execution(
task, legacy_payload_lines=parse_inventory_lines(payload),
)
if not inventory_lines:
inv_payload: dict[str, Any] = {"task_id": task.task_no}
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
@@ -1379,7 +1418,10 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
or purpose_line.get('unit')
or (order_field_lines[index] if index < len(order_field_lines) else {}).get('__display_uom')
),
'line_key': (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key'),
'line_key': (
(order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key')
or f'line-{index + 1}'
),
})
match_payload = match_order_lines_across_candidates(
order_lines=attach_candidate_scope_to_order_lines(task, stp_order_lines),
@@ -1522,6 +1564,20 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
quantity_field_id=str(quantity_fields[0].id),
progress_callback=_on_match_progress,
)
# 整单匹配与行级匹配必须写入同一结构化事实表;Review Projection 只读取该表。
# 仅更新 line_results_json 会导致订单明细继续显示“待确认”。
from app.services.shipping_notice.line_inventory_match_persistence import (
persist_line_inventory_match_facts,
)
persist_line_inventory_match_facts(
task=task,
match_payload=_profile_match_persistence_payload(
line_results,
inventory_source_code=task.inventory_source_code,
),
inventory_snapshot_id=(int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None),
matching_rule_version='profile_match_v1',
)
task.match_status = match_status
task.line_results_json = line_results
task.shortage_json = shortage
@@ -1597,6 +1653,29 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
Returns:
dict[str, Any]: 含 download_hint 的 Tool 响应;门禁失败时 forbidden_next_tools 含 upload_to_freight。
"""
# [T5 Orchestrator 守卫]:外部请求只能提交正式 artifact_generation Gate;
# 只有 ProcessGate Executor 才能携带内部标记执行实际 Excel 生成。
if not payload.get('_orchestrator_internal_dispatch', False):
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
from app.services.shipping_notice.query_service import resolve_task_from_payload as _rtp
task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip()
if not task_no and isinstance(payload, dict):
_task = _rtp(payload)
task_no = str(getattr(_task, 'task_no', '') or '').strip()
trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_generate_excel').strip()
actor_raw = payload.get('operator_id') or payload.get('actor_id') or payload.get('_trusted_user_id')
try:
operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != 'system' else None
except (TypeError, ValueError):
operator_id = None
return run_task_auto_progress(
task_no,
trigger=trigger,
expected_version=None,
idempotency_key=str(payload.get('idempotency_key') or '').strip() or None,
resume_gate_code='artifact_generation',
operator_id=operator_id,
)
lang = resolve_lang(payload)
actor_id = _event_actor_id(payload)
task = resolve_task_from_payload(payload)
@@ -257,9 +257,22 @@ def _next_task_set_version(*, task_id: int, session: Session) -> int:
return int(current_max or 0) + 1
def _invalidate_task_candidate_outputs(task: ShippingNotice, *, session: Session) -> None:
"""重冻结后立即失效旧匹配、导出与待上传事实,避免旧版本继续被消费。"""
from app.models import ShippingNoticeLineInventoryMatch, ShippingTaskInventoryRpaAttempt
def _invalidate_task_candidate_outputs(
task: ShippingNotice, *, old_candidate_set_id: int | None, session: Session,
) -> None:
"""重冻结后失效旧候选版本的准备、恢复、匹配、导出与上传事实。
仅取消旧版本的非终态记录,不删除审计;新 CandidateSet 随后会创建新的
正式 Execution/Attempt,因此迟到 RPA 回调无法写回新链。
"""
from app.models import (
ShippingExportArtifact,
ShippingInventoryPreparationAttempt,
ShippingNoticeLineInventoryMatch,
ShippingProcessRecoveryPlan,
ShippingTaskInventoryRpaAttempt,
ShippingUploadAttempt,
)
task.match_status = None
task.shortage_json = None
@@ -291,6 +304,48 @@ def _invalidate_task_candidate_outputs(task: ShippingNotice, *, session: Session
)
.update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False)
)
artifact_ids = [
row[0] for row in session.query(ShippingExportArtifact.id).filter(
ShippingExportArtifact.task_id == int(task.id),
ShippingExportArtifact.status.in_(('ready', 'uploading')),
).all()
]
if artifact_ids:
session.query(ShippingExportArtifact).filter(
ShippingExportArtifact.id.in_(artifact_ids),
).update({'status': 'superseded'}, synchronize_session=False)
session.query(ShippingUploadAttempt).filter(
ShippingUploadAttempt.artifact_id.in_(artifact_ids),
ShippingUploadAttempt.status.in_(('pending', 'running', 'timed_out', 'unknown')),
).update({
'status': 'failed',
'invalidated_at': datetime.utcnow(),
'invalidation_reason': 'candidate_set_refrozen',
'finished_at': datetime.utcnow(),
'error_code': 'candidate_set_refrozen',
}, synchronize_session=False)
prep_query = session.query(ShippingInventoryPreparationAttempt).filter(
ShippingInventoryPreparationAttempt.task_id == int(task.id),
ShippingInventoryPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')),
)
if old_candidate_set_id is not None:
prep_query = prep_query.filter(
ShippingInventoryPreparationAttempt.candidate_set_id == int(old_candidate_set_id)
)
prep_query.update({'status': 'superseded'}, synchronize_session=False)
active_execution_ids = [
row[0] for row in session.query(ShippingInventoryPreparationAttempt.execution_id).filter(
ShippingInventoryPreparationAttempt.task_id == int(task.id),
ShippingInventoryPreparationAttempt.candidate_set_id == old_candidate_set_id,
).all() if row[0]
]
if active_execution_ids:
session.query(ShippingProcessRecoveryPlan).filter(
ShippingProcessRecoveryPlan.execution_id.in_(active_execution_ids),
ShippingProcessRecoveryPlan.status.in_(
('planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual')
),
).update({'status': 'cancelled', 'completed_at': datetime.utcnow()}, synchronize_session=False)
def freeze_candidates_for_task(
@@ -524,7 +579,9 @@ def freeze_candidates_for_task(
existing_active.lifecycle_status = 'superseded'
existing_active.superseded_at = datetime.utcnow()
existing_active.superseded_by_set_id = int(new_set.id)
_invalidate_task_candidate_outputs(task, session=session)
_invalidate_task_candidate_outputs(
task, old_candidate_set_id=int(existing_active.id), session=session,
)
if getattr(task, 'id', None) is not None:
task.active_inventory_candidate_set_id = int(new_set.id)
@@ -20,6 +20,7 @@ from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingInventoryFile,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
@@ -472,6 +473,10 @@ def project_inventory_candidate_facts(
stale_details: dict[str, Any] | None = None
out_of_scope_details: dict[str, Any] | None = None
for row in _current_match_rows(task, session=sess):
snapshot = (
sess.get(ShippingInventoryFile, int(row.inventory_snapshot_id))
if getattr(row, 'inventory_snapshot_id', None) is not None else None
)
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
serialized = {
'id': int(row.id),
@@ -486,6 +491,13 @@ def project_inventory_candidate_facts(
'inventory_file_no': getattr(row, 'matched_file_no', None),
'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None),
'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')),
'inventory_file_sha256': (
dict(getattr(row, 'detail_json', None) or {}).get('file_sha256')
or dict(getattr(row, 'detail_json', None) or {}).get('inventory_file_sha256')
or getattr(snapshot, 'file_sha256', None)
),
'inventory_row_index': getattr(row, 'matched_row_index', None),
'match_attempt_id': getattr(row, 'match_attempt_id', None),
'required_qty': getattr(row, 'required_qty', None),
'matched_qty': getattr(row, 'matched_qty', None) or getattr(row, 'available_qty', None),
'match_result': getattr(row, 'match_result', None),
@@ -0,0 +1,33 @@
"""
services/shipping_notice/inventory_combination_fingerprint.py
用途:为多源库存准备轮次生成稳定组合输入指纹。
依赖:标准库 hashlib/json。
逻辑:对任务快照、候选冻结、逐源快照/Hash/解析映射版本、Reservation 和匹配规则做规范化哈希。
"""
from __future__ import annotations
import hashlib
import json
from typing import Any, Iterable
def build_inventory_combination_fingerprint(
*, task_snapshot_fingerprint: str | None, candidate_freeze_fingerprint: str | None,
sources: Iterable[dict[str, Any]], reservation_version: str | None = None,
matching_rule_version: str | None = None,
) -> str:
"""按稳定排序构建组合输入 SHA-256 指纹。"""
payload = {
'task_snapshot_fingerprint': task_snapshot_fingerprint,
'candidate_freeze_fingerprint': candidate_freeze_fingerprint,
'sources': sorted(
[dict(item) for item in sources],
key=lambda item: (str(item.get('source_code') or ''), int(item.get('snapshot_id') or 0)),
),
'reservation_version': reservation_version,
'matching_rule_version': matching_rule_version,
}
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
return hashlib.sha256(raw).hexdigest()
@@ -9,6 +9,7 @@ services/shipping_notice/inventory_file_store.py
from __future__ import annotations
import re
import hashlib
import shutil
import uuid
from pathlib import Path
@@ -90,6 +91,15 @@ def inventory_file_upload_path(inventory_file_no: str, *, suffix: str = ".xlsx")
return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / f"inventory{normalized}"
def _file_sha256(path: Path) -> str:
"""计算已落盘库存快照的内容指纹,供复用和组合输入门禁使用。"""
digest = hashlib.sha256()
with path.open('rb') as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(chunk)
return digest.hexdigest()
def inventory_storage_suffix_for_path(path: str | Path) -> str:
"""根据已有文件路径推导库存快照落盘后缀,未知格式回退 .xlsx。"""
suffix = Path(path).suffix.lower()
@@ -135,10 +145,46 @@ def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFil
def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
"""解析任务可用于匹配的库存行;批次库存快照优先,单票任务回退到任务投影字段。"""
"""读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。"""
inv_file = active_inventory_file_for_task(task)
if inv_file and isinstance(inv_file.inventory_lines_json, list):
return [row for row in inv_file.inventory_lines_json if isinstance(row, dict)]
rows = [row for row in inv_file.inventory_lines_json if isinstance(row, dict)]
if not rows and Path(inv_file.storage_path).is_file():
try:
reparsed, _meta = parse_inventory_snapshot_file(inv_file)
if reparsed:
inv_file.inventory_lines_json = reparsed
inv_file.line_count = len(reparsed)
db.session.flush()
rows = reparsed
except Exception: # noqa: BLE001
# 解析失败时保留原快照,交由上层 Gate 报告可解释错误。
pass
return rows
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
def resolve_inventory_lines_for_execution(
task: ShippingNotice,
*,
legacy_payload_lines: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
"""
解析库存匹配与导出的统一运行输入,活动库存 Link 为唯一事实源。
Args:
task: 当前正式发货通知。
legacy_payload_lines: 旧 Tool 请求携带的库存行;仅无活动 Link 的历史任务允许使用。
Returns:
本次执行使用的库存行;不会回写 ``ShippingNotice.inventory_lines_json``。
"""
if active_inventory_file_for_task(task) is not None:
return active_inventory_lines_for_task(task)
if isinstance(legacy_payload_lines, list):
rows = [row for row in legacy_payload_lines if isinstance(row, dict)]
if rows:
return rows
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
@@ -213,16 +259,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh
message='库存文件没有可用于匹配的有效库存数据',
http_status=409,
)
from app.services.shipping_notice.inventory_file_identity import (
assert_inventory_excel_warehouse_identity,
)
if str(warehouse_id or '').strip():
assert_inventory_excel_warehouse_identity(
path,
expected_warehouse_id=str(warehouse_id or ""),
operation="manual_upload",
)
# 手工上传同样只保留文件 Warehouse 事实,不要求其等于页面当前库位编码。
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = str(upload.filename or path.name)
preview['structure_validation'] = column_meta['structure_validation']
@@ -250,6 +287,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh
user_id=task.user_id,
source_file_name=str(upload.filename or "").strip() or path.name,
storage_path=str(path),
file_sha256=_file_sha256(path),
schema_preview_json=preview,
share_mode="task_only",
line_count=len(inventory_lines),
@@ -351,6 +389,7 @@ def save_task_inventory_file_from_local_path(
user_id=task.user_id,
source_file_name=str(source_file_name or source.name or path.name).strip() or path.name,
storage_path=str(path),
file_sha256=_file_sha256(path),
schema_preview_json=preview,
share_mode="task_only",
line_count=0,
@@ -8,6 +8,7 @@ services/shipping_notice/inventory_mapping.py
from __future__ import annotations
import re
from typing import Any
from app.models import ShippingInventoryField
@@ -226,6 +227,14 @@ def resolve_columns_from_field_mapping(
"""将显式 field_mapping 转为库存字段 ID → 列索引;未配置字段不自动猜测。"""
norm_headers = [str(h or "").strip() for h in headers]
lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h}
# Excel exports may contain line breaks or repeated whitespace in a
# visible header (for example ``Qty\nAvailable``). Explicit published
# mappings must still resolve deterministically without guessing a field.
normalized_to_idx: dict[str, int] = {}
for index, header in enumerate(norm_headers):
key = re.sub(r"[^a-z0-9]+", "", header.lower())
if key and key not in normalized_to_idx:
normalized_to_idx[key] = index
def idx_for(header_name: str | None) -> int | None:
if not header_name:
@@ -235,7 +244,11 @@ def resolve_columns_from_field_mapping(
return None
if name in norm_headers:
return norm_headers.index(name)
return lower_to_idx.get(name.lower())
exact_lower = lower_to_idx.get(name.lower())
if exact_lower is not None:
return exact_lower
normalized = re.sub(r"[^a-z0-9]+", "", name.lower())
return normalized_to_idx.get(normalized)
runtime_mapping, _catalog = runtime_field_mapping(field_mapping)
if not runtime_mapping:
@@ -0,0 +1,177 @@
"""
services/shipping_notice/inventory_recovery_service.py
用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉。
依赖:PreparationAttempt/SourceAttempt、候选冻结、InventoryFile/TaskLink。
逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import (
ShippingInventoryFile,
ShippingInventoryPreparationAttempt,
ShippingInventoryPreparationSourceAttempt,
ShippingNotice,
ShippingTaskInventoryLink,
)
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
def create_inventory_preparation_round(
*, task: ShippingNotice, execution_id: int | None, recovery_plan_id: int | None,
action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None,
gate_attempt_id: int | None = None,
) -> ShippingInventoryPreparationAttempt:
"""创建一次任务级准备轮次;同一任务按 attempt_no 递增。"""
last = ShippingInventoryPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by(
ShippingInventoryPreparationAttempt.attempt_no.desc(),
).first()
round_row = ShippingInventoryPreparationAttempt(
task_id=int(task.id), execution_id=execution_id, gate_attempt_id=gate_attempt_id,
recovery_plan_id=recovery_plan_id,
attempt_no=(int(last.attempt_no) + 1 if last else 1), status='queued',
candidate_set_id=getattr(task, 'active_inventory_candidate_set_id', None),
input_snapshot_json={
'action_code': action_code,
'source_codes': list(source_codes or []),
'gate_attempt_id': int(gate_attempt_id) if gate_attempt_id else None,
},
operation_id=operation_id,
created_at=datetime.utcnow(),
)
db.session.add(round_row)
db.session.flush()
codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()]
if not codes:
codes = [str(getattr(task, 'inventory_source_code', '') or '').strip().upper()]
codes = [code for code in codes if code]
active_file = active_inventory_file_for_task(task)
for source_code in codes:
reusable, _reuse_reasons = check_inventory_snapshot_reusable(
snapshot=active_file,
source_code=source_code,
warehouse_id=getattr(active_file, 'warehouse_id', None) if active_file else None,
source_config_version=getattr(active_file, 'source_config_version', None) if active_file else None,
expected_file_sha256=getattr(active_file, 'file_sha256', None) if active_file else None,
parser_version=getattr(active_file, 'parser_version', None) if active_file else None,
mapping_version=getattr(active_file, 'mapping_version', None) if active_file else None,
)
reusable = bool(action_code == 'retry_inventory_from_field_mapping' and reusable)
link = ShippingTaskInventoryLink.query.filter_by(
task_id=int(task.id), matched_source_code=source_code, is_active=True,
).order_by(ShippingTaskInventoryLink.id.desc()).first()
source = ShippingInventoryPreparationSourceAttempt(
preparation_attempt_id=int(round_row.id), source_code=source_code,
status='reusable' if reusable else 'queued',
inventory_file_id=int(active_file.id) if reusable and active_file else None,
task_inventory_link_id=int(link.id) if reusable and link else None,
operation_id=operation_id,
)
db.session.add(source)
db.session.flush()
round_row.combination_input_fingerprint = build_inventory_combination_fingerprint(
task_snapshot_fingerprint=str(getattr(task, 'content_fingerprint', '') or ''),
candidate_freeze_fingerprint=str(getattr(getattr(task, 'active_inventory_candidate_set', None), 'input_fingerprint', '') or ''),
sources=[
{
'source_code': str(item.source_code),
'snapshot_id': item.inventory_file_id,
'snapshot_hash': (
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'file_sha256', None)
if item.inventory_file_id else None
),
'parser_version': (
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'parser_version', None)
if item.inventory_file_id else None
),
'mapping_version': (
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'mapping_version', None)
if item.inventory_file_id else None
),
}
for item in round_row.source_attempts
],
reservation_version=str(getattr(task, 'order_data_version', '') or ''),
matching_rule_version=str(getattr(task, 'inventory_source_config_version', '') or ''),
)
db.session.flush()
return round_row
def sync_inventory_preparation_round(
*, preparation_attempt: ShippingInventoryPreparationAttempt, result: Any,
) -> ShippingInventoryPreparationAttempt:
"""将 RPA 准备结果回写当前 PreparationAttempt,供 Projection/Gate 使用同一事实源。"""
def _read(name: str, default: Any) -> Any:
return result.get(name, default) if isinstance(result, dict) else getattr(result, name, default)
prepared = {str(code).strip().upper() for code in _read('prepared_source_codes', [])}
pending = {str(code).strip().upper() for code in _read('pending_source_codes', [])}
failed = {str(code).strip().upper() for code in _read('failed_source_codes', [])}
summaries = dict(_read('source_attempts', {}) or {})
for source in preparation_attempt.source_attempts:
code = str(source.source_code or '').strip().upper()
summary = dict(summaries.get(code) or {})
if code in prepared:
source.status = 'ready' if source.status != 'reusable' else 'reusable'
elif code in failed:
source.status = 'failed'
elif code in pending:
source.status = 'waiting'
if summary.get('attempt_id'):
source.rpa_attempt_id = int(summary['attempt_id'])
if failed:
preparation_attempt.status = 'failed'
elif pending:
preparation_attempt.status = 'waiting_external'
else:
preparation_attempt.status = 'succeeded'
preparation_attempt.completed_at = datetime.utcnow()
preparation_attempt.output_snapshot_json = {
'prepared_source_codes': sorted(prepared),
'pending_source_codes': sorted(pending),
'failed_source_codes': sorted(failed),
}
db.session.flush()
return preparation_attempt
def sync_preparation_source_from_rpa_attempt(
*, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None,
) -> None:
"""由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。
SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次,
因而不会污染当前 GateAttempt 对应的 PreparationAttempt。
"""
source = ShippingInventoryPreparationSourceAttempt.query.filter_by(
rpa_attempt_id=int(rpa_attempt_id),
).order_by(ShippingInventoryPreparationSourceAttempt.id.desc()).first()
if source is None:
return
status = str(rpa_status or '').strip().lower()
if status in {'succeeded', 'consumed'}:
source.status = 'ready'
if inventory_file_id:
source.inventory_file_id = int(inventory_file_id)
elif status in {'failed', 'exhausted'}:
source.status = 'failed'
elif status in {'queued', 'running'}:
source.status = 'waiting'
preparation = source.preparation_attempt
rows = list(getattr(preparation, 'source_attempts', []) or [])
if any(row.status == 'failed' for row in rows):
preparation.status = 'failed'
elif any(row.status in {'queued', 'running', 'waiting'} for row in rows):
preparation.status = 'waiting_external'
elif rows and all(row.status in {'ready', 'reusable', 'skipped'} for row in rows):
preparation.status = 'succeeded'
preparation.completed_at = datetime.utcnow()
db.session.flush()
@@ -180,7 +180,6 @@ def _try_reuse_inventory_snapshot(
row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)
]
if cached_lines:
task.inventory_lines_json = cached_lines
return inventory_loaded_response(
task,
cached_lines,
@@ -639,7 +638,14 @@ def _lock_task_for_rpa_callback(task: ShippingNotice) -> ShippingNotice:
"""对任务行加悲观锁,防止并发回调重复消费同一轮次。"""
if task.id is None:
return task
return db.session.query(ShippingNotice).filter_by(id=task.id).with_for_update().one()
# ShippingNotice 默认关系加载会带 shipping_case 外连接;PostgreSQL 不允许
# 对外连接空值端执行 FOR UPDATE。回调只需锁任务主表,避免成功文件回调在入库前失败。
return (
db.session.query(ShippingNotice)
.filter_by(id=task.id)
.with_for_update(of=ShippingNotice)
.one()
)
def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str:
@@ -671,6 +677,23 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
"""
run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or ""))
if run_no_error:
# 逐源 batch Trigger 的任务事件可能仍保留旧的 task-level batch_run_no;
# source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt
# 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。
source_run_no = str(payload.get('source_run_no') or '').strip()
if source_run_no:
from app.models import ShippingTaskInventoryRpaAttempt
current_attempt = (
db.session.query(ShippingTaskInventoryRpaAttempt)
.filter_by(task_no=task.task_no, source_run_no=source_run_no)
.order_by(ShippingTaskInventoryRpaAttempt.id.desc())
.first()
)
if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running'}:
run_no_error = None
if not run_no_error:
return None
log_task_event(
task,
"rpa_callback_rejected",
@@ -812,6 +835,40 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
return None
def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
"""强制单源库存成功回调携带 v2 身份围栏,禁止旧 payload 写入库存事实。
单源 Worker 与批量 Worker 共用 ``shipping_inventory_rpa.v2``;缺少任一
Attempt/Execution 身份时直接拒绝,避免回调按 Task 级旧 run_no 错绑轮次。
"""
if str(payload.get('status') or '').strip().lower() != 'success':
return None
required = {
'schema_version': payload.get('schema_version'),
'callback_id': payload.get('callback_id'),
'source_run_no': payload.get('source_run_no'),
'source_code': payload.get('source_code'),
'attempt_no': payload.get('attempt_no'),
'lease_token': payload.get('lease_token'),
'candidate_set_id': payload.get('candidate_set_id'),
'execution_id': payload.get('execution_id'),
'gate_id': payload.get('gate_id'),
}
missing = [key for key, value in required.items() if value in (None, '')]
if required['schema_version'] != 'shipping_inventory_rpa.v2' or missing:
return tool_response(
status='failed',
task=task,
message='单源 RPA 回调缺少完整 v2 身份字段,已拒绝处理',
data={
**serialize_task_for_tool(task),
'reason_code': 'callback_schema_invalid',
'missing_fields': missing,
},
)
return None
def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
"""
合并 batch 顶层契约字段到 result item。
@@ -1180,6 +1237,36 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
rpa_source = task_rpa_inventory_source(task) or {}
# retry_rpa 使用逐源 Attempt 编排,确保 Trigger 携带 source_run_no/lease_token,
# Worker 回调后可以精确绑定到本次 Attempt;自动模式继续使用下方旧兼容路径。
if manual_retry_round:
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
prepared = ensure_all_required_sources_prepared(task, mode='retry_rpa')
db.session.flush()
if prepared.pending_source_codes:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
db.session.commit()
return tool_response(
status='running', task_id=task.task_no,
message='已重新触发库存获取,等待各库存源回调。',
data={**serialize_task_for_tool(task), 'rpa': {
'pending_source_codes': prepared.pending_source_codes,
'source_attempts': prepared.source_attempts,
}},
)
if prepared.all_prepared:
return tool_response(status='completed', task=task, message='库存快照已准备完成。')
return tool_response(
status='needs_human', task=task,
message='库存 RPA 未能为全部库存源生成结果。',
data={**serialize_task_for_tool(task), 'rpa': {
'failed_source_codes': prepared.failed_source_codes,
'source_attempts': prepared.source_attempts,
}},
)
# [STEP 0.5] 未过期库存快照优先复用;retry_rpa 强制跳过。
reused = _try_reuse_inventory_snapshot(task, rpa_source, mode=mode)
if reused is not None:
@@ -1570,14 +1657,24 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message="未找到任务编号")
# 单源成功回调必须先通过 v2 身份校验;批量回调走独立 v2 envelope。
# 失败/跳过回调仍由后续业务错误合同处理,不以缺失文件身份掩盖原始失败。
if not isinstance(payload.get('results'), list):
contract_resp = _validate_single_source_v2_contract(task, payload)
if contract_resp is not None:
return contract_resp
# [T7 统一回调幂等] 尝试按 per-source run_no 提取 source_code;如符合 PSR-*-<SOURCE>-A<N>-* 格式则先入 per_source_callback_handler
run_no_raw = str(payload.get("run_no") or "").strip()
source_code_from_run: str | None = None
if run_no_raw and run_no_raw.startswith('PSR-'):
# PSR-<task>-<SOURCE>-A<N>-<uuid8> → 第 3 段 = SOURCE
parts = run_no_raw.split('-')
if len(parts) >= 4 and parts[3].startswith('A'):
candidate = str(parts[2] or '').strip().upper()
# PSR-<task_no>-<SOURCE>-A<N>-<uuid8>;task_no 本身可含连字符,
# 因此必须从末尾的 source/attempt 结构反向解析,不能使用固定 split 下标。
import re
match = re.match(r'^PSR-(?P<task>.+)-(?P<source>[^-]+)-A\d+-[^-]+$', run_no_raw)
if match:
candidate = str(match.group('source') or '').strip().upper()
if candidate:
source_code_from_run = candidate
per_source_result = None
@@ -1601,6 +1698,54 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"idempotent": True,
},
)
if per_source_code == 'callback_conflict':
# callback_id 已归属于其他 Attempt;不得继续走兼容入口写入库存正式事实。
log_task_event(
task,
'shipping_inventory_callback_ignored',
{
'run_no': run_no_raw,
'source_code': source_code_from_run,
'reason': 'callback_id_already_consumed_by_other_attempt',
'callback_id': str(payload.get('callback_id') or '').strip(),
},
source='rpa_callback',
)
return tool_response(
status='success',
task=task,
message='RPA 回调已被其他 Attempt 消费,本次回调忽略。',
data={
'run_no': run_no_raw,
'source_code': source_code_from_run,
'callback_conflict': True,
'retry_safe': False,
},
)
if per_source_code == 'identity_mismatch':
# v2 身份围栏未通过时必须在统一入口 fail-closed,禁止回落到 Task 级旧回调路径。
log_task_event(
task,
'rpa_callback_rejected',
{
'run_no': run_no_raw,
'source_code': source_code_from_run,
'reason': 'callback_identity_mismatch',
'callback_id': str(payload.get('callback_id') or '').strip(),
},
source='rpa_callback',
)
return tool_response(
status='failed',
task=task,
message='RPA 回调身份与当前库存准备轮次不一致,已拒绝处理。',
data={
'run_no': run_no_raw,
'source_code': source_code_from_run,
'error_code': 'callback_identity_mismatch',
'retry_safe': False,
},
)
if per_source_code == 'superseded_late':
log_task_event(
task,
@@ -1969,7 +2114,12 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
raw_status = _normalize_rpa_inventory_batch_item_status(merged_item)
task_no = str(merged_item.get("task_no") or "").strip()
run_no_item = str(merged_item.get("run_no") or "").strip() or run_no
source_run_no_item = str(merged_item.get("source_run_no") or "").strip()
# Worker 旧版只回传 run_no;三元组定位 Attempt 时用本批次 run_no 兜底,
# 否则成功文件已入库但旧 failed Attempt 永远不会被收敛。
source_run_no_item = (
str(merged_item.get("source_run_no") or "").strip()
or run_no_item
)
item_callback_id = str(merged_item.get("callback_id") or "").strip()
if not item_callback_id and source_run_no_item:
item_callback_id = f"{callback_id}:{source_run_no_item}:C1"
@@ -1991,7 +2141,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
})
continue
# [T7 批量回调幂等] 每个 item 先走 per_source_callback_handler;batch 中单独处理不中断整体
if source_code and source_run_no_item and raw_status != 'success':
if source_code and source_run_no_item:
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
per_source_code, _a = per_source_callback_handler(
task,
@@ -2040,6 +2190,27 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
"retry_safe": True,
})
continue
if per_source_code == 'identity_mismatch':
log_task_event(
task,
'rpa_callback_rejected',
{
'run_no': run_no_item,
'source_code': source_code,
'reason': 'callback_identity_mismatch',
'callback_id': item_callback_id,
'batch': True,
},
source='rpa_callback',
)
failed.append({
'source_code': source_code,
'warehouse_id': warehouse_id,
'task_no': task_no,
'error_code': 'callback_identity_mismatch',
'error': 'RPA callback identity does not match the active preparation attempt.',
})
continue
task = _lock_task_for_rpa_callback(task)
if task and raw_status in {"skipped", "failed"}:
@@ -2120,6 +2291,15 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
continue
if raw_status == "success":
# 定时批量成功项必须显式携带 Warehouse 身份;先做身份校验,
# 避免缺 Warehouse 被后续文件路径错误遮蔽。
if not warehouse_id:
failed.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"error": "warehouse_id_missing",
})
continue
file_path = str(merged_item.get("file_path") or "").strip()
path = Path(file_path).resolve() if file_path else None
from app.services.shipping_notice.rpa import inventory_drop_dir
@@ -2237,7 +2417,10 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
from app.models import ShippingTaskInventoryRpaAttempt
_att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
if _att:
# 成功回调是该 Attempt 的最终事实;清理旧失败态,避免投影继续显示 failed/retry。
_att.status = 'succeeded'
_att.callback_id = item_callback_id or callback_id; _att.callback_received_at = datetime.utcnow(); _att.file_generated = True; _att.file_path = str(path); _att.file_sha256 = server_hash; _att.file_size = server_size; _att.file_exists_at_callback = True; _att.execution_phase = 'callback_received'; _att.transaction_status = 'succeeded'
_att.error_code = None; _att.error_message = None; _att.transaction_error_code = None
created.append(created_entry)
if item_orphan_path:
batch_new_storage_paths.append(item_orphan_path)
@@ -212,6 +212,26 @@ def _normalize_inventory_row(
parsed[field_id] = value.isoformat() if hasattr(value, 'isoformat') else str(value).strip()
else:
parsed[field_id] = str(value).strip()
# 正式运行快照对外统一 canonical 字段;同时保留字段 ID 供审计和旧 Profile 回放。
canonical_by_code = {
'part_number': 'part_number',
'reservation_id': 'reservation_id',
'available_qty': 'available_qty',
'qty': 'available_qty',
'unit': 'uom',
'warehouse_id': 'warehouse_id',
'warehouse_code': 'warehouse_id',
}
for field_id, field in catalog.items():
target = canonical_by_code.get(str(field.field_code or '').strip())
if target and parsed.get(field_id) not in (None, ''):
parsed[target] = parsed[field_id]
if 'reservation_id' in parsed:
parsed['reservation_id'] = validated_reservation_id(parsed['reservation_id'])
if 'part_number' in parsed:
parsed['part_number'] = str(parsed['part_number'] or '').strip()
if 'available_qty' in parsed:
parsed['available_qty'] = _parse_qty(parsed['available_qty'])
return parsed
idx_part_number = columns.get("part_number")
@@ -0,0 +1,52 @@
"""
services/shipping_notice/inventory_snapshot_reuse_policy.py
用途:统一判断库存快照是否可被当前任务复用。
依赖:ShippingInventoryFile、ShippingNotice、候选冻结事实。
逻辑:所有关键身份和版本条件均 fail-closed;返回结构化原因供审计和 Projection 使用。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
def check_inventory_snapshot_reusable(
*, snapshot: Any, source_code: str, warehouse_id: str | None = None,
source_config_version: str | None = None, candidate_input_fingerprint: str | None = None,
expected_file_sha256: str | None = None, parser_version: str | None = None,
mapping_version: str | None = None, now: datetime | None = None,
) -> tuple[bool, list[str]]:
"""返回 (是否可复用, 不可复用原因列表)。"""
reasons: list[str] = []
current = now or datetime.utcnow()
if snapshot is None:
return False, ['snapshot_missing']
if str(getattr(snapshot, 'snapshot_status', '') or '').lower() != 'ready':
reasons.append('snapshot_not_ready')
expires_at = getattr(snapshot, 'expires_at', None)
if expires_at is not None and expires_at <= current:
reasons.append('snapshot_expired')
if str(getattr(snapshot, 'source_code', '') or '').strip().upper() != str(source_code or '').strip().upper():
reasons.append('source_code_mismatch')
if warehouse_id is not None and str(getattr(snapshot, 'warehouse_id', '') or '').strip().upper() != str(warehouse_id).strip().upper():
reasons.append('warehouse_mismatch')
if source_config_version is not None and str(getattr(snapshot, 'source_config_version', '') or '') != str(source_config_version):
reasons.append('source_config_version_mismatch')
if expected_file_sha256 is not None and str(getattr(snapshot, 'file_sha256', '') or '') != str(expected_file_sha256):
reasons.append('file_hash_mismatch')
if parser_version is not None and str(getattr(snapshot, 'parser_version', '') or '') != str(parser_version):
reasons.append('parser_version_mismatch')
if mapping_version is not None and str(getattr(snapshot, 'mapping_version', '') or '') != str(mapping_version):
reasons.append('mapping_version_mismatch')
if candidate_input_fingerprint is not None and str(getattr(snapshot, 'input_fingerprint', '') or '') != str(candidate_input_fingerprint):
reasons.append('candidate_input_fingerprint_mismatch')
if getattr(snapshot, 'invalidated_at', None) is not None:
reasons.append('snapshot_invalidated')
return not reasons, reasons
def is_inventory_snapshot_reusable(**kwargs: Any) -> bool:
"""布尔兼容入口;详细原因由 check_inventory_snapshot_reusable 提供。"""
return check_inventory_snapshot_reusable(**kwargs)[0]
@@ -281,24 +281,21 @@ def create_inventory_snapshot_from_rpa(
excel_warehouse_id = ""
warehouse_id = export_warehouse_id
warehouse_code = warehouse_id
# Excel 内部 Warehouse 编码由外部 DSV/货代系统决定,不能假设等于 HXOPS 配置编码。
# 快照归属继续使用任务/库存源配置;实际文件编码仅作为可选审计信息保留。
excel_verified = False
if success:
local = Path(local_path)
expected_wh = str(verify_warehouse_id or export_warehouse_id or "").strip().upper()
if expected_wh:
from app.services.shipping_notice.inventory_file_identity import (
assert_inventory_excel_warehouse_identity,
)
# 仅采集文件中的 Warehouse 作为审计信息,不将外部编码与 HXOPS 配置编码做一致性拦截。
try:
from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel
excel_warehouse_id = assert_inventory_excel_warehouse_identity(
local,
expected_warehouse_id=expected_wh,
operation="rpa_snapshot",
)
warehouse_id = expected_wh
warehouse_code = warehouse_id
excel_verified = True
excel_warehouse_ids = extract_warehouse_ids_from_inventory_excel(local)
if len(excel_warehouse_ids) == 1:
excel_warehouse_id = next(iter(excel_warehouse_ids))
except Exception:
excel_warehouse_id = ""
path = inventory_file_upload_path(
inventory_file_no,
suffix=inventory_storage_suffix_for_path(local),
@@ -47,7 +47,8 @@ INVENTORY_SOURCE_ERROR_CODES = {
def _inventory_source_config_current(task: ShippingNotice) -> bool:
"""任务上记录的库存源配置版本须与当前数据库版本一致。"""
stored = str(task.inventory_source_config_version or "").strip()
# 兼容旧任务/轻量测试桩:缺失版本字段等同于未冻结当前配置。
stored = str(getattr(task, 'inventory_source_config_version', None) or "").strip()
current = inventory_sources_runtime_version()
if not stored:
return False
@@ -129,9 +129,11 @@ def persist_line_inventory_match_facts(
except (TypeError, ValueError):
continue
res = res_by_index.get(index) or {}
# Case 草稿 line_key 是订单明细的正式身份;匹配器临时 line-1 只能兜底,
# 禁止覆盖 machine-1 等正式键,否则事实已落库但工作台无法关联显示。
line_key = str(
res.get('line_key')
or keys_by_index.get(index)
keys_by_index.get(index)
or res.get('line_key')
or f'line-{index + 1}'
).strip()
if not line_key:
@@ -202,6 +204,13 @@ def persist_line_inventory_match_facts(
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# Draft line_key 发生过版本切换时,按稳定 line_index 关闭旧键事实,
# 避免同一订单行同时存在两个 current 投影。
(
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_index=index, is_current=True)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# [T6 E1] 行级证据哈希:SHA256(source_code|file_no|row_index|reservation_id|part_number)
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
file_no = str(result.get('inventory_file_no') or '')[:128] or None
@@ -323,6 +332,9 @@ def persist_line_inventory_match_facts(
existing.matching_rule_version = str(matching_rule_version or '')[:64] or None
existing.inventory_source_code = src_code
existing.is_current = True
existing.invalidated_at = None
existing.invalidated_by_attempt_id = None
existing.invalidation_reason = None
existing.matched_at = now
existing.updated_at = now
existing.candidate_set_id = int(current_candidate_set.id) if current_candidate_set is not None else None
@@ -361,6 +373,18 @@ def persist_line_inventory_match_facts(
)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# Draft line_key 发生过版本切换时,更新已有新键也必须关闭旧键;
# 否则旧 key 会与新 key 同时进入 current 投影,导致订单明细不确定。
(
ShippingNoticeLineInventoryMatch.query
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.line_index == index,
ShippingNoticeLineInventoryMatch.id != int(existing.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
written.append(existing)
db.session.flush()
@@ -14,7 +14,7 @@ from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
from app.models import ShippingNoticeLineInventoryMatch
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
MATCH_NOT_FOUND = 'not_found'
@@ -423,6 +423,10 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str,
def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]:
"""将 ORM 行序列化为投影输入。"""
snapshot = (
ShippingInventoryFile.query.get(int(row.inventory_snapshot_id))
if row.inventory_snapshot_id is not None else None
)
return {
'id': int(row.id),
'task_id': int(row.task_id),
@@ -442,6 +446,18 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
'unit': row.unit,
'matching_rule_version': row.matching_rule_version,
'inventory_source_code': row.inventory_source_code,
'inventory_file_no': getattr(row, 'matched_file_no', None),
'inventory_file_sha256': (
dict(row.detail_json or {}).get('file_sha256')
or dict(row.detail_json or {}).get('inventory_file_sha256')
or dict(row.detail_json or {}).get('file_sha256_hex')
or getattr(snapshot, 'file_sha256', None)
),
'inventory_row_index': getattr(row, 'matched_row_index', None),
'match_attempt_id': getattr(row, 'match_attempt_id', None),
'required_qty': row.required_qty,
'matched_qty': getattr(row, 'matched_qty', None) or row.available_qty,
'shortage_qty': row.shortage_qty,
'matched_at': row.matched_at.isoformat() if row.matched_at else None,
'is_current': bool(row.is_current),
'detail_json': dict(row.detail_json or {}),
@@ -639,6 +655,13 @@ def project_line_inventory_view(
'inventory_snapshot_id': fact.get('inventory_snapshot_id'),
'inventory_checked_at': fact.get('matched_at'),
'inventory_source_code': fact.get('inventory_source_code'),
'inventory_file_no': fact.get('inventory_file_no'),
'inventory_file_sha256': fact.get('inventory_file_sha256') or fact.get('file_sha256'),
'inventory_row_index': fact.get('inventory_row_index') or fact.get('matched_row_index'),
'match_attempt_id': fact.get('match_attempt_id'),
'required_qty': fact.get('required_qty'),
'matched_qty': fact.get('matched_qty') or fact.get('available_qty'),
'shortage_qty': fact.get('shortage_qty'),
'inventory_source': source,
'matching_rule_version': fact.get('matching_rule_version'),
'user_line_status': user_status,
@@ -85,7 +85,14 @@ def freeze_order_snapshot(
ValidationError: 当前 Extraction 不完整或核心字段契约不匹配。
"""
# [STEP 1] 锁定数据库中的 Task,令并发确认串行化;同一 Task 的重复点击复用既有快照。
locked_task = ShippingNotice.query.filter_by(id=task.id).with_for_update().one()
# query 默认带 shipping_case 的 joinedload;PostgreSQL 不允许对外连接的空值端
# 执行 FOR UPDATE。仅锁定正式任务主表,避免冻结在已确认但关联 Case 可为空时失败。
locked_task = (
ShippingNotice.query
.filter_by(id=task.id)
.with_for_update(of=ShippingNotice)
.one()
)
if locked_task.order_snapshot_id:
snapshot = db.session.get(ShippingOrderSnapshot, locked_task.order_snapshot_id)
if snapshot is not None:
@@ -536,6 +536,13 @@ def project_review_case_line_decisions(
'inventory_snapshot_id': inv_view.get('inventory_snapshot_id'),
'inventory_checked_at': inv_view.get('inventory_checked_at'),
'inventory_source_code': inv_view.get('inventory_source_code'),
'inventory_file_no': inv_view.get('inventory_file_no'),
'inventory_file_sha256': inv_view.get('inventory_file_sha256'),
'inventory_row_index': inv_view.get('inventory_row_index'),
'match_attempt_id': inv_view.get('match_attempt_id'),
'required_qty': inv_view.get('required_qty') or required,
'matched_qty': inv_view.get('matched_qty') or available,
'shortage_qty': inv_view.get('shortage_qty') or shortage,
'inventory_source': inv_view.get('inventory_source'),
'decision_source': inv_view.get('decision_source'),
'retryable': bool(inv_view.get('retryable')),
@@ -716,6 +716,16 @@ def serialize_review_case(
.order_by(ShippingProcessExecution.id.desc())
.first()
)
# 正式 OT 的 Execution 可能在 Case 创建后才绑定 task_id;复核页必须沿
# case.confirmed_task_id → ShippingNotice → Execution 继续查找,不能退回旧的
# process_gate 兜底,否则会丢失当前 Gate 与 RecoveryPlan 按钮。
if execution is None and formal_ot.get('task_id') is not None:
execution = (
ShippingProcessExecution.query
.filter_by(task_id=int(formal_ot['task_id']))
.order_by(ShippingProcessExecution.id.desc())
.first()
)
if execution is not None:
process_gate = apply_post_ot_gate_rules(
project_user_gate_summary(execution),
@@ -448,6 +448,22 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
except Exception: # noqa: BLE001
return None
def _safe_user_error(value: Any) -> str | None:
"""用户态只返回稳定错误码,禁止泄漏 ImportError、路径和堆栈。"""
raw = str(value or '').strip()
if not raw:
return None
lowered = raw.lower()
if (
'cannot import name' in lowered
or 'traceback' in lowered
or '\\app\\' in lowered
or '/app/' in lowered
or 'site-packages' in lowered
):
return 'auto_progress_job_failed'
return raw[:128]
def _job_fields(job) -> dict[str, Any]:
if job is None:
return {
@@ -465,7 +481,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
)
return {
'job_id': int(job.id),
'error_code': error_code,
'error_code': _safe_user_error(error_code),
'attempts': int(job.attempts or 0),
'max_attempts': int(job.max_attempts or 0) or None,
'completed_at': _iso(getattr(job, 'finished_at', None)),
@@ -621,6 +637,11 @@ def project_stage_for_task(
'stage_node': None,
}
# 上传登记/回调会先更新 ShippingNotice 聚合事实;旧 OT.stage 可能仍停在
# freight_uploading,不能用过期阶段覆盖已经完成的履约状态。
if process_status in {'uploaded', 'closed', 'completed'}:
return _with_label('completed', source='notice_terminal')
# [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。
order_task = None
try:
@@ -791,8 +812,12 @@ def apply_post_ot_gate_rules(
blocking = None
gate_code = ''
# inventory_preparation(Worker 等待)→ 技术自动,无人工卡。
if gate_code in _SYSTEM_WAIT_INVENTORY_GATES:
# inventory_preparation 的等待态由 Worker 自动推进;但 blocked_retryable
# 是明确的库存文件/RPA失败,必须保留 Gate 动作,不能被清成系统处理中。
if (
gate_code in _SYSTEM_WAIT_INVENTORY_GATES
and raw_gate_status in {'pending', 'queued', 'running', 'waiting_external'}
):
result['current_blocking_gate'] = None
result['blocking_reason_code'] = None
result['blocking_message'] = None
@@ -811,12 +836,11 @@ def apply_post_ot_gate_rules(
result['available_actions'] = []
return result
# 库存/履约域 + human + 有动作 → 保留人工阻断(显式集合优先;前缀仅作必要兼容)。
# 所有正式 OT Gate 均由服务端下发动作;页面只负责展示,实际可执行性由
# Gate API 按当前 Gate、Attempt、版本和权限逐项校验。不能仅因 Gate 属于
# Excel/上传等技术阶段就静默清除用户入口。
next_action = str(result.get('next_action_code') or '').strip()
in_domain = gate_code in _POST_OT_INVENTORY_FULFILLMENT_GATES or (
gate_code.startswith('inventory_') or gate_code.startswith('fulfill')
)
if in_domain and next_action and not result.get('technical_auto_only'):
if next_action and not result.get('technical_auto_only'):
result['owner_type'] = 'human'
result['technical_auto_only'] = False
return result
@@ -676,7 +676,10 @@ def ensure_stp_auto_create_for_case(
'idempotency_key': idempotency_key,
'job_status': str(existing.status),
'can_auto_create': True,
'retry_of_job_id': int(existing.retry_of_job_id) if existing.retry_of_job_id else None,
'retry_of_job_id': (
int(getattr(existing, 'retry_of_job_id', None))
if getattr(existing, 'retry_of_job_id', None) else None
),
}
# [STEP] failed/dead 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。
@@ -62,6 +62,47 @@ def _attempt_ref_has_ready_snapshot(
return is_snapshot_fresh(inv_file)
def _validate_callback_attempt_identity(
*,
task: ShippingNotice,
attempt: ShippingTaskInventoryRpaAttempt,
callback_payload: dict[str, Any],
) -> bool:
"""校验回调身份与已冻结 Attempt/当前 CandidateSet/正式 Execution 一致。"""
required = ('schema_version', 'callback_id', 'source_run_no', 'attempt_no', 'lease_token',
'candidate_set_id', 'execution_id', 'gate_id')
if str(callback_payload.get('schema_version') or '') != 'shipping_inventory_rpa.v2':
return False
if any(callback_payload.get(key) in (None, '') for key in required):
return False
if str(callback_payload.get('task_no') or '').strip() != str(task.task_no or '').strip():
return False
if str(callback_payload.get('source_code') or '').strip().upper() != str(attempt.source_code or '').strip().upper():
return False
if str(callback_payload.get('source_run_no') or '').strip() != str(attempt.source_run_no or '').strip():
return False
try:
if int(callback_payload.get('attempt_no')) != int(attempt.attempt_no):
return False
except (TypeError, ValueError):
return False
if str(callback_payload.get('lease_token') or '') != str(attempt.lease_token or ''):
return False
stored = dict(attempt.extra_json or {})
for key in ('candidate_set_id', 'execution_id', 'gate_id'):
try:
if int(callback_payload.get(key)) != int(stored.get(key)):
return False
except (TypeError, ValueError):
return False
active_candidate = getattr(task, 'active_inventory_candidate_set_id', None)
if active_candidate is not None and int(callback_payload.get('candidate_set_id')) != int(active_candidate):
return False
expected_warehouse = str(stored.get('expected_warehouse_id') or '').strip().upper()
callback_warehouse = str(callback_payload.get('expected_warehouse_id') or callback_payload.get('warehouse_id') or '').strip().upper()
return not expected_warehouse or callback_warehouse == expected_warehouse
PER_SOURCE_RUN_NO_PREFIX = 'PSR' # Per-Source Run,区别于 legacy T-xxx 全局 run_no
@@ -194,7 +235,21 @@ def _snapshot_ready_for_source(
snap = find_latest_ready_snapshot(source_code, warehouse_id)
except Exception:
snap = None
return snap is not None
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
source_config_version = None
if isinstance(rpa_source, dict):
source_config_version = rpa_source.get('source_config_version') or rpa_source.get('config_version')
parser_version = rpa_source.get('parser_version') if isinstance(rpa_source, dict) else None
mapping_version = rpa_source.get('mapping_version') if isinstance(rpa_source, dict) else None
reusable, _ = check_inventory_snapshot_reusable(
snapshot=snap,
source_code=source_code,
warehouse_id=warehouse_id,
source_config_version=source_config_version,
parser_version=parser_version,
mapping_version=mapping_version,
)
return reusable
def _attempts_summary(
@@ -345,8 +400,26 @@ def ensure_all_required_sources_prepared(
# trigger 文件的逻辑,文件名同时带 __SOURCE_CODE__A<N> 后缀即可。
# 这里的 trigger_file_path 仅作为审计字段记录,实际触发由 Worker 按目录扫描识别。
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.models import ShippingProcessExecution, ShippingProcessGate
legacy_rpa_source = task_rpa_inventory_source(task) or dict(rpa_source)
execution_id = getattr(task, 'active_process_execution_id', None)
gate_id = None
if execution_id:
execution_row = sess.get(ShippingProcessExecution, int(execution_id))
if execution_row is not None and execution_row.current_gate_code:
gate_row = sess.query(ShippingProcessGate).filter_by(
execution_id=int(execution_row.id),
gate_code=str(execution_row.current_gate_code),
).first()
gate_id = int(gate_row.id) if gate_row is not None else None
new_att.extra_json = dict(
new_att.extra_json or {},
candidate_set_id=getattr(task, 'active_inventory_candidate_set_id', None),
execution_id=execution_id,
gate_id=gate_id,
expected_warehouse_id=rpa_source.get('warehouse_id'),
)
# 强制注入 source_code 覆盖旧 task 级单源字段,使 RPA Worker 可按 per-source 执行
per_source_payload = {
'schema_version': 'shipping_inventory_rpa.v2',
@@ -355,8 +428,14 @@ def ensure_all_required_sources_prepared(
'attempt_no': next_att_no,
'source_code': source_code,
'source_run_no': new_att.source_run_no,
'callback_id': f'{new_att.source_run_no}:C1',
'batch_run_no': f'BATCH-{task_no}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}',
'lease_token': new_att.lease_token,
# 回调身份必须与本次冻结版本/正式 Execution 绑定;Worker 只原样回传。
'candidate_set_id': getattr(task, 'active_inventory_candidate_set_id', None),
'execution_id': execution_id,
'gate_id': gate_id,
'expected_warehouse_id': rpa_source.get('warehouse_id'),
'per_source_attempt': True,
}
trigger_result = write_inventory_export_trigger_for_task(
@@ -425,7 +504,26 @@ def per_source_callback_handler(
task_no = str(task.task_no or '').strip()
source_code_up = str(source_code or '').strip().upper()
# [STEP 1] 三元组定位
# [STEP 1] callback_id 重放检查。只要回调带有稳定 ID,先于业务身份解析,
# 防止同一事件被另一个 Attempt 消费;同 Attempt 重放直接返回幂等结果。
callback_id = str((callback_payload or {}).get('callback_id') or '').strip()
if callback_id:
callback_attempt = (
sess.query(ShippingTaskInventoryRpaAttempt)
.filter_by(callback_id=callback_id)
.one_or_none()
)
if callback_attempt is not None:
same_attempt = (
callback_attempt.task_no == task_no
and callback_attempt.source_code == source_code_up
and callback_attempt.run_no == str(run_no or '').strip()
)
if same_attempt:
return 'idempotent_ok', callback_attempt
return 'callback_conflict', callback_attempt
# [STEP 2] 三元组定位
attempt = (
sess.query(ShippingTaskInventoryRpaAttempt)
.filter(
@@ -440,11 +538,20 @@ def per_source_callback_handler(
if attempt is None:
return 'not_found', None
# [STEP 2] 幂等
if not _validate_callback_attempt_identity(
task=task,
attempt=attempt,
callback_payload=dict(callback_payload or {}),
):
attempt.extra_json = dict(attempt.extra_json or {}, callback_identity_rejected=True)
sess.flush([attempt])
return 'identity_mismatch', attempt
# [STEP 3] 幂等
if attempt.status in ('succeeded', 'consumed', 'superseded'):
return 'idempotent_ok', attempt
# [STEP 3] 迟到保护:同 (task, source) 有更新 run 已终态
# [STEP 4] 迟到保护:同 (task, source) 有更新 run 已终态
consumed_runs = _consumed_run_nos(task_no, source_code_up, session=sess)
# Run no format: PSR-<task>-<SOURCE>-A<N>-<uuid> → 排序按 attempt_no 前缀即可
try:
@@ -472,7 +579,7 @@ def per_source_callback_handler(
sess.flush([attempt])
return 'superseded_late', attempt
# [STEP 4] Task 已终态(兼容旧枚举 active/blocked 等非终态)
# [STEP 5] Task 已终态(兼容旧枚举 active/blocked 等非终态)
terminal_statuses = {'completed', 'cancelled', 'failed_terminal'}
if str(getattr(task, 'process_status', '') or '').strip() in terminal_statuses:
attempt.status = 'superseded'
@@ -483,7 +590,7 @@ def per_source_callback_handler(
sess.flush([attempt])
return 'task_terminal', attempt
# [STEP 5] 写回调结果
# [STEP 6] 写回调结果
attempt.callback_payload_json = dict(callback_payload or {})
attempt.callback_received_at = datetime.utcnow()
attempt.callback_id = str(callback_payload.get('callback_id') or '').strip() or attempt.callback_id
@@ -504,6 +611,8 @@ def per_source_callback_handler(
attempt.transaction_status = 'rejected'
attempt.error_code = error_code
attempt.error_message = error_message[:2000] if error_message else None
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed')
sess.flush([attempt])
return 'failed', attempt
# 回调标称成功,但必须二次验证快照已真实入库且 ready,否则仍然算失败(防止 RPA 伪成功)
@@ -528,10 +637,18 @@ def per_source_callback_handler(
attempt.error_message = (
f"回调返回成功但关联库存快照未通过门禁校验:{missing_reason}"[:2000]
)
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed')
sess.flush([attempt])
return 'failed', attempt
attempt.status = 'succeeded'
attempt.transaction_status = 'succeeded'
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
sync_preparation_source_from_rpa_attempt(
rpa_attempt_id=int(attempt.id),
rpa_status='succeeded',
inventory_file_id=(int(_inv.id) if inventory_file_no and _inv is not None else None),
)
sess.flush([attempt])
# 回调只改变 Attempt/Snapshot 事实;正式 Task Gate 由 AutoProgress Job 重新校验。
# 调用方在同一事务提交后,Job 才对 Worker 可见。
@@ -87,9 +87,12 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str:
return 'inventory_file_identity_mismatch'
return 'inventory_rpa_export_failed'
# [STEP] 空列表=文件无有效行;None/非列表=尚未落库存文件
if isinstance(task.inventory_lines_json, list):
if len(task.inventory_lines_json) == 0:
# [STEP] 活动库存快照是运行事实;任务字段仅为历史兼容投影。
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
active_lines = active_inventory_lines_for_task(task)
if isinstance(active_lines, list):
if len(active_lines) == 0:
return 'inventory_file_empty'
return 'inventory_preparation_failed'
return 'inventory_file_missing'
@@ -276,6 +279,10 @@ def apply_gate_outcome(
return gate
key = str(idempotency_key or '').strip() or f'bridge:{execution.execution_no}:{code}:{fingerprint[:16]}'
if force and gate is not None:
# 强制重评发生在新的 Gate evaluation_version 上;旧版本 Attempt 的成功回放
# 不能覆盖当前 invalidated/blocked 状态,否则 Execution 指针会永久停在历史 Gate。
key = f'{key}:v{int(gate.evaluation_version)}'
return sync_gate_from_business_result(
execution_no=str(execution.execution_no),
gate_code=code,
@@ -728,6 +735,63 @@ def sync_fulfillment_gates_from_task(
'task_no': str(task.task_no or '') or None,
'has_inventory_lines': has_inventory_lines,
}
# PreparationAttempt 是库存准备的主事实;仅在当前 Execution/CandidateSet
# 存在对应轮次时使用,避免旧任务的孤立轮次污染正式链。
preparation = None
try:
from app.models import ShippingInventoryPreparationAttempt
prep_query = (
ShippingInventoryPreparationAttempt.query
.filter_by(task_id=int(task.id), execution_id=int(execution.id))
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
)
if execution.candidate_set_id is not None:
prep_query = prep_query.filter(
ShippingInventoryPreparationAttempt.candidate_set_id == int(execution.candidate_set_id)
)
preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first()
except Exception: # noqa: BLE001
preparation = None
if preparation is not None:
source_rows = list(getattr(preparation, 'source_attempts', []) or [])
required = [str(row.source_code or '').strip().upper() for row in source_rows]
prepared = [code for code, row in zip(required, source_rows) if row.status in {'ready', 'reusable'}]
pending = [code for code, row in zip(required, source_rows) if row.status in {'queued', 'running', 'waiting'}]
failed = [code for code, row in zip(required, source_rows) if row.status == 'failed']
task_facts.update({
'preparation_attempt_id': int(preparation.id),
'preparation_attempt_no': int(preparation.attempt_no),
'required_sources': required,
'prepared_sources': prepared,
'pending_sources': pending,
'failed_sources': failed,
})
if preparation.status in {'queued', 'running', 'waiting_external'} or pending:
apply_gate_outcome(
execution=execution, gate_code='inventory_preparation', passed=False,
outcome='waiting_external', effective_result={'findings': [], **task_facts},
blocking_reason_code='inventory_preparation_waiting', actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:waiting', force=True,
)
return
if preparation.status == 'failed' or failed:
apply_gate_outcome(
execution=execution, gate_code='inventory_preparation', passed=False,
outcome='blocked_retryable', effective_result={'findings': [], **task_facts},
blocking_reason_code='inventory_preparation_failed', actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:failed', force=True,
)
return
if preparation.status == 'succeeded' and required and len(prepared) == len(required):
apply_gate_outcome(
execution=execution, gate_code='inventory_preparation', passed=True,
effective_result=task_facts, actor_type=actor_type, actor_id=actor_id,
idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:passed', force=True,
)
# Continue below for mapping/matching facts.
if status == 'waiting_inventory':
from app.services.shipping_notice.constants import PH_RPA_PENDING
waiting_reason = (
@@ -923,6 +987,9 @@ def sync_fulfillment_gates_from_task(
execution=execution,
gate_code='artifact_generation',
passed=artifact_ok,
# Excel 资格已通过但产物尚未生成属于系统可恢复动作;必须保留
# regenerate_excel_artifact,不能落为 blocked_manual 后失去自动推进入口。
outcome=None if artifact_ok else 'blocked_retryable',
effective_result={
'findings': (
[] if artifact_ok else _fulfillment_blocking_finding(
@@ -17,7 +17,17 @@ from typing import Any, Final
# 契约版本;投影、OpenAPI 与 i18n 必须与此对齐。
PROCESS_GATE_CONTRACT_VERSION: Final[str] = 'shipping-process-gate-v1'
PROCESS_GATE_CONTRACT_VERSION: Final[str] = 'shipping-process-gate-v2'
# Gate 实施能力状态:v2 运行时合同必须明确每个 Gate 的当前适配程度。
# supported:已有真实执行器或人工业务入口;implemented:库存/履约闭环已实现;
# adapter_required / blocked 预留给未来未接线 Gate,禁止前端据此猜测可执行动作。
PROCESS_GATE_IMPLEMENTATION_STATUSES: Final[frozenset[str]] = frozenset({
'supported',
'implemented',
'adapter_required',
'blocked',
})
# Finding 严重级别:仅 blocking 可改变 Gate 状态;diagnostic 供管理员诊断。
PROCESS_GATE_FINDING_SEVERITIES: Final[frozenset[str]] = frozenset({
@@ -75,6 +85,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 1,
'label': '文档和附件可用性',
'responsible_party': 'system',
'implementation_status': 'supported',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'rematerialize_document',
@@ -86,6 +97,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 2,
'label': 'PDF 版面解析',
'responsible_party': 'worker',
'implementation_status': 'supported',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_layout_parsing',
@@ -97,6 +109,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 3,
'label': 'Profile/模板路由',
'responsible_party': 'system',
'implementation_status': 'supported',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'reroute_document_profile',
@@ -108,6 +121,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 4,
'label': '订单字段抽取',
'responsible_party': 'worker',
'implementation_status': 'supported',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_order_extraction',
@@ -119,6 +133,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 5,
'label': '必填字段完整性',
'responsible_party': 'owner',
'implementation_status': 'supported',
'recoverable': True,
'default_next_actions': {
'blocked_manual': 'edit_order_fields',
@@ -129,6 +144,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 6,
'label': 'Reservation 格式和证据',
'responsible_party': 'owner',
'implementation_status': 'supported',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'revalidate_reservation',
@@ -140,6 +156,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 7,
'label': '客户身份识别',
'responsible_party': 'owner',
'implementation_status': 'supported',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_customer_resolution',
@@ -151,6 +168,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 8,
'label': '重复订单/修订判断',
'responsible_party': 'owner',
'implementation_status': 'supported',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_duplicate_detection',
@@ -162,6 +180,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 9,
'label': '字段冲突',
'responsible_party': 'owner',
'implementation_status': 'supported',
'recoverable': True,
'default_next_actions': {
'blocked_manual': 'resolve_field_conflicts',
@@ -172,6 +191,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 10,
'label': '库存源路由',
'responsible_party': 'owner',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_with_latest_rules',
@@ -183,6 +203,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 11,
'label': '订单冻结资格',
'responsible_party': 'system',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'recheck_freeze_readiness',
@@ -194,6 +215,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 12,
'label': 'ShippingNotice 创建',
'responsible_party': 'system',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_task_creation',
@@ -204,6 +226,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 13,
'label': '库存文件或快照准备',
'responsible_party': 'worker',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_inventory_preparation',
@@ -216,6 +239,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 14,
'label': '库存字段映射',
'responsible_party': 'owner',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_inventory_field_mapping',
@@ -227,6 +251,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 15,
'label': 'Reservation + 料号匹配',
'responsible_party': 'worker',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_inventory_matching',
@@ -238,6 +263,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 16,
'label': '库存满足性',
'responsible_party': 'owner',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'recheck_inventory_sufficiency',
@@ -249,6 +275,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 17,
'label': 'Excel 生成资格',
'responsible_party': 'system',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'recheck_excel_readiness',
@@ -259,6 +286,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 18,
'label': 'Excel Artifact',
'responsible_party': 'worker',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'regenerate_excel_artifact',
@@ -269,6 +297,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 19,
'label': '货代上传 RPA',
'responsible_party': 'worker',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'waiting_external': 'poll_freight_upload_rpa',
@@ -281,6 +310,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'sequence_no': 20,
'label': '人工上传交接',
'responsible_party': 'owner',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_manual': 'regenerate_manual_upload_todo',
@@ -322,6 +352,9 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
'retry_inventory_field_mapping',
'confirm_inventory_field_mapping',
'retry_inventory_matching',
'retry_inventory_from_preparation',
'retry_inventory_from_field_mapping',
'retry_inventory_from_matching',
'open_inventory_match_review',
'recheck_inventory_sufficiency',
'open_shortage_review',
@@ -332,27 +365,43 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
'regenerate_manual_upload_todo',
})
# 业务用户可在复核工作台 / Gate 卡片触发的动作(导航或本地 UX)。
# 技术重试(Worker/System)不得向业务用户投影为可点击写操作。
PROCESS_GATE_BUSINESS_USER_ACTION_CODES: Final[frozenset[str]] = frozenset({
'open_order_review',
'open_profile_review', # 仅导航至复核只读模板区,禁止人工选模板写路径
'edit_order_fields',
'edit_reservation',
'confirm_customer',
'retry_customer_resolution',
'adjudicate_duplicate',
'retry_duplicate_detection',
'resolve_field_conflicts',
'open_inventory_source_review',
'adopt_rule_suggestion',
'keep_manual_inventory_decision',
'upload_inventory_file',
'confirm_inventory_field_mapping',
'open_inventory_match_review',
'open_shortage_review',
'regenerate_manual_upload_todo',
})
# Gate 卡只展示服务端冻结合同中的动作码。每次点击仍受 Workspace API 的
# 当前 Gate 版本、执行归属和写权限校验;前端不自行决定目标节点或重试方式。
PROCESS_GATE_BUSINESS_USER_ACTION_CODES: Final[frozenset[str]] = PROCESS_GATE_ACTION_CODES
# 用户按钮展示合同:动作码仍是唯一执行标识,label_key/kind/dispatch 只描述业务语义。
# 任务级与明细行级不得再把所有动作降级为“重试”;前端只渲染本合同。
PROCESS_GATE_ACTION_PRESENTATION: Final[dict[str, dict[str, str]]] = {
code: {
'label_key': f'workspace.shippingNotice.processGate.actionCodes.{code}',
'kind': 'current_gate',
'dispatch': 'mutation',
}
for code in PROCESS_GATE_ACTION_CODES
}
for _code in {
'open_order_review', 'open_profile_review', 'edit_order_fields', 'edit_reservation',
'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts',
'open_inventory_source_review', 'open_inventory_match_review', 'open_shortage_review',
'upload_inventory_file', 'confirm_inventory_field_mapping',
}:
PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'navigation'
for _code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching'}:
PROCESS_GATE_ACTION_PRESENTATION[_code]['kind'] = 'recovery'
for _code in {'poll_inventory_preparation', 'poll_freight_upload_rpa'}:
PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'refresh'
def action_presentation(action_code: str | None, *, kind: str | None = None) -> dict[str, str] | None:
"""返回用户动作展示元数据;未知动作 fail-closed。"""
code = str(action_code or '').strip()
item = PROCESS_GATE_ACTION_PRESENTATION.get(code)
if item is None:
return None
payload = {'code': code, **item}
if kind:
payload['kind'] = kind
return payload
# 技术自动 Gate 的责任方;业务用户投影不得暴露其 POST 重试动作。
PROCESS_GATE_TECHNICAL_PARTIES: Final[frozenset[str]] = frozenset({
@@ -367,7 +416,7 @@ PROCESS_GATE_BUSINESS_PARTIES: Final[frozenset[str]] = frozenset({
def is_business_user_action(action_code: str | None) -> bool:
"""判断动作是否允许向业务用户投影为可处理入口。"""
"""判断服务端下发的 Gate 动作是否允许投影为可处理入口。"""
code = str(action_code or '').strip()
return bool(code) and code in PROCESS_GATE_BUSINESS_USER_ACTION_CODES
@@ -766,6 +815,7 @@ def assert_process_gate_contract_integrity() -> None:
assert set(sequences) == set(range(1, len(sequences) + 1)), 'process gate sequence_no must be contiguous'
for item in PROCESS_GATE_DEFINITIONS:
assert item['responsible_party'] in PROCESS_GATE_RESPONSIBLE_PARTIES
assert item.get('implementation_status') in PROCESS_GATE_IMPLEMENTATION_STATUSES
actions = item.get('default_next_actions') or {}
assert isinstance(actions, dict)
for status, action in actions.items():
@@ -139,6 +139,9 @@ def execute_queued_attempt(
snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {}
action = str(snapshot.get('action_code') or gate.next_action_code or '').strip()
payload = snapshot.get('payload') if isinstance(snapshot.get('payload'), dict) else {}
payload = {**payload, 'action_code': action, 'attempt_id': int(attempt.id)}
if attempt.recovery_plan_id:
payload.setdefault('recovery_plan_id', int(attempt.recovery_plan_id))
outcome = _dispatch_action(
execution=execution,
@@ -185,6 +188,9 @@ def _dispatch_action(
'poll_inventory_preparation': _handle_retry_inventory_preparation,
'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping,
'retry_inventory_matching': _handle_retry_inventory_matching,
'retry_inventory_from_preparation': _handle_retry_inventory_preparation,
'retry_inventory_from_field_mapping': _handle_retry_inventory_from_field_mapping,
'retry_inventory_from_matching': _handle_retry_inventory_from_matching,
'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency,
'recheck_excel_readiness': _handle_recheck_excel_readiness,
'regenerate_excel_artifact': _handle_regenerate_excel,
@@ -242,6 +248,9 @@ def _assert_action_belongs_to_gate(*, gate_code: str, action_code: str) -> None:
for value in (definition.get('default_next_actions') or {}).values()
if value
}
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
if recovery_plan_for_action(current_gate=gate_code, action_code=action_code) is not None:
return
if gate_code == 'inventory_source_routing':
allowed |= {
'adopt_rule_suggestion',
@@ -263,6 +272,10 @@ def _assert_action_belongs_to_gate(*, gate_code: str, action_code: str) -> None:
'confirm_inventory_field_mapping': {'inventory_field_mapping'},
'regenerate_manual_upload_todo': {'manual_upload_handoff'},
}
# 人工交接 Gate 仍允许用户主动重新发起 RPA;AUTO_UPLOAD 开关只控制
# 自动链路,不应阻断此显式恢复动作。
if action_code == 'retry_freight_upload_rpa' and gate_code == 'manual_upload_handoff':
return
if action_code in allowed:
return
if action_code in nav_owning and gate_code in nav_owning[action_code]:
@@ -325,7 +338,13 @@ def _manual_open(action: str, owning_gate: str) -> Callable[..., dict[str, Any]]
def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any]) -> dict[str, Any]:
"""构造履约 workflow 所需 payload。"""
"""
构造 Gate Worker 调用履约 workflow 所需的内部原子执行 payload。
核心逻辑:Gate Attempt 已经持有当前任务的编排边界,因此必须标记
``_orchestrator_internal_dispatch``,禁止库存/Excel workflow 再次绕回
``run_task_auto_progress``,把当前活动 Attempt 误判成“无待处理 Gate”。
"""
from app.models import ShippingNotice
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
@@ -335,6 +354,7 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any])
'task_id': str(task.task_no),
'source': 'process_gate',
'operator_id': payload.get('actor_user_id') or payload.get('user_id'),
'_orchestrator_internal_dispatch': True,
}
@@ -733,13 +753,38 @@ def _handle_retry_inventory_preparation(
"""
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.inventory_recovery_service import create_inventory_preparation_round
from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream
from app.services.shipping_notice.process_gate_bridge import (
inventory_preparation_reason_code,
sync_fulfillment_gates_from_task,
)
response = ensure_inventory(_task_payload(execution, payload))
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
recovery_plan_id = payload.get('recovery_plan_id')
preparation_round = None
if task is not None and payload.get('action_code') != 'poll_inventory_preparation':
if payload.get('action_code') in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping'}:
invalidate_inventory_downstream(
execution=execution,
action_code=str(payload.get('action_code')),
attempt_id=payload.get('attempt_id'),
actor_id=payload.get('actor_user_id'),
)
preparation_round = create_inventory_preparation_round(
task=task,
execution_id=int(execution.id),
recovery_plan_id=int(recovery_plan_id) if recovery_plan_id else None,
action_code=str(payload.get('action_code') or 'retry_inventory_preparation'),
operation_id=str(payload.get('operation_id') or '').strip() or None,
gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None,
)
response = ensure_inventory(_task_payload(execution, payload))
if preparation_round is not None:
from app.services.shipping_notice.inventory_recovery_service import sync_inventory_preparation_round
rpa_result = ((response.get('data') or {}).get('rpa') or {}) if isinstance(response, dict) else {}
sync_inventory_preparation_round(preparation_attempt=preparation_round, result=rpa_result)
prep_reason = (
inventory_preparation_reason_code(task)
if task is not None
@@ -781,12 +826,12 @@ def _handle_retry_inventory_field_mapping(
'output_snapshot': {'action_code': 'retry_inventory_field_mapping'},
}
inv_file = active_inventory_file_for_task(task)
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
mapped = bool(
inv_file is not None
and bool(getattr(inv_file, 'mapping_confirmed', False))
and (
isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0
)
and bool(active_inventory_lines_for_task(task))
)
apply_gate_outcome(
execution=execution,
@@ -822,27 +867,113 @@ def _handle_retry_inventory_field_mapping(
}
def _handle_retry_inventory_from_field_mapping(
*,
execution: ShippingProcessExecution,
gate: ShippingProcessGate,
payload: dict[str, Any],
) -> dict[str, Any]:
"""从库存字段映射恢复:失效匹配下游后只重跑映射,不创建库存准备轮次。"""
from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream
invalidate_inventory_downstream(
execution=execution,
action_code='retry_inventory_from_field_mapping',
attempt_id=payload.get('attempt_id'),
actor_id=payload.get('actor_user_id'),
)
mapping_outcome = _handle_retry_inventory_field_mapping(
execution=execution,
gate=gate,
payload=payload,
)
if mapping_outcome.get('outcome') != 'passed':
return mapping_outcome
return _handle_retry_inventory_matching(
execution=execution,
gate=gate,
payload=payload,
)
def _handle_retry_inventory_matching(
*,
execution: ShippingProcessExecution,
gate: ShippingProcessGate,
payload: dict[str, Any],
) -> dict[str, Any]:
"""重试库存匹配(仅 inventory_matching)。"""
"""
重试库存匹配;匹配已完成但仍有缺口时返回业务人工阻断。
核心逻辑:``match_inventory`` 的 ``needs_human`` 同时覆盖“匹配失败”和
“匹配成功但库存不足”。后者必须以库存满足性人工复核收口,不能误记为
技术失败,否则 RecoveryPlan 会反复失败且页面看不到有效推进。
"""
from app.models import ShippingNotice
from app.services.shipping_notice.fulfillment_workflow import match_inventory
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
response = match_inventory(_task_payload(execution, payload))
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
match_status = str(getattr(task, 'match_status', '') or '').strip().lower()
has_shortage = bool(getattr(task, 'shortage_json', None))
if str((response or {}).get('status') or '').strip().lower() == 'needs_human' and (
match_status in {'partial', 'unfulfillable'} or has_shortage
):
return {
'outcome': 'blocked_manual',
'blocking_reason_code': 'inventory_shortage_review_required',
'blocking_reason_json': {
'message': '库存重新匹配已完成,仍存在库存缺口。',
'match_status': match_status or None,
},
'recommendation_json': {
'navigation_action': 'open_shortage_review',
'dispatch_mode': 'navigate',
},
'effective_result_json': {
'findings': [],
'match_status': match_status or None,
'shortage': getattr(task, 'shortage_json', None),
},
'output_snapshot': {
'action_code': 'retry_inventory_matching',
'tool_status': 'needs_human',
'business_result': 'inventory_shortage',
},
}
outcome = _tool_outcome(
action_code='retry_inventory_matching',
response=response,
blocking_reason_code='inventory_match_failed',
invalidate_change_type=None,
)
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
return outcome
def _handle_retry_inventory_from_matching(
*,
execution: ShippingProcessExecution,
gate: ShippingProcessGate,
payload: dict[str, Any],
) -> dict[str, Any]:
"""缺口恢复:保留当前库存快照,仅重新执行 Reservation + 料号匹配。"""
from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream
invalidate_inventory_downstream(
execution=execution,
action_code='retry_inventory_from_matching',
attempt_id=payload.get('attempt_id'),
actor_id=payload.get('actor_user_id'),
)
return _handle_retry_inventory_matching(
execution=execution,
gate=gate,
payload=payload,
)
def _handle_recheck_inventory_sufficiency(
*,
execution: ShippingProcessExecution,
@@ -5,7 +5,7 @@ services/shipping_notice/process_gate_job_service.py
依赖:app.jobs.queue、JobType、ShippingProcessGateAttempt、process_gate_executor、
process_gate_service、fulfillment_audit。
逻辑:由 recovery_service 对异步动作调用 enqueue;Worker Handler 调用
claim_and_run_gate_attempt;重试/轮询使用 force_new 避免复用 running Job;
claim_and_run_gate_attempt;失败不自动重试,只有 waiting_external 轮询使用 force_new;
waiting_external 超时转入 blocked_manual;心跳 commit 后对其他 Worker 可见;
enqueue_process_gate_healthcheck_probe 供部署脚本验证 Worker 真实领取。
"""
@@ -55,6 +55,15 @@ def _heartbeat_seconds() -> int:
return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS', 15) or 15), 5)
def _technical_job_max_attempts() -> int:
"""返回同一 GateAttempt 的技术重试上限,默认 3 次。
只覆盖 Worker 领取、数据库或短暂外部故障等技术异常;业务失败仍由
Executor 完成当前 Attempt,并经 RecoveryPlan 创建新的业务 Attempt。
"""
return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_MAX_ATTEMPTS', 3) or 3), 1)
def enqueue_process_gate_healthcheck_probe(*, created_by_id: int | None = None) -> int:
"""
入队门禁健康检查探针 Job,供 deploy healthcheck 验证 Worker 真实领取。
@@ -91,13 +100,13 @@ def enqueue_gate_attempt_job(
为 Attempt 入队 Gate Job,并回写 attempt.job_id。
核心逻辑:默认仅对 queued 去重,绝不复用仍 running 的同 business_ref Job;
force_new 时使用带时间戳的 business_ref,保证重试/轮询一定新建可领取 Job。
force_new 时使用带时间戳的 business_ref,保证外部等待轮询一定新建可领取 Job。
Args:
attempt_id: Attempt 主键。
created_by_id: 可选创建人。
delay_seconds: 延迟入队秒数。
force_new: True 时强制新建 Job(重试/外部等待轮询)。
force_new: True 时强制新建 Job(仅用于外部等待轮询)。
Returns:
Job 主键。
@@ -117,7 +126,6 @@ def enqueue_gate_attempt_job(
if delay_seconds and int(delay_seconds) > 0:
scheduled_at = _utc_now() + timedelta(seconds=int(delay_seconds))
max_attempts = int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3)
# [STEP] force_new 用独立 business_ref,避免与刚结束/仍残留的 Job 去重冲突。
if force_new:
business_ref = f'attempt:{int(attempt.id)}:r{_utc_now().strftime("%Y%m%d%H%M%S")}:{uuid.uuid4().hex[:8]}'
@@ -125,12 +133,16 @@ def enqueue_gate_attempt_job(
business_ref = f'attempt:{int(attempt.id)}'
job_id = enqueue(
JobType.SHIPPING_PROCESS_GATE,
{'attempt_id': int(attempt.id)},
{
'attempt_id': int(attempt.id),
'recovery_plan_id': int(attempt.recovery_plan_id) if attempt.recovery_plan_id else None,
},
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
business_ref=business_ref,
created_by_id=created_by_id,
message='等待执行门禁恢复 Attempt',
max_attempts=max(max_attempts, 1),
# Job 仅对技术异常重试;业务失败由 Attempt/RecoveryPlan 显式建新轮次。
max_attempts=_technical_job_max_attempts(),
scheduled_at=scheduled_at,
# 仅匹配 queued:禁止复用仍 running 的旧 Job(重试场景)。
dedupe_statuses=('queued',),
@@ -19,16 +19,18 @@ from app.models import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingProcessRecoveryPlan,
)
from app.services.shipping_notice.error_explainability_contract import (
build_explainability_reason,
message_zh_for_reason,
)
from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_CODE_SET,
PROCESS_GATE_RECOVERABLE_STATUSES,
action_presentation,
get_process_gate_definition,
is_business_user_action,
primary_next_action_for_gate,
)
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
@@ -66,6 +68,20 @@ _ACTION_NAVIGATION_FOCUS: dict[str, str] = {
'upload_inventory_file': 'manual_upload',
}
def _projection_gate_definition(gate_code: str) -> dict[str, Any]:
"""只读取正式 20-Gate 契约;历史 Gate 由调用方走只读审计分支。"""
return get_process_gate_definition(gate_code)
def _projection_primary_next_action(*, gate_code: str, status: str) -> str | None:
"""按统一投影定义解析下一动作,兼容 P0-3 Gate。"""
definition = _projection_gate_definition(gate_code)
actions = definition.get('default_next_actions')
if not isinstance(actions, dict):
return None
value = actions.get(str(status or '').strip())
return str(value) if value else None
def serialize_gate_attempt(
attempt: ShippingProcessGateAttempt | None,
@@ -124,7 +140,11 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo
gate: 门禁行。
include_diagnostics: False 时仅保留用户可见 blocking Finding。
"""
definition = get_process_gate_definition(gate.gate_code)
legacy_readonly = str(gate.gate_code or '').strip() not in PROCESS_GATE_CODE_SET
definition = (
{'label': '历史 AutoProgress 记录', 'responsible_party': 'system', 'recoverable': False}
if legacy_readonly else _projection_gate_definition(gate.gate_code)
)
latest = None
if gate.latest_attempt_id:
latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id))
@@ -134,10 +154,28 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo
item for item in findings
if item.get('severity') == 'blocking' and item.get('user_visible', True)
]
allowed_actions = [str(gate.next_action_code)] if not legacy_readonly and (
gate.next_action_code and is_business_user_action(str(gate.next_action_code))
) else []
# 将 RecoveryPlan 目标绑定到当前 Gate 对象,避免 Case/UI 包装层只透传主动作时丢失恢复按钮。
from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS
recovery_targets = [] if legacy_readonly else [
{
'action_code': action_code,
'target_gate': plan.get('target_gate'),
'resume_after_gate': plan.get('resume_after_gate'),
'allowed_intermediate_gates': list(plan.get('allowed_intermediate_gates') or ()),
'invalidates': list(plan.get('invalidates') or ()),
'permission': plan.get('permission'),
}
for action_code, plan in (RECOVERY_PLAN_ACTIONS.get(str(gate.gate_code), {}) or {}).items()
]
return {
'gate_code': gate.gate_code,
'legacy_readonly': legacy_readonly,
'sequence_no': int(gate.sequence_no),
'label': definition.get('label'),
'implementation_status': definition.get('implementation_status'),
'status': gate.status,
'evaluation_version': int(gate.evaluation_version),
'input_fingerprint': gate.input_fingerprint,
@@ -150,12 +188,22 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo
'effective_result': gate.effective_result_json if include_diagnostics else None,
'findings': findings,
'next_action_code': gate.next_action_code,
'allowed_actions': allowed_actions,
'action_presentation': [item for code in allowed_actions if (item := action_presentation(code))],
'recovery_targets': recovery_targets,
'responsible_party': definition.get('responsible_party'),
'recoverable': bool(definition.get('recoverable')),
'passed_at': gate.passed_at.isoformat() if gate.passed_at else None,
'invalidated_at': gate.invalidated_at.isoformat() if gate.invalidated_at else None,
'latest_attempt': serialize_gate_attempt(latest) if include_diagnostics else (
{'attempt_no': latest.attempt_no, 'status': latest.status} if latest else None
{
'id': int(latest.id),
'attempt_no': latest.attempt_no,
'status': latest.status,
# 用户需要能区分“失败原因”和“系统失败”,但不能看到堆栈、路径或凭据。
'error_code': str(latest.error_code or '').strip() or None,
'error_summary': sanitize_gate_error_text(latest.error_summary, max_len=500),
} if latest else None
),
}
@@ -185,9 +233,29 @@ def serialize_process_execution(
(item for item in serialized if item.get('gate_code') == execution.current_gate_code),
None,
)
legacy_readonly = any(item.get('legacy_readonly') for item in serialized)
recovery_targets: list[dict[str, Any]] = []
if execution.current_gate_code and not legacy_readonly:
# RecoveryPlan 合同是服务端唯一动作来源;Projection 只读输出,客户端不能改写 target Gate。
from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS
for action_code, definition in (RECOVERY_PLAN_ACTIONS.get(execution.current_gate_code, {}) or {}).items():
recovery_targets.append({
'action_code': action_code,
'target_gate': definition.get('target_gate'),
'resume_after_gate': definition.get('resume_after_gate'),
'allowed_intermediate_gates': list(definition.get('allowed_intermediate_gates') or ()),
'invalidates': list(definition.get('invalidates') or ()),
'permission': definition.get('permission'),
})
active_recovery_plans = ShippingProcessRecoveryPlan.query.filter(
ShippingProcessRecoveryPlan.execution_id == int(execution.id),
ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}),
).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all()
return {
'execution_no': execution.execution_no,
'status': execution.status,
'status': 'legacy_readonly' if legacy_readonly else execution.status,
'legacy_readonly': legacy_readonly,
'current_gate_code': execution.current_gate_code,
'last_passed_gate_code': execution.last_passed_gate_code,
'primary_next_action_code': execution.primary_next_action_code,
@@ -199,6 +267,19 @@ def serialize_process_execution(
'review_case_id': int(execution.review_case_id) if execution.review_case_id else None,
'task_id': int(execution.task_id) if execution.task_id else None,
'current_gate': current,
'recovery_targets': recovery_targets,
'active_recovery_plans': [
{
'plan_no': plan.plan_no,
'action_code': plan.action_code,
'current_gate': plan.current_gate,
'target_gate': plan.target_gate,
'resume_after_gate': plan.resume_after_gate,
'status': plan.status,
'idempotency_key': plan.idempotency_key if include_diagnostics else None,
}
for plan in active_recovery_plans
],
'gates': serialized,
'updated_at': execution.updated_at.isoformat() if execution.updated_at else None,
}
@@ -278,6 +359,45 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
current_blocking_gate、reason、next_action、diagnostic_hint、technical_auto_only。
"""
full = serialize_process_execution(execution, include_diagnostics=False)
# 完成态的正式 Execution 会清空 current_gate_code;空值表示没有待处理 Gate,
# 不能被误判为已下线的 APX 历史执行。只有存在实际 Gate 编号且不在正式契约内时,
# 才进入 legacy_readonly 兼容投影。
current_gate_code = str(getattr(execution, 'current_gate_code', '') or '').strip()
legacy_readonly = bool(full.get('legacy_readonly')) or (
bool(current_gate_code) and current_gate_code not in PROCESS_GATE_CODE_SET
)
if legacy_readonly:
refs = _execution_navigation_refs(execution)
return {
'execution_no': full.get('execution_no'),
'status': 'legacy_readonly',
'legacy_readonly': True,
'execution_status': None,
'current_gate': full.get('current_gate'),
'current_blocking_gate': None,
'recovery_targets': [],
'active_recovery_plans': [],
'blocking_reason_code': 'shipping_apx_runtime_disabled',
'blocking_message': '历史自动推进记录仅供审计查看',
'failure_detail': None,
'explainability': None,
'next_action_code': None,
'primary_action': None,
'allowed_actions': [],
'action_presentation': [],
'view_actions': [{'code': 'view_audit', 'kind': 'view', 'dispatch': 'navigation'}],
'technical_auto_only': True,
'owner_type': 'system',
'responsible_party': 'system',
'diagnostic_hint': None,
**refs,
'navigation': None,
'gates_track': [
{'gate_code': item.get('gate_code'), 'label': item.get('label'),
'status': item.get('status'), 'sequence_no': item.get('sequence_no')}
for item in (full.get('gates') or [])
],
}
current = full.get('current_gate')
blocking = None
if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | {
@@ -311,20 +431,94 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
break
reason_code = (blocking or {}).get('blocking_reason_code')
next_action = full.get('primary_next_action_code') or (
primary_next_action_for_gate(
_projection_primary_next_action(
gate_code=str((blocking or {}).get('gate_code') or ''),
status=str((blocking or {}).get('status') or ''),
) if blocking else None
)
# [STEP] 技术重试动作不对业务用户投影;仅保留复核工作台业务动作白名单。
# [STEP] 兼容历史 Gate 行:RPA 失败曾被旧契约错误写成
# regenerate_manual_upload_todo;当前 Gate + 原因码才是履约真相,
# 统一纠正为用户可主动执行的 RPA 重试。AUTO_UPLOAD 只控制自动触发,
# 不参与手动动作投影。
blocking_gate_code = str((blocking or {}).get('gate_code') or '').strip().lower()
normalized_reason = str(reason_code or '').strip().lower()
if (
blocking_gate_code == 'freight_upload_rpa'
and normalized_reason in {
'upload_rpa_failed',
'upload_rpa_login_failed',
'upload_platform_rejected',
}
):
next_action = 'retry_freight_upload_rpa'
elif (
blocking_gate_code == 'manual_upload_handoff'
and normalized_reason in {'manual_upload_pending', 'upload_result_unknown'}
):
# 人工交接仍保留人工登记入口(Footer),同时在 Gate 卡提供显式 RPA 重试。
next_action = 'retry_freight_upload_rpa'
# [STEP] 所有冻结 Gate 动作均可投影到工作台;是否可执行由页面 canHandle
# 与 Workspace API 的权限/版本校验共同决定,禁止前端自行派生动作。
technical_auto_only = False
if next_action and not is_business_user_action(str(next_action)):
# 技术责任方的 retry_* 只作为系统执行动作,不能直接充当业务用户主按钮;
# RecoveryPlan 仍可在下方投影为经过权限校验的恢复入口。
if (
next_action
and (
not is_business_user_action(str(next_action))
or (
str(full.get('responsible_party') or '').strip().lower() in {'system', 'worker'}
and str(next_action).startswith('retry_')
)
)
):
next_action = None
technical_auto_only = bool(blocking)
# [STEP] 正式 OT 后的库存阻断仍需给业务用户提供精确入口:技术主动作
# (retry_inventory_*)不直接暴露,但 RecoveryPlan 存在时必须保留当前
# Gate 的复核入口,否则 apply_post_ot_gate_rules 会把整个阻断误判为系统态,
# 前端也就不会挂载 ProcessGateRecoveryCard。
if blocking and not next_action:
gate_code = str(blocking.get('gate_code') or '').strip().lower()
recovery_targets = full.get('recovery_targets') or []
if recovery_targets and gate_code == 'inventory_matching':
next_action = 'open_inventory_match_review'
technical_auto_only = False
elif recovery_targets and gate_code == 'inventory_sufficiency':
next_action = 'open_shortage_review'
technical_auto_only = False
# 正式 OT 后仍需允许业务用户恢复履约链路中的技术失败:
# 库存准备/匹配以及货代上传 RPA 的动作码由 Gate 合同固定,
# 不把其他 system/worker 节点泛化为可人工操作。
if not next_action and gate_code in {
'inventory_preparation',
'inventory_matching',
'freight_upload_rpa',
}:
candidate = _projection_primary_next_action(
gate_code=gate_code,
status=str(blocking.get('status') or ''),
)
if candidate and is_business_user_action(candidate):
next_action = candidate
technical_auto_only = False
# 无当前阻断时禁止残留 confirm_customer,避免「客户已确认」仍显示为优先处理。
if not blocking and str(next_action or '').strip() == 'confirm_customer':
next_action = None
allowed_actions: list[str] = []
action_items: list[dict[str, str]] = []
if blocking:
if next_action and is_business_user_action(str(next_action)):
allowed_actions.append(str(next_action))
for target in full.get('recovery_targets') or []:
code = str(target.get('action_code') or '').strip()
if code and code not in allowed_actions and is_business_user_action(code):
allowed_actions.append(code)
action_items = [item for code in allowed_actions if (item := action_presentation(code))]
# [STEP] 统一可解释性投影:文案/责任方/下一步与 error_explainability_contract 同源;
# request_id 仅真实请求号;execution_no 放入 details 供 Worker 路径关联。
explainability = None
@@ -350,11 +544,22 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
'execution_no': full.get('execution_no'),
'status': full.get('status'),
'execution_status': execution_status,
# 当前执行 Gate 与人工阻断分开投影:queued/running 不生成待办,但阶段游标必须
# 仍来自正式 Gate,避免旧 OT stage 把页面停留在库存匹配。
'current_gate': current,
'current_blocking_gate': blocking,
# 客户端只消费服务端已校验的恢复目标,不自行推导跨 Gate 路径。
'recovery_targets': full.get('recovery_targets') or [],
'active_recovery_plans': full.get('active_recovery_plans') or [],
'blocking_reason_code': reason_code,
'blocking_message': _user_facing_blocking_message(reason_code),
'failure_detail': _user_facing_failure_detail(blocking),
'explainability': explainability,
'next_action_code': next_action,
'primary_action': action_presentation(next_action),
'allowed_actions': allowed_actions,
'action_presentation': action_items,
'view_actions': [{'code': 'view_audit', 'kind': 'view', 'dispatch': 'navigation'}],
'technical_auto_only': technical_auto_only,
'owner_type': (
'system' if technical_auto_only or execution_status
@@ -409,6 +614,34 @@ def _user_facing_blocking_reason_payload(gate: ShippingProcessGate) -> dict[str,
return payload
def _user_facing_failure_detail(blocking: dict[str, Any] | None) -> str | None:
"""
提取当前 Gate 最近一次失败的脱敏业务详情,供用户排查。
优先级:Attempt.error_summary → blocking_reason.message → Finding.details.message。
仅返回已经经过门禁错误脱敏器处理的短文本;没有事实时返回 None,避免伪造原因。
"""
if not isinstance(blocking, dict):
return None
latest = blocking.get('latest_attempt')
candidates: list[Any] = []
if isinstance(latest, dict):
candidates.extend([latest.get('error_summary'), latest.get('error_code')])
reason = blocking.get('blocking_reason')
if isinstance(reason, dict):
candidates.extend([reason.get('message'), reason.get('failure_detail'), reason.get('error_summary')])
for finding in blocking.get('findings') or []:
if not isinstance(finding, dict):
continue
details = finding.get('details') if isinstance(finding.get('details'), dict) else {}
candidates.extend([details.get('failure_detail'), details.get('message'), details.get('error_summary')])
for value in candidates:
text = sanitize_gate_error_text(value, max_len=500)
if text:
return text
return None
def _current_request_id() -> str | None:
"""
读取当前 HTTP 请求的 request_id;无请求上下文时返回 None。
@@ -574,6 +807,12 @@ def _user_facing_blocking_message(reason_code: str | None) -> str | None:
'run_failed': '识别运行失败',
'run_cancelled': '识别运行已取消',
'pending_orders_present': '仍有待处理订单',
'inventory_candidates_required': '当前没有库存候选集,无法开始库存匹配;请先重新获取库存',
'inventory_candidates_frozen_required': '库存候选集尚未确认,请先完成库存源确认',
'inventory_snapshot_prepare_failed': '库存快照准备失败,请检查库存获取结果后重试',
'inventory_snapshots_pending': '库存快照仍在准备中,请稍后刷新进度',
'inventory_match_not_ready': '库存尚未满足匹配条件,请先完成库存准备',
'projection_data_inconsistent': '处理进度数据不一致,请刷新页面后重试;若仍失败请联系管理员',
}
return legacy.get(code)
@@ -15,7 +15,7 @@ from __future__ import annotations
from typing import Any
from app.core.errors import NotFoundError, ValidationError
from app.models import ShippingProcessExecution, ShippingProcessGate
from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_ACTION_CODES,
@@ -29,6 +29,8 @@ from app.services.shipping_notice.process_gate_executor import (
execute_queued_attempt,
)
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
from app.services.shipping_notice.recovery_plan_service import bind_recovery_attempt, create_recovery_plan
def _chat_process_gate_event_type(*, action_code: str, trigger_type: str) -> str:
@@ -138,13 +140,6 @@ def request_gate_action(
action = str(action_code or '').strip()
if action not in PROCESS_GATE_ACTION_CODES:
raise ValidationError('Unknown process gate action', code='SHIPPING.PROCESS_GATE_ACTION_INVALID')
# [STEP] 业务用户禁止触发技术 Gate 写动作;前端隐藏不是安全边界。
if str(actor_type or '') == 'user' and not is_business_user_action(action):
raise ValidationError(
'Technical gate actions are not allowed for business users',
code='SHIPPING.PROCESS_GATE_TECHNICAL_ACTION_FORBIDDEN',
details={'action_code': action},
)
forbidden = {'start_stage', 'target_status', 'worker_name', 'tool_name', 'next_node', 'sql'}
body = dict(payload) if isinstance(payload, dict) else {}
if forbidden.intersection(set(body.keys())):
@@ -159,6 +154,13 @@ def request_gate_action(
body.setdefault('idempotency_key', str(idempotency_key or ''))
execution = get_execution_by_no(execution_no)
execution_status = str(execution.status or '').strip().lower()
if execution_status in {'completed', 'cancelled'}:
raise ValidationError(
'Process execution is terminal; write actions are not allowed',
code='SHIPPING.PROCESS_EXECUTION_TERMINAL',
details={'execution_no': execution.execution_no, 'status': execution_status},
)
gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id),
gate_code=str(gate_code or '').strip(),
@@ -166,6 +168,43 @@ def request_gate_action(
if gate is None:
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
current_gate = str(execution.current_gate_code or '').strip()
replay_attempt = ShippingProcessGateAttempt.query.filter_by(
idempotency_key=str(idempotency_key or '').strip(),
).first()
# 跨阶段恢复目标先做 Gate 归属校验;错误 Gate 必须返回稳定的
# RECOVERY_TARGET_INVALID,而不是被普通技术动作权限错误遮蔽。
recovery_definition = recovery_plan_for_action(current_gate=gate.gate_code, action_code=action)
if action.startswith('retry_inventory_from_') and recovery_definition is None:
raise ValidationError(
'Recovery target is not allowed for current gate',
code='SHIPPING.RECOVERY_TARGET_INVALID',
details={'current_gate': gate.gate_code, 'action_code': action},
)
# [GLOBAL ACTION GUARD] 所有 20 Gate 共用同一入口:请求 Gate 必须是 Execution 当前 Gate。
# 跨阶段动作已在前面完成目标归属判定,避免错误地把非法恢复目标报告为状态漂移。
if replay_attempt is None and (not current_gate or current_gate != str(gate.gate_code or '').strip()):
raise ValidationError(
'Action must target the current process gate',
code='SHIPPING.PROCESS_GATE_NOT_CURRENT',
details={
'execution_no': execution.execution_no,
'current_gate': current_gate or None,
'requested_gate': gate.gate_code,
'action_code': action,
},
)
# [STEP] 业务用户禁止触发技术 Gate 写动作;前端隐藏不是安全边界。
# 必须在跨阶段目标归属之后判断,保证错误 Gate 返回 RECOVERY_TARGET_INVALID。
if str(actor_type or '') == 'user' and not is_business_user_action(action):
raise ValidationError(
'Technical gate actions are not allowed for business users',
code='SHIPPING.PROCESS_GATE_TECHNICAL_ACTION_FORBIDDEN',
details={'action_code': action},
)
definition = get_process_gate_definition(gate.gate_code)
if (
str(actor_type or '') == 'user'
@@ -181,6 +220,15 @@ def request_gate_action(
primary = gate.next_action_code or primary_next_action_for_gate(
gate_code=gate.gate_code, status=gate.status,
)
# [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA
# 重试,但数据库 Gate 行可能仍保留 regenerate_manual_upload_todo。
# 这里必须与用户投影使用同一 Gate/原因事实,否则点击必然被主动作校验拒绝。
if (
gate.gate_code == 'manual_upload_handoff'
and gate.blocking_reason_code in {'manual_upload_pending', 'upload_result_unknown'}
and action == 'retry_freight_upload_rpa'
):
primary = action
# [STEP] 附属动作仅允许挂在 inventory_source_routing,禁止跨门禁执行库存决定。
allowed_side: set[str] = set()
if gate.gate_code == 'inventory_source_routing':
@@ -188,7 +236,7 @@ def request_gate_action(
'adopt_rule_suggestion',
'keep_manual_inventory_decision',
}
if primary and action != primary and action not in allowed_side:
if primary and action != primary and action not in allowed_side and recovery_definition is None:
raise ValidationError(
'Action is not the primary recovery action for this gate',
code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED',
@@ -198,6 +246,20 @@ def request_gate_action(
trigger_type = (
'user_retry' if action.startswith('retry') or action.startswith('re') else 'user_manual'
)
recovery_plan = None
if recovery_definition is not None:
recovery_plan, _ = create_recovery_plan(
execution=execution,
gate=gate,
action_code=action,
idempotency_key=idempotency_key,
actor_type=actor_type,
actor_id=actor_id,
operation_id=str(body.get('operation_id') or '').strip() or None,
)
body['recovery_plan_id'] = int(recovery_plan.id)
body['recovery_action_code'] = action
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code=gate.gate_code,
@@ -209,6 +271,9 @@ def request_gate_action(
input_snapshot={'action_code': action, 'payload': body},
)
if recovery_definition is not None:
bind_recovery_attempt(plan=recovery_plan, attempt_id=int(attempt.id))
# 幂等回放且已终态:直接返回,不二次执行;也不重复写 chat_* 审计。
if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}:
db_gate = ShippingProcessGate.query.get(int(attempt.gate_id))
@@ -226,6 +291,7 @@ def request_gate_action(
},
'gate_status': db_gate.status if db_gate else gate.status,
'gate_evaluation_version': int(db_gate.evaluation_version) if db_gate else int(gate.evaluation_version),
'recovery_plan_id': int(recovery_plan.id) if recovery_plan is not None else None,
}
# [STEP] 对话工作台语义审计:与 process_gate_recovery_requested 并存,供审计中心 chat 分组筛选。
@@ -260,6 +326,7 @@ def request_gate_action(
'idempotency_key': attempt.idempotency_key,
},
'gate_evaluation_version': int(gate.evaluation_version),
'recovery_plan_id': int(recovery_plan.id) if recovery_plan is not None else None,
}
updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery')
@@ -278,4 +345,5 @@ def request_gate_action(
'gate_status': updated_gate.status,
'gate_evaluation_version': int(updated_gate.evaluation_version),
'next_action_code': updated_gate.next_action_code,
'recovery_plan_id': int(recovery_plan.id) if recovery_plan is not None else None,
}
@@ -23,9 +23,11 @@ from app.models import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingProcessRecoveryPlan,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_CODE_SET,
PROCESS_GATE_DEFINITIONS,
PROCESS_GATE_RECOVERABLE_STATUSES,
get_process_gate_definition,
@@ -293,6 +295,15 @@ def ensure_execution_for_workflow_version(
.order_by(ShippingProcessExecution.id.desc())
.first()
)
# APX 六 Gate 与正式 20-Gate 不能共用同一 Execution。历史数据可能仍按
# task_id 被查到;此时必须新建正式链,禁止把 20-Gate 行写进 APX sequence。
if existing is not None:
existing_codes = {
str(row.gate_code or '').strip()
for row in ShippingProcessGate.query.filter_by(execution_id=int(existing.id)).all()
}
if existing_codes and not existing_codes.issubset(PROCESS_GATE_CODE_SET):
existing = None
if existing is not None:
if review_case_id and existing.review_case_id is None:
existing.review_case_id = int(review_case_id)
@@ -635,11 +646,28 @@ def complete_gate_attempt(
attempt.error_code = str(error_code)[:64] if error_code else None
# [STEP] 持久化前脱敏,避免 URL/路径/连接信息进入 Attempt 与后续投影。
attempt.error_summary = sanitize_gate_error_text(error_summary, max_len=2000)
# waiting_external 表示 Attempt 本身成功完成并进入外部等待,不应记为 failed。
attempt.status = 'succeeded' if outcome in {'passed', 'waiting_external'} else 'failed'
# passed / waiting_external / blocked_manual 均表示执行器已成功得到业务结果;
# blocked_manual 只是 Gate 仍需人工复核(例如库存 14、缺口 16),不能误记为技术失败。
attempt.status = 'succeeded' if outcome in {
'passed', 'waiting_external', 'blocked_manual',
} else 'failed'
attempt.lease_token = None
attempt.lease_expires_at = None
if attempt.recovery_plan_id:
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
plan = db.session.get(ShippingProcessRecoveryPlan, int(attempt.recovery_plan_id))
if plan is not None:
complete_recovery_plan_for_attempt(
plan=plan,
outcome=outcome,
now=now,
error_code=error_code,
error_summary=error_summary,
business_result_code=blocking_reason_code,
)
gate.status = outcome
gate.blocking_reason_code = str(blocking_reason_code)[:64] if blocking_reason_code else None
reason_payload = dict(blocking_reason_json or {}) or None
@@ -667,13 +695,9 @@ def complete_gate_attempt(
# 过去只有复核确认建单链路会入队 auto_progress,导致其余门禁恢复后
# Gate 已 passed 但任务仍停在旧节点。这里使用同一幂等任务队列入口,
# 与事务一起提交,避免恢复动作提交前 Worker 读到不完整状态。
# 业务投影(trigger_type=auto)本身属于 auto_progress 当前事务,避免递归排队;
# 恢复动作(user/system_requeue)通过统一队列续跑后续节点。
if (
outcome == 'passed'
and execution.task_id
and str(attempt.trigger_type or '').strip() != 'auto'
):
# 无论由自动或恢复 Attempt 通过,都统一委托 AutoProgress 找到下一 Gate。
# 它只入队一个 Attempt/Job;同一事务内的状态尚未提交,Worker 不会读到半成品。
if outcome == 'passed' and execution.task_id:
_enqueue_auto_progress_after_gate_pass(execution=execution, gate=gate)
invalidated: list[str] = []
@@ -723,39 +747,41 @@ def _enqueue_auto_progress_after_gate_pass(
execution: ShippingProcessExecution,
gate: ShippingProcessGate,
) -> None:
"""门禁通过后为绑定任务排入幂等 auto_progress Job。
"""门禁通过后为绑定任务提交下一 Gate 的唯一 AutoProgress Attempt/Job。
核心逻辑:复用 shipping_notice_run 的业务去重与执行模式;不直接执行编排,
让当前恢复事务先提交后再由 Worker/同步队列继续后续门禁。已完成或仍需人工的
任务会由 auto_progress 自身的 checkpoint 逻辑安全早停。
核心逻辑:不再写 legacy shipping_notice_run;统一由 submit_auto_progress 创建
ProcessGate Attempt/Job。已完成或仍需人工的任务会安全早停。
"""
try:
from app.models import ShippingNotice
task = db.session.get(ShippingNotice, int(execution.task_id))
task_no = str(getattr(task, 'task_no', '') or '').strip().upper()
if not task_no:
return
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
ok, result = enqueue_shipping_notice_job(
task_no=task_no,
created_by_id=None,
commit=False,
# 直接为下一 Gate 创建 Attempt/ProcessGate Job,避免重新进入
# submit_auto_progress→sync_fulfillment_gates 的递归路径。
_refresh_execution_pointers(execution)
next_gate = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id), gate_code=str(execution.current_gate_code or ''))
.with_for_update()
.first()
)
if not ok:
record_fulfillment_audit(
event_type='task_auto_progress_enqueue_failed',
aggregate_type='shipping_task',
aggregate_id=task_no,
action='auto_progress',
actor_type='system',
actor_id=None,
task_no=task_no,
result='failure',
reason_code='auto_progress_enqueue_failed',
error_code='SHIPPING.AUTO_PROGRESS_ENQUEUE_FAILED',
after={'gate_code': gate.gate_code, 'message': str(result)[:500]},
source='process_gate',
)
if next_gate is None or not next_gate.next_action_code:
return
definition = get_process_gate_definition(next_gate.gate_code)
if str(definition.get('responsible_party') or '') not in {'system', 'worker'}:
return
attempt = queue_gate_attempt(
execution_no=str(execution.execution_no),
gate_code=next_gate.gate_code,
trigger_type='auto',
actor_type='system',
actor_id=None,
idempotency_key=(
f'shipping-auto-progress:{execution.task_id}:{execution.id}:'
f'{next_gate.id}:{next_gate.evaluation_version}'
),
expected_gate_version=int(next_gate.evaluation_version),
input_snapshot={'action_code': next_gate.next_action_code, 'payload': {'trigger': 'gate_attempt_passed'}},
)
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=None)
except Exception as exc: # noqa: BLE001 — 门禁结果不可被排程异常覆盖
record_fulfillment_audit(
event_type='task_auto_progress_enqueue_failed',
@@ -870,6 +896,23 @@ def sync_gate_from_business_result(
key = str(idempotency_key or '').strip() or f'sync:{execution_no}:{gate_code}:{uuid.uuid4().hex}'
execution = _locked_execution(execution_no)
gate = _locked_gate(execution=execution, gate_code=gate_code)
# [STEP] Gate Worker 执行器可能在当前 Attempt 内同步最新业务事实。
# 同一 Gate 已有 queued/running Attempt 时,事实同步必须由外层 Attempt
# 统一 complete,禁止递归创建第二个 Attempt,否则会误报 PROCESS_GATE_BUSY,
# 并最终把可恢复业务失败收口为 failed_terminal。
active_attempt = (
ShippingProcessGateAttempt.query
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
)
.order_by(ShippingProcessGateAttempt.attempt_no.desc())
.first()
)
if active_attempt is not None:
return gate
if allow_repass and gate.status == 'passed':
gate.status = 'invalidated'
gate.invalidated_at = _utc_now()
@@ -92,6 +92,9 @@ _ACTION_CODE_ALIASES: dict[str, str] = {
'rematch': 'open_inventory_match_review',
'match_inventory': 'open_inventory_match_review',
'generate_excel': 'regenerate_excel',
# 正式 Process Gate 动作投影到旧工作台的同一业务意图;真实写动作仍由
# Gate API 使用原始 action_code 校验,legacy projection 只负责展示语义。
'regenerate_excel_artifact': 'regenerate_excel',
'freeze_order': 'edit_formal_task',
}
@@ -453,6 +456,45 @@ def reconcile_processing_projection_facts(
stage_idx = shipping_processing_stage_index(stage)
waiting_idx = shipping_processing_stage_index('waiting_review') or 8
# 关键事实无法读取时 fail-closed:不能继续沿用旧 checkpoint 或写动作。
if payload.get('projection_data_inconsistent'):
payload['status'] = 'waiting_human'
payload['stage'] = 'waiting_review'
payload['current_gate'] = None
payload['primary_action'] = None
payload['available_actions'] = []
payload['retryable'] = False
payload['blocking_reason'] = {
'code': 'projection_data_inconsistent',
'message': '处理状态暂时无法确认,请刷新后重试',
}
payload['stage_nodes'] = build_stage_nodes(
stage='waiting_review', status='waiting_human', source_type=source_type,
invalidated_from_stage=invalidated_from_stage,
)
return payload
# [BE-08] 正式 Gate 是后半段唯一进度真相。OT 的旧 stage/status 可能仍停在
# inventory_matching/running,但 Gate 已经进入 Excel 或上传节点;先把统一
# 投影游标对齐 Gate,禁止旧 primary_action 继续生成 match_inventory。
gate_stage = {
'excel_readiness': 'excel_generating',
'artifact_generation': 'excel_generating',
'freight_upload_rpa': 'freight_uploading',
'manual_upload_handoff': 'freight_uploading',
}.get(str((gate or {}).get('gate_code') or '').strip().lower())
if gate_stage:
stage = gate_stage
payload['stage_label_key'] = gate_stage
gate_status = str((gate or {}).get('status') or '').strip().lower()
if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}:
status = 'blocked'
elif gate_status == 'waiting_external':
status = 'automating'
elif gate_status in {'queued', 'running'}:
status = 'automating'
stage_idx = shipping_processing_stage_index(stage)
# [BE-03] Extraction Run 完成误标为全流程 completed:早期 stage 时回退 status。
if status == 'completed' and stage and stage != 'completed':
if stage_idx is not None and stage_idx <= waiting_idx:
@@ -597,6 +639,31 @@ def apply_user_projection_fields(
payload['legacy_current_gate'] = payload.get('current_gate')
old_status = str(payload.get('status') or '').strip().lower()
old_stage = str(payload.get('stage') or '').strip().lower()
source_type = str(payload.get('source_type') or '').strip().lower() or None
old_gate = payload.get('current_gate') if isinstance(payload.get('current_gate'), dict) else None
# 关键事实读取失败时立即 fail-closed;不能继续执行后续 legacy/retry 推导,
# 否则后续逻辑可能重新生成可执行主动作覆盖诊断态。
if payload.get('projection_data_inconsistent'):
payload['user_status'] = 'waiting_human'
payload['user_stage'] = 'waiting_review'
payload['user_current_gate_code'] = None
payload['blocking_reason'] = {
'code': 'projection_data_inconsistent',
'i18n_key': 'workspace.shippingNotice.processGate.reasons.projection_data_inconsistent',
'details': {},
}
payload['retryable'] = False
payload['primary_action'] = None
payload['available_actions'] = []
payload['current_gate'] = None
payload['stage'] = 'waiting_review'
payload['status'] = 'waiting_human'
payload['stage_nodes'] = build_stage_nodes(
stage='waiting_review', status='waiting_human', source_type=source_type,
invalidated_from_stage=None,
)
return payload
# ===== [STEP 2] 读取 notice / order_task 原始字段(保持不变) =====
pending_reason: str | None = None
@@ -650,6 +717,13 @@ def apply_user_projection_fields(
)
def _compute_user_status() -> str:
# [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision
# 只描述任务调度,不能覆盖正式 Gate 已到达的 Excel/上传阻断。
gate_status = str((old_gate or {}).get('status') or '').strip().lower()
if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}:
return 'retryable'
if gate_status == 'blocked_manual':
return 'waiting_human'
# 1) 终态短路:old_status completed/cancelled/failed
if old_status == 'completed':
return 'completed'
@@ -706,7 +780,6 @@ def apply_user_projection_fields(
user_stage = 'document_parsing'
# ===== [不变] user_current_gate_code 计算(保持不动) =====
old_gate = payload.get('current_gate') if isinstance(payload.get('current_gate'), dict) else None
user_current_gate_code: str | None = None
if isinstance(old_gate, dict):
user_current_gate_code = str(old_gate.get('code') or old_gate.get('gate_code') or '').strip() or None
@@ -734,6 +807,12 @@ def apply_user_projection_fields(
'inventory_source_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_source_conflicted',
'inventory_source_unresolved': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
'inventory_multi_file_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_multi_file_conflict',
'inventory_candidates_required': 'workspace.shippingNotice.processGate.reasons.inventory_candidates_required',
'inventory_candidates_frozen_required': 'workspace.shippingNotice.processGate.reasons.inventory_candidates_frozen_required',
'inventory_snapshot_prepare_failed': 'workspace.shippingNotice.processGate.reasons.inventory_snapshot_prepare_failed',
'inventory_snapshots_pending': 'workspace.shippingNotice.processGate.reasons.inventory_snapshots_pending',
'inventory_match_not_ready': 'workspace.shippingNotice.processGate.reasons.inventory_match_not_ready',
'projection_data_inconsistent': 'workspace.shippingNotice.processGate.reasons.projection_data_inconsistent',
'order_review_required': 'workspace.shippingNotice.processGate.reasons.freeze_not_ready',
'duplicate_decision_required': 'chat.shippingProcessing.reasonCode.duplicateDecisionRequired',
'SHIPPING.NOTICE_EXACT_DUPLICATE': 'chat.shippingProcessing.reasonCode.exactDuplicateNotice',
@@ -786,6 +865,17 @@ def apply_user_projection_fields(
'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code],
'details': {},
}
gate_reason = str((old_gate or {}).get('blocking_reason_code') or '').strip()
if gate_reason and gate_reason in _REASON_TO_I18N_KEY:
return {
'code': gate_reason,
'i18n_key': _REASON_TO_I18N_KEY[gate_reason],
'details': dict(
(old_gate or {}).get('effective_result')
or (old_gate or {}).get('details')
or {}
),
}
return _legacy_waiting_human_blocking_reason()
# 3) retryable
if user_status == 'retryable':
@@ -824,6 +914,7 @@ def apply_user_projection_fields(
'open_inventory_match_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_match_review',
'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review',
'retry_freight_upload_rpa': 'workspace.shippingNotice.processGate.actionCodes.retry_freight_upload_rpa',
'regenerate_excel': 'workspace.shippingNotice.processGate.actionCodes.regenerate_excel_artifact',
'adjudicate_duplicate': 'workspace.shippingNotice.processGate.actionCodes.adjudicate_duplicate',
'reconcile_and_progress': 'workspace.shippingNotice.processGate.actionCodes.reconcile_and_progress',
'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review',
@@ -862,6 +953,20 @@ def apply_user_projection_fields(
return None
def _compute_primary_action() -> dict[str, Any] | None:
# [BE-10] Gate action 是当前阶段唯一主动作来源;旧 stage 的
# match_inventory/regenerate_excel 仅作兼容回退。
gate_action = str((old_gate or {}).get('next_action_code') or '').strip()
gate_action_alias = {
'regenerate_excel_artifact': 'regenerate_excel',
}.get(gate_action, gate_action)
if gate_action_alias in SHIPPING_PROCESSING_ACTION_INTENTS and user_status in {
'retryable', 'waiting_human', 'running',
}:
return {
'code': gate_action_alias,
'i18n_key': _resolve_action_i18n_key(gate_action_alias),
'parameters': {},
}
# 1) blocking_reason 非 None
if blocking_reason is not None:
bcode = str(blocking_reason.get('code') or '').strip()
@@ -903,6 +1008,7 @@ def apply_user_projection_fields(
code = 'open_order_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1h. available_actions 含 reconcile_and_progress → 统一对账恢复入口兜底
available_actions = payload.get('available_actions')
if isinstance(available_actions, list) and 'reconcile_and_progress' in available_actions:
code = 'reconcile_and_progress'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
@@ -937,6 +1043,27 @@ def apply_user_projection_fields(
'upload_state': 'not_created',
'switch_state': 'not_triggered',
}
# MVP 四库存里程碑是 Projection facts,不是第二套运行时 Gate 生命周期。
# 仅依据正式 current_gate 的顺序和已投影事实派生,避免重新引入 APX 六 Gate。
gate_code = str((payload.get('current_gate') or {}).get('gate_code') or '').strip()
gate_order = {
'inventory_source_routing': 0,
'inventory_preparation': 1,
'inventory_field_mapping': 2,
'inventory_matching': 3,
'inventory_sufficiency': 4,
'excel_readiness': 5,
'artifact_generation': 6,
'manual_upload_handoff': 7,
'upload_receipt_recorded': 8,
}
current_order = gate_order.get(gate_code)
facts['inventory_milestones'] = {
'candidates_calculated': 'completed' if current_order is not None and current_order >= 1 else 'pending',
'candidates_frozen': 'completed' if current_order is not None and current_order >= 1 else 'pending',
'snapshots_ready': 'completed' if current_order is not None and current_order >= 3 else 'pending',
'matched': 'completed' if current_order is not None and current_order >= 4 else 'pending',
}
if order_task is not None:
cand = getattr(order_task, 'candidate_source_codes_json', None)
if isinstance(cand, list):
@@ -954,6 +1081,32 @@ def apply_user_projection_fields(
fms = step_payload.get('forced_match_source_code')
if fms:
facts['forced_match_source_code'] = str(fms).strip().upper()
# 正式 OT 优先从 CandidateSet/LineMatch Projection 读取库存事实;旧
# step_payload 仅作为尚未形成正式候选集的历史任务兼容回退。
try:
from app.services.shipping_notice.inventory_candidate_projection import (
project_inventory_candidate_facts,
)
candidate_facts = project_inventory_candidate_facts(notice)
if candidate_facts.get('current_set') is not None:
facts['candidate_set_id'] = candidate_facts.get('candidate_set_id')
facts['candidate_set_version'] = candidate_facts.get('candidate_set_version')
facts['candidate_set_status'] = candidate_facts.get('candidate_set_status')
facts['candidate_source_codes'] = list(candidate_facts.get('candidate_source_codes') or [])
facts['prepared_source_codes'] = list(candidate_facts.get('prepared_source_codes') or [])
facts['pending_source_codes'] = list(candidate_facts.get('pending_source_codes') or [])
facts['failed_source_codes'] = list(candidate_facts.get('failed_source_codes') or [])
facts['source_attempts'] = dict(candidate_facts.get('source_attempts') or {})
facts['line_resolutions'] = list(candidate_facts.get('line_resolutions') or [])
elif candidate_facts.get('blocking_reason', {}).get('code') in {
'inventory_candidate_version_stale',
'inventory_candidate_out_of_scope',
}:
payload['projection_data_inconsistent'] = True
except Exception: # noqa: BLE001
# 结构化事实读取失败时交给最终 Projection invariant fail-closed;
# 不使用旧 payload 拼装出可执行状态。
payload['projection_data_inconsistent'] = True
# P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。
try:
from app.models import ShippingTaskInventoryRpaAttempt
@@ -125,6 +125,9 @@ def _dispatch_legacy_orchestration(
operator_id: int | None,
inventory_mode: str = 'auto',
line_scope_key: str | None = None,
recovery_plan_id: int | None = None,
recovery_attempt_id: int | None = None,
resume_after_gate: str | None = None,
) -> dict[str, Any]:
"""
resume_gate_code → 旧实现分派(短期复用稳定实现,后续逐步把每个 Gate 原子步骤迁入本 facade)。
@@ -209,6 +212,9 @@ def run_task_auto_progress(
operator_id: int | None = None,
inventory_mode: str = 'auto',
line_scope_key: str | None = None,
recovery_plan_id: int | None = None,
recovery_attempt_id: int | None = None,
resume_after_gate: str | None = None,
) -> dict[str, Any]:
"""
唯一 AutoProgress Orchestrator Facade。
@@ -232,6 +238,9 @@ def run_task_auto_progress(
operator_id: 操作人 ID(系统触发则 None)。
inventory_mode: 库存准备模式;用户显式重试传 retry_rpa,自动推进保持 auto。
line_scope_key: 行级 scope 键;传了则仅对该行执行(例如 match_inventory_line),不传则整单推进。
recovery_plan_id: 可选恢复计划 ID,用于关联本次 Gate 恢复执行。
recovery_attempt_id: 可选恢复 Attempt ID,用于关联本次 Gate 恢复执行。
resume_after_gate: 可选恢复后续 Gate 标识。
Returns:
Tool 标准响应(status=running/needs_human/failed/completed + task + data);
@@ -252,6 +261,9 @@ def run_task_auto_progress(
submitted = submit_auto_progress(
task=task, trigger=trigger, operator_id=operator_id,
resume_gate_code=resume_gate_code, commit=True,
recovery_plan_id=recovery_plan_id,
recovery_attempt_id=recovery_attempt_id,
resume_after_gate=resume_after_gate,
)
status = str(submitted.get('status') or 'queued')
if status == 'queued':
@@ -397,6 +409,9 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
idempotency_key=idempotency_key,
resume_gate_code=None,
operator_id=operator_id,
recovery_plan_id=payload.get('recovery_plan_id'),
recovery_attempt_id=payload.get('recovery_attempt_id'),
resume_after_gate=payload.get('resume_after_gate'),
)
# 下方:_auto_progress_full 内部调用路径(直接执行完整串联,不再走 Orchestrator 外层)
if not auto_progress_enabled():
@@ -317,8 +317,12 @@ def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str
if not task or not task.export_file_path:
return None
from app.models import ShippingExportArtifact
artifact = ShippingExportArtifact.query.filter_by(
task_id=task.id, status='ready', file_path=task.export_file_path,
# 已人工/RPA 上传完成的 Artifact 仍是用户可下载的最终 Excel;
# 不能因履约完成将 status=uploaded 排除在下载解析之外。
artifact = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status.in_({'ready', 'uploaded'}),
ShippingExportArtifact.file_path == task.export_file_path,
).order_by(
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
).first()
@@ -462,7 +462,12 @@ def project_case_allowed_actions(
if 'reconcile_and_progress' in actions:
_others = [a for a in actions if a != 'reconcile_and_progress']
actions = ['reconcile_and_progress', *_others]
if llm_review_enabled() and 'edit_draft' in actions:
try:
llm_enabled = llm_review_enabled()
except RuntimeError:
# 纯投影合同和离线诊断没有 Flask 请求上下文;缺少运行时配置时按关闭处理。
llm_enabled = False
if llm_enabled and 'edit_draft' in actions:
actions.append('request_llm_suggestion')
return actions
@@ -591,7 +596,7 @@ def project_case_user_status(
"""
auto_status = str((automation or {}).get('status') or '').strip().lower()
case_status = str(case.status or '').strip().lower()
if case_status in {'confirmed'} and auto_status in {'completed', 'success'}:
if auto_status in {'completed', 'success'}:
return 'completed'
if case_status in {'cancelled', 'superseded', 'non_order'}:
return 'cancelled'
@@ -41,6 +41,15 @@ _TECH_RETRYABLE_CATEGORY_HINTS: frozenset[str] = frozenset({
"lease_expired",
})
# 库存 RPA Trigger 投递/领取失败属于技术暂态;不能被当作业务人工阻断,
# 否则正式 OT 的 retryable 投影会变成 false,conversation retry 不会重新建 Trigger。
_TECH_RETRYABLE_ERROR_CODES: frozenset[str] = frozenset({
"trigger_not_claimed_missing",
"trigger_not_claimed_timeout",
"inventory_trigger_missing",
"inventory_trigger_write_failed",
})
# T3:业务阻断 → 推荐 UI 动作映射;未命中时 fallback 为 "open_order_review"
BLOCKING_REASON_TO_ACTION_CODES: dict[str, str] = {
"duplicate_decision_required": "adjudicate_duplicate",
@@ -100,6 +109,9 @@ def is_tech_retryable_error(
if normalized.startswith(prefix):
return True
if normalized.lower() in _TECH_RETRYABLE_ERROR_CODES:
return True
hint = str(category_hint or "").strip()
if hint and hint in _TECH_RETRYABLE_CATEGORY_HINTS:
return True
@@ -0,0 +1,97 @@
"""
services/shipping_notice/recovery_invalidation_service.py
用途:按恢复动作精确失效库存下游事实及正式 Gate。
依赖:ShippingProcessExecution/Gate、库存快照链接、行级 Match、Verification、Artifact、UploadAttempt。
逻辑:只标记失效,不删除、不覆盖历史事实;所有变更在调用方事务内完成。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import (
ShippingExportArtifact,
ShippingInventoryVerification,
ShippingInventoryMapping,
ShippingNoticeLineInventoryMatch,
ShippingProcessExecution,
ShippingTaskInventoryLink,
ShippingUploadAttempt,
)
from app.services.shipping_notice.process_gate_service import invalidate_downstream_gates
def invalidate_inventory_downstream(
*, execution: ShippingProcessExecution, action_code: str, attempt_id: int | None = None,
actor_id: int | str | None = None,
) -> dict[str, list[int] | list[str]]:
"""失效库存恢复受影响事实,并返回可审计的对象 ID。"""
task_id = int(execution.task_id or 0)
if not task_id:
return {'gates': [], 'links': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []}
now = datetime.utcnow()
from app.models import ShippingNotice
task = db.session.get(ShippingNotice, task_id)
result: dict[str, list[int] | list[str]] = {'gates': [], 'links': [], 'mappings': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []}
change_type = {
'retry_inventory_from_preparation': 'inventory_file_changed',
'retry_inventory_from_field_mapping': 'inventory_field_mapping_changed',
'retry_inventory_from_matching': 'inventory_matching_changed',
}.get(action_code, 'inventory_matching_changed')
result['gates'] = invalidate_downstream_gates(execution=execution, change_type=change_type, actor_id=actor_id)
if action_code == 'retry_inventory_from_preparation':
links = ShippingTaskInventoryLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all()
for link in links:
link.is_active = False
link.invalidated_at = now
link.invalidated_by_attempt_id = attempt_id
link.invalidation_reason = action_code
result['links'].append(int(link.id))
active_file_ids = [
int(link.inventory_file_id)
for link in ShippingTaskInventoryLink.query.filter_by(task_id=task_id).all()
if link.inventory_file_id
]
if action_code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping'} and active_file_ids:
mappings = ShippingInventoryMapping.query.filter(
ShippingInventoryMapping.inventory_file_id.in_(active_file_ids),
ShippingInventoryMapping.status == 'active',
).with_for_update().all()
for mapping in mappings:
mapping.status = 'invalidated'
result['mappings'].append(int(mapping.id))
matches = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all()
for row in matches:
row.is_current = False
row.invalidated_at = now
row.invalidated_by_attempt_id = attempt_id
row.invalidation_reason = action_code
result['matches'].append(int(row.id))
verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all()
for verification in verifications:
verification.status = 'superseded'
result['verifications'].append(int(verification.id))
artifacts = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task_id,
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
).with_for_update().all()
for artifact in artifacts:
artifact.status = 'superseded'
result['artifacts'].append(int(artifact.id))
uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).filter(
ShippingUploadAttempt.status.in_({'pending', 'running', 'timed_out', 'unknown'}),
).with_for_update().all()
for upload in uploads:
upload.invalidated_at = now
upload.invalidation_reason = action_code
result['uploads'].append(int(upload.id))
if task is not None and action_code == 'retry_inventory_from_preparation':
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.export_file_path = None
task.export_file_name = None
db.session.flush()
return result
@@ -0,0 +1,58 @@
"""
services/shipping_notice/recovery_plan_contract.py
用途:定义跨阶段恢复动作的服务端白名单及其失效/恢复边界。
依赖:process_gate_contract 的正式 Gate 编码。
逻辑:RecoveryPlan 服务和 Projection 共同消费此纯数据合同,客户端不能提交目标 Gate。
"""
from __future__ import annotations
from typing import Any
RECOVERY_PLAN_ACTIONS: dict[str, dict[str, dict[str, Any]]] = {
'inventory_matching': {
'retry_inventory_from_preparation': {
'target_gate': 'inventory_preparation',
'resume_after_gate': 'inventory_matching',
'allowed_intermediate_gates': ('inventory_field_mapping',),
'invalidate_change_type': 'inventory_file_changed',
'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
'permission': 'owner_or_admin',
},
'retry_inventory_from_field_mapping': {
'target_gate': 'inventory_field_mapping',
'resume_after_gate': 'inventory_matching',
'allowed_intermediate_gates': (),
'invalidate_change_type': 'inventory_field_mapping_changed',
'invalidates': ('inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
'permission': 'owner_or_admin',
},
},
# 库存有缺口时仍由 Gate 16 负责恢复入口;数量事实只读,恢复动作回到正式库存链路。
'inventory_sufficiency': {
'retry_inventory_from_preparation': {
'target_gate': 'inventory_preparation',
'resume_after_gate': 'inventory_sufficiency',
'allowed_intermediate_gates': ('inventory_field_mapping', 'inventory_matching'),
'invalidate_change_type': 'inventory_file_changed',
'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
'permission': 'owner_or_admin',
},
'retry_inventory_from_matching': {
'target_gate': 'inventory_matching',
'resume_after_gate': 'inventory_sufficiency',
'allowed_intermediate_gates': (),
'invalidate_change_type': 'inventory_matching_changed',
'invalidates': ('inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
'permission': 'owner_or_admin',
},
},
}
def recovery_plan_for_action(*, current_gate: str, action_code: str) -> dict[str, Any] | None:
"""读取当前 Gate 下的跨阶段恢复计划定义;未知组合返回 None。"""
item = RECOVERY_PLAN_ACTIONS.get(str(current_gate or '').strip(), {}).get(str(action_code or '').strip())
return dict(item) if isinstance(item, dict) else None
@@ -0,0 +1,125 @@
"""
services/shipping_notice/recovery_plan_service.py
用途:创建并绑定跨阶段 RecoveryPlan,保证 Gate/Execution 锁、幂等和终态保护统一。
依赖:ShippingProcessRecoveryPlan、process_gate_contract、recovery_plan_contract、db。
逻辑:只创建白名单计划;Gate Attempt 由既有 process_gate_service 创建后回填关联。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, ShippingProcessRecoveryPlan
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
_TERMINAL_EXECUTION_STATUSES = frozenset({'completed', 'cancelled', 'superseded'})
def create_recovery_plan(
*, execution: ShippingProcessExecution, gate: ShippingProcessGate, action_code: str,
idempotency_key: str, actor_type: str, actor_id: int | str | None,
operation_id: str | None = None,
) -> tuple[ShippingProcessRecoveryPlan, dict[str, Any]]:
"""校验并创建跨阶段恢复计划;同幂等键返回原计划。"""
definition = recovery_plan_for_action(current_gate=gate.gate_code, action_code=action_code)
if definition is None:
raise ValidationError(
'Recovery target is not allowed for current gate',
code='SHIPPING.RECOVERY_TARGET_INVALID',
details={'current_gate': gate.gate_code, 'action_code': action_code},
)
if execution.status in _TERMINAL_EXECUTION_STATUSES:
raise ConflictError(
'Recovery is not allowed on terminal execution',
code='SHIPPING.RECOVERY_NOT_ALLOWED_ON_TERMINAL',
details={'execution_no': execution.execution_no, 'status': execution.status},
)
key = str(idempotency_key or '').strip()
if not key:
raise ValidationError('idempotency_key is required', code='SHIPPING.PROCESS_GATE_IDEMPOTENCY_REQUIRED')
replay = ShippingProcessRecoveryPlan.query.filter_by(
execution_id=int(execution.id), idempotency_key=key,
).first()
if replay is not None:
return replay, definition
active_plan = ShippingProcessRecoveryPlan.query.filter(
ShippingProcessRecoveryPlan.execution_id == int(execution.id),
ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}),
).with_for_update().first()
if active_plan is not None:
raise ConflictError(
'Another recovery plan is active for this execution',
code='SHIPPING.RECOVERY_PLAN_CONFLICT',
details={'execution_no': execution.execution_no, 'plan_no': active_plan.plan_no},
)
plan = ShippingProcessRecoveryPlan(
plan_no=f'RCP-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}-{int(execution.id)}-{str(idempotency_key)[-8:]}',
execution_id=int(execution.id), current_gate=gate.gate_code,
action_code=str(action_code), target_gate=str(definition['target_gate']),
resume_after_gate=definition.get('resume_after_gate'), status='planned',
invalidation_plan_json={
'change_type': definition.get('invalidate_change_type'),
'invalidates': list(definition.get('invalidates') or ()),
'allowed_intermediate_gates': list(definition.get('allowed_intermediate_gates') or ()),
}, idempotency_key=key, expected_gate_version=int(gate.evaluation_version),
actor_type=str(actor_type or 'system'), actor_id=str(actor_id) if actor_id is not None else None,
operation_id=operation_id,
)
db.session.add(plan)
db.session.flush()
return plan, definition
def bind_recovery_attempt(*, plan: ShippingProcessRecoveryPlan, attempt_id: int) -> None:
"""把 Gate Attempt 纳入 RecoveryPlan;不提交事务。"""
plan.recovery_attempt_id = int(attempt_id)
attempt = db.session.get(ShippingProcessGateAttempt, int(attempt_id))
if attempt is not None:
attempt.recovery_plan_id = int(plan.id)
plan.status = 'queued'
db.session.flush()
def complete_recovery_plan_for_attempt(
*, plan: ShippingProcessRecoveryPlan, outcome: str, now: datetime | None = None,
error_code: str | None = None, error_summary: str | None = None,
business_result_code: str | None = None,
) -> None:
"""
将 RecoveryPlan 与绑定 Attempt 的执行结果原子收口。
核心逻辑:使用当前库存重新匹配后若仍有缺口,说明恢复动作本身已成功,
只是正式流程重新停在库存满足性人工复核;该计划必须终态完成,不能以
``waiting_manual`` 长期占用 Execution,阻塞用户再次选择其他恢复方式。
"""
status_by_outcome = {
'passed': 'succeeded',
'waiting_external': 'waiting_external',
'blocked_manual': 'waiting_manual',
'blocked_retryable': 'failed',
'failed_terminal': 'failed',
}
resolved_outcome = str(outcome)
rematch_reached_shortage_review = (
resolved_outcome == 'blocked_manual'
and str(plan.action_code or '') == 'retry_inventory_from_matching'
and str(plan.resume_after_gate or '') == 'inventory_sufficiency'
and str(business_result_code or '') == 'inventory_shortage_review_required'
)
plan.status = (
'succeeded'
if rematch_reached_shortage_review
else status_by_outcome.get(resolved_outcome, 'failed')
)
plan.failure_code = str(error_code)[:64] if error_code else None
plan.failure_detail_json = ({'message': str(error_summary)[:500]} if error_summary else None)
finished_at = now or datetime.utcnow()
plan.started_at = plan.started_at or finished_at
if plan.status in {'succeeded', 'failed', 'cancelled'}:
plan.completed_at = finished_at
db.session.flush()
+21 -9
View File
@@ -15,6 +15,7 @@ from pathlib import Path
from typing import Any
from flask import current_app
from app.core.errors import ValidationError
def _runtime_summary(mode: str) -> dict[str, str | bool]:
@@ -153,9 +154,14 @@ def write_inventory_export_batch_trigger(
"validation_run_no": source.get("validation_run_no"),
}
# v2 逐源身份必须由后端显式写入,Worker 不得重新生成。
for identity_key in ("task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version", "expected_warehouse_id", "lease_token"):
for identity_key in (
"callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version",
"execution_id", "gate_id", "expected_warehouse_id", "lease_token",
):
if source.get(identity_key) is not None:
item[identity_key] = source[identity_key]
if not item.get('callback_id') and item.get('source_run_no'):
item['callback_id'] = f"{item['source_run_no']}:C1"
inventory_sources.append(item)
if not inventory_sources:
return None
@@ -163,6 +169,7 @@ def write_inventory_export_batch_trigger(
body = {
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"{run_no}:batch:C1",
"batch_run_no": run_no,
"run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段
"trigger_type": "scheduled",
@@ -194,7 +201,8 @@ def write_inventory_export_trigger_for_task(
写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。
【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。
核心逻辑:batch 模式写 inventory_export_batch(含 task_no);否则写 legacy inventory_export。
核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed,
不再生成 legacy inventory_export trigger。
"""
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
@@ -211,11 +219,18 @@ def write_inventory_export_trigger_for_task(
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
source_item = dict(rpa_source)
source_item.update({
"callback_id": body.get("callback_id") or (
f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None
),
"task_no": task_no,
"attempt_no": body.get("attempt_no"),
# 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致
# Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。
"attempt_no": body.get("attempt_no") or body.get("attempt"),
"source_run_no": body.get("source_run_no"),
"candidate_set_id": body.get("candidate_set_id"),
"candidate_set_version": body.get("candidate_set_version"),
"execution_id": body.get("execution_id"),
"gate_id": body.get("gate_id"),
"expected_warehouse_id": body.get("expected_warehouse_id"),
"lease_token": body.get("lease_token"),
})
@@ -229,12 +244,9 @@ def write_inventory_export_trigger_for_task(
**body,
},
)
return write_inventory_export_trigger(
task_no,
{
"rpa_inventory_source": rpa_source,
**body,
},
raise ValidationError(
'shipping inventory RPA v2 batch trigger is required',
code='SHIPPING.INVENTORY_RPA_V2_REQUIRED',
)
@@ -764,15 +764,35 @@ def _order_task_current_gate(
Returns:
ProcessGateSummary 形状 dict;无需门禁时 None。
"""
open_case = (
ShippingOrderReviewCase.query.filter(
ShippingOrderReviewCase.run_id == int(run.id),
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
ShippingOrderReviewCase.confirmed_task_id.is_(None),
)
.order_by(ShippingOrderReviewCase.id.desc())
.first()
# Child OT 必须先按自身 Candidate 找 Case;仅按 run_id 取最新 Case 会把
# 多 PDF 的子订单阶段错误绑定到根 PDF。
open_case = None
is_child_order_task = bool(
order_task is not None
and getattr(order_task, 'candidate_id', None)
and str(getattr(order_task, 'task_no', '') or '').strip()
!= str(getattr(run, 'user_task_no', '') or '').strip()
)
if is_child_order_task:
open_case = (
ShippingOrderReviewCase.query.filter(
ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id),
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
ShippingOrderReviewCase.confirmed_task_id.is_(None),
)
.order_by(ShippingOrderReviewCase.id.desc())
.first()
)
if open_case is None:
open_case = (
ShippingOrderReviewCase.query.filter(
ShippingOrderReviewCase.run_id == int(run.id),
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
ShippingOrderReviewCase.confirmed_task_id.is_(None),
)
.order_by(ShippingOrderReviewCase.id.desc())
.first()
)
if open_case is not None:
from app.models import ShippingProcessExecution
from app.services.shipping_notice.process_gate_projection import (
@@ -786,7 +806,7 @@ def _order_task_current_gate(
)
if execution is not None:
summary = project_user_gate_summary(execution)
blocking = summary.get('current_blocking_gate')
blocking = summary.get('current_blocking_gate') or summary.get('current_gate')
if isinstance(blocking, dict) and blocking.get('gate_code'):
return {
'gate_code': str(blocking.get('gate_code') or ''),
@@ -794,7 +814,6 @@ def _order_task_current_gate(
'next_action_code': (
summary.get('next_action_code')
or blocking.get('next_action_code')
or 'open_order_review'
),
'blocking_reason_code': (
summary.get('blocking_reason_code')
@@ -825,7 +844,7 @@ def _order_task_current_gate(
)
if execution is not None:
summary = project_user_gate_summary(execution)
blocking = summary.get('current_blocking_gate')
blocking = summary.get('current_blocking_gate') or summary.get('current_gate')
if isinstance(blocking, dict) and blocking.get('gate_code'):
return {
'gate_code': str(blocking.get('gate_code') or ''),
@@ -833,7 +852,6 @@ def _order_task_current_gate(
'next_action_code': (
summary.get('next_action_code')
or blocking.get('next_action_code')
or 'open_fulfillment'
),
'blocking_reason_code': (
summary.get('blocking_reason_code')
@@ -985,6 +1003,7 @@ def _project_order_task_work_item(
stage = map_run_to_processing_stage(run, source_type=source_type)
# [BE-02] 已挂正式 Notice 时与 Case.current_stage 同源(project_stage_for_task)。
stage_label_key = None
notice_for_stage = None
if order_task.shipping_notice_id:
notice_for_stage = db.session.get(ShippingNotice, int(order_task.shipping_notice_id))
if notice_for_stage is not None:
@@ -1007,6 +1026,13 @@ def _project_order_task_work_item(
str(run.status or ''),
stage=stage,
)
# 人工上传登记/RPA 回调先更新 ShippingNotice 聚合事实;旧 OT.status 可能仍为
# automating。终态 Notice 必须覆盖旧 OT 状态,保证统一投影、右侧状态和进度节点同源。
notice_process_status = str(getattr(notice_for_stage, 'process_status', None) or '').strip().lower() if notice_for_stage is not None else ''
if notice_process_status in {'uploaded', 'closed', 'completed'}:
status = 'completed'
stage = 'completed'
stage_label_key = 'completed'
# [BE-03] OT 上残留的 completed + 早期 stage 组合在输出前再折叠。
if status == 'completed' and stage != 'completed':
status = derivation_status_for_extraction_run('completed', stage=stage)
@@ -1043,15 +1069,27 @@ def _project_order_task_work_item(
# [P0] 深链订单处理工作台需要 run_no / case_no;禁止前端合成 OT 时丢失。
run_no = str(getattr(run, 'run_no', None) or '').strip() or None
case_no = None
open_case = (
ShippingOrderReviewCase.query.filter(
ShippingOrderReviewCase.run_id == int(run.id),
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
ShippingOrderReviewCase.confirmed_task_id.is_(None),
open_case = None
if order_task is not None and getattr(order_task, 'candidate_id', None):
open_case = (
ShippingOrderReviewCase.query.filter(
ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id),
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
ShippingOrderReviewCase.confirmed_task_id.is_(None),
)
.order_by(ShippingOrderReviewCase.id.desc())
.first()
)
if open_case is None:
open_case = (
ShippingOrderReviewCase.query.filter(
ShippingOrderReviewCase.run_id == int(run.id),
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
ShippingOrderReviewCase.confirmed_task_id.is_(None),
)
.order_by(ShippingOrderReviewCase.id.desc())
.first()
)
.order_by(ShippingOrderReviewCase.id.desc())
.first()
)
if open_case is not None:
case_no = str(getattr(open_case, 'case_no', None) or '').strip() or None
elif order_task is not None and getattr(order_task, 'candidate_id', None):
@@ -1148,14 +1186,17 @@ def _project_order_task_work_item(
post_confirm=post_confirm_snapshot,
is_admin=False,
)
formal_gate_projection = isinstance(payload.get('current_gate'), dict) and bool(
str((payload.get('current_gate') or {}).get('gate_code') or '').strip()
)
# 六字段覆盖:user_status / blocking_reason / primary_action / current_gate / available_actions / retryable
if isinstance(bundle.get('user_status'), str):
payload['user_status'] = bundle['user_status']
if isinstance(bundle.get('blocking_reason'), dict):
payload['blocking_reason'] = dict(bundle['blocking_reason'])
if isinstance(bundle.get('primary_action'), dict):
if isinstance(bundle.get('primary_action'), dict) and not formal_gate_projection:
payload['primary_action'] = dict(bundle['primary_action'])
if isinstance(bundle.get('current_gate'), dict):
if isinstance(bundle.get('current_gate'), dict) and not formal_gate_projection:
current_gate = dict(payload.get('current_gate') or {})
current_gate.update(bundle['current_gate'])
payload['current_gate'] = current_gate
@@ -1173,32 +1214,58 @@ def _project_order_task_work_item(
if retry_flag or str(payload.get('user_status') or '') == 'retryable':
payload['retryable'] = True
except Exception: # noqa: BLE001
# 只读投影失败不阻断列表输出(fail-closed 兜底 invariants 结果)
pass
# Review bundle 是当前用户动作的权威来源;读取失败时不得静默回退到
# 旧 checkpoint/notice 字段,避免前端展示可继续执行的过时动作。
payload['user_status'] = 'waiting_human'
payload['retryable'] = False
payload['primary_action'] = None
payload['available_actions'] = []
payload['blocking_reason'] = {
'code': 'projection_data_inconsistent',
'message': '处理状态暂时无法确认,请刷新后重试',
}
# 题4A:注入 inventory_preparation 结构化字段(题7A:区分 failed/exhausted_sources);
# 仅当 inventory 阶段或更早、且已挂正式 Notice 时才填充;其他阶段填 None 避免误导。
inventory_preparation = None
if notice is not None:
try:
from app.services.shipping_notice.task_retry_decision_service import (
summarize_inventory_rpa_latest_attempts,
)
from app.models import ShippingInventoryPreparationAttempt
snapshot_src = summarize_inventory_rpa_latest_attempts(notice, include_gate_status=True)
required_sources = list(snapshot_src.get('required_frozen_sources') or [])
prepared_sources = list(snapshot_src.get('prepared_source_codes') or [])
pending_sources = list(snapshot_src.get('pending_source_codes') or [])
failed_sources = list(snapshot_src.get('failed_source_codes') or [])
exhausted_sources = list(snapshot_src.get('exhausted_source_codes') or [])
active_attempt_count = int(snapshot_src.get('active_attempt_count') or 0)
latest_attempts = dict(snapshot_src.get('latest_attempts') or {})
preparation = (
ShippingInventoryPreparationAttempt.query
.filter_by(task_id=int(notice.id))
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc())
.first()
)
source_attempts = list(getattr(preparation, 'source_attempts', []) or []) if preparation else []
required_sources = [str(row.source_code) for row in source_attempts]
prepared_sources = [str(row.source_code) for row in source_attempts if row.status in {'ready', 'reusable'}]
pending_sources = [str(row.source_code) for row in source_attempts if row.status in {'queued', 'running', 'waiting'}]
failed_sources = [str(row.source_code) for row in source_attempts if row.status == 'failed']
exhausted_sources: list[str] = []
active_attempt_count = 1 if preparation and preparation.status in {'queued', 'running', 'waiting_external'} else 0
latest_attempts = {
str(row.source_code): {
'attempt_no': int(preparation.attempt_no),
'status': row.status,
'rpa_attempt_id': row.rpa_attempt_id,
'inventory_file_id': row.inventory_file_id,
}
for row in source_attempts
}
# 快照载入状态补入 prepared_sources(如果快照就绪且 inventory_lines_json 已保存但 per_source 尚未标记 prepared)
if notice.inventory_lines_json and notice.inventory_snapshot_id:
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
if active_inventory_lines_for_task(notice) and notice.inventory_snapshot_id:
for code in required_sources:
if code and code not in prepared_sources and code not in pending_sources:
prepared_sources.append(code)
inventory_preparation = {
'attempt_id': int(preparation.id) if preparation else None,
'attempt_no': int(preparation.attempt_no) if preparation else None,
'status': preparation.status if preparation else None,
'required_sources': required_sources,
'prepared_sources': prepared_sources,
'pending_sources': pending_sources,
@@ -1206,10 +1273,16 @@ def _project_order_task_work_item(
'exhausted_sources': exhausted_sources,
'active_attempt_count': active_attempt_count,
'latest_attempts': latest_attempts,
'gate_attempt_active': bool(snapshot_src.get('gate_attempt_active')),
'source_attempts': latest_attempts,
'gate_attempt_active': active_attempt_count > 0,
}
except Exception: # noqa: BLE001
# 关键准备事实读取失败时 fail-closed;禁止静默回退到旧字段拼装出可执行状态。
inventory_preparation = None
payload['projection_data_inconsistent'] = True
# PreparationAttempt 读取发生在首次用户态归一化之后;立即重新应用
# fail-closed 规则,防止异常分支保留旧 primary_action/available_actions。
payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task)
payload['inventory_preparation'] = inventory_preparation
# 题4A & 题7A:根据 inventory_preparation 统一折叠 retryable(仅当没有 pending/running + (failed or exhausted) 时,保证可重试为 true;
@@ -61,6 +61,7 @@ def _inventory_row_key(row: dict[str, Any]) -> tuple[str, str, str] | None:
row.get('reservation_id') or row.get('Reservation ID') or row.get('reservation')
)
part = _norm_part(row.get('part_number') or row.get('Part Number') or row.get('mpn') or row.get('sku'))
# 单位只有在 Profile 显式配置并被标准化进快照时才参与;默认空单位不阻断匹配。
unit = _norm_unit(row.get('uom') or row.get('unit') or row.get('UOM') or row.get('Unit'))
if not reservation or not part:
return None
@@ -314,6 +315,7 @@ def match_order_lines_across_candidates(
resolutions: list[dict[str, Any]] = []
has_ok = False
has_block = False
has_partial = False
for index, line in enumerate(order_lines):
part = _norm_part(line.get('part_number') or line.get('__display_part_number'))
@@ -344,7 +346,7 @@ def match_order_lines_across_candidates(
for key in buckets
if key[0] == (effective or '')
and key[1] == part
and key[2] == unit
and (not unit or not key[2] or key[2] == unit)
] if effective and part else []
# 正式匹配必须存在结构化 CandidateLine,并严格限制在该行允许源内。
# 缺少行级范围本身就是候选事实缺失,不能退化为任务级并集匹配。
@@ -462,6 +464,7 @@ def match_order_lines_across_candidates(
'resolved_inventory_source_code': hit['source_code'],
}
has_block = True
has_partial = available > 0
line_results.append(result)
resolutions.append({
@@ -486,7 +489,7 @@ def match_order_lines_across_candidates(
if not order_lines:
match_status = 'unfulfillable'
elif has_block:
match_status = 'unfulfillable' if not has_ok else 'partial'
match_status = 'partial' if (has_ok or has_partial) else 'unfulfillable'
else:
match_status = 'fulfillable'
@@ -41,6 +41,66 @@ PH_UPLOAD_PENDING = 'upload_rpa_pending'
PH_UPLOAD_FAILED = 'upload_rpa_failed'
def _request_formal_gate_action(
*,
task: ShippingNotice,
action_code: str,
user_id: int,
idempotency_key: str,
trigger: str,
line_key: str | None = None,
) -> dict[str, Any]:
"""将外部重试意图提交给正式 20-Gate Recovery/ProcessGate 编排。
外部入口只负责定位当前正式 Gate 和动作;库存准备、匹配等旧函数仅允许
由 ``process_gate_executor`` 通过内部分派标记调用。
"""
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
from app.services.shipping_notice.process_gate_recovery_service import request_gate_action
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
from app.models import ShippingProcessExecution, ShippingProcessGate
execution = None
current_id = getattr(task, 'active_process_execution_id', None)
if current_id:
execution = ShippingProcessExecution.query.filter_by(id=int(current_id)).with_for_update().first()
if execution is None:
execution = ensure_execution_for_workflow_version(
task_id=int(task.id), actor_type='user', actor_id=int(user_id),
start_gate_code=determine_formal_start_gate(task),
)
task.active_process_execution_id = int(execution.id)
db.session.flush()
gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code=str(execution.current_gate_code or '').strip(),
).first()
if gate is None:
raise ValidationError('Current formal process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
requested = str(action_code or '').strip()
if requested == 'retry_inventory_from_matching' and gate.gate_code != 'inventory_sufficiency':
requested = 'retry_inventory_matching'
payload: dict[str, Any] = {'trigger': trigger}
if line_key:
payload['line_key'] = str(line_key)
result = request_gate_action(
execution_no=str(execution.execution_no), gate_code=str(gate.gate_code),
action_code=requested, expected_gate_version=int(gate.evaluation_version),
idempotency_key=str(idempotency_key), actor_type='user', actor_id=int(user_id),
payload=payload,
)
return {
'status': 'running' if result.get('dispatch') in {'async_job', 'sync'} else 'failed',
'action': action_code,
'task_id': task.task_no,
'job_id': result.get('job_id'),
'attempt_id': (result.get('attempt') or {}).get('id'),
'execution_no': result.get('execution_no'),
'gate_code': result.get('gate_code'),
'message': '已提交正式 20-Gate 恢复动作',
}
def retry_task_with_decision(
*,
task_no: str,
@@ -219,6 +279,17 @@ def _decide(
'retryable': False,
'reason_code': 'already_running',
}
latest_statuses = {
str(item.get('status') or '').strip().lower()
for item in (active.get('latest_attempts') or {}).values()
}
if scope != 'line' and pending == PH_RPA_PENDING and latest_statuses <= {'', 'not_started'}:
return {
'action': ACTION_NOOP,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'already_running',
}
if pending == PH_UPLOAD_FAILED:
return {
'action': ACTION_NEEDS_HUMAN,
@@ -360,13 +431,20 @@ def _decide_for_line(
inventory_rpa_running=line_running_flag,
)
user_status = str(view.get('user_line_status') or '')
if user_status in {'shortage', 'source_conflict'}:
if user_status == 'source_conflict':
return {
'action': ACTION_NEEDS_HUMAN,
'status': STATUS_NEEDS_HUMAN,
'retryable': False,
'reason_code': 'inventory_shortage' if user_status == 'shortage' else 'inventory_source_conflict',
}
if user_status == 'shortage':
return {
'action': ACTION_NEEDS_HUMAN,
'status': STATUS_NEEDS_HUMAN,
'retryable': False,
'reason_code': 'inventory_shortage',
}
if not project_line_retryable(
inventory_allowed_actions=list(view.get('inventory_allowed_actions') or []),
user_line_status=user_status,
@@ -459,10 +537,10 @@ def _execute(
adjudicate_and_apply_inventory_source,
ensure_inventory_source_review_state,
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice import tools as shipping_tools
action = str(decided.get('action') or ACTION_NOOP)
# 所有重试动作(含库存匹配 REMATCH)共用同一触发来源;不能只在 FETCH 分支内初始化。
trigger_norm = str(trigger or '').strip().lower() or 'user_retry'
base_kwargs = {
'task': task,
'decision_version': decision_version,
@@ -510,83 +588,58 @@ def _execute(
action = ACTION_FETCH_INVENTORY
if action == ACTION_FETCH_INVENTORY:
# 题1C:按调用来源分流。
# user_retry / user_line_retry:直接 mode='retry_rpa',显式重试无论 auto 是否已 exhausted 都开新 Attempt。
# conversation_retry / system_auto_progress 等:先 mode='auto' 复用快照,失败再 mode='retry_rpa' 兜底。
trigger_norm = str(trigger or '').strip().lower()
user_explicit = trigger_norm in {'user_retry', 'user_line_retry'}
if not user_explicit:
reused = ensure_inventory({
'task_id': task.task_no,
'mode': 'auto',
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
'trigger': trigger_norm,
})
if str((reused or {}).get('status') or '') in {'ok', 'completed'}:
if continue_auto_progress:
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
return _map_tool_result(
reused,
action=ACTION_FETCH_INVENTORY,
base_kwargs=base_kwargs,
message='已复用库存快照',
# 库存 RPA 的正式前置事实是订单快照。历史任务可能已完成解析但未成功冻结,
# 会话重试必须先补做一次冻结;冻结门禁失败时返回 needs_human,禁止伪造 Trigger。
if not getattr(task, 'order_snapshot_id', None) and isinstance(task, ShippingNotice):
try:
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
freeze_order_snapshot(
task,
actor_id=int(user_id),
expected_order_data_version=decision_version,
freeze_mode='manual',
)
fetched = ensure_inventory({
'task_id': task.task_no,
'mode': 'retry_rpa',
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
'trigger': trigger_norm,
})
return _map_tool_result(
fetched,
action=ACTION_FETCH_INVENTORY,
base_kwargs={
**base_kwargs,
'snapshot_id': getattr(task, 'inventory_snapshot_id', None),
},
message='已提交库存获取',
db.session.flush()
except AppError as freeze_err:
return _result_payload(
action=ACTION_NEEDS_HUMAN,
status=STATUS_NEEDS_HUMAN,
retryable=False,
reason_code=str(getattr(freeze_err, 'code', None) or 'order_freeze_not_ready'),
message='订单快照尚未冻结,无法进入库存 RPA。',
**base_kwargs,
)
formal = _request_formal_gate_action(
task=task,
action_code='retry_inventory_preparation',
user_id=int(user_id),
idempotency_key=idempotency_key,
trigger=trigger_norm,
line_key=line_key,
)
return _map_tool_result(formal, action=ACTION_FETCH_INVENTORY, base_kwargs=base_kwargs, message='已提交库存获取')
if action == ACTION_REMATCH:
# 题5B:有 line_key → 调用新 match_inventory_line 只对目标行匹配,避免整单重算覆盖其他行;
# 否则(例如 scope=task 且缺快照或整单重算)仍走原 match_inventory。
norm_line_key = str(line_key or '').strip()
if norm_line_key:
matched = shipping_tools.match_inventory_line(
{
'task_id': task.task_no,
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
'trigger': trigger_norm,
},
line_key=norm_line_key,
)
else:
matched = shipping_tools.match_inventory({
'task_id': task.task_no,
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
'trigger': trigger_norm,
})
mapped = _map_tool_result(
matched,
action=ACTION_REMATCH,
base_kwargs=base_kwargs,
message='已提交库存匹配',
formal = _request_formal_gate_action(
task=task,
action_code='retry_inventory_from_matching',
user_id=int(user_id),
idempotency_key=idempotency_key,
trigger=trigger_norm,
line_key=norm_line_key or None,
)
if continue_auto_progress and mapped.get('status') == STATUS_COMPLETED:
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
return mapped
return _map_tool_result(formal, action=ACTION_REMATCH, base_kwargs=base_kwargs, message='已提交库存匹配')
# ACTION_AUTO_PROGRESS 或 continue
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
except AppError as err:
# 下游 flush/写库失败会使 PostgreSQL 事务进入 aborted;必须先清理,
# 才能让调用方继续写本次失败决策审计。
db.session.rollback()
return _result_payload(
action=ACTION_FAILED,
status=STATUS_FAILED,
@@ -597,6 +650,9 @@ def _execute(
)
except Exception as exc: # noqa: BLE001
_LOGGER.exception('task retry execute failed task_no=%s action=%s', task.task_no, action)
# 同上:避免后续 _audit_decision 查询审计哈希链时触发
# InFailedSqlTransaction,掩盖真正的业务失败。
db.session.rollback()
return _result_payload(
action=ACTION_FAILED,
status=STATUS_FAILED,
@@ -641,22 +697,32 @@ def _map_tool_result(
) -> dict[str, Any]:
"""将既有 tool 响应映射为统一 Retry 结果。"""
status_raw = str((tool_result or {}).get('status') or '').strip().lower()
if status_raw in {'needs_human', 'waiting_manual', 'wait_manual_upload'}:
if status_raw in {'needs_human', 'waiting_manual', 'wait_manual_upload', 'blocked_manual'}:
return _result_payload(
action=ACTION_NEEDS_HUMAN,
status=STATUS_NEEDS_HUMAN,
retryable=False,
reason_code=str((tool_result or {}).get('error_code') or 'needs_human'),
reason_code=str(
(tool_result or {}).get('error_code')
or (tool_result or {}).get('reason_code')
or (tool_result or {}).get('blocking_reason_code')
or 'needs_human'
),
message=str((tool_result or {}).get('message') or '当前需要人工处理'),
job_id=(tool_result or {}).get('job_id'),
**base_kwargs,
)
if status_raw in {'failed', 'enqueue_failed', 'sync_execution_failed'}:
if status_raw in {'failed', 'enqueue_failed', 'sync_execution_failed', 'blocked_retryable'}:
return _result_payload(
action=ACTION_FAILED,
status=STATUS_FAILED,
retryable=True,
reason_code=str((tool_result or {}).get('error_code') or status_raw),
reason_code=str(
(tool_result or {}).get('error_code')
or (tool_result or {}).get('reason_code')
or (tool_result or {}).get('blocking_reason_code')
or status_raw
),
message=str((tool_result or {}).get('message') or '自动处理失败'),
job_id=(tool_result or {}).get('job_id'),
**base_kwargs,
@@ -762,6 +828,7 @@ def summarize_inventory_rpa_latest_attempts(
[STEP 4] 可选 include_gate_status:补充 Process Gate Attempt 的 queued/running。
"""
from app.models import (
Job,
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
@@ -789,7 +856,7 @@ def summarize_inventory_rpa_latest_attempts(
if task_no:
# 先一次性查出 (task_no, source_code) → 最新 attempt
rows = (
query = (
ShippingTaskInventoryRpaAttempt.query
.filter(ShippingTaskInventoryRpaAttempt.task_no == task_no)
.order_by(
@@ -797,11 +864,15 @@ def summarize_inventory_rpa_latest_attempts(
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
ShippingTaskInventoryRpaAttempt.id.desc(),
)
.all()
)
# 轻量调用方可能只提供 first();正式 ORM 使用 all() 做一次批量读取。
rows = query.all() if hasattr(query, 'all') else [query.first()]
rows = [row for row in rows if row is not None]
latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {}
for row in rows:
key = str(row.source_code or '').strip().upper() or None
key = str(getattr(row, 'source_code', None) or '').strip().upper() or None
if not key and len(required_frozen_sources) == 1:
key = required_frozen_sources[0]
if not key or key in latest_by_source:
continue
latest_by_source[key] = row
@@ -822,11 +893,11 @@ def summarize_inventory_rpa_latest_attempts(
continue
st = str(att.status or '').strip().lower()
latest_attempts[key] = {
'attempt_no': int(att.attempt_no or 0),
'run_no': str(att.run_no or '') or None,
'attempt_no': int(getattr(att, 'attempt_no', 0) or 0),
'run_no': str(getattr(att, 'run_no', '') or '') or None,
'status': st,
'error_code': str(att.error_code or '') or None,
'error_message': str(att.error_message or '') or None,
'error_code': str(getattr(att, 'error_code', '') or '') or None,
'error_message': str(getattr(att, 'error_message', '') or '') or None,
}
if st in {'queued', 'running'}:
pending.append(key)
@@ -852,7 +923,9 @@ def summarize_inventory_rpa_latest_attempts(
ShippingProcessExecution,
ShippingProcessGate.execution_id == ShippingProcessExecution.id,
)
.join(Job, Job.id == ShippingProcessGateAttempt.job_id)
.filter(ShippingProcessGateAttempt.status.in_(('queued', 'running')))
.filter(Job.status.in_(('queued', 'running')))
.filter(ShippingProcessExecution.task_id == int(task_id))
.limit(1)
.first()
@@ -410,7 +410,13 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else []
multi_block = bool(payload.get('multi_source_excel_block'))
candidate_projection = project_inventory_candidate_facts(task)
frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(task)
frozen_codes = (
list(candidate_projection.get('candidate_source_codes') or [])
or list(
(payload.get('line_inventory_candidates') or {}).get('source_codes') or []
)
or task_frozen_inventory_source_codes(task)
)
has_stp = (
status in {'candidates_frozen', 'resolved'}
or method.startswith('stp')
@@ -436,6 +442,12 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
'part_number': item.get('part_number'),
'resolved_inventory_source_code': item.get('resolved_inventory_source_code'),
'inventory_file_no': item.get('inventory_file_no'),
'inventory_file_sha256': item.get('inventory_file_sha256'),
'inventory_row_index': item.get('inventory_row_index'),
'match_attempt_id': item.get('match_attempt_id'),
'required_qty': item.get('required_qty'),
'matched_qty': item.get('matched_qty'),
'shortage_qty': item.get('shortage_qty'),
'inventory_row_ref': item.get('inventory_row_ref'),
})
@@ -50,13 +50,13 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
if existing is not None:
if existing.artifact_id != artifact.id:
raise ConflictError('Idempotency key belongs to another artifact', code='SHIPPING.UPLOAD_ATTEMPT_CONFLICT')
if existing.status == 'timed_out':
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN')
if existing.status in {'timed_out', 'unknown'}:
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN')
return existing
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='timed_out').first():
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN')
if ShippingUploadAttempt.query.filter(ShippingUploadAttempt.artifact_id == artifact.id, ShippingUploadAttempt.status.in_({'timed_out', 'unknown'})).first():
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RETRY_FORBIDDEN_UNTIL_TERMINAL')
attempt_no = (db.session.query(ShippingUploadAttempt).filter_by(artifact_id=artifact.id).count() + 1)
attempt = ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=attempt_no, mode='rpa', idempotency_key=key,
@@ -98,9 +98,11 @@ def complete_attempt(
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
if artifact is None:
raise ValidationError('Upload artifact is missing', code='SHIPPING.UPLOAD_ARTIFACT_REQUIRED')
if artifact.status in {'superseded', 'invalidated'}:
raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED')
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
if attempt.status not in {'pending', 'running', 'timed_out'}:
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
attempt.callback_id = callback
attempt.finished_at = datetime.utcnow()
@@ -121,7 +123,7 @@ def complete_attempt(
else:
# A missing callback may conceal a completed freight submission. A late
# transport error is not enough to safely release or retry that Artifact.
if attempt.status == 'timed_out' and not str(error_message or '').strip().lower().startswith('freight_rejected:'):
if attempt.status in {'timed_out', 'unknown'} and not str(error_message or '').strip().lower().startswith('freight_rejected:'):
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
attempt.error_message = str(error_message or 'Upload result remains unknown')[:500]
db.session.flush()
@@ -141,7 +143,7 @@ def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploa
"""超时后冻结 Artifact;仅迟到成功回调或货代明确拒绝才能解除未知结果。"""
if attempt.status != 'running':
return attempt
attempt.status = 'timed_out'
attempt.status = 'unknown'
attempt.finished_at = datetime.utcnow()
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
attempt.error_message = 'RPA callback timed out; freight submission must be reconciled before retry'