Files
syops/backend/app/services/shipping_notice/duplicate_detection.py
T

709 lines
28 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/shipping_notice/duplicate_detection.py
用途:发货通知业务重复检测(文件哈希 + 业务指纹),产出统一 duplicate 结果。
依赖:models.ShippingNotice/FileAsset/Document/Candidate、business_fingerprint、core.response.utc_iso。
逻辑:Intake 级与 Candidate 级共用匹配规则;候选 A 重复只写回 A,不连带阻断同信其它候选;
刷新入口按 Candidate 重检再聚合到 Intake;检测异常可 clear 为 unchecked;
Candidate 级可 exclude_task_ids 豁免同复核 Case 既有履约波次;
范围限定当前 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,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderSnapshot,
ShippingNotice,
)
from app.services.shipping_notice.business_fingerprint import (
CONTENT_FINGERPRINT_VERSION,
FINGERPRINT_VERSION,
build_business_fingerprint,
build_content_fingerprint,
)
from app.services.shipping_notice.reservation_id import validated_reservation_id
# 与 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: ShippingNotice) -> 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: ShippingNotice, *, 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),
'content_fingerprint': task.content_fingerprint,
'content_fingerprint_version': task.content_fingerprint_version,
}
def _reservation_differences(task: ShippingNotice, summary: dict[str, Any]) -> list[dict[str, Any]]:
"""比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
if snapshot is None:
return []
proposed = {
validated_reservation_id(str(line.get('reservation_id') or '')): line
for line in summary.get('lines') or []
if isinstance(line, dict) and validated_reservation_id(str(line.get('reservation_id') or ''))
}
differences: list[dict[str, Any]] = []
for line in snapshot.lines:
reservation_id = validated_reservation_id(line.reservation_id)
candidate_line = proposed.get(reservation_id)
if not reservation_id or candidate_line is None:
continue
previous = {'part_number': str(line.part_number or '').strip(), 'qty': str(line.qty)}
proposed_value = {
'part_number': str(candidate_line.get('part_number') or '').strip(),
'qty': str(candidate_line.get('qty') or '').strip(),
}
if previous != proposed_value:
differences.append({
'reservation_id': reservation_id,
'previous': previous,
'proposed': proposed_value,
})
return differences
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: ShippingOrderIntake,
asset: FileAsset | None = None,
business_summary: dict[str, Any] | None = None,
fingerprint_result: dict[str, Any] | None = None,
content_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 {}
content_fp = content_fingerprint_result or build_content_fingerprint(summary)
content_fingerprint = content_fp.get('fingerprint')
content_version = str(content_fp.get('version') or CONTENT_FINGERPRINT_VERSION)
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(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
)
.order_by(ShippingNotice.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(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
)
.order_by(ShippingNotice.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':
comparable = [
task for task in fp_tasks
if task.content_fingerprint and task.content_fingerprint_version == content_version
]
if content_fingerprint and comparable:
status = (
'same_business_content'
if any(task.content_fingerprint == content_fingerprint for task in comparable)
else 'possible_revision'
)
else:
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(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
)
.order_by(ShippingNotice.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
for match in matches:
task = db.session.query(ShippingNotice).filter_by(task_no=match['task_no']).one_or_none()
if task is not None:
match['reservation_differences'] = _reservation_differences(task, summary)
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: ShippingOrderIntake,
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: ShippingOrderIntake) -> 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(ShippingOrderCandidate)
.filter(ShippingOrderCandidate.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: ShippingOrderCandidate,
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 result.get('content_fingerprint') is not None:
candidate.content_fingerprint = result.get('content_fingerprint')
if result.get('content_fingerprint_version') is not None:
candidate.content_fingerprint_version = result.get('content_fingerprint_version')
if clear_resolution:
candidate.duplicate_resolution = None
candidate.duplicate_resolution_reason = None
candidate.duplicate_target_task_no = None
candidate.duplicate_resolved_by_id = None
candidate.duplicate_resolved_at = None
candidate.updated_at = datetime.utcnow()
def refresh_candidates_and_aggregate_intake(
*,
intake: ShippingOrderIntake,
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(ShippingOrderCandidate)
.filter(ShippingOrderCandidate.intake_id == int(intake.id))
.order_by(ShippingOrderCandidate.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)
content_fingerprint = build_content_fingerprint(summary)
result = detect_duplicates_for_intake(
intake=intake,
asset=parent_asset,
business_summary=summary,
fingerprint_result=fingerprint,
content_fingerprint_result=content_fingerprint,
)
apply_duplicate_result_to_intake(intake, result)
return result
candidate_results: list[dict[str, Any]] = []
for candidate in candidates:
document = db.session.get(ShippingOrderDocument, 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: ShippingOrderIntake,
asset: FileAsset | None = None,
document: ShippingOrderDocument | None = None,
business_summary: dict[str, Any] | None = None,
fingerprint_result: dict[str, Any] | None = None,
content_fingerprint_result: dict[str, Any] | None = None,
exclude_task_ids: set[int] | None = None,
) -> dict[str, Any]:
"""
对单个订单候选执行重复检测(不写 Intake,不影响同信其它候选)。
核心逻辑:与 detect_duplicates_for_intake 同源规则,但 exact_file 优先用
Document/派生资产 content_hash(单 PDF),避免整封 EML 哈希误伤其它订单。
exclude_task_ids 用于同一复核 Case 合法后续履约波次豁免本 Case 既有 Task。
Args:
intake: 来源 Intake。
asset / document: 可选文件资产与 PDF 文档。
business_summary / fingerprint_result / content_fingerprint_result: 指纹输入。
exclude_task_ids: 可选;忽略这些 Task(同 Case 既有波次)。
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_fp = content_fingerprint_result or build_content_fingerprint(summary)
content_fingerprint = content_fp.get('fingerprint')
content_version = str(content_fp.get('version') or CONTENT_FINGERPRINT_VERSION)
skipped_ids = {int(item) for item in (exclude_task_ids or []) if item is not None}
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_query = (
db.session.query(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
)
)
if skipped_ids:
hash_query = hash_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
hash_tasks = hash_query.order_by(ShippingNotice.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_query = (
db.session.query(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
)
)
if skipped_ids:
fp_query = fp_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
fp_tasks = fp_query.order_by(ShippingNotice.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':
comparable = [
task for task in fp_tasks
if task.content_fingerprint and task.content_fingerprint_version == content_version
]
if content_fingerprint and comparable:
status = (
'same_business_content'
if any(task.content_fingerprint == content_fingerprint for task in comparable)
else 'possible_revision'
)
else:
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':
weak_query = (
db.session.query(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
)
)
if skipped_ids:
weak_query = weak_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
fp_tasks = weak_query.order_by(ShippingNotice.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',
'same_business_content',
'possible_revision',
}
if strength == 'unavailable' and status == 'none':
blocking = False
for match in matches:
task = db.session.query(ShippingNotice).filter_by(task_no=match['task_no']).one_or_none()
if task is not None:
match['reservation_differences'] = _reservation_differences(task, summary)
return {
'status': status,
'blocking': blocking,
'fingerprint_strength': strength,
'fingerprint': fingerprint,
'fingerprint_version': version,
'components': components,
'content_fingerprint': content_fingerprint,
'content_fingerprint_version': content_version,
'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: ShippingOrderIntake,
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,
}