329 lines
17 KiB
Python
329 lines
17 KiB
Python
"""
|
|
backend/app/services/shipping_notice/candidate_service.py
|
|
|
|
用途:提供订单候选的用户态查询、选择与重复决策能力;含 STP 严格建单门禁。
|
|
依赖:ShippingOrderCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
|
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态;
|
|
仅严格门禁通过且客户已确认的 Candidate 可物化 Task
|
|
(缺字段/低置信/缺证据/重复冲突/客户未确认 → 拒绝)。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from app import db
|
|
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
|
from app.models import FileAsset, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingNotice, User
|
|
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint
|
|
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
|
|
from app.services.shipping_notice.duplicate_detection import apply_duplicate_result_to_candidate, detect_duplicates_for_candidate
|
|
from app.services.shipping_notice.intake_service import can_force_create_shipping_duplicate
|
|
|
|
_ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
|
|
_STP_DUPLICATE_OK = frozenset({'none', 'unchecked'})
|
|
_LIFECYCLE_ELIGIBLE_STATUSES = frozenset({'provisional', 'accepted'})
|
|
|
|
|
|
def is_current_reviewable_candidate(candidate: ShippingOrderCandidate | None) -> bool:
|
|
"""判断 Candidate 是否可作为订单生命周期的当前准入事实。
|
|
|
|
触发时机:Case、批次投影和 Gate 收口需要决定是否可以从接收解析进入订单复核时。
|
|
仅当前版本且仍可复核/已接受的 Candidate 可以开放生命周期;已拒绝、过期、被替代
|
|
或空 Candidate 只能保留审计,不能影响实时阶段或前端入口。
|
|
"""
|
|
return bool(
|
|
candidate is not None
|
|
and bool(getattr(candidate, 'is_current_version', False))
|
|
and str(getattr(candidate, 'candidate_status', '') or '').strip().lower()
|
|
in _LIFECYCLE_ELIGIBLE_STATUSES
|
|
)
|
|
|
|
|
|
def evaluate_candidate_stp_gate(candidate: ShippingOrderCandidate) -> tuple[bool, list[str]]:
|
|
"""
|
|
评估 Candidate 是否通过 STP 严格建单门禁(不抛异常)。
|
|
|
|
核心逻辑:仅对 automatic 接受态施加严格门禁(缺字段、阻断冲突、低置信、缺证据、
|
|
未解决重复)。人工复核确认(acceptance_mode=manual)不走 STP 直通门禁。
|
|
|
|
Args:
|
|
candidate: 待评估订单候选。
|
|
|
|
Returns:
|
|
(是否通过, 失败原因码列表)。
|
|
"""
|
|
if str(candidate.acceptance_mode or '') != 'automatic':
|
|
return True, []
|
|
reasons: list[str] = []
|
|
if str(candidate.validation_status or '') != 'ready':
|
|
reasons.append('incomplete_fields')
|
|
from app.services.shipping_notice.candidate_qualification_service import blocking_candidate_conflicts
|
|
|
|
if blocking_candidate_conflicts(candidate):
|
|
reasons.append('blocking_conflict')
|
|
missing = list(candidate.missing_fields_json or [])
|
|
if missing:
|
|
reasons.append('incomplete_fields')
|
|
evidence = candidate.evidence_json
|
|
if evidence is None or (isinstance(evidence, list) and len(evidence) == 0):
|
|
reasons.append('missing_evidence')
|
|
try:
|
|
confidence = float(candidate.confidence) if candidate.confidence is not None else None
|
|
except (TypeError, ValueError):
|
|
confidence = None
|
|
if confidence is not None and confidence < 0.85:
|
|
reasons.append('low_confidence')
|
|
dup_status = str(candidate.duplicate_status or 'unchecked')
|
|
if dup_status not in _STP_DUPLICATE_OK:
|
|
if str(candidate.duplicate_resolution or '') != 'open_existing':
|
|
reasons.append('duplicate_conflict')
|
|
return not reasons, sorted(set(reasons))
|
|
|
|
|
|
def ensure_candidate_fulfillment_ready(candidate: ShippingOrderCandidate) -> None:
|
|
"""
|
|
统一履约门禁:已接受、当前、无阻断;建 Task 前客户必须已确认;
|
|
automatic 候选额外通过 STP 严格门禁。
|
|
|
|
Raises:
|
|
ConflictError: 接受态、选中态、版本、消费态、客户未确认或 STP 严格门禁失败。
|
|
"""
|
|
if str(candidate.candidate_status or '') != 'accepted':
|
|
raise ConflictError(
|
|
code='SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED',
|
|
message='订单候选尚未被接受,不能进入履约',
|
|
)
|
|
if not candidate.selected:
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中')
|
|
if not candidate.is_current_version:
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代')
|
|
if candidate.consumed_task_id is not None:
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
|
from app.services.shipping_notice.candidate_qualification_service import blocking_candidate_conflicts
|
|
|
|
if str(candidate.validation_status or '') != 'ready' or blocking_candidate_conflicts(candidate):
|
|
raise ConflictError(
|
|
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
|
message='订单候选仍有字段冲突或未完成审核',
|
|
)
|
|
# [STEP] 客户确认必须在创建 Task 之前,禁止依赖建单后 customer_review。
|
|
from app.services.shipping_notice.candidate_qualification_service import (
|
|
assert_customer_confirmed_before_task_create,
|
|
)
|
|
|
|
assert_customer_confirmed_before_task_create(candidate=candidate)
|
|
# [STEP] STP 严格门禁仅约束自动直通;人工确认建单已由复核草稿校验背书。
|
|
passed, reason_codes = evaluate_candidate_stp_gate(candidate)
|
|
if not passed:
|
|
raise ConflictError(
|
|
code='SHIPPING_NOTICE.CANDIDATE_STP_GATE_FAILED',
|
|
message='订单候选未通过直通建单严格门禁',
|
|
details={'reason_codes': reason_codes},
|
|
)
|
|
|
|
|
|
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingOrderCandidate, ShippingOrderIntake, ShippingOrderDocument]:
|
|
"""按候选编号和用户加载 Candidate、Intake、Document;写路径可加行锁。"""
|
|
query = (
|
|
db.session.query(ShippingOrderCandidate, ShippingOrderIntake, ShippingOrderDocument)
|
|
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderCandidate.intake_id)
|
|
.join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingOrderCandidate.primary_document_id)
|
|
.filter(
|
|
ShippingOrderCandidate.candidate_no == str(candidate_no or '').strip().upper(),
|
|
ShippingOrderIntake.user_id == int(user_id),
|
|
)
|
|
)
|
|
if lock:
|
|
query = query.with_for_update()
|
|
row = query.first()
|
|
if row is None:
|
|
raise NotFoundError(code='SHIPPING_NOTICE.CANDIDATE_NOT_FOUND', message='订单候选不存在')
|
|
return row
|
|
|
|
|
|
def _refresh_candidate(candidate: ShippingOrderCandidate, intake: ShippingOrderIntake, document: ShippingOrderDocument) -> dict[str, Any]:
|
|
"""重算 Candidate 双指纹和重复状态,不提交事务。"""
|
|
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
|
|
summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
|
|
identity = build_business_fingerprint(summary)
|
|
content = build_content_fingerprint(summary)
|
|
asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
|
|
result = detect_duplicates_for_candidate(
|
|
intake=intake,
|
|
asset=asset,
|
|
document=document,
|
|
business_summary=summary,
|
|
fingerprint_result=identity,
|
|
content_fingerprint_result=content,
|
|
)
|
|
candidate.business_fingerprint = identity.get('fingerprint')
|
|
candidate.fingerprint_version = identity.get('version')
|
|
candidate.fingerprint_strength = identity.get('strength')
|
|
candidate.content_fingerprint = content.get('fingerprint')
|
|
candidate.content_fingerprint_version = content.get('version')
|
|
apply_duplicate_result_to_candidate(candidate, result)
|
|
return result
|
|
|
|
|
|
def update_candidate(*, user_id: int, candidate_no: str, selected: bool) -> dict[str, Any]:
|
|
"""
|
|
更新遗留批量建单流程的候选选择状态。
|
|
|
|
订单抽取的建单前人工编辑只允许通过 Review Draft API 完成,不能覆盖
|
|
机器 Candidate 的业务摘要;本接口仅保留给尚未迁移的历史批量流程。
|
|
"""
|
|
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
|
|
if candidate.consumed_task_id is not None or intake.parse_status == 'consumed':
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
|
if not isinstance(selected, bool):
|
|
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='selected 必须为布尔值')
|
|
# Selection is retained for legacy batch APIs but may not bypass acceptance.
|
|
candidate.selected = selected if candidate.candidate_status == 'accepted' else False
|
|
candidate.updated_at = datetime.utcnow()
|
|
db.session.commit()
|
|
return _serialize_candidate_brief(candidate)
|
|
|
|
|
|
def _append_candidate_decision_history(candidate: ShippingOrderCandidate, *, action: str, user_id: int, reason: str | None = None) -> None:
|
|
"""记录人工采纳或驳回事件,便于审核回放。"""
|
|
structured = dict(candidate.structured_result_json or {})
|
|
history = list(structured.get('manual_review_history') or [])
|
|
history.append({
|
|
'action': action,
|
|
'actor_user_id': int(user_id),
|
|
'reason': str(reason or '').strip() or None,
|
|
'decided_at': datetime.utcnow().isoformat(),
|
|
})
|
|
structured['manual_review_history'] = history
|
|
candidate.structured_result_json = structured
|
|
|
|
|
|
def promote_candidate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
|
|
"""人工采纳 Dify 兜底 Candidate;重复采纳请求保持幂等。"""
|
|
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
|
|
if candidate.candidate_status == 'accepted':
|
|
return _serialize_candidate_brief(candidate)
|
|
if candidate.candidate_status != 'provisional':
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DECISION_FINAL', message='订单候选已被驳回或过期')
|
|
if str(candidate.extraction_source or '') not in {'dify_workflow', 'manual'}:
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_PROMOTION_FORBIDDEN', message='仅 Dify 兜底候选允许人工采纳')
|
|
if candidate.consumed_task_id is not None or not candidate.is_current_version:
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选不可再采纳')
|
|
_refresh_candidate(candidate, intake, document)
|
|
from app.services.shipping_notice.candidate_qualification_service import blocking_candidate_conflicts
|
|
|
|
if (
|
|
candidate.validation_status != 'ready'
|
|
or blocking_candidate_conflicts(candidate)
|
|
or candidate.duplicate_status not in {'none', 'unchecked'}
|
|
):
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED', message='请先完成字段和重复审核')
|
|
candidate.candidate_status = 'accepted'
|
|
candidate.acceptance_mode = 'manual'
|
|
candidate.accepted_at = datetime.utcnow()
|
|
candidate.accepted_by_id = int(user_id)
|
|
candidate.acceptance_reason = 'dify_candidate_promoted'
|
|
candidate.acceptance_policy_version = 'manual-review-v1'
|
|
candidate.selected = True
|
|
_append_candidate_decision_history(candidate, action='promoted', user_id=user_id)
|
|
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
|
record_fulfillment_audit(
|
|
event_type='candidate_promoted',
|
|
aggregate_type='order_candidate',
|
|
aggregate_id=candidate.candidate_no,
|
|
action='promote',
|
|
actor_type='user',
|
|
actor_id=user_id,
|
|
run_no=getattr(candidate, 'run_no', None) or None,
|
|
document_id=getattr(document, 'id', None),
|
|
before={'status': 'provisional'},
|
|
after={'status': 'accepted'},
|
|
metadata={'acceptance_mode': 'manual'},
|
|
)
|
|
db.session.commit()
|
|
return _serialize_candidate_brief(candidate)
|
|
|
|
|
|
def reject_candidate(*, user_id: int, candidate_no: str, reason: str | None = None) -> dict[str, Any]:
|
|
"""人工驳回未消费 Candidate,并保留审计原因。"""
|
|
candidate, intake, _document = _candidate_for_user(candidate_no, user_id, lock=True)
|
|
if candidate.candidate_status == 'rejected':
|
|
return _serialize_candidate_brief(candidate)
|
|
if candidate.candidate_status != 'provisional' or candidate.consumed_task_id is not None or not candidate.is_current_version:
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DECISION_FINAL', message='订单候选不可再驳回')
|
|
candidate.candidate_status = 'rejected'
|
|
candidate.selected = False
|
|
candidate.acceptance_mode = None
|
|
candidate.accepted_at = None
|
|
candidate.accepted_by_id = None
|
|
candidate.acceptance_reason = str(reason or '').strip() or 'manual_rejected'
|
|
candidate.acceptance_policy_version = 'manual-review-v1'
|
|
candidate.updated_at = datetime.utcnow()
|
|
_append_candidate_decision_history(candidate, action='rejected', user_id=user_id, reason=reason)
|
|
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
|
record_fulfillment_audit(
|
|
event_type='candidate_rejected',
|
|
aggregate_type='order_candidate',
|
|
aggregate_id=candidate.candidate_no,
|
|
action='reject',
|
|
actor_type='user',
|
|
actor_id=user_id,
|
|
run_no=getattr(candidate, 'run_no', None) or None,
|
|
reason_code='task_rejected_by_user',
|
|
before={'status': 'provisional'},
|
|
after={'status': 'rejected'},
|
|
)
|
|
db.session.commit()
|
|
return _serialize_candidate_brief(candidate)
|
|
|
|
|
|
def refresh_candidate_duplicate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
|
|
"""刷新单个 Candidate 的重复检测结果并清除陈旧决策。"""
|
|
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
|
|
if candidate.consumed_task_id is not None or intake.parse_status == 'consumed':
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
|
_refresh_candidate(candidate, intake, document)
|
|
db.session.commit()
|
|
return _serialize_candidate_brief(candidate)
|
|
|
|
|
|
def resolve_candidate_duplicate(*, user_id: int, candidate_no: str, action: str, target_task_no: str | None = None, reason: str | None = None, actor: User | None = None) -> dict[str, Any]:
|
|
"""保存单个 Candidate 的重复处理决策,并校验目标、权限及强制原因。"""
|
|
action_norm = str(action or '').strip().lower()
|
|
if action_norm not in _ACTIONS:
|
|
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='无效的重复处理动作')
|
|
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
|
|
if candidate.consumed_task_id is not None or intake.parse_status == 'consumed':
|
|
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
|
result = _refresh_candidate(candidate, intake, document)
|
|
if action_norm not in set(result.get('allowed_actions') or []):
|
|
raise ConflictError(
|
|
code='SHIPPING_NOTICE.DUPLICATE_ACTION_UNAVAILABLE',
|
|
message='当前重复状态不允许该处理方式',
|
|
)
|
|
matches = list(result.get('matches') or [])
|
|
target_no = str(target_task_no or '').strip().upper() or (
|
|
str(matches[0].get('task_no') or '').strip().upper() if matches else ''
|
|
)
|
|
if not target_no or not any(str(item.get('task_no') or '').upper() == target_no for item in matches):
|
|
raise NotFoundError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在或已变化')
|
|
target = db.session.query(ShippingNotice).filter_by(task_no=target_no, user_id=int(user_id)).first()
|
|
if target is None:
|
|
raise NotFoundError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在')
|
|
if action_norm == 'force_create':
|
|
user = actor or db.session.get(User, int(user_id))
|
|
if not can_force_create_shipping_duplicate(user):
|
|
raise ForbiddenError(code='SHIPPING_NOTICE.DUPLICATE_OVERRIDE_FORBIDDEN', message='无权强制新建重复订单')
|
|
if not str(reason or '').strip():
|
|
raise ValidationError(code='SHIPPING_NOTICE.DUPLICATE_REASON_REQUIRED', message='强制新建必须填写原因')
|
|
candidate.duplicate_resolution = action_norm
|
|
candidate.duplicate_target_task_no = target_no
|
|
candidate.duplicate_resolution_reason = str(reason or '').strip() or None
|
|
candidate.duplicate_resolved_by_id = int(user_id)
|
|
candidate.duplicate_resolved_at = datetime.utcnow()
|
|
candidate.updated_at = datetime.utcnow()
|
|
db.session.commit()
|
|
return _serialize_candidate_brief(candidate)
|