feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环

This commit is contained in:
hugo committed 2026-08-09 11:43:53 +08:00
1 parent cfa19a0b7b
commit 8e0bbf7a81
180 files changed
+31210 -1864

No files matched your search

+1
View File
@@ -11,6 +11,7 @@ from app.api.workspace.schedule import workspace_schedule_bp
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
import app.api.workspace.shipping_process_gate # noqa: F401
import app.api.workspace.shipping_inventory_candidates # noqa: F401
__all__ = [
'workspace_announcements_bp',
@@ -0,0 +1,69 @@
"""
backend/app/api/workspace/shipping_inventory_candidates.py
用途:正式 Task 库存候选只读详情 API。
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。
逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason,
不把可恢复业务阻断误报成 404。
"""
from __future__ import annotations
from flask import request
from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
from app.core.errors import ValidationError
from app.services.shipping_notice.inventory_candidate_projection import (
project_inventory_candidate_detail,
)
from app.services.shipping_notice.query_service import get_task_for_user
def _parse_version_arg() -> str | int:
"""解析 version 查询参数,仅允许 current 或正整数。"""
raw = str(request.args.get('version') or 'current').strip().lower()
if raw == 'current':
return 'current'
try:
value = int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError('version must be "current" or an integer') from exc
if value <= 0:
raise ValidationError('version must be positive')
return value
def _parse_bool_arg(name: str, *, default: bool) -> bool:
"""解析布尔查询参数。"""
raw = request.args.get(name)
if raw is None:
return default
return str(raw).strip().lower() in {'1', 'true', 'yes', 'on'}
@workspace_shipping_notice_bp.route(
'/shipping-notice/tasks/<task_no>/inventory-candidates',
methods=['GET'],
)
def workspace_get_task_inventory_candidates(task_no: str):
"""返回正式 Task 当前候选版本、历史摘要与行级详情。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
version = _parse_version_arg()
include_history = _parse_bool_arg('include_history', default=True)
include_drafts = _parse_bool_arg('include_drafts', default=False)
payload = project_inventory_candidate_detail(
task,
version=version,
include_history=include_history,
include_drafts=include_drafts,
)
return _ok({
'task_no': task.task_no,
'current_set': payload.get('current_set'),
'sources': payload.get('sources') or [],
'lines': payload.get('lines') or [],
'history': payload.get('history') or [],
'blocking_reason': payload.get('blocking_reason'),
'primary_action': payload.get('primary_action'),
})
+305 -26
View File
@@ -488,7 +488,44 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
site_id=site_id,
actor_id=user.id,
reason=str(data.get('reason') or ''),
commit=False,
)
# [STEP P1-7] 抽取侧客户确认后,同事务内触发 Case 级协调器(level-triggered reconcile 补偿)。
# 通过 Extraction → Candidate → Review Case 反查未终态 Case;若抽取阶段太早尚无 Case,不报错跳过。
if role == 'bill_to':
from app.models import ShippingOrderCandidate, ShippingOrderReviewCase
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
)
_TERMINAL = frozenset({
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
})
candidates = list(
ShippingOrderCandidate.query
.filter_by(order_extraction_id=int(extraction.id))
.all()
)
candidate_ids = {int(c.id) for c in candidates}
case = None
if candidate_ids:
case = (
ShippingOrderReviewCase.query
.filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids))
.first()
)
if case is None and extraction.run_id:
case = (
ShippingOrderReviewCase.query
.filter_by(run_id=int(extraction.run_id))
.first()
)
if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id:
reconcile_single_case_for_auto_progress(
case=case,
trigger='extraction_customer_confirmed',
refresh_validation=True,
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
@@ -508,18 +545,77 @@ def workspace_retry_conversation_auto_progress(conversation_id: str):
核心逻辑:委托 conversation_retry_auto_progress_service;前端不提交对象列表;
返回 summary + items;写 conversation_retry_auto_progress 汇总审计。
异常保护:
[STEP R-1] 路由级显式 try/except 兜底,保证模块导入期 SyntaxError/ImportError
不冒泡为裸 500(与 conversation_retry_auto_progress_service 内部
三分支 _execute_* 的 import 级 try/except 形成双层防护)。
[STEP R-2] AppError 正常 re-raise,交给 @app.errorhandler(AppError);
SyntaxError/ImportError/其他 Exception 统一转为 SHIPPING.RETRY_AUTO_PROGRESS_FAILED
并返回 summary={failed:1} 的骨架,避免前端 JSON 解析失败。
"""
import logging as _rt_logging
_rt_log = _rt_logging.getLogger(__name__)
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,
)
normalized_conv_id = str(conversation_id or '').strip()
fallback_payload = {
'conversation_id': normalized_conv_id,
'summary': {'total': 1, 'retried': 0, 'skipped': 0, 'failed': 1},
'items': [{
'object_type': 'conversation',
'object_ref': normalized_conv_id,
'action': 'retry_auto_progress',
'outcome': 'failed',
'reason_code': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
'metadata': {},
}],
}
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'),
))
try:
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
retry_auto_progress_for_conversation,
)
except (SyntaxError, ImportError) as mod_err:
_rt_log.exception(
'retry_conversation_auto_progress module import error conversation_id=%s err=%s',
normalized_conv_id, type(mod_err).__name__,
)
fallback_payload['items'][0]['reason_code'] = 'SHIPPING.MODULE_IMPORT_ERROR'
fallback_payload['items'][0]['metadata']['import_error'] = type(mod_err).__name__
return _ok(fallback_payload)
except Exception as exc: # noqa: BLE001
_rt_log.exception(
'retry_conversation_auto_progress import unexpected error conversation_id=%s',
normalized_conv_id,
)
fallback_payload['items'][0]['reason_code'] = (
'SHIPPING.RETRY_AUTO_PROGRESS_FAILED'
)
fallback_payload['items'][0]['metadata']['error_type'] = type(exc).__name__
return _ok(fallback_payload)
try:
result = retry_auto_progress_for_conversation(
user_id=int(user.id),
conversation_id=normalized_conv_id,
reason=str(data.get('reason') or 'user_retry_auto_progress'),
)
except AppError:
raise
except Exception as exc: # noqa: BLE001
_rt_log.exception(
'retry_conversation_auto_progress execution error conversation_id=%s',
normalized_conv_id,
)
fallback_payload['items'][0]['reason_code'] = (
'SHIPPING.RETRY_AUTO_PROGRESS_FAILED'
)
fallback_payload['items'][0]['metadata']['error_type'] = type(exc).__name__
return _ok(fallback_payload)
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
@@ -1005,15 +1101,11 @@ def workspace_auto_progress_shipping_task(task_no: str):
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
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,
# 普通用户不提交 Gate;服务端从当前事实定位最早未通过 Gate。
result = run_task_auto_progress(
str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id),
)
# 兼容旧前端:若仍有 export 路径则附带 download_url。
@@ -1120,7 +1212,15 @@ def workspace_mark_manual_uploaded(task_no: str):
'freight_ref_no': data.get('freight_ref_no'),
'artifact_id': data.get('artifact_id'),
}
return _ok(shipping_tools.upload_to_freight(payload))
result = shipping_tools.upload_to_freight(payload)
if isinstance(result, dict) and str(result.get('status') or '') == 'ok':
# 回执先由既有服务原子登记;随后仅提交 upload_receipt_recorded Gate,由服务端复核事实后 completed。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
run_task_auto_progress(
str(task.task_no), trigger='manual_upload_receipt_recorded', operator_id=int(user.id),
)
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
@@ -1471,15 +1571,17 @@ def workspace_get_shipping_order_review_run(run_no: str):
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>', methods=['GET'])
def workspace_get_shipping_order_review_case(case_no: str):
"""读取当前用户的一份 PDF 复核详情;Case 编号不能跨 owner 越权访问;访问留痕。"""
"""读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_review_case_snapshot import (
build_order_review_case_snapshot,
)
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
# 只读:禁止在 GET 中入队 STP(入队仅抽取收尾 / resume / 显式 retry POST)。
payload = serialize_review_case(
snapshot = build_order_review_case_snapshot(
get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin),
is_admin=is_admin,
)
@@ -1489,9 +1591,13 @@ def workspace_get_shipping_order_review_case(case_no: str):
aggregate_id=str(case_no),
actor_id=user.id,
review_case_no=str(case_no),
run_no=str(payload.get('run_no') or '') or None if isinstance(payload, dict) else None,
run_no=(
str(((snapshot.get('case') or {}).get('run_no')) or '') or None
if isinstance(snapshot, dict)
else None
),
)
return _ok(payload)
return _ok(snapshot)
@workspace_shipping_notice_bp.route(
@@ -1500,20 +1606,190 @@ def workspace_get_shipping_order_review_case(case_no: str):
)
def workspace_retry_shipping_order_stp_auto_create(case_no: str):
"""
显式重试 STP 自动建单入队(failed / manual_fallback)。
显式重试 STP 自动建单入队(仅用于确认没有业务冲突后的技术重试 — Q6 职责严格区分)。
核心逻辑:委托 retry_stp_auto_create_for_case;成功返回 queued/reused+job_id;
失败抛结构化业务错误,禁止伪装成功。
核心逻辑:
[Phase 2-4 前置校验] 先调 reconciliation_service.assert_case_not_blocked_manual,
如命中「业务阻断 waiting_human」(如 NOTICE_EXACT_DUPLICATE)直接抛 409,
要求前端切换到 reconcile-and-progress;通过后再委托 retry_stp_auto_create_for_case。
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
from app.services.shipping_notice.order_stp_auto_create_service import (
retry_stp_auto_create_for_case,
)
from app.services.shipping_notice.reconciliation_service import (
assert_case_not_blocked_manual,
)
case = get_review_case_visible_to_user(str(case_no), int(user.id), is_admin=is_admin)
# [DUPLICATE-GUARD-1] 第一道:retry API 前置校验 — 命中 duplicate 等业务阻断时直接 409,禁止普通 retry
assert_case_not_blocked_manual(case_no=str(case_no), case=case)
result = retry_stp_auto_create_for_case(user_id=int(user.id), case_no=str(case_no))
return _ok(result)
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/retry-auto-progress',
methods=['POST'],
)
def workspace_retry_shipping_order_case_auto_progress(case_no: str):
"""
单个 Case 精确自动推进恢复入口。适用于 Projection primary_action.code = retry_auto_progress。
禁止 duplicate 等业务阻断对象调用;assert_case_not_blocked_manual 前置双校验。
核心逻辑:
[可见性] get_review_case_visible_to_user → [业务阻断] assert_case_not_blocked_manual
→ [终态幂等] confirmed_task_id/status 终态 → [协调器] reconcile_single_case_for_auto_progress
→ [审计] case_retry_auto_progress_invoked → 返回 success+case_no+reconcile_result+serialized case。
异常保护:
[STEP R-1] 路由级显式 try/except 兜底,保证模块导入期 SyntaxError/ImportError
不冒泡为裸 500(与 case_retry_auto_progress_service 内部双校验
形成双层防护)。
[STEP R-2] AppError 正常 re-raise;SyntaxError/ImportError/其他 Exception 转为
success=false + error_code,前端统一消费 retry 结果投影。
"""
import logging as _rt_logging
_rt_log = _rt_logging.getLogger(__name__)
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
normalized_case_no = str(case_no or '').strip()
fallback_result = {
'success': False,
'case_no': normalized_case_no,
'error': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
'enqueue_status': 'not_eligible',
}
try:
from app.services.shipping_notice.case_retry_auto_progress_service import (
case_retry_auto_progress,
)
except (SyntaxError, ImportError) as mod_err:
_rt_log.exception(
'case_retry_auto_progress module import error case_no=%s err=%s',
normalized_case_no, type(mod_err).__name__,
)
fallback_result['error'] = 'SHIPPING.MODULE_IMPORT_ERROR'
fallback_result['import_error'] = type(mod_err).__name__
return _ok(fallback_result)
except Exception as exc: # noqa: BLE001
_rt_log.exception(
'case_retry_auto_progress import unexpected error case_no=%s',
normalized_case_no,
)
fallback_result['error_type'] = type(exc).__name__
return _ok(fallback_result)
try:
result = case_retry_auto_progress(
user_id=int(user.id),
case_no=normalized_case_no,
is_admin=bool(is_admin),
)
except AppError:
raise
except Exception as exc: # noqa: BLE001
_rt_log.exception(
'case_retry_auto_progress execution error case_no=%s',
normalized_case_no,
)
fallback_result['error_type'] = type(exc).__name__
return _ok(fallback_result)
return _ok(result)
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/reconcile-and-progress',
methods=['POST'],
)
def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
"""
对账 → 复用 / 裁决 / 入队(Q6 与 retry-stp-auto-create 并存,职责严格区分)。
【Phase 2 正式入口】:
- 仅当用户点击了「处理重复任务」裁决按钮后或需要对账恢复的场景才调用;
- 按 Q7:operation_id + expected_case_version 双保险幂等;
- 按 Q1:内部调用 reconcile_queries 做 L1-L3 五级归属;
- 按 Q3:用户 create_revision / force_create 裁决后走资格刷新 → resume → STP,
禁止直改 duplicate_status 绕过门禁。
Body 字段:
operation_id: string(必填,客户端生成)
user_action: 'reuse_existing' | 'create_revision' | 'force_create' | 'adjudicate' | 'auto'(默认 auto)
expected_case_version: integer(可选,版本校验过期抛 409)
source_content_hash: string(可选,请求快照用于参数一致性)
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
payload = request.get_json(silent=True) if request.is_json else None
if not isinstance(payload, dict):
payload = {}
from app.core.errors import ValidationError
operation_id = str(payload.get('operation_id') or '').strip()
if not operation_id:
raise ValidationError(
'operation_id required (client-generated idempotency component)',
code='SHIPPING.RECONCILE_OPERATION_ID_REQUIRED',
)
user_action_raw = str(payload.get('user_action') or 'auto').strip() or 'auto'
allowed = {'reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto'}
if user_action_raw not in allowed:
raise ValidationError(
f'invalid user_action: {user_action_raw}',
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
details={'allowed': sorted(allowed)},
)
user_action = user_action_raw # type: ignore[assignment]
expected_case_version = payload.get('expected_case_version')
if expected_case_version is not None:
try:
expected_case_version = int(expected_case_version)
except (TypeError, ValueError):
raise ValidationError(
'expected_case_version must be integer if provided',
code='SHIPPING.RECONCILE_INVALID_EXPECTED_VERSION',
)
else:
expected_case_version = None
source_content_hash = (
str(payload.get('source_content_hash') or '').strip() or None
)
# [Phase 4] 管理员专用扩展:legacy_job_id(历史 Job 928/929 replay)与 replay_mode 透传;
# 非管理员若传入 → 直接 422 拒绝(与 reconcile_and_progress PRE-CHECK 一致)。
legacy_job_id_raw = payload.get('legacy_job_id')
legacy_job_id: int | None = None
if legacy_job_id_raw is not None:
try:
legacy_job_id = int(legacy_job_id_raw)
except (TypeError, ValueError):
raise ValidationError(
'legacy_job_id must be integer if provided',
code='SHIPPING.RECONCILE_INVALID_EXPECTED_VERSION',
)
replay_mode_raw = payload.get('replay_mode')
replay_mode = bool(replay_mode_raw) if replay_mode_raw is not None else False
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
result = reconcile_and_progress(
user_id=int(user.id),
case_no=str(case_no),
operation_id=operation_id,
user_action=user_action,
expected_case_version=expected_case_version,
source_content_hash=source_content_hash,
is_admin=is_admin,
legacy_job_id=legacy_job_id,
replay_mode=replay_mode,
)
return _ok(result.to_public())
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/access/version-history',
methods=['POST'],
@@ -2506,9 +2782,10 @@ def workspace_attempt_shipping_order_review_field_locate(case_no: str):
def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
"""列出 Case 下 Dify 最小证据建议记录。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.order_review_llm_service import list_case_suggestions
return _ok(list_case_suggestions(user_id=user.id, case_no=case_no))
return _ok(list_case_suggestions(user_id=user.id, case_no=case_no, is_admin=is_admin))
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/llm-suggestions', methods=['POST'])
@@ -2540,6 +2817,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, suggestion_no: str):
"""人工裁决 LLM 建议:accept / modify / reject。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.order_review_llm_service import decide_suggestion
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='adjudicate_llm_suggestion')
@@ -2552,6 +2830,7 @@ def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, sugg
value=payload.get('value'),
reason=payload.get('reason'),
note=payload.get('note'),
is_admin=is_admin,
)
db.session.commit()
return _ok(result)