test(shipping): 更新订单复核库存与通知流程测试
This commit is contained in:
1 parent
8ec028e6a3
commit
265a6e179a
168 files changed
+9420
-4613
No files matched your search
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_auto_resolution.py
|
||||
|
||||
用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。
|
||||
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。
|
||||
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
|
||||
用途:验证受控 OT 自动客户确认、降级开关、强规则歧义和规则快照防篡改。
|
||||
依赖:客户主数据/证据、Candidate 影子结果、ShippingOrderTask、customer_auto_resolution。
|
||||
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动确认,且不创建 Notice。
|
||||
"""
|
||||
|
||||
from copy import deepcopy
|
||||
@@ -11,7 +11,6 @@ from copy import deepcopy
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCustomer,
|
||||
@@ -28,19 +27,17 @@ from app.models import (
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
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]:
|
||||
@@ -123,10 +120,9 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
)
|
||||
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",
|
||||
task = ShippingOrderTask(
|
||||
task_no=f"OT-AUTO-{user.id}", user_id=user.id,
|
||||
candidate_id=candidate.id, source_type="eml",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -201,8 +197,13 @@ def _allow_auto_confirmation(app) -> None:
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
|
||||
|
||||
|
||||
def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
"""开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。"""
|
||||
def _assert_ot_did_not_create_notice(task: ShippingOrderTask) -> None:
|
||||
"""断言 OT 自动确认只写客户识别结果,不提前创建或编号正式 Notice。"""
|
||||
assert ShippingNotice.query.filter_by(order_task_id=task.id).count() == 0
|
||||
|
||||
|
||||
def test_unique_approved_strong_rule_auto_confirms_at_ot_without_creating_notice(app):
|
||||
"""开关启用且唯一强规则命中时,OT 自动确认但不创建或编号 Notice。"""
|
||||
with app.app_context():
|
||||
_allow_auto_confirmation(app)
|
||||
customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
@@ -212,22 +213,15 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
|
||||
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']
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
assert shadow.status == "confirmed"
|
||||
assert shadow.confirmation_method == "auto_rule"
|
||||
assert shadow.confirmed_customer_id == customer.id
|
||||
assert shadow.evidence_json[0]['definition_id']
|
||||
metrics = get_auto_resolution_metrics()
|
||||
assert result['business_no'] is None
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
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):
|
||||
@@ -238,13 +232,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
|
||||
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
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
_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
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
|
||||
@@ -258,8 +252,8 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
|
||||
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
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
@@ -275,10 +269,8 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
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
|
||||
persisted_task = db.session.get(ShippingOrderTask, task_id)
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=persisted_task.candidate_id).one().status == "unique_candidate"
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0
|
||||
|
||||
|
||||
@@ -295,8 +287,8 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic
|
||||
|
||||
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
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_business_evidence_never_auto_confirms(app):
|
||||
@@ -315,7 +307,7 @@ def test_business_evidence_never_auto_confirms(app):
|
||||
status='approved', auto_match_allowed=True,
|
||||
))
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.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'])
|
||||
@@ -336,7 +328,7 @@ def test_business_evidence_never_auto_confirms(app):
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
|
||||
assert result['status'] == 'rule_snapshot_missing'
|
||||
assert task.customer_resolution_status == 'pending'
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate'
|
||||
|
||||
|
||||
def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
|
||||
@@ -347,7 +339,7 @@ def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
|
||||
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 = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
shadow.resolution_context_json = {}
|
||||
db.session.commit()
|
||||
missing = resolve_auto_customer_from_shadow(task)
|
||||
@@ -361,14 +353,14 @@ def test_tampered_shadow_value_or_schema_anchor_never_auto_confirms(app):
|
||||
_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()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.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'
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate'
|
||||
|
||||
shadow.evidence_json = []
|
||||
context = deepcopy(shadow.resolution_context_json)
|
||||
@@ -390,7 +382,7 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
|
||||
db.session.add(truth)
|
||||
db.session.flush()
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
shadow.manual_customer_id = truth.id
|
||||
db.session.commit()
|
||||
|
||||
@@ -400,79 +392,81 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
|
||||
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
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app):
|
||||
"""客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。"""
|
||||
def _rebind_shadow_to_new_schema_version(shadow, *, new_version) -> None:
|
||||
"""把影子记录、证据与 Extraction 重锚到新 Schema 版本,模拟 Schema 重发布后重新解析。"""
|
||||
shadow.order_schema_version_id = new_version.id
|
||||
# JSON 列需整体重赋值才能被 SQLAlchemy 追踪变更,不能只在嵌套 dict 上就地修改。
|
||||
evidence = deepcopy(shadow.evidence_json)
|
||||
evidence[0]['source']['order_schema_version_id'] = new_version.id
|
||||
shadow.evidence_json = evidence
|
||||
extraction = db.session.get(
|
||||
ShippingOrderExtraction, evidence[0]['source']['extraction_id'],
|
||||
)
|
||||
extraction.schema_version_id = new_version.id
|
||||
|
||||
|
||||
def test_schema_republish_with_same_semantics_still_auto_confirms(app):
|
||||
"""Schema 重发布造成版本 id 错位、但字段语义(code/type/normalizer)未变时,自动确认仍放行。"""
|
||||
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])
|
||||
_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.candidate_id).one()
|
||||
|
||||
old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
|
||||
old_version.status = 'retired'
|
||||
new_version = ShippingOrderSchemaVersion(
|
||||
schema_id=old_version.schema_id, version=old_version.version + 1, status='published',
|
||||
definition_json={'fields': [{
|
||||
'field_id': old_version.definition_json['fields'][0]['field_id'],
|
||||
'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim',
|
||||
}]},
|
||||
checksum='f' * 64,
|
||||
)
|
||||
db.session.add(new_version)
|
||||
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)
|
||||
_rebind_shadow_to_new_schema_version(shadow, new_version=new_version)
|
||||
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,
|
||||
)
|
||||
result = resolve_auto_customer_from_shadow(task)
|
||||
|
||||
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
|
||||
assert result['status'] == 'unique_strong_match'
|
||||
assert result['customer_id'] is not None
|
||||
|
||||
|
||||
def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(app):
|
||||
"""纠错必须有原因,且已对外上传业务单需先走外部作废流程。"""
|
||||
def test_schema_republish_changes_semantics_never_auto_confirms(app):
|
||||
"""Schema 重发布且字段语义变化(normalizer 变更)时,仍必须 fail-closed 到人工复核。"""
|
||||
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",
|
||||
_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.candidate_id).one()
|
||||
|
||||
old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
|
||||
old_version.status = 'retired'
|
||||
new_version = ShippingOrderSchemaVersion(
|
||||
schema_id=old_version.schema_id, version=old_version.version + 1, status='published',
|
||||
definition_json={'fields': [{
|
||||
'field_id': old_version.definition_json['fields'][0]['field_id'],
|
||||
'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True,
|
||||
'normalizer_key': 'uppercase_trim', # 语义变化:normalizer 已变更,不得放行。
|
||||
}]},
|
||||
checksum='e' * 64,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.add(new_version)
|
||||
db.session.flush()
|
||||
_rebind_shadow_to_new_schema_version(shadow, new_version=new_version)
|
||||
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()
|
||||
result = resolve_auto_customer_from_shadow(task)
|
||||
|
||||
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
|
||||
assert result['status'] == 'rule_snapshot_missing'
|
||||
assert result['customer_id'] is None
|
||||
Reference in new issue
Block a user