- 统一 XFA 数据集、字段拆分、校验及运行时解析 - 完善订单模板管理、发布检查与迁移状态 - 优化订单审核草稿、预约回退及 STP 投影缓存 - 更新前端模板编辑器、映射组件与多语言错误文案 - 补充后端与前端测试,并更新本地集成启动配置
809 lines
37 KiB
Python
809 lines
37 KiB
Python
"""
|
||
backend/app/services/shipping_notice/reconciliation_service.py
|
||
|
||
用途:Phase 2 统一对账恢复决策服务(Q3 冻结原则)。
|
||
依赖:reconcile_queries.query_case_task_ownership、business_fingerprint、
|
||
recovery_contract(错误分类/动作契约)、order_review_resume_service.resume_after_review_change、
|
||
order_stp_auto_create_service.ensure_stp_auto_create_for_case、
|
||
candidate_qualification_service.recalculate_candidate_qualification、
|
||
fulfillment_audit(写对账审计)。
|
||
逻辑:reconcile_existing_task() 先调用 reconcile_queries 做 L1-L3 归属判定,
|
||
基于 match_level + 用户动作(reuse / create_revision / force_create / adjudicate)
|
||
执行不同后续:
|
||
• L1 CERTAIN 同 Case 复用 → 写 Case.confirmed_task_id 等 3 处绑定 → 审计
|
||
• L2 PROBABLE 或 L3 AMBIGUOUS → duplicate_decision_required(等待人工裁决)
|
||
• 用户明确 create_revision / force_create → 不直改 duplicate_status,
|
||
而是先资格刷新 → resume_after_review_change → STP 入队
|
||
• NONE → 直接 resume → STP(与 Q14 Phase 2 行为一致)
|
||
全程:复用 Candidate duplicate 裁决业务规则,不绕过 Candidate Qualification 门禁;
|
||
幂等键按 Q7:reconcile:{case_no}:v{case_version}:{action}:{operation_id}。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import copy
|
||
import logging
|
||
from dataclasses import dataclass
|
||
from datetime import datetime
|
||
from typing import Any, Literal
|
||
|
||
from app import db
|
||
from app.core.errors import AppError, ConflictError, ValidationError
|
||
from app.jobs.queue import enqueue
|
||
from app.jobs.types import JobType
|
||
from app.models import (
|
||
Job,
|
||
ShippingNotice,
|
||
ShippingOrderTask,
|
||
ShippingOrderCandidate,
|
||
ShippingOrderReviewCase,
|
||
ShippingOrderReviewCaseEvent,
|
||
User,
|
||
)
|
||
# 说明:business_numbering_service._customer_code_from_summary 已移除(该函数从未在本模块实际调用,
|
||
# 且 business_numbering_service 中也不存在该函数——编号流程改为直接从 customer.short_code 取简码)。
|
||
from app.services.shipping_notice.candidate_qualification_service import (
|
||
recalculate_candidate_qualification,
|
||
)
|
||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||
from app.services.shipping_notice.intake_service import (
|
||
can_force_create_shipping_duplicate,
|
||
)
|
||
from app.services.shipping_notice.order_review_resume_service import (
|
||
resume_after_review_change,
|
||
)
|
||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||
ensure_stp_auto_create_for_case,
|
||
retry_stp_auto_create_for_case,
|
||
)
|
||
from app.services.shipping_notice.reconcile_queries import (
|
||
query_case_task_ownership,
|
||
)
|
||
from app.services.shipping_notice.recovery_contract import (
|
||
RECOVERY_CONTRACT_VERSION,
|
||
ReconcileConfidence,
|
||
ReconcileMatchLevel,
|
||
ReconcileMatchResult,
|
||
should_general_retry_be_removed,
|
||
)
|
||
|
||
_LOGGER = logging.getLogger(__name__)
|
||
|
||
# Q7:幂等键骨架(operation_id 客户端生成,服务端写入审计防重放)
|
||
IDEMPOTENCY_KEY_TEMPLATE = 'reconcile:{case_no}:v{case_version}:{action}:{operation_id}'
|
||
|
||
ReconcileUserAction = Literal['reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto']
|
||
|
||
|
||
@dataclass
|
||
class ReconcileProgressResult:
|
||
"""reconcile_and_progress 的统一返回(API 响应 + 审计字段)。"""
|
||
|
||
outcome: Literal[
|
||
'reused_existing', # L1 命中,已绑定到既有 Task
|
||
'duplicate_decision_required', # L2/L3 命中,等待人工裁决
|
||
'ownership_anomaly_rejected', # 归属异常(Q13),进入人工隔离
|
||
'stp_enqueued', # 无冲突或用户裁决后,已入队 STP
|
||
'resume_result', # 仅 resume 结果(未到入队)
|
||
'idempotent_replay', # 同 operation_id 幂等回返
|
||
]
|
||
case_no: str
|
||
match: ReconcileMatchResult
|
||
task_no: str | None
|
||
job_id: int | None
|
||
idempotency_key: str
|
||
operation_id: str
|
||
resume_outcome: dict[str, Any] | None
|
||
audit_written: bool
|
||
message: str
|
||
|
||
def to_public(self) -> dict[str, Any]:
|
||
"""返回给前端的公开响应结构(与 retry-stp-auto-create 风格一致)。"""
|
||
return {
|
||
'outcome': self.outcome,
|
||
'case_no': self.case_no,
|
||
'match_level': self.match['match_level'],
|
||
'confidence': self.match['confidence'],
|
||
'task_no': self.task_no,
|
||
'matched_task_no': self.match['task_no'],
|
||
'job_id': self.job_id,
|
||
'idempotency_key': self.idempotency_key,
|
||
'operation_id': self.operation_id,
|
||
'resume_outcome': self.resume_outcome,
|
||
'audit_written': self.audit_written,
|
||
'message': self.message,
|
||
'evidence': _sanitize_evidence(self.match.get('evidence')),
|
||
}
|
||
|
||
|
||
# ============================================================
|
||
# 证据脱敏:防止内部长哈希/敏感字段完整返给前端
|
||
# ============================================================
|
||
|
||
def _sanitize_evidence(evidence: Any) -> dict[str, Any]:
|
||
if not isinstance(evidence, dict):
|
||
return {}
|
||
out: dict[str, Any] = copy.deepcopy(evidence)
|
||
for key in ('content_hash', 'business_fingerprint'):
|
||
if isinstance(out.get(key), str) and len(out[key]) > 16:
|
||
out[key] = out[key][:16] + '…'
|
||
return out
|
||
|
||
|
||
# ============================================================
|
||
# Q7:幂等键生成 + 冲突校验(写入审计或 CaseEvent 做持久化)
|
||
# ============================================================
|
||
|
||
def _build_idempotency_key(*, case_no: str, case_version: int, action: str, operation_id: str) -> str:
|
||
return IDEMPOTENCY_KEY_TEMPLATE.format(
|
||
case_no=str(case_no).strip(),
|
||
case_version=int(case_version),
|
||
action=str(action).strip() or 'auto',
|
||
operation_id=str(operation_id).strip(),
|
||
)
|
||
|
||
|
||
def _case_version(case: ShippingOrderReviewCase) -> int:
|
||
"""case_version:draft_version(前端 expected_case_version 通常取自 draft_version)。"""
|
||
if getattr(case, 'current_draft', None) is not None:
|
||
return int(case.current_draft.draft_version or 1)
|
||
return 1
|
||
|
||
|
||
def _check_idempotency(
|
||
*,
|
||
case: ShippingOrderReviewCase,
|
||
case_no: str,
|
||
action: ReconcileUserAction,
|
||
operation_id: str,
|
||
expected_case_version: int | None,
|
||
request_snapshot: dict[str, Any],
|
||
) -> tuple[str, ReconcileProgressResult | None]:
|
||
"""
|
||
Q7 三条规则:
|
||
1) 同 operation_id + 参数一致 → 返回第一次结果(幂等回返)
|
||
2) 同 operation_id + 参数不同 → 409 IDEMPOTENT_CONFLICT
|
||
3) 不同 operation_id + expected_case_version 过期 → 409 VERSION_CONFLICT
|
||
"""
|
||
case_ver = _case_version(case)
|
||
idem_key = _build_idempotency_key(
|
||
case_no=case_no,
|
||
case_version=case_ver,
|
||
action=action,
|
||
operation_id=operation_id,
|
||
)
|
||
|
||
# [RULE 3] 不同 operation_id 但 expected_case_version 过期 → 409
|
||
if expected_case_version is not None and int(expected_case_version) != case_ver:
|
||
raise ConflictError(
|
||
f'case_version mismatch: expected v{expected_case_version}, current v{case_ver}',
|
||
code='SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT',
|
||
details={
|
||
'expected_case_version': int(expected_case_version),
|
||
'actual_case_version': case_ver,
|
||
'case_no': case_no,
|
||
'operation_id': operation_id,
|
||
},
|
||
)
|
||
|
||
# [RULE 1/2] 查 CaseEvent 中同 operation_id 的历史结果
|
||
prior = (
|
||
ShippingOrderReviewCaseEvent.query
|
||
.filter_by(case_id=int(case.id), event_type='reconcile_operation')
|
||
.order_by(ShippingOrderReviewCaseEvent.id.desc())
|
||
.limit(50)
|
||
.all()
|
||
)
|
||
for ev in prior:
|
||
op = (ev.operation_json or {}).get('operation_id') if isinstance(ev.operation_json, dict) else None
|
||
if op != operation_id:
|
||
continue
|
||
old_snapshot = (ev.operation_json or {}).get('request_snapshot') if isinstance(ev.operation_json, dict) else None
|
||
old_result = (ev.operation_json or {}).get('result') if isinstance(ev.operation_json, dict) else None
|
||
# 参数比较:source_content_hash / draft_version / case_version / action 四元组相等
|
||
same = (
|
||
isinstance(old_snapshot, dict)
|
||
and str(old_snapshot.get('source_content_hash') or '') == str(request_snapshot.get('source_content_hash') or '')
|
||
and int(old_snapshot.get('case_version') or 0) == int(request_snapshot.get('case_version') or 0)
|
||
and int(old_snapshot.get('draft_version') or 0) == int(request_snapshot.get('draft_version') or 0)
|
||
and str(old_snapshot.get('action') or '') == str(request_snapshot.get('action') or '')
|
||
)
|
||
if same and isinstance(old_result, dict):
|
||
return idem_key, ReconcileProgressResult(
|
||
outcome=str(old_result.get('outcome') or 'idempotent_replay'),
|
||
case_no=case_no,
|
||
match=old_result.get('match') if isinstance(old_result.get('match'), dict) else {
|
||
'match_level': ReconcileMatchLevel.NONE,
|
||
'task_no': None,
|
||
'confidence': ReconcileConfidence.NONE,
|
||
'evidence': {},
|
||
},
|
||
task_no=(old_result.get('task_no') if isinstance(old_result.get('task_no'), str) else None),
|
||
job_id=int(old_result['job_id']) if isinstance(old_result.get('job_id'), int) else None,
|
||
idempotency_key=str(old_result.get('idempotency_key') or idem_key),
|
||
operation_id=operation_id,
|
||
resume_outcome=old_result.get('resume_outcome') if isinstance(old_result.get('resume_outcome'), dict) else None,
|
||
audit_written=bool((ev.operation_json or {}).get('audit_written')),
|
||
message=str(old_result.get('message') or 'idempotent replay'),
|
||
)
|
||
# RULE 2:同 operation_id 参数不同 → 409
|
||
raise ConflictError(
|
||
'same operation_id but different request snapshot',
|
||
code='SHIPPING.RECONCILE_IDEMPOTENT_CONFLICT',
|
||
details={
|
||
'operation_id': operation_id,
|
||
'case_no': case_no,
|
||
'request_snapshot_new': request_snapshot,
|
||
'request_snapshot_old': old_snapshot,
|
||
},
|
||
)
|
||
return idem_key, None
|
||
|
||
|
||
# ============================================================
|
||
# 写对账审计 + 幂等结果持久化(写入 CaseEvent)
|
||
# ============================================================
|
||
|
||
def _write_reconcile_audit_and_event(
|
||
*,
|
||
case: ShippingOrderReviewCase,
|
||
user: User | None,
|
||
operation_id: str,
|
||
idempotency_key: str,
|
||
request_snapshot: dict[str, Any],
|
||
result: ReconcileProgressResult,
|
||
user_action: ReconcileUserAction,
|
||
actor_type: Literal['user', 'system'] = 'user',
|
||
) -> None:
|
||
"""
|
||
审计写入两条:fulfillment_audit(业务审计)+ CaseEvent(幂等持久化 + 可追溯)。
|
||
strict=False(审计失败不阻断对账结果返回)。
|
||
"""
|
||
case_id = int(case.id)
|
||
case_no = str(case.case_no)
|
||
actor_id = int(user.id) if user is not None else 0
|
||
result_dict = result.to_public()
|
||
|
||
# 1) 写 CaseEvent(承载幂等持久化 — 保证 Q7 下一次同 operation_id 可幂等回返)
|
||
try:
|
||
event = ShippingOrderReviewCaseEvent(
|
||
case_id=case_id,
|
||
event_type='reconcile_operation',
|
||
draft_version=getattr(getattr(case, 'current_draft', None), 'draft_version', None),
|
||
actor_user_id=actor_id if actor_type == 'user' else None,
|
||
operation_json={
|
||
'operation_id': operation_id,
|
||
'idempotency_key': idempotency_key,
|
||
'contract_version': RECOVERY_CONTRACT_VERSION,
|
||
'actor_type': actor_type,
|
||
'user_action': user_action,
|
||
'request_snapshot': request_snapshot,
|
||
'result': result_dict,
|
||
'audit_written': True,
|
||
'occurred_at_iso': datetime.utcnow().isoformat() + 'Z',
|
||
},
|
||
)
|
||
db.session.add(event)
|
||
db.session.flush()
|
||
except Exception as exc: # noqa: BLE001 — 审计失败不阻断业务
|
||
_LOGGER.warning('reconcile CaseEvent write failed case=%s op=%s err=%r', case_no, operation_id, exc)
|
||
|
||
# 2) 写 fulfillment_audit(业务可见审计)
|
||
try:
|
||
record_fulfillment_audit(
|
||
event_type='shipping_reconcile_progress',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=case_no,
|
||
action=f'reconcile_{result.outcome}',
|
||
actor_type=actor_type,
|
||
actor_id=actor_id,
|
||
review_case_no=case_no,
|
||
run_no=str(getattr(getattr(case, 'run', None), 'run_no', '') or '') or None,
|
||
metadata={
|
||
'operation_id': operation_id,
|
||
'idempotency_key': idempotency_key,
|
||
'user_action': user_action,
|
||
'match_level': result.match.get('match_level'),
|
||
'confidence': result.match.get('confidence'),
|
||
'matched_task_no': result.match.get('task_no'),
|
||
'outcome': result.outcome,
|
||
'task_no': result.task_no,
|
||
'job_id': result.job_id,
|
||
'request_snapshot': request_snapshot,
|
||
'contract_version': RECOVERY_CONTRACT_VERSION,
|
||
},
|
||
source='reconciliation_service',
|
||
sensitivity_level='sensitive',
|
||
strict=False,
|
||
)
|
||
except Exception as exc: # noqa: BLE001
|
||
_LOGGER.warning('reconcile fulfillment_audit failed case=%s op=%s err=%r', case_no, operation_id, exc)
|
||
|
||
|
||
# ============================================================
|
||
# [Q2] L2 命中后写回正式关联(三处绑定)
|
||
# ============================================================
|
||
|
||
def _write_back_case_task_binding(
|
||
*,
|
||
case: ShippingOrderReviewCase,
|
||
task: ShippingOrderTask,
|
||
actor_type: str,
|
||
) -> None:
|
||
"""
|
||
Q2:L2 命中后必须写回正式关联,避免下次恢复仍撞重复检查。
|
||
1. Case.confirmed_task_id / confirmed_task_no
|
||
2. Candidate.fulfilled_task_id(若存在当前 Candidate)
|
||
3. 来源文档继续由 Case.document_id / Candidate.primary_document_id 承载;
|
||
OT 只保存 intake/candidate 指针,不写入已移除的 source_document_id 投影。
|
||
"""
|
||
case.confirmed_task_id = int(task.id)
|
||
# confirmed_task_no 通常为 property,但实际存字段若可写则同步
|
||
if hasattr(case, 'confirmed_task_no') and not str(getattr(case, 'confirmed_task_no', '') or '').strip():
|
||
try:
|
||
case.confirmed_task_no = str(task.task_no)
|
||
except Exception: # noqa: BLE001 — property 只读则跳过
|
||
pass
|
||
# Candidate.fulfilled_task_id
|
||
if getattr(case, 'candidate_id', None):
|
||
cand = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||
if cand is not None and getattr(cand, 'fulfilled_task_id', None) is None:
|
||
try:
|
||
cand.fulfilled_task_id = int(task.id)
|
||
except Exception: # noqa: BLE001 — 模型无列则降级
|
||
pass
|
||
|
||
|
||
# ============================================================
|
||
# [Q3] Candidate 裁决规则复用 — 不直改 duplicate_status,而是资格刷新 → resume → STP
|
||
# ============================================================
|
||
|
||
def _candidate_refresh_resume_stp_flow(
|
||
*,
|
||
case: ShippingOrderReviewCase,
|
||
user_id: int,
|
||
) -> tuple[dict[str, Any] | None, int | None, str | None]:
|
||
"""
|
||
用户选择 create_revision / force_create 时的标准链路:
|
||
1) [资格刷新] recalculate_candidate_qualification(Candidate 级裁决规则)
|
||
2) [resume] resume_after_review_change(trigger='duplicate_resolved')
|
||
3) [STP 入队] ensure_stp_auto_create_for_case(force_retry=True)
|
||
禁止直接改 duplicate_status 绕过门禁。
|
||
"""
|
||
# [STEP 1] Candidate Qualification 刷新
|
||
run = case.run
|
||
cand = None
|
||
if getattr(case, 'candidate_id', None):
|
||
cand = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||
if cand is not None and run is not None:
|
||
recalculate_candidate_qualification(candidate=cand, run=run, persist=True)
|
||
db.session.flush()
|
||
|
||
# [STEP 2] resume(同步建单前 Gate + 重验资格)
|
||
resume_out = resume_after_review_change(
|
||
user_id=int(user_id),
|
||
case_no=str(case.case_no),
|
||
trigger='duplicate_resolved',
|
||
change_type='duplicate_resolved',
|
||
allow_auto_create=False,
|
||
)
|
||
db.session.flush()
|
||
|
||
# [STEP 3] STP 入队(force_retry=True 跳过重复裁决缓存)
|
||
case = (
|
||
ShippingOrderReviewCase.query
|
||
.filter_by(case_no=str(case.case_no))
|
||
.order_by(ShippingOrderReviewCase.id.desc())
|
||
.first()
|
||
) or case
|
||
ensure_result = ensure_stp_auto_create_for_case(
|
||
case=case, commit=False, refresh_validation=True, force_retry=True,
|
||
)
|
||
job_id = int(ensure_result['job_id']) if isinstance(ensure_result.get('job_id'), int) else None
|
||
stp_status = str(ensure_result.get('status') or '')
|
||
if stp_status in {'queued', 'reused', 'already_queued', 'already_running', 'enqueued'}:
|
||
return resume_out, job_id, stp_status
|
||
# STP 不达标 → 把 ensure 结果写入 resume 返回供前端展示
|
||
resume_out = dict(resume_out or {})
|
||
resume_out.setdefault('stp_enqueue_result', ensure_result)
|
||
return resume_out, None, stp_status
|
||
|
||
|
||
# ============================================================
|
||
# 对外主入口:reconcile_and_progress
|
||
# ============================================================
|
||
|
||
def reconcile_and_progress(
|
||
*,
|
||
user_id: int,
|
||
case_no: str,
|
||
operation_id: str,
|
||
user_action: ReconcileUserAction = 'auto',
|
||
expected_case_version: int | None = None,
|
||
source_content_hash: str | None = None,
|
||
is_admin: bool = False,
|
||
) -> ReconcileProgressResult:
|
||
"""
|
||
统一对账恢复总入口(Q6 reconcile-and-progress API 委托本函数)。
|
||
【AI 触发时机】:用户点击「处理重复任务」走自动化恢复,或前端
|
||
duplicate_decision_required 裁决后调用。
|
||
|
||
核心执行顺序(Q11 短事务锁 + Q1 五级归属 + Q3 复用 Candidate 裁决 + Q2 写回绑定):
|
||
1. 加载 Case(FOR UPDATE 短锁);查可见性;构建 request_snapshot(参数一致性校验)
|
||
2. Q7 幂等校验(同 operation_id 回返 / 409 参数冲突 / 409 版本过期)
|
||
3. 调用 query_case_task_ownership() 做 L1-L3 归属判定(真实 DB 关系)
|
||
4. 按 match_level + user_action 路由:
|
||
• L1 → 复用 → Q2 写回三处绑定 → 推进 post-confirm(不创建新 Job)
|
||
• L2 且 user_action=reuse_existing → 复用绑定
|
||
• L2/L3 且 user_action=auto/adjudicate → duplicate_decision_required 返回
|
||
• user_action=create_revision / force_create → 资格刷新 → resume → STP
|
||
• NONE → resume → STP(正常新建单路径)
|
||
5. 写审计(fulfillment_audit + CaseEvent 幂等持久化)
|
||
6. commit 后触发 auto-progress post-commit 钩子
|
||
|
||
BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计
|
||
→ 归属异常统一抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY,
|
||
否则返回 outcome=ownership_anomaly_rejected。
|
||
|
||
Args:
|
||
user_id: 操作人。
|
||
case_no: Case 编号。
|
||
operation_id: 客户端生成的幂等操作 ID(Q7 强制,空码 → 抛校验错)。
|
||
user_action: 用户决策动作(auto 时只做对账不主动裁决)。
|
||
expected_case_version: 前端传来的草稿版本(过期抛 409 VERSION_CONFLICT)。
|
||
source_content_hash: 请求快照指纹(用于参数一致性比对)。
|
||
is_admin: 是否管理员(force_create 受权限控制)。
|
||
|
||
Returns:
|
||
ReconcileProgressResult(公开响应 to_public() 方法)。
|
||
|
||
Raises:
|
||
ValidationError: 缺必要参数 / blocked_manual 被错误用技术重试。
|
||
ConflictError: Q7 幂等冲突 / 版本过期。
|
||
AppError: STP 链路业务拒绝。
|
||
"""
|
||
# [PRE-CHECK] operation_id 必须客户端生成(Q7 契约)
|
||
op_id = str(operation_id or '').strip()
|
||
if not op_id:
|
||
raise ValidationError(
|
||
'operation_id required (client-generated idempotency component)',
|
||
code='SHIPPING.RECONCILE_OPERATION_ID_REQUIRED',
|
||
)
|
||
if len(op_id) > 128:
|
||
raise ValidationError('operation_id too long (>128)', code='SHIPPING.RECONCILE_OPERATION_ID_TOO_LONG')
|
||
|
||
# [PRE-CHECK] user_action 合法范围
|
||
if user_action not in {'reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto'}:
|
||
raise ValidationError(
|
||
f'invalid user_action: {user_action}',
|
||
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
|
||
details={'allowed': ['reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto']},
|
||
)
|
||
|
||
# [STEP 1] 加载 Case + 权限校验(短事务内 FOR UPDATE,Q11)
|
||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||
|
||
case: ShippingOrderReviewCase = (
|
||
ShippingOrderReviewCase.query
|
||
.filter_by(case_no=str(case_no).strip())
|
||
.order_by(ShippingOrderReviewCase.id.desc())
|
||
.with_for_update()
|
||
.first()
|
||
)
|
||
if case is None:
|
||
from app.core.errors import NotFoundError
|
||
raise NotFoundError(f'review case not found: {case_no}', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||
# 可见性校验
|
||
case_v = get_review_case_visible_to_user(str(case.case_no), int(user_id), is_admin=bool(is_admin))
|
||
if int(case_v.id) != int(case.id):
|
||
raise ValidationError('case visible row differs from locked row; retry',
|
||
code='SHIPPING.RECONCILE_LOCK_VISIBILITY_RACE')
|
||
user = db.session.get(User, int(user_id))
|
||
|
||
# [STEP 1b] 构建请求快照(Q7:source_content_hash / draft_version / case_version / action)
|
||
draft_ver = int(getattr(getattr(case, 'current_draft', None), 'draft_version', 1) or 1)
|
||
case_ver = _case_version(case)
|
||
request_snapshot: dict[str, Any] = {
|
||
'source_content_hash': str(source_content_hash or '').strip() or None,
|
||
'draft_version': draft_ver,
|
||
'case_version': case_ver,
|
||
'action': user_action,
|
||
'contract_version': RECOVERY_CONTRACT_VERSION,
|
||
'owner_user_id': int(case.owner_user_id),
|
||
'document_id': int(case.document_id),
|
||
}
|
||
|
||
# [STEP 2] Q7 幂等校验(返回同 operation_id 第一次结果或抛 409)
|
||
idem_key, prior = _check_idempotency(
|
||
case=case, case_no=str(case.case_no),
|
||
action=user_action, operation_id=op_id,
|
||
expected_case_version=expected_case_version,
|
||
request_snapshot=request_snapshot,
|
||
)
|
||
if prior is not None:
|
||
_write_reconcile_audit_and_event(
|
||
case=case, user=user, operation_id=op_id, idempotency_key=idem_key,
|
||
request_snapshot=request_snapshot, result=prior, user_action=user_action,
|
||
)
|
||
db.session.commit()
|
||
return prior
|
||
|
||
# [STEP 3] L1-L3 对账(只读查询,reconcile_queries 严格按 Q1 五级顺序 + 真实 DB 关系)
|
||
match_result: ReconcileMatchResult = query_case_task_ownership(case)
|
||
mlvl: str = match_result['match_level']
|
||
confidence: str = match_result['confidence']
|
||
matched_task_no: str | None = match_result.get('task_no')
|
||
matched_task: ShippingOrderTask | None = (
|
||
ShippingOrderTask.query.filter_by(task_no=matched_task_no).first()
|
||
if matched_task_no else None
|
||
)
|
||
|
||
# [PRE-CHECK] force_create 必须有权限(复用 Candidate 级权限规则)
|
||
if user_action == 'force_create' and not is_admin and not can_force_create_shipping_duplicate(user):
|
||
raise ValidationError(
|
||
'force_create requires admin or special permission',
|
||
code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED',
|
||
)
|
||
|
||
# [STEP 4] 按 match_level + user_action 路由
|
||
final_result: ReconcileProgressResult | None = None
|
||
resume_outcome: dict[str, Any] | None = None
|
||
job_id: int | None = None
|
||
outcome_task_no: str | None = None
|
||
msg = ''
|
||
audit_actor: Literal['user', 'system'] = 'user' if user_id > 0 else 'system'
|
||
|
||
# ------------------------------------------------
|
||
# BRANCH A:用户明确裁决 create_revision / force_create
|
||
# ------------------------------------------------
|
||
if user_action in {'create_revision', 'force_create'}:
|
||
# Q3:不直改 duplicate_status — 资格刷新 → resume → STP
|
||
resume_outcome, job_id, stp_status = _candidate_refresh_resume_stp_flow(
|
||
case=case, user_id=int(user_id),
|
||
)
|
||
if job_id:
|
||
msg = f'duplicate resolved via {user_action}; STP {stp_status} (job {job_id})'
|
||
final_result = ReconcileProgressResult(
|
||
outcome='stp_enqueued',
|
||
case_no=str(case.case_no), match=match_result,
|
||
task_no=outcome_task_no, job_id=job_id, idempotency_key=idem_key,
|
||
operation_id=op_id, resume_outcome=resume_outcome,
|
||
audit_written=False, message=msg,
|
||
)
|
||
else:
|
||
msg = f'duplicate resolved via {user_action}; STP not eligible ({stp_status})'
|
||
final_result = ReconcileProgressResult(
|
||
outcome='resume_result',
|
||
case_no=str(case.case_no), match=match_result,
|
||
task_no=None, job_id=None, idempotency_key=idem_key,
|
||
operation_id=op_id, resume_outcome=resume_outcome,
|
||
audit_written=False, message=msg,
|
||
)
|
||
|
||
# ------------------------------------------------
|
||
# BRANCH B:L1 CERTAIN → 复用(用户动作 reuse_existing 或 auto)
|
||
# ------------------------------------------------
|
||
elif mlvl == ReconcileMatchLevel.L1 and matched_task is not None and user_action in {'auto', 'reuse_existing'}:
|
||
_write_back_case_task_binding(case=case, task=matched_task, actor_type=audit_actor)
|
||
outcome_task_no = str(matched_task.task_no)
|
||
msg = f'reuse existing task (L1 {confidence}): {outcome_task_no}'
|
||
final_result = ReconcileProgressResult(
|
||
outcome='reused_existing',
|
||
case_no=str(case.case_no), match=match_result,
|
||
task_no=outcome_task_no, job_id=None, idempotency_key=idem_key,
|
||
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
|
||
)
|
||
|
||
# ------------------------------------------------
|
||
# BRANCH C:L2 PROBABLE + reuse_existing → 绑定(用户明确点击复用)
|
||
# ------------------------------------------------
|
||
elif (mlvl == ReconcileMatchLevel.L2
|
||
and user_action == 'reuse_existing'
|
||
and matched_task is not None
|
||
and confidence in {ReconcileConfidence.CERTAIN, ReconcileConfidence.PROBABLE}):
|
||
_write_back_case_task_binding(case=case, task=matched_task, actor_type=audit_actor)
|
||
outcome_task_no = str(matched_task.task_no)
|
||
msg = f'reuse existing task (L2 {confidence}): {outcome_task_no}'
|
||
final_result = ReconcileProgressResult(
|
||
outcome='reused_existing',
|
||
case_no=str(case.case_no), match=match_result,
|
||
task_no=outcome_task_no, job_id=None, idempotency_key=idem_key,
|
||
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
|
||
)
|
||
|
||
# ------------------------------------------------
|
||
# BRANCH D:L2 auto 或 L3 → duplicate_decision_required(不绑定,返回给前端裁决面板)
|
||
# ------------------------------------------------
|
||
elif (mlvl in {ReconcileMatchLevel.L2, ReconcileMatchLevel.L3}
|
||
and user_action in {'auto', 'adjudicate'}):
|
||
msg = (f'duplicate decision required (match_level={mlvl}, confidence={confidence}); '
|
||
f'candidates={len(match_result.get("evidence", {}).get("candidate_matches") or [])}')
|
||
final_result = ReconcileProgressResult(
|
||
outcome='duplicate_decision_required',
|
||
case_no=str(case.case_no), match=match_result,
|
||
task_no=None, job_id=None, idempotency_key=idem_key,
|
||
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
|
||
)
|
||
|
||
# ------------------------------------------------
|
||
# BRANCH E:NONE → 无冲突,resume → STP 标准新路径
|
||
# ------------------------------------------------
|
||
elif mlvl == ReconcileMatchLevel.NONE:
|
||
resume_outcome, job_id, stp_status = _candidate_refresh_resume_stp_flow(
|
||
case=case, user_id=int(user_id),
|
||
)
|
||
if job_id:
|
||
msg = f'no task conflict; STP {stp_status} (job {job_id})'
|
||
final_result = ReconcileProgressResult(
|
||
outcome='stp_enqueued',
|
||
case_no=str(case.case_no), match=match_result,
|
||
task_no=None, job_id=job_id, idempotency_key=idem_key,
|
||
operation_id=op_id, resume_outcome=resume_outcome,
|
||
audit_written=False, message=msg,
|
||
)
|
||
else:
|
||
msg = f'no task conflict; STP not eligible ({stp_status})'
|
||
final_result = ReconcileProgressResult(
|
||
outcome='resume_result',
|
||
case_no=str(case.case_no), match=match_result,
|
||
task_no=None, job_id=None, idempotency_key=idem_key,
|
||
operation_id=op_id, resume_outcome=resume_outcome,
|
||
audit_written=False, message=msg,
|
||
)
|
||
|
||
# ------------------------------------------------
|
||
# BRANCH F:其它组合(如 L3+reuse_existing 太模糊)→ ownership_anomaly 隔离(Q13)
|
||
# ------------------------------------------------
|
||
if final_result is None:
|
||
pending_reason = 'ownership_anomaly'
|
||
# [Phase 4 Q13 硬隔离] — 先回滚 BRANCH B/C 半写(_write_back_case_task_binding)
|
||
# 避免把 Case 的 candidate_id / confirmed_task_id / fulfilled_task_id 留痕;
|
||
# 再单独写 sensitive 审计;ReviewCase 不承担履约阶段字段
|
||
# outcome=ownership_anomaly_rejected 或抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY。
|
||
try:
|
||
db.session.rollback()
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
# 重新 reload case 行(rollback 后失效 ORM 对象;不 FOR UPDATE 因为只读写审计)
|
||
case_after: ShippingOrderReviewCase | None = (
|
||
ShippingOrderReviewCase.query
|
||
.filter_by(id=int(case.id))
|
||
.first()
|
||
)
|
||
if case_after is None:
|
||
case_after = case
|
||
# 写高敏感审计:归属异常 Q13 触发点;metadata 包含 match_level_steps 全量证据。
|
||
try:
|
||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||
match_evidence: dict[str, Any] = {
|
||
'match_level': match_result.get('match_level'),
|
||
'confidence': match_result.get('confidence'),
|
||
'task_no': match_result.get('task_no'),
|
||
'evidence': match_result.get('evidence'),
|
||
'match_level_steps': match_result.get('match_level_steps'),
|
||
'user_action': user_action,
|
||
'case_version': case_ver,
|
||
}
|
||
record_fulfillment_audit(
|
||
user_id=int(user_id) if user else None,
|
||
event_type='shipping_reconcile_ownership_anomaly',
|
||
resource_type='shipping_order_review_case',
|
||
resource_id=str(case_after.case_no),
|
||
review_case_id=int(case_after.id),
|
||
sensitivity_level='sensitive',
|
||
strict=False,
|
||
operation_id=op_id,
|
||
idempotency_key=idem_key,
|
||
metadata=match_evidence,
|
||
)
|
||
except Exception: # noqa: BLE001
|
||
# 审计写入失败不影响硬隔离:Q13 主职责是不写脏数据回正式关系
|
||
pass
|
||
msg = (f'ambiguous ownership: match_level={match_result.get("match_level")} '
|
||
f'user_action={user_action}; marked ownership_anomaly pending human review')
|
||
final_result = ReconcileProgressResult(
|
||
outcome='ownership_anomaly_rejected',
|
||
case_no=str(case_after.case_no), match=match_result,
|
||
task_no=None, job_id=None, idempotency_key=idem_key,
|
||
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
|
||
)
|
||
# 用 case_after 替换引用,防止后续审计写入已失效对象。
|
||
case = case_after
|
||
user = db.session.get(User, int(user_id))
|
||
# 归属 L3 歧义不是可继续处理的业务结果:调用方若收到普通 200 outcome,
|
||
# 仍可能继续执行后续复用/推进。回滚与敏感审计完成后必须硬隔离,要求
|
||
# 用户回到人工裁决面,而不是把不确定归属投影成可操作阶段。
|
||
raise ValidationError(
|
||
'Ambiguous task ownership requires manual adjudication',
|
||
code='SHIPPING.RECONCILE_OWNERSHIP_ANOMALY',
|
||
details={
|
||
'hard_isolation': True,
|
||
'case_no': str(case_after.case_no),
|
||
'match': match_result,
|
||
'user_action': user_action,
|
||
},
|
||
)
|
||
|
||
# [STEP 5] 写审计 + 幂等持久化(CaseEvent 保证下一次同 operation_id 可回返)
|
||
_write_reconcile_audit_and_event(
|
||
case=case, user=user, operation_id=op_id, idempotency_key=idem_key,
|
||
request_snapshot=request_snapshot, result=final_result,
|
||
user_action=user_action, actor_type=audit_actor,
|
||
)
|
||
final_result.audit_written = True
|
||
|
||
# [STEP 6] commit;commit 后 order_review_confirmation.schedule... 钩子由上层 API 触发
|
||
db.session.commit()
|
||
|
||
return final_result
|
||
|
||
|
||
# ============================================================
|
||
# 辅助:供现有 retry-stp-auto-create API 做前置 blocked_manual 拦截
|
||
# ============================================================
|
||
|
||
def assert_case_not_blocked_manual(*, case_no: str, case: ShippingOrderReviewCase) -> None:
|
||
"""
|
||
Phase 2-4:retry-stp-auto-create 前置校验(Q6 职责边界)。
|
||
blocked_manual = Projection 层 automation.retryable=false + blocking_reason 非空。
|
||
若命中 → 抛 409,要求改用 reconcile-and-progress(返回 adjudicate_duplicate)。
|
||
"""
|
||
# 读取 Case 关联的最新 failed STP Job.result_json
|
||
# 说明:Job 模型没有 reference_type / reference_key,通过 business_ref 前缀匹配。
|
||
_run_no = str(getattr(getattr(case, 'run', None), 'run_no', '') or '').strip()
|
||
_doc_id = getattr(case, 'document_id', None)
|
||
_stp_prefix = None
|
||
if _run_no and _doc_id is not None:
|
||
_stp_prefix = f'stp-auto:{_run_no}:doc-{int(_doc_id)}:'
|
||
|
||
latest: Job | None = None
|
||
if _stp_prefix is not None:
|
||
latest = (
|
||
Job.query
|
||
.filter(Job.domain == 'shipping_notice',
|
||
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||
Job.business_ref.like(f"{_stp_prefix}%"))
|
||
.filter(Job.status.in_(['failed', 'dead']))
|
||
.order_by(Job.created_at.desc())
|
||
.first()
|
||
)
|
||
if latest is None:
|
||
return
|
||
rj = latest.result_json if isinstance(latest.result_json, dict) else {}
|
||
retryable_flag = bool(rj.get('retryable', True))
|
||
error_code = str(rj.get('error_code') or '').strip()
|
||
blocking_reason_raw = rj.get('blocking_reason')
|
||
blocking_reason = (
|
||
{'code': str(blocking_reason_raw)}
|
||
if isinstance(blocking_reason_raw, str) and blocking_reason_raw
|
||
else blocking_reason_raw if isinstance(blocking_reason_raw, dict) else None
|
||
)
|
||
# 兼容修复前已落库的技术异常:旧结果被错误写成 retryable=false,
|
||
# 但 SHIPPING.STP_AUTO_CREATE_UNEXPECTED 本身不是业务裁决原因,普通
|
||
# retry 应创建新的 Job,而不是强制用户走 reconcile-and-progress。
|
||
# ORDER_FREEZE_BLOCKED:冻结门禁每次 confirm 重算(如预约单号表头回退已修复),
|
||
# 允许技术重试再入队,避免 UI/API 死锁在「人工裁决」文案上。
|
||
effective_error_code = error_code or (
|
||
blocking_reason.get('code')
|
||
if isinstance(blocking_reason, dict)
|
||
else str(blocking_reason or '').strip()
|
||
)
|
||
if not retryable_flag and effective_error_code in {
|
||
'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
|
||
'SHIPPING.ORDER_FREEZE_BLOCKED',
|
||
}:
|
||
return
|
||
if should_general_retry_be_removed(retryable_flag=retryable_flag, blocking_reason=blocking_reason):
|
||
raise ConflictError(
|
||
'Case blocked on manual adjudication; use reconcile-and-progress instead of retry-stp-auto-create',
|
||
code='SHIPPING.RETRY_STP_BLOCKED_MANUAL',
|
||
details={
|
||
'error_code': rj.get('error_code'),
|
||
'blocking_reason': blocking_reason.get('code') if isinstance(blocking_reason, dict) else blocking_reason,
|
||
'next_action': rj.get('next_action'),
|
||
'case_no': case_no,
|
||
'alternative_api': 'POST /workspace/shipping-notice/order-review-cases/<case_no>/reconcile-and-progress',
|
||
'allowed_user_actions': ['reuse_existing', 'create_revision', 'force_create', 'adjudicate'],
|
||
},
|
||
)
|