feat(shipping-notice): 新增发货通知重复检测与处理接口,支持重复决策保存与重新执行检测

This commit is contained in:
hugo committed 2026-07-14 21:12:36 +08:00
1 parent 729546a7b7
commit ceb49461e8
72 files changed
+14270 -460

No files matched your search

@@ -0,0 +1,609 @@
"""
backend/app/services/shipping_notice/duplicate_detection.py
用途:发货通知业务重复检测(文件哈希 + 业务指纹),产出统一 duplicate 结果。
依赖:models.ShippingTask/FileAsset/Document/Candidate、business_fingerprint、core.response.utc_iso。
逻辑:Intake 级与 Candidate 级共用匹配规则;候选 A 重复只写回 A,不连带阻断同信其它候选;
刷新入口按 Candidate 重检再聚合到 Intake;检测异常可 clear 为 unchecked;
范围限定当前 user_id,不跨用户泄露。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.response import utc_iso
from app.models import (
FileAsset,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingTask,
)
from app.services.shipping_notice.business_fingerprint import FINGERPRINT_VERSION, build_business_fingerprint
# 与 state_machine 主路径对齐的活跃/完成/关闭态(禁止 needs_review/matching/export_ready 等非主状态)
_ACTIVE_PROCESS_STATUSES = frozenset(
{
'created',
'parsed',
'pending_review',
'inventory_ready',
'waiting_inventory',
'matched',
'waiting_upload',
'upload_failed',
}
)
_COMPLETED_PROCESS_STATUSES = frozenset({'uploaded', 'completed'})
_CLOSED_PROCESS_STATUSES = frozenset({'closed', 'rejected'})
_IRREVERSIBLE_PROCESS_STATUSES = frozenset({'uploaded', 'completed', 'closed', 'rejected'})
def classify_task_lifecycle(process_status: str | None) -> str:
"""将 process_status 归类为 active / completed / closed / unknown。"""
status = str(process_status or '').strip().lower()
if status in _ACTIVE_PROCESS_STATUSES:
return 'active'
if status in _COMPLETED_PROCESS_STATUSES:
return 'completed'
if status in _CLOSED_PROCESS_STATUSES:
return 'closed'
return 'unknown'
def is_irreversible_task(task: ShippingTask) -> bool:
"""已 uploaded 或终态任务不可原地覆盖源文件。"""
status = str(task.process_status or '').strip().lower()
if status in _IRREVERSIBLE_PROCESS_STATUSES:
return True
upload_status = str(task.upload_status or '').strip().lower()
return upload_status in {'uploaded', 'succeeded', 'success'}
def _match_payload(task: ShippingTask, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]:
return {
'task_no': task.task_no,
'process_status': task.process_status,
'document_version': int(task.document_version or 1),
'match_type': match_type,
'matched_fields': list(matched_fields),
'lifecycle': classify_task_lifecycle(task.process_status),
'created_at': utc_iso(task.created_at),
}
def _allowed_actions_for(
*,
status: str,
fingerprint_strength: str,
matches: list[dict[str, Any]],
) -> list[str]:
if status in {'none', 'unchecked'} or not matches:
return []
actions = ['open_existing']
primary = matches[0]
lifecycle = str(primary.get('lifecycle') or '')
if lifecycle in {'active', 'completed', 'closed'}:
actions.append('create_revision')
if fingerprint_strength in {'strong', 'medium', 'weak', 'unavailable'}:
actions.append('force_create')
return actions
def detect_duplicates_for_intake(
*,
intake: ShippingNoticeIntake,
asset: FileAsset | None = None,
business_summary: dict[str, Any] | None = None,
fingerprint_result: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
对已解析 intake 执行重复检测。
核心逻辑:
1. 同用户同 content_hash 且已有未关闭任务 → exact_file;
2. 同业务指纹任务 → same_active_task / same_completed_task;
3. 弱指纹仅可能标记 possible_duplicate;
4. strength=unavailable 不阻断。
Returns:
{status, blocking, fingerprint_strength, fingerprint, fingerprint_version, matches, allowed_actions, components}
"""
summary = business_summary if isinstance(business_summary, dict) else (
intake.structured_result_json.get('business_summary')
if isinstance(intake.structured_result_json, dict)
else None
)
fp = fingerprint_result or build_business_fingerprint(summary if isinstance(summary, dict) else {})
strength = str(fp.get('strength') or 'unavailable')
fingerprint = fp.get('fingerprint')
version = str(fp.get('version') or FINGERPRINT_VERSION)
components = fp.get('components') if isinstance(fp.get('components'), dict) else {}
if asset is None:
asset = db.session.get(FileAsset, int(intake.asset_id))
matches: list[dict[str, Any]] = []
status = 'none'
# [STEP 1] 精确文件哈希
content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower()
if content_hash:
hash_tasks = (
db.session.query(ShippingTask)
.filter(
ShippingTask.user_id == int(intake.user_id),
ShippingTask.source_content_hash == content_hash,
ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
)
.order_by(ShippingTask.id.desc())
.limit(10)
.all()
)
for task in hash_tasks:
matches.append(
_match_payload(
task,
match_type='exact_file',
matched_fields=['source_content_hash'],
)
)
if matches:
status = 'exact_file'
# [STEP 2] 业务指纹
if fingerprint and strength in {'strong', 'medium'}:
fp_tasks = (
db.session.query(ShippingTask)
.filter(
ShippingTask.user_id == int(intake.user_id),
ShippingTask.business_fingerprint == fingerprint,
ShippingTask.fingerprint_version == version,
)
.order_by(ShippingTask.id.desc())
.limit(20)
.all()
)
matched_fields = list(components.keys())
for task in fp_tasks:
# 跳过已被当前 exact_file 命中过的同一 task
if any(m.get('task_no') == task.task_no for m in matches):
continue
matches.append(
_match_payload(
task,
match_type='business_fingerprint',
matched_fields=matched_fields,
)
)
if matches and status == 'none':
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
if primary_life == 'active':
status = 'same_active_task'
elif primary_life == 'completed':
status = 'same_completed_task'
else:
status = 'possible_duplicate'
elif matches and status == 'exact_file':
# 同文件命中优先;保留 status=exact_file
pass
elif fingerprint and strength == 'weak' and status == 'none':
# 弱指纹:仅标记疑似,不按 active 强阻断
fp_tasks = (
db.session.query(ShippingTask)
.filter(
ShippingTask.user_id == int(intake.user_id),
ShippingTask.business_fingerprint == fingerprint,
ShippingTask.fingerprint_version == version,
ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
)
.order_by(ShippingTask.id.desc())
.limit(5)
.all()
)
for task in fp_tasks:
matches.append(
_match_payload(
task,
match_type='weak_fingerprint',
matched_fields=list(components.keys()),
)
)
if matches:
status = 'possible_duplicate'
blocking = status in {
'exact_file',
'same_active_task',
'same_completed_task',
'possible_duplicate', # 疑似重复须用户确认,不可静默建单
}
if strength == 'unavailable' and status == 'none':
blocking = False
return {
'status': status,
'blocking': blocking,
'fingerprint_strength': strength,
'fingerprint': fingerprint,
'fingerprint_version': version,
'components': components,
'matches': matches,
'allowed_actions': _allowed_actions_for(
status=status,
fingerprint_strength=strength,
matches=matches,
),
'checked_at': utc_iso(datetime.utcnow()),
}
def apply_duplicate_result_to_intake(
intake: ShippingNoticeIntake,
result: dict[str, Any],
) -> None:
"""将检测结果写回 intake ORM 字段(不 commit)。"""
intake.business_fingerprint = result.get('fingerprint')
intake.fingerprint_version = result.get('fingerprint_version')
intake.fingerprint_strength = result.get('fingerprint_strength')
intake.duplicate_status = str(result.get('status') or 'none')
intake.duplicate_matches_json = list(result.get('matches') or [])
intake.duplicate_checked_at = datetime.utcnow()
# 重新检测后清空旧决策,避免陈旧 resolution
intake.duplicate_resolution = None
intake.duplicate_resolution_reason = None
intake.duplicate_target_task_no = None
intake.duplicate_resolved_by_id = None
intake.duplicate_resolved_at = None
intake.updated_at = datetime.utcnow()
def clear_duplicate_state_to_unchecked(*, intake: ShippingNoticeIntake) -> None:
"""
将 Intake 与其 Candidate 的重复结果/决策统一清空为 unchecked。
核心逻辑:重复检测 SAVEPOINT 回滚后调用,避免 partial 写回与陈旧 resolution 并存。
"""
now = datetime.utcnow()
intake.duplicate_status = 'unchecked'
intake.duplicate_matches_json = []
intake.business_fingerprint = None
intake.fingerprint_version = None
intake.fingerprint_strength = None
intake.duplicate_checked_at = now
intake.duplicate_resolution = None
intake.duplicate_resolution_reason = None
intake.duplicate_target_task_no = None
intake.duplicate_resolved_by_id = None
intake.duplicate_resolved_at = None
intake.updated_at = now
candidates = (
db.session.query(ShippingNoticeCandidate)
.filter(ShippingNoticeCandidate.intake_id == int(intake.id))
.all()
)
for candidate in candidates:
candidate.duplicate_status = 'unchecked'
candidate.duplicate_matches_json = []
candidate.duplicate_checked_at = now
candidate.duplicate_resolution = None
candidate.duplicate_resolution_reason = None
candidate.duplicate_target_task_no = None
candidate.updated_at = now
def apply_duplicate_result_to_candidate(
candidate: ShippingNoticeCandidate,
result: dict[str, Any],
*,
clear_resolution: bool = True,
) -> None:
"""
将检测结果写回 Candidate ORM 字段(不 commit)。
核心逻辑:刷新/重解析后同步 duplicate_* 与指纹概要;默认清空旧决策。
"""
candidate.duplicate_status = str(result.get('status') or 'none')
candidate.duplicate_matches_json = list(result.get('matches') or [])
candidate.duplicate_checked_at = datetime.utcnow()
if result.get('fingerprint') is not None:
candidate.business_fingerprint = result.get('fingerprint')
if result.get('fingerprint_version') is not None:
candidate.fingerprint_version = result.get('fingerprint_version')
if result.get('fingerprint_strength') is not None:
candidate.fingerprint_strength = result.get('fingerprint_strength')
if clear_resolution:
candidate.duplicate_resolution = None
candidate.duplicate_resolution_reason = None
candidate.duplicate_target_task_no = None
candidate.updated_at = datetime.utcnow()
def refresh_candidates_and_aggregate_intake(
*,
intake: ShippingNoticeIntake,
parent_asset: FileAsset | None = None,
) -> dict[str, Any]:
"""
逐 Candidate 重跑重复检测,写回各候选后聚合 Intake 概览。
核心逻辑:有 Candidate 时必须走候选级路径,避免仅刷新 Intake 造成数据分裂;
无候选时回退扁平 Intake 级检测。
调用方须已对 Intake FOR UPDATE,并确认仍为 parsed 且未消费。
Returns:
聚合后的 duplicate 结果(已 apply 到 Intake;Candidate 已写回)。
"""
candidates = (
db.session.query(ShippingNoticeCandidate)
.filter(ShippingNoticeCandidate.intake_id == int(intake.id))
.order_by(ShippingNoticeCandidate.id.asc())
.all()
)
if not candidates:
summary = (
intake.structured_result_json.get('business_summary')
if isinstance(intake.structured_result_json, dict)
else None
)
summary = summary if isinstance(summary, dict) else {}
fingerprint = build_business_fingerprint(summary)
result = detect_duplicates_for_intake(
intake=intake,
asset=parent_asset,
business_summary=summary,
fingerprint_result=fingerprint,
)
apply_duplicate_result_to_intake(intake, result)
return result
candidate_results: list[dict[str, Any]] = []
for candidate in candidates:
document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id))
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 {}
fingerprint = build_business_fingerprint(summary)
child_asset = None
if document is not None and document.asset_id:
child_asset = db.session.get(FileAsset, int(document.asset_id))
dup = detect_duplicates_for_candidate(
intake=intake,
asset=child_asset or parent_asset,
document=document,
business_summary=summary,
fingerprint_result=fingerprint,
)
apply_duplicate_result_to_candidate(candidate, dup)
candidate_results.append(dup)
aggregated = aggregate_intake_duplicate_from_candidates(intake, candidate_results)
# 概览指纹不足时用扁平摘要补强列表展示
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
flat_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
if flat_summary and not aggregated.get('fingerprint'):
flat_fp = build_business_fingerprint(flat_summary)
if flat_fp.get('fingerprint'):
aggregated = {
**aggregated,
'fingerprint': flat_fp.get('fingerprint'),
'fingerprint_version': flat_fp.get('version'),
'fingerprint_strength': flat_fp.get('strength'),
'components': flat_fp.get('components') or {},
}
apply_duplicate_result_to_intake(intake, aggregated)
return aggregated
def detect_duplicates_for_candidate(
*,
intake: ShippingNoticeIntake,
asset: FileAsset | None = None,
document: ShippingNoticeDocument | None = None,
business_summary: dict[str, Any] | None = None,
fingerprint_result: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
对单个订单候选执行重复检测(不写 Intake,不影响同信其它候选)。
核心逻辑:与 detect_duplicates_for_intake 同源规则,但 exact_file 优先用
Document/派生资产 content_hash(单 PDF),避免整封 EML 哈希误伤其它订单。
Returns:
与 intake 检测相同结构的结果字典。
"""
summary = business_summary if isinstance(business_summary, dict) else {}
fp = fingerprint_result or build_business_fingerprint(summary)
strength = str(fp.get('strength') or 'unavailable')
fingerprint = fp.get('fingerprint')
version = str(fp.get('version') or FINGERPRINT_VERSION)
components = fp.get('components') if isinstance(fp.get('components'), dict) else {}
content_hash = ''
if document is not None and str(document.content_hash or '').strip():
content_hash = str(document.content_hash).strip().lower()
if not content_hash and asset is not None:
content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower()
matches: list[dict[str, Any]] = []
status = 'none'
# [STEP 1] 精确文件哈希(附件级)
if content_hash:
hash_tasks = (
db.session.query(ShippingTask)
.filter(
ShippingTask.user_id == int(intake.user_id),
ShippingTask.source_content_hash == content_hash,
ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
)
.order_by(ShippingTask.id.desc())
.limit(10)
.all()
)
for task in hash_tasks:
matches.append(
_match_payload(
task,
match_type='exact_file',
matched_fields=['source_content_hash'],
)
)
if matches:
status = 'exact_file'
# [STEP 2] 业务指纹
if fingerprint and strength in {'strong', 'medium'}:
fp_tasks = (
db.session.query(ShippingTask)
.filter(
ShippingTask.user_id == int(intake.user_id),
ShippingTask.business_fingerprint == fingerprint,
ShippingTask.fingerprint_version == version,
)
.order_by(ShippingTask.id.desc())
.limit(20)
.all()
)
matched_fields = list(components.keys())
for task in fp_tasks:
if any(m.get('task_no') == task.task_no for m in matches):
continue
matches.append(
_match_payload(
task,
match_type='business_fingerprint',
matched_fields=matched_fields,
)
)
if matches and status == 'none':
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
if primary_life == 'active':
status = 'same_active_task'
elif primary_life == 'completed':
status = 'same_completed_task'
else:
status = 'possible_duplicate'
elif fingerprint and strength == 'weak' and status == 'none':
fp_tasks = (
db.session.query(ShippingTask)
.filter(
ShippingTask.user_id == int(intake.user_id),
ShippingTask.business_fingerprint == fingerprint,
ShippingTask.fingerprint_version == version,
ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
)
.order_by(ShippingTask.id.desc())
.limit(5)
.all()
)
for task in fp_tasks:
matches.append(
_match_payload(
task,
match_type='weak_fingerprint',
matched_fields=list(components.keys()),
)
)
if matches:
status = 'possible_duplicate'
blocking = status in {
'exact_file',
'same_active_task',
'same_completed_task',
'possible_duplicate',
}
if strength == 'unavailable' and status == 'none':
blocking = False
return {
'status': status,
'blocking': blocking,
'fingerprint_strength': strength,
'fingerprint': fingerprint,
'fingerprint_version': version,
'components': components,
'matches': matches,
'allowed_actions': _allowed_actions_for(
status=status,
fingerprint_strength=strength,
matches=matches,
),
'checked_at': utc_iso(datetime.utcnow()),
}
def aggregate_intake_duplicate_from_candidates(
intake: ShippingNoticeIntake,
candidate_results: list[dict[str, Any]],
) -> dict[str, Any]:
"""
将多个 Candidate 检测结果汇总到 Intake(仅概览,不抹平单候选独立性)。
核心逻辑:全部 none → none;部分阻断 → partial_duplicate;全部同态则透传该状态。
"""
if not candidate_results:
return {
'status': 'none',
'blocking': False,
'fingerprint_strength': 'unavailable',
'fingerprint': None,
'fingerprint_version': FINGERPRINT_VERSION,
'components': {},
'matches': [],
'allowed_actions': [],
'checked_at': utc_iso(datetime.utcnow()),
}
statuses = [str(item.get('status') or 'none') for item in candidate_results]
blocking_items = [item for item in candidate_results if item.get('blocking')]
unique_blocking = {str(item.get('status') or 'none') for item in blocking_items}
if not blocking_items:
status = 'none'
blocking = False
elif len(unique_blocking) == 1 and len(blocking_items) == len(candidate_results):
status = next(iter(unique_blocking))
blocking = True
else:
status = 'partial_duplicate'
blocking = True
# 概览指纹:取首个强/中指纹候选;否则首个候选
primary = next(
(
item
for item in candidate_results
if str(item.get('fingerprint_strength') or '') in {'strong', 'medium'}
),
candidate_results[0],
)
matches: list[dict[str, Any]] = []
for item in blocking_items:
for match in item.get('matches') or []:
if isinstance(match, dict) and match not in matches:
matches.append(match)
return {
'status': status,
'blocking': blocking,
'fingerprint_strength': primary.get('fingerprint_strength'),
'fingerprint': primary.get('fingerprint'),
'fingerprint_version': primary.get('fingerprint_version') or FINGERPRINT_VERSION,
'components': primary.get('components') or {},
'matches': matches,
'allowed_actions': _allowed_actions_for(
status=status,
fingerprint_strength=str(primary.get('fingerprint_strength') or 'unavailable'),
matches=matches,
),
'checked_at': utc_iso(datetime.utcnow()),
'candidate_statuses': statuses,
}