feat(shipping-notice): 客户识别证据命中分级为三层匹配

- 归一层新增 canonical 等值键与包含分级(完整/截断),统一证据标准化入口
- 影子识别升至 shadow-v3:等值 > 完整包含 > 截断包含层级裁决,邮箱/域名仅精确等值
- 自动确认升至 auto-v3:完整包含可自动确认,截断包含仅供人工建议不进自动裁决
- 影子候选状态与复核侧重新识别统一复用 resolver 分级裁决,移除本地分数重复判定
- 新增客户身份三层匹配契约测试
This commit is contained in:
hugo committed 2026-09-17 15:54:52 +08:00
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='客户识别指纹唯一命中自动确认',
@@ -0,0 +1,384 @@
"""
backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py
用途:验证客户识别三级命中(canonical 等值 > 完整包含 > 截断包含)与受控自动确认边界。
依赖:内存数据库、customer_normalization、identity_resolution.resolver、
customer_auto_resolution、customer_shadow_resolution。
逻辑:以 QCH/Quanta 真实差异形态(标点变体、c/o 截断、折行块整段提取、家族前缀、
跨行 vs 单行证据)构造分支,断言影子候选层级、状态语义,以及自动确认只放行
「等值唯一」与「完整包含唯一且证据授权」,截断建议永不自动确认。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import (
ShippingCustomer,
ShippingIdentityDefinition,
ShippingIdentityEvidence,
ShippingIdentityRuleSet,
ShippingOrderCandidate,
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderIntake,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice.customer_auto_resolution import resolve_auto_customer_decision
from app.services.shipping_notice.customer_normalization import (
IDENTITY_MATCH_CONTAINMENT_STRONG,
IDENTITY_MATCH_CONTAINMENT_WEAK,
IDENTITY_MATCH_EQUALITY,
canonical_identity_key,
classify_identity_containment,
normalize_identity_evidence_value,
)
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
from app.services.shipping_notice.identity_resolution import resolve_candidate_identity
FIELD_ID = 'fid-ship-to-customer'
RULE_SET_DEF_ID = 'def-ship-to-customer'
@pytest.mark.pure_unit
class TestCanonicalIdentityKey:
"""canonical 键:标点/空白/大小写不敏感,中文保留。"""
def test_punctuation_whitespace_case_insensitive(self):
# 关键断言:QCH 注册值与 PDF 打印值的标点/空格差异不再分裂等值命中。
assert canonical_identity_key('QCH, INC., A NEVADA CORPORATION') == canonical_identity_key(
'qch inc a nevada corporation',
)
def test_keeps_cjk_word_chars(self):
# 关键断言:中文客户名不被剔除,仍可参与等值比较。
assert canonical_identity_key('英業達股份有限公司桃科廠') == '英業達股份有限公司桃科廠'
assert canonical_identity_key('Inventec 英業達') == 'inventec英業達'
@pytest.mark.pure_unit
class TestNormalizeIdentityEvidenceValue:
"""识别证据统一归一化:三处调用点同源,兜底分支折叠内部空白。"""
def test_fallback_collapses_newlines(self):
# 关键断言:多行提取值折叠换行后可与单行注册证据等值(修复换行不对称缺陷)。
assert normalize_identity_evidence_value('QUANTA MFG,\n1 WALDENBOOKS DR.') == 'QUANTA MFG, 1 WALDENBOOKS DR.'
def test_name_normalizer_strips_punctuation(self):
assert normalize_identity_evidence_value('Hyve, Solutions', normalizer_key='name') == 'HYVESOLUTIONS'
def test_email_branch_keeps_semantic_chars(self):
assert normalize_identity_evidence_value('A@B.COM', option_key='from_email') == 'a@b.com'
def test_blank_returns_none(self):
assert normalize_identity_evidence_value(' ') is None
@pytest.mark.pure_unit
class TestClassifyIdentityContainment:
"""双向包含分级:强=指纹完整出现;弱=提取值疑似截断;邮箱/域名不参与。"""
EVIDENCE = 'QCH INC., A NEVADA CORPORATION C/O QUANTA'
def test_strong_when_fingerprint_fully_inside_runtime(self):
# 关键断言:折行块整段进入字段值时,完整指纹命中判强包含(可受控自动确认)。
assert classify_identity_containment(
'QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC', self.EVIDENCE,
) == IDENTITY_MATCH_CONTAINMENT_STRONG
def test_weak_when_runtime_is_truncation(self):
# 关键断言:截断方向只判弱命中——剩余部分未经验证,禁止自动确认。
assert classify_identity_containment(
'QCH, INC., A NEVADA CORPORATION c/o', self.EVIDENCE,
) == IDENTITY_MATCH_CONTAINMENT_WEAK
def test_fragment_below_minimum_chars_rejected(self):
# 关键断言:'c/o'→'CO' 这类短碎片不得产生包含噪声。
assert classify_identity_containment('c/o', self.EVIDENCE) is None
def test_email_domain_never_contained(self):
assert classify_identity_containment('ops@corp.com', 'ops@corp', option_key='from_email') is None
def test_unrelated_values_rejected(self):
assert classify_identity_containment('HYVE SOLUTIONS CORPORATION', self.EVIDENCE) is None
def _build_identity_world(*, runtime_value: str, evidences: list[dict]):
"""
构建最小识别世界:发布规则集 + 单 Header 字段抽取链 + 客户/证据主数据。
Args:
runtime_value: 已裁决 Header 字段值(模拟 PDF 提取结果)。
evidences: 注册证据列表,每项含 customer_name/short_code/normalized_value,
可选 auto(默认 True,对应 auto_match_allowed)。
Returns:
(candidate, intake) 供 resolve_candidate_identity / 影子刷新使用。
"""
user = User(username='tier-user', email='tier@example.com', role='user')
db.session.add(user)
db.session.flush()
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
if schema is None:
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
db.session.add(schema)
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', lock_version=1, checksum='1' * 64,
definition_json={'fields': [{
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'display_name': 'Ship To Customer',
'scope': 'header', 'value_type': 'string', 'enabled': True,
'available_for_customer_identity': True, 'normalizer_key': 'trim',
}]},
)
db.session.add(version)
db.session.flush()
definition_json = {
'order_schema': {'id': version.id, 'version': version.version, 'checksum': version.checksum},
'definitions': [{
'id': RULE_SET_DEF_ID, 'definition_code': 'ship_to_customer_rule',
'display_name': 'Ship To Customer', 'evidence_label': 'Ship To',
'target_type': 'customer', 'context_field_id': FIELD_ID,
'default_weight': 100, 'max_automation': 'conditional', 'status': 'active',
'field_config': {
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'scope': 'header',
'value_type': 'string', 'normalizer_key': 'trim',
'context_source': {'provider': 'order_field', 'option_key': None},
'available_for_customer_identity': True,
},
}],
}
db.session.add(ShippingIdentityRuleSet(version=1, status='published', definition_json=definition_json, checksum='c' * 64))
db.session.add(ShippingIdentityDefinition(
id=RULE_SET_DEF_ID, definition_code='ship_to_customer_rule', target_type='customer',
context_field_id=FIELD_ID, default_weight=100, max_automation='conditional', status='active',
))
intake = ShippingOrderIntake(intake_no='INT-TIER', asset_id=1, user_id=user.id, parser_version='test')
db.session.add(intake)
db.session.flush()
extraction = ShippingOrderExtraction(
intake_id=intake.id, schema_version_id=version.id, input_snapshot_hash='h' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, field_id=FIELD_ID, decision_status='accepted', decided_at=datetime.utcnow(),
)
db.session.add(decision)
db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, field_id=FIELD_ID, decision_id=decision.id, value_text=runtime_value,
))
candidate = ShippingOrderCandidate(
candidate_no='CAND-TIER', intake_id=intake.id, primary_document_id=1,
candidate_key='tier-test', candidate_status='accepted', order_extraction_id=extraction.id,
)
db.session.add(candidate)
for index, spec in enumerate(evidences, start=1):
customer = ShippingCustomer(
standard_name=spec['customer_name'], short_code=spec['short_code'], status='active',
)
db.session.add(customer)
db.session.flush()
db.session.add(ShippingIdentityEvidence(
definition_id=RULE_SET_DEF_ID, customer_id=customer.id,
raw_value=spec['normalized_value'], normalized_value=spec['normalized_value'],
status='approved', auto_match_allowed=spec.get('auto', True),
))
db.session.commit()
return candidate, intake
class TestResolverTierMatching:
"""影子识别三级命中与状态语义(resolve_candidate_identity)。"""
def test_punctuation_variant_hits_equality_tier(self, app):
with app.app_context():
# 关键断言:'QCH,' vs 'QCH' 标点差异经 canonical 等值命中,不再是 unmatched。
candidate, intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
}],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
def test_truncated_runtime_becomes_weak_suggestion(self, app):
with app.app_context():
# 关键断言:c/o 截断形态产出唯一弱命中候选(unique_candidate 仅表示展示层唯一),
# match_kind=containment_weak,交由人工确认。
candidate, intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
}],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_WEAK
def test_wrapped_block_hits_strong_containment(self, app):
with app.app_context():
# 关键断言:折行块整段提取时完整指纹出现,判强包含。
candidate, intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
}],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
def test_family_prefix_stays_ambiguous(self, app):
with app.app_context():
# 关键断言:家族共享前缀同时包含命中 QCG/TW 两个站点客户 → ambiguous,不取首条。
candidate, intake = _build_identity_world(
runtime_value='Quanta Computer Inc.',
evidences=[
{
'customer_name': 'QUANTA QCG', 'short_code': 'QCG',
'normalized_value': 'QUANTA COMPUTER INC. DE 2470.58.340',
},
{
'customer_name': 'QUANTA TW', 'short_code': 'TWQ',
'normalized_value': 'QUANTA COMPUTER INC. HQ PLANT',
},
],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'ambiguous'
assert {item['match_kind'] for item in result['customer_matches']} == {IDENTITY_MATCH_CONTAINMENT_WEAK}
def test_equality_beats_containment_in_order(self, app):
with app.app_context():
# 关键断言:等值候选排在包含候选之前,且顶层唯一时状态为 unique_candidate。
candidate, intake = _build_identity_world(
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
evidences=[
{
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
'normalized_value': 'WISTRON CORPORATION',
},
{
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
},
],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
names = {item['standard_name']: item for item in result['customer_matches']}
# 关键断言:等值候选排第一,强包含候选次之;强层级唯一 → unique_candidate。
assert result['customer_matches'][0]['standard_name'] == 'WIWYNN CZ BRNO'
assert names['WIWYNN CZ BRNO']['match_kind'] == IDENTITY_MATCH_EQUALITY
assert names['WIWYNN CZ']['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
def test_multiline_runtime_matches_single_line_evidence(self, app):
with app.app_context():
# 关键断言:运行侧换行折叠修复后,跨行提取值可与单行注册证据等值命中。
candidate, intake = _build_identity_world(
runtime_value='Quanta Manufacturing Nashville, LLC,\n1 Waldenbooks Dr.',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QUANTA MANUFACTURING NASHVILLE, LLC, 1 WALDENBOOKS DR.',
}],
)
result = resolve_candidate_identity(candidate, intake)
assert result['status'] == 'unique_candidate'
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
class TestAutoConfirmDecision:
"""自动确认分级裁决(resolve_auto_customer_decision)。"""
def _shadow(self, candidate):
return refresh_candidate_shadow_resolution(candidate)
def test_equality_unique_confirms_strong(self, app):
with app.app_context():
candidate, _intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
}],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unique_strong_match'
assert decision['customer_id'] is not None
def test_containment_strong_unique_confirms_with_match_kind(self, app):
with app.app_context():
# 关键断言:指纹完整出现的唯一包含命中且证据授权 → unique_containment_match,
# 审计证据带 match_kind=containment_strong 溯源。
candidate, _intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
}],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unique_containment_match'
assert decision['customer_id'] is not None
assert decision['evidence'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
def test_truncation_only_never_confirms(self, app):
with app.app_context():
# 关键断言:截断形态(本单 7911678818.PDF)永不自动确认,保持 unmatched 交人工。
candidate, _intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
}],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unmatched'
assert decision['customer_id'] is None
def test_unauthorized_evidence_never_confirms(self, app):
with app.app_context():
# 关键断言:auto_match_allowed=False 的证据即使等值唯一也不自动确认。
candidate, _intake = _build_identity_world(
runtime_value='QCH, INC., A NEVADA CORPORATION',
evidences=[{
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
'normalized_value': 'QCH INC., A NEVADA CORPORATION', 'auto': False,
}],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unmatched'
assert decision['customer_id'] is None
def test_equality_precedes_containment(self, app):
with app.app_context():
# 关键断言:等值命中存在时包含命中不参与裁决,等值客户唯一即确认。
candidate, _intake = _build_identity_world(
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
evidences=[
{
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
'normalized_value': 'WISTRON CORPORATION',
},
{
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
},
],
)
decision = resolve_auto_customer_decision(self._shadow(candidate))
assert decision['status'] == 'unique_strong_match'
customers = {c.id: c.standard_name for c in ShippingCustomer.query.all()}
assert customers[decision['customer_id']] == 'WIWYNN CZ BRNO'