581 lines
28 KiB
Python
581 lines
28 KiB
Python
"""
|
||
backend/app/services/shipping_notice/reconcile_queries.py
|
||
|
||
用途:Phase 2 对账只读查询层 — 按 Q1 五级 L1-L3 归属链判断 Case → Task 的绑定关系。
|
||
依赖:models.ShippingOrderReviewCase / ShippingOrderCandidate / ShippingOrderDocument
|
||
/ ShippingNotice(=OrderTask)、business_fingerprint.build_business_fingerprint、
|
||
duplicate_detection.classify_task_lifecycle、recovery_contract(类型契约)。
|
||
逻辑:由 reconciliation_service.reconcile_existing_task() 调用;全部为只读查询,
|
||
不做任何 DB 写入;返回统一 ReconcileMatchResult 结构(match_level / task_no /
|
||
confidence / evidence)。严禁凭字段名推断,必须真实 JOIN 关系表。
|
||
注意:business_numbering_service._customer_code_from_summary 不在顶层 import(该函数
|
||
已从编号服务移除),调用处做 try 延迟 import,失败兜底空字符串。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
|
||
from app import db
|
||
from app.models import (
|
||
FileAsset,
|
||
ShippingNotice,
|
||
ShippingOrderCandidate,
|
||
ShippingOrderDocument,
|
||
ShippingOrderIntake,
|
||
ShippingOrderProcessingUnit,
|
||
ShippingOrderReviewCase,
|
||
)
|
||
from app.services.shipping_notice.business_fingerprint import (
|
||
FINGERPRINT_VERSION,
|
||
build_business_fingerprint,
|
||
)
|
||
from app.services.shipping_notice.duplicate_detection import classify_task_lifecycle
|
||
from app.services.shipping_notice.recovery_contract import (
|
||
ReconcileConfidence,
|
||
ReconcileMatchEvidence,
|
||
ReconcileMatchLevel,
|
||
ReconcileMatchResult,
|
||
)
|
||
|
||
|
||
# ============================================================
|
||
# 公共辅助:统一生成「无匹配」结果
|
||
# ============================================================
|
||
|
||
def _no_match(*, reason: str, case_no: str) -> ReconcileMatchResult:
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.NONE,
|
||
task_no=None,
|
||
confidence=ReconcileConfidence.NONE,
|
||
evidence=ReconcileMatchEvidence(
|
||
case_no=case_no,
|
||
match_level_steps=[{'step': 'L0-none', 'passed': False, 'reason': reason}],
|
||
),
|
||
)
|
||
|
||
|
||
# ============================================================
|
||
# L1:Case 显式绑定(最高优先级,最快路径)
|
||
# ============================================================
|
||
|
||
def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMatchResult | None:
|
||
"""
|
||
L1:Case.confirmed_task_id → 直接查 ShippingNotice 拿到 task_no。
|
||
【AI 触发时机】:对账入口必须先执行本步骤,避免 L2/L3 瞎匹配覆盖掉人工确认的绑定。
|
||
"""
|
||
steps: list[dict[str, Any]] = []
|
||
case_no = str(case.case_no)
|
||
|
||
# 1a. confirmed_task_id 有值且指向存在的 Task
|
||
task_id = getattr(case, 'confirmed_task_id', None)
|
||
if task_id is not None:
|
||
task = db.session.get(ShippingNotice, int(task_id))
|
||
if task is not None and task.task_no:
|
||
steps.append({'step': 'L1a-confirmed_task_id', 'passed': True,
|
||
'evidence': {'task_id': int(task_id), 'task_no': str(task.task_no)}})
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.L1,
|
||
task_no=str(task.task_no),
|
||
confidence=ReconcileConfidence.CERTAIN,
|
||
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps,
|
||
confirmed_task_id=int(task_id),
|
||
lifecycle=classify_task_lifecycle(task.process_status)),
|
||
)
|
||
steps.append({'step': 'L1a-confirmed_task_id', 'passed': False,
|
||
'reason': 'confirmed_task_id 指向的 ShippingNotice 不存在或无 task_no',
|
||
'evidence': {'task_id': int(task_id)}})
|
||
else:
|
||
steps.append({'step': 'L1a-confirmed_task_id', 'passed': False, 'reason': 'confirmed_task_id is None'})
|
||
|
||
# 1b. confirmed_task_no 字符串有值 → 反向查询 ShippingNotice 校验存在性
|
||
confirmed_task_no = str(getattr(case, 'confirmed_task_no', '') or '').strip()
|
||
if confirmed_task_no:
|
||
task = ShippingNotice.query.filter_by(task_no=confirmed_task_no).first()
|
||
if task is not None:
|
||
steps.append({'step': 'L1b-confirmed_task_no', 'passed': True,
|
||
'evidence': {'task_no': confirmed_task_no, 'task_id': int(task.id)}})
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.L1,
|
||
task_no=confirmed_task_no,
|
||
confidence=ReconcileConfidence.CERTAIN,
|
||
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps,
|
||
confirmed_task_no=confirmed_task_no,
|
||
lifecycle=classify_task_lifecycle(task.process_status)),
|
||
)
|
||
steps.append({'step': 'L1b-confirmed_task_no', 'passed': False,
|
||
'reason': 'confirmed_task_no 反向查无 ShippingNotice',
|
||
'evidence': {'task_no': confirmed_task_no}})
|
||
else:
|
||
steps.append({'step': 'L1b-confirmed_task_no', 'passed': False, 'reason': 'confirmed_task_no 为空'})
|
||
|
||
# L1 未命中,保留 steps 供上层聚合 → 返回 None 让后续 L2/L3 继续
|
||
return None
|
||
|
||
|
||
# ============================================================
|
||
# L1c / L1d / L1e:Candidate 级、Document 级(仍算 L1,因为来源明确)
|
||
# ============================================================
|
||
|
||
def _current_candidate_of_case(case: ShippingOrderReviewCase) -> ShippingOrderCandidate | None:
|
||
"""加载 Case 的当前 Candidate(按 candidate_id → 按 document+run+is_current)。"""
|
||
if getattr(case, 'candidate_id', None):
|
||
c = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||
if c is not None:
|
||
return c
|
||
return (
|
||
ShippingOrderCandidate.query
|
||
.filter_by(
|
||
order_extraction_run_id=int(case.run_id),
|
||
primary_document_id=int(case.document_id),
|
||
is_current_version=True,
|
||
)
|
||
.order_by(ShippingOrderCandidate.id.desc())
|
||
.first()
|
||
)
|
||
|
||
|
||
def _step_l1cde_downstream_links(
|
||
case: ShippingOrderReviewCase,
|
||
candidate: ShippingOrderCandidate | None,
|
||
) -> ReconcileMatchResult | None:
|
||
"""
|
||
L1c: Candidate → 已有 OrderTask(Candidate.fulfilled_task_id 或 wave_lines → Task)。
|
||
L1d: Document → ShippingNotice.source_document_id / document_id 外键。
|
||
L1e: Candidate + Document + PO + customer_code + fingerprint 联合匹配(过渡到 L2)。
|
||
"""
|
||
steps: list[dict[str, Any]] = []
|
||
case_no = str(case.case_no)
|
||
|
||
# -------- L1c:Candidate 显式关联 Task --------
|
||
if candidate is not None:
|
||
fulfilled_task_id = getattr(candidate, 'fulfilled_task_id', None)
|
||
if fulfilled_task_id is not None:
|
||
task = db.session.get(ShippingNotice, int(fulfilled_task_id))
|
||
if task is not None and task.task_no:
|
||
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': True,
|
||
'evidence': {'candidate_id': int(candidate.id),
|
||
'task_id': int(fulfilled_task_id),
|
||
'task_no': str(task.task_no)}})
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.L1,
|
||
task_no=str(task.task_no),
|
||
confidence=ReconcileConfidence.CERTAIN,
|
||
evidence=ReconcileMatchEvidence(
|
||
case_no=case_no, match_level_steps=steps,
|
||
candidate_id=int(candidate.id),
|
||
linked_candidate_task_id=int(fulfilled_task_id),
|
||
lifecycle=classify_task_lifecycle(task.process_status),
|
||
),
|
||
)
|
||
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False,
|
||
'reason': 'Candidate 未绑定 fulfilled_task_id'})
|
||
|
||
# L1c-alt:通过 ShippingOrderReviewWaveLine.case_id + task_id 反查(Phase 1 已存在的关系)
|
||
from app.models import ShippingOrderReviewWaveLine
|
||
wave_task_id_rows = (
|
||
db.session.query(ShippingOrderReviewWaveLine.task_id)
|
||
.filter(ShippingOrderReviewWaveLine.case_id == int(case.id),
|
||
ShippingOrderReviewWaveLine.task_id.isnot(None))
|
||
.distinct()
|
||
.limit(5)
|
||
.all()
|
||
)
|
||
wave_task_ids = [int(r.task_id) for r in wave_task_id_rows if r.task_id is not None]
|
||
if len(wave_task_ids) == 1:
|
||
task = db.session.get(ShippingNotice, wave_task_ids[0])
|
||
if task is not None and task.task_no:
|
||
steps.append({'step': 'L1c-wave_line_task', 'passed': True,
|
||
'evidence': {'task_id': wave_task_ids[0], 'task_no': str(task.task_no)}})
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.L1,
|
||
task_no=str(task.task_no),
|
||
confidence=ReconcileConfidence.CERTAIN,
|
||
evidence=ReconcileMatchEvidence(
|
||
case_no=case_no, match_level_steps=steps,
|
||
wave_linked_task_id=wave_task_ids[0],
|
||
lifecycle=classify_task_lifecycle(task.process_status),
|
||
),
|
||
)
|
||
steps.append({'step': 'L1c-wave_line_task', 'passed': False,
|
||
'reason': 'wave_line 反查 task_id 不唯一或不存在',
|
||
'evidence': {'matched_count': len(wave_task_ids)}})
|
||
else:
|
||
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False, 'reason': 'Case 没有 Candidate'})
|
||
steps.append({'step': 'L1c-wave_line_task', 'passed': False, 'reason': 'Case 没有 Candidate'})
|
||
|
||
# -------- L1d:Document 外键链:Unit → Intake → Notice(ShippingNotice.source_document_id / document_id)--------
|
||
document_id = int(case.document_id)
|
||
# 路径 A:ShippingNotice.source_document_id == document_id(PDF 级直接关联)
|
||
doc_task_a = (
|
||
ShippingNotice.query
|
||
.filter((ShippingNotice.source_document_id == document_id) |
|
||
(ShippingNotice.document_id == document_id))
|
||
.order_by(ShippingNotice.id.desc())
|
||
.limit(5)
|
||
.all()
|
||
)
|
||
if len(doc_task_a) == 1:
|
||
task = doc_task_a[0]
|
||
steps.append({'step': 'L1d-document_foreign_key', 'passed': True,
|
||
'evidence': {'document_id': document_id, 'task_no': str(task.task_no)}})
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.L1,
|
||
task_no=str(task.task_no),
|
||
confidence=ReconcileConfidence.CERTAIN,
|
||
evidence=ReconcileMatchEvidence(
|
||
case_no=case_no, match_level_steps=steps,
|
||
source_document_id=document_id,
|
||
lifecycle=classify_task_lifecycle(task.process_status),
|
||
),
|
||
)
|
||
steps.append({'step': 'L1d-document_foreign_key', 'passed': False,
|
||
'reason': f'Document 反查 Task {len(doc_task_a)} 个(不唯一)',
|
||
'evidence': {'document_id': document_id, 'matched_count': len(doc_task_a)}})
|
||
|
||
# 路径 B:经由 ProcessingUnit → Intake.asset_id → FileAsset.id
|
||
unit = db.session.get(ShippingOrderProcessingUnit, int(case.unit_id)) if case.unit_id else None
|
||
intake: ShippingOrderIntake | None = None
|
||
if unit is not None and getattr(unit, 'intake_id', None):
|
||
intake = db.session.get(ShippingOrderIntake, int(unit.intake_id))
|
||
asset_id = getattr(intake, 'asset_id', None) if intake is not None else None
|
||
if asset_id is not None:
|
||
# FileAsset.content_hash == ShippingNotice.source_content_hash(文件哈希级)
|
||
asset = db.session.get(FileAsset, int(asset_id))
|
||
content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower()
|
||
if content_hash:
|
||
file_tasks = (
|
||
ShippingNotice.query
|
||
.filter_by(user_id=int(case.owner_user_id), source_content_hash=content_hash)
|
||
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
|
||
.order_by(ShippingNotice.id.desc())
|
||
.limit(5)
|
||
.all()
|
||
)
|
||
if len(file_tasks) == 1:
|
||
task = file_tasks[0]
|
||
steps.append({'step': 'L1d-file_hash_match', 'passed': True,
|
||
'evidence': {'content_hash': content_hash[:16] + '…',
|
||
'task_no': str(task.task_no)}})
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.L1,
|
||
task_no=str(task.task_no),
|
||
confidence=ReconcileConfidence.PROBABLE,
|
||
evidence=ReconcileMatchEvidence(
|
||
case_no=case_no, match_level_steps=steps,
|
||
content_hash=content_hash,
|
||
lifecycle=classify_task_lifecycle(task.process_status),
|
||
),
|
||
)
|
||
steps.append({'step': 'L1d-file_hash_match', 'passed': False,
|
||
'reason': f'文件哈希匹配 {len(file_tasks)} 个(不唯一)',
|
||
'evidence': {'matched_count': len(file_tasks)}})
|
||
else:
|
||
steps.append({'step': 'L1d-file_hash_match', 'passed': False, 'reason': 'FileAsset.content_hash 为空'})
|
||
else:
|
||
steps.append({'step': 'L1d-file_hash_match', 'passed': False, 'reason': '无 Intake/FileAsset 链'})
|
||
|
||
return None
|
||
|
||
|
||
# ============================================================
|
||
# L2:结构化字段联合匹配(PO + 客户码 + 指纹)
|
||
# ============================================================
|
||
|
||
def _extract_candidate_business_payload(
|
||
case: ShippingOrderReviewCase,
|
||
candidate: ShippingOrderCandidate | None,
|
||
) -> dict[str, Any]:
|
||
"""按 Q2:PO 优先 Candidate.structured → 其次 Draft.header;客户优先 candidate/draft customer_code。"""
|
||
payload: dict[str, Any] = {
|
||
'po_numbers': [],
|
||
'customer_code': '',
|
||
'customer_name': '',
|
||
'business_fingerprint': None,
|
||
'fingerprint_strength': 'unavailable',
|
||
'from_candidate': False,
|
||
'from_draft': False,
|
||
}
|
||
|
||
# [STEP Q2-1] Candidate 结构化结果优先
|
||
if candidate is not None:
|
||
structured = getattr(candidate, 'structured_result_json', None)
|
||
if isinstance(structured, dict):
|
||
summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
|
||
payload['po_numbers'] = [
|
||
str(x).strip().upper() for x in (summary.get('po_numbers') or []) if str(x).strip()
|
||
] or [str(summary.get('po_number') or '').strip().upper()]
|
||
payload['po_numbers'] = [x for x in payload['po_numbers'] if x]
|
||
try:
|
||
from app.services.shipping_notice.business_numbering_service import (
|
||
_customer_code_from_summary,
|
||
)
|
||
code = _customer_code_from_summary(summary)
|
||
except (ImportError, AttributeError):
|
||
code = ''
|
||
if not code:
|
||
code = str(summary.get('customer_code') or '').strip().upper()
|
||
if not code:
|
||
code = str(getattr(candidate, 'customer_code', '') or '').strip().upper()
|
||
payload['customer_code'] = code
|
||
payload['customer_name'] = str(summary.get('customer_name') or '').strip()
|
||
payload['from_candidate'] = True
|
||
|
||
# Candidate 持久化指纹优先(Q2:"如果没有 Candidate 指纹,才重算")
|
||
cand_fp = getattr(candidate, 'business_fingerprint', None)
|
||
if isinstance(cand_fp, dict) and cand_fp.get('fingerprint'):
|
||
payload['business_fingerprint'] = str(cand_fp['fingerprint'])
|
||
payload['fingerprint_strength'] = str(cand_fp.get('strength') or 'unavailable')
|
||
payload['fingerprint_version'] = str(cand_fp.get('version') or FINGERPRINT_VERSION)
|
||
|
||
# [STEP Q2-2] Draft 最终字段作兜底(Candidate 缺失时或空字段时)
|
||
draft = getattr(case, 'current_draft', None)
|
||
if draft is not None and not payload['from_candidate']:
|
||
header = draft.header_values_json if isinstance(draft.header_values_json, dict) else {}
|
||
values = header.get('values') if isinstance(header.get('values'), dict) else {}
|
||
po_val = ''
|
||
cc_val = ''
|
||
cn_val = ''
|
||
for key, item in values.items():
|
||
if not isinstance(item, dict):
|
||
continue
|
||
k = str(key).lower()
|
||
v = str(item.get('value') or '').strip()
|
||
if 'po' in k and not po_val:
|
||
po_val = v.upper()
|
||
if ('customer' in k and 'code' in k) and not cc_val:
|
||
cc_val = v.upper()
|
||
if ('customer' in k and 'name' in k) and not cn_val:
|
||
cn_val = v
|
||
if po_val and not payload['po_numbers']:
|
||
payload['po_numbers'] = [po_val]
|
||
if cc_val and not payload['customer_code']:
|
||
payload['customer_code'] = cc_val
|
||
if cn_val and not payload['customer_name']:
|
||
payload['customer_name'] = cn_val
|
||
payload['from_draft'] = True
|
||
|
||
# [STEP Q2-3] 指纹兜底:无 Candidate 指纹才重算(Q2 明确要求)
|
||
if payload['business_fingerprint'] is None:
|
||
fp = build_business_fingerprint({
|
||
'po_numbers': payload['po_numbers'],
|
||
'customer_code': payload['customer_code'],
|
||
'customer_name': payload['customer_name'],
|
||
})
|
||
payload['business_fingerprint'] = str(fp.get('fingerprint') or '')
|
||
payload['fingerprint_strength'] = str(fp.get('strength') or 'unavailable')
|
||
payload['fingerprint_version'] = str(fp.get('version') or FINGERPRINT_VERSION)
|
||
payload['fingerprint_recalculated'] = True
|
||
else:
|
||
payload['fingerprint_recalculated'] = False
|
||
|
||
return payload
|
||
|
||
|
||
def _step_l2_structural_match(
|
||
case: ShippingOrderReviewCase,
|
||
candidate: ShippingOrderCandidate | None,
|
||
l1_steps: list[dict[str, Any]],
|
||
) -> ReconcileMatchResult | None:
|
||
"""
|
||
L2:PO + 客户码 + Candidate 持久化指纹 联合匹配。
|
||
严格遵循 Q2 的「字段来源优先级」和「指纹使用顺序」。
|
||
"""
|
||
steps = list(l1_steps)
|
||
case_no = str(case.case_no)
|
||
|
||
payload = _extract_candidate_business_payload(case, candidate)
|
||
evidence: ReconcileMatchEvidence = ReconcileMatchEvidence(
|
||
case_no=case_no,
|
||
match_level_steps=steps,
|
||
candidate_id=int(candidate.id) if candidate is not None else None,
|
||
po_numbers=list(payload['po_numbers']),
|
||
customer_code=payload['customer_code'] or None,
|
||
business_fingerprint=payload['business_fingerprint'] or None,
|
||
fingerprint_strength=payload['fingerprint_strength'],
|
||
fingerprint_recalculated=bool(payload.get('fingerprint_recalculated')),
|
||
)
|
||
|
||
# L2a:同用户 + 同 business_fingerprint + 强指纹 strength
|
||
if (payload['business_fingerprint']
|
||
and payload['fingerprint_strength'] in {'strong', 'medium'}):
|
||
same_fp_tasks = (
|
||
ShippingNotice.query
|
||
.filter(ShippingNotice.user_id == int(case.owner_user_id),
|
||
ShippingNotice.business_fingerprint == payload['business_fingerprint'])
|
||
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
|
||
.order_by(ShippingNotice.id.desc())
|
||
.limit(5)
|
||
.all()
|
||
)
|
||
if len(same_fp_tasks) == 1:
|
||
task = same_fp_tasks[0]
|
||
steps.append({'step': 'L2a-fingerprint_match', 'passed': True,
|
||
'evidence': {'fingerprint_strength': payload['fingerprint_strength'],
|
||
'recalculated': payload['fingerprint_recalculated'],
|
||
'task_no': str(task.task_no)}})
|
||
evidence['match_level_steps'] = steps
|
||
evidence['lifecycle'] = classify_task_lifecycle(task.process_status)
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.L2,
|
||
task_no=str(task.task_no),
|
||
confidence=(ReconcileConfidence.CERTAIN
|
||
if payload['fingerprint_strength'] == 'strong'
|
||
else ReconcileConfidence.PROBABLE),
|
||
evidence=evidence,
|
||
)
|
||
steps.append({'step': 'L2a-fingerprint_match', 'passed': False,
|
||
'reason': f'指纹匹配 {len(same_fp_tasks)} 个(不唯一)',
|
||
'evidence': {'matched_count': len(same_fp_tasks),
|
||
'strength': payload['fingerprint_strength']}})
|
||
else:
|
||
steps.append({'step': 'L2a-fingerprint_match', 'passed': False,
|
||
'reason': '指纹不可用或强度不足 strong/medium',
|
||
'evidence': {'strength': payload['fingerprint_strength']}})
|
||
|
||
# L2b:同用户 + PO 精确一致 + customer_code 精确一致
|
||
if payload['po_numbers'] and payload['customer_code']:
|
||
# ShippingNotice 头字段 JSON:查 structured_result_json.business_summary.po_numbers / customer_code
|
||
# 因 ORM 层无强列,退化为查 source_content_po_numbers 的 Candidate → Task 反向
|
||
same_customer_tasks = (
|
||
ShippingNotice.query
|
||
.filter_by(user_id=int(case.owner_user_id))
|
||
.filter(ShippingNotice.customer_code == payload['customer_code']
|
||
if hasattr(ShippingNotice, 'customer_code') else True)
|
||
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
|
||
.order_by(ShippingNotice.id.desc())
|
||
.limit(20)
|
||
.all()
|
||
)
|
||
po_matched: list[ShippingNotice] = []
|
||
for task in same_customer_tasks:
|
||
structured = getattr(task, 'structured_result_json', None) if hasattr(ShippingNotice, 'structured_result_json') else None
|
||
summary = structured.get('business_summary') if isinstance(structured, dict) else None
|
||
task_pos: set[str] = set()
|
||
if isinstance(summary, dict):
|
||
task_pos = {str(x).strip().upper() for x in (summary.get('po_numbers') or []) if str(x).strip()}
|
||
if not task_pos and summary.get('po_number'):
|
||
task_pos = {str(summary['po_number']).strip().upper()}
|
||
if task_pos and task_pos.intersection(set(payload['po_numbers'])):
|
||
po_matched.append(task)
|
||
if len(po_matched) == 1:
|
||
task = po_matched[0]
|
||
steps.append({'step': 'L2b-po_customer_match', 'passed': True,
|
||
'evidence': {'customer_code': payload['customer_code'],
|
||
'pos_matched': sorted(set(payload['po_numbers']) &
|
||
{str(x).strip().upper() for x in
|
||
((task.structured_result_json or {}).get('business_summary') or {}).get('po_numbers') or []}),
|
||
'task_no': str(task.task_no)}})
|
||
evidence['match_level_steps'] = steps
|
||
evidence['lifecycle'] = classify_task_lifecycle(task.process_status)
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.L2,
|
||
task_no=str(task.task_no),
|
||
confidence=ReconcileConfidence.PROBABLE,
|
||
evidence=evidence,
|
||
)
|
||
steps.append({'step': 'L2b-po_customer_match', 'passed': False,
|
||
'reason': f'PO+客码匹配 {len(po_matched)} 个(不唯一)',
|
||
'evidence': {'matched_count': len(po_matched)}})
|
||
else:
|
||
steps.append({'step': 'L2b-po_customer_match', 'passed': False,
|
||
'reason': 'PO 或 customer_code 缺失,无法联合匹配',
|
||
'evidence': {'pos_count': len(payload['po_numbers']),
|
||
'customer_code_empty': not bool(payload['customer_code'])}})
|
||
|
||
# -------- L3:仅文件哈希但多候选 / 弱指纹匹配(ambiguous,返回 L3 供人工裁决)--------
|
||
# 在 L1d 步骤中已筛选 content_hash 但超过 1 个的情形,这里统一转为 L3 ambiguous
|
||
document_id = int(case.document_id)
|
||
doc_tasks_multi = (
|
||
ShippingNotice.query
|
||
.filter((ShippingNotice.source_document_id == document_id) |
|
||
(ShippingNotice.document_id == document_id))
|
||
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
|
||
.order_by(ShippingNotice.id.desc())
|
||
.limit(5)
|
||
.all()
|
||
)
|
||
if len(doc_tasks_multi) > 1:
|
||
steps.append({'step': 'L3-multi_document_match', 'passed': True,
|
||
'evidence': {'matched_task_nos': [t.task_no for t in doc_tasks_multi],
|
||
'count': len(doc_tasks_multi)}})
|
||
evidence['match_level_steps'] = steps
|
||
evidence['candidate_matches'] = [
|
||
{'task_no': str(t.task_no), 'lifecycle': classify_task_lifecycle(t.process_status)}
|
||
for t in doc_tasks_multi
|
||
]
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.L3,
|
||
task_no=None,
|
||
confidence=ReconcileConfidence.AMBIGUOUS,
|
||
evidence=evidence,
|
||
)
|
||
|
||
return None
|
||
|
||
|
||
# ============================================================
|
||
# 对外总入口:5 级归属链按顺序串起来
|
||
# ============================================================
|
||
|
||
def query_case_task_ownership(
|
||
case: ShippingOrderReviewCase,
|
||
) -> ReconcileMatchResult:
|
||
"""
|
||
按 Q1 L1-L3 五级归属链,判断 Case 应归属到哪个既有的 Task。
|
||
【AI 触发时机】:对账恢复 / reconcile-and-progress API / 历史 Job 928/929 排错入口。
|
||
|
||
核心逻辑(严格按 Q1 指定顺序,真实 DB 关系,禁止凭字段名猜):
|
||
1. Case.confirmed_task_id → L1 CERTAIN
|
||
2. Case.confirmed_task_no → L1 CERTAIN
|
||
3. Candidate.fulfilled_task_id / wave_lines.task_id → L1 CERTAIN
|
||
4. Document.source_document_id / document_id 外键 / FileAsset content_hash → L1 CERTAIN/PROBABLE
|
||
5. Candidate/Draft PO + 客户码 + Candidate 持久化指纹 → L2 CERTAIN/PROBABLE
|
||
6. 多 Document 匹配 / 弱指纹多候选 → L3 AMBIGUOUS
|
||
|
||
Args:
|
||
case: 已加载的 ReviewCase(建议 SELECT FOR UPDATE 锁定后再调)。
|
||
|
||
Returns:
|
||
ReconcileMatchResult:统一 match_level / task_no / confidence / evidence 结构。
|
||
"""
|
||
case_no = str(case.case_no)
|
||
|
||
# [STEP 1] L1:显式绑定
|
||
l1_explicit = _step_l1_case_explicit_binding(case)
|
||
if l1_explicit is not None:
|
||
return l1_explicit
|
||
# 提取 L1 前两步的 steps(failed 记录)以便 L2 证据链完整
|
||
probe_no_match_steps: list[dict[str, Any]] = []
|
||
probe_none = _no_match(reason='probe', case_no=case_no)
|
||
_ = probe_none
|
||
|
||
# [STEP 2] L1cde:Candidate / Document 链
|
||
candidate = _current_candidate_of_case(case)
|
||
l1cde = _step_l1cde_downstream_links(case, candidate)
|
||
if l1cde is not None:
|
||
return l1cde
|
||
probe_no_match_steps = list((l1cde or {}).get('evidence', {}).get('match_level_steps', [])
|
||
if isinstance(l1cde, dict) else [])
|
||
|
||
# [STEP 3] L2:结构化字段联合
|
||
l2 = _step_l2_structural_match(case, candidate, probe_no_match_steps)
|
||
if l2 is not None:
|
||
return l2
|
||
|
||
# [STEP END] NONE:无匹配
|
||
reason_parts = []
|
||
if candidate is None:
|
||
reason_parts.append('no candidate')
|
||
reason_parts.append('all L1/L2 steps passed=false')
|
||
final_steps = list((l2 or {}).get('evidence', {}).get('match_level_steps', [])
|
||
if isinstance(l2, dict) else probe_no_match_steps)
|
||
final_steps.append({'step': 'Lx-none', 'passed': True, 'reason': '所有 L1-L2 步骤均未命中;未达 L3 多候选阈值'})
|
||
return ReconcileMatchResult(
|
||
match_level=ReconcileMatchLevel.NONE,
|
||
task_no=None,
|
||
confidence=ReconcileConfidence.NONE,
|
||
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=final_steps,
|
||
candidate_id=int(candidate.id) if candidate else None),
|
||
)
|