""" tests/test_shipping_inventory_routing_engine.py 用途:验证库存源路由只消费冻结订单 Snapshot 中的已裁决字段值。 依赖:订单 Schema service、库存路由模型、onhand_routing_engine。 逻辑:测试以稳定 field_id 创建冻结行事实,确认库存源线索优先于预定单号兜底且不会读取可变解析投影。 """ from __future__ import annotations from app.extensions import db from app.models import ( FreightRpaOnhandRoutingRule, FreightRpaOnhandRoutingRuleCondition, ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, ) from app.services.shipping_notice.onhand_routing_engine import ( evaluate_inventory_source_rules, evaluate_inventory_source_rules_for_field_values, ) from app.services.shipping_notice.order_schema import service as order_schema_service def _field_config(field_id: str, *, name: str, value_type: str = 'string') -> dict: """构造最小可发布行字段配置;路由只依赖其稳定 field_id。""" return { 'field_id': field_id, 'display_name': name, 'required': False, 'aliases': [], 'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim', 'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text', 'evidence_policy': { 'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True, }, 'relation_role': None, } def _published_line_fields() -> dict[str, str]: """创建冻结履约所需字段及可选库存源线索,并发布其稳定契约。""" order_schema_service.initialize_schema({'display_name': '路由字段'}, actor_id=None) reservation = order_schema_service.save_field( {'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None, ) part_number = order_schema_service.save_field( {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None, ) qty = order_schema_service.save_field( {'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None, ) source_hint = order_schema_service.save_field( {'field_code': 'inventory_source_hint', 'scope': 'line', 'value_type': 'string'}, actor_id=None, ) draft = order_schema_service.create_draft({}, actor_id=None) reservation_config = _field_config(reservation['id'], name='预定单号') reservation_config['business_purpose'] = 'reservation_id' part_number_config = _field_config(part_number['id'], name='料号') part_number_config['business_purpose'] = 'part_number' qty_config = _field_config(qty['id'], name='数量', value_type='decimal') qty_config['business_purpose'] = 'quantity' source_hint_config = _field_config(source_hint['id'], name='库存源线索') source_hint_config['business_purpose'] = 'inventory_source_hint' saved = order_schema_service.save_draft(draft['id'], { 'fields': [reservation_config, part_number_config, qty_config, source_hint_config], 'expected_lock_version': draft['lock_version'], }, actor_id=None) order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) return { 'reservation_id': reservation['id'], 'part_number': part_number['id'], 'qty': qty['id'], 'inventory_source_hint': source_hint['id'], } def _task_with_line_values( fields: dict[str, str], values: dict[str, tuple[str, str]], ) -> tuple[ShippingOrderTask, dict[str, int]]: """创建冻结快照;路由测试只允许从该不可变事实读取字段。""" task = ShippingOrderTask(task_no='OT-DYNAMIC-ROUTE', user_id=1, source_type='eml') db.session.add(task) db.session.flush() extraction = ShippingOrderExtraction( schema_version_id=order_schema_service.get_published_contract()['schema_version_id'], input_snapshot_hash='d' * 64, status='accepted', task_id=task.id, ) 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() for field_id, (value, _purpose) in values.items(): decision = ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_status='accepted', supporting_observation_ids_json=[], resolved_value_json=value, ) db.session.add(decision) db.session.flush() db.session.add(ShippingOrderFieldValue( extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_id=decision.id, value_text=value, value_json=value, )) task.current_order_extraction_id = extraction.id snapshot_values = {field_id: value for field_id, (value, _purpose) in values.items()} snapshot_values.setdefault(fields['part_number'], 'PN-ROUTE') snapshot_values.setdefault(fields['qty'], '1') snapshot = ShippingOrderSnapshot( task_id=task.id, extraction_id=extraction.id, schema_version_id=extraction.schema_version_id, order_data_version=1, rule_versions_json={}, header_values_json={}, customer_po_number='ROUTE-PO-001', ) db.session.add(snapshot) db.session.flush() db.session.add(ShippingOrderSnapshotLine( snapshot_id=snapshot.id, position=0, line_no=1, reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''), part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']], field_values_json=snapshot_values, )) task.order_snapshot_id = snapshot.id db.session.flush() return task, {'_position': 0} def _rule(*, code: str, priority: int, sources: list[str], conditions: list[tuple[str, str, object]]): """构造已发布的行级订单字段规则;禁止使用 system_fact 路径。""" return FreightRpaOnhandRoutingRule( rule_code=code, rule_name=code, scope='line', priority=priority, match_mode='all', status='published', action_type='add_source_candidates', action_payload_json={'source_codes': sources}, version=1, conditions=[ FreightRpaOnhandRoutingRuleCondition( condition_group=1, source_kind='order_field', order_field_id=field_id, operator=operator, expected_value_json=expected, sequence=index, ) for index, (field_id, operator, expected) in enumerate(conditions, start=1) ], ) def test_reservation_prefix_rule_returns_ambiguous_source_candidates(app): """十位预定单号兜底只产生 DUB/RTM 候选,不在路由阶段擅自选择 Source。""" with app.app_context(): fields = _published_line_fields() task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) db.session.add(_rule( code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'], conditions=[(fields['reservation_id'], 'prefix', '1')], )) db.session.commit() result = evaluate_inventory_source_rules(task=task, line=line) assert result.status == 'ambiguous' assert result.source_codes == ('DBS_DUB', 'DBS_RTM') assert result.can_build is True assert result.block_reason is None def test_inventory_source_hint_wins_over_reservation_fallback(app): """高优先级库存源线索必须覆盖预定单号兜底,体现明确订单事实优先。""" with app.app_context(): fields = _published_line_fields() task, line = _task_with_line_values(fields, { fields['reservation_id']: ('1000123456', 'reservation_id'), fields['inventory_source_hint']: ('VMI-FRA01', 'inventory_source_hint'), }) db.session.add_all([ _rule( code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'], conditions=[(fields['reservation_id'], 'prefix', '1')], ), _rule( code='HINT_FRA', priority=300, sources=['DBS_FRA'], conditions=[(fields['inventory_source_hint'], 'in', ['VMI-FRA01', 'FRA01'])], ), ]) db.session.commit() result = evaluate_inventory_source_rules(task=task, line=line) assert result.status == 'resolved' assert result.source_codes == ('DBS_FRA',) def test_crane_inventory_source_hint_wins_over_reservation_fallback(app): """Crane 邮件线索必须按高优先级规则命中,不依赖五位预定单号兜底。""" with app.app_context(): fields = _published_line_fields() task, line = _task_with_line_values(fields, { fields['reservation_id']: ('1000123456', 'reservation_id'), fields['inventory_source_hint']: ('LUK', 'inventory_source_hint'), }) db.session.add_all([ _rule( code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'], conditions=[(fields['reservation_id'], 'prefix', '1')], ), _rule( code='HINT_CRANE', priority=300, sources=['CRANE'], conditions=[( fields['inventory_source_hint'], 'in', ['DBS TZR02', 'TZR02', 'VMI-RBD02', 'RBD2', 'LUK'], )], ), ]) db.session.commit() result = evaluate_inventory_source_rules(task=task, line=line) assert result.status == 'resolved' assert result.source_codes == ('CRANE',) def test_five_digit_reservation_rule_can_route_to_crane(app): """五位纯数字预定单号通过订单 FieldValue 路由 Crane,Warehouse 仍留给库存行匹配。""" with app.app_context(): fields = _published_line_fields() task, line = _task_with_line_values(fields, {fields['reservation_id']: ('12345', 'reservation_id')}) db.session.add(_rule( code='RSV_LENGTH_5', priority=200, sources=['CRANE'], conditions=[(fields['reservation_id'], 'numeric_length', 5)], )) db.session.commit() result = evaluate_inventory_source_rules(task=task, line=line) assert result.status == 'resolved' assert result.source_codes == ('CRANE',) # ---------- 库存源线索直连(引擎内建,优先于全部规则层) ---------- def _hint_sources(monkeypatch, codes): """隔离线索解析的启用源清单(引擎自 list_database_inventory_sources 读取)。""" monkeypatch.setattr( 'app.services.shipping_notice.onhand_routing_engine.list_database_inventory_sources', lambda enabled_only=True: [{'source_code': code} for code in codes], ) def _set_snapshot_line_hint(task, hint: str) -> None: """在冻结快照行的强类型线索列写入线索值(模拟订单明细「库存源线索」)。""" snapshot_line = ShippingOrderSnapshotLine.query.filter_by( snapshot_id=task.order_snapshot_id, position=0, ).one() snapshot_line.inventory_source_hint = hint db.session.commit() def test_hint_direct_connect_suffix_wins_over_reservation_fallback(app, monkeypatch): """[断言] 核心需求:线索非空且可唯一后缀解析时直接 resolved,预约单号兜底规则不得参与。""" _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01', 'DSV360_AWSCV']) fields = _published_line_fields() task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) db.session.add(_rule( code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'], conditions=[(fields['reservation_id'], 'prefix', '1')], )) _set_snapshot_line_hint(task, 'BYAWSPRD01') db.session.commit() result = evaluate_inventory_source_rules(task=task, line=line) assert result.status == 'resolved' assert result.source_codes == ('DSV360_AWSBI_BYAWSPRD01',) assert result.evidence.get('reason') == 'inventory_source_hint' assert result.matched_rule_ids == () def test_hint_direct_connect_exact_code_match(app, monkeypatch): """[断言] 线索即完整源编码时精确命中。""" _hint_sources(monkeypatch, ['DSV360_AWSCV', 'DSV360_AWSDU']) fields = _published_line_fields() task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) _set_snapshot_line_hint(task, 'DSV360_AWSCV') db.session.commit() result = evaluate_inventory_source_rules(task=task, line=line) assert result.status == 'resolved' assert result.source_codes == ('DSV360_AWSCV',) def test_hint_unresolvable_falls_back_to_reservation_rule(app, monkeypatch): """[断言] fail-open:线索无命中(拼错/停用)时落回规则层,预约兜底照常,不阻断流程。""" _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01']) fields = _published_line_fields() task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) db.session.add(_rule( code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'], conditions=[(fields['reservation_id'], 'prefix', '1')], )) _set_snapshot_line_hint(task, 'NOPE_WAREHOUSE') db.session.commit() result = evaluate_inventory_source_rules(task=task, line=line) assert result.status == 'ambiguous' assert result.source_codes == ('DBS_DUB', 'DBS_RTM') def test_hint_ambiguous_suffix_falls_back_to_rules(app, monkeypatch): """[断言] 后缀撞多个启用源(多命中)时不采用线索,落回规则层裁决。""" _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01', 'DSV360_CRANE_BYAWSPRD01']) fields = _published_line_fields() task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) db.session.add(_rule( code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB'], conditions=[(fields['reservation_id'], 'prefix', '1')], )) _set_snapshot_line_hint(task, 'BYAWSPRD01') db.session.commit() result = evaluate_inventory_source_rules(task=task, line=line) assert result.status == 'resolved' assert result.source_codes == ('DBS_DUB',) def test_hint_direct_connect_ignored_for_task_scope(app, monkeypatch): """[断言] 线索是行级信号:任务级评估(line=None)维持原行为。""" _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01']) fields = _published_line_fields() task, _line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) _set_snapshot_line_hint(task, 'BYAWSPRD01') db.session.commit() result = evaluate_inventory_source_rules(task=task, line=None) assert result.status == 'unresolved' def test_draft_entry_hint_direct_connect_and_fallback(app, monkeypatch): """[断言] Draft 入口:线索命中直接 resolved(无规则也生效);未传线索时维持 unresolved。""" _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01']) result = evaluate_inventory_source_rules_for_field_values( header_field_values={}, line_field_values={}, scope='line', line_source_hint='BYAWSPRD01', ) assert result.status == 'resolved' assert result.source_codes == ('DSV360_AWSBI_BYAWSPRD01',) assert result.evidence.get('reason') == 'inventory_source_hint' fallback = evaluate_inventory_source_rules_for_field_values( header_field_values={}, line_field_values={}, scope='line', ) assert fallback.status == 'unresolved'