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
@@ -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'
|
||||
Reference in new issue
Block a user