feat(shipping-notice): 添加识别定义和规则集管理功能,支持客户和站点的可配置识别规则

This commit is contained in:
hugo committed 2026-07-20 19:28:17 +08:00
1 parent 88408490d7
commit 34d489a2d1
167 files changed
+10365 -7978

No files matched your search

@@ -0,0 +1,5 @@
"""统一客户身份取证与影子候选解析入口。"""
from app.services.shipping_notice.identity_resolution.resolver import resolve_candidate_identity
__all__ = ['resolve_candidate_identity']
@@ -0,0 +1,259 @@
"""
用途:基于已发布身份规则集产生客户主体与送货站点的可解释影子候选。
依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据和邮件接入元数据。
逻辑:只读取邮件元数据及 accepted/corroborated Header FieldValue;站点候选独立保存,绝不反向确认客户主体。
"""
from __future__ import annotations
from collections import defaultdict
from email.utils import parseaddr
import hashlib
import re
from typing import Any
from app import db
from app.models import (
ShippingCustomer,
ShippingCustomerSite,
ShippingIdentityEvidence,
ShippingIdentityRuleSet,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
)
from app.services.shipping_notice.customer_normalization import (
normalize_customer_name,
normalize_domain,
normalize_email,
)
RESOLUTION_VERSION = 'shadow-v2'
ACCEPTED_DECISION_STATUSES = frozenset({'accepted', 'corroborated'})
def _normalize(definition: dict[str, Any], value: object) -> str | None:
"""按发布定义快照生成稳定匹配键;无效输入仅跳过当前证据而不影响其余取证。"""
try:
normalizer = str(definition.get('normalizer_key') or '')
if normalizer == 'email':
return normalize_email(value)
if normalizer == 'domain':
return normalize_domain(value)
if normalizer == 'name':
return normalize_customer_name(value) or None
normalized = str(value or '').strip().upper()
return normalized or None
except Exception:
return None
def _published_rule_set() -> ShippingIdentityRuleSet | None:
"""读取唯一已发布规则集;未发布时安全返回空候选而不是回退旧硬编码规则。"""
return ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
def _mail_values(intake: ShippingNoticeIntake) -> dict[str, str]:
"""从接入邮件元数据取邮箱和域名投影,不读取订单解析或 LLM 摘要。"""
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
email_meta = structured.get('email') if isinstance(structured.get('email'), dict) else {}
sender = parseaddr(str(email_meta.get('from') or ''))[1].strip()
if not sender:
return {}
try:
email = normalize_email(sender)
domain = normalize_domain(email)
except Exception:
return {}
return {'email': email, 'domain': domain}
def _template_fingerprint(candidate: ShippingNoticeCandidate) -> str | None:
"""由主文档文本生成脱敏模板指纹;只保留哈希,不将正文或个人信息写入识别快照。"""
document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id))
if document is None or int(document.intake_id) != int(candidate.intake_id):
return None
text = str(document.extracted_text or '').upper().strip()
if not text:
return None
# 订单编号、日期、金额等可变字面量不参与模板身份,减少同模板不同订单的误分裂。
template_shape = re.sub(r'\b[A-Z0-9][A-Z0-9_\-/]{2,}\b', '<TOKEN>', text)
template_shape = re.sub(r'\d+', '<NUMBER>', template_shape)
template_shape = re.sub(r'\s+', ' ', template_shape).strip()
if not template_shape:
return None
return hashlib.sha256(template_shape.encode('utf-8')).hexdigest()
def _accepted_header_values(candidate: ShippingNoticeCandidate) -> tuple[ShippingOrderExtraction | None, dict[str, str]]:
"""仅从 Candidate 外键关联的已裁决 Header FieldValue 读取业务证据,拒绝原始 JSON 和 Line 字段。"""
if candidate.order_extraction_id is None:
return None, {}
extraction = db.session.get(ShippingOrderExtraction, int(candidate.order_extraction_id))
if extraction is None or int(extraction.intake_id) != int(candidate.intake_id):
return None, {}
rows = (
db.session.query(ShippingOrderFieldValue, ShippingOrderFieldDecision)
.join(ShippingOrderFieldDecision, ShippingOrderFieldDecision.id == ShippingOrderFieldValue.decision_id)
.filter(
ShippingOrderFieldValue.extraction_id == extraction.id,
ShippingOrderFieldValue.line_id.is_(None),
ShippingOrderFieldDecision.line_id.is_(None),
ShippingOrderFieldDecision.decision_status.in_(ACCEPTED_DECISION_STATUSES),
)
.all()
)
return extraction, {
str(value.field_id): str(value.value_text or value.value_json or '').strip()
for value, _decision in rows
if str(value.value_text or value.value_json or '').strip()
}
def _source_evidence(
definitions: list[dict[str, Any]], *, candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake,
) -> tuple[list[dict[str, Any]], ShippingOrderExtraction | None]:
"""按规则快照的受控来源适配器编译证据输入,拒绝按定义编码决定取值。"""
extraction, header_values = _accepted_header_values(candidate)
mail_values = _mail_values(intake)
template_fingerprint = _template_fingerprint(candidate)
evidence: list[dict[str, Any]] = []
for definition in definitions:
definition_id = str(definition.get('id') or '')
code = str(definition.get('definition_code') or '')
adapter_key = str(definition.get('source_adapter_key') or '')
selector = definition.get('source_selector') if isinstance(definition.get('source_selector'), dict) else {}
value: str | None = None
source: dict[str, Any] = {'kind': 'unsupported_source_adapter'}
if adapter_key == 'order_field':
field_id = str(selector.get('order_field_id') or definition.get('order_field_id') or '')
value = header_values.get(field_id)
source = {'kind': 'order_field_value', 'order_field_id': field_id, 'extraction_id': extraction.id if extraction else None}
elif adapter_key == 'email_metadata':
projection = str(selector.get('projection') or '')
if selector.get('attribute') == 'email.from' and projection in {'email', 'domain'}:
value = mail_values.get(projection)
source = {'kind': 'mail_metadata', 'attribute': 'email.from', 'projection': projection}
elif adapter_key == 'document_template' and selector == {'document': 'primary'}:
value = template_fingerprint
source = {'kind': 'document_template_fingerprint', 'document_id': candidate.primary_document_id}
if not value:
continue
normalized = _normalize(definition, value)
if not normalized:
continue
evidence.append({
'definition_id': definition_id,
'definition_code': code,
'source_adapter_key': adapter_key,
'source_selector': selector,
'target_type': definition.get('target_type'),
'attribute_key': definition.get('attribute_key'),
'raw_value': value,
'normalized_value': normalized,
'weight': int(definition.get('default_weight') or 0),
'source': source,
})
return evidence, extraction
def _customer_match_payload(customer: ShippingCustomer, *, score: float, reasons: list[dict[str, Any]]) -> dict[str, Any]:
"""构建客户候选快照,避免前端或后续流程回读可变主数据推断命中原因。"""
return {
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'score': score,
'reasons': reasons,
}
def _rank_customer_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""按同定义已审核证据聚合客户候选;同分保留歧义,禁止排序取首条。"""
scores: dict[int, float] = defaultdict(float)
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
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',
).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
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'])),
)
def _rank_site_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""独立聚合站点候选;站点命中仅供 Ship-to 人工复核,不构成客户主体候选。"""
scores: dict[int, float] = defaultdict(float)
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
customers = {item.id: item for item in ShippingCustomer.query.filter_by(status='active').all()}
sites = {
item.id: item for item in ShippingCustomerSite.query.filter_by(status='active').all()
if item.customer_id in customers
}
for item in evidence:
if item['target_type'] != 'site':
continue
records = ShippingIdentityEvidence.query.filter_by(
definition_id=item['definition_id'], normalized_value=item['normalized_value'], status='approved',
).all()
for record in records:
site = sites.get(record.site_id) if record.site_id is not None else None
if site is None:
continue
scores[site.id] += item['weight']
reasons[site.id].append({**item, 'evidence_id': record.id, 'match_kind': 'approved_identity_evidence'})
return sorted([
{
'site_id': site_id,
'site_name': sites[site_id].site_name,
'site_code': sites[site_id].site_code,
'customer_id': sites[site_id].customer_id,
'customer_name': customers[sites[site_id].customer_id].standard_name,
'score': score,
'reasons': reasons[site_id],
}
for site_id, score in scores.items()
], key=lambda item: (-float(item['score']), int(item['site_id'])))
def resolve_candidate_identity(candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake) -> dict[str, Any]:
"""
解析一个 Candidate 的身份影子候选。
仅在 Candidate/Intake 已持久化后调用;返回快照数据,不绑定业务单、不编号,也不读取 raw_llm_output_json。
"""
rule_set = _published_rule_set()
definitions = list((rule_set.definition_json or {}).get('definitions') or []) if rule_set else []
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 []
return {
'resolution_version': RESOLUTION_VERSION,
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous',
'evidence': evidence,
'customer_matches': customer_matches,
'site_matches': site_matches,
'rule_set': {
'id': rule_set.id if rule_set else None,
'version': rule_set.version if rule_set else None,
'checksum': rule_set.checksum if rule_set else None,
'definitions': definitions,
},
'order_schema_version_id': extraction.schema_version_id if extraction else None,
'order_extraction_id': extraction.id if extraction else None,
}