""" backend/tests/test_shipping_customer_identity_gate.py 用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。 依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。 逻辑:构造 pending 或缺失业务单的任务逐入口断言无副作用;确认后验证业务单/修订同步。 """ from __future__ import annotations from io import BytesIO import pytest from werkzeug.datastructures import FileStorage from app import db from app.core.errors import AppError from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent, User from app.services.shipping_notice.customer_identity_gate import ( assert_customer_identity_gate, confirm_task_customer, customer_identity_is_confirmed, ) from app.services.shipping_notice.fulfillment_workflow import generate_excel, match_inventory, upload_to_freight from app.services.shipping_notice.inventory_rpa_workflow import ( _validate_rpa_callback_gate, ensure_inventory_via_rpa, ) from app.services.shipping_notice.inventory_workflow import ensure_inventory, upload_inventory_file from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.task_workflow import retry_task def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]: """创建待确认任务、启用客户和任务用户。""" sequence = db.session.query(User).count() user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user') short_code = f'G{chr(65 + (sequence // 26) % 26)}{chr(65 + sequence % 26)}' customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active') db.session.add_all([user, customer]) db.session.flush() case = ShippingCase(case_no=f'CASE-GATE-{user.id}') if with_case else None if case: db.session.add(case) db.session.flush() task = ShippingNotice( task_no=f'SN-GATE-{user.id}', user_id=user.id, shipping_case_id=case.id if case else None, customer_resolution_status='pending' if case else None, lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}], inventory_source_status='user_confirmed', inventory_source_code='DSV', ) db.session.add(task) db.session.commit() return task, customer, user def _assert_customer_gate_response(result: dict) -> None: """断言 Tool 入口返回统一客户检查点。""" assert result['status'] == 'needs_human' assert result['checkpoint'] == 'customer_review' assert 'human_options' not in result def test_pending_customer_blocks_every_downstream_entry(app): """未确认客户时所有库存与履约公共入口都必须在副作用前停止。""" with app.app_context(): task, _customer, _user = _seed_task() app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True results = [ auto_progress({'task_id': task.task_no}), ensure_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}), upload_inventory_file( task.task_no, FileStorage(stream=BytesIO(b'not-used'), filename='inventory.xlsx'), ), ensure_inventory_via_rpa(task, mode='auto'), match_inventory({'task_id': task.task_no}), generate_excel({'task_id': task.task_no}), ] for result in results: _assert_customer_gate_response(result) # upload_to_freight(manual_confirm) 仍受客户门禁约束(不再范围外硬拒绝)。 upload = upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}) _assert_customer_gate_response(upload) callback = _validate_rpa_callback_gate(task) assert callback is not None assert callback['status'] == 'failed' db.session.refresh(task) assert task.inventory_lines_json is None assert task.export_file_path is None assert task.upload_status is None def test_pending_customer_blocks_retry_before_clearing_review_state(app): """重试入口必须保留 customer_review,不能先清除人工检查点再异步阻断。""" with app.app_context(): task, _customer, _user = _seed_task() task.pending_human_reason = 'customer_unconfirmed' task.error_message = '标准客户尚未确认' db.session.commit() result = retry_task({'task_id': task.task_no}) _assert_customer_gate_response(result) db.session.refresh(task) assert task.pending_human_reason == 'customer_unconfirmed' assert task.error_message == '标准客户尚未确认' def test_confirm_customer_syncs_revision_chain_and_assigns_number(app): """客户确认同步同业务单全部任务,并在同事务生成正式业务号。""" with app.app_context(): task, customer, user = _seed_task() revision = ShippingNotice( task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id, supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending', ) db.session.add(revision) db.session.commit() updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) db.session.refresh(revision) case = db.session.get(ShippingCase, task.shipping_case_id) assert updated.customer_resolution_status == 'confirmed' assert revision.customer_resolution_status == 'confirmed' assert updated.customer_resolution_method == 'manual' assert case.customer_id == customer.id assert case.customer_name_snapshot == customer.standard_name assert case.customer_short_code_snapshot == customer.short_code assert case.business_no.startswith(customer.short_code) assert len(case.business_no) == len(customer.short_code) + 8 assert case.sequence_value == 1 assert case.numbering_status == 'assigned' assert customer_identity_is_confirmed(updated) is True assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 2 assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 2 def test_inactive_customer_reblocks_and_missing_case_is_blocked(app): """已确认客户停用后重新阻断;缺少业务单的任务也必须阻断。""" with app.app_context(): task, customer, user = _seed_task() confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) customer.status = 'inactive' db.session.commit() with pytest.raises(AppError) as exc_info: assert_customer_identity_gate(task, operation='match_inventory') assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' missing_case, _other_customer, _other_user = _seed_task(with_case=False) with pytest.raises(AppError) as missing_case_error: assert_customer_identity_gate(missing_case, operation='match_inventory') assert missing_case_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' assert customer_identity_is_confirmed(missing_case) is False def test_workspace_customer_search_and_confirmation_api(app, client): """业务用户只能确认自己的任务,确认响应返回正式业务编号。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): task, customer, user = _seed_task() other_user = User(username='gate-other-user', email='gate-other@example.com', role='user') db.session.add(other_user) db.session.commit() task_no = task.task_no customer_id = customer.id short_code = customer.short_code username = user.username headers = {'X-Username': username, 'X-Role': 'user', 'Content-Type': 'application/json'} options_response = client.get(f'/api/workspace/shipping-customers?q={short_code}', headers=headers) assert options_response.status_code == 200 options_payload = options_response.get_json() assert options_payload['success'] is True assert options_payload['data'][0]['short_code'] == short_code confirm_response = client.post( f'/api/workspace/shipping-tasks/{task_no}/confirm-customer', json={'customer_id': customer_id}, headers=headers, ) assert confirm_response.status_code == 200 envelope = confirm_response.get_json() assert envelope['success'] is True payload = envelope['data'] assert payload['customer_resolution_status'] == 'confirmed' assert payload['customer_id'] == customer_id assert payload['business_no'].startswith(short_code) other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'} forbidden_response = client.post( f'/api/workspace/shipping-tasks/{task_no}/confirm-customer', json={'customer_id': customer_id}, headers=other_headers, ) assert forbidden_response.status_code == 404