feat(shipping-notice): 实现对话级批量重试自动推进功能,优化库存与PDF匹配逻辑

- 新增对话级批量重试自动推进的完整链路:后端服务、API、数据投影逻辑
- 前端新增对话级重试按钮、多语言国际化支持与API类型定义
- 优化行级库存重试控制,新增retryable字段统一管控重试按钮展示,清理废弃的view_fulfillment_detail动作,标准化前端动作码排序逻辑
- 修复PDF坐标匹配的fail-close防护逻辑,避免生成伪精确匹配分数
- 调整订单确认后流程,提前进入库存获取阶段,移除冗余的确认建单按钮,优化用户流转体验
- 新增对应单元测试用例覆盖核心业务逻辑
This commit is contained in:
hugo committed 2026-08-07 16:30:45 +08:00
1 parent fd6a23f870
commit 1008911a7e
41 files changed
+3956 -1256

No files matched your search

+93 -34
View File
@@ -498,6 +498,30 @@ def workspace_shipping_conversation_batch_workspace(conversation_id: str):
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
@workspace_shipping_notice_bp.route(
'/shipping-conversations/<conversation_id>/retry-auto-progress',
methods=['POST'],
)
def workspace_retry_conversation_auto_progress(conversation_id: str):
"""
对话级「重试自动推进」:扫描会话下可恢复 Case/正式 OT 并逐对象重试。
核心逻辑:委托 conversation_retry_auto_progress_service;前端不提交对象列表;
返回 summary + items;写 conversation_retry_auto_progress 汇总审计。
"""
user = _require_user()
data = request.get_json(silent=True) or {}
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
retry_auto_progress_for_conversation,
)
return _ok(retry_auto_progress_for_conversation(
user_id=int(user.id),
conversation_id=str(conversation_id or '').strip(),
reason=str(data.get('reason') or 'user_retry_auto_progress'),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
def workspace_create_shipping_task_from_notice():
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
@@ -649,27 +673,56 @@ def workspace_shipping_task_chat_actions(task_no: str):
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
def workspace_retry_shipping_task(task_no: str):
"""
重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。
用户侧重试当前正式 OT:统一决策器选择 resolve_source / fetch / rematch / auto_progress。
核心逻辑:注入当前用户为操作人,保证 TaskEvent / 统一审计可追溯。
核心逻辑:委托 task_retry_decision_service.retry_task_with_decision(scope=task);
不再直接调用通用 retry_task 重置编排器。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
payload = {
'task_id': task.task_no,
'operator_id': user.id,
'actor_id': user.id,
'_trusted_user_id': user.id,
'event_source': 'workspace_api',
}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
return _ok(shipping_tools.retry_task(payload))
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
return _ok(retry_task_with_decision(
task_no=str(task.task_no),
user_id=int(user.id),
scope='task',
reason=str(data.get('reason') or data.get('comment') or 'user_retry'),
trigger='user_retry',
continue_auto_progress=False,
))
@workspace_shipping_notice_bp.route(
'/shipping-tasks/<task_no>/lines/<line_key>/retry',
methods=['POST'],
)
def workspace_retry_shipping_task_line(task_no: str, line_key: str):
"""
行级统一「重试」:与任务级共用决策器,scope=line。
核心逻辑:前端不传内部动作码;后端按行库存事实选择 fetch/rematch/needs_human。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
_assert_fulfillment_task_ownership(task, user.id)
data = request.get_json(silent=True) or {}
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
return _ok(retry_task_with_decision(
task_no=str(task.task_no),
user_id=int(user.id),
scope='line',
line_key=str(line_key or '').strip(),
reason=str(data.get('reason') or 'user_retry_inventory'),
trigger='user_line_retry',
continue_auto_progress=False,
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
def workspace_confirm_shipping_inventory_source(task_no: str):
@@ -943,34 +996,40 @@ def workspace_remove_shipping_notice_line(task_no: str):
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
def workspace_auto_progress_shipping_task(task_no: str):
"""
用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。
系统/确认后调度兼容入口:内部委托统一决策器(continue_auto_progress=True)。
核心逻辑:标记 source=workspace_api 并注入操作人,避免用户触发被记成匿名 system。
核心逻辑:用户界面不应再调用本接口;用户重试走 /retry 或对话级 API。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
payload: dict = {
'task_id': task.task_no,
'source': 'workspace_api',
'operator_id': user.id,
'actor_id': user.id,
'_trusted_user_id': user.id,
}
for key in ('lang', 'locale', 'language'):
if data.get(key):
payload[key] = data[key]
break
result = shipping_tools.auto_progress(payload)
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
if isinstance(result, dict) and result.get('status') == 'ok':
gen_data = result.get('data')
if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
result = {**result, 'data': gen_data}
result = retry_task_with_decision(
task_no=str(task.task_no),
user_id=int(user.id),
scope='task',
reason=str(data.get('reason') or 'system_auto_progress'),
trigger='system_auto_progress',
continue_auto_progress=True,
)
# 兼容旧前端:若仍有 export 路径则附带 download_url。
if isinstance(result, dict) and result.get('status') in {'completed', 'running', 'ok'}:
# 重新加载任务以读取 export_file_path(若决策器已推进到导出)。
refreshed = get_task_for_user(task_no, user.id)
export_path = getattr(refreshed, 'export_file_path', None) if refreshed is not None else None
if export_path:
result = {
**result,
'data': {
**dict(result.get('data') or {}),
'export_file_path': export_path,
'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export',
},
}
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
@@ -0,0 +1,463 @@
"""
services/shipping_notice/conversation_retry_auto_progress_service.py
用途:对话级「重试自动推进」投影与批量执行(Case STP / 正式 OT 统一决策器)。
依赖:order_review_projection、order_stp_auto_create_service、task_retry_decision_service、
fulfillment_audit、ShippingOrderReviewCase / ShippingOrderProcessingRun / ShippingNotice。
逻辑:eligible 唯一依据 automation.retryable=true;建单前 Case→retry_stp_auto_create,
正式 OT→task_retry_decision_service(与任务级 /retry 同源);不批量行库存;
写 conversation_retry_auto_progress 汇总审计,对象级审计由既有链路写入。
"""
from __future__ import annotations
import logging
from typing import Any
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import (
ShippingNotice,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
)
_LOGGER = logging.getLogger(__name__)
ACTION_RETRY_AUTO_PROGRESS = 'retry_auto_progress'
ACTION_RETRY_STP = 'retry_stp_auto_create'
OBJECT_REVIEW_CASE = 'review_case'
OBJECT_FORMAL_TASK = 'formal_task'
def project_conversation_allowed_actions(
*,
user_id: int,
conversation_id: str,
) -> list[dict[str, Any]]:
"""
投影对话级可执行动作(当前仅重试自动推进)。
核心逻辑:扫描会话下 Case;automation.retryable=true 计入 eligible_count;
无合格对象时返回空列表(前端不渲染禁用空按钮)。
Args:
user_id: 当前用户。
conversation_id: 会话 ID。
Returns:
``[{code, eligible_count}]`` 或 ``[]``。
"""
normalized = str(conversation_id or '').strip()
if not normalized or not user_id:
return []
eligible = _list_eligible_targets(user_id=int(user_id), conversation_id=normalized)
if not eligible:
return []
return [{
'code': ACTION_RETRY_AUTO_PROGRESS,
'eligible_count': len(eligible),
}]
def retry_auto_progress_for_conversation(
*,
user_id: int,
conversation_id: str,
reason: str | None = None,
) -> dict[str, Any]:
"""
对话级批量重试自动推进。
核心逻辑:按 conversation_id 服务端扫描;逐对象重读最新 automation 后执行;
Case→STP(内部 refresh_validation);正式 OT→auto_progress;不批量行库存。
Args:
user_id: 操作人。
conversation_id: 会话 ID。
reason: 可选原因(写入审计 metadata)。
Returns:
``{conversation_id, summary, items}``。
Raises:
ValidationError: conversation_id 为空。
NotFoundError: 会话下无可访问对象且会话不存在于用户范围。
"""
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
normalized = str(conversation_id or '').strip()
if not normalized:
raise ValidationError('conversation_id is required')
cases = _list_conversation_cases(user_id=int(user_id), conversation_id=normalized)
if not cases and not _conversation_has_any_asset(user_id=int(user_id), conversation_id=normalized):
raise NotFoundError('Conversation not found')
items: list[dict[str, Any]] = []
for case in cases:
items.append(_retry_one_case(user_id=int(user_id), case=case))
summary = _summarize_items(items)
record_fulfillment_audit(
event_type='conversation_retry_auto_progress',
aggregate_type='shipping_conversation',
aggregate_id=normalized,
action='retry_auto_progress',
actor_id=int(user_id),
conversation_id=normalized,
owner_user_id=int(user_id),
result='success' if summary['failed'] == 0 else 'partial',
metadata={
'reason': str(reason or 'user_retry_auto_progress')[:200],
'summary': summary,
'items': items,
},
source='api',
)
try:
db.session.commit()
except Exception: # noqa: BLE001
db.session.rollback()
_LOGGER.exception('conversation retry audit commit failed conversation_id=%s', normalized)
return {
'conversation_id': normalized,
'summary': summary,
'items': items,
}
def _conversation_has_any_asset(*, user_id: int, conversation_id: str) -> bool:
"""会话是否存在属于当前用户的 Run / 正式任务(用于 404 判定)。"""
run_exists = (
ShippingOrderProcessingRun.query
.filter_by(user_id=int(user_id), conversation_id=conversation_id)
.limit(1)
.first()
)
if run_exists is not None:
return True
notice_exists = (
ShippingNotice.query
.filter_by(user_id=int(user_id), conversation_id=conversation_id)
.limit(1)
.first()
)
return notice_exists is not None
def _list_conversation_cases(*, user_id: int, conversation_id: str) -> list[ShippingOrderReviewCase]:
"""
列出会话下全部复核 Case(按 id 升序,稳定执行顺序)。
核心逻辑:经 ProcessingRun.conversation_id + user_id 关联,禁止跨会话/跨用户。
"""
return (
db.session.query(ShippingOrderReviewCase)
.join(
ShippingOrderProcessingRun,
ShippingOrderReviewCase.run_id == ShippingOrderProcessingRun.id,
)
.filter(
ShippingOrderProcessingRun.conversation_id == conversation_id,
ShippingOrderProcessingRun.user_id == int(user_id),
)
.order_by(ShippingOrderReviewCase.id.asc())
.all()
)
def _automation_for_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""投影 Case automation(与工作台同源)。"""
from app.services.shipping_notice.order_review_projection import (
_project_case_automation_status,
_project_post_confirm_auto_progress,
)
from app.services.shipping_notice.order_review_workbench_projection import (
enrich_automation_status,
resolve_formal_ot,
)
draft = case.current_draft
validation = dict(draft.validation_result_json or {}) if draft is not None else None
post_confirm = _project_post_confirm_auto_progress(case)
automation = _project_case_automation_status(
case,
validation=validation,
post_confirm=post_confirm,
)
formal_ot = resolve_formal_ot(case)
return enrich_automation_status(
automation if isinstance(automation, dict) else {},
formal_ot=formal_ot,
is_admin=False,
)
def _formal_task_no(case: ShippingOrderReviewCase, automation: dict[str, Any]) -> str | None:
"""解析正式 OT 编号(有则走 auto-progress,无则走 STP)。"""
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
formal = resolve_formal_ot(case)
if formal.get('task_missing'):
return None
if not formal.get('has_formal_ot'):
return None
task_no = str(
automation.get('task_no')
or getattr(case, 'confirmed_task_no', None)
or ''
).strip()
return task_no or None
def _list_eligible_targets(*, user_id: int, conversation_id: str) -> list[dict[str, Any]]:
"""扫描可重试对象(仅 retryable=true)。"""
targets: list[dict[str, Any]] = []
for case in _list_conversation_cases(user_id=user_id, conversation_id=conversation_id):
automation = _automation_for_case(case)
if not bool(automation.get('retryable')):
continue
task_no = _formal_task_no(case, automation)
if task_no:
targets.append({
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'case_no': case.case_no,
})
elif not case.confirmed_task_id:
targets.append({
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'case_no': case.case_no,
})
return targets
def _skip_reason_from_automation(automation: dict[str, Any], *, task_missing: bool) -> str | None:
"""
根据最新 automation 返回跳过原因;可执行时返回 None。
核心逻辑:queued/running/completed/task_missing 跳过;needs_human 跳过;
manual_fallback 的 owner_type=human 仍可 retryable,不得误判为人工阻断跳过。
"""
if task_missing:
return 'task_missing'
status = str(automation.get('status') or '').strip().lower()
if status in {'queued', 'running'}:
return 'already_running'
if status in {'completed', 'succeeded'}:
return 'already_completed'
if status == 'needs_human':
return 'human_blocking'
if not bool(automation.get('retryable')):
return 'not_retryable'
return None
def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, Any]:
"""
对单个 Case 执行重试或跳过。
核心逻辑:重读 automation;正式 OT→auto_progress;否则 STP;异常映射为 failed/skipped。
"""
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
automation = _automation_for_case(case)
formal = resolve_formal_ot(case)
task_missing = bool(formal.get('task_missing'))
task_no = _formal_task_no(case, automation)
if task_no:
skip = _skip_reason_from_automation(automation, task_missing=task_missing)
if skip:
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': None,
'outcome': 'skipped',
'reason_code': skip,
}
return _execute_formal_task_retry(user_id=user_id, task_no=task_no)
if task_missing or case.confirmed_task_id:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': None,
'outcome': 'skipped',
'reason_code': 'task_missing' if task_missing else 'already_confirmed',
}
skip = _skip_reason_from_automation(automation, task_missing=False)
if skip:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': None,
'outcome': 'skipped',
'reason_code': skip,
}
return _execute_stp_retry(user_id=user_id, case_no=str(case.case_no))
def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
"""调用既有 STP retry;捕获业务错误为逐对象 outcome。"""
from app.services.shipping_notice.order_stp_auto_create_service import (
retry_stp_auto_create_for_case,
)
try:
result = retry_stp_auto_create_for_case(user_id=user_id, case_no=case_no)
status = str(result.get('status') or '').strip().lower()
if status in {'queued', 'reused', 'enqueued'}:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case_no,
'action': ACTION_RETRY_STP,
'outcome': 'queued',
'reason_code': None,
}
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case_no,
'action': ACTION_RETRY_STP,
'outcome': 'skipped',
'reason_code': status or 'not_retryable',
}
except AppError as err:
code = str(getattr(err, 'code', None) or 'SHIPPING.STP_ENQUEUE_FAILED')
if 'ALREADY_CONFIRMED' in code:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case_no,
'action': None,
'outcome': 'skipped',
'reason_code': 'already_confirmed',
}
if 'NOT_ELIGIBLE' in code:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case_no,
'action': ACTION_RETRY_STP,
'outcome': 'failed',
'reason_code': code,
}
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case_no,
'action': ACTION_RETRY_STP,
'outcome': 'failed',
'reason_code': code,
}
except Exception: # noqa: BLE001
_LOGGER.exception('conversation STP retry failed case_no=%s', case_no)
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case_no,
'action': ACTION_RETRY_STP,
'outcome': 'failed',
'reason_code': 'SHIPPING.STP_ENQUEUE_FAILED',
}
def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
"""正式 OT 重试:委托统一决策器(与任务级 /retry 同源)。"""
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
try:
result = retry_task_with_decision(
task_no=str(task_no),
user_id=int(user_id),
scope='task',
reason='conversation_retry_auto_progress',
trigger='conversation_retry',
continue_auto_progress=False,
)
except AppError as err:
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'failed',
'reason_code': str(getattr(err, 'code', None) or 'SHIPPING.AUTO_PROGRESS_FAILED'),
}
except Exception: # noqa: BLE001
_LOGGER.exception('conversation task retry failed task_no=%s', task_no)
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'failed',
'reason_code': 'SHIPPING.AUTO_PROGRESS_FAILED',
}
status = str((result or {}).get('status') or '').strip().lower()
action = str((result or {}).get('action') or '') or ACTION_RETRY_AUTO_PROGRESS
if status == 'needs_human':
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': action,
'outcome': 'skipped',
'reason_code': str((result or {}).get('reason_code') or 'human_blocking'),
}
if status == 'failed':
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': action,
'outcome': 'failed',
'reason_code': str((result or {}).get('reason_code') or status),
}
if action == 'noop' and str((result or {}).get('reason_code') or '') == 'already_running':
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': action,
'outcome': 'skipped',
'reason_code': 'already_running',
}
if action == 'noop' and status == 'completed':
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': action,
'outcome': 'skipped',
'reason_code': str((result or {}).get('reason_code') or 'already_completed'),
}
if status in {'running', 'completed', 'queued'}:
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': action,
'outcome': 'queued',
'reason_code': None,
}
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': action,
'outcome': 'skipped',
'reason_code': str((result or {}).get('reason_code') or status or 'not_retryable'),
}
def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]:
"""汇总逐对象结果。"""
retried = skipped = failed = 0
for item in items:
outcome = str(item.get('outcome') or '').strip().lower()
if outcome == 'queued':
retried += 1
elif outcome == 'failed':
failed += 1
else:
skipped += 1
return {
'total': len(items),
'retried': retried,
'skipped': skipped,
'failed': failed,
}
@@ -13,15 +13,29 @@ def _coordinate_mapping(value: Any) -> dict[str, Any]:
return dict(value) if isinstance(value, dict) else {}
def _append_issue(layout: dict[str, Any], issue: str) -> None:
"""稳定追加坐标恢复失败码,不改变原 issues 相对顺序。"""
existing = layout.get('issues') if isinstance(layout.get('issues'), list) else []
issues = [str(item) for item in existing]
if issue not in issues:
issues.append(issue)
layout['issues'] = issues
def ensure_on_demand_coordinate_evidence(
*, document: ShippingOrderDocument, layout: dict[str, Any], page_nos: set[int] | None,
table_by_page: dict[int, dict[str, Any] | list[dict[str, Any]]] | None = None,
) -> dict[str, Any]:
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。"""
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。
【AI/调用方触发时机】:
- 订单字段重放、模板匹配或明细重建前,为当前 snapshot 恢复缺失页的真实坐标。
- 失败不静默;任何 PDFium/OCR 失败都会在 layout['issues'] 追加稳定失败码,
上游可据此将 matcher 从 no_match 转为 evidence_insufficient。
"""
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
return layout
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
# 兼容历史布局快照:布局任务曾将坐标证据写在顶层,正式抽取仍需复用它。
if not evidence:
legacy_keys = ('pages', 'page_glyphs', 'sources', 'tables')
evidence = {
@@ -29,7 +43,6 @@ def ensure_on_demand_coordinate_evidence(
for key in legacy_keys
if isinstance(layout.get(key), dict)
}
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
current_version = getattr(document, 'current_layout_version', None)
current_payload = getattr(current_version, 'payload_json', None)
if isinstance(current_payload, dict):
@@ -44,7 +57,15 @@ def ensure_on_demand_coordinate_evidence(
sources = _coordinate_mapping(evidence.get('sources'))
source_pages = _coordinate_mapping(sources.get('pages'))
tables = _coordinate_mapping(evidence.get('tables'))
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
# [FAIL-CLOSED GATE] page_glyphs 必须对所需页真实存在;不能用 pages 元数据或
# 非数字脏键来假装已恢复。MinerU HTML 表 + 空 page_glyphs 的组合必须继续走
# 真实 PDFium/OCR 抽取,否则会退化为"伪精确匹配分数"。
present_pages = {
int(key) for key in page_glyphs
if str(key).isdigit() and isinstance(page_glyphs.get(key), list) and len(page_glyphs.get(key) or []) > 0
}
needs_recovery = bool(page_nos is None) or not page_nos.issubset(present_pages)
if not needs_recovery:
return layout
tables_by_page: dict[int, list[dict[str, Any]]] = {}
for raw_table in layout.get('tables') or []:
@@ -70,11 +91,15 @@ def ensure_on_demand_coordinate_evidence(
)
asset = db.session.get(FileAsset, int(document.asset_id))
if asset is None:
_append_issue(layout, 'coordinate_evidence_asset_missing')
return layout
try:
native_pages = extract_native_pdf_pages(read_asset_bytes(asset))
except Exception:
# [FAIL-CLOSED] PDFium 级异常必须显式上报;禁止用 MinerU HTML 列名顶替坐标。
_append_issue(layout, 'coordinate_evidence_native_pdf_unavailable')
return layout
recovered_any_page = False
for page in native_pages:
if page_nos is not None and int(page.page_no) not in page_nos:
continue
@@ -87,12 +112,14 @@ def ensure_on_demand_coordinate_evidence(
source = 'ocr_coordinate'
except Exception:
glyphs = []
_append_issue(layout, f'coordinate_evidence_ocr_failed_page_{page.page_no}')
if not glyphs:
continue
page_key = str(page.page_no)
pages[page_key] = {'width': page.width, 'height': page.height}
page_glyphs[page_key] = glyphs
source_pages[page_key] = source
recovered_any_page = True
for table in tables_by_page.get(int(page.page_no), []):
table_id = str(table.get('table_id') or '')
chars = _native_characters_in_table(
@@ -107,6 +134,8 @@ def ensure_on_demand_coordinate_evidence(
chars = []
if table_id and chars:
tables[table_id] = chars
if page_nos is not None and not recovered_any_page:
_append_issue(layout, 'coordinate_evidence_no_page_recovered')
next_layout = dict(layout)
next_layout['coordinate_evidence'] = {
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
@@ -119,7 +119,22 @@ def match_frozen_coordinate_profiles(
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
if not pages or (not glyph_tables and not page_glyphs and not tables):
# [FAIL-CLOSED GATE] 第零层:on-demand 坐标恢复显式失败时直接拒绝匹配。
# 任何 coordinate_evidence_* 失败码都意味着正式证据不可用,MinerU HTML 列名
# 不得作为坐标模板匹配的替代事实源。
layout_issues = {str(item) for item in (layout.get('issues') or []) if str(item)}
coordinate_failure_issues = {
code for code in layout_issues if code.startswith('coordinate_evidence_')
}
if coordinate_failure_issues:
return ProfileMatchResult(status='evidence_insufficient')
# [FAIL-CLOSED GATE] 第一层:坐标字符证据必须至少有一种来源。
# MinerU HTML tables(layout['tables'])只有结构化列名、没有绝对坐标/bbox,
# 严禁单独充当坐标模板的匹配证据。否则会出现"MinerU 有列名但 matcher
# header_tokens=空、column_count=0、evidence_coverage 伪分数"的分裂。
if not pages:
return ProfileMatchResult(status='evidence_insufficient')
if not glyph_tables and not page_glyphs:
return ProfileMatchResult(status='evidence_insufficient')
page_text = _layout_page_text(
@@ -201,6 +216,25 @@ def match_frozen_coordinate_profiles(
)
reason_codes.extend(hard_conflict_codes)
# [FAIL-CLOSED GATE] 第二层:身份证据缺失时,结构/几何维度不得独立构成模板命中。
# 用户场景:page_glyphs 虽有字符但观测不到 header_tokens 或
# column_centers;若签名冻结了核心列身份证据,就必须以身份优先、
# 结构辅助。否则 table_geometry + page_structure 的弱证据会掩盖
# "列名证据没有进入匹配器" 的真正问题。
signature_patterns = (
[item for item in (signature_body or {}).get('table_patterns') or [] if isinstance(item, dict)]
if signature_body is not None else []
)
signature_expects_identity = any(
bool(p.get('header_tokens') or p.get('column_centers') or (p.get('column_count') or 0) > 0)
for p in signature_patterns
)
observed_header = [str(item) for item in (observed.get('header_tokens') or []) if str(item).strip()]
observed_col_count = int(observed.get('column_count') or 0)
observed_has_identity = bool(observed_header) or observed_col_count > 0
if signature_expects_identity and not observed_has_identity:
reason_codes.append('profile_core_column_evidence_missing')
weights = profile.document_match.scoring_weights
score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results)
hard_match = not reason_codes
@@ -256,6 +290,19 @@ def match_frozen_coordinate_profiles(
status='no_match', candidates=rendered,
top1_score=top1_score, top2_score=top2_score, margin=margin,
)
# [FAIL-CLOSED GATE] 第三层:全局证据不足优先于 no_match / layout_drift。
# 当所有候选要么缺签名身份证据、要么观测不到核心列名/列坐标时,必须
# evidence_insufficient,禁止把"没证据"误报成"模板都不匹配"。
global_identity_missing = all(
'profile_core_column_evidence_missing' in item.reason_codes
or 'profile_signature_missing' in item.reason_codes
for item in rendered
)
if global_identity_missing:
return ProfileMatchResult(
status='evidence_insufficient', candidates=rendered,
top1_score=None, top2_score=None, margin=None,
)
if _any_special_profile_feature(candidates, page_text=page_text):
return ProfileMatchResult(
status='layout_drift', candidates=rendered,
@@ -500,10 +500,12 @@ def _native_pdf_fallback_snapshot(
layout_payload=layout_payload_preview,
)
evidence_started = perf_counter()
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
# [FAIL-CLOSED OVERRIDE] Fallback 快照即使是 PDFium 文本回退,也必须默认
# 保存整页 glyph。否则一旦 on-demand 恢复异常(如 asset_id 丢失或 PDFium 崩
# 溃),matcher 会看到"MinerU 列名存在 + 空 page_glyphs"的分裂证据,输出
# 伪精确模板分数。坐标预算由后续 compact 负责兜底,初始生成必须包含身份证据。
evidence = _table_coordinate_evidence(
pages=native_pages, tables=tables, include_page_glyphs=False,
pages=native_pages, tables=tables, include_page_glyphs=True,
diagnostics=diagnostics,
)
if diagnostics is not None:
@@ -5,7 +5,8 @@ services/shipping_notice/line_inventory_match_projection.py
依赖:ShippingNoticeLineInventoryMatch、Config 自动履约开关。
逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用;
ready+not_found→available=0;result_missing 不得转 0;
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮)。
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail。
"""
from __future__ import annotations
@@ -35,7 +36,30 @@ STATUS_INVALID_KEY = 'invalid_key'
ACTION_RETRY_PREPARATION = 'retry_inventory_preparation'
ACTION_RETRY_MATCHING = 'retry_inventory_matching'
ACTION_CLOSE = 'close_unfulfillable'
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail'
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail' # 已下线:不得再下发 UI
def project_line_retryable(
*,
inventory_allowed_actions: list[str] | None,
user_line_status: str | None,
inventory_rpa_running: bool = False,
) -> bool:
"""
行级是否对用户展示统一「重试」按钮。
核心逻辑:存在内部库存动作且非短缺/冲突人工阻断、非 RPA 运行中。
UI 只消费本布尔值,不展示内部动作码。
"""
if inventory_rpa_running:
return False
status = str(user_line_status or '').strip().lower()
if status in {
'shortage', 'source_conflict', 'wave_created', 'fulfilled', 'closed', 'inventory_matched',
}:
return False
return bool([a for a in (inventory_allowed_actions or []) if a])
SOURCE_STATUS_RESOLVED = 'resolved'
SOURCE_STATUS_RESOLVING = 'resolving'
@@ -326,7 +350,9 @@ def resolve_line_allowed_actions(
user_line_status: str | None,
) -> list[str]:
"""
行生命周期动作;本轮仅 close_unfulfillable(已完成/已关闭不展示)。
行生命周期动作;仅 close_unfulfillable。
核心逻辑:已完成/已关闭/已入波次不开放行动作;彻底移除 view_fulfillment_detail。
"""
if not has_formal_ot:
return []
@@ -335,8 +361,6 @@ def resolve_line_allowed_actions(
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
'wave_created', 'fulfilled', 'closed',
}:
if user_status in {'wave_created', 'fulfilled'}:
return [ACTION_VIEW_FULFILLMENT] if user_status != 'closed' else []
return []
return [ACTION_CLOSE]
@@ -477,6 +501,7 @@ def project_line_inventory_view(
},
'user_line_status': user_status,
'decision_source': decision_source,
'retryable': False,
'inventory_allowed_actions': [],
'line_allowed_actions': [],
'allowed_actions': [],
@@ -538,6 +563,11 @@ def project_line_inventory_view(
source_code=fact.get('inventory_source_code'),
source_labels=source_labels,
)
retryable = project_line_retryable(
inventory_allowed_actions=inv_actions,
user_line_status=user_status,
inventory_rpa_running=bool(inventory_rpa_running),
)
return {
'inventory_status': inventory_status,
'match_result': match_result,
@@ -552,6 +582,7 @@ def project_line_inventory_view(
'matching_rule_version': fact.get('matching_rule_version'),
'user_line_status': user_status,
'decision_source': decision_source,
'retryable': retryable,
'inventory_allowed_actions': inv_actions,
'line_allowed_actions': line_actions,
'allowed_actions': [*inv_actions, *line_actions],
@@ -1686,7 +1686,9 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
def _route_reason_for_issue(issue: str) -> str:
"""把内部解析问题收敛为管理员可长期依赖的稳定路由原因码。"""
mapping = {
'order_profile_evidence_insufficient': 'required_anchor_missing',
'order_layout_prerequisite_missing': 'coordinate_evidence_unavailable',
'order_layout_evidence_incomplete': 'coordinate_evidence_unavailable',
'order_profile_evidence_insufficient': 'coordinate_evidence_unavailable',
'order_profile_no_match': 'profile_not_found',
'order_profile_ambiguous': 'profile_ambiguous',
'order_profile_layout_drift': 'profile_drift_detected',
@@ -1694,6 +1696,9 @@ def _route_reason_for_issue(issue: str) -> str:
'order_profile_multiple_matches': 'profile_ambiguous',
'order_profile_coordinate_reconstruction_unavailable': 'coordinate_evidence_unavailable',
}
# 第零层:on-demand 坐标恢复失败码直接收敛为证据不可用,不经过 fallback 误报为 drift。
if str(issue).startswith('coordinate_evidence_'):
return 'coordinate_evidence_unavailable'
return mapping.get(issue, 'profile_drift_detected')
@@ -1357,6 +1357,16 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
task,
line_projections=list(validation.get('line_projections') or []),
)
# [STEP] 候选库存源已在建单前冻结;正式 OT 创建完成后立即进入获取库存,
# 不再让统一进度停留在“创建正式订单”。最终行级实际库存源仍由后续匹配决定。
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
sync_order_task_processing_state(
order_task,
stage='inventory_fetching',
status='processing',
reason_code='inventory_candidates_frozen_after_confirm',
)
# [STEP] 建单前已校验客户确认:立即绑定标准客户,禁止落入 customer_review。
from app.services.shipping_notice.candidate_qualification_service import (
resolve_confirmed_bill_to_customer_id,
@@ -489,6 +489,7 @@ def project_review_case_line_decisions(
'inventory_source_code': inv_view.get('inventory_source_code'),
'inventory_source': inv_view.get('inventory_source'),
'decision_source': inv_view.get('decision_source'),
'retryable': bool(inv_view.get('retryable')),
'inventory_allowed_actions': list(inv_view.get('inventory_allowed_actions') or []),
'line_allowed_actions': list(inv_view.get('line_allowed_actions') or []),
'allowed_actions': list(inv_view.get('allowed_actions') or []),
@@ -19,7 +19,7 @@ backend/app/services/shipping_notice/order_review_projection.py
固定投影 customer_resolution / field_conflicts / duplicate / profile_match /
field_completeness / completed_checks / current_stage / reservation /
line_fulfillment(分域 inventory/line_allowed_actions)/ inventory_issue_fallback /
automation;
automation / conversation_allowed_actions;
profile_match:普通用户四态裁剪,管理员保留完整审计;
automation 区分 pre_ot_stp / post_ot_progress 与 owner_type,禁止资格冒充正在推进;
正式 OT automation/needs_retry 同源绑定 shipping_notice_run Job;
@@ -30,6 +30,8 @@ backend/app/services/shipping_notice/order_review_projection.py
为每行/表头投影 field_meta(value_source / locked / override_reason);
已确认 Case 附带 confirmed_task_no 与 post_confirm_auto_progress,供刷新后恢复「已建单待推进」;
已确认 Case available_actions 含 edit_formal_task,并投影 formal_editable_field_ids;
普通路径不再投影 confirm(自动建单走 STP;无 manual_create_fallback);
conversation_allowed_actions 与对话处理 GET 同源(retry_auto_progress + eligible_count);
WorkflowItem 已关闭时 available_actions 仅保留 view;
不返回全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。
"""
@@ -521,9 +523,8 @@ def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
actions.append('create_draft')
else:
actions.append('edit_draft')
if case.current_draft is not None and str((case.current_draft.validation_result_json or {}).get('status') or '') == 'ready':
actions.append('confirm')
# STP 失败 / manual_fallback:可重试自动建单(与确认兜底互斥由前端按 automation.status 控制)。
# 普通路径不投影 confirm;自动建单走 STP retry;本轮不提供 manual_create_fallback。
# STP 失败 / manual_fallback:可重试自动建单。
automation = None
try:
automation = _project_case_automation_status(
@@ -776,10 +777,8 @@ def serialize_review_case(
'recovery_available': False,
}
# task_missing:禁止 confirm;无恢复 API 时明确 view + contact_admin。
available_actions = _allowed_actions(case)
if formal_ot.get('task_missing') or formal_ot.get('has_formal_ot'):
available_actions = [a for a in available_actions if a != 'confirm']
# task_missing:无恢复 API 时明确 view + contact_admin;防御性剥离残留 confirm。
available_actions = [a for a in _allowed_actions(case) if a != 'confirm']
if formal_ot.get('task_missing'):
available_actions = ['view', 'contact_admin']
@@ -807,6 +806,23 @@ def serialize_review_case(
automation=automation if isinstance(automation, dict) else None,
)
# 对话级动作与 GET /shipping-processing/conversations 同源;切换 Case 时刷新。
conversation_allowed_actions: list[dict[str, Any]] = []
try:
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
project_conversation_allowed_actions,
)
conversation_id = str(getattr(run, 'conversation_id', None) or '').strip()
owner_id = int(getattr(run, 'user_id', 0) or 0)
if conversation_id and owner_id:
conversation_allowed_actions = project_conversation_allowed_actions(
user_id=owner_id,
conversation_id=conversation_id,
)
except Exception: # noqa: BLE001
conversation_allowed_actions = []
return {
'case_no': case.case_no,
'run_no': run.run_no,
@@ -853,6 +869,7 @@ def serialize_review_case(
'order_data_version': order_data_version,
'process_gate': process_gate,
'inventory_issue_fallback': inventory_issue_fallback,
'conversation_allowed_actions': conversation_allowed_actions,
}
@@ -170,6 +170,8 @@ CONVERSATION_PROCESSING_TASK_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozense
'conversation_processing_task_focused',
'conversation_processing_task_viewed',
'conversation_processing_task_acknowledged',
# 对话级批量「重试自动推进」汇总事件(对象级仍写 STP / auto-progress 既有审计)。
'conversation_retry_auto_progress',
})
# 输入追加阻断原因码;前端只展示 i18n,禁止本地发明 reason。
@@ -14,7 +14,8 @@ services/shipping_notice/shipping_processing_projection.py
写入 stage_nodes 与 available_actions;stage/status 以 OT 已写入值为准(BE-07,禁止 Notice 覆盖);
已挂正式 Notice 时 stage/stage_label_key 与 Case.current_stage 同源(project_stage_for_task);
**只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert);已建 Notice 时填 shipping_notice_no;
work_items 构建后由 _conversation_processing_from_work_items 重建兼容 conversation_processing。
work_items 构建后由 _conversation_processing_from_work_items 重建兼容 conversation_processing;
附带 conversation_allowed_actions(与 Case 工作台同源,retry_auto_progress)。
"""
from __future__ import annotations
@@ -1358,6 +1359,31 @@ def _conversation_processing_from_work_items(
}
def _project_conversation_allowed_actions_safe(
*,
user_id: int,
conversation_id: str,
) -> list[dict[str, Any]]:
"""
安全投影对话级动作;失败时返回空列表,避免拖垮会话处理读源。
"""
try:
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
project_conversation_allowed_actions,
)
return project_conversation_allowed_actions(
user_id=int(user_id),
conversation_id=str(conversation_id or '').strip(),
)
except Exception: # noqa: BLE001
logging.getLogger(__name__).exception(
'conversation_allowed_actions projection failed conversation_id=%s',
conversation_id,
)
return []
def project_conversation_processing_items(
*,
user_id: int,
@@ -1523,6 +1549,10 @@ def project_conversation_processing_items(
'conversation_id': normalized,
'work_items': work_items,
'conversation_processing': rebuilt,
'conversation_allowed_actions': _project_conversation_allowed_actions_safe(
user_id=int(user_id),
conversation_id=normalized,
),
}
@@ -0,0 +1,715 @@
"""
services/shipping_notice/task_retry_decision_service.py
用途:正式 OT「重试」统一决策与执行入口(任务级 / 行级 / 对话级 / auto-progress 兼容)。
依赖:inventory_source_gate、inventory_workflow、fulfillment_workflow.match_inventory、
progress_workflow.auto_progress、fulfillment_audit、ShippingNotice /
ShippingNoticeLineInventoryMatch。
逻辑:用户只表达重试意图;本服务按最新事实选择 resolve_source / fetch_inventory /
rematch / needs_human / noop / failed,或非库存阶段委托 auto_progress;
禁止对话级与任务级分叉实现;幂等键与审计字段一并返回。
"""
from __future__ import annotations
import logging
from typing import Any, Literal
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch
_LOGGER = logging.getLogger(__name__)
Scope = Literal['task', 'line']
ACTION_RESOLVE_SOURCE = 'resolve_source'
ACTION_FETCH_INVENTORY = 'fetch_inventory'
ACTION_REMATCH = 'rematch'
ACTION_NEEDS_HUMAN = 'needs_human'
ACTION_NOOP = 'noop'
ACTION_FAILED = 'failed'
ACTION_AUTO_PROGRESS = 'auto_progress'
STATUS_RUNNING = 'running'
STATUS_NEEDS_HUMAN = 'needs_human'
STATUS_COMPLETED = 'completed'
STATUS_FAILED = 'failed'
PH_RPA_PENDING = 'rpa_pending'
PH_UPLOAD_PENDING = 'upload_rpa_pending'
PH_UPLOAD_FAILED = 'upload_rpa_failed'
def retry_task_with_decision(
*,
task_no: str,
user_id: int,
scope: Scope = 'task',
line_key: str | None = None,
reason: str | None = None,
trigger: str = 'user_retry',
continue_auto_progress: bool = False,
) -> dict[str, Any]:
"""
统一重试决策并执行。
核心逻辑:加锁读取任务事实 → 决策树 → 执行既有库存/推进处理器 → 写审计 → 返回统一结果。
Args:
task_no: 正式任务号。
user_id: 操作人。
scope: task=整单;line=单行。
line_key: scope=line 时必填。
reason: 用户/系统原因。
trigger: 调用方标识(user_retry / conversation_retry / system_auto_progress)。
continue_auto_progress: True 时库存节点通过后继续 auto_progress(兼容调度入口)。
Returns:
含 action/status/retryable/decision_version/snapshot_id/job_id/idempotency_key 等。
Raises:
ValidationError / NotFoundError / AppError。
"""
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.query_service import get_task_for_user
normalized_task = str(task_no or '').strip()
if not normalized_task:
raise ValidationError('task_no is required')
scope_norm: Scope = 'line' if str(scope or '').strip().lower() == 'line' else 'task'
line = str(line_key or '').strip() or None
if scope_norm == 'line' and not line:
raise ValidationError('line_key is required for line scope')
task = get_task_for_user(normalized_task, int(user_id))
if task is None:
raise NotFoundError('Not found')
decision_version = int(getattr(task, 'order_data_version', None) or 1)
decided = _decide(task, scope=scope_norm, line_key=line)
action = str(decided.get('action') or ACTION_NOOP)
idempotency_key = _build_idempotency_key(
task=task,
action=action,
decision_version=decision_version,
line_key=line,
)
# [STEP] 幂等:同键活跃运行中直接回放。
if _is_inventory_rpa_active(task) and action in {ACTION_FETCH_INVENTORY, ACTION_REMATCH, ACTION_AUTO_PROGRESS}:
result = _result_payload(
task=task,
action=ACTION_NOOP,
status=STATUS_RUNNING,
retryable=False,
reason_code='already_running',
decision_version=decision_version,
idempotency_key=idempotency_key,
idempotent_replay=True,
message='已有库存处理在运行',
)
_audit_decision(
task=task,
user_id=int(user_id),
scope=scope_norm,
line_key=line,
trigger=trigger,
reason=reason,
result=result,
)
return result
executed = _execute(
task=task,
user_id=int(user_id),
decided=decided,
continue_auto_progress=bool(continue_auto_progress),
decision_version=decision_version,
idempotency_key=idempotency_key,
line_key=line,
)
_audit_decision(
task=task,
user_id=int(user_id),
scope=scope_norm,
line_key=line,
trigger=trigger,
reason=reason,
result=executed,
)
try:
db.session.commit()
except Exception: # noqa: BLE001
db.session.rollback()
_LOGGER.exception('task retry decision commit failed task_no=%s', normalized_task)
raise
return executed
def decide_retry_action_only(
task: ShippingNotice,
*,
scope: Scope = 'task',
line_key: str | None = None,
) -> dict[str, Any]:
"""
只读决策(供投影 / 测试);不执行副作用。
Returns:
``{action, reason_code, retryable, ...}``。
"""
return _decide(task, scope=scope, line_key=line_key)
def _decide(
task: ShippingNotice,
*,
scope: Scope,
line_key: str | None,
) -> dict[str, Any]:
"""按冻结优先级计算 RetryDecision。"""
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower()
if process_status in {'completed', 'fulfilled', 'closed', 'cancelled'}:
return {
'action': ACTION_NOOP,
'status': STATUS_COMPLETED,
'retryable': False,
'reason_code': 'already_completed',
}
if pending in {PH_RPA_PENDING, PH_UPLOAD_PENDING} or _is_inventory_rpa_active(task):
return {
'action': ACTION_NOOP,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'already_running',
}
if pending == PH_UPLOAD_FAILED:
return {
'action': ACTION_NEEDS_HUMAN,
'status': STATUS_NEEDS_HUMAN,
'retryable': False,
'reason_code': 'upload_rpa_failed',
}
if scope == 'line' and line_key:
return _decide_for_line(task, line_key=line_key)
# [STEP] 库存源不稳定:先解析源,不得直接写 RPA。
if not is_inventory_source_stable(task):
status = str(getattr(task, 'inventory_source_status', None) or '').strip().lower()
if status in {'ambiguous', 'candidates_frozen', 'conflicted', 'unresolved', ''}:
# 多候选 / 客户未指定:不得自动选源进 RPA。
codes = _frozen_or_candidate_codes(task)
if status == 'conflicted' or (len(codes) > 1 and status in {'ambiguous', 'candidates_frozen'}):
# 客户已确认源(user_confirmed)才允许继续;多候选未确认必须人工。
customer_specified = status == 'user_confirmed' or bool(
str(getattr(task, 'inventory_source_confirmed_by', None) or '').strip()
)
if not customer_specified and len(codes) > 1:
return {
'action': ACTION_NEEDS_HUMAN,
'status': STATUS_NEEDS_HUMAN,
'retryable': False,
'reason_code': 'inventory_source_candidates_need_human',
}
return {
'action': ACTION_RESOLVE_SOURCE,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'inventory_source_unstable',
}
has_lines = bool(getattr(task, 'inventory_lines_json', None))
snapshot_id = getattr(task, 'inventory_snapshot_id', None)
if not has_lines and not snapshot_id:
return {
'action': ACTION_FETCH_INVENTORY,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'inventory_snapshot_missing',
}
# 有快照/明细但匹配未完成或失败 → rematch;短缺 → needs_human。
match_hint = _task_match_hint(task)
if match_hint.get('needs_human'):
return {
'action': ACTION_NEEDS_HUMAN,
'status': STATUS_NEEDS_HUMAN,
'retryable': False,
'reason_code': match_hint.get('reason_code') or 'inventory_shortage',
}
if match_hint.get('needs_rematch'):
return {
'action': ACTION_REMATCH,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'inventory_match_incomplete',
}
# 非库存阻断:委托现有 auto_progress 推进后续阶段。
return {
'action': ACTION_AUTO_PROGRESS,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': None,
}
def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]:
"""行级决策:只处理该行库存事实。"""
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
from app.services.shipping_notice.line_inventory_match_projection import (
project_line_inventory_view,
project_line_retryable,
)
if not is_inventory_source_stable(task):
return {
'action': ACTION_RESOLVE_SOURCE,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'inventory_source_unstable',
}
row = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_key=str(line_key))
.order_by(ShippingNoticeLineInventoryMatch.id.desc())
.first()
)
fact = {
'match_result': getattr(row, 'match_result', None) if row else None,
'inventory_status': getattr(row, 'inventory_status', None) if row else 'preparing',
'available_qty': getattr(row, 'available_qty', None) if row else None,
'required_qty': getattr(row, 'required_qty', None) if row else None,
'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None) if row else None,
'inventory_source_code': getattr(row, 'inventory_source_code', None) if row else None,
'matched_at': getattr(row, 'matched_at', None) if row else None,
'matching_rule_version': getattr(row, 'matching_rule_version', None) if row else None,
'detail_json': dict(getattr(row, 'detail_json', None) or {}) if row else {},
}
view = project_line_inventory_view(
has_formal_ot=True,
fact=fact,
required_qty=fact.get('required_qty'),
stored_line_status=None,
decision_source=None,
can_fulfill_complete_line=False,
inventory_rpa_running=_is_inventory_rpa_active(task),
)
user_status = str(view.get('user_line_status') or '')
if user_status in {'shortage', '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 not project_line_retryable(
inventory_allowed_actions=list(view.get('inventory_allowed_actions') or []),
user_line_status=user_status,
inventory_rpa_running=_is_inventory_rpa_active(task),
):
return {
'action': ACTION_NOOP,
'status': STATUS_COMPLETED,
'retryable': False,
'reason_code': 'already_completed',
}
inv_actions = set(view.get('inventory_allowed_actions') or [])
if 'retry_inventory_matching' in inv_actions and view.get('inventory_snapshot_id'):
return {
'action': ACTION_REMATCH,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'inventory_match_incomplete',
'line_key': line_key,
}
return {
'action': ACTION_FETCH_INVENTORY,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'inventory_snapshot_missing',
'line_key': line_key,
}
def _execute(
*,
task: ShippingNotice,
user_id: int,
decided: dict[str, Any],
continue_auto_progress: bool,
decision_version: int,
idempotency_key: str,
line_key: str | None,
) -> dict[str, Any]:
"""执行决策动作并映射统一响应。"""
from app.services.shipping_notice.inventory_source_gate import (
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)
base_kwargs = {
'task': task,
'decision_version': decision_version,
'idempotency_key': idempotency_key,
'snapshot_id': getattr(task, 'inventory_snapshot_id', None),
'source_code': str(getattr(task, 'inventory_source_code', None) or '') or None,
}
if action == ACTION_NOOP:
return _result_payload(
action=ACTION_NOOP,
status=str(decided.get('status') or STATUS_COMPLETED),
retryable=False,
reason_code=str(decided.get('reason_code') or 'already_completed'),
message='无需重试',
**base_kwargs,
)
if action == ACTION_NEEDS_HUMAN:
return _result_payload(
action=ACTION_NEEDS_HUMAN,
status=STATUS_NEEDS_HUMAN,
retryable=False,
reason_code=str(decided.get('reason_code') or 'needs_human'),
message='当前需要人工处理',
**base_kwargs,
)
try:
if action == ACTION_RESOLVE_SOURCE:
adjudicate_and_apply_inventory_source(task)
ensure_inventory_source_review_state(task)
db.session.flush()
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
if not is_inventory_source_stable(task):
return _result_payload(
action=ACTION_NEEDS_HUMAN,
status=STATUS_NEEDS_HUMAN,
retryable=False,
reason_code='inventory_source_candidates_need_human',
message='库存源未稳定,需要人工确认',
**base_kwargs,
)
# 源已稳定:继续获取库存。
action = ACTION_FETCH_INVENTORY
if action == ACTION_FETCH_INVENTORY:
# 先尝试复用快照;仍无则显式 retry_rpa。
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',
})
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='已复用库存快照',
)
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',
})
return _map_tool_result(
fetched,
action=ACTION_FETCH_INVENTORY,
base_kwargs={
**base_kwargs,
'snapshot_id': getattr(task, 'inventory_snapshot_id', None),
},
message='已提交库存获取',
)
if action == ACTION_REMATCH:
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',
'line_key': line_key,
})
mapped = _map_tool_result(
matched,
action=ACTION_REMATCH,
base_kwargs=base_kwargs,
message='已提交库存匹配',
)
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
# ACTION_AUTO_PROGRESS 或 continue
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
except AppError as err:
return _result_payload(
action=ACTION_FAILED,
status=STATUS_FAILED,
retryable=True,
reason_code=str(getattr(err, 'code', None) or 'SHIPPING.RETRY_FAILED'),
message=str(getattr(err, 'message', None) or err),
**base_kwargs,
)
except Exception as exc: # noqa: BLE001
_LOGGER.exception('task retry execute failed task_no=%s action=%s', task.task_no, action)
return _result_payload(
action=ACTION_FAILED,
status=STATUS_FAILED,
retryable=True,
reason_code='SHIPPING.RETRY_FAILED',
message=str(exc)[:500],
**base_kwargs,
)
def _run_auto_progress(
task: ShippingNotice,
*,
user_id: int,
base_kwargs: dict[str, Any],
) -> dict[str, Any]:
"""委托现有 auto_progress 推进非库存/后续阶段。"""
from app.services.shipping_notice import tools as shipping_tools
result = shipping_tools.auto_progress({
'task_id': task.task_no,
'source': 'workspace_api',
'operator_id': int(user_id),
'actor_id': int(user_id),
'_trusted_user_id': int(user_id),
'trigger': 'task_retry_decision',
})
return _map_tool_result(
result,
action=ACTION_AUTO_PROGRESS,
base_kwargs=base_kwargs,
message='已提交自动推进',
)
def _map_tool_result(
tool_result: dict[str, Any] | None,
*,
action: str,
base_kwargs: dict[str, Any],
message: str,
) -> 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'}:
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'),
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'}:
return _result_payload(
action=ACTION_FAILED,
status=STATUS_FAILED,
retryable=True,
reason_code=str((tool_result or {}).get('error_code') or status_raw),
message=str((tool_result or {}).get('message') or '自动处理失败'),
job_id=(tool_result or {}).get('job_id'),
**base_kwargs,
)
if status_raw in {'ok', 'completed', 'succeeded'}:
return _result_payload(
action=action,
status=STATUS_COMPLETED,
retryable=False,
reason_code=None,
message=str((tool_result or {}).get('message') or message),
job_id=(tool_result or {}).get('job_id'),
**base_kwargs,
)
# running / queued / processing
return _result_payload(
action=action,
status=STATUS_RUNNING,
retryable=False,
reason_code=None,
message=str((tool_result or {}).get('message') or message),
job_id=(tool_result or {}).get('job_id'),
**base_kwargs,
)
def _result_payload(
*,
task: ShippingNotice,
action: str,
status: str,
retryable: bool,
reason_code: str | None,
decision_version: int,
idempotency_key: str,
message: str,
snapshot_id: Any = None,
source_code: str | None = None,
job_id: Any = None,
idempotent_replay: bool = False,
) -> dict[str, Any]:
"""组装统一响应。"""
return {
'task_no': task.task_no,
'idempotent_replay': bool(idempotent_replay),
'action': action,
'stage': str(getattr(task, 'process_status', None) or '') or None,
'status': status,
'retryable': bool(retryable),
'job_id': job_id,
'reason_code': reason_code,
'message': message,
'decision_version': int(decision_version),
'snapshot_id': int(snapshot_id) if snapshot_id not in (None, '') else None,
'source_code': source_code,
'idempotency_key': idempotency_key,
}
def _build_idempotency_key(
*,
task: ShippingNotice,
action: str,
decision_version: int,
line_key: str | None,
) -> str:
"""按冻结约定生成业务幂等键。"""
task_no = str(task.task_no)
source = str(getattr(task, 'inventory_source_code', None) or 'NA').strip().upper() or 'NA'
snapshot = getattr(task, 'inventory_snapshot_id', None) or 'none'
if action == ACTION_FETCH_INVENTORY:
key = f'inventory-fetch:{task_no}:{source}:v{decision_version}'
elif action == ACTION_REMATCH:
key = f'inventory-match:{task_no}:{snapshot}:v{decision_version}'
elif action == ACTION_RESOLVE_SOURCE:
key = f'inventory-source:{task_no}:v{decision_version}'
else:
key = f'auto-progress:{task_no}:v{decision_version}'
if line_key:
key = f'{key}:line:{line_key}'
return key
def _is_inventory_rpa_active(task: ShippingNotice) -> bool:
"""库存 RPA 是否仍在等待。"""
pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower()
process = str(getattr(task, 'process_status', None) or '').strip().lower()
if pending == PH_RPA_PENDING:
return True
if process == 'waiting_inventory' and pending == PH_RPA_PENDING:
return True
return False
def _frozen_or_candidate_codes(task: ShippingNotice) -> list[str]:
"""读取冻结/候选库存源编码。"""
try:
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
return list(task_frozen_inventory_source_codes(task) or [])
except Exception: # noqa: BLE001
return []
def _task_match_hint(task: ShippingNotice) -> dict[str, Any]:
"""根据行匹配事实判断是否需 rematch 或人工。"""
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id))
.order_by(ShippingNoticeLineInventoryMatch.id.desc())
.limit(200)
.all()
)
if not rows:
# 有库存明细但无匹配行 → 需要匹配。
if getattr(task, 'inventory_lines_json', None) or getattr(task, 'inventory_snapshot_id', None):
return {'needs_rematch': True}
return {}
needs_rematch = False
for row in rows:
result = str(getattr(row, 'match_result', None) or '').strip().lower()
status = str(getattr(row, 'inventory_status', None) or '').strip().lower()
if result in {'not_found'} or status in {'source_conflict'}:
# 短缺/冲突:人工。
return {'needs_human': True, 'reason_code': 'inventory_shortage' if result == 'not_found' else 'inventory_source_conflict'}
if result in {'mapping_failed', 'result_missing', 'preparing', ''} or status in {'mapping_failed', 'preparing'}:
needs_rematch = True
if needs_rematch:
return {'needs_rematch': True}
return {}
def _audit_decision(
*,
task: ShippingNotice,
user_id: int,
scope: Scope,
line_key: str | None,
trigger: str,
reason: str | None,
result: dict[str, Any],
) -> None:
"""写对象级重试决策审计。"""
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
action = str(result.get('action') or ACTION_NOOP)
event_type = {
ACTION_RESOLVE_SOURCE: 'inventory_source_resolved',
ACTION_FETCH_INVENTORY: 'inventory_rpa_triggered',
ACTION_REMATCH: 'inventory_matching_started',
ACTION_AUTO_PROGRESS: 'auto_progress_retried',
ACTION_NEEDS_HUMAN: 'auto_progress_retried',
ACTION_NOOP: 'auto_progress_retried',
ACTION_FAILED: 'auto_progress_retried',
}.get(action, 'auto_progress_retried')
record_fulfillment_audit(
event_type=event_type,
aggregate_type='shipping_task',
aggregate_id=str(task.task_no),
action='retry',
actor_id=int(user_id),
task_no=str(task.task_no),
conversation_id=str(getattr(task, 'conversation_id', None) or '') or None,
owner_user_id=int(getattr(task, 'user_id', 0) or user_id),
reason_code=str(result.get('reason_code') or '') or None,
reason=str(reason or trigger)[:200],
result='success' if result.get('status') != STATUS_FAILED else 'failed',
error_code=str(result.get('reason_code') or '') if result.get('status') == STATUS_FAILED else None,
metadata={
'scope': scope,
'line_key': line_key,
'trigger': trigger,
'previous_stage': str(getattr(task, 'process_status', None) or '') or None,
'next_stage': result.get('stage'),
'action': action,
'decision_version': result.get('decision_version'),
'snapshot_id': result.get('snapshot_id'),
'job_id': result.get('job_id'),
'idempotency_key': result.get('idempotency_key'),
'status': result.get('status'),
},
source='api',
strict=False,
)