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,237 @@
"""
backend/tests/services/shipping_notice/test_identity_rules_service.py
用途:验证可配置客户识别定义、规则集版本和订单字段依赖门禁。
依赖:内存数据库、订单 Schema 模型、identity_rules.service。
逻辑:只覆盖阶段一配置模型,不提前验证阶段二运行时客户候选解析。
"""
from __future__ import annotations
import json
import pytest
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingCustomer, ShippingIdentityDefinition, ShippingOrderField, ShippingOrderSchema, ShippingOrderSchemaVersion
from app.services.shipping_notice.identity_rules import service
from app.services.shipping_notice.order_schema import service as order_schema_service
def _published_header_field() -> ShippingOrderField:
"""建立已发布 Header 文本字段,模拟业务识别定义的唯一合法来源。"""
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
db.session.add(schema)
db.session.flush()
field = ShippingOrderField(schema_id=schema.id, field_code='ship_to_address', scope='header', value_type='string')
db.session.add(field)
db.session.flush()
db.session.add(ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={'fields': [{
'field_id': field.id, 'field_code': field.field_code, 'scope': 'header',
'value_type': 'string', 'enabled': True,
}]}, lock_version=1,
))
db.session.commit()
return field
def test_order_field_definition_requires_published_header_text_field_and_never_auto_confirms(app):
"""订单字段定义只能引用当前发布 Header 文本字段,且首期不能提升自动确认等级。"""
with app.app_context():
field = _published_header_field()
created = service.save_definition({
'definition_code': 'ship_to_address', 'target_type': 'site', 'attribute_key': 'ship_to_address',
'order_field_id': field.id, 'normalizer_key': 'text_upper',
'comparator_key': 'normalized_exact', 'default_weight': 50, 'max_automation': 'none',
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
}, actor_id=1)
assert created['order_field_id'] == field.id
assert created['source_adapter_key'] == 'order_field'
with pytest.raises(ValidationError) as exc_info:
service.save_definition({
'definition_code': 'unsafe', 'target_type': 'site', 'attribute_key': 'ship_to_address',
'order_field_id': field.id, 'normalizer_key': 'text_upper',
'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
}, actor_id=1)
assert exc_info.value.code == 'SHIPPING.IDENTITY_AUTOMATION_FORBIDDEN'
def test_definition_reference_blocks_order_field_retirement(app):
"""关键断言:被启用识别定义引用的 field_id 不能退役,避免字段改名/退役静默失效。"""
with app.app_context():
field = _published_header_field()
service.save_definition({
'definition_code': 'site_contact', 'target_type': 'site', 'attribute_key': 'contact',
'order_field_id': field.id, 'normalizer_key': 'name',
'comparator_key': 'normalized_exact', 'max_automation': 'none',
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
}, actor_id=1)
with pytest.raises(ConflictError) as exc_info:
order_schema_service.retire_field(field.id, actor_id=1)
assert exc_info.value.code == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
def test_published_rule_snapshot_also_blocks_order_field_retirement_after_definition_is_retired(app):
"""关键断言:历史发布规则快照仍引用字段时,退役字段必须被阻断。"""
with app.app_context():
field = _published_header_field()
definition = service.save_definition({
'definition_code': 'site_address_history', 'target_type': 'site', 'attribute_key': 'ship_to_address',
'order_field_id': field.id, 'normalizer_key': 'text_upper',
'comparator_key': 'normalized_exact', 'max_automation': 'none',
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
}, actor_id=1)
draft = service.create_rule_set({}, actor_id=1)
saved = service.save_rule_set(draft['id'], {
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
}, actor_id=1)
service.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
service.retire_definition(definition['id'], actor_id=1)
with pytest.raises(ConflictError) as exc_info:
order_schema_service.retire_field(field.id, actor_id=1)
assert exc_info.value.code == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
def test_rule_set_is_optimistically_locked_and_published_snapshot_is_immutable(app):
"""草稿以锁版本防覆盖,发布后冻结定义快照并自动退役上一版本。"""
with app.app_context():
definition = service.save_definition({
'definition_code': 'sender_email', 'target_type': 'customer', 'attribute_key': 'email',
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'default_weight': 100,
'max_automation': 'conditional', 'source_adapter_key': 'email_metadata',
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
}, actor_id=1)
draft = service.create_rule_set({}, actor_id=1)
saved = service.save_rule_set(draft['id'], {
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
}, actor_id=1)
published = service.publish_rule_set(
draft['id'], expected_lock_version=saved['lock_version'], actor_id=1,
)
assert published['status'] == 'published'
assert published['checksum']
with pytest.raises(ConflictError):
service.save_rule_set(draft['id'], {
'expected_lock_version': saved['lock_version'], 'definition_ids': [definition['id']],
}, actor_id=1)
def test_customer_evidence_is_unique_per_definition_and_normalized_value(app):
"""关键断言:同一客户相同定义的标准值只能保存一次,NULL 目标列不得绕过唯一性。"""
with app.app_context():
customer = ShippingCustomer(standard_name='Evidence Customer', short_code='EVC', status='active')
db.session.add(customer)
db.session.commit()
definition = service.save_definition({
'definition_code': 'customer_sender_email', 'target_type': 'customer', 'attribute_key': 'email',
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
'source_adapter_key': 'email_metadata',
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
}, actor_id=1)
# 阶段三后证据维护只能选择当前已发布规则集中的定义,避免录入运行期不消费的值。
draft = service.create_rule_set({}, actor_id=1)
saved = service.save_rule_set(draft['id'], {
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
}, actor_id=1)
service.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
service.create_evidence(
target_type='customer', target_id=customer.id,
data={'definition_id': definition['id'], 'raw_value': 'buyer@example.com', 'status': 'approved'}, actor_id=1,
)
with pytest.raises(ConflictError) as exc_info:
service.create_evidence(
target_type='customer', target_id=customer.id,
data={'definition_id': definition['id'], 'raw_value': 'BUYER@example.com', 'status': 'approved'}, actor_id=1,
)
assert exc_info.value.code == 'SHIPPING.IDENTITY_EVIDENCE_CONFLICT'
def test_identity_rule_admin_routes_are_registered(app):
"""关键断言:阶段一规则目录、规则集和新证据值均通过管理员受保护 API 暴露。"""
with app.app_context():
rules = {rule.rule for rule in app.url_map.iter_rules()}
assert '/api/admin/shipping-identity-rules/definitions' in rules
assert '/api/admin/shipping-identity-rules/rule-sets' in rules
assert '/api/admin/shipping-customers/<int:customer_id>/identity-evidences' in rules
def test_business_definition_owns_display_copy_and_service_derives_execution_settings(app):
"""管理员维护业务名称和说明;来源适配器而非前端白名单决定内部标准化与自动化上限。"""
with app.app_context():
definition = service.save_definition({
'display_name': '北美客户业务邮箱',
'description': '仅用于北美区域客户的发件人邮箱识别。',
'evidence_label': '北美客户业务邮箱',
'target_type': 'customer',
'source_adapter_key': 'email_metadata',
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
# 客户端传入的运行参数不能覆盖平台受控来源的安全边界。
'attribute_key': 'customer_name', 'normalizer_key': 'text_upper',
'max_automation': 'conditional',
}, actor_id=1)
# 关键断言:业务名称进入 API 返回和后续规则快照,实际匹配策略由来源能力决定。
assert definition['display_name'] == '北美客户业务邮箱'
assert definition['description'] == '仅用于北美区域客户的发件人邮箱识别。'
assert definition['evidence_label'] == '北美客户业务邮箱'
assert definition['attribute_key'] == 'email'
assert definition['normalizer_key'] == 'email'
assert definition['max_automation'] == 'conditional'
def test_definition_catalog_serializes_source_adapter_sets_as_stable_json_arrays(app):
"""来源目录中的内部集合必须转换为有序 JSON 数组,规则列表接口不能因目录加载而返回 500。"""
with app.app_context():
catalog = service.list_definitions()['catalog']
email_adapter = next(item for item in catalog['source_adapters'] if item['key'] == 'email_metadata')
# 关键断言:内部 set 不可泄漏到 API;固定排序也保证前端目录结果可预测。
assert email_adapter['selectors']['projections'] == ['domain', 'email']
assert json.loads(json.dumps(catalog)) == catalog
def test_email_and_template_definitions_are_explicit_business_configuration(app):
"""空库不自动补齐定义;管理员可按受控适配器创建邮箱和模板业务规则。"""
with app.app_context():
assert ShippingIdentityDefinition.query.count() == 0
email = service.save_definition({
'definition_code': 'apac_sender_email', 'target_type': 'customer', 'attribute_key': 'email',
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
'source_adapter_key': 'email_metadata',
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
}, actor_id=1)
template = service.save_definition({
'definition_code': 'apac_notice_template', 'target_type': 'customer', 'attribute_key': 'template_fingerprint',
'normalizer_key': 'text_upper', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
'source_adapter_key': 'document_template', 'source_selector': {'document': 'primary'},
}, actor_id=1)
assert email['source_adapter_key'] == 'email_metadata'
assert email['source_selector']['projection'] == 'email'
assert template['source_adapter_key'] == 'document_template'
assert ShippingIdentityDefinition.query.count() == 2
def test_source_adapter_rejects_arbitrary_paths_and_unsafe_automation(app):
"""来源选择器只能使用平台目录,订单字段和站点定义均不能借 API 绕过自动化红线。"""
with app.app_context():
with pytest.raises(ValidationError) as invalid_source:
service.save_definition({
'definition_code': 'unsafe_path', 'target_type': 'customer', 'attribute_key': 'email',
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
'source_adapter_key': 'email_metadata',
'source_selector': {'attribute': 'raw_llm_output_json', 'projection': 'email'},
}, actor_id=1)
assert invalid_source.value.code == 'SHIPPING.IDENTITY_DEFINITION_INVALID'
with pytest.raises(ValidationError) as site_automation:
service.save_definition({
'definition_code': 'site_template', 'target_type': 'site', 'attribute_key': 'ship_to_name',
'normalizer_key': 'name', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
'source_adapter_key': 'document_template', 'source_selector': {'document': 'primary'},
}, actor_id=1)
assert site_automation.value.code == 'SHIPPING.IDENTITY_DEFINITION_INVALID'