Merge branch 'hugo-auto-transfer' into dev

This commit is contained in:
hugo committed 2026-10-13 21:18:25 +08:00
commit af2658e244
30 files changed
+1913 -93

No files matched your search

@@ -0,0 +1,517 @@
"""
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,
ShippingInventoryParsingProfile,
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 = ShippingInventoryParsingProfile(
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/<case_no>/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'
@@ -14,7 +14,10 @@ from app.models import (
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingOrderTask,
)
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
from app.services.shipping_notice.inventory_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
@@ -212,3 +215,111 @@ def test_five_digit_reservation_rule_can_route_to_crane(app):
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.inventory_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'