146 lines
8.3 KiB
Python
146 lines
8.3 KiB
Python
"""
|
|
backend/app/services/shipping_notice/candidate_service.py
|
|
|
|
用途:提供订单候选的用户态查询、修订、选择与重复决策能力。
|
|
依赖:ShippingNoticeCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
|
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态。
|
|
"""
|
|
|
|
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, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, ShippingTask, User
|
|
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint
|
|
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
|
|
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'})
|
|
|
|
|
|
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]:
|
|
"""按候选编号和用户加载 Candidate、Intake、Document;写路径可加行锁。"""
|
|
query = (
|
|
db.session.query(ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument)
|
|
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeCandidate.intake_id)
|
|
.join(ShippingNoticeDocument, ShippingNoticeDocument.id == ShippingNoticeCandidate.primary_document_id)
|
|
.filter(
|
|
ShippingNoticeCandidate.candidate_no == str(candidate_no or '').strip().upper(),
|
|
ShippingNoticeIntake.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: ShippingNoticeCandidate, intake: ShippingNoticeIntake, document: ShippingNoticeDocument) -> 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 | None = None, business_summary: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
"""
|
|
更新候选选择状态或人工修订后的业务摘要。
|
|
|
|
核心逻辑:已消费候选禁止修改;摘要变化时清除冲突、置 ready 并重算双指纹与判重。
|
|
"""
|
|
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 selected is not None:
|
|
if not isinstance(selected, bool):
|
|
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='selected 必须为布尔值')
|
|
candidate.selected = selected
|
|
if business_summary is not None:
|
|
if not isinstance(business_summary, dict):
|
|
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='business_summary 必须为对象')
|
|
normalized_summary = normalize_candidate_business_summary(business_summary)
|
|
structured = dict(candidate.structured_result_json or {})
|
|
structured['business_summary'] = normalized_summary
|
|
structured['manual_edited'] = True
|
|
candidate.structured_result_json = structured
|
|
candidate.po_number = str(normalized_summary.get('po_number') or '').strip() or None
|
|
candidate.conflicts_json = []
|
|
candidate.validation_status = 'ready'
|
|
_refresh_candidate(candidate, intake, document)
|
|
candidate.updated_at = datetime.utcnow()
|
|
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(ShippingTask).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)
|