feat(shipping-notice): 添加订单抽取功能,支持异步运行和管理,优化相关数据模型和处理逻辑
This commit is contained in:
1 parent
34d489a2d1
commit
ce26d6d0c4
144 files changed
+12241
-4233
No files matched your search
@@ -6,6 +6,8 @@ backend/tests/test_shipping_customer_auto_resolution.py
|
||||
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
|
||||
"""
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
@@ -21,6 +23,12 @@ from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
User,
|
||||
@@ -38,12 +46,37 @@ from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]:
|
||||
"""创建管理员配置的邮箱定义及冻结发布规则集快照。"""
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField.query.filter_by(schema_id=schema.id, field_code='sender_email').one_or_none()
|
||||
if field is None:
|
||||
field = ShippingOrderField(
|
||||
schema_id=schema.id, field_code='sender_email', scope='header', value_type='string',
|
||||
field_category='general_context', collection_mode='deterministic_context',
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
field_config = {
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': 'Sender email',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim',
|
||||
'context_source': {'provider_key': 'mail_header', 'option_key': 'from_email'},
|
||||
}
|
||||
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if schema_version is None:
|
||||
schema_version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': [field_config]},
|
||||
checksum='1' * 64,
|
||||
)
|
||||
db.session.add(schema_version)
|
||||
db.session.flush()
|
||||
definition = ShippingIdentityDefinition.query.filter_by(definition_code='test_mail_sender_email').one_or_none()
|
||||
if definition is None:
|
||||
definition = ShippingIdentityDefinition(
|
||||
definition_code='test_mail_sender_email', target_type='customer', source_adapter_key='email_metadata',
|
||||
source_selector_json={'attribute': 'email.from', 'projection': 'email'},
|
||||
attribute_key='email', normalizer_key='email', comparator_key='normalized_exact',
|
||||
definition_code='test_mail_sender_email', target_type='customer', context_field_id=field.id,
|
||||
default_weight=100, max_automation='conditional', status='active',
|
||||
)
|
||||
db.session.add(definition)
|
||||
@@ -52,9 +85,12 @@ def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRule
|
||||
if rule_set is None:
|
||||
rule_set = ShippingIdentityRuleSet(
|
||||
version=1, status='published', checksum='a' * 64,
|
||||
definition_json={'definitions': [{
|
||||
definition_json={'order_schema': {
|
||||
'id': schema_version.id, 'version': schema_version.version, 'checksum': schema_version.checksum,
|
||||
}, 'definitions': [{
|
||||
'id': definition.id, 'definition_code': definition.definition_code,
|
||||
'target_type': 'customer', 'attribute_key': 'email', 'max_automation': 'conditional',
|
||||
'target_type': 'customer', 'context_field_id': field.id, 'max_automation': 'conditional',
|
||||
'field_config': field_config,
|
||||
}]},
|
||||
)
|
||||
db.session.add(rule_set)
|
||||
@@ -102,23 +138,49 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
definition, rule_set = _auto_definition()
|
||||
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
extraction = ShippingOrderExtraction(
|
||||
intake_id=intake.id, schema_version_id=schema_version.id, input_snapshot_hash='a' * 64,
|
||||
status='accepted', raw_llm_output_json={},
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, field_id=definition.context_field_id,
|
||||
decision_status='accepted', resolved_value_json=sender,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
field_value = ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, field_id=definition.context_field_id, decision_id=decision.id,
|
||||
value_text=sender, value_json=sender,
|
||||
)
|
||||
db.session.add(field_value)
|
||||
db.session.flush()
|
||||
candidate.order_extraction_id = extraction.id
|
||||
shadow = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=intake.id, resolution_version="shadow-v1",
|
||||
identity_rule_set_id=rule_set.id, identity_rule_set_version=rule_set.version,
|
||||
identity_rule_set_checksum=rule_set.checksum,
|
||||
order_schema_version_id=schema_version.id,
|
||||
status="unique_candidate",
|
||||
evidence_json=[
|
||||
{"definition_id": definition.id, "definition_code": definition.definition_code,
|
||||
"raw_value": sender, "normalized_value": sender, "source": {"kind": "mail_metadata"}},
|
||||
"raw_value": sender, "normalized_value": sender, "source": {
|
||||
"kind": "field_value", "context_field_id": definition.context_field_id,
|
||||
"field_value_id": field_value.id, "decision_id": decision.id,
|
||||
"extraction_id": extraction.id, "order_schema_version_id": schema_version.id,
|
||||
}},
|
||||
],
|
||||
candidate_matches_json=[], resolution_context_json={'rule_set': {
|
||||
'id': rule_set.id, 'version': rule_set.version, 'checksum': rule_set.checksum,
|
||||
'order_schema': rule_set.definition_json['order_schema'],
|
||||
'definitions': [{
|
||||
'id': definition.id, 'definition_code': definition.definition_code,
|
||||
'target_type': 'customer', 'attribute_key': 'email', 'max_automation': 'conditional',
|
||||
'source_adapter_key': 'email_metadata',
|
||||
'target_type': 'customer', 'context_field_id': definition.context_field_id,
|
||||
'max_automation': 'conditional', 'field_config': rule_set.definition_json['definitions'][0]['field_config'],
|
||||
}],
|
||||
}},
|
||||
}, 'order_extraction_id': extraction.id},
|
||||
)
|
||||
db.session.add(shadow)
|
||||
db.session.commit()
|
||||
@@ -166,6 +228,9 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
assert event.detail_json['rule_set']['checksum']
|
||||
assert event.detail_json['evidence'][0]['definition_id']
|
||||
assert event.detail_json['evidence'][0]['evidence_id']
|
||||
source = event.detail_json['evidence'][0]['source']
|
||||
assert source['field_value_id'] and source['decision_id'] and source['extraction_id']
|
||||
assert source['order_schema_version_id'] == event.detail_json['order_schema_version_id']
|
||||
metrics = get_auto_resolution_metrics()
|
||||
assert metrics["auto_confirmed_count"] == 1
|
||||
assert metrics["recent_events"][0]["event_type"] == "customer_auto_confirmed"
|
||||
@@ -244,14 +309,12 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic
|
||||
|
||||
|
||||
def test_business_evidence_never_auto_confirms(app):
|
||||
"""订单业务字段即使被人为授权,也受定义上限约束而不能自动绑定客户。"""
|
||||
"""规则快照被篡改为业务字段上限时必须拒绝该快照,不能自动绑定客户。"""
|
||||
with app.app_context():
|
||||
_allow_auto_confirmation(app)
|
||||
customer = ShippingCustomer(standard_name='业务字段客户', short_code='BIZ', status='active')
|
||||
definition = ShippingIdentityDefinition(
|
||||
definition_code='test_business_contact', target_type='customer', source_adapter_key='order_field',
|
||||
source_selector_json={'order_field_id': 'test-field'},
|
||||
attribute_key='customer_code', normalizer_key='text_upper', comparator_key='normalized_exact',
|
||||
definition_code='test_business_contact', target_type='customer', context_field_id=_auto_definition()[0].context_field_id,
|
||||
default_weight=100, max_automation='none', status='active',
|
||||
)
|
||||
db.session.add_all([customer, definition])
|
||||
@@ -262,18 +325,26 @@ def test_business_evidence_never_auto_confirms(app):
|
||||
))
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow.evidence_json = [{'definition_id': definition.id, 'normalized_value': 'ACME'}]
|
||||
shadow.resolution_context_json = {'rule_set': {
|
||||
'id': shadow.identity_rule_set_id, 'version': shadow.identity_rule_set_version,
|
||||
'checksum': shadow.identity_rule_set_checksum,
|
||||
'definitions': [{'id': definition.id, 'target_type': 'customer', 'attribute_key': 'customer_code',
|
||||
'max_automation': 'none', 'source_adapter_key': 'order_field'}],
|
||||
}}
|
||||
original_source = shadow.evidence_json[0]['source']
|
||||
field_value = db.session.get(ShippingOrderFieldValue, original_source['field_value_id'])
|
||||
decision = db.session.get(ShippingOrderFieldDecision, original_source['decision_id'])
|
||||
field_value.value_text = 'ACME'
|
||||
field_value.value_json = 'ACME'
|
||||
decision.resolved_value_json = 'ACME'
|
||||
shadow.evidence_json = [{
|
||||
'definition_id': definition.id, 'normalized_value': 'ACME', 'source': original_source,
|
||||
}]
|
||||
context = deepcopy(shadow.resolution_context_json)
|
||||
context['rule_set']['definitions'] = [{
|
||||
'id': definition.id, 'target_type': 'customer',
|
||||
'context_field_id': definition.context_field_id, 'max_automation': 'none',
|
||||
}]
|
||||
shadow.resolution_context_json = context
|
||||
db.session.commit()
|
||||
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
|
||||
assert result['status'] == 'unmatched'
|
||||
assert result['status'] == 'rule_snapshot_missing'
|
||||
assert task.customer_resolution_status == 'pending'
|
||||
|
||||
|
||||
@@ -293,6 +364,30 @@ def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
|
||||
assert missing['customer_id'] is None
|
||||
|
||||
|
||||
def test_tampered_shadow_value_or_schema_anchor_never_auto_confirms(app):
|
||||
"""影子值或 Schema 锚点被篡改时必须回到人工复核,不能仅信任 JSON 中的追溯主键。"""
|
||||
with app.app_context():
|
||||
_allow_auto_confirmation(app)
|
||||
_customer_with_identifier(code='WYC', value='buyer@wyc.example.com')
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
evidence = deepcopy(shadow.evidence_json)
|
||||
evidence[0]['normalized_value'] = 'attacker@example.com'
|
||||
shadow.evidence_json = evidence
|
||||
db.session.commit()
|
||||
|
||||
assert try_auto_confirm_task_customer(task)['status'] == 'unmatched'
|
||||
assert task.customer_resolution_status == 'pending'
|
||||
|
||||
shadow.evidence_json = []
|
||||
context = deepcopy(shadow.resolution_context_json)
|
||||
context['rule_set']['order_schema']['checksum'] = 'f' * 64
|
||||
shadow.resolution_context_json = context
|
||||
db.session.commit()
|
||||
|
||||
assert resolve_auto_customer_from_shadow(task)['status'] == 'rule_snapshot_missing'
|
||||
|
||||
|
||||
def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app):
|
||||
"""有足够样本但强规则与人工真值不一致时,自动确认必须安全降级。"""
|
||||
with app.app_context():
|
||||
|
||||
Reference in new issue
Block a user