""" 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, ShippingTask, 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, parse_inventory, upload_inventory_file from app.services.shipping_notice.progress_workflow import auto_progress def _seed_task(*, with_case: bool = True) -> tuple[ShippingTask, 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 = ShippingTask( 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, process_status='parsed', lines_json=[{'sku': 'A001', '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 result['human_options'] == ['confirm_customer'] 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}), parse_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}), 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}), upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}), ] for result in results: _assert_customer_gate_response(result) 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_confirm_customer_syncs_revision_chain_and_assigns_number(app): """客户确认同步同业务单全部任务,并在同事务生成正式业务号。""" with app.app_context(): task, customer, user = _seed_task() revision = ShippingTask( 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', process_status='parsed', ) 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_legacy_task_is_compatible(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' legacy, _other_customer, _other_user = _seed_task(with_case=False) assert_customer_identity_gate(legacy, operation='match_inventory') assert customer_identity_is_confirmed(legacy) is True 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 username = user.username headers = {'X-Username': username, 'X-Role': 'user', 'Content-Type': 'application/json'} options_response = client.get('/api/workspace/shipping-customers?q=GAA', headers=headers) assert options_response.status_code == 200 assert options_response.get_json()[0]['short_code'] == 'GAA' 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 payload = confirm_response.get_json() assert payload['customer_resolution_status'] == 'confirmed' assert payload['customer_id'] == customer_id assert payload['business_no'].startswith('GAA') 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