feat(shipping-notice): 优化货运订单履约流程与用户体验

- 优化聊天附件列表为横向可滚动布局并新增配套测试用例
- 移除自动填充默认用户消息逻辑,空备注时不再伪造默认正文
- 修复流程Gate动作展示逻辑,隐藏历史遗留操作与自动阶段无效按钮
- 完善库存匹配重试与订单快照冻结校验流程
- 优化进度展示优先级,优先显示人工待处理状态
- 移除Excel导出自动推导金额逻辑,强制使用Schema配置字段
- 新增货代通用报表RPA详细设计文档
- 更新相关测试用例与断言逻辑
This commit is contained in:
hugo committed 2026-08-13 00:17:01 +08:00
1 parent dc282f3b1d
commit 11cef575b4
51 files changed
+2197 -112

No files matched your search

@@ -172,12 +172,6 @@ def _mapping_value(
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':
@@ -467,9 +461,6 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
if line.id not in available_line_ids:
continue
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
@@ -1,5 +1,5 @@
"""
services/shipping_notice/fulfillment_audit.py
backend/app/services/shipping_notice/fulfillment_audit.py
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
@@ -148,6 +148,49 @@ def record_fulfillment_audit(
) from exc
def emit_stp_auto_create_blocked_manual_audit(
*,
case: Any | None,
job_id: int,
error_code: str,
next_action: str,
details: dict[str, Any] | None = None,
) -> None:
"""
记录 STP 自动建单业务阻断的人工处理审计事件。
核心逻辑:使用订单复核 Case 作为可选聚合,Job 作为稳定元数据引用;Worker 无请求上下文时仍可写入。
Args:
case: 可选 ShippingOrderReviewCase,优先提供 case_no;不得传入正文或凭据。
job_id: STP Job 主键。
error_code: 稳定业务阻断错误码。
next_action: 后续人工处理动作编码。
details: 脱敏诊断事实,仅允许审计元数据白名单字段。
Returns:
None。审计失败由 record_fulfillment_audit 按 strict 契约抛出。
"""
case_no = str(getattr(case, 'case_no', '') or '').strip() or None
metadata = {
'job_id': int(job_id),
'next_action': str(next_action or '').strip() or None,
**dict(details or {}),
}
record_fulfillment_audit(
event_type='stp_auto_create_blocked_manual',
aggregate_type='order_review_case' if case_no else 'shipping_job',
aggregate_id=case_no or str(job_id),
action='stp_auto_create_blocked_manual',
actor_type='worker',
task_no=case_no,
review_case_no=case_no,
reason_code=str(error_code or '').strip() or None,
error_code=str(error_code or '').strip() or None,
result='rejected',
metadata=metadata,
source='worker',
)
def record_access_audit(
*,
action: str,
@@ -27,7 +27,7 @@ from flask import current_app
from app import db
from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError
from app.models import ShippingNotice
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch
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 resolve_inventory_lines_for_execution
@@ -1170,6 +1170,10 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
'available_qty': float(available_qty) if available_qty is not None else 0.0,
'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0,
}
entry['line_status'] = (
'ok' if match_result == 'matched' and entry['shortage_qty'] <= 0
else 'shortage'
)
task.line_results_json.append(entry)
if match_result == 'matched':
has_ok = True
@@ -1441,8 +1445,12 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
),
matching_rule_version='stp_line_v2',
)
match_status = str(match_payload.get('match_status') or 'unfulfillable')
line_results = list(match_payload.get('line_results') or [])
# 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单,
# 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。
match_status, shortages = _recompute_task_match_aggregate(task)
line_results = list(task.line_results_json or [])
task.match_status = match_status
task.shortage_json = {'lines': shortages}
from app.services.shipping_notice.reservation_service import record_inventory_verification
verification = record_inventory_verification(
task, inventory_snapshot_id=task.inventory_snapshot_id,
@@ -299,6 +299,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh
source_type=str(task.inventory_connector_type or "").strip() or None,
warehouse_id=warehouse_id,
source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(),
source_query_json={'trigger_type': 'manual_upload'},
identity_status="pending",
snapshot_status="ready",
exported_at=datetime.utcnow(),
@@ -393,6 +394,7 @@ def save_task_inventory_file_from_local_path(
schema_preview_json=preview,
share_mode="task_only",
line_count=0,
source_query_json={'trigger_type': 'manual_upload'},
)
db.session.add(inv_file)
db.session.flush()
@@ -675,12 +675,27 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
校验 RPA 回调轮次契约(run_no + 幂等)。
核心逻辑:success/skipped/failed 共用;无有效触发或旧轮次/重放均拒绝。
"""
# Batch 回调顶层 run_no 是 batch identity;逐源 item 的 source_run_no
# 才是正式 Attempt identity。先按 source_run_no 接受当前 Attempt,避免
# per-source 已成功后又被 task-level batch_run_no 的旧 trigger 校验否决。
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', 'succeeded'}:
return None
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
@@ -872,9 +887,13 @@ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str,
def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
"""
合并 batch 顶层契约字段到 result item。
核心逻辑:仅合并 run_no / task_no;成功回调身份字段必须由 Worker 显式返回,禁止后端从任务补齐。
核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由
Worker item 显式返回,禁止后端从任务或数据库补齐。
"""
merged = dict(item)
top_schema_version = str(payload.get('schema_version') or '').strip()
if top_schema_version and not str(merged.get('schema_version') or '').strip():
merged['schema_version'] = top_schema_version
top_run_no = str(payload.get("run_no") or "").strip()
if top_run_no and not str(merged.get("run_no") or "").strip():
merged["run_no"] = top_run_no
@@ -1909,6 +1928,10 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
structure_check = validate_production_inventory_structure(
source_code=str(rpa_source['source_code']), path=ingest_path,
)
# RPA 来源已通过正式 Profile 结构校验;映射是确定性事实,不应再要求人工确认。
inv_file.field_mapping_json = dict(structure_check['field_mapping'])
inv_file.mapping_source = 'parsing_profile'
inv_file.mapping_confirmed = True
lines, column_meta = ingest_inventory_file(
ingest_path, move_to=None,
field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile',
@@ -1956,6 +1979,8 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
column_meta=column_meta,
source="rpa_callback",
event_type="inventory_rpa_ready",
field_mapping=dict(structure_check['field_mapping']),
mapping_source='parsing_profile',
commit=False,
)
item_savepoint.commit()
@@ -2245,6 +2270,21 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
})
else:
_handle_rpa_inventory_failed(task, merged_item, runtime, commit=False)
# 失败回调已把 Task 从 rpa_pending 还原为库存不可用;必须立即同步正式 Gate,
# 否则 Execution 仍是 waiting_external,前端会错误停在“系统处理中”。
if task.active_process_execution_id:
from app.models import ShippingProcessExecution
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
execution = db.session.get(
ShippingProcessExecution,
int(task.active_process_execution_id),
)
if execution is not None:
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
)
failed.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
@@ -2400,6 +2440,10 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
structure_check = validate_production_inventory_structure(
source_code=source_code, path=ingest_path,
)
# 定时预热快照同样经过正式 Profile 校验,后续绑定任务可直接匹配。
inv_file.field_mapping_json = dict(structure_check['field_mapping'])
inv_file.mapping_source = 'parsing_profile'
inv_file.mapping_confirmed = True
created_entry = {
"inventory_file_no": inv_file.inventory_file_no,
"source_code": inv_file.source_code or source_code,
@@ -2455,6 +2499,8 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
column_meta=column_meta,
source="rpa_batch_callback",
event_type="inventory_rpa_ready",
field_mapping=dict(structure_check['field_mapping']),
mapping_source='parsing_profile',
commit=False,
)
_mark_inventory_rpa_run_no_consumed(
@@ -2381,6 +2381,8 @@ def submit_order_extraction(
primary_run: ShippingOrderProcessingRun | None = None
any_reused = False
for index, intake_no in enumerate(list(intake_nos or [])):
# [STEP 2] 首个 Run 可能在空 conversation_id 下创建本地会话;后续 Intake
# 必须沿用该会话,避免一次多 EML 被拆成多个左侧对话。
created_run, reused_one = create_order_extraction_run(
user=user,
agent_id=owner_agent.id,
@@ -2395,6 +2397,7 @@ def submit_order_extraction(
any_reused = any_reused or reused_one
if primary_run is None:
primary_run = created_run
conversation_id = created_run.conversation_id
if primary_run is None:
raise ValidationError(
'intake_nos is required',
@@ -16,6 +16,8 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
物化 accepted Extraction(保留派生 field_lineage);建单前再次校验客户确认并
持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task
豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束;
新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照
Task 推入库存/RPA;
成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至
building_order(不关闭);同步 Process Execution 推进至 task_creation 通过,
避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox),
@@ -357,6 +359,24 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
if isinstance(run.input_snapshot_json, dict) else {}
)
configs = [item for item in definition.get('fields') or [] if isinstance(item, dict) and item.get('enabled', True)]
formal_line_codes = {
str(item.get('field_code') or '')
for item in configs
if str(item.get('scope') or '') == 'line' and item.get('field_code')
}
unknown_line_fields = sorted({
str(key)
for line in summary.get('lines') or []
if isinstance(line, dict)
for key in line
if str(key) not in formal_line_codes and not str(key).startswith('_')
})
if unknown_line_fields:
raise ValidationError(
'订单明细包含未在当前 Schema 中定义的字段',
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
details={'fields': unknown_line_fields, 'schema_version_id': int(case.current_draft.schema_version_id)},
)
normalized = _build_confirmation_normalized_result(case=case, summary=summary)
extraction = ShippingOrderExtraction(
run_id=int(run.id), intake_id=int(intake_id), schema_version_id=int(case.current_draft.schema_version_id),
@@ -1388,6 +1408,16 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
)
else:
try_auto_confirm_task_customer(task)
# [STEP] Review 确认建单与自动建单必须共享订单快照前置条件。
# 冻结失败由外层 AppError 回滚,不能留下已建单但库存链路无法启动的半成品。
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=int(task.order_data_version or 1),
freeze_mode='manual',
)
except AppError as err:
_reject_confirmation(
case,
@@ -443,11 +443,17 @@ def ensure_all_required_sources_prepared(
dict(legacy_rpa_source, **{'source_code': source_code}),
payload=per_source_payload,
)
if trigger_result:
new_att.trigger_file_path = str(trigger_result)
if not trigger_result:
# 没有真实文件就不能宣称 queued;否则 Gate 会显示等待 RPA,Worker 永远不会领取。
new_att.status = 'failed'
new_att.error_code = 'trigger_not_written'
new_att.error_message = '库存 RPA trigger 文件未生成'
new_att.execution_phase = 'trigger_write_failed'
new_att.updated_at = datetime.utcnow()
failed.append(source_code)
else:
new_att.trigger_file_path = trigger_fname
pending.append(source_code)
new_att.trigger_file_path = str(trigger_result)
pending.append(source_code)
except Exception as exc: # pragma: no cover - RPA 环境异常
new_att.status = 'failed'
new_att.error_code = 'trigger_write_error'
@@ -18,6 +18,7 @@ from __future__ import annotations
import hashlib
import json
import logging
from datetime import datetime
from typing import Any
from app.models import (
@@ -666,6 +667,74 @@ def _fulfillment_blocking_finding(
}]
def _supersede_auto_inventory_poll_for_rpa_failure(
*,
execution: ShippingProcessExecution,
task: ShippingNotice,
actor_type: str,
actor_id: str | int | None,
) -> None:
"""RPA 已耗尽时终止同 Gate 的自动轮询,释放业务结果回写。
自动轮询 Attempt 不产生新的库存事实;其在 RPA 已失败后继续 queued/running
会使 sync_gate_from_business_result 早退,Gate 永久停留 waiting_external。
仅处理 trigger_type=auto 且 action_code=poll_inventory_preparation,绝不终止
用户主动 retry_inventory_preparation。
"""
from app import db
from app.models import ShippingProcessGateAttempt
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
if (
str(task.process_status or '').strip() != 'waiting_inventory'
or str(task.pending_human_reason or '').strip() != PH_RPA_EXHAUSTED
):
return
gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code='inventory_preparation',
).with_for_update().first()
if gate is None:
return
active_attempts = (
ShippingProcessGateAttempt.query
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
ShippingProcessGateAttempt.trigger_type == 'auto',
)
.with_for_update()
.all()
)
now = datetime.utcnow()
for attempt in active_attempts:
snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {}
if str(snapshot.get('action_code') or '').strip() != 'poll_inventory_preparation':
continue
before = {'status': attempt.status, 'gate_code': gate.gate_code}
attempt.status = 'superseded'
attempt.finished_at = now
attempt.lease_token = None
attempt.lease_expires_at = None
attempt.error_code = 'rpa_callback_failed'
attempt.error_summary = 'RPA callback failed; automatic inventory poll superseded.'
record_fulfillment_audit(
event_type='process_gate_attempt_superseded',
aggregate_type='process_gate_attempt',
aggregate_id=str(attempt.id),
action='supersede_auto_inventory_poll',
actor_type=actor_type,
actor_id=actor_id,
task_no=str(task.task_no or '') or None,
reason_code='rpa_callback_failed',
before=before,
after={'status': 'superseded', 'gate_code': gate.gate_code},
metadata={'execution_no': execution.execution_no},
source='process_gate_bridge',
)
db.session.flush()
def sync_fulfillment_gates_from_task(
*,
execution: ShippingProcessExecution,
@@ -690,6 +759,13 @@ def sync_fulfillment_gates_from_task(
if task is None:
return
_supersede_auto_inventory_poll_for_rpa_failure(
execution=execution,
task=task,
actor_type=actor_type,
actor_id=actor_id,
)
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
@@ -711,9 +787,14 @@ def sync_fulfillment_gates_from_task(
match_passed = match_status in {'fulfillable', 'partial', 'unfulfillable'} or status in {
'matched', 'waiting_upload', 'upload_failed', *done_statuses,
}
# 仅当存在活跃库存文件且未确认映射时阻断;无文件但已有解析行视为映射已由 Profile 固化。
# 仅手动上传且未确认映射的文件允许进入人工字段映射;库存源/RPA 文件必须由
# 正式 Profile 在入库时确定性确认,不能因为历史快照缺少该标记而阻塞。
source_query = getattr(inv_file, 'source_query_json', None) if inv_file is not None else None
trigger_type = str((source_query or {}).get('trigger_type') or '').strip().lower() if isinstance(source_query, dict) else ''
is_manual_upload = trigger_type == 'manual_upload'
mapping_needed = (
inv_file is not None
and is_manual_upload
and not mapping_confirmed
and status not in {'matched', 'waiting_upload', 'upload_failed', *done_statuses}
)
@@ -753,7 +834,9 @@ def sync_fulfillment_gates_from_task(
preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first()
except Exception: # noqa: BLE001
preparation = None
if preparation is not None:
# 已绑定库存行代表正式快照已成功落库;历史 PreparationAttempt 即使仍标为
# waiting_external,也只能保留审计,不能覆盖当前任务事实并阻止进入匹配。
if preparation is not None and not has_inventory_lines:
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'}]
@@ -767,7 +850,10 @@ def sync_fulfillment_gates_from_task(
'pending_sources': pending,
'failed_sources': failed,
})
if preparation.status in {'queued', 'running', 'waiting_external'} or pending:
# Task 已明确 rpa_exhausted 时,Preparation 的旧 waiting_external 不能
# 继续把 Gate 投影成系统处理中;Preparation 保留 waiting 作为原始审计事实。
task_rpa_exhausted = str(task.pending_human_reason or '').strip() == 'rpa_exhausted'
if not task_rpa_exhausted and (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},
@@ -793,17 +879,25 @@ def sync_fulfillment_gates_from_task(
)
# Continue below for mapping/matching facts.
if status == 'waiting_inventory':
from app.services.shipping_notice.constants import PH_RPA_PENDING
waiting_reason = (
'inventory_rpa_queued'
if str(task.pending_human_reason or '').strip() == PH_RPA_PENDING
else 'inventory_preparation_waiting'
)
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
pending_reason = str(task.pending_human_reason or '').strip()
# 只有 Worker 已领取/等待回调才是 waiting_external。RPA 失败或次数耗尽时
# 必须退出自动处理中,回到可恢复 Gate,不能因 process_status 相同再次自动入队。
if pending_reason == PH_RPA_PENDING:
outcome = 'waiting_external'
waiting_reason = 'inventory_rpa_queued'
elif pending_reason == PH_RPA_EXHAUSTED:
outcome = 'blocked_manual'
waiting_reason = 'inventory_rpa_exhausted'
else:
outcome = 'blocked_retryable'
waiting_reason = inventory_preparation_reason_code(task) or 'inventory_preparation_failed'
apply_gate_outcome(
execution=execution,
gate_code='inventory_preparation',
passed=False,
outcome='waiting_external',
outcome=outcome,
effective_result={
'findings': _fulfillment_blocking_finding(
gate_code='inventory_preparation',
@@ -894,7 +988,9 @@ def sync_fulfillment_gates_from_task(
execution=execution,
gate_code='inventory_matching',
passed=match_passed,
outcome='blocked_manual' if (not match_passed and status in {'pending_review', 'inventory_ready'}) else None,
# 库存快照已就绪但 match_status 未落终态表示匹配自动推进已中断。此时必须
# 提供 retry_inventory_matching,不能保留 pending 并伪装为系统处理中。
outcome='blocked_retryable' if not match_passed else None,
effective_result={
'findings': (
[] if match_passed else _fulfillment_blocking_finding(
@@ -15,6 +15,7 @@ from __future__ import annotations
from typing import Any, Callable
from app import db
from app.core.errors import ValidationError
from app.models import (
ShippingOrderDocument,
@@ -762,14 +763,33 @@ def _handle_retry_inventory_preparation(
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
recovery_plan_id = payload.get('recovery_plan_id')
# Gate Worker 通过 _task_payload 传递 operator_id;人工 API 可能传 actor_user_id/user_id。
# 三者必须统一,否则冻结订单快照会收到 None,并在 RPA Attempt/trigger 创建前失败。
actor_id = (
payload.get('actor_user_id')
or payload.get('user_id')
or payload.get('operator_id')
)
preparation_round = None
if task is not None and payload.get('action_code') != 'poll_inventory_preparation':
# 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实,
# 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。
if not task.order_snapshot_id:
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
freeze_order_snapshot(
task,
actor_id=actor_id,
expected_order_data_version=int(task.order_data_version or 1),
freeze_mode='manual',
)
db.session.flush()
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'),
actor_id=actor_id,
)
preparation_round = create_inventory_preparation_round(
task=task,
@@ -107,6 +107,7 @@ def _resolve_recovery_next_action(
blocking_gate_code = str((blocking or {}).get('gate_code') or '').strip().lower()
normalized_reason = str((blocking or {}).get('blocking_reason_code') or '').strip().lower()
status = str((blocking or {}).get('status') or '').strip().lower()
has_formal_task = bool(execution and getattr(execution, 'task_id', None))
# [STEP 1] 库存准备失败统一允许业务用户手动重新获取库存;人工上传是辅助输入入口。
if blocking_gate_code == 'inventory_preparation':
@@ -114,6 +115,13 @@ def _resolve_recovery_next_action(
if inventory_action:
return inventory_action, False
# 库存匹配失败属于业务可恢复阻断;即使 Gate 责任方是 worker,
# 业务用户仍必须能重新提交匹配,不能只投影“可重试”状态而隐藏按钮。
if blocking_gate_code == 'inventory_matching' and (
has_formal_task or status == 'blocked_retryable'
):
return 'retry_inventory_matching', False
# [STEP 2] 货代上传 RPA 失败 / 人工交接失败:保持统一的 RPA 重试入口。
if (
blocking_gate_code == 'freight_upload_rpa'
@@ -143,10 +151,11 @@ def _resolve_recovery_next_action(
next_action = None
technical_auto_only = True
# RecoveryPlan 复核入口兜底(inventory_matching / inventory_sufficiency)。
# RecoveryPlan 复核入口兜底(建单前 inventory_matching / inventory_sufficiency)。
# 正式 OT 的库存匹配只能重试,不能下发无写操作的复核导航入口。
if not next_action:
recovery_targets = full.get('recovery_targets') or []
if recovery_targets and blocking_gate_code == 'inventory_matching':
if recovery_targets and blocking_gate_code == 'inventory_matching' and not has_formal_task:
next_action = 'open_inventory_match_review'
technical_auto_only = False
elif recovery_targets and blocking_gate_code == 'inventory_sufficiency':
@@ -428,6 +437,23 @@ def _navigation_for_action(action_code: str | None, refs: dict[str, Any]) -> dic
return None
def _has_confirmed_inventory_for_matching(execution: ShippingProcessExecution) -> bool:
"""判断 pending 匹配 Gate 是否已有可复用的已确认库存快照。"""
if not execution.task_id:
return False
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
task = ShippingNotice.query.get(int(execution.task_id))
if task is None or not isinstance(task.inventory_lines_json, list) or not task.inventory_lines_json:
return False
inventory_file = active_inventory_file_for_task(task)
return bool(
inventory_file is not None
and bool(getattr(inventory_file, 'mapping_confirmed', False))
)
def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, Any]:
"""
用户端安全投影:唯一当前阻断 + 主要恢复动作;不含管理员诊断 JSON。
@@ -482,6 +508,20 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
}
current = full.get('current_gate')
blocking = None
if (
isinstance(current, dict)
and str(current.get('gate_code') or '').strip().lower() == 'inventory_field_mapping'
and str(current.get('status') or '').strip().lower() == 'pending'
):
current = {**current, 'status': 'blocked_manual', 'next_action_code': 'confirm_inventory_field_mapping'}
if (
isinstance(current, dict)
and str(current.get('gate_code') or '').strip().lower() == 'inventory_matching'
and str(current.get('status') or '').strip().lower() == 'pending'
and _has_confirmed_inventory_for_matching(execution)
):
# 库存快照已确认但匹配未落终态,说明自动推进已中断;不能继续显示系统处理中。
current = {**current, 'status': 'blocked_retryable', 'next_action_code': 'retry_inventory_matching'}
if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | {
'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated',
}:
@@ -525,6 +565,16 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
allowed_actions: list[str] = []
action_items: list[dict[str, str]] = []
is_formal_inventory_matching = bool(
getattr(execution, 'task_id', None)
and str((blocking or {}).get('gate_code') or '').strip().lower() == 'inventory_matching'
)
recovery_targets = full.get('recovery_targets') or []
if is_formal_inventory_matching:
recovery_targets = [
target for target in recovery_targets
if str(target.get('action_code') or '').strip() == 'retry_inventory_from_preparation'
]
if blocking:
if next_action and is_business_user_action(str(next_action)):
allowed_actions.append(str(next_action))
@@ -533,7 +583,7 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
and next_action == 'retry_inventory_preparation'
):
allowed_actions.append('upload_inventory_file')
for target in full.get('recovery_targets') or []:
for target in recovery_targets:
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)
@@ -569,7 +619,7 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
'current_gate': current,
'current_blocking_gate': blocking,
# 客户端只消费服务端已校验的恢复目标,不自行推导跨 Gate 路径。
'recovery_targets': full.get('recovery_targets') or [],
'recovery_targets': recovery_targets,
'active_recovery_plans': full.get('active_recovery_plans') or [],
'blocking_reason_code': reason_code,
'blocking_message': _user_facing_blocking_message(reason_code),
@@ -109,6 +109,20 @@ def get_execution_by_no(execution_no: str) -> ShippingProcessExecution:
return row
def _primary_recovery_action(
*, execution: ShippingProcessExecution, gate: ShippingProcessGate,
) -> str | None:
"""按用户投影同一事实裁决当前 Gate 的可提交主恢复动作。"""
if gate.gate_code == 'inventory_preparation':
return inventory_preparation_primary_action(gate.status)
# 正式 OT 的库存匹配不再接受仅导航的旧 Gate 动作;历史行仍保留原值供审计。
if gate.gate_code == 'inventory_matching' and execution.task_id:
return 'retry_inventory_matching'
return gate.next_action_code or primary_next_action_for_gate(
gate_code=gate.gate_code, status=gate.status,
)
def request_gate_action(
*,
execution_no: str,
@@ -218,10 +232,7 @@ def request_gate_action(
details={'gate_code': gate.gate_code, 'action_code': action},
)
primary = inventory_preparation_primary_action(gate.status) if gate.gate_code == 'inventory_preparation' else None
primary = primary or gate.next_action_code or primary_next_action_for_gate(
gate_code=gate.gate_code, status=gate.status,
)
primary = _primary_recovery_action(execution=execution, gate=gate)
# [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA
# 重试,但数据库 Gate 行可能仍保留 regenerate_manual_upload_todo。
# 这里必须与用户投影使用同一 Gate/原因事实,否则点击必然被主动作校验拒绝。
@@ -765,8 +765,16 @@ def _enqueue_auto_progress_after_gate_pass(
if next_gate is None or not next_gate.next_action_code:
return
definition = get_process_gate_definition(next_gate.gate_code)
# default_next_actions 中可恢复不等于可自动执行。库存匹配等动作必须由
# 用户明确点击;否则库存准备通过后会立刻消费“重试库存匹配”按钮,页面
# 只剩被自动执行后的结果,用户无法控制重试时机。
if str(definition.get('responsible_party') or '') not in {'system', 'worker'}:
return
if (
next_gate.next_action_code in {'retry_inventory_matching'}
or str(next_gate.next_action_code).startswith('open_')
):
return
attempt = queue_gate_attempt(
execution_no=str(execution.execution_no),
gate_code=next_gate.gate_code,
@@ -911,7 +919,33 @@ def sync_gate_from_business_result(
.first()
)
if active_attempt is not None:
return gate
# 库存快照已落库时,自动轮询已获得其等待的正式事实。直接复用此 Attempt
# 完成库存准备,避免先终止后重新排队时被自动推进器插入新的轮询。用户主动
# Attempt 绝不在这里完成或覆盖。
snapshot = (
active_attempt.input_snapshot_json
if isinstance(active_attempt.input_snapshot_json, dict)
else {}
)
inventory_ready = bool(
gate_code == 'inventory_preparation'
and passed
and isinstance(effective_result_json, dict)
and effective_result_json.get('has_inventory_lines')
)
is_auto_poll = (
active_attempt.trigger_type == 'auto'
and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation'
)
if not inventory_ready or not is_auto_poll:
return gate
return complete_gate_attempt(
attempt_id=int(active_attempt.id),
outcome='passed',
output_snapshot=effective_result_json,
recommendation_json=recommendation_json,
effective_result_json=effective_result_json,
)
if allow_repass and gate.status == 'passed':
gate.status = 'invalidated'
@@ -290,6 +290,7 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = (
'open_inventory_match_review',
'open_shortage_review',
'upload_inventory_file',
'retry_inventory_matching',
'retry',
'refresh',
'regenerate_excel',
@@ -9,6 +9,7 @@ services/shipping_notice/rpa.py
from __future__ import annotations
import json
import os
import shutil
from datetime import datetime
from pathlib import Path
@@ -837,11 +837,19 @@ def _order_task_current_gate(
notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id))
if notice is not None:
execution = (
ShippingProcessExecution.query.filter_by(task_id=int(notice.id))
.order_by(ShippingProcessExecution.id.desc())
.first()
)
execution = None
active_execution_id = getattr(notice, 'active_process_execution_id', None)
if active_execution_id is not None:
execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
if execution is not None and int(getattr(execution, 'task_id', 0) or 0) != int(notice.id):
execution = None
if execution is None:
execution = (
ShippingProcessExecution.query.filter_by(task_id=int(notice.id))
.filter(ShippingProcessExecution.status != 'superseded')
.order_by(ShippingProcessExecution.id.desc())
.first()
)
if execution is not None:
summary = project_user_gate_summary(execution)
blocking = summary.get('current_blocking_gate') or summary.get('current_gate')
@@ -1015,6 +1023,14 @@ def _project_order_task_work_item(
if shared_code in SHIPPING_PROCESSING_STAGES:
stage = shared_code
stage_label_key = str(shared.get('label_key') or '').strip() or None
active_execution_id = getattr(notice_for_stage, 'active_process_execution_id', None)
if active_execution_id is not None:
from app.models import ShippingProcessExecution
active_execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
active_gate = str(getattr(active_execution, 'current_gate_code', '') or '').strip().lower()
if active_gate in SHIPPING_PROCESSING_STAGES:
stage = active_gate
stage_label_key = active_gate
# order_creating 无共享投影时仍统一用户文案键。
if not stage_label_key and stage == 'order_creating':
stage_label_key = 'waiting_system_start'