""" tests/test_customer_resolution_rebind.py 用途:确认客户改绑(customer_resolution_service.rebind_confirmed_customer)契约测试。 依赖:内存数据库、客户识别结果服务、order_freeze_service(真实冻结链)、 order_edit_window_service(编辑窗 header 谓词)、ShippingExportArtifact。 逻辑:已确认订单在产生发货通知/Excel 之前允许直接修改确认客户;改绑同步刷新冻结快照客户, 并保持 evidence_json / identity_rule_set_checksum 非空冻结契约;Excel 已产生 / 活动 Gate Attempt / 同客户 / 未知或停用客户 / 未确认识别结果均 fail-closed 且零副作用。 """ from __future__ import annotations from decimal import Decimal import pytest from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingAuditEvent, ShippingCustomer, ShippingCustomerShadowResolution, ShippingExportArtifact, FreightRpaParsingProfile, ShippingNotice, ShippingOrderCandidate, ShippingOrderExtraction, ShippingOrderField, ShippingOrderIntake, ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderTask, User, ) from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer from app.services.shipping_notice.order_review_customer_service import project_review_case_customer_resolution from app.services.shipping_notice.order_freeze_service import ( HEADER_FIELD_PROJECTIONS, LINE_FIELD_PROJECTIONS, freeze_order_snapshot, ) from tests.conftest import parse_api_error def _build_confirmed_frozen_order(*, suffix: str) -> dict: """构造已确认客户 + 已冻结快照 + 未产生 Excel 的正式订单(编辑窗 header 可编辑)。""" user = User(username=f'rebind-user-{suffix}', email=f'rebind-user-{suffix}@example.test', password_hash='x') old_customer = ShippingCustomer(standard_name='原确认客户', short_code='OLD', status='active') new_customer = ShippingCustomer(standard_name='新确认客户', short_code='NEWC', status='active') inactive_customer = ShippingCustomer(standard_name='停用客户', short_code='OFF', status='inactive') task = ShippingOrderTask(task_no=f'OT-REBIND-{suffix}', source_type='direct_pdf', user_id=1, order_data_version=7) schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Rebind frozen order') db.session.add_all([user, old_customer, new_customer, inactive_customer, task, schema]) db.session.flush() from app.services.shipping_notice import field_asset_service field_asset_service.ensure_standard_assets_seeded() definitions = [] fields: dict[str, ShippingOrderField] = {} for code in [*HEADER_FIELD_PROJECTIONS, *LINE_FIELD_PROJECTIONS]: scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line' field = ShippingOrderField.query.filter_by(field_code=code, scope=scope).one() fields[code] = field definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': field.value_type, 'enabled': True}) version = ShippingOrderSchemaVersion( schema_id=schema.id, version=1, status='published', definition_json={'fields': definitions}, checksum='rebind-test', ) db.session.add(version) db.session.flush() extraction = ShippingOrderExtraction( task_id=task.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted', ) db.session.add(extraction) db.session.flush() line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() values = { 'customer_po_number': 'PO-REBIND', 'customer_code': 'C-001', 'customer_name': 'Customer', 'part_number': '000123', 'reservation_id': '0012345678', 'qty': Decimal('12.50'), 'unit_price': Decimal('2.30'), 'line_amount_with_tax': Decimal('28.75'), 'uom': 'PCS', } for code, field in fields.items(): value = values.get(code) decision = _make_decision(extraction, line, field, code, value) db.session.add(decision) db.session.flush() if value is not None: db.session.add(_make_field_value(extraction, line, field, decision, value)) task.current_order_extraction_id = extraction.id intake = ShippingOrderIntake( intake_no=f'INT-REBIND-{suffix}', asset_id=1, user_id=user.id, parser_version='test', ) db.session.add(intake) db.session.flush() candidate = ShippingOrderCandidate( candidate_no=f'CAND-REBIND-{suffix}', intake_id=intake.id, primary_document_id=1, candidate_key=f'rebind-{suffix}', order_extraction_id=extraction.id, candidate_status='accepted', ) db.session.add(candidate) db.session.flush() task.candidate_id = candidate.id task.user_id = int(user.id) resolution = ShippingCustomerShadowResolution( candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed', evidence_json=[{'definition_code': 'test_customer', 'normalized_value': old_customer.short_code}], candidate_matches_json=[ {'customer_id': old_customer.id, 'score': 100}, {'customer_id': new_customer.id, 'score': 90}, ], resolution_context_json={'rule_set': {'checksum': 'f' * 64}}, identity_rule_set_checksum='f' * 64, top_customer_id=old_customer.id, top_score=100, confirmed_customer_id=old_customer.id, confirmation_method='manual', confirmed_by_id=user.id, ) notice = ShippingNotice(task_no=f'SN-REBIND-{suffix}', order_task_id=task.id) db.session.add_all([resolution, notice]) db.session.flush() snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) db.session.commit() return { 'user': user, 'task': task, 'notice': notice, 'resolution': resolution, 'old_customer': old_customer, 'new_customer': new_customer, 'inactive_customer': inactive_customer, 'snapshot': snapshot, 'schema_version_id': int(version.id), } def _make_decision(extraction, line, field, code, value): """构造单头/行字段裁决行(与既有快照测试同构)。""" from app.models import ShippingOrderFieldDecision return ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=None if code in HEADER_FIELD_PROJECTIONS else line.id, field_id=field.id, decision_status='accepted', resolved_value_json=str(value) if isinstance(value, Decimal) else value, supporting_observation_ids_json=[], ) def _make_field_value(extraction, line, field, decision, value): """构造字段值投影行(Decimal 保留精度,料号/预约号保留前导零)。""" from app.models import ShippingOrderFieldValue return ShippingOrderFieldValue( extraction_id=extraction.id, line_id=None if field.scope == 'header' else line.id, field_id=field.id, decision_id=decision.id, value_json=str(value) if isinstance(value, Decimal) else value, value_text=str(value) if isinstance(value, str) else None, value_decimal=value if isinstance(value, Decimal) else None, ) def _attach_ready_export_artifact(notice: ShippingNotice) -> None: """给通知挂一个 ready 导出产物(Excel 已产生,header 编辑窗关闭)。""" from app.models import ShippingOrderSchema as Schema from app.models import ShippingOrderSchemaVersion, ShippingOrderExtraction template = _template_row() profile = FreightRpaParsingProfile( profile_code='REBIND_PROFILE', display_name='Rebind profile', version=1, status='published', file_format='xlsx', definition_json={}, ) schema = Schema(schema_code='REBIND_SCHEMA', display_name='Rebind schema') db.session.add_all([template, profile, schema]) db.session.flush() version = ShippingOrderSchemaVersion( schema_id=schema.id, version=1, status='published', definition_json={}, checksum='b' * 64, ) db.session.add(version) db.session.flush() extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted') db.session.add(extraction) db.session.flush() db.session.add(ShippingExportArtifact( task_id=int(notice.id), artifact_no=f'ART-REBIND-{notice.task_no}', template_id=template.id, order_schema_version_id=version.id, order_extraction_id=extraction.id, inventory_parsing_profile_id=profile.id, input_checksum='d' * 64, file_path='rebind.xlsx', file_name='rebind.xlsx', file_checksum='e' * 64, file_size=1, status='ready', )) db.session.flush() _TEMPLATE_CACHE: dict = {} def _template_row(): """复用同进程内已建模板,避免不同用例重复建模板造成噪音。 缓存需自愈:每测试独立 create_all/drop_all,缓存 id 在新 DB 中可能不存在 (该脆弱组合即 Task 1 评审预警项),取不到时重建并刷新缓存。 """ from app.models import ShippingExcelTemplate cached_id = _TEMPLATE_CACHE.get('id') if cached_id is not None: template = db.session.get(ShippingExcelTemplate, int(cached_id)) if template is not None: return template _TEMPLATE_CACHE.pop('id', None) template = ShippingExcelTemplate( template_code='REBIND_TPL', display_name='Rebind template', version=1, status='published', storage_bucket='test', storage_key='rebind-tpl.xlsx', original_filename='rebind-tpl.xlsx', file_checksum='a' * 64, definition_json={}, ) db.session.add(template) db.session.flush() _TEMPLATE_CACHE['id'] = int(template.id) return template def _resolution_of(task: ShippingOrderTask) -> ShippingCustomerShadowResolution: """按 OT 的候选反查唯一识别结果行。""" return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(task.candidate_id)).one() def _attach_confirmed_revision(fx: dict, *, suffix: str): """构造建单确认修订,把冻结任务挂到真实复核 Case 上(审计 review_case_no 反查依赖)。""" from app.models import ShippingOrderReviewConfirmedRevision _user, case = _seed_review_case(suffix=suffix) db.session.add(ShippingOrderReviewConfirmedRevision( case_id=int(case.id), task_id=int(fx['task'].id), draft_version=1, schema_version_id=int(fx['schema_version_id']), idempotency_key=f'IDEM-REBIND-{suffix}', confirmed_by_id=int(fx['user'].id), )) # 生产确认路径会把任务挂上 Case;改绑投影经 confirmed_task_id 反查确认结果。 case.confirmed_task_id = int(fx['task'].id) db.session.flush() return case def test_rebind_updates_confirmed_customer_and_refreezes_snapshot(app): """改绑必须更新确认结果并按新客户重冻结快照(客户 ODM 白名单随新客户生效)。""" with app.app_context(): fx = _build_confirmed_frozen_order(suffix='happy') # Case 反查夹具的 suffix 必须大写(intake_no 查找统一 upper 归一)。 case = _attach_confirmed_revision(fx, suffix='HAPPY-CASE') result = rebind_confirmed_customer( task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id), expected_order_data_version=7, reason='选错客户', ) db.session.commit() resolution = result['resolution'] snapshot = result['snapshot'] # 断言意图:确认结果与快照客户同步改绑;审计与 evidence_json 记录原客户(可追溯)。 assert resolution.confirmed_customer_id == int(fx['new_customer'].id) assert snapshot.customer_id == int(fx['new_customer'].id) assert snapshot.customer_short_code_snapshot == str(fx['new_customer'].short_code) rebind_record = next( item for item in (resolution.evidence_json or []) if isinstance(item, dict) and item.get('rebind') ) assert rebind_record['rebind']['previous_customer_id'] == int(fx['old_customer'].id) assert rebind_record['rebind']['new_customer_id'] == int(fx['new_customer'].id) assert rebind_record['rebind']['actor_id'] == int(fx['user'].id) assert rebind_record['rebind']['reason'] == '选错客户' assert resolution.identity_rule_set_checksum == 'f' * 64 # 冻结契约:保持非空 # 原始识别证据保留(rebind 记录是追加,不是覆盖)。 assert resolution.evidence_json[0]['definition_code'] == 'test_customer' # 快照唯一约束(uq task_id):一个任务一份快照,改绑是原地刷新而非新行。 assert int(snapshot.id) == int(fx['snapshot'].id) assert fx['task'].order_snapshot_id == snapshot.id # 审计事件:before/after 携带原/新确认客户与原因;挂 review_case_no 供 Case 时间线查询。 event = ShippingAuditEvent.query.filter_by( event_type='review_customer_rebound', aggregate_id=str(fx['task'].task_no), ).one() assert event.before_snapshot_json['previous_value'] == int(fx['old_customer'].id) assert event.after_snapshot_json['new_value'] == int(fx['new_customer'].id) assert event.reason == '选错客户' assert event.actor_type == 'user' assert event.review_case_no == str(case.case_no) # 改绑后投影以确认结果+客户主数据为权威展示:名字/简称/改绑谓词直供工作台。 projection = project_review_case_customer_resolution(case=case) assert projection['standard_name'] == str(fx['new_customer'].standard_name) assert projection['short_code'] == str(fx['new_customer'].short_code) assert projection['customer_id'] == int(fx['new_customer'].id) assert projection['rebind_allowed'] is True def test_task_ui_state_emits_edit_window_gate_for_workbench(app): """工作台 payload 必须下发 edit_window(D10 门控数据源,防合并再次丢失)。 回归背景:前端波次出单工具条的显示条件读 ui_state.edit_window.header, 后端曾把该字段丢失,导致 Excel 已产生仍显示「生成发货通知和 Excel」工具条。 """ fx = _build_confirmed_frozen_order(suffix='ew') from app.services.shipping_notice.ui_state import build_task_ui_state ui = build_task_ui_state(fx['notice'], include_stage_context=True) # 断言意图:Excel 未产生时 header=True(出单工具条显示)。 assert ui['edit_window']['header'] is True _attach_ready_export_artifact(fx['notice']) ui_after = build_task_ui_state(fx['notice'], include_stage_context=True) # 断言意图:Excel 已产生时 header=False(出单工具条隐藏——用户报告的缺陷)。 assert ui_after['edit_window']['header'] is False # OT 身份构建必须与通知身份同判(editable_scope 身份归一):用户场景即按 OT 加载详情。 ui_by_ot = build_task_ui_state(fx['task'], include_stage_context=True) assert ui_by_ot['edit_window']['header'] is False def test_rebind_rejects_when_export_artifact_exists(app): """已产生 Excel(header 不可编辑)时改绑必须 409,且确认结果不被改动。""" with app.app_context(): fx = _build_confirmed_frozen_order(suffix='excel') _attach_ready_export_artifact(fx['notice']) case = _attach_confirmed_revision(fx, suffix='EXCEL-CASE') # 断言意图:Excel 已产生时投影谓词 fail-closed(前端「修改客户」按钮禁用的数据源)。 assert project_review_case_customer_resolution(case=case)['rebind_allowed'] is False with pytest.raises(ConflictError) as exc: rebind_confirmed_customer( task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id), expected_order_data_version=7, ) # 断言意图:A 管控 fail-closed;错误码可前端定位(details 区分 Excel / 活动 Attempt)。 assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED' assert exc.value.details['excel_exists'] is True assert exc.value.details['active_attempt'] is False db.session.rollback() assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) def test_rebind_rejects_when_active_gate_attempt_exists(app, monkeypatch): """存在活动 Gate Attempt(库存 RPA / 匹配处理中)时改绑必须 409。""" monkeypatch.setattr( 'app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: True, ) with app.app_context(): fx = _build_confirmed_frozen_order(suffix='busy') with pytest.raises(ConflictError) as exc: rebind_confirmed_customer( task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id), expected_order_data_version=7, ) assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED' assert exc.value.details['excel_exists'] is False assert exc.value.details['active_attempt'] is True db.session.rollback() assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) def test_rebind_rejects_same_customer_and_unknown_customer(app): """同客户重复改绑与不存在/停用客户都必须 409/404,不产生副作用。""" with app.app_context(): fx = _build_confirmed_frozen_order(suffix='guards') with pytest.raises(ConflictError) as same: rebind_confirmed_customer( task=fx['task'], new_customer_id=int(fx['old_customer'].id), actor_id=int(fx['user'].id), expected_order_data_version=7, ) assert same.value.code == 'SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER' with pytest.raises(NotFoundError) as unknown: rebind_confirmed_customer( task=fx['task'], new_customer_id=999999, actor_id=int(fx['user'].id), expected_order_data_version=7, ) assert unknown.value.code == 'SHIPPING.CUSTOMER_NOT_FOUND' with pytest.raises(ConflictError) as inactive: rebind_confirmed_customer( task=fx['task'], new_customer_id=int(fx['inactive_customer'].id), actor_id=int(fx['user'].id), expected_order_data_version=7, ) assert inactive.value.code == 'SHIPPING.CUSTOMER_INACTIVE' # 断言意图:拒绝路径零副作用(确认结果与快照均不被触碰)。 db.session.rollback() assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) assert fx['task'].order_snapshot_id == fx['snapshot'].id def test_rebind_requires_confirmed_resolution(app): """识别结果未确认(或缺失)时改绑必须 409,提示走既有识别确认流程。""" with app.app_context(): fx = _build_confirmed_frozen_order(suffix='unconfirmed') resolution = _resolution_of(fx['task']) resolution.status = 'unique_candidate' db.session.commit() with pytest.raises(ConflictError) as exc: rebind_confirmed_customer( task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id), expected_order_data_version=7, ) assert exc.value.code == 'SHIPPING.CUSTOMER_RESOLUTION_REQUIRED' db.session.rollback() assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) def test_rebind_rejects_stale_version_without_side_effects(app): """[断言] 客户端版本比较在守卫阶段执行:版本不一致必须 409 且零副作用(不写确认结果/审计/快照)。""" with app.app_context(): fx = _build_confirmed_frozen_order(suffix='stale') with pytest.raises(ConflictError) as exc: rebind_confirmed_customer( task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id), expected_order_data_version=6, ) # 断言意图:乐观锁在写前拒绝;details 呈现 expected/actual 供前端提示刷新。 assert exc.value.code == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH' assert exc.value.details == {'expected': 6, 'actual': 7} db.session.rollback() assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) assert fx['task'].order_snapshot_id == fx['snapshot'].id assert ShippingAuditEvent.query.filter_by(event_type='review_customer_rebound').count() == 0 def test_rebind_requires_operator_for_internal_call(app): """[断言] 缺少执行人的内部调用按参数错误拒绝(独立于编辑窗 A 管控语义)。""" with app.app_context(): fx = _build_confirmed_frozen_order(suffix='no-actor') with pytest.raises(ValidationError) as exc: rebind_confirmed_customer( task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=None, expected_order_data_version=7, ) assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED' db.session.rollback() assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) # --------------------------------------------------------------------------- # API 路由层(POST /api/workspace/shipping-notice/order-review-cases//customer/rebind) # --------------------------------------------------------------------------- def _seed_review_case(*, suffix: str): """构造属主用户与其复核 Case(未建正式 OT,够验证路由守卫)。""" from tests.test_shipping_order_extraction_runs import _seed_run_input from tests.test_shipping_order_review_service import _materialized_run user, agent, session, intake, _document = _seed_run_input(suffix=suffix) run = _materialized_run(user=user, agent=agent, session=session, intake=intake) from app.services.shipping_notice.order_review_service import ensure_run_review_cases case = ensure_run_review_cases(run=run)[0] db.session.commit() return user, case def _auth_headers(user) -> dict: from app.core.auth.jwt import issue_local_access_token return {'Authorization': f'Bearer {issue_local_access_token(user)}'} def test_rebind_api_requires_customer_id(app): """[断言] 缺少 customer_id 的请求体被 400 拦截,错误码可前端定位。""" with app.app_context(): user, case = _seed_review_case(suffix='API-BODY') client = app.test_client() response = client.post( f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind', headers=_auth_headers(user), json={}, ) error = parse_api_error(response.get_json()) assert response.status_code == 400 assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED' def test_rebind_api_requires_expected_version(app): """[断言] 缺少 expected_order_data_version 的请求体被 400 拦截(乐观锁必填)。""" with app.app_context(): user, case = _seed_review_case(suffix='API-VER') client = app.test_client() response = client.post( f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind', headers=_auth_headers(user), json={'customer_id': 1}, ) error = parse_api_error(response.get_json()) assert response.status_code == 400 assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED' assert error['details']['field'] == 'expected_order_data_version' def test_rebind_api_rejects_case_outside_ownership(app): """[断言] 非属主访问他人 Case 必须按不存在拒绝(404),不泄露存在性。""" with app.app_context(): owner, case = _seed_review_case(suffix='API-OWNER') # agent_code 全局唯一,非属主用户须使用独立 agent_code。 from tests.test_shipping_order_extraction_runs import _seed_run_input outsider, _a, _s, _i, _d = _seed_run_input(suffix='API-OUTSIDER', agent_code='shipping_notice_rebind') client = app.test_client() response = client.post( f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind', headers=_auth_headers(outsider), json={'customer_id': 1, 'expected_order_data_version': 1}, ) error = parse_api_error(response.get_json()) assert response.status_code == 404 assert error['code'] == 'SHIPPING.REVIEW_CASE_NOT_FOUND' assert owner is not None def test_rebind_api_requires_formal_order_task(app): """[断言] Case 尚未确认建单(无正式 OT)时改绑必须 409。""" with app.app_context(): user, case = _seed_review_case(suffix='API-NOOT') client = app.test_client() response = client.post( f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind', headers=_auth_headers(user), json={'customer_id': 1, 'expected_order_data_version': 1}, ) error = parse_api_error(response.get_json()) assert response.status_code == 409 assert error['code'] == 'SHIPPING.FORMAL_OT_REQUIRED'