feat(shipping-notice): 客户识别证据命中分级为三层匹配
- 归一层新增 canonical 等值键与包含分级(完整/截断),统一证据标准化入口 - 影子识别升至 shadow-v3:等值 > 完整包含 > 截断包含层级裁决,邮箱/域名仅精确等值 - 自动确认升至 auto-v3:完整包含可自动确认,截断包含仅供人工建议不进自动裁决 - 影子候选状态与复核侧重新识别统一复用 resolver 分级裁决,移除本地分数重复判定 - 新增客户身份三层匹配契约测试
This commit is contained in:
1 parent
e472abc4e3
commit
241d8d48ab
6 files changed
+655
-49
No files matched your search
@@ -4,6 +4,9 @@ services/shipping_notice/customer_auto_resolution.py
|
||||
用途:基于管理员审核的强证据受控自动确认 OT 客户。
|
||||
依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、Flask 配置。
|
||||
逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;不创建 Notice 或分配业务编号。
|
||||
命中分级与复核侧共用:canonical 等值(unique_strong_match)与完整包含
|
||||
(unique_containment_match,指纹整体出现在提取值中且证据授权)可自动确认;
|
||||
截断包含(containment_weak)只供人工建议,永不进入本裁决。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,14 +32,18 @@ from app.services.shipping_notice.customer_identity_gate import (
|
||||
customer_confirmation_facts,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
IDENTITY_MATCH_CONTAINMENT_STRONG,
|
||||
IDENTITY_MATCH_EQUALITY,
|
||||
canonical_identity_key,
|
||||
classify_identity_containment,
|
||||
is_public_email_domain,
|
||||
normalize_customer_name,
|
||||
normalize_domain,
|
||||
normalize_email,
|
||||
normalize_identity_evidence_value,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, task_event_task_id
|
||||
|
||||
AUTO_RESOLUTION_VERSION = "customer-auto-v2"
|
||||
AUTO_RESOLUTION_VERSION = "customer-auto-v3"
|
||||
# 允许自动确认的裁决状态;质量门禁分母与审计均以该集合为准。
|
||||
AUTO_CONFIRM_ELIGIBLE_STATUSES = frozenset({'unique_strong_match', 'unique_containment_match'})
|
||||
CUSTOMER_AUDIT_EVENT_TYPES = (
|
||||
"customer_auto_resolution_evaluated",
|
||||
"customer_auto_confirmed",
|
||||
@@ -65,8 +72,8 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]:
|
||||
eligible_samples = 0
|
||||
correct_samples = 0
|
||||
for shadow in labeled:
|
||||
decision = _resolve_auto_customer_from_shadow_resolution(shadow)
|
||||
if decision['status'] != 'unique_strong_match':
|
||||
decision = resolve_auto_customer_decision(shadow)
|
||||
if decision['status'] not in AUTO_CONFIRM_ELIGIBLE_STATUSES:
|
||||
continue
|
||||
eligible_samples += 1
|
||||
if int(decision['customer_id']) == int(shadow.manual_customer_id):
|
||||
@@ -229,23 +236,55 @@ def _verified_shadow_value(
|
||||
config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
context_source = config.get('context_source') if isinstance(config.get('context_source'), dict) else {}
|
||||
try:
|
||||
if context_source.get('option_key') == 'from_email':
|
||||
return normalize_email(value)
|
||||
if context_source.get('option_key') == 'from_domain':
|
||||
return normalize_domain(value)
|
||||
if config.get('normalizer_key') == 'name':
|
||||
return normalize_customer_name(value) or None
|
||||
return str(value or '').strip().upper() or None
|
||||
# 与影子识别/证据导入共用同一归一化,保证复核键与存储键同源(含换行折叠)。
|
||||
return normalize_identity_evidence_value(
|
||||
value,
|
||||
option_key=context_source.get('option_key'),
|
||||
normalizer_key=config.get('normalizer_key'),
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]:
|
||||
def _classify_auto_evidence_match(
|
||||
*, runtime_normalized: str, evidence_normalized: str, option_key: str,
|
||||
) -> str | None:
|
||||
"""
|
||||
对单个授权证据做自动确认视角的命中分级。
|
||||
|
||||
核心逻辑:邮箱/域名只做大小写无关精确等值;文本类先比 canonical 等值
|
||||
(吸收标点/空白差异),再判「指纹完整出现在提取值中」的强包含;
|
||||
截断包含(containment_weak)返回给展示层但在此一律判不命中——剩余部分
|
||||
未经验证,无法排除「另一个更短名的完整客户」,禁止自动确认。
|
||||
"""
|
||||
if option_key in {'from_email', 'from_domain'}:
|
||||
if runtime_normalized.casefold() == evidence_normalized.casefold():
|
||||
return IDENTITY_MATCH_EQUALITY
|
||||
return None
|
||||
if canonical_identity_key(runtime_normalized) == canonical_identity_key(evidence_normalized):
|
||||
return IDENTITY_MATCH_EQUALITY
|
||||
match_kind = classify_identity_containment(
|
||||
runtime_normalized, evidence_normalized, option_key=option_key,
|
||||
)
|
||||
return match_kind if match_kind == IDENTITY_MATCH_CONTAINMENT_STRONG else None
|
||||
|
||||
|
||||
def resolve_auto_customer_decision(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]:
|
||||
"""
|
||||
按影子记录的冻结定义和当前已审核授权证据求唯一自动确认客户。
|
||||
|
||||
业务定义、站点证据、公共邮箱域名及快照外字段都不是自动确认依据;多个客户命中时
|
||||
一律返回歧义,即使其中一个客户累积的证据更多。
|
||||
一律返回歧义,即使其中一个客户累积的证据更多。等值命中存在时包含命中不参与裁决;
|
||||
仅「指纹完整出现在提取值中」(unique_containment_match)这一种包含形态在唯一且
|
||||
授权时可自动确认,截断形态永不。
|
||||
|
||||
Args:
|
||||
shadow: 已持久化的客户影子识别记录(须含规则快照与证据 JSON)。
|
||||
|
||||
Returns:
|
||||
裁决字典:status(unique_strong_match / unique_containment_match /
|
||||
ambiguous / unmatched / rule_snapshot_missing 等)、customer_id、
|
||||
evidence(含 match_kind 溯源)与候选客户列表。
|
||||
"""
|
||||
snapshot = _rule_snapshot(shadow)
|
||||
if snapshot is None:
|
||||
@@ -256,6 +295,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
if isinstance(item, dict) and str(item.get('id') or '')
|
||||
}
|
||||
matched: dict[int, list[dict[str, Any]]] = {}
|
||||
match_tiers: dict[int, str] = {}
|
||||
for evidence in shadow.evidence_json or []:
|
||||
if not isinstance(evidence, dict):
|
||||
continue
|
||||
@@ -298,8 +338,12 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
auto_match_allowed=True,
|
||||
).all()
|
||||
for record in records:
|
||||
# 主数据中历史录入值也可能保留不同大小写;按指纹语义比较而非原始字符串比较。
|
||||
if str(record.normalized_value or '').strip().casefold() != normalized.casefold():
|
||||
match_kind = _classify_auto_evidence_match(
|
||||
runtime_normalized=verified_normalized,
|
||||
evidence_normalized=str(record.normalized_value or ''),
|
||||
option_key=option_key,
|
||||
)
|
||||
if match_kind is None:
|
||||
continue
|
||||
if record.customer_id is None:
|
||||
continue
|
||||
@@ -311,16 +355,34 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
'definition_id': definition_id,
|
||||
'definition_code': definition.get('definition_code'),
|
||||
'normalized_value': normalized,
|
||||
'match_kind': match_kind,
|
||||
'source': field_value_source,
|
||||
'context_source': context_source,
|
||||
})
|
||||
if (
|
||||
customer.id not in match_tiers
|
||||
or match_kind == IDENTITY_MATCH_EQUALITY
|
||||
):
|
||||
match_tiers[customer.id] = match_kind
|
||||
# [STEP] 等值优先:存在等值命中的客户时,包含命中客户不参与裁决;
|
||||
# 截断包含已在分级阶段被排除,绝不出现在自动确认候选中。
|
||||
equality_customer_ids = {cid for cid, kind in match_tiers.items() if kind == IDENTITY_MATCH_EQUALITY}
|
||||
decision_customer_ids = equality_customer_ids or set(match_tiers)
|
||||
matched = {cid: matched[cid] for cid in decision_customer_ids}
|
||||
if len(matched) != 1:
|
||||
result = _decision_base(shadow, status='ambiguous' if matched else 'unmatched')
|
||||
result['evidence'] = [item for rows in matched.values() for item in rows]
|
||||
result['candidate_customer_ids'] = sorted(matched)
|
||||
return result
|
||||
customer_id = next(iter(matched))
|
||||
result = _decision_base(shadow, status='unique_strong_match')
|
||||
result = _decision_base(
|
||||
shadow,
|
||||
status=(
|
||||
'unique_strong_match'
|
||||
if match_tiers[customer_id] == IDENTITY_MATCH_EQUALITY
|
||||
else 'unique_containment_match'
|
||||
),
|
||||
)
|
||||
result['customer_id'] = customer_id
|
||||
result['evidence'] = matched[customer_id]
|
||||
return result
|
||||
@@ -362,7 +424,7 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice | ShippingOrderTask)
|
||||
if shadow is None:
|
||||
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
|
||||
decision = _resolve_auto_customer_from_shadow_resolution(shadow)
|
||||
decision = resolve_auto_customer_decision(shadow)
|
||||
quality_gate = _auto_confirmation_quality_gate()
|
||||
if not quality_gate['is_eligible']:
|
||||
return {
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
"""
|
||||
services/shipping_notice/customer_normalization.py
|
||||
|
||||
用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验。
|
||||
用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验,
|
||||
并提供识别证据的 canonical 比较键与包含关系分级。
|
||||
依赖:re、unicodedata 标准库。
|
||||
逻辑:管理后台导入与运行期客户裁决共用,避免同一证据在不同入口产生不同匹配键。
|
||||
逻辑:管理后台导入、运行期影子识别与自动确认复核共用同一证据归一化
|
||||
(normalize_identity_evidence_value),避免同一证据在不同入口产生不同匹配键;
|
||||
canonical 键用于标点/空白无关的等值比较,包含分级支撑客户识别的三层匹配。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -130,3 +133,97 @@ def normalize_identifier(identifier_type: Any, value: Any) -> str:
|
||||
details={'field': 'identifier_value'},
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
# 邮箱/域名上下文键:指纹语义为精确标识,禁止参与包含分级。
|
||||
_IDENTITY_EMAIL_DOMAIN_OPTION_KEYS = frozenset({'from_email', 'from_domain'})
|
||||
# 包含命中的最短 canonical 字符数:更短片段(如 'c/o'→'CO')不足以声明同主体,
|
||||
# 且短指纹一律由 canonical 等值路径承担,不享受包含兜底。
|
||||
IDENTITY_CONTAINMENT_MIN_CHARS = 8
|
||||
# 包含关系等值性强弱标记:strong=指纹完整出现在提取值中;weak=提取值疑似指纹截断。
|
||||
IDENTITY_MATCH_EQUALITY = 'approved_identity_evidence'
|
||||
IDENTITY_MATCH_CONTAINMENT_STRONG = 'containment_strong'
|
||||
IDENTITY_MATCH_CONTAINMENT_WEAK = 'containment_weak'
|
||||
# 等值 > 完整包含 > 截断包含;数值越小身份信号越强。
|
||||
IDENTITY_MATCH_TIER_RANK = {
|
||||
IDENTITY_MATCH_EQUALITY: 0,
|
||||
IDENTITY_MATCH_CONTAINMENT_STRONG: 1,
|
||||
IDENTITY_MATCH_CONTAINMENT_WEAK: 2,
|
||||
}
|
||||
|
||||
_CANONICAL_STRIP_RE = re.compile(r'[\W_]+', re.UNICODE)
|
||||
|
||||
|
||||
def normalize_identity_evidence_value(
|
||||
value: Any, *, option_key: Any = None, normalizer_key: Any = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
按识别定义冻结的字段配置生成证据匹配键;导入、影子识别与自动确认复核共用。
|
||||
|
||||
核心逻辑:与 identity_rules._normalize_for_snapshot、resolver._normalize、
|
||||
customer_auto_resolution._verified_shadow_value 的历史分支一一对应;兜底分支统一
|
||||
走 clean_text(折叠内部空白/换行),修复运行侧保留换行导致多行提取值永远无法
|
||||
等值命中单行注册证据的不对称缺陷。
|
||||
|
||||
Args:
|
||||
value: 已裁决 Header 字段值或管理员录入的原始证据值。
|
||||
option_key: 字段上下文来源(from_email/from_domain 时按邮箱/域名校验归一)。
|
||||
normalizer_key: 冻结 Schema 字段配置的 normalizer('name' 走客户名称词管线)。
|
||||
|
||||
Returns:
|
||||
归一化匹配键;空值返回 None(调用方按各自契约决定跳过或报错)。
|
||||
|
||||
Raises:
|
||||
ValidationError: 邮箱/域名值不合法(由下游 normalize_* 抛出,调用方自行容错)。
|
||||
"""
|
||||
kind = clean_text(option_key).lower() if option_key else ''
|
||||
if kind == 'from_email':
|
||||
return normalize_email(value)
|
||||
if kind == 'from_domain':
|
||||
return normalize_domain(value)
|
||||
if clean_text(normalizer_key or '').lower() == 'name':
|
||||
return normalize_customer_name(value) or None
|
||||
return clean_text(value).upper() or None
|
||||
|
||||
|
||||
def canonical_identity_key(value: Any) -> str:
|
||||
"""
|
||||
生成识别证据的 canonical 比较键:NFKC + casefold + 剔除全部非字母数字。
|
||||
|
||||
核心逻辑:中文等 Unicode 词字符保留(支持中文客户名),标点、空白、下划线
|
||||
全部剔除,使 'QCH, INC.' 与 'QCH INC.' 这类打印差异在等值比较中不再分裂。
|
||||
邮箱/域名指纹禁止使用本键比较('@'、'.' 属于语义字符),调用方须先分流。
|
||||
"""
|
||||
return _CANONICAL_STRIP_RE.sub('', unicodedata.normalize('NFKC', str(value or '')).casefold())
|
||||
|
||||
|
||||
def classify_identity_containment(
|
||||
runtime_normalized: Any, evidence_normalized: Any, *, option_key: Any = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
对文本类识别证据做双向包含分级,供客户识别的弱命中层使用。
|
||||
|
||||
Args:
|
||||
runtime_normalized: 运行时提取值(已经 normalize_identity_evidence_value 归一)。
|
||||
evidence_normalized: 库内已注册证据值(同上归一)。
|
||||
option_key: 字段上下文来源;from_email/from_domain 直接返回 None。
|
||||
|
||||
Returns:
|
||||
IDENTITY_MATCH_CONTAINMENT_STRONG:注册指纹完整出现在提取值中(提取多带
|
||||
折行尾巴),身份信号可参与受控自动确认;
|
||||
IDENTITY_MATCH_CONTAINMENT_WEAK:提取值疑似指纹截断片段(剩余部分未经验
|
||||
证,无法区分「截断」与「另一个更短名的完整客户」),只允许作为人工确认建议;
|
||||
None:无包含关系,或包含侧短于 IDENTITY_CONTAINMENT_MIN_CHARS。
|
||||
"""
|
||||
kind = clean_text(option_key).lower() if option_key else ''
|
||||
if kind in _IDENTITY_EMAIL_DOMAIN_OPTION_KEYS:
|
||||
return None
|
||||
runtime_key = canonical_identity_key(runtime_normalized)
|
||||
evidence_key = canonical_identity_key(evidence_normalized)
|
||||
if not runtime_key or not evidence_key:
|
||||
return None
|
||||
if len(evidence_key) >= IDENTITY_CONTAINMENT_MIN_CHARS and evidence_key in runtime_key:
|
||||
return IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
if len(runtime_key) >= IDENTITY_CONTAINMENT_MIN_CHARS and runtime_key in evidence_key:
|
||||
return IDENTITY_MATCH_CONTAINMENT_WEAK
|
||||
return None
|
||||
@@ -36,9 +36,10 @@ def refresh_candidate_shadow_resolution(candidate: ShippingOrderCandidate) -> Sh
|
||||
resolution = resolve_candidate_identity(candidate, intake)
|
||||
evidence = list(resolution['evidence'])
|
||||
matches = list(resolution['customer_matches'])
|
||||
# 状态一律以 resolver 的层级裁决为准(等值 > 完整包含 > 截断包含),
|
||||
# 本地不再按分数重复判定,避免两处排序/歧义语义分叉;top_score 取排序首位的累计权重。
|
||||
status = str(resolution['status'])
|
||||
top_score = float(matches[0]['score']) if matches else None
|
||||
tied = [item for item in matches if float(item['score']) == top_score] if top_score is not None else []
|
||||
status = 'unmatched' if not matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous'
|
||||
row = db.session.query(ShippingCustomerShadowResolution).filter_by(candidate_id=int(candidate.id)).first()
|
||||
if row is None:
|
||||
row = ShippingCustomerShadowResolution(candidate_id=int(candidate.id), intake_id=int(candidate.intake_id))
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
用途:基于已发布身份规则集产生客户主体与送货站点的可解释影子候选。
|
||||
依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据。
|
||||
逻辑:只读取 Candidate 所属 Extraction 的 accepted/corroborated Header FieldValue;站点候选不反向确认客户主体。
|
||||
客户命中分三层:canonical 等值 > 完整包含(指纹整体出现在提取值中)> 截断包含(仅人工建议);
|
||||
邮箱/域名指纹只做精确等值,禁止包含比较。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,12 +25,14 @@ from app.models import (
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
normalize_customer_name,
|
||||
normalize_domain,
|
||||
normalize_email,
|
||||
IDENTITY_MATCH_EQUALITY,
|
||||
IDENTITY_MATCH_TIER_RANK,
|
||||
canonical_identity_key,
|
||||
classify_identity_containment,
|
||||
normalize_identity_evidence_value,
|
||||
)
|
||||
|
||||
RESOLUTION_VERSION = 'shadow-v2'
|
||||
RESOLUTION_VERSION = 'shadow-v3'
|
||||
ACCEPTED_DECISION_STATUSES = frozenset({'accepted', 'corroborated'})
|
||||
|
||||
|
||||
@@ -37,14 +41,11 @@ def _normalize(definition: dict[str, Any], value: object) -> str | None:
|
||||
try:
|
||||
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
if source.get('option_key') == 'from_email':
|
||||
return normalize_email(value)
|
||||
if source.get('option_key') == 'from_domain':
|
||||
return normalize_domain(value)
|
||||
if field_config.get('normalizer_key') == 'name':
|
||||
return normalize_customer_name(value) or None
|
||||
normalized = str(value or '').strip().upper()
|
||||
return normalized or None
|
||||
return normalize_identity_evidence_value(
|
||||
value,
|
||||
option_key=source.get('option_key'),
|
||||
normalizer_key=field_config.get('normalizer_key'),
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@@ -154,6 +155,8 @@ def _source_evidence(
|
||||
normalized = _normalize(definition, value)
|
||||
if not normalized:
|
||||
continue
|
||||
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
context_source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
evidence.append({
|
||||
'definition_id': definition_id,
|
||||
'definition_code': code,
|
||||
@@ -161,6 +164,8 @@ def _source_evidence(
|
||||
'target_type': definition.get('target_type'),
|
||||
'raw_value': value,
|
||||
'normalized_value': normalized,
|
||||
# 供命中分级使用:邮箱/域名指纹只做精确等值,不参与包含比较。
|
||||
'option_key': str(context_source.get('option_key') or ''),
|
||||
'weight': int(definition.get('default_weight') or 0),
|
||||
'source': source,
|
||||
})
|
||||
@@ -178,27 +183,68 @@ def _customer_match_payload(customer: ShippingCustomer, *, score: float, reasons
|
||||
}
|
||||
|
||||
|
||||
def _classify_evidence_match(
|
||||
*, runtime_value: str, evidence_value: str, option_key: str,
|
||||
) -> str | None:
|
||||
"""
|
||||
对单个已审核证据做命中分级:等值 > 完整包含 > 截断包含。
|
||||
|
||||
核心逻辑:邮箱/域名指纹语义字符(@、.)参与构成身份,只做归一化后精确等值;
|
||||
文本类指纹先比 canonical 等值(吸收标点/空白/大小写差异),再判双向包含。
|
||||
"""
|
||||
if option_key in {'from_email', 'from_domain'}:
|
||||
return IDENTITY_MATCH_EQUALITY if runtime_value == evidence_value else None
|
||||
if canonical_identity_key(runtime_value) == canonical_identity_key(evidence_value):
|
||||
return IDENTITY_MATCH_EQUALITY
|
||||
return classify_identity_containment(runtime_value, evidence_value, option_key=option_key)
|
||||
|
||||
|
||||
def _rank_customer_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""按同定义已审核证据聚合客户候选;同分保留歧义,禁止排序取首条。"""
|
||||
"""
|
||||
按同定义已审核证据聚合客户候选,附命中层级;禁止排序取首条抹平歧义。
|
||||
|
||||
核心逻辑:每个(运行时证据, 注册证据)对先分级;同一客户取其最强命中层级,
|
||||
排序先按层级升序(等值候选始终排在包含候选前),再按累计权重降序。
|
||||
顶层(最强层级)候选唯一时调用方才判 unique_candidate,多家并列即 ambiguous。
|
||||
"""
|
||||
scores: dict[int, float] = defaultdict(float)
|
||||
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
tiers: dict[int, str] = {}
|
||||
customers = {item.id: item for item in ShippingCustomer.query.filter_by(status='active').all()}
|
||||
for item in evidence:
|
||||
if item['target_type'] != 'customer':
|
||||
continue
|
||||
records = ShippingIdentityEvidence.query.filter_by(
|
||||
definition_id=item['definition_id'], normalized_value=item['normalized_value'], status='approved',
|
||||
definition_id=item['definition_id'], status='approved',
|
||||
).all()
|
||||
for record in records:
|
||||
customer = customers.get(record.customer_id) if record.customer_id is not None else None
|
||||
if customer is None:
|
||||
continue
|
||||
match_kind = _classify_evidence_match(
|
||||
runtime_value=str(item['normalized_value'] or ''),
|
||||
evidence_value=str(record.normalized_value or ''),
|
||||
option_key=str(item.get('option_key') or ''),
|
||||
)
|
||||
if match_kind is None:
|
||||
continue
|
||||
scores[customer.id] += item['weight']
|
||||
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': 'approved_identity_evidence'})
|
||||
return sorted(
|
||||
[_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id]) for customer_id, score in scores.items()],
|
||||
key=lambda item: (-float(item['score']), int(item['customer_id'])),
|
||||
)
|
||||
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': match_kind})
|
||||
if customer.id not in tiers or IDENTITY_MATCH_TIER_RANK[match_kind] < IDENTITY_MATCH_TIER_RANK[tiers[customer.id]]:
|
||||
tiers[customer.id] = match_kind
|
||||
ranked = [
|
||||
_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id])
|
||||
for customer_id, score in scores.items()
|
||||
]
|
||||
# 客户最强层级在聚合后补写,再按(层级, 权重, 客户 ID)排序。
|
||||
for item in ranked:
|
||||
item['match_kind'] = tiers[int(item['customer_id'])]
|
||||
ranked.sort(key=lambda item: (
|
||||
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])],
|
||||
-float(item['score']),
|
||||
int(item['customer_id']),
|
||||
))
|
||||
return ranked
|
||||
|
||||
|
||||
def _rank_site_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
@@ -252,11 +298,20 @@ def resolve_candidate_identity(candidate: ShippingOrderCandidate, intake: Shippi
|
||||
evidence, extraction = _source_evidence(definitions, candidate=candidate, intake=intake)
|
||||
customer_matches = _rank_customer_matches(evidence)
|
||||
site_matches = _rank_site_matches(evidence)
|
||||
top_score = float(customer_matches[0]['score']) if customer_matches else None
|
||||
tied = [item for item in customer_matches if float(item['score']) == top_score] if top_score is not None else []
|
||||
# [STEP] 顶层 = 候选中的最强命中层级;仅顶层唯一才 unique_candidate,
|
||||
# 强层级唯一时弱层级候选仅作展示,不参与歧义计算。
|
||||
top_tier_candidates: list[dict[str, Any]] = []
|
||||
if customer_matches:
|
||||
top_tier_rank = min(
|
||||
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] for item in customer_matches
|
||||
)
|
||||
top_tier_candidates = [
|
||||
item for item in customer_matches
|
||||
if IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] == top_tier_rank
|
||||
]
|
||||
return {
|
||||
'resolution_version': RESOLUTION_VERSION,
|
||||
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous',
|
||||
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(top_tier_candidates) == 1 else 'ambiguous',
|
||||
'evidence': evidence,
|
||||
'customer_matches': customer_matches,
|
||||
'site_matches': site_matches,
|
||||
|
||||
@@ -258,19 +258,26 @@ def retry_review_case_customer_resolution(
|
||||
case = _load_writable_case(user_id=user_id, case_no=case_no)
|
||||
matches: list[dict[str, Any]] = []
|
||||
if case.candidate_id:
|
||||
from app.services.shipping_notice.customer_auto_resolution import (
|
||||
AUTO_CONFIRM_ELIGIBLE_STATUSES,
|
||||
resolve_auto_customer_decision,
|
||||
)
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||||
if candidate is not None:
|
||||
shadow = refresh_candidate_shadow_resolution(candidate)
|
||||
# [STEP 2] 重新识别后若客户指纹唯一命中,直接写入确认结果;投影函数保持纯读。
|
||||
# [STEP 2] 重新识别后与任务期协调器共用同一分级裁决:canonical 等值唯一或
|
||||
# 「指纹完整出现」包含唯一且证据授权才自动确认;截断建议(containment_weak)
|
||||
# 只进候选展示,绝不在此确认。投影函数保持纯读。
|
||||
decision = resolve_auto_customer_decision(shadow)
|
||||
if (
|
||||
shadow.status == 'unique_candidate'
|
||||
and shadow.top_customer_id
|
||||
str(decision.get('status') or '') in AUTO_CONFIRM_ELIGIBLE_STATUSES
|
||||
and decision.get('customer_id') is not None
|
||||
and not resolve_review_case_customer_resolved(case=case, candidate=candidate)
|
||||
):
|
||||
confirm_customer_resolution(
|
||||
candidate,
|
||||
customer_id=int(shadow.top_customer_id),
|
||||
customer_id=int(decision['customer_id']),
|
||||
actor_id=None,
|
||||
method='auto_rule',
|
||||
reason='客户识别指纹唯一命中自动确认',
|
||||
|
||||
Reference in new issue
Block a user