Files
syops/backend/tests/test_shipping_customer_auto_resolution.py
T
hugo 1e5aedb9ed feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
2026-08-26 02:47:07 +08:00

479 lines
23 KiB
Python

"""
backend/tests/test_shipping_customer_auto_resolution.py
用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
"""
from copy import deepcopy
import pytest
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
FileAsset,
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingIdentityDefinition,
ShippingIdentityEvidence,
ShippingIdentityRuleSet,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingNotice,
ShippingTaskEvent,
User,
)
from app.services.shipping_notice.customer_auto_resolution import (
AUTO_RESOLUTION_VERSION,
correct_numbered_task_customer,
get_auto_resolution_metrics,
resolve_auto_customer_from_shadow,
try_auto_confirm_task_customer,
)
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
from app.services.shipping_notice.query_service import get_task_by_ref
def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]:
"""创建管理员配置的识别定义及冻结发布规则集快照(使用标准 bill_to_customer)。"""
from app.services.shipping_notice import field_asset_service
field_asset_service.ensure_standard_assets_seeded()
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(field_code='bill_to_customer').one()
field_config = {
'field_id': field.id, 'field_code': field.field_code, 'display_name': 'Bill To Customer',
'scope': 'header', 'value_type': 'string', 'enabled': True,
'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim',
}
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', context_field_id=field.id,
default_weight=100, max_automation='conditional', status='active',
)
db.session.add(definition)
db.session.flush()
rule_set = ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
if rule_set is None:
rule_set = ShippingIdentityRuleSet(
version=1, status='published', checksum='a' * 64,
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', 'context_field_id': field.id, 'max_automation': 'conditional',
'field_config': field_config,
}]},
)
db.session.add(rule_set)
db.session.flush()
return definition, rule_set
def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
"""创建带邮件证据的 Candidate、影子记录和待确认任务。"""
user = User(username=f"auto-user-{db.session.query(User).count()}", email="auto@example.com", role="user")
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no=f"AUTO-ASSET-{user.id}", owner_user_id=user.id, original_filename="notice.eml",
storage_provider="minio", storage_bucket="test", storage_key=f"auto-{user.id}",
content_hash=f"{user.id:064d}", file_size=1, upload_status="uploaded", lifecycle_status="temporary",
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no=f"AUTO-INTAKE-{user.id}", asset_id=asset.id, user_id=user.id,
parser_version="v6", parse_status="parsed", structured_result_json={"email": {"from": sender}},
)
db.session.add(intake)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type="attachment", attachment_key="file",
filename="notice.pdf", classification="order_notice", parse_status="parsed",
)
db.session.add(document)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no=f"AUTO-CAND-{user.id}", intake_id=intake.id, primary_document_id=document.id,
candidate_key="document:1", validation_status="ready", selected=True,
structured_result_json={"business_summary": {"customer_name": "unstable name"}},
)
db.session.add(candidate)
db.session.flush()
task = ShippingNotice(
task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id,
user_id=user.id, source_type="email_attachment",
customer_resolution_status="pending",
)
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": "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', '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()
return task
def _customer_with_identifier(*, code: str, value: str, allowed: bool = True, status: str = "approved"):
"""创建客户及冻结邮箱定义对应的可审核证据。"""
customer = ShippingCustomer(standard_name=f"客户 {code}", short_code=code, status="active")
db.session.add(customer)
db.session.flush()
definition, _ = _auto_definition()
db.session.add(ShippingIdentityEvidence(
definition_id=definition.id, customer_id=customer.id, raw_value=value, normalized_value=value,
status=status, auto_match_allowed=allowed,
))
db.session.flush()
return customer
def _allow_auto_confirmation(app) -> None:
"""为自动确认专项用例显式放宽门禁,不改变生产默认安全阈值。"""
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 0
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
"""开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。"""
with app.app_context():
_allow_auto_confirmation(app)
customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
task = _seed_candidate_task()
result = try_auto_confirm_task_customer(task)
assert result["status"] == "auto_confirmed"
assert result["rule_version"] == AUTO_RESOLUTION_VERSION
assert task.customer_resolution_status == "confirmed"
assert task.customer_resolution_method == "auto_rule"
assert task.customer_id == customer.id
assert task.business_no.startswith("WYC")
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1
event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one()
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"
assert metrics["recent_events"][0]["task_no"] == task.task_no
def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
"""总开关关闭或证据未审核/未授权时保持 pending,不占用业务流水。"""
with app.app_context():
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com", allowed=False)
task = _seed_candidate_task()
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False
disabled = try_auto_confirm_task_customer(task)
assert disabled["status"] == "disabled"
assert task.business_no is None
_allow_auto_confirmation(app)
unmatched = try_auto_confirm_task_customer(task)
assert unmatched["status"] == "unmatched"
assert task.customer_resolution_status == "pending"
assert task.business_no is None
def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
"""同一强证据映射多个客户时必须降级人工确认。"""
with app.app_context():
_allow_auto_confirmation(app)
_customer_with_identifier(code="AAA", value="buyer@wyc.example.com")
_customer_with_identifier(code="BBB", value="buyer@wyc.example.com")
task = _seed_candidate_task()
result = try_auto_confirm_task_customer(task)
assert result["status"] == "ambiguous"
assert len(result["candidate_customer_ids"]) == 2
assert task.customer_resolution_status == "pending"
assert task.business_no is None
def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
"""批次编排失败时,自动确认、编号和审计必须随外层事务整体回滚。"""
with app.app_context():
_allow_auto_confirmation(app)
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
task = _seed_candidate_task()
task_id = task.id
result = try_auto_confirm_task_customer(task)
assert result["status"] == "auto_confirmed"
db.session.rollback()
db.session.expire_all()
persisted_task = db.session.get(ShippingNotice, task_id)
assert persisted_task.customer_resolution_status == "pending"
assert persisted_task.customer_id is None
assert persisted_task.business_no is None
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0
def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insufficient(app):
"""总开关开启但没有足够人工真值时,必须保持人工客户复核和未编号状态。"""
with app.app_context():
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 1
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
task = _seed_candidate_task()
result = try_auto_confirm_task_customer(task)
assert result["status"] == "insufficient_labeled_samples"
assert result["quality_gate"]["labeled_sample_count"] == 0
assert task.customer_resolution_status == "pending"
assert task.business_no is None
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', context_field_id=_auto_definition()[0].context_field_id,
default_weight=100, max_automation='none', status='active',
)
db.session.add_all([customer, definition])
db.session.flush()
db.session.add(ShippingIdentityEvidence(
definition_id=definition.id, customer_id=customer.id, raw_value='ACME', normalized_value='ACME',
status='approved', auto_match_allowed=True,
))
task = _seed_candidate_task()
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
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'] == 'rule_snapshot_missing'
assert task.customer_resolution_status == 'pending'
def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
"""公共域名和无法验证的冻结规则快照均不可触发自动绑定。"""
with app.app_context():
_allow_auto_confirmation(app)
_customer_with_identifier(code='PUB', value='buyer@gmail.com')
task = _seed_candidate_task(sender='buyer@gmail.com')
assert try_auto_confirm_task_customer(task)['status'] == 'unmatched'
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
shadow.resolution_context_json = {}
db.session.commit()
missing = resolve_auto_customer_from_shadow(task)
assert missing['status'] == 'rule_snapshot_missing'
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():
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 1
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
matched = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
truth = ShippingCustomer(standard_name="真实客户", short_code="TRU", status="active")
db.session.add(truth)
db.session.flush()
task = _seed_candidate_task()
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
shadow.manual_customer_id = truth.id
db.session.commit()
result = try_auto_confirm_task_customer(task)
assert matched.id != truth.id
assert result["status"] == "insufficient_accuracy"
assert result["quality_gate"]["labeled_sample_count"] == 1
assert result["quality_gate"]["accuracy"] == 0
assert task.customer_resolution_status == "pending"
assert task.business_no is None
def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app):
"""客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。"""
with app.app_context():
wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active")
correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active")
db.session.add_all([wrong, correct])
db.session.flush()
first = ShippingNotice(
task_no="SN-CORRECTION-V1", document_version=1,
source_type="manual", upload_status="pending", customer_resolution_status="pending", inventory_source_code="DSV",
inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}],
match_status="fulfillable", line_results_json=[{"sku": "A"}],
export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx",
)
db.session.add(first)
db.session.commit()
confirm_task_customer(first, customer_id=wrong.id, actor_id=None)
old_business_no = first.business_no
result = correct_numbered_task_customer(
first,
customer_id=correct.id,
reason="自动识别客户错误",
actor_id=None,
)
replacement = db.session.get(ShippingNotice, result["new_notice_id"])
assert first.business_no == old_business_no
assert first.lifecycle_status == "voided"
assert replacement.supersedes_task_id == first.id
assert replacement.business_no.startswith("NEW")
assert replacement.business_no != old_business_no
assert replacement.customer_resolution_method == "admin_correction"
assert replacement.inventory_source_status is None
assert replacement.inventory_lines_json is None
assert replacement.export_file_path is None
assert replacement.source_type == "manual"
assert get_task_by_ref(old_business_no).id == first.id
assert get_task_by_ref(replacement.business_no).id == replacement.id
assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2
metrics = get_auto_resolution_metrics()
assert metrics["corrected_task_count"] == 2
assert metrics["recent_events"][0]["detail"]["old_business_no"] == old_business_no
def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(app):
"""纠错必须有原因,且已对外上传业务单需先走外部作废流程。"""
with app.app_context():
wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active")
correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active")
db.session.add_all([wrong, correct])
db.session.flush()
task = ShippingNotice(
task_no="SN-CORRECTION-BLOCK",
source_type="manual", customer_resolution_status="pending",
)
db.session.add(task)
db.session.commit()
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
correct_numbered_task_customer(task, customer_id=correct.id, reason="", actor_id=None)
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED"
db.session.rollback()
task.upload_status = "uploaded"
db.session.commit()
with pytest.raises(ConflictError) as exc_info:
correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None)
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED"
db.session.rollback()
assert db.session.query(ShippingNotice).count() == 1