""" backend/tests/test_shipping_customer_auto_resolution.py 用途:验证受控自动客户确认、降级开关、强规则歧义和历史客户回填。 依赖:客户主数据/证据、Candidate 影子结果、ShippingTask/Case、customer_auto_resolution。 逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。 """ import pytest from app import db from app.core.errors import ConflictError, ValidationError from app.models import ( FileAsset, ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerShadowResolution, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, ShippingTask, ShippingTaskEvent, User, ) from app.services.shipping_notice.customer_auto_resolution import ( AUTO_RESOLUTION_VERSION, backfill_historical_task_customer, correct_numbered_task_customer, get_auto_resolution_metrics, 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 _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 = ShippingNoticeIntake( 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 = ShippingNoticeDocument( 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 = ShippingNoticeCandidate( 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"}}, ) case = ShippingCase(case_no=f"AUTO-CASE-{user.id}", numbering_status="pending") db.session.add_all([candidate, case]) db.session.flush() task = ShippingTask( task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id, user_id=user.id, source_type="email_attachment", process_status="parsed", customer_resolution_status="pending", ) db.session.add(task) db.session.flush() shadow = ShippingCustomerShadowResolution( candidate_id=candidate.id, intake_id=intake.id, resolution_version="shadow-v1", status="unique_candidate", evidence_json=[ {"type": "email", "raw_value": sender, "normalized_value": sender}, {"type": "domain", "raw_value": sender.split("@")[-1], "normalized_value": sender.split("@")[-1]}, ], candidate_matches_json=[], ) 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() db.session.add(ShippingCustomerIdentifier( customer_id=customer.id, identifier_type="email", raw_value=value, normalized_value=value, status=status, source="manual", auto_match_allowed=allowed, )) db.session.flush() return customer def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): """开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。""" with app.app_context(): app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True 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.shipping_case.customer_id == customer.id assert task.shipping_case.business_no.startswith("WYC") assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1 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.shipping_case.business_no is None app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True unmatched = try_auto_confirm_task_customer(task) assert unmatched["status"] == "unmatched" assert task.customer_resolution_status == "pending" assert task.shipping_case.business_no is None def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): """同一强证据映射多个客户时必须降级人工确认。""" with app.app_context(): app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True _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.shipping_case.business_no is None def test_historical_backfill_binds_customer_without_numbering(app): """历史任务回填客户后业务号仍为空,不倒占当日流水。""" with app.app_context(): customer = ShippingCustomer(standard_name="历史客户", short_code="HIS", status="active") task = ShippingTask(task_no="SN-20200101-HISTORY", source_type="manual", process_status="closed") db.session.add_all([customer, task]) db.session.commit() result = backfill_historical_task_customer(task, customer_id=customer.id, actor_id=None) assert result["business_no"] is None assert task.shipping_case.customer_id == customer.id assert task.shipping_case.numbering_status == "historical_unnumbered" assert task.shipping_case.business_no is None assert task.customer_resolution_method == "historical_backfill" metrics = get_auto_resolution_metrics() assert metrics["historical_backfilled_count"] == 1 assert metrics["recent_events"][0]["event_type"] == "customer_historical_backfilled" def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): """批次编排失败时,自动确认、编号和审计必须随外层事务整体回滚。""" with app.app_context(): app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() task_id = task.id case_id = task.shipping_case_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(ShippingTask, task_id) persisted_case = db.session.get(ShippingCase, case_id) assert persisted_task.customer_resolution_status == "pending" assert persisted_case.customer_id is None assert persisted_case.business_no is None assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0 def test_numbered_customer_correction_voids_old_number_and_replaces_case(app): """客户误确认纠错必须保留原号作废,生成新客户编号并让原号查询跟随替代单。""" with app.app_context(): wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active") correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active") case = ShippingCase(case_no="CASE-CORRECTION", numbering_status="pending") db.session.add_all([wrong, correct, case]) db.session.flush() first = ShippingTask( task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1, source_type="manual", process_status="parsed", customer_resolution_status="pending", ) db.session.add(first) db.session.flush() latest = ShippingTask( task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2, supersedes_task_id=first.id, source_type="manual", process_status="waiting_upload", 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(latest) db.session.commit() confirm_task_customer(first, customer_id=wrong.id, actor_id=None) old_case_id = case.id old_business_no = case.business_no result = correct_numbered_task_customer( latest, customer_id=correct.id, reason="自动识别客户错误", actor_id=None, ) old_case = db.session.get(ShippingCase, old_case_id) replacement = db.session.get(ShippingCase, result["new_case_id"]) assert old_case.business_no == old_business_no assert old_case.status == "voided" assert old_case.numbering_status == "voided" assert replacement.replaces_case_id == old_case.id assert replacement.business_no.startswith("NEW") assert replacement.business_no != old_business_no assert latest.shipping_case_id == replacement.id assert first.shipping_case_id == replacement.id assert latest.customer_resolution_method == "admin_correction" assert latest.inventory_source_status is None assert latest.inventory_lines_json is None assert latest.export_file_path is None assert latest.process_status == "parsed" assert get_task_by_ref(old_business_no).id == latest.id assert get_task_by_ref(replacement.business_no).id == latest.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") case = ShippingCase(case_no="CASE-CORRECTION-BLOCK", numbering_status="pending") db.session.add_all([wrong, correct, case]) db.session.flush() task = ShippingTask( task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id, source_type="manual", process_status="parsed", 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.process_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(ShippingCase).count() == 1