feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议

This commit is contained in:
hugo committed 2026-07-18 11:41:02 +08:00
1 parent 46eb63f5bb
commit e9bdd81f1a
320 files changed
+28361 -10487

No files matched your search

+135 -19
View File
@@ -54,8 +54,8 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
def _shipping_notice_stable_auto_config(app, request, monkeypatch):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
tmp_path = request.getfixturevalue("tmp_path")
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
)
if request.node.get_closest_marker("auto_rpa"):
@@ -132,12 +132,12 @@ def seed_task_inventory_source(
compute_routing_fingerprint,
extract_routing_context,
)
from app.services.shipping_notice.inventory_sources import (
get_inventory_source,
get_inventory_sources_config_version,
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
source = get_inventory_source(source_code)
source = get_database_inventory_source(source_code)
if not source:
raise ValueError(f"unknown inventory source for tests: {source_code}")
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
@@ -151,11 +151,10 @@ def seed_task_inventory_source(
identity = resolution.identity
task.inventory_source_code = identity.source_code
task.inventory_connector_type = identity.connector_type
task.inventory_site_id = identity.site_id
task.inventory_warehouse_id = identity.warehouse_id
task.inventory_source_status = "resolved"
task.inventory_source_method = "rule_exact"
task.inventory_source_config_version = get_inventory_sources_config_version()
task.inventory_source_config_version = inventory_sources_runtime_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
@@ -184,9 +183,10 @@ def inventory_xlsx_with_warehouse(
warehouse_id: str,
*,
sku: str = "A001",
reservation_id: str = "R-1",
qty: int = 1,
) -> "BytesIO":
"""生成带 Warehouse ID 列的库存 Excel,供身份校验测试使用。"""
"""生成符合发布解析方案的库存 Excel,供身份、结构和库存解析测试使用。"""
from io import BytesIO
from openpyxl import Workbook
@@ -194,8 +194,8 @@ def inventory_xlsx_with_warehouse(
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "SKU", "Qty"])
ws.append([warehouse_id, sku, qty])
ws.append(["Warehouse ID", "SKU", "Reservation ID", "Qty"])
ws.append([warehouse_id, sku, reservation_id, qty])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -220,25 +220,23 @@ def inventory_csv_with_warehouse(
def batch_rpa_item_identity(task: "ShippingTask") -> dict[str, str]:
"""构造 batch 成功回调 item 须携带的 Worker 身份字段。"""
"""构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。"""
return {
"source_code": str(task.inventory_source_code or ""),
"site_id": str(task.inventory_site_id or ""),
"warehouse_id": str(task.inventory_warehouse_id or ""),
}
def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
"""构造定时 batch 成功回调 item 的四字段身份(与 YAML 配置一致)。"""
from app.services.shipping_notice.inventory_sources import get_inventory_source
"""构造定时 batch 成功回调 item 的 Source/Warehouse 身份(与数据库配置一致)。"""
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_inventory_source(source_code)
source = get_database_inventory_source(source_code)
if not source:
raise ValueError(f"unknown inventory source for tests: {source_code}")
item = {
"source_code": source_code,
"site_id": str(source.get("site_id") or ""),
"warehouse_id": str(source.get("warehouse_id") or ""),
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
}
item.update(overrides)
return item
@@ -258,7 +256,6 @@ def rpa_callback_payload(
"file_path": str(file_path),
"run_no": run_no,
"source_code": task.inventory_source_code,
"site_id": task.inventory_site_id,
"warehouse_id": task.inventory_warehouse_id,
}
@@ -281,11 +278,130 @@ def app():
app = create_app('testing')
with app.app_context():
db.create_all()
_seed_test_inventory_configuration()
yield app
db.session.remove()
db.drop_all()
def _seed_test_inventory_configuration() -> None:
"""为发货测试创建数据库库存源与发布路由规则,测试运行期不读取 YAML。"""
from app import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition, ShippingInventorySource, ShippingRpaProfile,
)
from app.services.shipping_notice.inventory_structure_fingerprint import (
FINGERPRINT_VERSION,
compatibility_fingerprint,
exact_fingerprint,
structure_definition,
)
# 各测试显式创建所需用户字段;生产目录本身保持零预置。
if not ShippingInventoryField.query.filter_by(field_code='part_number').first():
db.session.add_all([
ShippingInventoryField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10),
ShippingInventoryField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20),
ShippingInventoryField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30),
ShippingInventoryField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40),
ShippingInventoryField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100),
ShippingInventoryField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110),
ShippingInventoryField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120),
ShippingInventoryField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130),
ShippingInventoryField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140),
])
db.session.flush()
inventory_fields = {
item.field_code: item
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_([
'part_number', 'reservation_id', 'available_qty', 'warehouse_id',
])
).all()
}
field_mapping = {
str(inventory_fields['part_number'].id): 'SKU',
str(inventory_fields['reservation_id'].id): 'Reservation ID',
str(inventory_fields['available_qty'].id): 'Qty',
str(inventory_fields['warehouse_id'].id): 'Warehouse ID',
}
# 测试专用稳定字段 ID 避免全局创建订单模板,后者会破坏订单模板初始化专项测试。
match_keys = [
{
'order_field_id': 'test-order-part-number',
'inventory_field_id': str(inventory_fields['part_number'].id),
},
{
'order_field_id': 'test-order-reservation-id',
'inventory_field_id': str(inventory_fields['reservation_id'].id),
},
]
definition = {
'sheet_name': 'Sheet',
'header_row_index': 1,
'field_mapping': field_mapping,
'match_keys': match_keys,
}
structure = structure_definition(
file_format='xlsx', sheet_name='Sheet', header_row_index=1,
headers=['Warehouse ID', 'SKU', 'Reservation ID', 'Qty'],
)
import hashlib
import json
checksum = hashlib.sha256(
json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
).hexdigest()
parsing_profile = ShippingInventoryParsingProfile(
profile_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published',
file_format='xlsx', definition_json=definition, checksum=checksum,
structure_definition_json=structure,
exact_structure_fingerprint=exact_fingerprint(structure),
compatibility_fingerprint=compatibility_fingerprint(
definition=structure, field_mapping=field_mapping, match_keys=match_keys,
),
fingerprint_version=FINGERPRINT_VERSION,
)
excel_template = ShippingExcelTemplate(
template_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published',
storage_provider='minio', storage_bucket='test', storage_key='test/runtime/template.xlsx',
original_filename='template.xlsx',
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
)
profile = ShippingRpaProfile(
profile_code='DBS_DUB_TEST', display_name='DBS Dublin', connector_type='dbs',
login_url='https://test.invalid/dbs', login_config_json={'auth_mode': 'password'},
)
source = ShippingInventorySource(
source_code='DSV360_AWSDU', display_name='DBS Dublin AWSDU', connector_type='dbs',
rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU',
report_path_json={
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
},
query_parameters_json=[
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': True, 'select_all': False},
],
match_aliases_json=['AWSDU', 'DUB'],
enabled=True,
)
rule = ShippingInventoryRoutingRule(
rule_code='TEST_DUB', rule_name='Test DUB route', scope='task', priority=100,
match_mode='all', status='published', action_type='add_source_candidates',
action_payload_json={'source_codes': ['DSV360_AWSDU']}, version=1,
)
rule.conditions.append(ShippingInventoryRoutingRuleCondition(
condition_group=1, source_kind='system_fact', system_fact_key='task.destination_port', operator='equals',
expected_value_json='DUB', sequence=1,
))
db.session.add_all([profile, parsing_profile, excel_template, source, rule])
db.session.commit()
@pytest.fixture
def client(app):
return app.test_client()
@@ -0,0 +1,280 @@
"""
tests/services/admin/test_shipping_customer_lifecycle_service.py
用途:验证货代客户删除资格必须覆盖业务、导入、外部来源与影子识别引用。
依赖:客户领域模型、shipping_customer_lifecycle_service、内存数据库。
逻辑:分别构造每类引用,断言后端统一影响结果阻断删除而识别证据仅作为可级联配置。
"""
from __future__ import annotations
from datetime import date
import pytest
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerImportBatch,
ShippingCustomerImportRow,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
)
from app.services.admin.shipping_customer_lifecycle_service import (
delete_customer,
get_customer_lifecycle_impact,
get_customer_lifecycle_timeline,
)
def _customer(code: str = 'WYC') -> ShippingCustomer:
"""创建可用于生命周期影响测试的最小标准客户。"""
customer = ShippingCustomer(standard_name=f'客户 {code}', short_code=code, status='active')
db.session.add(customer)
db.session.flush()
return customer
def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
"""仅有识别证据的误建客户可删除,证据不应成为业务阻断引用。"""
with app.app_context():
customer = _customer()
db.session.add(ShippingCustomerIdentifier(
customer_id=customer.id,
identifier_type='name_alias',
raw_value='WYC LTD',
normalized_value='WYCLTD',
status='approved',
source='manual',
))
db.session.commit()
impact = get_customer_lifecycle_impact(customer.id)
assert impact['can_delete'] is True
assert impact['cascade']['identifiers'] == 1
assert not any(impact['blockers'].values())
@pytest.mark.parametrize('reference_kind', [
'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
])
def test_business_and_audit_references_block_delete(app, reference_kind: str):
"""每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。"""
with app.app_context():
customer = _customer()
if reference_kind == 'case':
db.session.add(ShippingCase(case_no='CASE-LIFECYCLE', customer_id=customer.id))
elif reference_kind == 'sequence':
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
elif reference_kind == 'external_ref':
db.session.add(ShippingCustomerExternalRef(customer_id=customer.id, source_system='ERP', legacy_customer_key='C-1'))
elif reference_kind in {'import_target', 'import_result'}:
batch = ShippingCustomerImportBatch(
batch_no=f'BATCH-{reference_kind}', file_name='test.xlsx', file_hash=f'{reference_kind:0<64}'[:64],
file_size=1, source_system='ERP',
)
db.session.add(batch)
db.session.flush()
values = {
'batch_id': batch.id, 'sheet_name': 'customers', 'row_no': 2, 'row_order': 1,
'row_type': 'customer', 'raw_json': {}, 'normalized_json': {},
}
if reference_kind == 'import_target':
values['target_customer_id'] = customer.id
else:
values['result_customer_id'] = customer.id
db.session.add(ShippingCustomerImportRow(**values))
else:
# 影子引用仅需最小分辨记录;生命周期统计不要求 Candidate 外键链完整。
resolution = ShippingCustomerShadowResolution(
candidate_id=1000 + customer.id,
intake_id=1000 + customer.id,
resolution_version='shadow-v1', status='unmatched', evidence_json=[], candidate_matches_json=[],
)
if reference_kind == 'shadow_top':
resolution.top_customer_id = customer.id
if reference_kind == 'shadow_manual':
resolution.manual_customer_id = customer.id
db.session.add(resolution)
db.session.flush()
if reference_kind == 'shadow_match':
db.session.add(ShippingCustomerShadowMatch(
resolution_id=resolution.id, customer_id=customer.id, match_rank=1, score=60,
standard_name_snapshot=customer.standard_name, short_code_snapshot=customer.short_code, reasons_json=[],
))
db.session.commit()
impact = get_customer_lifecycle_impact(customer.id)
assert impact['can_delete'] is False
assert any(impact['blockers'].values())
def test_lifecycle_impact_rejects_missing_customer(app):
"""不存在的客户必须返回统一 not-found 错误,不能返回伪空影响结果。"""
with app.app_context():
with pytest.raises(NotFoundError) as exc_info:
get_customer_lifecycle_impact(99999)
assert exc_info.value.code == 'SHIPPING.CUSTOMER_NOT_FOUND'
def test_delete_unused_customer_cascades_identifiers_and_keeps_snapshot_audit(app):
"""仅含配置证据的误建客户删除后,客户和证据消失但快照审计必须保留。"""
with app.app_context():
customer = _customer('DEL')
db.session.add(ShippingCustomerIdentifier(
customer_id=customer.id,
identifier_type='name_alias', raw_value='Delete Me', normalized_value='DELETEME',
status='approved', source='manual',
))
db.session.commit()
customer_id = customer.id
result = delete_customer(
customer_id,
confirmation_short_code='del',
reason='误建客户',
actor_id=None,
)
assert result['deleted_customer']['short_code'] == 'DEL'
assert result['cascade']['identifiers'] == 1
assert db.session.get(ShippingCustomer, customer_id) is None
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=customer_id).count() == 0
event = db.session.get(ShippingCustomerLifecycleEvent, result['lifecycle_event_id'])
assert event is not None
assert event.event_type == 'deleted'
assert event.customer_id_snapshot == customer_id
assert event.customer_short_code_snapshot == 'DEL'
assert event.reason == '误建客户'
@pytest.mark.parametrize('reference_kind', [
'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
])
def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str):
"""永久删除必须复用完整生命周期统计,任一业务或审计引用均返回冲突。"""
with app.app_context():
customer = _customer('BLK')
if reference_kind == 'case':
db.session.add(ShippingCase(case_no='CASE-DELETE-BLOCK', customer_id=customer.id))
elif reference_kind == 'sequence':
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
elif reference_kind == 'external_ref':
db.session.add(ShippingCustomerExternalRef(customer_id=customer.id, source_system='ERP', legacy_customer_key='DELETE-BLOCK'))
elif reference_kind in {'import_target', 'import_result'}:
batch = ShippingCustomerImportBatch(
batch_no=f'BATCH-DELETE-{reference_kind}', file_name='test.xlsx',
file_hash=f'delete-{reference_kind}'.ljust(64, 'x')[:64], file_size=1, source_system='ERP',
)
db.session.add(batch)
db.session.flush()
values = {
'batch_id': batch.id, 'sheet_name': 'customers', 'row_no': 2, 'row_order': 1,
'row_type': 'customer', 'raw_json': {}, 'normalized_json': {},
}
values['target_customer_id' if reference_kind == 'import_target' else 'result_customer_id'] = customer.id
db.session.add(ShippingCustomerImportRow(**values))
else:
resolution = ShippingCustomerShadowResolution(
candidate_id=2000 + customer.id, intake_id=2000 + customer.id,
resolution_version='shadow-v1', status='unmatched', evidence_json=[], candidate_matches_json=[],
)
if reference_kind == 'shadow_top':
resolution.top_customer_id = customer.id
if reference_kind == 'shadow_manual':
resolution.manual_customer_id = customer.id
db.session.add(resolution)
db.session.flush()
if reference_kind == 'shadow_match':
db.session.add(ShippingCustomerShadowMatch(
resolution_id=resolution.id, customer_id=customer.id, match_rank=1, score=60,
standard_name_snapshot=customer.standard_name, short_code_snapshot=customer.short_code, reasons_json=[],
))
db.session.commit()
with pytest.raises(ConflictError) as exc_info:
delete_customer(customer.id, confirmation_short_code='BLK', reason='尝试删除', actor_id=None)
assert exc_info.value.code == 'SHIPPING.CUSTOMER_DELETE_BLOCKED'
assert any(exc_info.value.details['blockers'].values())
assert db.session.get(ShippingCustomer, customer.id) is not None
def test_delete_requires_current_short_code_and_reason(app):
"""删除请求必须同时带当前简码和非空原因,不能仅依赖前端确认。"""
with app.app_context():
customer = _customer('CHK')
db.session.commit()
with pytest.raises(ValidationError) as code_error:
delete_customer(customer.id, confirmation_short_code='BAD', reason='删除', actor_id=None)
assert code_error.value.code == 'SHIPPING.CUSTOMER_DELETE_CONFIRMATION_INVALID'
with pytest.raises(ValidationError) as reason_error:
delete_customer(customer.id, confirmation_short_code='CHK', reason=' ', actor_id=None)
assert reason_error.value.code == 'SHIPPING.CUSTOMER_DELETE_REASON_REQUIRED'
assert db.session.get(ShippingCustomer, customer.id) is not None
def test_delete_blocks_reference_created_after_preview(app):
"""预检只是展示;提交删除时必须重新统计预检后新增的业务引用。"""
with app.app_context():
customer = _customer('RCE')
db.session.commit()
preview = get_customer_lifecycle_impact(customer.id)
assert preview['can_delete'] is True
db.session.add(ShippingCase(case_no='CASE-DELETE-RACE', customer_id=customer.id))
db.session.commit()
with pytest.raises(ConflictError) as exc_info:
delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None)
assert exc_info.value.code == 'SHIPPING.CUSTOMER_DELETE_BLOCKED'
assert exc_info.value.details['blockers']['business_cases'] == 1
assert db.session.get(ShippingCustomer, customer.id) is not None
def test_customer_lifecycle_timeline_returns_snapshot_events(app):
"""时间线按最新事件倒序返回当前客户的快照审计,不混入其他客户记录。"""
with app.app_context():
customer = _customer('TIM')
other = _customer('OTH')
db.session.add_all([
ShippingCustomerLifecycleEvent(
event_type='created', customer_id_snapshot=customer.id,
customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code,
detail_json={'after': {'short_code': 'TIM'}},
),
ShippingCustomerLifecycleEvent(
event_type='created', customer_id_snapshot=other.id,
customer_name_snapshot=other.standard_name, customer_short_code_snapshot=other.short_code,
detail_json={},
),
])
db.session.commit()
result = get_customer_lifecycle_timeline(customer.id)
assert result['customer']['id'] == customer.id
assert len(result['items']) == 1
assert result['items'][0]['event_type'] == 'created'
def test_customer_lifecycle_timeline_replays_deleted_customer_snapshot(app):
"""永久删除后仍能通过事件快照读取时间线,不能因主表不存在而丢失审计。"""
with app.app_context():
customer = _customer('DEL')
db.session.commit()
delete_customer(customer.id, confirmation_short_code='DEL', reason='误建', actor_id=None)
result = get_customer_lifecycle_timeline(customer.id)
assert result['customer'] == {
'id': customer.id,
'standard_name': '客户 DEL',
'short_code': 'DEL',
'status': 'deleted',
}
assert result['items'][0]['event_type'] == 'deleted'
@@ -0,0 +1,185 @@
"""
tests/services/admin/test_shipping_customer_merge_service.py
用途:验证客户归并只迁移未来配置,不改写历史业务与审计引用。
依赖:客户模型、合并服务、内存数据库。
逻辑:覆盖正常归并、重复证据去重、受控校验以及归并后的删除资格保护。
"""
from __future__ import annotations
from datetime import date
import pytest
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerMerge,
ShippingCustomerShadowResolution,
)
from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact
from app.services.admin.shipping_customer_merge_service import get_customer_merge_impact, merge_customer
from app.services.admin.shipping_customer_service import update_customer
from app.services.admin.shipping_customer_service import create_identifier, update_identifier
from app.services.shipping_notice.customer_identity_gate import list_customer_options
from app.services.shipping_notice.customer_shadow_resolution import label_shadow_resolution
def _customer(name: str, code: str, *, status: str = 'active') -> ShippingCustomer:
"""创建最小客户记录,供归并两端和非法状态测试复用。"""
customer = ShippingCustomer(standard_name=name, short_code=code, status=status)
db.session.add(customer)
db.session.flush()
return customer
def test_merge_moves_future_configuration_and_preserves_history(app):
"""归并迁移证据和来源键,但业务单、流水及其客户快照始终保留源客户。"""
with app.app_context():
source = _customer('重复客户', 'SRC')
target = _customer('标准客户', 'TGT')
db.session.add_all([
ShippingCustomerIdentifier(
customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias',
normalized_value='SOURCEALIAS', status='approved', source='manual',
),
ShippingCustomerIdentifier(
customer_id=source.id, identifier_type='email', raw_value='same@example.com',
normalized_value='same@example.com', status='approved', source='manual',
),
ShippingCustomerIdentifier(
customer_id=target.id, identifier_type='email', raw_value='same@example.com',
normalized_value='same@example.com', status='approved', source='manual',
),
ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'),
ShippingCase(
case_no='CASE-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
),
ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1),
])
db.session.commit()
source_id = source.id
target_id = target.id
preview = get_customer_merge_impact(source_id, target_id)
assert preview['historical_references']['business_cases'] == 1
assert preview['migrate'] == {
'identifiers': 1, 'duplicate_identifiers': 1, 'external_references': 1, 'sites': 0,
}
result = merge_customer(
source_id, target_customer_id=target_id, confirmation_short_code='SRC', reason='重复建档', actor_id=None,
)
assert result['migrate'] == {
'identifiers': 1, 'duplicate_identifiers': 1, 'external_references': 1, 'sites': 0,
}
source_after = db.session.get(ShippingCustomer, source_id)
target_after = db.session.get(ShippingCustomer, target_id)
assert source_after is not None and source_after.status == 'merged'
assert source_after.merged_into_customer_id == target_id
assert target_after is not None and target_after.status == 'active'
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source_id).count() == 0
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2
assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1
historical_case = db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-HISTORY').one()
assert historical_case.customer_id == source_id
assert historical_case.business_no == 'SRC26071601'
assert historical_case.customer_short_code_snapshot == 'SRC'
assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1
merge = db.session.get(ShippingCustomerMerge, result['merge_id'])
assert merge is not None and merge.source_customer_id_snapshot == source_id
assert db.session.query(ShippingCustomerLifecycleEvent).filter_by(event_type='merged_source').count() == 1
assert db.session.query(ShippingCustomerLifecycleEvent).filter_by(event_type='merged_target').count() == 1
assert {item['id'] for item in list_customer_options()} == {target_id}
@pytest.mark.parametrize('mode', ['same', 'inactive_target', 'wrong_confirmation', 'missing_reason'])
def test_merge_rejects_invalid_request(app, mode: str):
"""归并请求必须选择不同的启用目标客户,并由服务端校验简码和原因。"""
with app.app_context():
source = _customer('源客户', 'SRC')
target = _customer('目标客户', 'TGT', status='inactive' if mode == 'inactive_target' else 'active')
db.session.commit()
kwargs = {
'target_customer_id': source.id if mode == 'same' else target.id,
'confirmation_short_code': 'BAD' if mode == 'wrong_confirmation' else 'SRC',
'reason': '' if mode == 'missing_reason' else '重复',
'actor_id': None,
}
expected = {
'same': 'SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER',
'inactive_target': 'SHIPPING.CUSTOMER_MERGE_TARGET_INVALID',
'wrong_confirmation': 'SHIPPING.CUSTOMER_MERGE_CONFIRMATION_INVALID',
'missing_reason': 'SHIPPING.CUSTOMER_MERGE_REASON_REQUIRED',
}[mode]
with pytest.raises((ConflictError, ValidationError)) as exc_info:
merge_customer(source.id, **kwargs)
assert exc_info.value.code == expected
assert db.session.get(ShippingCustomer, source.id).status == 'active'
def test_merged_customer_cannot_be_edited_or_merged_twice_and_blocks_deletion(app):
"""源客户归并后锁定,且源/目标均必须被删除资格服务拒绝。"""
with app.app_context():
source = _customer('源客户', 'SRC')
target = _customer('目标客户', 'TGT')
db.session.commit()
merge_customer(source.id, target_customer_id=target.id, confirmation_short_code='SRC', reason='重复', actor_id=None)
with pytest.raises(ConflictError) as edit_error:
update_customer(source.id, {'remark': 'cannot edit'}, actor_id=None)
assert edit_error.value.code == 'SHIPPING.CUSTOMER_MERGED_LOCKED'
with pytest.raises(ConflictError) as merge_error:
merge_customer(source.id, target_customer_id=target.id, confirmation_short_code='SRC', reason='again', actor_id=None)
assert merge_error.value.code == 'SHIPPING.CUSTOMER_MERGE_SOURCE_ALREADY_MERGED'
source_impact = get_customer_lifecycle_impact(source.id)
target_impact = get_customer_lifecycle_impact(target.id)
assert source_impact['blockers']['merged_into_customer'] == 1
assert target_impact['blockers']['merged_source_customers'] == 1
def test_merged_customer_cannot_receive_future_identifier_or_shadow_label(app):
"""归并后所有新的识别入口都必须拒绝源客户,避免未来任务重新命中旧身份。"""
with app.app_context():
source = _customer('源客户', 'SRC')
target = _customer('目标客户', 'TGT')
db.session.add(ShippingCustomerIdentifier(
customer_id=source.id, identifier_type='name_alias', raw_value='Old Alias',
normalized_value='OLDALIAS', status='approved', source='manual',
))
db.session.commit()
merge_customer(source.id, target_customer_id=target.id, confirmation_short_code='SRC', reason='重复', actor_id=None)
with pytest.raises(ConflictError) as create_error:
create_identifier(source.id, {
'identifier_type': 'name_alias', 'identifier_value': 'New Alias', 'status': 'pending',
}, actor_id=None)
assert create_error.value.code == 'SHIPPING.CUSTOMER_MERGED_LOCKED'
# 原证据已经归并至目标;直接构造源客户证据编辑场景以验证服务端防御。
blocked_identifier = ShippingCustomerIdentifier(
customer_id=source.id, identifier_type='contact', raw_value='Old Contact',
normalized_value='OLDCONTACT', status='pending', source='manual',
)
db.session.add(blocked_identifier)
db.session.commit()
with pytest.raises(ConflictError) as update_error:
update_identifier(blocked_identifier.id, {'status': 'approved'}, actor_id=None)
assert update_error.value.code == 'SHIPPING.CUSTOMER_MERGED_LOCKED'
shadow = ShippingCustomerShadowResolution(
candidate_id=9000 + source.id, intake_id=9000 + source.id,
resolution_version='shadow-v1', status='unmatched', evidence_json=[], candidate_matches_json=[],
)
db.session.add(shadow)
db.session.commit()
with pytest.raises(ConflictError) as label_error:
label_shadow_resolution(shadow.id, customer_id=source.id, actor_id=None)
assert label_error.value.code == 'SHIPPING.CUSTOMER_MERGED_LOCKED'
@@ -13,11 +13,12 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier
from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent
from app.services.admin.shipping_customer_service import (
create_customer,
create_identifier,
list_customers,
update_customer,
update_identifier,
)
@@ -113,7 +114,11 @@ def test_identifier_loses_auto_match_when_approval_is_revoked(app):
actor_id=None,
)
updated = update_identifier(identifier['id'], {'status': 'pending'}, actor_id=None)
updated = update_identifier(
identifier['id'],
{'status': 'pending', 'reason': '识别证据失效'},
actor_id=None,
)
assert updated['status'] == 'pending'
assert updated['auto_match_allowed'] is False
@@ -136,7 +141,7 @@ def test_identifier_validation_failure_does_not_leave_dirty_state(app):
with pytest.raises(ValidationError) as exc_info:
update_identifier(
identifier['id'],
{'status': 'pending', 'auto_match_allowed': True},
{'status': 'pending', 'auto_match_allowed': True, 'reason': '验证失败'},
actor_id=None,
)
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED'
@@ -145,6 +150,71 @@ def test_identifier_validation_failure_does_not_leave_dirty_state(app):
assert persisted.auto_match_allowed is True
def test_lifecycle_events_capture_customer_and_identifier_governance_changes(app):
"""客户简码、状态及证据自动授权变更必须留存前后快照和操作者原因。"""
with app.app_context():
customer = _create_customer()
updated = update_customer(
customer['id'],
{'short_code': 'NEW', 'status': 'inactive', 'reason': '客户资料纠正'},
actor_id=42,
)
identifier = create_identifier(
customer['id'],
{
'identifier_type': 'domain',
'identifier_value': 'wyc.example.com',
'status': 'approved',
'auto_match_allowed': False,
},
actor_id=42,
)
update_identifier(
identifier['id'],
{'auto_match_allowed': True, 'reason': '人工审核后授权'},
actor_id=42,
)
events = ShippingCustomerLifecycleEvent.query.order_by(ShippingCustomerLifecycleEvent.id).all()
assert [item.event_type for item in events] == ['created', 'updated', 'identifier_created', 'identifier_updated']
assert events[1].reason == '客户资料纠正'
assert events[1].detail_json['changes']['short_code'] == {'before': 'WYC', 'after': 'NEW'}
assert events[1].detail_json['changes']['status'] == {'before': 'active', 'after': 'inactive'}
assert events[-1].reason == '人工审核后授权'
assert events[-1].detail_json['changes']['auto_match_allowed'] == {'before': False, 'after': True}
assert updated['short_code'] == 'NEW'
def test_high_risk_governance_changes_require_reason(app):
"""简码、状态和自动匹配授权属于高风险变更,服务端不能依赖前端补原因。"""
with app.app_context():
customer = _create_customer()
with pytest.raises(ValidationError) as customer_error:
update_customer(customer['id'], {'short_code': 'NEW'}, actor_id=None)
assert customer_error.value.code == 'SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED'
persisted_customer = db.session.get(ShippingCustomer, customer['id'])
assert persisted_customer.short_code == 'WYC'
unchanged = update_customer(customer['id'], {'standard_name': '无锡宇辰精密有限公司'}, actor_id=None)
assert unchanged['standard_name'] == '无锡宇辰精密有限公司'
identifier = create_identifier(
customer['id'],
{
'identifier_type': 'domain',
'identifier_value': 'wyc.example.com',
'status': 'approved',
'auto_match_allowed': False,
},
actor_id=None,
)
with pytest.raises(ValidationError) as identifier_error:
update_identifier(identifier['id'], {'auto_match_allowed': True}, actor_id=None)
assert identifier_error.value.code == 'SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED'
persisted_identifier = db.session.get(ShippingCustomerIdentifier, identifier['id'])
assert persisted_identifier.auto_match_allowed is False
def test_customer_list_returns_preaggregated_reference_counts(app):
"""列表返回业务单和识别证据数量,避免管理端逐客户补查。"""
with app.app_context():
@@ -0,0 +1,402 @@
"""
tests/services/admin/test_shipping_inventory_service.py
用途:验证库存主数据管理服务的安全性和关键业务约束。
依赖:Flask app/db、shipping_inventory_service、库存配置模型。
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
"""
from __future__ import annotations
from cryptography.fernet import Fernet
import pytest
from app.core.errors import ConflictError, ValidationError
from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import inventory_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service
from app import db
from app.models import ShippingExcelTemplate, ShippingInventoryField
def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict:
return {
'profile_code': code, 'display_name': code, 'connector_type': connector_type,
'login_url': 'https://example.invalid/login', 'login_config_json': {'auth_mode': 'password'},
'username': 'test-user', 'password': 'test-password', 'enabled': True,
}
def _parsing_profile() -> dict:
"""发布可由多个库存源共享的最小库存解析 Profile。"""
state = order_schema_service.get_state()
if state['schema'] is None:
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
fields = {item['field_code']: item for item in order_schema_service.get_state()['fields']}
for code in ('part_number', 'reservation_id'):
if code not in fields:
fields[code] = order_schema_service.save_field(
{'field_code': code, 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
if not any(item['status'] == 'published' for item in order_schema_service.get_state()['versions']):
schema_draft = order_schema_service.create_draft({}, actor_id=None)
saved_schema = order_schema_service.save_draft(schema_draft['id'], {'fields': [{
'field_id': field['id'], 'display_name': code, 'required': True, 'aliases': [],
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_table'],
'conflict_policy': 'block', 'allow_single_source': True,
},
'relation_role': None, 'comparator_key': 'normalized_text',
'extraction_instruction': f'提取订单行 {code}',
} for code, field in fields.items()], 'expected_lock_version': schema_draft['lock_version']})
order_schema_service.publish(
schema_draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
)
inventory_fields = {
item.field_code: str(item.id)
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
ShippingInventoryField.status == 'active',
).all()
}
assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'}
draft = inventory_parsing_profile.save_draft({
'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx',
'definition': {
'header_row_index': 1,
'field_mapping': {
inventory_fields['part_number']: 'Supplier Sku',
inventory_fields['reservation_id']: 'Reservation ID',
inventory_fields['available_qty']: 'Qty Available',
},
'match_keys': [{
'order_field_id': fields['part_number']['id'],
'inventory_field_id': inventory_fields['part_number'],
}],
},
}, actor_id=None)
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
def _excel_template_id() -> int:
"""创建库存源绑定所需的最小已发布 Excel 模板版本。"""
current = ShippingExcelTemplate.query.filter_by(template_code='COMMON_EXPORT').first()
if current:
return current.id
current = ShippingExcelTemplate(
template_code='COMMON_EXPORT', display_name='Common Export', version=1, status='published',
storage_provider='minio', storage_bucket='test', storage_key='test/common-export.xlsx',
original_filename='template.xlsx',
file_checksum='0' * 64, definition_json={'filename_pattern': 'shipment_{task_no}.xlsx', 'mappings': []},
definition_checksum='1' * 64,
)
db.session.add(current)
db.session.flush()
return current.id
def _source_data(profile_id: int, *, parsing_profile_id: int | None = None, code: str = 'DBS_DUB', connector_type: str = 'dbs') -> dict:
return {
'source_code': code, 'display_name': code, 'connector_type': connector_type,
'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'],
'excel_template_id': _excel_template_id(),
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB',
'snapshot_ttl_seconds': 3600, 'enabled': True,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
},
'query_parameters_json': [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
],
'match_aliases_json': ['DUB'],
}
def test_profile_credentials_are_not_returned(app):
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
assert payload['password_configured'] is True
assert payload['username_masked'] == 'configured'
assert 'password' not in payload
assert 'ciphertext' not in payload
def test_profile_rejects_page_operation_configuration(app):
"""货代登录连接不得保存报表路径、selector 或下载策略,防止连接越界成为业务配置源。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = _profile_data()
payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}}
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_profile(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_CONFIG_INVALID'
def test_multiple_dbs_profiles_bind_independent_sources(app):
"""同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
second = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
first_source = shipping_inventory_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None)
second_source = shipping_inventory_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None)
assert first_source['rpa_profile_id'] == first['id']
assert second_source['rpa_profile_id'] == second['id']
def test_source_rejects_profile_connector_mismatch(app):
"""库存源不能绑定不同 Driver 的 Profile。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH'
def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
"""禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='DRAFT_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
draft = shipping_inventory_service.save_source(payload, actor_id=None)
assert draft['enabled'] is False
assert draft['parsing_profile_id'] is None
assert draft['excel_template_id'] is None
payload.update({'enabled': True})
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id'])
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED'
payload.update({
'parsing_profile_id': _parsing_profile()['id'],
'excel_template_id': _excel_template_id(),
})
enabled = shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id'])
assert enabled['enabled'] is True
def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
"""普通保存只能保留停用站点;独立启用动作必须返回尚未完成的测试步骤。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='ACTIVATION_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
assert draft['activation']['ready'] is False
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
payload['enabled'] = True
saved = shipping_inventory_service.save_source(
payload, actor_id=None, source_id=draft['id'], allow_enable_transition=False,
)
assert saved['enabled'] is False
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.activate_source(draft['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
def test_enabled_source_rejects_disabled_rpa_profile(app):
"""启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(
{**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None,
)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None)
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLED'
def test_dbs_source_persists_report_path_parameters_and_aliases(app):
"""数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
assert source['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv'
assert source['query_parameters_json'] == [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
]
assert source['match_aliases_json'] == ['DUB']
def test_source_rejects_driver_selector_in_business_parameters(app):
"""业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
payload = _source_data(profile['id'])
payload['query_parameters_json'][0]['selector_env'] = 'SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
def test_crane_source_rejects_dbs_report_path(app):
"""动态仓 Crane 库存源不得误填 DBS 四级报表路径。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
payload = _source_data(profile['id'], code='CRANE', connector_type='crane')
payload['warehouse_resolution_mode'] = 'inventory_match'
payload['fixed_warehouse_id'] = None
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
def test_published_rule_cannot_be_mutated_in_place(app):
"""发布规则必须依靠新版本演进,避免改写历史任务依据。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
rule = shipping_inventory_service.save_rule({
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Reservation starts with 1', 'scope': 'line',
'priority': 100, 'match_mode': 'all', 'action_type': 'add_source_candidates',
'action_payload_json': {'source_codes': [source['source_code']]}, 'version': 1,
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None)
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.save_rule({
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Changed', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None, rule_id=rule['id'])
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_IMMUTABLE'
def test_draft_rule_update_keeps_the_same_draft(app):
"""草稿更新应原地替换条件,不能偷偷新增同版本规则记录。"""
with app.app_context():
rule = shipping_inventory_service.save_rule({
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'Before', 'scope': 'task',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'task.destination_port', 'operator': 'equals', 'expected_value_json': 'DUB'}],
}, actor_id=None)
updated = shipping_inventory_service.save_rule({
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'After', 'scope': 'task',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'task.destination_port', 'operator': 'equals', 'expected_value_json': 'FRA'}],
}, actor_id=None, rule_id=rule['id'])
assert updated['id'] == rule['id']
assert updated['rule_name'] == 'After'
assert updated['conditions'][0]['expected_value_json'] == 'FRA'
def test_rule_condition_value_type_follows_the_selected_operator(app):
"""列表、长度和空值操作符必须保存受控值类型,不能把配置错误拖到运行期。"""
with app.app_context():
rule = shipping_inventory_service.save_rule({
'rule_code': 'RSV_IN', 'rule_name': 'Reservation list', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'in', 'expected_value_json': ['1001', '1002']}],
}, actor_id=None)
assert rule['conditions'][0]['expected_value_json'] == ['1001', '1002']
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_rule({
'rule_code': 'RSV_BAD_IN', 'rule_name': 'Invalid list', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'in', 'expected_value_json': '1001'}],
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_CONDITION_INVALID'
def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
"""未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
shipping_inventory_service.delete_profile(unused['id'])
assert all(item['profile_code'] != 'UNUSED' for item in shipping_inventory_service.list_profiles())
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.delete_profile(profile['id'])
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DELETE_BLOCKED'
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id'])
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLE_BLOCKED'
rule = shipping_inventory_service.save_rule({
'rule_code': 'RETIRE_ME', 'rule_name': 'Retire me', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None)
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
retired = shipping_inventory_service.retire_rule(rule['id'], actor_id=None)
assert retired['status'] == 'retired'
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.delete_draft_rule(rule['id'])
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_DELETE_BLOCKED'
def test_publish_rule_rejects_missing_or_disabled_source(app):
"""发布规则只能引用启用库存源,避免运行期落入无法确认的伪候选。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None)
disabled_payload = _source_data(profile['id'], code='DISABLED_ROUTE_SOURCE')
disabled_payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
shipping_inventory_service.save_source(disabled_payload, actor_id=None)
for index, code in enumerate(('MISSING_SOURCE', 'DISABLED_ROUTE_SOURCE'), start=1):
rule = shipping_inventory_service.save_rule({
'rule_code': f'INVALID_SOURCE_{index}', 'rule_name': 'Invalid source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [code]},
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': str(index)}],
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID'
valid_rule = shipping_inventory_service.save_rule({
'rule_code': 'VALID_SOURCE', 'rule_name': 'Valid source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '9'}],
}, actor_id=None)
assert shipping_inventory_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published'
def test_active_default_external_mapping_is_unique_per_source(app):
"""同一库存源只能有一条启用的默认外部系统映射。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
payload = {
'inventory_source_id': source['id'], 'external_system_code': 'TOPGP', 'external_organization_code': None,
'external_site_code': 'EU01', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
}
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
with pytest.raises(ConflictError):
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
def test_external_mapping_normalizes_freight_warehouse_identity(app):
"""配置端小写货代仓应与库存行大写 Warehouse 使用同一精确映射身份。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
mapping = shipping_inventory_service.save_external_mapping({
'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub',
'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01',
'external_warehouse_name': 'Dublin', 'enabled': True,
}, actor_id=None)
assert mapping['freight_warehouse_id'] == 'DUB'
+212 -13
View File
@@ -13,6 +13,7 @@ from app.models import (
FileAsset,
ShippingCase,
ShippingCustomer,
ShippingCustomerIdentifier,
ShippingCustomerShadowResolution,
ShippingNoticeCandidate,
ShippingNoticeDocument,
@@ -80,29 +81,227 @@ def test_shipping_customer_admin_routes_reject_non_admin(app, client):
assert parse_api_error(response.get_json())['code'] == 'AUTH.FORBIDDEN'
def test_shipping_customer_historical_backfill_api_does_not_number(app, client):
"""管理员可为历史任务回填客户,且响应与业务单均不生成历史业务号。"""
def test_shipping_customer_lifecycle_impact_api_is_admin_only(app, client):
"""生命周期影响预览返回统一结构,普通用户不能读取删除资格。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
customer = ShippingCustomer(standard_name='历史客户', short_code='HIS', status='active')
task = ShippingTask(task_no='SN-20200101-HISTAPI', source_type='manual', process_status='closed')
db.session.add_all([customer, task])
customer = ShippingCustomer(standard_name='生命周期客户', short_code='LIF', status='active')
db.session.add(customer)
db.session.commit()
customer_id = customer.id
response = client.post(
'/api/admin/shipping-customers/historical-task-backfill',
json={'task_no': 'SN-20200101-HISTAPI', 'customer_id': customer_id},
forbidden = client.get(
f'/api/admin/shipping-customers/{customer_id}/lifecycle-impact',
headers=_headers('shipping-user', 'user'),
)
assert forbidden.status_code == 403
response = client.get(
f'/api/admin/shipping-customers/{customer_id}/lifecycle-impact',
headers=_headers('shipping-admin', 'admin'),
)
assert response.status_code == 200
payload = parse_api_data(response.get_json())
assert payload['business_no'] is None
impact = parse_api_data(response.get_json())
assert impact['can_delete'] is True
assert impact['cascade']['identifiers'] == 0
def test_shipping_customer_timeline_and_governance_quality_apis_are_admin_only(app, client):
"""治理时间线和质量汇总必须复用管理员权限,并返回自动确认门禁状态。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
persisted = ShippingTask.query.filter_by(task_no='SN-20200101-HISTAPI').one()
assert persisted.shipping_case.business_no is None
assert persisted.shipping_case.numbering_status == 'historical_unnumbered'
_create_users()
customer = ShippingCustomer(standard_name='时间线客户', short_code='TIM', status='active')
db.session.add(customer)
db.session.flush()
from app.models import ShippingCustomerLifecycleEvent
db.session.add(ShippingCustomerLifecycleEvent(
event_type='created', customer_id_snapshot=customer.id,
customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code,
detail_json={},
))
db.session.commit()
customer_id = customer.id
admin_headers = _headers('shipping-admin', 'admin')
for path in (
f'/api/admin/shipping-customers/{customer_id}/lifecycle-timeline',
'/api/admin/shipping-customers/governance-quality',
):
forbidden = client.get(path, headers=_headers('shipping-user', 'user'))
assert forbidden.status_code == 403
timeline = client.get(
f'/api/admin/shipping-customers/{customer_id}/lifecycle-timeline', headers=admin_headers,
)
assert timeline.status_code == 200
assert parse_api_data(timeline.get_json())['items'][0]['event_type'] == 'created'
quality = client.get('/api/admin/shipping-customers/governance-quality', headers=admin_headers)
assert quality.status_code == 200
payload = parse_api_data(quality.get_json())
assert payload['shadow_quality']['total'] == 0
assert payload['shadow_quality']['auto_resolution']['quality_gate']['status'] == 'insufficient_labeled_samples'
assert payload['lifecycle_event_counts']['created'] == 1
def test_shipping_customer_delete_api_is_admin_only_and_audited(app, client):
"""删除 API 仅管理员可用,并在成功后保留客户快照审计。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
customer = ShippingCustomer(standard_name='可删除客户', short_code='DEL', status='active')
db.session.add(customer)
db.session.flush()
db.session.add(ShippingCustomerIdentifier(
customer_id=customer.id, identifier_type='name_alias', raw_value='Delete Customer',
normalized_value='DELETECUSTOMER', status='approved', source='manual',
))
db.session.commit()
customer_id = customer.id
payload = {'confirmation_short_code': 'DEL', 'reason': '误建'}
forbidden = client.delete(
f'/api/admin/shipping-customers/{customer_id}', json=payload,
headers=_headers('shipping-user', 'user'),
)
assert forbidden.status_code == 403
response = client.delete(
f'/api/admin/shipping-customers/{customer_id}', json=payload,
headers=_headers('shipping-admin', 'admin'),
)
assert response.status_code == 200
deleted = parse_api_data(response.get_json())
assert deleted['deleted_customer']['id'] == customer_id
assert deleted['cascade']['identifiers'] == 1
missing = client.get(f'/api/admin/shipping-customers/{customer_id}', headers=_headers('shipping-admin', 'admin'))
assert missing.status_code == 404
def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(app, client):
"""API 必须校验二次确认,并在删除提交时返回完整阻断明细。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active')
db.session.add(customer)
db.session.flush()
db.session.add(ShippingCase(case_no='CASE-DELETE-API', customer_id=customer.id))
db.session.commit()
customer_id = customer.id
headers = _headers('shipping-admin', 'admin')
invalid = client.delete(
f'/api/admin/shipping-customers/{customer_id}',
json={'confirmation_short_code': 'BAD', 'reason': '误建'}, headers=headers,
)
assert invalid.status_code == 400
assert parse_api_error(invalid.get_json())['code'] == 'SHIPPING.CUSTOMER_DELETE_CONFIRMATION_INVALID'
blocked = client.delete(
f'/api/admin/shipping-customers/{customer_id}',
json={'confirmation_short_code': 'BLK', 'reason': '误建'}, headers=headers,
)
assert blocked.status_code == 409
error = parse_api_error(blocked.get_json())
assert error['code'] == 'SHIPPING.CUSTOMER_DELETE_BLOCKED'
assert error['details']['blockers']['business_cases'] == 1
def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(app, client):
"""管理员归并客户时仅迁移未来证据,源客户历史业务仍保持原关联。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingCustomer(standard_name='重复客户', short_code='SRC', status='active')
target = ShippingCustomer(standard_name='标准客户', short_code='TGT', status='active')
db.session.add_all([source, target])
db.session.flush()
db.session.add_all([
ShippingCustomerIdentifier(
customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias',
normalized_value='SOURCEALIAS', status='approved', source='manual',
),
ShippingCase(case_no='CASE-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
])
db.session.commit()
source_id = source.id
target_id = target.id
admin_headers = _headers('shipping-admin', 'admin')
forbidden = client.post(
f'/api/admin/shipping-customers/{source_id}/merge',
json={'target_customer_id': target_id, 'confirmation_short_code': 'SRC', 'reason': '重复建档'},
headers=_headers('shipping-user', 'user'),
)
assert forbidden.status_code == 403
preview = client.get(
f'/api/admin/shipping-customers/{source_id}/merge-impact?target_customer_id={target_id}',
headers=admin_headers,
)
assert preview.status_code == 200
assert parse_api_data(preview.get_json())['historical_references']['business_cases'] == 1
response = client.post(
f'/api/admin/shipping-customers/{source_id}/merge',
json={'target_customer_id': target_id, 'confirmation_short_code': 'SRC', 'reason': '重复建档'},
headers=admin_headers,
)
assert response.status_code == 200
result = parse_api_data(response.get_json())
assert result['source']['id'] == source_id
assert result['target']['id'] == target_id
with app.app_context():
assert db.session.get(ShippingCustomer, source_id).status == 'merged'
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1
assert db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-API').one().customer_id == source_id
def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client):
"""合并 API 由服务端校验目标状态、源简码与原因,不能依赖前端限制。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingCustomer(standard_name='源客户', short_code='SRC', status='active')
target = ShippingCustomer(standard_name='停用目标', short_code='TGT', status='inactive')
db.session.add_all([source, target])
db.session.commit()
source_id = source.id
target_id = target.id
headers = _headers('shipping-admin', 'admin')
invalid_target = client.post(
f'/api/admin/shipping-customers/{source_id}/merge',
json={'target_customer_id': target_id, 'confirmation_short_code': 'SRC', 'reason': '重复'}, headers=headers,
)
assert invalid_target.status_code == 400
assert parse_api_error(invalid_target.get_json())['code'] == 'SHIPPING.CUSTOMER_MERGE_TARGET_INVALID'
empty_reason = client.post(
f'/api/admin/shipping-customers/{source_id}/merge',
json={'target_customer_id': source_id, 'confirmation_short_code': 'SRC', 'reason': ''}, headers=headers,
)
assert empty_reason.status_code == 400
assert parse_api_error(empty_reason.get_json())['code'] == 'SHIPPING.CUSTOMER_MERGE_REASON_REQUIRED'
def test_shipping_customer_historical_backfill_api_is_not_registered(app, client):
"""新契约不保留历史客户回填入口,管理员也不能调用。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
response = client.post(
'/api/admin/shipping-customers/historical-task-backfill',
json={'task_no': 'SN-20200101-HISTAPI', 'customer_id': 1},
headers=_headers('shipping-admin', 'admin'),
)
assert response.status_code == 404
def test_shipping_customer_shadow_report_and_label_api(app, client):
@@ -0,0 +1,178 @@
"""
tests/test_admin_shipping_inventory.py
用途:验证货代库存后台的只读快照/导出记录接口及管理员权限。
依赖:Flask 测试客户端、库存文件和排程运行模型。
逻辑:库存快照来自库存文件;没有库存文件的失败 RPA 运行也必须出现在导出记录中。
"""
from __future__ import annotations
from datetime import datetime
from pathlib import Path
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, User
from app.models import ShippingInventorySource, ShippingRpaProfile
from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import parse_api_data, parse_api_error
def _create_users() -> None:
"""创建接口权限验证所需的管理员和普通用户。"""
db.session.add_all([
User(username='inventory-admin', email='inventory-admin@example.com', role='admin', status='active'),
User(username='inventory-user', email='inventory-user@example.com', role='user', status='active'),
])
db.session.commit()
def _headers(username: str, role: str) -> dict[str, str]:
"""构造遗留 Header 认证上下文,匹配现有管理 API 测试方式。"""
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_path):
"""快照和导出记录仅管理员可读,且失败排程不因无库存文件而丢失。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
snapshot_file = Path(tmp_path) / 'snapshot.xlsx'
snapshot_file.write_bytes(b'admin-snapshot')
file_record = ShippingInventoryFile(
inventory_file_no='SIF-ADMIN-READY', storage_path=str(snapshot_file), source_code='DBS_DUB',
warehouse_id='DUB', snapshot_status='ready', identity_status='verified',
exported_at=datetime(2026, 7, 17, 10, 0, 0), rpa_run_no='RUN-READY-01',
)
schedule_task = ScheduleTask(
schedule_no='SCH-INVENTORY-FAILED', name='Inventory Export', schedule_type='platform_job',
owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='shipping-inventory-rpa',
)
db.session.add_all([file_record, schedule_task])
db.session.flush()
db.session.add(ScheduleRun(
run_no='RUN-FAILED-01', schedule_task_id=schedule_task.id, status='failed',
api_request_json={'run_no': 'RUN-FAILED-01', 'source_codes': ['CRANE']},
error_message='login timeout', created_at=datetime(2026, 7, 17, 11, 0, 0),
))
db.session.commit()
for path in ('/api/admin/shipping-notice/snapshots', '/api/admin/shipping-notice/export-records'):
forbidden = client.get(path, headers=_headers('inventory-user', 'user'))
assert forbidden.status_code == 403
assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN'
snapshots = client.get('/api/admin/shipping-notice/snapshots', headers=_headers('inventory-admin', 'admin'))
assert snapshots.status_code == 200
snapshot_rows = parse_api_data(snapshots.get_json())
assert snapshot_rows[0]['inventory_file_no'] == 'SIF-ADMIN-READY'
assert 'storage_path' not in snapshot_rows[0]
assert snapshot_rows[0]['download_available'] is True
downloaded = client.get('/api/admin/shipping-notice/snapshots/1/download', headers=_headers('inventory-admin', 'admin'))
assert downloaded.status_code == 200
assert downloaded.data == b'admin-snapshot'
exports = client.get('/api/admin/shipping-notice/export-records', headers=_headers('inventory-admin', 'admin'))
assert exports.status_code == 200
export_rows = parse_api_data(exports.get_json())
failed_row = next(item for item in export_rows if item['rpa_run_no'] == 'RUN-FAILED-01')
assert failed_row['snapshot_status'] == 'failed'
assert failed_row['source_code'] == 'CRANE'
assert failed_row['error_message'] == 'login timeout'
def test_inventory_configuration_catalog_is_admin_only_and_backend_controlled(app, client):
"""结构化配置目录仅管理员可读,字段和白名单均来自当前后端契约。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = order_schema_service.save_field({
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
draft = order_schema_service.create_draft({}, actor_id=None)
saved = order_schema_service.save_draft(draft['id'], {'fields': [{
'field_id': field['id'], 'display_name': '内部料号', 'required': True,
'aliases': [], 'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_table'],
'conflict_policy': 'block', 'allow_single_source': True,
},
'relation_role': None, 'comparator_key': 'normalized_text',
'extraction_instruction': '提取内部料号',
}], 'expected_lock_version': draft['lock_version']})
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
path = '/api/admin/shipping-notice/configuration-catalog'
forbidden = client.get(path, headers=_headers('inventory-user', 'user'))
assert forbidden.status_code == 403
response = client.get(path, headers=_headers('inventory-admin', 'admin'))
assert response.status_code == 200
catalog = parse_api_data(response.get_json())
assert catalog['order_fields'][0]['field_id'] == field['id']
assert {'内部料号', '预约号', '可用库存数量'} <= {
field['display_name'] for field in catalog['inventory_fields']
}
assert {'order_field', 'inventory_field', 'system_fact', 'constant'} == set(catalog['template_source_kinds'])
assert {'header', 'line'} == set(catalog['template_row_modes'])
assert 'decimal' in catalog['template_formatters']
def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app, client):
"""订单字段尚未发布时,库存配置页应得到空目录而不是将前置条件误报为 500。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
for path in (
'/api/admin/shipping-notice/routing-fields',
'/api/admin/shipping-notice/configuration-catalog',
):
response = client.get(path, headers=_headers('inventory-admin', 'admin'))
assert response.status_code == 200
catalog = parse_api_data(response.get_json())
assert catalog['order_schema_published'] is False
assert catalog['order_fields'] == []
def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_missing_steps(app, client):
"""管理端普通保存不允许跳过测试直接启用,独立启用接口应返回业务缺失项。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
profile = ShippingRpaProfile(
profile_code='API_ACTIVATION_LOGIN', display_name='API Activation', connector_type='dbs',
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
)
db.session.add(profile)
db.session.commit()
profile_id = profile.id
payload = {
'source_code': 'API_ACTIVATION_SOURCE', 'display_name': 'API Activation Source', 'connector_type': 'dbs',
'rpa_profile_id': profile_id, 'parsing_profile_id': None, 'excel_template_id': None,
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
'enabled': True,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand',
},
'query_parameters_json': [], 'match_aliases_json': [],
}
created = client.post('/api/admin/shipping-notice/sources', json=payload, headers=_headers('inventory-admin', 'admin'))
assert created.status_code == 201
source = parse_api_data(created.get_json())
assert source['enabled'] is False
assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
activation = client.post(
f"/api/admin/shipping-notice/sources/{source['id']}/activate",
json={}, headers=_headers('inventory-admin', 'admin'),
)
assert activation.status_code == 409
error = parse_api_error(activation.get_json())
assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
@@ -0,0 +1,101 @@
"""
backend/tests/test_admin_shipping_order_schema_history.py
用途:验证订单 Schema 历史版本分页和只读快照 API。
依赖:Flask 管理 API、订单 Schema service、测试用户模型。
逻辑:创建连续发布版本后,历史列表仅返回概要;详情固定读取发布快照并保持权限边界。
"""
from __future__ import annotations
from app import db
from app.models import User
from app.services.shipping_notice.order_schema import service
from tests.conftest import parse_api_data, parse_api_error
def _headers(username: str, role: str) -> dict[str, str]:
"""构造管理 API 使用的遗留 Header 身份。"""
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
def _config(field_id: str, *, display_name: str) -> dict:
"""构造可发布的 Header 文本字段规则。"""
return {
'field_id': field_id,
'display_name': display_name,
'required': True,
'aliases': ['PO'],
'normalizer_key': 'trim',
'validator_keys': ['non_empty'],
'enum_options': [],
'evidence_policy': {
'required': True,
'source_precedence': ['attachment_table'],
'conflict_policy': 'block',
'allow_single_source': True,
},
'relation_role': None,
'comparator_key': 'normalized_text',
'extraction_instruction': '提取采购订单号',
}
def _publish_version(field_id: str, *, display_name: str, source_version_id: int | None = None) -> dict:
"""创建、保存并发布一个版本,返回不可变发布快照。"""
draft = service.create_draft(
{'copy_from_version_id': source_version_id} if source_version_id else {}, actor_id=1,
)
saved = service.save_draft(draft['id'], {
'fields': [_config(field_id, display_name=display_name)],
'expected_lock_version': draft['lock_version'],
}, actor_id=1)
return service.publish(draft['id'], actor_id=1, expected_lock_version=saved['lock_version'])
def test_admin_can_list_and_view_immutable_schema_history(app, client):
"""历史列表分页返回概要,详情固定返回版本快照且普通用户无权访问。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
db.session.add_all([
User(id=1, username='schema-history-admin', email='schema-history-admin@example.com', role='admin', status='active', real_name='版本管理员'),
User(id=2, username='schema-history-user', email='schema-history-user@example.com', role='user', status='active'),
])
db.session.commit()
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=1)
field = service.save_field({
'field_code': 'po_number', 'scope': 'header', 'value_type': 'string',
}, actor_id=1)
first = _publish_version(field['id'], display_name='采购订单号')
second = _publish_version(field['id'], display_name='客户订单号', source_version_id=first['id'])
service.save_field({
'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string',
}, actor_id=1, field_id=field['id'])
forbidden = client.get('/api/admin/shipping-order-schema/versions', headers=_headers('schema-history-user', 'user'))
assert forbidden.status_code == 403
assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN'
response = client.get('/api/admin/shipping-order-schema/versions?page=1&page_size=1', headers=_headers('schema-history-admin', 'admin'))
assert response.status_code == 200
page = parse_api_data(response.get_json())
assert page['total'] == 2
assert page['items'][0]['id'] == second['id']
assert 'definition' not in page['items'][0]
assert page['items'][0]['published_by']['display_name'] == '版本管理员'
exact = client.get('/api/admin/shipping-order-schema/versions?version_number=1', headers=_headers('schema-history-admin', 'admin'))
assert exact.status_code == 200
assert parse_api_data(exact.get_json())['items'][0]['id'] == first['id']
first_detail = client.get(
f"/api/admin/shipping-order-schema/versions/{first['id']}", headers=_headers('schema-history-admin', 'admin'),
)
assert first_detail.status_code == 200
definition = parse_api_data(first_detail.get_json())['definition']
assert definition['fields'][0]['display_name'] == '采购订单号'
assert definition['fields'][0]['field_code'] == 'po_number'
state = client.get('/api/admin/shipping-order-schema', headers=_headers('schema-history-admin', 'admin'))
assert state.status_code == 200
assert [item['status'] for item in parse_api_data(state.get_json())['versions']] == ['published']
+44
View File
@@ -203,6 +203,50 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkey
assert "run.failed" not in event_names
def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, client, monkeypatch):
"""任务级库存附件必须进入 formal upload handler,而不是临时对话库存会话。"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
task_no = _create_task_for_user(user.id)
captured: dict[str, object] = {}
def fake_upload_inventory(received_task_no, upload):
captured['task_no'] = received_task_no
captured['filename'] = upload.filename
captured['content'] = upload.read()
return {
'status': 'ok', 'message': '库存文件已按发布方案解析。',
'data': {'schema_preview': {'headers': ['Supplier Sku']}, 'inventory_file_no': 'SIF-TURN-001'},
}
monkeypatch.setattr(
'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_inventory_file',
fake_upload_inventory,
)
res = client.post(
'/api/chat/turns/stream',
headers={'X-Username': user.username, 'X-Role': user.role},
data={
'agent_id': str(agent.id),
'input': json.dumps({
'type': 'upload_followup', 'display_text': '上传库存文件:task.xls',
'action_type': 'shipping.upload_inventory', 'payload': {'task_no': task_no},
}, ensure_ascii=False),
'files': (BytesIO(b'legacy-inventory'), 'task.xls'),
},
content_type='multipart/form-data',
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
assert 'run.failed' not in [item.get('event') for item in events]
assert captured == {'task_no': task_no, 'filename': 'task.xls', 'content': b'legacy-inventory'}
assistant_payloads = [item.get('data', {}).get('payload', {}) for item in events if item.get('event') == 'message.completed']
assert all('schema_preview' not in payload for payload in assistant_payloads)
def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path):
"""shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。"""
from io import BytesIO
+14 -15
View File
@@ -32,13 +32,11 @@ def test_fill_parameters_skips_warehouse(monkeypatch):
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR",
"mode": "single",
"values": ["TZR2"],
},
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_CRANE_OWNER_SELECTOR",
"mode": "single",
"values": ["OWNER1"],
},
@@ -49,7 +47,7 @@ def test_fill_parameters_skips_warehouse(monkeypatch):
select_or_fill=_fake_select,
)
assert calls == [("FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
assert calls == [("SHIPPING_NOTICE_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
def test_build_schedule_description_uses_short_uuid_hex(monkeypatch):
@@ -75,7 +73,7 @@ def test_build_schedule_description_hex_len_env():
text = module._build_schedule_description(
{"source_code": "CRANE_TZR2"},
None,
env=lambda name, default="": "16" if name == "FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
env=lambda name, default="": "16" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
)
assert len(text) == 16
@@ -114,7 +112,7 @@ def test_export_scheduled_report_flow(monkeypatch):
result = module.export_crane_inventory_report(
page,
{"navigation": {"download_mode": "scheduled_report"}, "parameters": [], "source_code": "CRANE_TZR2"},
{"parameters": [], "source_code": "CRANE_TZR2"},
trigger={"task_no": "SN-1001"},
env=lambda name, default="": default,
browser_timeout_ms=5_000,
@@ -128,8 +126,8 @@ def test_export_scheduled_report_flow(monkeypatch):
assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST"
def test_should_run_report_before_schedule_defaults_true():
"""默认必须先 Run Report;仅显式 run_before_schedule=false 可关闭。"""
def test_should_run_report_before_schedule_uses_driver_environment_only():
"""默认必须先 Run Report;业务配置不得关闭 Driver 步骤。"""
module = _load_export()
assert (
module._should_run_report_before_schedule(
@@ -143,12 +141,12 @@ def test_should_run_report_before_schedule_defaults_true():
{"navigation": {"run_before_schedule": False}},
env=lambda name, default="": default,
)
is False
is True
)
assert (
module._should_run_report_before_schedule(
{"navigation": {}},
env=lambda name, default="": "false" if name == "FREIGHT_RPA_CRANE_RUN_BEFORE_SCHEDULE" else default,
env=lambda name, default="": "false" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default,
)
is False
)
@@ -430,17 +428,18 @@ def test_is_crane_login_blocking_ignores_login_flash_when_table_visible():
session.is_crane_login_page = original
def test_resolve_scheduled_report_file_name_prefers_navigation_config():
"""scheduled_report_file_name 应优先于环境变量默认值。"""
def test_resolve_scheduled_report_file_name_ignores_source_navigation():
"""调度报表文件名是 Driver 模板策略,不读 Source navigation。"""
module = _load_export()
name = module._resolve_scheduled_report_file_name(
{"navigation": {"scheduled_report_file_name": "Custom.xlsx"}},
env=lambda name, default="": default,
)
assert name == "Custom.xlsx"
assert name == "OnHandDetails.xlsx"
def test_resolve_download_mode_defaults_to_scheduled_report():
"""未配置 download_mode 时默认走 scheduled_report。"""
def test_resolve_download_mode_uses_driver_environment_only():
"""下载模式只能由 Driver 环境变量决定。"""
module = _load_export()
assert module._resolve_download_mode({"navigation": {}}) == "scheduled_report"
assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report"
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
+5 -5
View File
@@ -108,15 +108,15 @@ def test_maybe_auto_login_crane_fills_username_password_and_clicks_sign_in(monke
module.maybe_auto_login_crane(
page,
env=lambda name, default="": {
"FREIGHT_RPA_CRANE_USERNAME": "crane-user",
"FREIGHT_RPA_CRANE_PASSWORD": "crane-pass",
"SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME": "crane-user",
"SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD": "crane-pass",
}.get(name, default),
browser_timeout_ms=5_000,
)
assert calls == [
("FREIGHT_RPA_CRANE_USERNAME_SELECTOR", "crane-user"),
("FREIGHT_RPA_CRANE_PASSWORD_SELECTOR", "crane-pass"),
("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"),
("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"),
]
@@ -133,7 +133,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
locator = module._find_crane_sign_in_button(
page,
selector_env="FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR",
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
env=lambda name, default="": default,
browser_timeout_ms=3_000,
)
@@ -1,74 +0,0 @@
"""scripts/rpa/dsv_export_batch_smoke.py 轻量单测(退出码与 REQUIRE_EXPORT 开关)。"""
from __future__ import annotations
import importlib.util
from pathlib import Path
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _load_dsv_export_batch_smoke():
module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_batch_smoke.py"
spec = importlib.util.spec_from_file_location("dsv_export_batch_smoke_under_test", module_path)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _load_freight_rpa_worker():
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_smoke_exit_test", module_path)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_resolve_smoke_scenario_exit_code_all_skipped_default_passes():
"""默认不要求导出时,全 skipped 应退出 0。"""
smoke = _load_dsv_export_batch_smoke()
worker = _load_freight_rpa_worker()
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
summary = worker._summarize_inventory_batch_results(results)
assert smoke._resolve_smoke_scenario_exit_code(
results=results,
summary=summary,
require_export=False,
) == 0
def test_resolve_smoke_scenario_exit_code_all_skipped_require_export_fails():
"""FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 时,全 skipped 应退出 2。"""
smoke = _load_dsv_export_batch_smoke()
worker = _load_freight_rpa_worker()
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
summary = worker._summarize_inventory_batch_results(results)
assert summary["status"] == "success"
assert summary["has_success"] is False
assert smoke._resolve_smoke_scenario_exit_code(
results=results,
summary=summary,
require_export=True,
) == 2
def test_resolve_smoke_scenario_exit_code_has_success_with_require_export():
"""require_export=true 但已有 success 导出时仍应退出 0。"""
smoke = _load_dsv_export_batch_smoke()
worker = _load_freight_rpa_worker()
results = [
{"source_code": "A", "status": "success", "success": True},
{"source_code": "B", "status": "skipped", "success": False, "skipped": True},
]
summary = worker._summarize_inventory_batch_results(results)
assert smoke._resolve_smoke_scenario_exit_code(
results=results,
summary=summary,
require_export=True,
) == 0
+2 -2
View File
@@ -43,7 +43,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
module.fill_dsv_filter_if_needed(
_FakePage(),
"FREIGHT_RPA_DSV_OWNER_SELECTOR",
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
"Owner",
"CADU-0000000100",
env=lambda name, default="": default,
@@ -104,7 +104,7 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue():
module.fill_dsv_filter_if_needed(
_FakePage(),
"FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse",
"BYAWSATL01",
env=lambda name, default="": default,
+5 -5
View File
@@ -22,7 +22,7 @@ def _load_freight_rpa_heartbeat_module():
def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
module = _load_freight_rpa_heartbeat_module()
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
payload = module.build_heartbeat_payload(
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
drop_dir=r"C:\HxopsRpaTest\data\inventory_drop",
@@ -33,15 +33,15 @@ def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
module = _load_freight_rpa_heartbeat_module()
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False)
monkeypatch.setenv(
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR",
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR",
r"C:\HxopsRpaTest\data\inventory_triggers",
)
assert module._resolve_shared_scope_id() == ""
monkeypatch.setenv(
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR",
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR",
r"C:\mount\hxops-rpa-test-data\inventory_triggers",
)
assert module._resolve_shared_scope_id() == "hxops-rpa-test-data"
@@ -52,7 +52,7 @@ def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
trigger_dir = tmp_path / "inventory_triggers"
trigger_dir.mkdir()
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01")
sentinel = trigger_dir / ".hxops_rpa_shared_mount"
+118 -74
View File
@@ -16,6 +16,7 @@ import sys
from pathlib import Path
import pytest
from cryptography.fernet import Fernet
from openpyxl import load_workbook
@@ -33,16 +34,6 @@ def _load_freight_rpa_worker():
return module
def _load_dsv_export_batch_smoke():
module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_batch_smoke.py"
spec = importlib.util.spec_from_file_location("dsv_export_batch_smoke_worker_test", module_path)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
"""构造库存导出 trigger 样本,避免测试依赖会被 worker 消费掉的仓库文件。"""
return {
@@ -72,20 +63,96 @@ def test_env_strips_wrapping_quotes(monkeypatch):
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", '"user@example.com"')
monkeypatch.setenv("FREIGHT_RPA_DSV_PASSWORD", "'secret-pass'")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", '"user@example.com"')
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "'secret-pass'")
assert worker._env("FREIGHT_RPA_DSV_USERNAME") == "user@example.com"
assert worker._env("FREIGHT_RPA_DSV_PASSWORD") == "secret-pass"
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "user@example.com"
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "secret-pass"
def test_worker_accepts_business_connector_without_site_id():
"""数据库 Source 的 dbs/crane 业务类型不应要求已删除的 site_id 字段。"""
worker = _load_freight_rpa_worker()
worker._validate_inventory_source_for_rpa({
"source_code": "DBS_DUB", "connector_type": "dbs", "warehouse_id": "DUB",
})
worker._validate_inventory_source_for_rpa({
"source_code": "CRANE", "connector_type": "crane",
})
def test_worker_groups_same_connector_by_rpa_profile():
"""同 connector 的不同 Profile 必须分组,防止错误复用登录态。"""
worker = _load_freight_rpa_worker()
grouped = worker._group_batch_sources_by_profile([
{"source_code": "DBS_DUB", "connector_type": "dbs", "rpa_profile_code": "DBS_EU_A"},
{"source_code": "DBS_RTM", "connector_type": "dbs", "rpa_profile_code": "DBS_EU_B"},
])
assert set(grouped) == {("dsv360", "DBS_EU_A"), ("dsv360", "DBS_EU_B")}
def test_worker_keeps_same_profile_sources_in_one_session_group():
"""同一登录连接的多个 Source 可复用登录会话,不与其他 Profile 混用。"""
worker = _load_freight_rpa_worker()
grouped = worker._group_batch_sources_by_profile([
{'source_code': 'DBS_DUB', 'connector_type': 'dbs', 'rpa_profile_code': 'DBS_EU_A'},
{'source_code': 'DBS_RTM', 'connector_type': 'dbs', 'rpa_profile_code': 'DBS_EU_A'},
{'source_code': 'DBS_CMH', 'connector_type': 'dbs', 'rpa_profile_code': 'DBS_US_B'},
])
assert [item['source_code'] for item in grouped[('dsv360', 'DBS_EU_A')]] == ['DBS_DUB', 'DBS_RTM']
assert [item['source_code'] for item in grouped[('dsv360', 'DBS_US_B')]] == ['DBS_CMH']
def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
"""worker 解密 Profile 密文后必须在退出执行范围时恢复原有环境。"""
worker = _load_freight_rpa_worker()
key = Fernet.generate_key()
cipher = Fernet(key)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", key.decode("ascii"))
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", raising=False)
monkeypatch.delenv("FREIGHT_RPA_DSV_USERNAME", raising=False)
monkeypatch.delenv("FREIGHT_RPA_DSV_PASSWORD", raising=False)
source = {
"connector_type": "dbs",
"credential_envelope": {
"username_ciphertext": cipher.encrypt(b"test-user").decode("ascii"),
"password_ciphertext": cipher.encrypt(b"test-password").decode("ascii"),
},
}
with worker._profile_credentials(source):
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "test-user"
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "test-password"
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == ""
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == ""
def test_worker_prefers_canonical_rpa_env_over_legacy_name(monkeypatch):
"""新旧 RPA 变量同时存在时必须使用统一的新命名空间,避免旧部署值覆盖新配置。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "false"
def test_worker_reads_legacy_rpa_env_during_migration(monkeypatch):
"""规范变量缺失时允许读取旧名称,保障 Windows Worker 分阶段迁移不中断。"""
worker = _load_freight_rpa_worker()
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", raising=False)
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
with pytest.warns(DeprecationWarning, match="FREIGHT_RPA_MOCK is deprecated"):
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "true"
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
"""配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
"""配置 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "logs" / "worker.log"
timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ")
monkeypatch.setenv("FREIGHT_RPA_LOG_FILE", str(log_path))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(log_path))
original_stdout = sys.stdout
original_stderr = sys.stderr
@@ -116,14 +183,14 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
"""日志超过 FREIGHT_RPA_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
"""日志超过 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
Path(f"{log_path}.1").write_text("old-1", encoding="utf-8")
monkeypatch.setenv("FREIGHT_RPA_LOG_MAX_BYTES", "1")
monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "2")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
worker._rotate_log_file_if_needed(log_path)
@@ -138,8 +205,8 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
monkeypatch.setenv("FREIGHT_RPA_LOG_MAX_BYTES", "1")
monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "0")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0")
worker._rotate_log_file_if_needed(log_path)
@@ -171,10 +238,10 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
def start(self):
return _FakePlaywright()
monkeypatch.delenv("FREIGHT_RPA_BROWSER_PROFILE_DIR", raising=False)
monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "true")
monkeypatch.delenv("FREIGHT_RPA_BROWSER_CHANNEL", raising=False)
monkeypatch.delenv("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
temp_roots: list[Path] = []
@@ -209,7 +276,7 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa
"""profile 根目录配置为 data/shipping_notice 时,应按 backend 根目录解析。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
"data/shipping_notice/freight_rpa/browser_profile",
)
@@ -222,7 +289,7 @@ def test_browser_profile_root_remaps_legacy_freight_rpa_path(monkeypatch):
"""本机残留旧 profile 路径时,应强制迁到 shipping_notice 命名空间。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
"backend/data/freight_rpa/browser_profile",
)
@@ -235,7 +302,7 @@ def test_browser_profile_root_remaps_absolute_legacy_freight_rpa_path(monkeypatc
"""本机环境变量保存绝对旧路径时,也应迁到 shipping_notice 命名空间。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
str(_repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"),
)
@@ -265,7 +332,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
out_file.write_bytes(b"fake inventory content")
return out_file
monkeypatch.setenv("FREIGHT_RPA_MOCK", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
@@ -312,8 +379,8 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
processed_dir = trigger_dir / "processed"
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
monkeypatch.delenv("FREIGHT_RPA_SAMPLE_INVENTORY", raising=False)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
@@ -363,7 +430,7 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
def raise_no_inventory(_trigger: dict, _drop: Path):
raise worker.NoInventoryDataError("DSV report has no inventory data")
monkeypatch.setenv("FREIGHT_RPA_MOCK", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
@@ -447,37 +514,14 @@ def test_summarize_inventory_batch_item_empty_dict_counts_as_failed():
assert summary["success"] is False
def test_summarize_inventory_batch_results_all_skipped_smoke_exit_success():
"""全 skipped 时 summary status=success,smoke 应退出 0(链路正常、无 Excel)。"""
def test_summarize_inventory_batch_results_all_skipped_is_success():
"""全 skipped 代表链路正常但无库存,不得误报为批量导出失败。"""
worker = _load_freight_rpa_worker()
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
summary = worker._summarize_inventory_batch_results(results)
assert summary["status"] == "success"
assert summary["has_success"] is False
assert summary["status"] not in {"failed", "partial_failed"}
smoke = _load_dsv_export_batch_smoke()
assert smoke._resolve_smoke_scenario_exit_code(
results=results,
summary=summary,
require_export=False,
) == 0
def test_summarize_inventory_batch_results_all_skipped_require_export_smoke_exit_fail():
"""FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 时,全 skipped 应退出 2(无 Excel 导出)。"""
worker = _load_freight_rpa_worker()
smoke = _load_dsv_export_batch_smoke()
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
summary = worker._summarize_inventory_batch_results(results)
assert summary["status"] == "success"
assert summary["has_success"] is False
assert smoke._resolve_smoke_scenario_exit_code(
results=results,
summary=summary,
require_export=True,
) == 2
def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path):
"""真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。"""
worker = _load_freight_rpa_worker()
@@ -503,10 +547,10 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
def start(self):
return _FakePlaywright()
monkeypatch.setenv("FREIGHT_RPA_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "false")
monkeypatch.setenv("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
monkeypatch.delenv("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads")
@@ -1004,7 +1048,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
worker._fill_dsv_filter_if_needed(
_FakePage(),
"FREIGHT_RPA_DSV_OWNER_SELECTOR",
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
"Owner",
"CADU-0000000100",
)
@@ -1159,26 +1203,26 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
"""
手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。
默认跳过;仅当 FREIGHT_RPA_E2E=true 时执行。执行前需准备账号密码:
- FREIGHT_RPA_MOCK=false
- FREIGHT_RPA_HEADLESS=false(建议首次调试)
- FREIGHT_RPA_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
- FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD
默认跳过;仅当 SHIPPING_NOTICE_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码:
- SHIPPING_NOTICE_RPA_WORKER_MOCK=false
- SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false(建议首次调试)
- SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
- SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD
"""
if str(os.getenv("FREIGHT_RPA_E2E") or "").strip().lower() != "true":
pytest.skip("set FREIGHT_RPA_E2E=true to run real freight RPA export")
if str(os.getenv("SHIPPING_NOTICE_RPA_WORKER_E2E") or "").strip().lower() != "true":
pytest.skip("set SHIPPING_NOTICE_RPA_WORKER_E2E=true to run real freight RPA export")
worker = _load_freight_rpa_worker()
trigger = _build_inventory_export_trigger("SN-20260629-2EDADC77")
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
monkeypatch.setenv("FREIGHT_RPA_MOCK", "false")
if not os.getenv("FREIGHT_RPA_HEADLESS"):
monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "false")
if not os.getenv("FREIGHT_RPA_BROWSER_PROFILE_DIR"):
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS"):
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR"):
monkeypatch.setenv(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
str(tmp_path / "browser_profile"),
)
@@ -42,12 +42,12 @@ def test_fill_report_parameter_multi_select(monkeypatch):
page,
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"mode": "multi_select",
"values": ["WH1", "WH2"],
},
)
assert calls == [("FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
assert calls == [("SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
@@ -67,29 +67,22 @@ def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
}
)
selectors = {
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
}
monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi)
worker._fill_report_parameter(
page,
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "multi_select",
"select_all": True,
"selectors": selectors,
"values": ["RTM"],
"mode": "multi_select",
"select_all": True,
"values": ["RTM"],
},
)
assert calls == [
{
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"label": "Warehouse",
"values": ["RTM"],
"selectors": selectors,
"selectors": None,
"select_all": True,
}
]
+78
View File
@@ -0,0 +1,78 @@
"""
tests/test_init_local_db.py
用途:验证本地 SQLite 初始化脚本只操作显式目标,并安全区分空库、版本库与未知旧库。
依赖:init_local_db.py、SQLite、Alembic 迁移目录、subprocess。
逻辑:使用临时路径执行真实脚本;检查全新库版本标记和种子数据,并确认未知旧库被拒绝且字节不变。
"""
from __future__ import annotations
import os
import sqlite3
import subprocess
import sys
from pathlib import Path
BACKEND_DIR = Path(__file__).resolve().parents[1]
SCRIPT_PATH = BACKEND_DIR / 'init_local_db.py'
def _run_initializer(database_path: Path) -> subprocess.CompletedProcess[str]:
"""
在隔离 SQLite 路径运行真实初始化脚本。
Args:
database_path: 测试专用数据库文件,禁止指向仓库默认 local_test.db。
Returns:
捕获标准输出和错误输出的子进程结果。
"""
env = os.environ.copy()
env['HXOPS_LOCAL_DATABASE_PATH'] = str(database_path)
env['FIXED_ASSETS_SYNC_ENABLED'] = 'false'
return subprocess.run(
[sys.executable, str(SCRIPT_PATH)],
cwd=BACKEND_DIR,
env=env,
capture_output=True,
text=True,
timeout=120,
check=False,
)
def test_init_local_db_creates_isolated_current_schema(tmp_path):
"""全新隔离库应初始化、标记 Alembic head,并写入最小本地账号。"""
database_path = tmp_path / 'isolated-local.db'
result = _run_initializer(database_path)
assert result.returncode == 0, result.stderr
assert database_path.is_file()
with sqlite3.connect(database_path) as connection:
version = connection.execute('SELECT version_num FROM alembic_version').fetchone()
admin = connection.execute(
"SELECT username, role FROM users WHERE username = 'admin'",
).fetchone()
agent_count = connection.execute('SELECT COUNT(*) FROM agents').fetchone()[0]
assert version is not None and version[0]
assert admin == ('admin', 'admin')
assert int(agent_count) == 1
def test_init_local_db_refuses_unversioned_database_without_modifying_it(tmp_path):
"""已有业务表但无 Alembic 版本的数据库必须原样拒绝,不能静默 stamp 或删库。"""
database_path = tmp_path / 'legacy-local.db'
with sqlite3.connect(database_path) as connection:
connection.execute('CREATE TABLE legacy_orders (id INTEGER PRIMARY KEY, code TEXT NOT NULL)')
connection.execute("INSERT INTO legacy_orders (code) VALUES ('KEEP-ME')")
connection.commit()
before = database_path.read_bytes()
result = _run_initializer(database_path)
assert result.returncode == 2
assert 'Refusing to modify legacy unversioned database' in result.stderr
assert database_path.read_bytes() == before
+1 -1
View File
@@ -9,7 +9,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
"""POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
from app import db
@@ -0,0 +1,238 @@
"""验证库存站点测试导出的隔离、结构识别和解析方案确认。"""
from __future__ import annotations
from pathlib import Path
from unittest.mock import patch
import pytest
from cryptography.fernet import Fernet
from openpyxl import Workbook
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingInventoryConfigurationTestRun,
ShippingInventoryExternalMapping,
ShippingExcelTemplate,
ShippingExcelTemplate,
ShippingInventoryFile,
ShippingInventoryField,
ShippingInventorySource,
)
from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import (
inventory_configuration_test,
inventory_parsing_profile,
inventory_structure_analysis,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
def _inventory_field_id(field_code: str) -> str:
"""获取测试显式创建的用户库存字段 ID。"""
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
def _workbook(path: Path) -> None:
"""生成模拟 RPA 下载完成的最小库存 Excel。"""
workbook = Workbook()
sheet = workbook.active
sheet.append(['Supplier Sku', 'Reservation ID', 'Qty Available'])
sheet.append(['PN-1', '1000140351', 9])
workbook.save(path)
def _source() -> dict:
"""创建一个保持停用的 DBS 库存站点。"""
login = shipping_inventory_service.save_profile({
'profile_code': 'TEST_EXPORT_LOGIN', 'display_name': 'Test Login', 'connector_type': 'dbs',
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
'username': 'user', 'password': 'password', 'enabled': True,
}, actor_id=None)
return shipping_inventory_service.save_source({
'source_code': 'TEST_EXPORT_SOURCE', 'display_name': 'Test Export Source', 'connector_type': 'dbs',
'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None,
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
'enabled': False,
'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
'query_parameters_json': [], 'match_aliases_json': [],
}, actor_id=None)
def _published_order_field() -> str:
"""创建测试解析方案所需的已发布订单明细字段。"""
order_schema_service.initialize_schema({'display_name': 'Configuration Test'}, actor_id=None)
field = order_schema_service.save_field({
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
draft = order_schema_service.create_draft({}, actor_id=None)
saved = order_schema_service.save_draft(draft['id'], {'fields': [{
'field_id': field['id'], 'display_name': '料号', 'required': True, 'aliases': [],
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'],
'conflict_policy': 'block', 'allow_single_source': True},
'relation_role': None, 'comparator_key': 'normalized_text', 'extraction_instruction': '提取料号',
}], 'expected_lock_version': draft['lock_version']})
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
return field['id']
def _publish_profile_from_analysis(analysis_id: int, field_id: str, *, code: str) -> dict:
"""从测试分析创建并发布方案,模拟管理员确认解析配置的前置动作。"""
analysis = inventory_structure_analysis.get_analysis(analysis_id)
draft = inventory_structure_analysis.create_profile_draft(analysis_id, {
'profile_code': code, 'display_name': code, 'sheet_name': 'Sheet', 'header_row_index': 1,
'field_mapping': {
_inventory_field_id('part_number'): 'Supplier Sku',
_inventory_field_id('reservation_id'): 'Reservation ID',
_inventory_field_id('available_qty'): 'Qty Available',
},
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}],
}, actor_id=None)
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
def _complete_test_run(source: dict, tmp_path: Path) -> dict:
"""完成一次模拟 RPA 测试导出,返回可供确认的测试运行。"""
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
result_file = tmp_path / f"{started['run_no']}.xlsx"
_workbook(result_file)
return inventory_configuration_test.report_test_export({
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
})
def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path):
"""测试文件只能生成测试分析,重复发起复用运行,禁止创建生产库存快照。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
assert started['status'] == 'awaiting_rpa'
assert inventory_configuration_test.start_test_export(source['id'], actor_id=None)['run_no'] == started['run_no']
result_file = tmp_path / 'rpa-result.xlsx'
_workbook(result_file)
completed = inventory_configuration_test.report_test_export({
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
})
assert completed['status'] == 'completed'
assert completed['stage'] == 'ready_for_confirmation'
assert not ShippingInventoryFile.query.count()
assert ShippingInventoryConfigurationTestRun.query.count() == 1
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
"""确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
completed = _complete_test_run(source, tmp_path)
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_CONFIRMED')
confirmed = inventory_configuration_test.confirm_test_profile(
source['id'], completed['run_no'], profile['id'], actor_id=None,
)
assert confirmed['parsing_profile_id'] == profile['id']
source_model = db.session.get(ShippingInventorySource, source['id'])
assert source_model.parsing_profile_id == profile['id']
assert 'configuration_test' not in shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements']
assert 'warehouse_mapping' in shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements']
db.session.add(ShippingInventoryExternalMapping(
inventory_source_id=source['id'], freight_warehouse_id='DUB', external_system_code='TOPGP',
external_warehouse_code='DUB-01', external_warehouse_name='Dublin', enabled=True,
))
template = ShippingExcelTemplate(
template_code='TEST_ACTIVATION', display_name='Activation Template', version=1, status='published',
storage_bucket='test', storage_key='activation.xlsx', original_filename='activation.xlsx',
file_checksum='0' * 64,
definition_json={'filename_pattern': '{business_no}.xlsx', 'mappings': [{
'sheet': 'Sheet', 'row_mode': 'line', 'start_row': 2, 'target_column': 1,
'source_kind': 'inventory_field', 'source_key': _inventory_field_id('part_number'), 'formatter': 'text',
}]}, definition_checksum='1' * 64,
)
db.session.add(template)
db.session.flush()
source_model.excel_template_id = template.id
db.session.commit()
assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True
assert shipping_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True
def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path):
"""正式运行中的站点不能发起测试;站点配置变化后旧测试不得绑定。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
completed = _complete_test_run(source, tmp_path)
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_STALE')
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
shipping_inventory_service.save_source({**current, 'display_name': 'Changed after test'}, actor_id=None, source_id=source['id'])
with pytest.raises(ConflictError) as stale:
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
assert stale.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE'
source_model = db.session.get(ShippingInventorySource, source['id'])
source_model.parsing_profile_id = profile['id']
template = ShippingExcelTemplate(
template_code='TEST_ENABLED', display_name='Test Enabled', version=1, status='published',
storage_bucket='test', storage_key='test.xlsx', original_filename='test.xlsx',
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
)
db.session.add(template)
db.session.flush()
source_model.excel_template_id = template.id
source_model.enabled = True
db.session.commit()
with pytest.raises(ConflictError) as enabled:
inventory_configuration_test.start_test_export(source['id'], actor_id=None)
assert enabled.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID'
def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
"""失败回调和非推荐方案均不得产生生产快照或修改站点解析方案。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
failed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
result = inventory_configuration_test.report_test_export({
'run_no': failed['run_no'], 'status': 'failed', 'error_message': 'RPA login failed',
})
assert result['status'] == 'failed'
assert not ShippingInventoryFile.query.count()
completed = _complete_test_run(source, tmp_path)
field_id = _published_order_field()
_publish_profile_from_analysis(completed['analysis_id'], field_id, code='TEST_MATCHED')
unrelated = inventory_parsing_profile.save_draft({
'profile_code': 'TEST_UNRELATED', 'display_name': 'Unrelated', 'file_format': 'xlsx',
'definition': {
'sheet_name': 'Other', 'header_row_index': 1,
'field_mapping': {
_inventory_field_id('part_number'): 'Other Part',
_inventory_field_id('reservation_id'): 'Other Reservation',
_inventory_field_id('available_qty'): 'Other Qty',
},
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}],
},
}, actor_id=None)
unrelated = inventory_parsing_profile.publish(unrelated['id'], actor_id=None)
with pytest.raises(ValidationError) as rejected:
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], unrelated['id'], actor_id=None)
assert rejected.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID'
assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None
@@ -0,0 +1,68 @@
"""
用途:验证库存字段目录零预置、用户字段维护和引用保护。
依赖:inventory_field_catalog、库存字段 ORM 与统一测试应用上下文。
逻辑:目录初始为空;用户字段未引用时可删除,引用后用途和数据格式受保护。
"""
import pytest
from app.core.errors import ConflictError
from app import db
from app.models import ShippingInventoryField
from app.models import ShippingInventoryParsingProfile
from app.services.shipping_notice import inventory_field_catalog
def test_catalog_is_empty_until_user_creates_fields(app):
"""新环境不得由迁移或服务自动创建任何具体库存字段。"""
with app.app_context():
ShippingInventoryField.query.delete()
db.session.commit()
assert inventory_field_catalog.list_fields() == []
def test_extension_field_can_be_created_updated_and_deleted(app):
"""未被下游配置引用的扩展字段可完整维护,不需要再改 Python 白名单。"""
with app.app_context():
created = inventory_field_catalog.create_field({
'display_name': '原产国', 'description': '货品原产地国家或地区。',
'value_type': 'text', 'usage_type': 'general', 'sort_order': 200,
}, actor_id=None)
updated = inventory_field_catalog.update_field(created['id'], {
'display_name': '原产国家', 'description': '货品原产地国家或地区。',
'value_type': 'text', 'usage_type': 'general', 'sort_order': 210,
}, actor_id=None)
assert updated['display_name'] == '原产国家'
assert updated['sort_order'] == 210
assert inventory_field_catalog.delete_field(created['id']) == {'action': 'deleted'}
assert db.session.get(ShippingInventoryField, created['id']) is None
def test_extension_field_referenced_by_parsing_profile_cannot_be_deleted_or_retired(app):
"""解析方案已引用用户字段时,目录服务阻止删除、停用和改变能力用途。"""
with app.app_context():
extension = ShippingInventoryField(
field_code='batch_no', display_name='库存批号', value_type='text',
usage_type='general', status='active', sort_order=100,
)
db.session.add(extension)
db.session.flush()
db.session.add(ShippingInventoryParsingProfile(
profile_code='REFERENCE_FIELD', display_name='Reference field', version=1,
status='draft', file_format='xlsx',
definition_json={'field_mapping': {str(extension.id): 'Batch No'}, 'match_keys': []},
))
db.session.commit()
for operation, code in (
(inventory_field_catalog.delete_field, 'SHIPPING.INVENTORY_FIELD_DELETE_BLOCKED'),
(inventory_field_catalog.retire_field, 'SHIPPING.INVENTORY_FIELD_RETIRE_BLOCKED'),
):
with pytest.raises(ConflictError) as error:
operation(extension.id)
assert error.value.code == code
with pytest.raises(ConflictError) as update_error:
inventory_field_catalog.update_field(extension.id, {
'display_name': '库存批号', 'description': '',
'value_type': 'decimal', 'usage_type': 'inventory_quantity', 'sort_order': 100,
}, actor_id=None)
assert update_error.value.code == 'SHIPPING.INVENTORY_FIELD_IMMUTABLE'
@@ -0,0 +1,214 @@
"""
用途:验证可复用库存解析 Profile 的版本、共享绑定和订单字段匹配键门禁。
依赖:inventory_parsing_profile、shipping_inventory_service、订单 Schema 服务。
逻辑:发布一个 Profile 后绑定多个 Source;新版本并存且旧绑定稳定,非法字段、退役引用或非发布绑定被拒绝。
"""
from cryptography.fernet import Fernet
import pytest
from app.core.errors import ValidationError
from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import inventory_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service
from app import db
from app.models import ShippingExcelTemplate, ShippingInventoryField
def _inventory_mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]:
"""以库存字段目录 ID 构造解析映射,禁止测试继续模拟旧字段编码配置。"""
rows = {item.field_code: item for item in ShippingInventoryField.query.filter_by(status='active').all()}
return {
str(rows['part_number'].id): part,
str(rows['reservation_id'].id): reservation,
str(rows['available_qty'].id): quantity,
}
def _part_number_field_id() -> str:
"""返回内部料号目录 ID,作为订单明细匹配键的库存端引用。"""
return str(ShippingInventoryField.query.filter_by(field_code='part_number').one().id)
def _published_profile() -> dict:
"""创建含 part_number 匹配键的 published 解析 Profile。"""
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
schema_draft = order_schema_service.create_draft({}, actor_id=None)
saved_schema = order_schema_service.save_draft(schema_draft['id'], {
'fields': [_schema_field_config(field['id'])],
'expected_lock_version': schema_draft['lock_version'],
})
order_schema_service.publish(
schema_draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
)
draft = inventory_parsing_profile.save_draft({
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common', 'file_format': 'xlsx',
'definition': {
'header_row_index': 1,
'field_mapping': _inventory_mapping(),
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
},
}, actor_id=None)
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
def _schema_field_config(field_id: str) -> dict:
"""构造库存匹配测试使用的最小可发布订单行字段规则。"""
return {
'field_id': field_id, 'display_name': '内部料号', 'required': True, 'aliases': [],
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_table'],
'conflict_policy': 'block', 'allow_single_source': True,
},
'relation_role': None, 'comparator_key': 'normalized_text',
'extraction_instruction': '提取订单行内部料号',
}
def _source(profile_id: int, parsing_id: int, code: str) -> dict:
"""构造绑定共享解析 Profile 的 DBS 库存源。"""
return {
'source_code': code, 'display_name': code, 'connector_type': 'dbs',
'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_id,
'excel_template_id': _excel_template_id(),
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': code,
'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
'query_parameters_json': [], 'match_aliases_json': [], 'snapshot_ttl_seconds': 3600, 'enabled': True,
}
def _excel_template_id() -> int:
"""创建本组 Source 绑定共享的最小已发布发货模板。"""
item = ShippingExcelTemplate.query.filter_by(template_code='COMMON_EXPORT').first()
if item:
return item.id
item = ShippingExcelTemplate(
template_code='COMMON_EXPORT', display_name='Common Export', version=1, status='published',
storage_provider='minio', storage_bucket='test', storage_key='test/common-export.xlsx',
original_filename='template.xlsx',
file_checksum='0' * 64, definition_json={'filename_pattern': 'shipment_{task_no}.xlsx', 'mappings': []},
definition_checksum='1' * 64,
)
db.session.add(item)
db.session.flush()
return item.id
def test_published_parsing_profile_can_be_shared_by_sources(app):
"""同一 published Profile 应可绑定多个库存源,避免重复维护相同模板。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
parsing = _published_profile()
login = shipping_inventory_service.save_profile({
'profile_code': 'DBS_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs',
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
'username': 'u', 'password': 'p', 'enabled': True,
}, actor_id=None)
first = shipping_inventory_service.save_source(_source(login['id'], parsing['id'], 'DUB'), actor_id=None)
second = shipping_inventory_service.save_source(_source(login['id'], parsing['id'], 'RTM'), actor_id=None)
assert first['parsing_profile_id'] == parsing['id']
assert second['parsing_profile_id'] == parsing['id']
assert inventory_parsing_profile.list_profiles()[0]['source_count'] == 2
def test_source_rejects_draft_parsing_profile(app):
"""库存源只能绑定 published Profile,避免运行期读取可变草稿。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
draft = inventory_parsing_profile.save_draft({
'profile_code': 'DRAFT_ONLY', 'display_name': 'Draft', 'definition': {
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
},
}, actor_id=None)
login = shipping_inventory_service.save_profile({
'profile_code': 'LOGIN', 'display_name': 'Login', 'connector_type': 'dbs',
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
'username': 'u', 'password': 'p', 'enabled': True,
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(_source(login['id'], draft['id'], 'DUB'), actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED'
def test_csv_parsing_profile_rejects_worksheet_configuration(app):
"""CSV 没有工作表语义,保存 Profile 时不得接受会被运行期忽略的 sheet_name。"""
with app.app_context():
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
field = order_schema_service.save_field({
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
inventory_parsing_profile.save_draft({
'profile_code': 'CSV_SHEET', 'display_name': 'CSV Sheet', 'file_format': 'csv',
'definition': {
'sheet_name': 'Inventory', 'header_row_index': 1,
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
},
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
def test_new_published_version_does_not_retire_bound_version(app):
"""发布新版本不得使现有库存源绑定的旧 published 版本失效。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
first = _published_profile()
field_id = order_schema_service.get_state()['fields'][0]['id']
second_draft = inventory_parsing_profile.save_draft({
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx',
'definition': {
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_field_id()}],
},
}, actor_id=None)
second = inventory_parsing_profile.publish(second_draft['id'], actor_id=None)
assert first['id'] != second['id']
assert {item['status'] for item in inventory_parsing_profile.list_profiles()} == {'published'}
def test_referenced_published_profile_cannot_be_retired(app):
"""已绑定库存源的解析 Profile 必须先迁移 Source,不能直接退役。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
parsing = _published_profile()
login = shipping_inventory_service.save_profile({
'profile_code': 'RETIRE_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs',
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
'username': 'u', 'password': 'p', 'enabled': True,
}, actor_id=None)
shipping_inventory_service.save_source(_source(login['id'], parsing['id'], 'RETIRE'), actor_id=None)
with pytest.raises(Exception) as exc_info:
inventory_parsing_profile.retire(parsing['id'])
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED'
def test_parsing_profile_publish_rejects_field_removed_from_current_schema(app):
"""解析 Profile 不得发布仍引用旧 Schema 字段的匹配键。"""
with app.app_context():
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
old_field = order_schema_service.save_field({'field_code': 'old_part', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
new_field = order_schema_service.save_field({'field_code': 'new_part', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
first = order_schema_service.create_draft({}, actor_id=None)
saved_schema = order_schema_service.save_draft(first['id'], {
'fields': [_schema_field_config(new_field['id'])], 'expected_lock_version': first['lock_version'],
})
order_schema_service.publish(
first['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
)
profile = inventory_parsing_profile.save_draft({
'profile_code': 'STALE_FIELD', 'display_name': 'Stale Field',
'definition': {
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': old_field['id'], 'inventory_field_id': _part_number_field_id()}],
},
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
inventory_parsing_profile.publish(profile['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID'
@@ -0,0 +1,105 @@
"""
tests/test_inventory_profile_matching.py
用途:验证库存文件结构指纹与已发布解析方案的确定性复用推荐。
依赖:库存结构分析、库存解析方案、订单字段 Schema 服务。
逻辑:库存数据内容和文件名不参与判断;完全一致与兼容变化只产生管理员建议,绝不自动绑定库存站点。
"""
from __future__ import annotations
from io import BytesIO
from openpyxl import Workbook
from werkzeug.datastructures import FileStorage
from app.services.shipping_notice import inventory_parsing_profile, inventory_structure_analysis
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.models import ShippingInventoryField
def _part_number_inventory_field_id() -> str:
"""返回测试用户创建的匹配字段 ID。"""
return str(ShippingInventoryField.query.filter_by(field_code='part_number').one().id)
def _upload(*, qty: int, extra_column: bool = False) -> FileStorage:
"""构造结构相同但库存数据不同的样本,可选增加无关栏位。"""
stream = BytesIO()
workbook = Workbook()
sheet = workbook.active
headers = ['Supplier Sku', 'Reservation ID', 'Qty Available']
if extra_column:
headers.append('Last Export Time')
sheet.append(headers)
row = ['PN-001', '1000140351', qty]
if extra_column:
row.append('2026-07-17 10:00')
sheet.append(row)
workbook.save(stream)
stream.seek(0)
return FileStorage(stream=stream, filename=f'inventory-{qty}.xlsx')
def _field_id() -> str:
"""创建当前已发布订单契约中的内部料号字段。"""
order_schema_service.initialize_schema({'display_name': 'Matching'}, actor_id=None)
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
draft = order_schema_service.create_draft({}, actor_id=None)
saved = order_schema_service.save_draft(draft['id'], {'fields': [{
'field_id': field['id'], 'display_name': '内部料号', 'required': True, 'aliases': [],
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
'relation_role': None, 'comparator_key': 'normalized_text', 'extraction_instruction': '提取内部料号',
}], 'expected_lock_version': draft['lock_version']})
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
return field['id']
def _published_profile(field_id: str) -> dict:
"""通过一次真实分析创建并发布含结构指纹的库存文件解析方案。"""
analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=9), actor_id=None)
draft = inventory_structure_analysis.create_profile_draft(analysis['id'], {
'profile_code': 'SHARED_INVENTORY', 'display_name': '共享库存文件', 'sheet_name': 'Sheet', 'header_row_index': 1,
'field_mapping': {
_part_number_inventory_field_id(): 'Supplier Sku',
str(ShippingInventoryField.query.filter_by(field_code='reservation_id').one().id): 'Reservation ID',
str(ShippingInventoryField.query.filter_by(field_code='available_qty').one().id): 'Qty Available',
},
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_inventory_field_id()}],
}, actor_id=None)
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
def test_same_structure_with_different_data_recommends_exact_profile(app, tmp_path):
"""库存数量变化不影响模板判断,同表头结构必须推荐同一已发布方案。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
profile = _published_profile(_field_id())
analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=999), actor_id=None)
result = analysis['match_result']
assert result['status'] == 'exact'
assert result['candidates'][0]['profile_id'] == profile['id']
def test_added_non_critical_column_recommends_compatible_profile(app, tmp_path):
"""新增无关栏位可推荐已有方案,但不伪装为完全相同结构。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
profile = _published_profile(_field_id())
analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=12, extra_column=True), actor_id=None)
candidate = analysis['match_result']['candidates'][0]
assert analysis['match_result']['status'] == 'compatible'
assert candidate['profile_id'] == profile['id']
assert 'last export time' in candidate['difference']['added_columns']
def test_adopting_recommendation_does_not_bind_inventory_source(app, tmp_path):
"""管理员采用推荐方案只留下分析审计,不能在样本上传阶段修改任何库存站点。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
profile = _published_profile(_field_id())
analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=10), actor_id=None)
adopted = inventory_structure_analysis.adopt_published_profile(analysis['id'], profile['id'])
assert adopted['match_result']['adopted_profile_id'] == profile['id']
assert profile['source_count'] == 0
@@ -0,0 +1,170 @@
"""
tests/test_inventory_structure_analysis.py
用途:验证库存样本的后端结构分析、真实表头约束和解析方案草稿创建。
依赖:openpyxl、inventory_structure_analysis、订单字段 Schema 服务。
逻辑:管理端上传样本后必须由后端决定工作表和来源栏位;草稿创建只能引用分析出的真实栏位。
"""
from __future__ import annotations
from io import BytesIO
from pathlib import Path
from openpyxl import Workbook
from werkzeug.datastructures import FileStorage
import pytest
from app.core.errors import ValidationError
from app.services.shipping_notice import inventory_structure_analysis
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.models import ShippingInventoryField
def _field_id(field_code: str) -> str:
"""返回测试显式创建的用户库存字段 ID。"""
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
def _mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]:
"""使用字段目录 ID 构造样本解析映射。"""
return {
_field_id('part_number'): part,
_field_id('reservation_id'): reservation,
_field_id('available_qty'): quantity,
}
def _inventory_upload() -> FileStorage:
"""构造带标题行和库存表头的 xlsx 样本,覆盖候选表头识别。"""
stream = BytesIO()
workbook = Workbook()
cover = workbook.active
cover.title = 'Cover'
cover['A1'] = 'Inventory report'
sheet = workbook.create_sheet('Inventory')
sheet.append(['AWS Inventory Report'])
sheet.append([])
sheet.append(['Supplier Sku', 'Reservation ID', 'Qty Available', 'Warehouse ID', 'ODM ID'])
sheet.append(['PN-001', '1000140351', 9, 'AWSDU', '0000000574'])
sheet.append(['PN-002', '1000140352', 11, 'AWSDU', '0000000574'])
workbook.save(stream)
stream.seek(0)
return FileStorage(stream=stream, filename='inventory-sample.xlsx')
def _published_part_number() -> str:
"""建立草稿创建所需的已发布订单明细字段并返回稳定字段 ID。"""
order_schema_service.initialize_schema({'display_name': 'Inventory Analysis'}, actor_id=None)
field = order_schema_service.save_field({
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
draft = order_schema_service.create_draft({}, actor_id=None)
saved = order_schema_service.save_draft(draft['id'], {'fields': [{
'field_id': field['id'], 'display_name': '内部料号', 'required': True, 'aliases': [],
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_table'],
'conflict_policy': 'block', 'allow_single_source': True,
},
'relation_role': None, 'comparator_key': 'normalized_text',
'extraction_instruction': '提取内部料号',
}], 'expected_lock_version': draft['lock_version']})
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
return field['id']
def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_path):
"""上传样本必须定位真实库存表头,并仅返回少量样例和值类型统计。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
result = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
assert result['file_format'] == 'xlsx'
assert result['structure']['selected_sheet_name'] == 'Inventory'
assert result['structure']['selected_header_row_index'] == 3
# 用户字段名称与来源表头不同,后端不得通过内置业务词典擅自猜测。
assert result['suggested_mapping'] == {}
columns = result['structure']['selected_columns']
qty = next(column for column in columns if column['header'] == 'Qty Available')
assert qty['inferred_type'] == 'number'
assert qty['sample_values'] == ['9', '11']
def test_sample_analysis_reads_legacy_xls(app, tmp_path):
"""旧 xls 样本必须走 xlrd 分析并保留其真实文件格式,不能要求用户先转换。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
template = Path(__file__).resolve().parents[1] / 'templates' / 'maintenance_record_history_template.xls'
with app.app_context():
upload = FileStorage(stream=BytesIO(template.read_bytes()), filename='legacy-inventory.xls')
result = inventory_structure_analysis.create_sample_upload(upload, actor_id=None)
assert result['file_format'] == 'xls'
assert result['structure']['selected_headers']
def test_profile_draft_rejects_source_header_not_present_in_analysis(app, tmp_path):
"""草稿不能提交浏览器伪造的来源栏位,必须只使用分析结果中的真实表头。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
field_id = _published_part_number()
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
with pytest.raises(ValidationError) as exc_info:
inventory_structure_analysis.create_profile_draft(analysis['id'], {
'profile_code': 'INVALID_HEADERS', 'display_name': 'Invalid',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(part='Made Up'),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID'
def test_profile_draft_rejects_duplicate_source_header(app, tmp_path):
"""同名来源栏位不能作为映射目标,避免运行期按第一列静默解析。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
field_id = _published_part_number()
stream = BytesIO()
workbook = Workbook()
sheet = workbook.active
sheet.append(['Supplier Sku', 'Supplier Sku', 'Reservation ID', 'Qty Available'])
sheet.append(['PN-1', 'PN-OTHER', '1000140351', 9])
workbook.save(stream)
stream.seek(0)
analysis = inventory_structure_analysis.create_sample_upload(
FileStorage(stream=stream, filename='duplicate.xlsx'), actor_id=None,
)
with pytest.raises(ValidationError) as exc_info:
inventory_structure_analysis.create_profile_draft(analysis['id'], {
'profile_code': 'DUPLICATE_HEADERS', 'display_name': 'Duplicate',
'sheet_name': 'Sheet', 'header_row_index': 1,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID'
def test_profile_draft_uses_analysis_header_selection(app, tmp_path):
"""确认的工作表、表头和来源栏位能创建可继续编辑的库存文件解析方案草稿。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
field_id = _published_part_number()
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
'profile_code': 'AWS_INVENTORY', 'display_name': 'AWS 库存文件',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
}, actor_id=None)
assert profile['status'] == 'draft'
assert profile['definition']['sheet_name'] == 'Inventory'
assert profile['definition']['field_mapping'][_field_id('part_number')] == 'Supplier Sku'
def test_sample_analysis_rejects_invalid_file(app, tmp_path):
"""伪装为 xlsx 的非工作簿必须被拒绝,且不留下分析记录。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
upload = FileStorage(stream=BytesIO(b'not a workbook'), filename='invalid.xlsx')
with pytest.raises(ValidationError) as exc_info:
inventory_structure_analysis.create_sample_upload(upload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID'
@@ -0,0 +1,173 @@
"""验证正式库存文件结构漂移必须在入库前受控处理。"""
from __future__ import annotations
from pathlib import Path
import pytest
from openpyxl import Workbook
from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryFile,
ShippingInventoryParsingProfile, ShippingInventorySource, ShippingRpaProfile,
)
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition
def _workbook(path: Path, headers: list[str]) -> None:
"""创建可控表头的库存文件,用于模拟货代导出格式变化。"""
workbook = Workbook()
sheet = workbook.active
sheet.append(headers)
values = {
'Supplier Sku': 'PN-1', 'Reservation ID': '1000140351', 'Qty Available': 9,
'Custom Part': 'PN-CUSTOM', 'Custom Reservation': '1000140999', 'Custom Quantity': 7,
'Export Time': '2026-07-17',
}
sheet.append([values.get(header, 'value') for header in headers])
workbook.save(path)
def _multi_sheet_workbook(path: Path) -> None:
"""创建含相似工作表的文件,验证正式校验不会选错已确认工作表。"""
workbook = Workbook()
summary = workbook.active
summary.title = 'Summary'
# Summary 表刻意缺少关键栏位,不能影响已配置 Inventory 表的正式校验。
summary.append(['Changed Part', 'Reservation ID', 'Qty Available'])
summary.append(['SUMMARY-PN', '1000140351', 99])
inventory = workbook.create_sheet('Inventory')
inventory.append(['Supplier Sku', 'Reservation ID', 'Qty Available'])
inventory.append(['PN-1', '1000140351', 9])
workbook.save(path)
def _source_with_profile(path: Path) -> ShippingInventorySource:
"""从基准文件建立已启用站点和已发布方案,模拟完成全部启用前校验后的状态。"""
structure, _suggested, _summary, _warnings = _analyse_path(path, '.xlsx')
definition = structure_definition(
file_format='xlsx', sheet_name='Sheet', header_row_index=1,
headers=structure['selected_headers'],
)
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.filter_by(status='active').all()}
profile = ShippingInventoryParsingProfile(
profile_code='DRIFT_PROFILE', display_name='Drift Profile', version=1, status='published', file_format='xlsx',
definition_json={'sheet_name': 'Sheet', 'header_row_index': 1, 'field_mapping': {
inventory_fields['part_number']: 'Supplier Sku', inventory_fields['reservation_id']: 'Reservation ID',
inventory_fields['available_qty']: 'Qty Available',
}, 'match_keys': []}, structure_definition_json=definition,
exact_structure_fingerprint=exact_fingerprint(definition), checksum='1' * 64,
)
rpa = ShippingRpaProfile(
profile_code='DRIFT_LOGIN', display_name='Drift Login', connector_type='dbs',
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
)
template = ShippingExcelTemplate(
template_code='DRIFT_TEMPLATE', display_name='Drift Template', version=1, status='published',
storage_bucket='test', storage_key='drift.xlsx', original_filename='drift.xlsx', file_checksum='0' * 64,
definition_json={'mappings': [{'source_kind': 'inventory_field', 'source_key': 'part_number'}]},
definition_checksum='2' * 64,
)
source = ShippingInventorySource(
source_code='DRIFT_SOURCE', display_name='Drift Source', connector_type='dbs', rpa_profile=rpa,
parsing_profile=profile, excel_template=template, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
query_parameters_json=[], match_aliases_json=[], enabled=True,
)
db.session.add(source)
db.session.commit()
return source
def test_production_structure_accepts_exact_and_noncritical_column_change(app, tmp_path):
"""同结构和仅新增无关栏位可入库,但结果需明确标注一致性等级。"""
with app.app_context():
baseline = tmp_path / 'baseline.xlsx'
_workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available'])
_source_with_profile(baseline)
exact = validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=baseline)
assert exact['level'] == 'exact'
compatible = tmp_path / 'compatible.xlsx'
_workbook(compatible, ['Supplier Sku', 'Reservation ID', 'Qty Available', 'Export Time'])
result = validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=compatible)
assert result['level'] == 'compatible'
assert 'export time' in result['difference']['added_columns']
def test_production_structure_blocks_core_column_drift(app, tmp_path):
"""关键库存栏位改名后必须阻断,禁止运行期自动猜测新来源列。"""
with app.app_context():
baseline = tmp_path / 'baseline.xlsx'
_workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available'])
_source_with_profile(baseline)
drifted = tmp_path / 'drifted.xlsx'
_workbook(drifted, ['Changed Part', 'Reservation ID', 'Qty Available'])
with pytest.raises(ConflictError) as blocked:
validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=drifted)
assert blocked.value.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED'
def test_production_structure_uses_configured_worksheet_not_best_guess(app, tmp_path):
"""多工作表文件必须依赖方案指定工作表,不能被其他错误工作表影响。"""
with app.app_context():
baseline = tmp_path / 'baseline.xlsx'
_workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available'])
source = _source_with_profile(baseline)
source.parsing_profile.definition_json = {
**source.parsing_profile.definition_json,
'sheet_name': 'Inventory',
}
source.parsing_profile.structure_definition_json = structure_definition(
file_format='xlsx', sheet_name='Inventory', header_row_index=1,
headers=['Supplier Sku', 'Reservation ID', 'Qty Available'],
)
source.parsing_profile.exact_structure_fingerprint = exact_fingerprint(
source.parsing_profile.structure_definition_json,
)
db.session.commit()
_multi_sheet_workbook(tmp_path / 'multi-sheet.xlsx')
result = validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=tmp_path / 'multi-sheet.xlsx')
assert result['level'] == 'exact'
assert result['sheet_name'] == 'Inventory'
def test_snapshot_reread_uses_published_profile_not_header_guess(app, tmp_path):
"""正式快照丢失缓存行后仍按绑定方案重读,不能回退自动表头猜测。"""
with app.app_context():
path = tmp_path / 'configured-only.xlsx'
_workbook(path, ['Custom Part', 'Custom Reservation', 'Custom Quantity'])
source = _source_with_profile(path)
fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
source.parsing_profile.definition_json = {
'sheet_name': 'Sheet', 'header_row_index': 1,
'field_mapping': {
fields['part_number']: 'Custom Part',
fields['reservation_id']: 'Custom Reservation',
fields['available_qty']: 'Custom Quantity',
},
'match_keys': [],
}
snapshot = ShippingInventoryFile(
inventory_file_no='INV-REREAD-001', storage_path=str(path), source_code=source.source_code,
warehouse_id='DUB', snapshot_status='ready', inventory_lines_json=None,
)
db.session.add(snapshot)
db.session.commit()
lines, meta = parse_inventory_snapshot_file(snapshot)
assert lines == [{
fields['part_number']: 'PN-CUSTOM',
fields['reservation_id']: '1000140999',
fields['available_qty']: 7.0,
}]
assert 'part_number' not in lines[0]
assert str(meta['mapping_source']).startswith('parsing_profile:DRIFT_PROFILE:v1')
@@ -0,0 +1,71 @@
"""
用途:验证旧任务级库存映射缓存表迁移可独立升级和回滚。
依赖:Alembic Operations、SQLAlchemy SQLite、fb1c2d3e4f5a 迁移。
逻辑:创建旧表结构,升级后确认删除;回滚后确认仅恢复历史结构和索引。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def _load_migration():
"""加载旧库存映射缓存移除迁移。"""
path = Path(__file__).parents[1] / 'migrations' / 'versions' / 'fb1c2d3e4f5a_remove_legacy_inventory_mapping_cache.py'
spec = importlib.util.spec_from_file_location('legacy_inventory_mapping_removal', path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_legacy_inventory_mapping_cache_migration_round_trip():
"""升级必须物理删除旧表,回滚只恢复可迁移的历史表结构。"""
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
sa.Table(
'shipping_inventory_mappings',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('customer_code', sa.String(64), nullable=False),
sa.Column('header_hash', sa.String(64), nullable=False),
sa.Column('headers_json', sa.JSON()),
sa.Column('field_mapping_json', sa.JSON(), nullable=False),
sa.Column('last_used_at', sa.DateTime()),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
)
with engine.begin() as connection:
metadata.create_all(connection)
context = MigrationContext.configure(connection)
operations = Operations(context)
migration = _load_migration()
migration.op = operations
migration.upgrade()
assert 'shipping_inventory_mappings' not in sa.inspect(connection).get_table_names()
migration.downgrade()
inspector = sa.inspect(connection)
assert 'shipping_inventory_mappings' in inspector.get_table_names()
assert {item['name'] for item in inspector.get_columns('shipping_inventory_mappings')} == {
'id',
'customer_code',
'header_hash',
'headers_json',
'field_mapping_json',
'last_used_at',
'created_at',
'updated_at',
}
assert {
'ix_shipping_inventory_mappings_customer_code',
'ix_shipping_inventory_mappings_created_at',
'ix_shipping_inventory_mappings_updated_at',
}.issubset({item['name'] for item in inspector.get_indexes('shipping_inventory_mappings')})
+8 -8
View File
@@ -63,12 +63,12 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d
trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id=scope_id)
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_MOCK"] = "false"
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
return trigger_dir
@@ -128,11 +128,11 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_MOCK"] = "false"
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
with app.app_context():
record_rpa_worker_heartbeat(
@@ -150,7 +150,7 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
"""生产策略要求 Redis 时,写入失败应抛存储不可用。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
monkeypatch.setattr(
@@ -171,11 +171,11 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path
trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_MOCK"] = "false"
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
@@ -367,7 +367,7 @@ def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path)
trigger_dir.mkdir(parents=True)
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config.pop("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", None)
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
assert shared_scope_id() == "hxops-rpa-test-data"
@@ -32,7 +32,7 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
@@ -41,7 +41,7 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = ""
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
app.config["FREIGHT_RPA_MOCK"] = "false"
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
return trigger_dir
+37 -14
View File
@@ -19,6 +19,15 @@ from app.services.schedule.job_params import (
)
def _enabled_source_code() -> str:
"""读取测试数据库的首个启用库存源,避免测试依赖已废弃 YAML 的固定编码。"""
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
sources = list_database_inventory_sources()
assert sources, 'expected at least one enabled inventory source'
return str(sources[0]['source_code'])
@pytest.fixture
def admin_jwt_headers(app):
"""创建 admin 用户并签发 Bearer JWT。"""
@@ -80,7 +89,8 @@ def test_platform_task_options_shipping_sources(client, admin_jwt_headers, app):
assert options, 'expected at least one enabled inventory source'
assert all('label' in item and 'value' in item for item in options)
values = {item['value'] for item in options}
assert 'DSV360_AWSBI_BYAWSATL01' in values
with app.app_context():
assert _enabled_source_code() in values
def test_platform_task_options_unknown_source_rejected(client, admin_jwt_headers):
@@ -112,10 +122,11 @@ def test_validate_task_params_rejects_unknown_key(app):
def test_validate_task_params_rejects_wrong_type(app):
"""multi_select 传入非 list 应报类型错误。"""
with app.app_context():
source_code = _enabled_source_code()
with pytest.raises(JobParamsValidationError, match='list of option values'):
validate_task_params(
'shipping-inventory-rpa',
{'source_codes': 'DSV360_AWSBI_BYAWSATL01'},
{'source_codes': source_code},
check_options=False,
)
@@ -123,6 +134,7 @@ def test_validate_task_params_rejects_wrong_type(app):
def test_validate_task_params_checks_option_range(app):
"""check_options=True 时,multi_select 值不在选项范围内应报错。"""
with app.app_context():
source_code = _enabled_source_code()
with pytest.raises(JobParamsValidationError, match='not in options'):
validate_task_params(
'shipping-inventory-rpa',
@@ -132,10 +144,10 @@ def test_validate_task_params_checks_option_range(app):
# 合法值应通过
result = validate_task_params(
'shipping-inventory-rpa',
{'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
{'source_codes': [source_code]},
check_options=True,
)
assert result['source_codes'] == ['DSV360_AWSBI_BYAWSATL01']
assert result['source_codes'] == [source_code]
def test_validate_task_params_passes_advanced_through(app):
@@ -186,16 +198,18 @@ def owner_id(app):
def test_post_schedule_persists_valid_job_params(client, admin_jwt_headers, owner_id, app):
"""合法 job_params 应持久化并出现在 serialize_task 响应中。"""
with app.app_context():
source_code = _enabled_source_code()
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
job_params={'source_codes': [source_code]},
)
assert res.status_code == 201
body = res.get_json()
assert body['job_params'] == {'source_codes': ['DSV360_AWSBI_BYAWSATL01']}
assert body['job_params'] == {'source_codes': [source_code]}
with app.app_context():
task = db.session.get(ScheduleTask, body['id'])
assert task.job_params == {'source_codes': ['DSV360_AWSBI_BYAWSATL01']}
assert task.job_params == {'source_codes': [source_code]}
def test_post_schedule_without_job_params_applies_schema_defaults(client, admin_jwt_headers, owner_id, app):
@@ -254,9 +268,11 @@ def test_post_data_pipeline_rejects_job_params(client, admin_jwt_headers, owner_
def test_patch_schedule_updates_and_clears_job_params(client, admin_jwt_headers, owner_id, app):
"""PATCH 应支持更新;显式 null 对有 schema 的任务重置为默认值。"""
with app.app_context():
source_code = _enabled_source_code()
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
job_params={'source_codes': [source_code]},
)
task_id = res.get_json()['id']
@@ -275,9 +291,11 @@ def test_patch_schedule_updates_and_clears_job_params(client, admin_jwt_headers,
def test_patch_platform_api_path_resets_job_params_to_new_defaults(client, admin_jwt_headers, owner_id, app):
"""切换 platform_api_path 且未传 job_params 时,应按新任务 schema 重置,避免旧参数残留。"""
with app.app_context():
source_code = _enabled_source_code()
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
job_params={'source_codes': [source_code]},
)
task_id = res.get_json()['id']
@@ -295,9 +313,11 @@ def test_patch_platform_api_path_resets_job_params_to_new_defaults(client, admin
def test_patch_platform_api_path_to_schemaless_clears_job_params(client, admin_jwt_headers, owner_id, app):
"""切换到无 params_schema 的平台任务且未传 job_params 时应清空旧参数。"""
with app.app_context():
source_code = _enabled_source_code()
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
job_params={'source_codes': [source_code]},
)
task_id = res.get_json()['id']
@@ -310,11 +330,13 @@ def test_patch_platform_api_path_to_schemaless_clears_job_params(client, admin_j
assert body['job_params'] is None
def test_patch_platform_api_path_with_explicit_job_params_keeps_payload(client, admin_jwt_headers, owner_id):
def test_patch_platform_api_path_with_explicit_job_params_keeps_payload(client, admin_jwt_headers, owner_id, app):
"""切换 platform_api_path 同时显式传 job_params 时,应保留请求体参数(经新 schema 校验)。"""
with app.app_context():
source_code = _enabled_source_code()
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
job_params={'source_codes': [source_code]},
)
task_id = res.get_json()['id']
@@ -346,9 +368,10 @@ def test_shipping_rpa_filter_prefers_job_params(app):
from app.services.schedule.shipping_inventory_rpa_job import _filter_sources
with app.app_context():
task = ScheduleTask(job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']})
source_code = _enabled_source_code()
task = ScheduleTask(job_params={'source_codes': [source_code]})
sources = _filter_sources(task)
assert [item.get('source_code') for item in sources] == ['DSV360_AWSBI_BYAWSATL01']
assert [item.get('source_code') for item in sources] == [source_code]
# job_params 为空(默认值)时不筛选 → 返回全部启用源
task_all = ScheduleTask(job_params={'source_codes': []})
assert len(_filter_sources(task_all)) >= 1
@@ -1,7 +1,7 @@
"""
backend/tests/test_shipping_customer_auto_resolution.py
用途:验证受控自动客户确认、降级开关、强规则歧义和历史客户回填。
用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。
依赖:客户主数据/证据、Candidate 影子结果、ShippingTask/Case、customer_auto_resolution。
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
"""
@@ -25,7 +25,6 @@ from app.models import (
)
from app.services.shipping_notice.customer_auto_resolution import (
AUTO_RESOLUTION_VERSION,
backfill_historical_task_customer,
correct_numbered_task_customer,
get_auto_resolution_metrics,
try_auto_confirm_task_customer,
@@ -100,10 +99,17 @@ def _customer_with_identifier(*, code: str, value: str, allowed: bool = True, st
return customer
def _allow_auto_confirmation(app) -> None:
"""为自动确认专项用例显式放宽门禁,不改变生产默认安全阈值。"""
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 0
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
"""开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。"""
with app.app_context():
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
_allow_auto_confirmation(app)
customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
task = _seed_candidate_task()
@@ -132,7 +138,7 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
assert disabled["status"] == "disabled"
assert task.shipping_case.business_no is None
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
_allow_auto_confirmation(app)
unmatched = try_auto_confirm_task_customer(task)
assert unmatched["status"] == "unmatched"
assert task.customer_resolution_status == "pending"
@@ -142,7 +148,7 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
"""同一强证据映射多个客户时必须降级人工确认。"""
with app.app_context():
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
_allow_auto_confirmation(app)
_customer_with_identifier(code="AAA", value="buyer@wyc.example.com")
_customer_with_identifier(code="BBB", value="buyer@wyc.example.com")
task = _seed_candidate_task()
@@ -154,29 +160,10 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
assert task.shipping_case.business_no is None
def test_historical_backfill_binds_customer_without_numbering(app):
"""历史任务回填客户后业务号仍为空,不倒占当日流水。"""
with app.app_context():
customer = ShippingCustomer(standard_name="历史客户", short_code="HIS", status="active")
task = ShippingTask(task_no="SN-20200101-HISTORY", source_type="manual", process_status="closed")
db.session.add_all([customer, task])
db.session.commit()
result = backfill_historical_task_customer(task, customer_id=customer.id, actor_id=None)
assert result["business_no"] is None
assert task.shipping_case.customer_id == customer.id
assert task.shipping_case.numbering_status == "historical_unnumbered"
assert task.shipping_case.business_no is None
assert task.customer_resolution_method == "historical_backfill"
metrics = get_auto_resolution_metrics()
assert metrics["historical_backfilled_count"] == 1
assert metrics["recent_events"][0]["event_type"] == "customer_historical_backfilled"
def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
"""批次编排失败时,自动确认、编号和审计必须随外层事务整体回滚。"""
with app.app_context():
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
_allow_auto_confirmation(app)
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
task = _seed_candidate_task()
task_id = task.id
@@ -195,6 +182,48 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0
def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insufficient(app):
"""总开关开启但没有足够人工真值时,必须保持人工客户复核和未编号状态。"""
with app.app_context():
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 1
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
task = _seed_candidate_task()
result = try_auto_confirm_task_customer(task)
assert result["status"] == "insufficient_labeled_samples"
assert result["quality_gate"]["labeled_sample_count"] == 0
assert task.customer_resolution_status == "pending"
assert task.shipping_case.business_no is None
def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app):
"""有足够样本但强规则与人工真值不一致时,自动确认必须安全降级。"""
with app.app_context():
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 1
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
matched = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
truth = ShippingCustomer(standard_name="真实客户", short_code="TRU", status="active")
db.session.add(truth)
db.session.flush()
task = _seed_candidate_task()
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
shadow.manual_customer_id = truth.id
db.session.commit()
result = try_auto_confirm_task_customer(task)
assert matched.id != truth.id
assert result["status"] == "insufficient_accuracy"
assert result["quality_gate"]["labeled_sample_count"] == 1
assert result["quality_gate"]["accuracy"] == 0
assert task.customer_resolution_status == "pending"
assert task.shipping_case.business_no is None
def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
"""客户误确认纠错必须保留原号作废,生成新客户编号并让原号查询跟随替代单。"""
with app.app_context():
@@ -3,7 +3,7 @@ backend/tests/test_shipping_customer_identity_gate.py
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。
依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。
逻辑:构造 pending 任务逐入口断言无副作用;确认后验证业务单/修订同步和历史兼容。
逻辑:构造 pending 或缺失业务单的任务逐入口断言无副作用;确认后验证业务单/修订同步。
"""
from __future__ import annotations
@@ -26,7 +26,7 @@ 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.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
@@ -71,7 +71,6 @@ def test_pending_customer_blocks_every_downstream_entry(app):
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,
@@ -140,8 +139,8 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
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):
"""已确认客户停用后重新阻断;历史无业务单任务继续兼容。"""
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)
@@ -151,9 +150,11 @@ def test_inactive_customer_reblocks_and_legacy_task_is_compatible(app):
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
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):
@@ -1,7 +1,7 @@
"""
backend/tests/test_shipping_customer_migrations.py
用途:独立验证客户主数据、期初导入与影子识别三段迁移可升级和降级。
用途:独立验证客户主数据、期初导入、影子识别与生命周期基础迁移可升级和降级。
依赖:Alembic MigrationContext、SQLAlchemy、f1/a2/b3 客户迁移模块。
逻辑:构造订单抽取阶段的最小历史结构,依序执行迁移并检查约束,再逆序回滚。
"""
@@ -28,13 +28,15 @@ def _customer_pre_migration_schema(engine: sa.Engine) -> None:
def test_shipping_customer_migrations_upgrade_and_downgrade():
"""三段客户迁移应建立关键约束,并能逆序移除全部新增结构。"""
"""客户迁移应建立关键约束、回填影子候选,并能逆序移除新增结构。"""
engine = sa.create_engine('sqlite:///:memory:')
_customer_pre_migration_schema(engine)
modules = [
importlib.import_module('migrations.versions.f1a2b3c4d5e6_shipping_customer_case_foundation'),
importlib.import_module('migrations.versions.a2c3d4e5f6a7_shipping_customer_imports'),
importlib.import_module('migrations.versions.b3d4e5f6a7b8_shipping_customer_shadow_resolution'),
importlib.import_module('migrations.versions.5d6e7f8a9b0c_shipping_customer_lifecycle_foundation'),
importlib.import_module('migrations.versions.6e7f8a9b0c1d_shipping_customer_merge_foundation'),
]
with engine.begin() as connection:
@@ -55,6 +57,9 @@ def test_shipping_customer_migrations_upgrade_and_downgrade():
'shipping_customer_import_batches',
'shipping_customer_import_rows',
'shipping_customer_shadow_resolutions',
'shipping_customer_shadow_matches',
'shipping_customer_lifecycle_events',
'shipping_customer_merges',
} <= set(inspector.get_table_names())
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
assert {'shipping_case_id', 'customer_resolution_status', 'customer_confirmed_at'} <= task_columns
@@ -82,6 +87,9 @@ def test_shipping_customer_migrations_upgrade_and_downgrade():
assert 'shipping_customers' not in remaining
assert 'shipping_customer_import_batches' not in remaining
assert 'shipping_customer_shadow_resolutions' not in remaining
assert 'shipping_customer_shadow_matches' not in remaining
assert 'shipping_customer_lifecycle_events' not in remaining
assert 'shipping_customer_merges' not in remaining
task_columns = {column['name'] for column in sa.inspect(connection).get_columns('shipping_tasks')}
assert 'shipping_case_id' not in task_columns
finally:
@@ -15,6 +15,7 @@ from app.models import (
ShippingCustomer,
ShippingCustomerIdentifier,
ShippingCustomerShadowResolution,
ShippingCustomerShadowMatch,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
@@ -90,6 +91,7 @@ def test_shadow_resolution_uses_strong_evidence_without_binding_case(app):
assert resolution.status == 'unique_candidate'
assert resolution.top_customer_id == customer.id
assert resolution.top_score == 100.0
assert db.session.query(ShippingCustomerShadowMatch).filter_by(customer_id=customer.id).count() == 1
assert case.customer_id is None
assert case.business_no is None
assert get_shadow_quality_report()['auto_bound_count'] == 0
@@ -107,6 +109,7 @@ def test_shadow_resolution_reports_ambiguous_and_unmatched(app):
assert ambiguous.status == 'ambiguous'
assert ambiguous.top_customer_id is None
assert len(ambiguous.candidate_matches_json) == 2
assert len(ambiguous.matches) == 2
assert unmatched.status == 'unmatched'
assert unmatched.candidate_matches_json == []
@@ -0,0 +1,490 @@
"""
用途:验证版本化发货 Excel 模板发布、库存源共享绑定及动态字段导出产物审计。
依赖:excel_template/export 服务、openpyxl、订单动态 Schema 与库存配置模型。
逻辑:创建真实 xlsx 草稿并发布,生成任务产物后断言 Header/Line 写入及版本锁定字段。
"""
from __future__ import annotations
from datetime import date
from io import BytesIO
from unittest.mock import patch
from openpyxl import Workbook, load_workbook
from werkzeug.datastructures import FileStorage
import pytest
from app import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingTask,
)
from app.services.shipping_notice import excel_template
from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
from app.core.errors import ValidationError
def _inventory_field_id(field_code: str) -> str:
"""返回库存字段目录 ID,使模板测试覆盖当前发布契约。"""
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
@pytest.fixture(autouse=True)
def _template_object_storage(monkeypatch):
"""使用内存私有对象存储替身,验证模板不依赖本机文件系统。"""
objects: dict[str, bytes] = {}
def upload_bytes(*, storage_key: str, data: bytes, content_type: str) -> None:
objects[storage_key] = bytes(data)
def get_bytes(storage_key: str) -> bytes:
if storage_key not in objects:
raise RuntimeError(f'missing test object: {storage_key}')
return objects[storage_key]
def delete_object(storage_key: str) -> None:
objects.pop(storage_key, None)
for module in ('app.services.shipping_notice.excel_template', 'app.services.shipping_notice.export'):
monkeypatch.setattr(f'{module}.file_asset_storage.upload_bytes', upload_bytes)
monkeypatch.setattr(f'{module}.file_asset_storage.get_bytes', get_bytes)
monkeypatch.setattr(f'{module}.file_asset_storage.delete_object', delete_object)
monkeypatch.setattr(f'{module}.file_asset_storage.bucket_name', 'test-template-bucket')
return objects
def _workbook_upload() -> FileStorage:
"""构造含 Header/Detail 工作表的内存 xlsx 上传对象。"""
stream = BytesIO()
wb = Workbook()
wb.active.title = 'Header'
wb.create_sheet('Detail')
wb.save(stream)
stream.seek(0)
return FileStorage(stream=stream, filename='shipping.xlsx', content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
def test_filename_pattern_supports_business_number_and_split_business_variables():
"""业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。"""
shipping_case = ShippingCase(
case_no='CASE-FILENAME', business_no='WYC26060201', customer_short_code_snapshot='WYC',
business_date=date(2026, 6, 2), sequence_value=1,
)
task = ShippingTask(task_no='TASK-FILENAME', inventory_source_code='DBS')
task.shipping_case = shipping_case
template = ShippingExcelTemplate(
template_code='FILENAME', display_name='Filename',
definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'},
)
assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx'
def test_published_template_generates_dynamic_artifact(app, tmp_path):
"""发布模板后按稳定 field_id 写入订单值,并锁定模板、Schema、Profile 与库存快照。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add(schema)
db.session.flush()
customer = ShippingOrderField(schema_id=schema.id, field_code='customer_code', scope='header', value_type='string')
po_number = ShippingOrderField(schema_id=schema.id, field_code='po_number', scope='header', value_type='string')
part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string')
db.session.add_all([customer, po_number, part])
db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={
'fields': [{'field_id': customer.id}, {'field_id': po_number.id}, {'field_id': part.id}],
}, checksum='s' * 64)
db.session.add(version)
db.session.flush()
definition = {
'filename_pattern': 'shipment_{task_no}_{date}.xlsx',
'mappings': [
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'order_field', 'source_key': customer.id, 'formatter': 'upper'},
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 2, 'source_kind': 'system_fact', 'source_key': 'warehouse_id', 'formatter': 'text'},
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 3, 'source_kind': 'system_fact', 'source_key': 'export_date', 'formatter': 'date_mmddyyyy'},
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 1, 'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text'},
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 2, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 3, 'source_kind': 'order_field', 'source_key': po_number.id, 'formatter': 'text'},
],
}
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'COMMON_SHIPMENT', 'display_name': 'Common Shipment', 'definition': definition,
}, actor_id=None)
published = excel_template.publish(draft['id'], actor_id=None)
parsing = ShippingInventoryParsingProfile(
profile_code='COMMON_INV', display_name='Common Inventory', version=1, status='published',
file_format='xlsx', definition_json={
'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'},
'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}],
}, checksum='p' * 64,
)
login = ShippingRpaProfile(
profile_code='LOGIN', display_name='Login', connector_type='dbs', login_url='https://invalid',
login_config_json={'auth_mode': 'password'},
)
db.session.add_all([parsing, login])
db.session.flush()
source = ShippingInventorySource(
source_code='DUB', display_name='Dublin', connector_type='dbs', rpa_profile_id=login.id,
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], match_aliases_json=[],
)
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
db.session.add_all([source, extraction])
db.session.flush()
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
db.session.add(order_line)
db.session.flush()
header_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=customer.id, decision_status='accepted', resolved_value_json='acme')
po_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=po_number.id, decision_status='accepted', resolved_value_json='16754796')
line_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, decision_status='accepted', resolved_value_json='PN-1')
db.session.add_all([header_decision, po_decision, line_decision])
db.session.flush()
db.session.add_all([
ShippingOrderFieldValue(extraction_id=extraction.id, field_id=customer.id, value_text='acme', decision_id=header_decision.id),
ShippingOrderFieldValue(extraction_id=extraction.id, field_id=po_number.id, value_text='16754796', decision_id=po_decision.id),
ShippingOrderFieldValue(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, value_text='PN-1', decision_id=line_decision.id),
])
task = ShippingTask(
task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB',
inventory_warehouse_id='DUB', inventory_lines_json=[{
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
}], inventory_snapshot_id=None,
)
db.session.add(task)
db.session.flush()
path, filename, artifact = generate_shipment_excel(task)
db.session.commit()
wb = load_workbook(path, read_only=True)
assert wb['Header'].cell(2, 1).value == 'ACME' # Header 动态字段及 formatter 生效。
assert wb['Header'].cell(2, 2).value == 'DUB' # 受控系统事实写入目标列。
assert wb['Header'].cell(2, 3).value == _system_fact(task, 'export_date').strftime('%m/%d/%Y')
assert wb['Detail'].cell(3, 1).value == 'PN-1' # Line 字段按订单行写入。
assert wb['Detail'].cell(3, 2).value == 'ODM-9' # 标准库存字段无需 LLM 判断。
assert wb['Detail'].cell(3, 3).value == '16754796' # Header 字段按业务要求重复到每条明细。
wb.close()
assert filename.startswith('shipment_TASK-EXPORT-1_')
assert artifact.template_id == published['id']
assert artifact.order_schema_version_id == version.id
assert artifact.inventory_parsing_profile_id == parsing.id
assert artifact.file_checksum and artifact.input_checksum and artifact.file_size > 0
# Dynamic inventory sources must resolve Warehouse before any export can be created.
task.inventory_warehouse_id = None
with pytest.raises(ValueError, match='缺少已解析的 Warehouse ID'):
generate_shipment_excel(task)
def test_header_mapping_rejects_line_order_field(app):
"""订单头区域不得引用明细字段,避免把多行值错误压缩为单个表头值。"""
with app.app_context():
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add(schema)
db.session.flush()
part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string')
db.session.add(part)
db.session.flush()
db.session.add(ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published',
definition_json={'fields': [{'field_id': part.id}]}, checksum='s' * 64,
))
db.session.flush()
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'INVALID_HEADER_LINE', 'display_name': 'Invalid Header Line',
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [{
'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 1,
'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text',
}]},
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
excel_template.publish(draft['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID'
def test_export_date_system_fact_uses_business_timezone(app):
"""导出日期必须返回上海业务时区的日期对象,供模板统一格式化。"""
with app.app_context():
value = _system_fact(ShippingTask(task_no='TASK-DATE'), 'export_date')
assert isinstance(value, date)
def test_two_sources_can_share_one_published_excel_template(app, tmp_path):
"""同结构库存源绑定同一 published 模板,避免复制维护映射规则。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'SHARED', 'display_name': 'Shared',
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1, 'source_kind': 'constant', 'source_key': 'n', 'formatter': 'text'},
]},
}, actor_id=None)
published = excel_template.publish(draft['id'], actor_id=None)
parsing = ShippingInventoryParsingProfile(
profile_code='SHARED_INV', display_name='Shared Inventory', version=1, status='published',
file_format='xlsx', definition_json={}, checksum='p' * 64,
)
login = ShippingRpaProfile(
profile_code='SHARED_LOGIN', display_name='Shared Login', connector_type='dbs',
login_url='https://invalid', login_config_json={'auth_mode': 'password'},
)
db.session.add_all([parsing, login])
db.session.flush()
for code in ('DUB', 'RTM'):
db.session.add(ShippingInventorySource(
source_code=code, display_name=code, connector_type='dbs', rpa_profile_id=login.id,
parsing_profile_id=parsing.id, excel_template_id=published['id'],
warehouse_resolution_mode='fixed', fixed_warehouse_id=code,
report_path_json={}, query_parameters_json=[], match_aliases_json=[],
))
db.session.commit()
template = db.session.get(ShippingExcelTemplate, published['id'])
assert template is not None
assert {source.source_code for source in template.sources} == {'DUB', 'RTM'} # 一个发布版本供多个 Source 共享。
def test_disabled_source_still_blocks_template_retirement(app):
"""禁用库存源仍保留模板配置引用,迁移前不得退役其模板版本。"""
with app.app_context():
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'DISABLED_REF', 'display_name': 'Disabled Ref',
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [{
'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1,
'source_kind': 'constant', 'source_key': 'x', 'formatter': 'text',
}]},
}, actor_id=None)
published = excel_template.publish(draft['id'], actor_id=None)
login = ShippingRpaProfile(
profile_code='DISABLED_REF', display_name='Disabled Ref', connector_type='dbs',
login_url='https://invalid', login_config_json={'auth_mode': 'password'},
)
db.session.add(login)
db.session.flush()
db.session.add(ShippingInventorySource(
source_code='DISABLED_REF', display_name='Disabled Ref', connector_type='dbs', enabled=False,
rpa_profile_id=login.id, excel_template_id=published['id'],
warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
report_path_json={}, query_parameters_json=[], match_aliases_json=[],
))
db.session.commit()
with pytest.raises(Exception) as exc_info:
excel_template.retire(published['id'])
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.EXCEL_TEMPLATE_RETIRE_BLOCKED'
def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path):
"""库存行顺序与订单相反时仍须按稳定 match_keys 写入正确 ODM,禁止按数组下标配对。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add(schema); db.session.flush()
part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string')
db.session.add(part); db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={
'fields': [{'field_id': part.id}],
})
db.session.add(version); db.session.flush()
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'KEYED', 'display_name': 'Keyed',
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 1, 'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text'},
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 2, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
]},
}, actor_id=None)
published = excel_template.publish(draft['id'], actor_id=None)
parsing = ShippingInventoryParsingProfile(
profile_code='KEYED', display_name='Keyed', version=1, status='published', file_format='xlsx',
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
)
login = ShippingRpaProfile(
profile_code='KEYED', display_name='Keyed', connector_type='dbs', login_url='https://invalid',
login_config_json={'auth_mode': 'password'},
)
db.session.add_all([parsing, login]); db.session.flush()
db.session.add(ShippingInventorySource(
source_code='KEYED', display_name='Keyed', connector_type='dbs', rpa_profile_id=login.id,
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], match_aliases_json=[],
))
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
db.session.add(extraction); db.session.flush()
for position, value in enumerate(('PN-A', 'PN-B'), start=1):
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_key=str(position))
db.session.add(line); db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
decision_status='accepted', 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=part.id,
value_text=value, decision_id=decision.id,
))
task = ShippingTask(
task_no='TASK-KEYED', current_order_extraction_id=extraction.id, inventory_source_code='KEYED',
inventory_warehouse_id='DUB', inventory_lines_json=[
{_inventory_field_id('part_number'): 'PN-B', _inventory_field_id('odm_id'): 'ODM-B'},
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-A'},
],
)
db.session.add(task); db.session.flush()
path, _filename, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, read_only=True)
assert workbook['Detail'].cell(2, 2).value == 'ODM-A'
assert workbook['Detail'].cell(3, 2).value == 'ODM-B'
workbook.close()
def test_template_upload_rejects_fake_xlsx_without_leaving_file(app, tmp_path, _template_object_storage):
"""扩展名伪装的无效工作簿必须在创建草稿前拒绝,模板目录不得产生孤立文件。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
fake = FileStorage(stream=BytesIO(b'not-a-workbook'), filename='fake.xlsx')
with pytest.raises(ValidationError) as exc_info:
excel_template.create_draft(fake, {
'template_code': 'FAKE', 'display_name': 'Fake', 'definition': {},
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_INVALID'
assert not _template_object_storage
def test_existing_template_can_create_new_draft_version_without_reupload(app):
"""新版本直接复制受管文件和映射定义,用户无需再次选择本地 Excel。"""
with app.app_context():
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'COPY_VERSION', 'display_name': 'Copy Version',
'definition': {'filename_pattern': '{business_no}.xlsx', 'mappings': [{
'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1,
'source_kind': 'constant', 'source_key': 'x', 'formatter': 'text',
}]},
}, actor_id=None)
published = excel_template.publish(draft['id'], actor_id=None)
copied = excel_template.create_draft_from_existing(published['id'], actor_id=None)
assert copied['version'] == 2
assert copied['status'] == 'draft'
assert copied['definition'] == draft['definition']
layout = excel_template.get_layout(copied['id'])
assert set(layout['sheets']) == {'Header', 'Detail'}
def test_template_publish_rejects_order_field_removed_from_current_schema(app):
"""模板草稿不得在订单字段移出当前 published Schema 后继续发布。"""
from app.services.shipping_notice.order_schema import service as order_schema_service
with app.app_context():
order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
old_field = order_schema_service.save_field({
'field_code': 'old_part', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
new_field = order_schema_service.save_field({
'field_code': 'new_part', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
def config(field_id: str) -> dict:
return {
'field_id': field_id, 'display_name': '内部料号', 'required': True, 'aliases': [],
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_table'],
'conflict_policy': 'block', 'allow_single_source': True,
},
'relation_role': None, 'comparator_key': 'normalized_text',
'extraction_instruction': '提取内部料号',
}
first = order_schema_service.create_draft({}, actor_id=None)
saved_schema = order_schema_service.save_draft(first['id'], {
'fields': [config(new_field['id'])], 'expected_lock_version': first['lock_version'],
})
order_schema_service.publish(
first['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
)
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'STALE_FIELD', 'display_name': 'Stale Field',
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [{
'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 1,
'source_kind': 'order_field', 'source_key': old_field['id'], 'formatter': 'text',
}]},
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
excel_template.publish(draft['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID'
def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app, tmp_path):
"""同一匹配键对应多个不同 ODM 时必须阻断,且不得留下半成品 Excel。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add(schema); db.session.flush()
part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string')
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add_all([part, version]); db.session.flush()
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'AMBIGUOUS', 'display_name': 'Ambiguous',
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 1, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
]},
}, actor_id=None)
published = excel_template.publish(draft['id'], actor_id=None)
parsing = ShippingInventoryParsingProfile(
profile_code='AMBIGUOUS', display_name='Ambiguous', version=1, status='published', file_format='xlsx',
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
)
login = ShippingRpaProfile(
profile_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', login_url='https://invalid',
login_config_json={'auth_mode': 'password'},
)
db.session.add_all([parsing, login]); db.session.flush()
db.session.add(ShippingInventorySource(
source_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', rpa_profile_id=login.id,
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], match_aliases_json=[],
))
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
db.session.add(extraction); db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
db.session.add(line); db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
decision_status='accepted', resolved_value_json='PN-A',
)
db.session.add(decision); db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
value_text='PN-A', decision_id=decision.id,
))
task = ShippingTask(
task_no='TASK-AMBIGUOUS', current_order_extraction_id=extraction.id,
inventory_source_code='AMBIGUOUS', inventory_warehouse_id='DUB', inventory_lines_json=[
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-1'},
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-2'},
],
)
db.session.add(task); db.session.flush()
with pytest.raises(ValueError, match='值不一致'):
generate_shipment_excel(task)
export_root = tmp_path / 'shipping' / 'exports'
assert not export_root.exists() or not list(export_root.rglob('*.xlsx'))
def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch):
"""Artifact/任务事务提交失败时必须删除已生成文件,避免孤立 ready-looking 产物。"""
path = tmp_path / 'orphan.xlsx'
path.write_bytes(b'orphan')
with app.app_context():
monkeypatch.setattr(db.session, 'commit', lambda: (_ for _ in ()).throw(RuntimeError('commit failed')))
with pytest.raises(RuntimeError, match='commit failed'):
_commit_generated_export(str(path))
assert not path.exists()
@@ -0,0 +1,146 @@
"""
用途:验证发货 Excel 批次 ZIP 的权限、最新 Artifact、重名、校验和与 manifest 契约。
依赖:export_archive、ShippingBatch/Task/ExportArtifact、zipfile。
逻辑:构造同批次有效、缺失及损坏产物,断言 ZIP 仅包含可信文件并完整列出排除原因。
"""
from __future__ import annotations
import hashlib
import json
from zipfile import ZipFile
import pytest
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
ShippingBatch, ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile,
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingTask, User,
)
from app.services.shipping_notice.export_archive import build_export_archive
from app.core.auth.jwt import issue_local_access_token
def _seed_artifact_dependencies():
"""创建 Artifact 外键所需的最小发布版本。"""
template = ShippingExcelTemplate(
template_code='ZIP', display_name='ZIP', version=1, status='published',
storage_provider='minio', storage_bucket='test', storage_key='test/zip-template.xlsx',
original_filename='template.xlsx', file_checksum='t' * 64, definition_json={}, definition_checksum='d' * 64,
)
parsing = ShippingInventoryParsingProfile(
profile_code='ZIP', display_name='ZIP', version=1, status='published', file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add_all([template, parsing, schema]); db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version); db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
db.session.add(extraction); db.session.flush()
return template, parsing, version, extraction
def _artifact(task, path, dependencies, *, no: str, checksum: str | None = None):
"""为任务新增 ready Artifact,checksum 默认按文件内容计算。"""
template, parsing, version, extraction = dependencies
content = path.read_bytes() if path.is_file() else b''
item = ShippingExportArtifact(
artifact_no=no, task_id=task.id, batch_id=task.batch_id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=parsing.id, input_checksum='x' * 64,
file_path=str(path), file_name='shipment.xlsx', file_checksum=checksum or hashlib.sha256(content).hexdigest(),
file_size=len(content), status='ready',
)
db.session.add(item)
task.export_file_path = str(path)
task.export_file_name = 'shipment.xlsx'
return item
def test_batch_archive_manifest_and_duplicate_names(app, tmp_path):
"""有效同名文件均进入 ZIP,缺失/损坏任务只进入 manifest 并带明确状态。"""
with app.app_context():
user = User(username='zip-owner', email='zip@example.com', role='user', status='approved')
batch = ShippingBatch(batch_no='SB-ZIP', user_id=None, file_count=4)
db.session.add_all([user, batch]); db.session.flush(); batch.user_id = user.id
tasks = [ShippingTask(task_no=f'TASK-{index}', user_id=user.id, batch_id=batch.id, batch_index=index, batch_total=4) for index in range(1, 5)]
db.session.add_all(tasks); db.session.flush()
first = tmp_path / 'first.xlsx'; first.write_bytes(b'first')
second = tmp_path / 'second.xlsx'; second.write_bytes(b'second')
corrupt = tmp_path / 'corrupt.xlsx'; corrupt.write_bytes(b'changed')
dependencies = _seed_artifact_dependencies()
_artifact(tasks[0], first, dependencies, no='EXP-1')
_artifact(tasks[1], second, dependencies, no='EXP-2')
_artifact(tasks[2], tmp_path / 'missing.xlsx', dependencies, no='EXP-3')
_artifact(tasks[3], corrupt, dependencies, no='EXP-4', checksum='0' * 64)
db.session.commit()
stream, filename, manifest = build_export_archive(user_id=user.id, batch_no=batch.batch_no)
with ZipFile(stream) as archive:
names = archive.namelist()
assert 'shipment.xlsx' in names
assert 'shipment_TASK-2.xlsx' in names # 同名按任务号消歧,避免覆盖。
archived_manifest = json.loads(archive.read('manifest.json'))
assert filename.startswith('shipping_exports_SB-ZIP_')
assert archived_manifest['included_count'] == 2
assert [entry['status'] for entry in manifest['entries']] == [
'included', 'included', 'missing_file', 'checksum_mismatch',
]
def test_archive_rejects_foreign_task_and_invalid_selection(app):
"""任一越权任务整体拒绝,且 batch_no/task_nos 不能同时或同时不传。"""
with app.app_context():
owner = User(username='archive-owner', email='archive-owner@example.com', role='user', status='approved')
other = User(username='archive-other', email='archive-other@example.com', role='user', status='approved')
task = ShippingTask(task_no='FOREIGN-TASK', user_id=owner.id)
db.session.add_all([owner, other]); db.session.flush(); task.user_id = owner.id; db.session.add(task); db.session.commit()
with pytest.raises(NotFoundError):
build_export_archive(user_id=other.id, task_nos=[task.task_no])
with pytest.raises(ValidationError):
build_export_archive(user_id=owner.id)
with pytest.raises(ValidationError):
build_export_archive(user_id=owner.id, batch_no='SB', task_nos=[task.task_no])
def test_archive_excludes_artifact_after_task_export_is_invalidated(app, tmp_path):
"""任务纠错清空当前导出引用后,旧 ready Artifact 不得继续进入下载包。"""
with app.app_context():
user = User(username='archive-reset', email='archive-reset@example.com', role='user', status='approved')
batch = ShippingBatch(batch_no='SB-RESET', user_id=None, file_count=1)
db.session.add_all([user, batch]); db.session.flush(); batch.user_id = user.id
task = ShippingTask(task_no='TASK-RESET', user_id=user.id, batch_id=batch.id, batch_index=1, batch_total=1)
db.session.add(task); db.session.flush()
path = tmp_path / 'old.xlsx'; path.write_bytes(b'old')
_artifact(task, path, _seed_artifact_dependencies(), no='EXP-OLD')
task.export_file_path = None
task.export_file_name = None
db.session.commit()
_stream, _filename, manifest = build_export_archive(user_id=user.id, batch_no=batch.batch_no)
assert manifest['included_count'] == 0
assert manifest['entries'][0]['status'] == 'missing_artifact'
def test_workspace_archive_api_returns_zip(app, client, tmp_path):
"""Workspace API 必须以当前用户权限生成 attachment ZIP,而不是暴露服务器文件路径。"""
with app.app_context():
user = User(username='archive-api', email='archive-api@example.com', role='user', status='approved')
db.session.add(user); db.session.flush()
batch = ShippingBatch(batch_no='SB-API-ZIP', user_id=user.id, file_count=1)
db.session.add(batch); db.session.flush()
task = ShippingTask(task_no='TASK-API-ZIP', user_id=user.id, batch_id=batch.id, batch_index=1, batch_total=1)
db.session.add(task); db.session.flush()
path = tmp_path / 'api.xlsx'; path.write_bytes(b'api-content')
_artifact(task, path, _seed_artifact_dependencies(), no='EXP-API')
db.session.commit()
token = issue_local_access_token(user)
response = client.post(
'/api/workspace/shipping-exports/archive', json={'batch_no': 'SB-API-ZIP'},
headers={'Authorization': f'Bearer {token}'},
)
assert response.status_code == 200
assert response.mimetype == 'application/zip'
assert 'attachment' in response.headers['Content-Disposition']
@@ -0,0 +1,337 @@
"""
tests/test_shipping_inventory_configuration.py
用途:验证库存源主数据、外部系统映射约束和 RPA 凭据加密的阶段一契约。
依赖:Flask app/db、库存配置模型、credential_crypto、inventory_source_repository。
逻辑:阶段二前锁定最小数据安全与关系约束,避免错误配置进入路由或 RPA 执行链路。
"""
from __future__ import annotations
from cryptography.fernet import Fernet
import pytest
from sqlalchemy.exc import IntegrityError
from app.core.errors import ServiceUnavailableError, ValidationError
from app.extensions import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryExternalMapping, ShippingInventoryFile,
ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingTask,
)
from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source
from app.services.shipping_notice.inventory_external_mapping import resolve_external_warehouse
def _profile(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> ShippingRpaProfile:
"""构造最小可持久化 RPA Profile,避免测试包含明文真实凭据。"""
return ShippingRpaProfile(
profile_code=code,
display_name=code,
connector_type=connector_type,
login_url='https://example.invalid/login',
login_config_json={'auth_mode': 'password'},
)
def _source(profile: ShippingRpaProfile, *, code: str = 'DBS_DUB', mode: str = 'fixed') -> ShippingInventorySource:
"""构造固定或动态 Warehouse 的库存源,供约束测试复用。"""
parsing = ShippingInventoryParsingProfile(
profile_code=f'{code}_PARSING', display_name=f'{code} Parsing', version=1,
status='published', file_format='xlsx', definition_json={'match_keys': []},
)
template = ShippingExcelTemplate(
template_code=f'{code}_EXPORT', display_name=f'{code} Export', version=1,
status='published', storage_provider='minio', storage_bucket='test',
storage_key=f'test/{code}-export.xlsx', original_filename='template.xlsx',
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
)
return ShippingInventorySource(
source_code=code,
display_name=code,
connector_type=profile.connector_type,
rpa_profile=profile,
parsing_profile=parsing,
excel_template=template,
warehouse_resolution_mode=mode,
fixed_warehouse_id='DUB' if mode == 'fixed' else None,
)
def test_encrypt_credential_round_trip_requires_runtime_key(app):
"""凭据必须依赖环境主密钥加密,且可在受控运行时回读。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
ciphertext = encrypt_credential('not-a-real-password')
assert ciphertext != 'not-a-real-password'
assert decrypt_credential(ciphertext) == 'not-a-real-password'
def test_encrypt_credential_rejects_missing_runtime_key(app):
"""关键加密主密钥缺失时拒绝写入凭据,避免产生不可恢复密文。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = ''
with app.app_context(), pytest.raises(ServiceUnavailableError):
encrypt_credential('not-a-real-password')
def test_source_profile_connector_types_must_match(app):
"""Source 绑定不同 Driver 的 Profile 必须被服务层拒绝。"""
with app.app_context(), pytest.raises(ValidationError) as exc_info:
validate_source_profile(_source(_profile(connector_type='dbs')), _profile(code='CRANE_01', connector_type='crane'))
assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH'
def test_dynamic_source_disallows_fixed_warehouse_in_database(app):
"""动态仓 Source 不得保存固定 Warehouse,避免 Crane 配置被误建为单仓。"""
with app.app_context():
profile = _profile(connector_type='crane')
source = _source(profile, code='CRANE', mode='inventory_match')
source.fixed_warehouse_id = 'TZR'
db.session.add_all([profile, source])
with pytest.raises(IntegrityError):
db.session.commit()
db.session.rollback()
def test_external_mapping_allows_topgp_organization_code_to_be_null(app):
"""TOPGP 无公司代码概念时,映射必须允许 NULL 而非伪造占位值。"""
with app.app_context():
profile = _profile()
source = _source(profile)
mapping = ShippingInventoryExternalMapping(
inventory_source=source,
freight_warehouse_id='DUB',
external_system_code='TOPGP',
external_organization_code=None,
external_site_code='EU01',
external_warehouse_code='DUB01',
external_warehouse_name='Dublin Warehouse',
)
db.session.add(mapping)
db.session.commit()
assert mapping.id is not None
def test_database_source_snapshot_excludes_profile_credentials(app):
"""运行时 Source 快照只提供操作配置,禁止泄漏 Profile 凭据字段。"""
with app.app_context():
profile = _profile()
profile.username_ciphertext = 'ciphertext'
profile.password_ciphertext = 'ciphertext'
source = _source(profile)
db.session.add(source)
db.session.commit()
payload = get_database_inventory_source('DBS_DUB')
assert payload is not None
assert payload['source_code'] == 'DBS_DUB'
assert 'username_ciphertext' not in payload
assert 'password_ciphertext' not in payload
def test_database_source_snapshot_uses_source_business_report_configuration(app):
"""运行时快照必须从 Source 读取报表路径和查询条件,不得从 Profile 读取旧报表配置。"""
with app.app_context():
profile = _profile()
profile.login_config_json = {'auth_mode': 'password'}
source = _source(profile)
source.report_path_json = {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'Source Report',
}
source.query_parameters_json = [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
]
source.match_aliases_json = ['DUB', 'Dublin']
db.session.add(source)
db.session.commit()
payload = get_database_inventory_source('DBS_DUB')
assert payload is not None
assert payload['navigation']['report_name'] == 'Source Report'
assert payload['parameters'][0]['name'] == 'Warehouse'
assert payload['match_aliases_json'] == ['DUB', 'Dublin']
assert 'operation_config' not in payload
assert payload['login_config'] == {'auth_mode': 'password'}
def test_rpa_trigger_snapshot_keeps_profile_credentials_encrypted(app):
"""RPA 专用快照可投递密文,但任何运行时普通读取不得获得该字段。"""
with app.app_context():
profile = _profile()
profile.username_ciphertext = 'encrypted-user'
profile.password_ciphertext = 'encrypted-password'
db.session.add(_source(profile))
db.session.commit()
payload = get_rpa_trigger_inventory_source('DBS_DUB')
assert payload is not None
assert payload['credential_envelope'] == {
'username_ciphertext': 'encrypted-user',
'password_ciphertext': 'encrypted-password',
}
def test_external_mapping_prefers_exact_warehouse_then_source_default(app):
"""同一 Source 的动态仓先命中精确映射,未命中时才回退默认外部系统仓库。"""
with app.app_context():
profile = _profile(code='CRANE_EU', connector_type='crane')
source = _source(profile, code='CRANE', mode='inventory_match')
exact = ShippingInventoryExternalMapping(
inventory_source=source, freight_warehouse_id='FRA', external_system_code='TOPGP',
external_warehouse_code='FRA01', external_warehouse_name='Frankfurt',
)
fallback = ShippingInventoryExternalMapping(
inventory_source=source, freight_warehouse_id=None, external_system_code='TOPGP',
external_warehouse_code='CRANE_DEFAULT', external_warehouse_name='Crane Default',
)
db.session.add_all([exact, fallback])
db.session.commit()
assert resolve_external_warehouse(source_code='CRANE', freight_warehouse_id='FRA')['external_warehouse_code'] == 'FRA01'
assert resolve_external_warehouse(source_code='CRANE', freight_warehouse_id='fra')['external_warehouse_code'] == 'FRA01'
assert resolve_external_warehouse(source_code='CRANE', freight_warehouse_id='SIN')['external_warehouse_code'] == 'CRANE_DEFAULT'
def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, tmp_path):
"""动态 Source 只能以订单键命中的库存行确定 Warehouse,不能按库存数量挑选。"""
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context
with app.app_context():
source = _source(_profile(code='CRANE_PROFILE', connector_type='crane'), code='CRANE', mode='inventory_match')
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
part_field = ShippingOrderField(id='dynamic-order-part', schema=schema, field_code='part_number', scope='line', value_type='string')
reservation_field = ShippingOrderField(id='dynamic-order-reservation', schema=schema, field_code='reservation_id', scope='line', value_type='string')
version = ShippingOrderSchemaVersion(
schema=schema, version=1, status='published', checksum='d' * 64,
definition_json={'fields': [
{'id': part_field.id, 'field_code': part_field.field_code, 'scope': 'line', 'value_type': 'string'},
{'id': reservation_field.id, 'field_code': reservation_field.field_code, 'scope': 'line', 'value_type': 'string'},
]},
)
source.parsing_profile.definition_json = {
'field_mapping': {
inventory_fields['part_number']: 'Part',
inventory_fields['reservation_id']: 'Reservation',
inventory_fields['available_qty']: 'Qty',
inventory_fields['warehouse_id']: 'Warehouse',
},
'match_keys': [
{'order_field_id': part_field.id, 'inventory_field_id': inventory_fields['part_number']},
{'order_field_id': reservation_field.id, 'inventory_field_id': inventory_fields['reservation_id']},
],
}
db.session.add(source)
db.session.add_all([schema, part_field, reservation_field, version])
db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='d' * 64, status='accepted')
db.session.add(extraction)
db.session.flush()
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
db.session.add(order_line)
db.session.flush()
part_decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id,
decision_status='accepted', resolved_value_json='A001',
)
reservation_decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id,
decision_status='accepted', resolved_value_json='R-1',
)
db.session.add_all([part_decision, reservation_decision])
db.session.flush()
db.session.add_all([
ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id,
value_text='A001', decision_id=part_decision.id,
),
ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id,
value_text='R-1', decision_id=reservation_decision.id,
),
])
task = ShippingTask(
task_no='SN-DYNAMIC-WH', source_type='manual', inventory_source_code='CRANE',
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
current_order_extraction_id=extraction.id,
)
task.inventory_source_config_version = inventory_sources_runtime_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
path = tmp_path / 'dynamic.xlsx'
path.write_bytes(b'not-parsed-in-this-test')
snapshot = ShippingInventoryFile(
inventory_file_no='SIF-DYNAMIC-WH', storage_path=str(path), snapshot_status='ready',
source_code='CRANE', warehouse_id='FALLBACK', share_mode='warehouse_pool',
inventory_lines_json=[
{
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
inventory_fields['warehouse_id']: 'FRA', inventory_fields['available_qty']: 1,
},
{
inventory_fields['part_number']: 'OTHER', inventory_fields['reservation_id']: 'R-2',
inventory_fields['warehouse_id']: 'SIN', inventory_fields['available_qty']: 999,
},
],
)
db.session.add_all([task, snapshot])
db.session.commit()
link = link_snapshot_to_task(task, snapshot, reason='dynamic_test')
assert link is not None
assert task.inventory_warehouse_id == 'FRA'
assert link.matched_warehouse_id == 'FRA'
def test_dynamic_source_rejects_ambiguous_warehouse_for_same_order_key(app, tmp_path):
"""同一 Reservation + PN 对应多个 Warehouse 时必须拒绝关联,防止错误业务路由。"""
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context
with app.app_context():
source = _source(_profile(code='CRANE_AMBIG_PROFILE', connector_type='crane'), code='CRANE_AMBIG', mode='inventory_match')
db.session.add(source)
db.session.commit()
task = ShippingTask(
task_no='SN-DYNAMIC-AMBIG', source_type='manual', inventory_source_code='CRANE_AMBIG',
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
)
task.inventory_source_config_version = inventory_sources_runtime_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
path = tmp_path / 'ambiguous.xlsx'
path.write_bytes(b'not-parsed-in-this-test')
snapshot = ShippingInventoryFile(
inventory_file_no='SIF-DYNAMIC-AMBIG', storage_path=str(path), snapshot_status='ready',
source_code='CRANE_AMBIG', warehouse_id='FALLBACK', share_mode='warehouse_pool',
inventory_lines_json=[
{'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'FRA', 'available_qty': 1},
{'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'SIN', 'available_qty': 1},
],
)
db.session.add_all([task, snapshot])
db.session.commit()
assert link_snapshot_to_task(task, snapshot, reason='dynamic_test') is None
assert task.inventory_warehouse_id is None
def test_dynamic_snapshot_is_idempotent_per_rpa_run(app, tmp_path):
"""同一 RPA run 的动态多仓文件只能入库一次,避免回调重放产生重复快照。"""
with app.app_context():
first = ShippingInventoryFile(
inventory_file_no='SIF-DYNAMIC-IDEMPOTENT-1', storage_path=str(tmp_path / 'first.xlsx'),
snapshot_status='ready', source_code='CRANE', warehouse_id=None, rpa_run_no='RUN-DYNAMIC-1',
)
second = ShippingInventoryFile(
inventory_file_no='SIF-DYNAMIC-IDEMPOTENT-2', storage_path=str(tmp_path / 'second.xlsx'),
snapshot_status='ready', source_code='CRANE', warehouse_id=None, rpa_run_no='RUN-DYNAMIC-1',
)
db.session.add(first)
db.session.commit()
db.session.add(second)
with pytest.raises(IntegrityError):
db.session.commit()
db.session.rollback()
@@ -0,0 +1,136 @@
"""
tests/test_shipping_inventory_routing_engine.py
用途:验证通用库存源路由规则的候选、优先级和冲突裁决。
依赖:库存路由模型、inventory_routing_engine、Flask 测试数据库。
逻辑:锁定 Reservation ID 兜底规则只是受控事实字段之一,规则引擎不会执行 RPA 或猜测 Warehouse。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.extensions import db
from app.models import (
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
def _rule(*, code: str, priority: int, action: str, sources: list[str], value: object, operator: str = 'prefix'):
"""构造一个已发布的行级 Reservation ID 路由规则。"""
return ShippingInventoryRoutingRule(
rule_code=code,
rule_name=code,
scope='line',
priority=priority,
match_mode='all',
status='published',
action_type=action,
action_payload_json={'source_codes': sources},
version=1,
conditions=[
ShippingInventoryRoutingRuleCondition(
condition_group=1,
source_kind='system_fact',
system_fact_key='line.reservation_id',
operator=operator,
expected_value_json=value,
sequence=1,
)
],
)
def _task() -> SimpleNamespace:
"""提供最小任务事实,确保路由测试只依赖显式输入。"""
return SimpleNamespace(
customer_code=None, destination_country=None, destination_city=None,
destination_port=None, warehouse_hint=None, order_type=None, sender_email=None,
current_order_extraction_id=None,
)
def test_prefix_rule_returns_ambiguous_source_candidates(app):
"""前缀 1 规则只产生 DUB/RTM 候选,不在路由阶段擅自选择 Source。"""
with app.app_context():
db.session.add(_rule(code='RSV_PREFIX_1', priority=100, action='add_source_candidates', sources=['DBS_DUB', 'DBS_RTM'], value='1'))
db.session.commit()
result = evaluate_inventory_source_rules(task=_task(), line={'reservation_id': '1000123456'})
assert result.status == 'ambiguous'
assert result.source_codes == ('DBS_DUB', 'DBS_RTM')
def test_higher_priority_document_rule_wins_over_reservation_fallback(app):
"""高优先级规则覆盖兜底规则,体现明确业务事实优先于通用前缀。"""
with app.app_context():
db.session.add_all([
_rule(code='RSV_PREFIX_1', priority=100, action='add_source_candidates', sources=['DBS_DUB', 'DBS_RTM'], value='1'),
_rule(code='RSV_FIXED_DUB', priority=200, action='add_source_candidates', sources=['DBS_DUB'], value='1000123456', operator='equals'),
])
db.session.commit()
result = evaluate_inventory_source_rules(task=_task(), line={'reservation_id': '1000123456'})
assert result.status == 'resolved'
assert result.source_codes == ('DBS_DUB',)
def test_five_digit_reservation_rule_can_route_to_crane(app):
"""五位纯数字经 numeric_length 规则产生 Crane Source,最终 Warehouse 仍留给库存行匹配。"""
with app.app_context():
db.session.add(_rule(code='RSV_LENGTH_5', priority=100, action='add_source_candidates', sources=['CRANE'], value=5, operator='numeric_length'))
db.session.commit()
result = evaluate_inventory_source_rules(task=_task(), line={'reservation_id': '12345'})
assert result.status == 'resolved'
assert result.source_codes == ('CRANE',)
def test_dynamic_order_field_value_routes_inventory_source(app):
"""路由条件引用稳定订单 field_id,并从 Task 当前 Extraction 读取行值。"""
with app.app_context():
order_schema_service.initialize_schema({'display_name': '路由字段'}, actor_id=None)
field = order_schema_service.save_field(
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
draft = order_schema_service.create_draft({}, actor_id=None)
saved_schema = order_schema_service.save_draft(draft['id'], {'fields': [{
'field_id': field['id'], 'display_name': 'Reservation', 'required': True, 'aliases': [],
'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id'], 'enum_options': [],
'evidence_policy': {'required': True, 'source_precedence': ['attachment_text'], 'conflict_policy': 'block', 'allow_single_source': True},
'relation_role': None, 'comparator_key': 'reservation_id',
}], 'expected_lock_version': draft['lock_version']})
order_schema_service.publish(
draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
)
task = ShippingTask(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual')
db.session.add(task)
db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=draft['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)
db.session.add(line)
db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=field['id'], decision_status='accepted',
supporting_observation_ids_json=[], resolved_value_json='1000123456',
)
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='1000123456', value_json='1000123456',
))
task.current_order_extraction_id = extraction.id
rule = _rule(code='DYNAMIC_RSV', priority=200, action='add_source_candidates', sources=['DBS_DUB'], value='1')
condition = rule.conditions[0]
condition.source_kind = 'order_field'
condition.system_fact_key = None
condition.order_field_id = field['id']
db.session.add(rule)
db.session.commit()
result = evaluate_inventory_source_rules(task=task, line={'_position': 0})
assert result.status == 'resolved'
assert result.source_codes == ('DBS_DUB',)
+166 -39
View File
@@ -21,10 +21,13 @@ from app.models import (
Job,
KbJob,
ShippingBatch,
ShippingCase,
ShippingCustomer,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingTask,
ShippingTaskEvent,
ShippingTemporaryInventorySession,
User,
)
from app.core.auth.jwt import issue_local_access_token
@@ -36,6 +39,24 @@ from app.services.shipping_notice.progress_workflow import auto_progress
from tests.conftest import seed_task_inventory_source
def _confirm_direct_task_customer(task: ShippingTask) -> None:
"""为直接构造且聚焦客户门禁后流程的任务补齐已确认客户。"""
customer = ShippingCustomer.query.filter_by(short_code='BAT').one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name='批次流程测试客户', short_code='BAT', status='active',
)
db.session.add(customer)
db.session.flush()
task.shipping_case = ShippingCase(
case_no=f'CASE-{task.task_no}', customer=customer,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
)
task.customer_resolution_status = 'confirmed'
task.customer_resolution_method = 'test_fixture'
def _tool_headers(app):
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
@@ -636,8 +657,8 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
"""库存自动获取失败时应进入第 3 步库存准备,而不是继续显示解析确认。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = ""
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = ""
with app.app_context():
user = User(username="shipping_inventory_step_user", email="shipping_inventory_step_user@example.com")
db.session.add(user)
@@ -660,6 +681,7 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
}
},
)
_confirm_direct_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
db.session.commit()
@@ -686,7 +708,7 @@ def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, cli
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 5
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
@@ -740,12 +762,12 @@ def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, cli
assert not list((tmp_path / "inventory_triggers").glob("inventory_export_*.json"))
def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_path):
"""目的地 DUB 应解析到 DSV360_AWSDU,并写入 RPA 库存导出 trigger。"""
def test_auto_progress_resolves_dub_source_without_implicitly_triggering_rpa(app, tmp_path):
"""自动推进可解析 Dublin 库存源,但正式 RPA 刷新必须由用户明确触发。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
with app.app_context():
user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com")
@@ -759,47 +781,40 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p
parse_confidence=0.95,
raw_content="Ship to Dublin DUB\nA001 x 10",
ship_to="Dublin",
destination_code="DUB",
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}],
step_payload_json={"destination": {"port_code": "DUB", "city": "Dublin"}},
)
_confirm_direct_task_customer(task)
db.session.add(task)
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
db.session.refresh(task)
assert result["status"] == "running"
source = task.step_payload_json["rpa_inventory_source"]
assert source["source_code"] == "DSV360_AWSDU"
assert result["status"] == "needs_human"
assert result["checkpoint"] == "upload_req"
assert task.inventory_source_code == "DSV360_AWSDU"
trigger_path = tmp_path / "inventory_triggers" / f"inventory_export_{task.task_no}.json"
assert trigger_path.exists()
trigger_text = trigger_path.read_text(encoding="utf-8")
assert '"source_code": "DSV360_AWSDU"' in trigger_text
assert '"connector_type": "dsv360"' in trigger_text
assert not trigger_path.exists()
def test_inventory_source_rules_cover_dsv360_programs(app):
"""截图中的 DSV 360 Program 均应能通过别名解析到对应库存源。"""
def test_inventory_source_rules_resolve_configured_dublin_source(app):
"""数据库中已发布的 Dublin 规则应解析到已启用库存站点。"""
from app.services.shipping_notice.inventory_source_rules import resolve_inventory_source
cases = [
("BYAWSATL01", "DSV360_AWSBI_BYAWSATL01"),
("Cincinnati", "DSV360_AWSCV"),
("Moerdijk", "DSV360_AWSAMS"),
]
with app.app_context():
for ship_to, expected_code in cases:
task = ShippingTask(
task_no=f"SN-INVENTORY-SOURCE-{expected_code}",
source_type="pdf",
process_status="parsed",
ship_to=ship_to,
lines_json=[{"sku": "A001", "qty": 10}],
)
resolution = resolve_inventory_source(task)
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-DSV360-AWSDU",
source_type="pdf",
process_status="parsed",
destination_code="DUB",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 10}],
)
resolution = resolve_inventory_source(task)
assert resolution.status == "resolved"
assert resolution.source_code == expected_code
assert resolution.status == "resolved"
assert resolution.source_code == "DSV360_AWSDU"
def test_auto_progress_unknown_destination_requires_inventory_source_review(app):
@@ -820,6 +835,7 @@ def test_auto_progress_unknown_destination_requires_inventory_source_review(app)
ship_to="Mystery Port",
lines_json=[{"sku": "A001", "qty": 10}],
)
_confirm_direct_task_customer(task)
db.session.add(task)
db.session.commit()
@@ -831,7 +847,7 @@ def test_auto_progress_unknown_destination_requires_inventory_source_review(app)
assert task.process_status == "pending_review"
assert task.pending_human_reason == "inventory_source_unresolved"
assert task.step_payload_json["inventory_source_resolution"]["status"] == "unresolved"
assert len(result["data"]["inventory_source_candidates"]) >= 4
assert len(result["data"]["inventory_source_candidates"]) == 1
def test_inventory_source_review_chat_actions_return_source_buttons(app):
@@ -904,12 +920,11 @@ def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
assert [item["id"] for item in ui_state["action_buttons"]] == [
"confirm_inventory_source",
"retry_resolve_inventory_source",
"upload_inventory_file",
]
def test_parse_stage_ui_state_lists_all_issues(app):
"""文件解析阶段 UI State 应一次列出库存源问题、解析 warnings(含存量延后低置信度提示)。"""
"""库存源检查点应列出当前库存源问题和解析警告,不生成旧顺序延后复核提示。"""
from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context():
@@ -921,7 +936,6 @@ def test_parse_stage_ui_state_lists_all_issues(app):
error_message="无法根据发货通知唯一确定库存查询来源",
parse_confidence=0.4,
step_payload_json={
"pending_parse_review_after_source": True,
"inventory_source_resolution": {"status": "unresolved", "candidates": []},
"parse_validation": {
"status": "needs_review",
@@ -955,8 +969,7 @@ def test_parse_stage_ui_state_lists_all_issues(app):
assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues
assert "解析引擎回退到启发式规则,请人工核对字段。" in issues
assert "第 1 行料号 A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues
assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues
assert len(issues) == 5
assert len(issues) == 4
def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client):
@@ -1001,7 +1014,7 @@ def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client)
assert task_state["checkpoint"] == "shortage_review"
assert [item["id"] for item in task_state["action_buttons"]] == [
"reparse_inventory",
"retry_rpa",
"rematch",
"reject",
]
@@ -1933,6 +1946,120 @@ def test_build_dify_chat_inputs_does_not_fallback_to_latest_task_without_explici
assert runtime_context["refs"] == {"run_purpose": "chat_turn"}
def test_build_dify_chat_inputs_restores_pending_temporary_inventory_session(app):
"""临时库存确认跨回合时应从 HXOPS 数据库恢复会话号,而不是依赖 Dify 隐式记忆。"""
with app.app_context():
conversation_id = 'conv-temp-inventory-resume-001'
user = User(username='temp_resume_user', email='temp-resume@example.com', role='user', status='active')
user.set_password('password')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-TEMP-RESUME-001', owner_user_id=user.id, original_filename='inventory.xls',
storage_provider='minio', storage_bucket='test', storage_key='temp/inventory.xls',
content_hash='a' * 64, file_size=16, extension='.xls', upload_status='ready',
)
db.session.add(asset)
db.session.flush()
pending = ShippingTemporaryInventorySession(
session_no='TIS-RESUME-001', user_id=user.id, conversation_id=conversation_id,
asset_id=asset.id, declared_intent='inventory_candidate',
file_classification_status='inventory_candidate', status='awaiting_mapping_confirmation',
expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add(pending)
db.session.commit()
inputs = dify_inputs.build_dify_chat_inputs(conversation_id)
runtime_context = json.loads(inputs['agent_runtime_context'])
assert runtime_context['refs']['temporary_inventory_session_no'] == pending.session_no
assert runtime_context['refs']['run_purpose'] == 'chat_turn'
assert 'capability' not in runtime_context['refs']
def test_build_dify_chat_inputs_ignores_expired_or_terminal_temporary_inventory_session(app):
"""过期或已确认会话不得继续污染后续聊天运行态。"""
with app.app_context():
conversation_id = 'conv-temp-inventory-terminal-001'
user = User(username='temp_terminal_user', email='temp-terminal@example.com', role='user', status='active')
user.set_password('password')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-TEMP-TERMINAL-001', owner_user_id=user.id, original_filename='inventory.csv',
storage_provider='minio', storage_bucket='test', storage_key='temp/inventory.csv',
content_hash='b' * 64, file_size=16, extension='.csv', upload_status='ready',
)
db.session.add(asset)
db.session.flush()
db.session.add_all([
ShippingTemporaryInventorySession(
session_no='TIS-EXPIRED-001', user_id=user.id, conversation_id=conversation_id,
asset_id=asset.id, declared_intent='inventory_candidate',
file_classification_status='inventory_candidate', status='awaiting_mapping_confirmation',
expires_at=datetime.utcnow() - timedelta(minutes=1),
),
ShippingTemporaryInventorySession(
session_no='TIS-CONFIRMED-001', user_id=user.id, conversation_id=conversation_id,
asset_id=asset.id, declared_intent='inventory_candidate',
file_classification_status='inventory_candidate', status='confirmed_for_temporary_use',
expires_at=datetime.utcnow() + timedelta(hours=1),
),
])
db.session.commit()
inputs = dify_inputs.build_dify_chat_inputs(conversation_id)
runtime_context = json.loads(inputs['agent_runtime_context'])
assert 'temporary_inventory_session_no' not in runtime_context['refs']
def test_build_dify_chat_inputs_prefers_explicit_temporary_inventory_session(app):
"""显式锚点必须优先,便于 UI 精确续办指定的临时库存会话。"""
with app.app_context():
inputs = dify_inputs.build_dify_chat_inputs(
'conv-temp-explicit-001',
temporary_inventory_session_no='tis-explicit-001',
)
runtime_context = json.loads(inputs['agent_runtime_context'])
assert runtime_context['refs']['temporary_inventory_session_no'] == 'TIS-EXPLICIT-001'
def test_build_dify_chat_inputs_does_not_restore_temporary_session_for_backend_orchestrator(app):
"""后台订单解析不得继承聊天中的临时库存会话锚点。"""
with app.app_context():
conversation_id = 'conv-temp-inventory-worker-001'
user = User(username='temp_worker_user', email='temp-worker@example.com', role='user', status='active')
user.set_password('password')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-TEMP-WORKER-001', owner_user_id=user.id, original_filename='inventory.xlsx',
storage_provider='minio', storage_bucket='test', storage_key='temp/inventory.xlsx',
content_hash='c' * 64, file_size=16, extension='.xlsx', upload_status='ready',
)
db.session.add(asset)
db.session.flush()
db.session.add(ShippingTemporaryInventorySession(
session_no='TIS-WORKER-001', user_id=user.id, conversation_id=conversation_id,
asset_id=asset.id, declared_intent='inventory_candidate',
file_classification_status='inventory_candidate', status='awaiting_mapping_confirmation',
expires_at=datetime.utcnow() + timedelta(hours=1),
))
db.session.commit()
inputs = dify_inputs.build_dify_chat_inputs(
conversation_id,
trigger_source='backend_orchestrator',
)
runtime_context = json.loads(inputs['agent_runtime_context'])
assert 'temporary_inventory_session_no' not in runtime_context['refs']
assert runtime_context['refs']['run_purpose'] == 'parse_notice'
def test_shipping_notice_agent_code_from_resolver():
"""发货通知识别应基于 resolve_agent_code,不再提供 dify_inputs 名称启发式。"""
from app.services.agent_registry.resolver import resolve_agent_code
@@ -6,7 +6,10 @@ backend/tests/test_shipping_notice_business_case.py
逻辑:直接调用领域服务并断言业务单关系,不触发解析和库存副作用。
"""
import pytest
from app import db
from app.core.errors import ConflictError
from app.models import ShippingCase, ShippingTask
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
from app.services.shipping_notice.task_workflow import create_batch_tasks, create_task
@@ -52,20 +55,20 @@ def test_revision_inherits_existing_parent_case(app):
assert ShippingCase.query.count() == 1
def test_revision_backfills_case_for_legacy_parent(app):
"""历史父任务没有业务单时,首次修订应补建并复用同一业务单。"""
def test_revision_rejects_parent_without_business_case(app):
"""修订父任务缺少业务单时必须阻断,禁止隐式补建。"""
with app.app_context():
parent = _task('SN-CASE-LEGACY-1')
db.session.add(parent)
db.session.flush()
resolved = resolve_shipping_case_for_new_task(
supersedes_task_id=parent.id,
duplicate_resolution_type='revision',
)
db.session.flush()
assert parent.shipping_case_id == resolved.id
assert ShippingCase.query.count() == 1
with pytest.raises(ConflictError) as exc_info:
resolve_shipping_case_for_new_task(
supersedes_task_id=parent.id,
duplicate_resolution_type='revision',
)
assert exc_info.value.code == 'SHIPPING_NOTICE.REVISION_CASE_MISSING'
assert ShippingCase.query.count() == 0
def test_revision_chain_reuses_root_case(app):
@@ -3,6 +3,7 @@
from pathlib import Path
from openpyxl import Workbook
import pytest
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
@@ -104,18 +105,26 @@ def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app):
"aws_part_number": "AWS Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
"odm_id": "ODM ID",
},
)
assert lines[0]["odm_id"] == "16754796"
def test_match_aggregates_same_part_number_reservation():
notice = [{"part_number": "D4-A", "reservation_id": "AWS-311", "qty": 3}]
notice = [{"order-sku": "D4-A", "order-ref": "AWS-311", "__required_qty": 3}]
inventory = [
{"part_number": "D4-A", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 1},
{"part_number": "D4-A", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 2},
{"501": "D4-A", "502": "AWS-311", "503": 1},
{"501": "D4-A", "502": "AWS-311", "503": 2},
]
status, results, _ = match_notice_lines(notice, inventory)
status, results, _ = match_notice_lines(
notice, inventory,
match_keys=[
{'order_field_id': 'order-sku', 'inventory_field_id': '501'},
{'order_field_id': 'order-ref', 'inventory_field_id': '502'},
],
quantity_field_id='503',
)
assert status == "fulfillable"
assert results[0]["available_qty"] == 3.0
@@ -163,9 +172,45 @@ def test_parse_inventory_excel_uses_preview_header_row_index(app, tmp_path):
assert any(line["part_number"] == "EARLY-001" and line["available_qty"] == 7.0 for line in lines_fixed)
def test_inventory_parser_uses_configured_worksheet_and_rejects_missing_sheet(tmp_path):
"""多 Sheet 库存文件必须读取 Profile 指定工作表,错误名称不得静默回退 active sheet。"""
from openpyxl import Workbook
from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel_with_meta
path = tmp_path / 'multi-sheet.xlsx'
workbook = Workbook()
workbook.active.title = 'Instructions'
workbook.active.append(['Do not parse this sheet'])
data = workbook.create_sheet('Inventory')
data.append(['Supplier Sku', 'Reservation ID', 'Qty Available'])
data.append(['PN-1', 'RSV-1', 5])
workbook.save(path)
mapping = {
'part_number': 'Supplier Sku', 'reservation_id': 'Reservation ID',
'available_qty': 'Qty Available',
}
lines, meta = parse_inventory_excel_with_meta(
path, field_mapping=mapping, header_row_index=1, sheet_name='Inventory',
)
assert lines[0]['part_number'] == 'PN-1'
assert meta['sheet_name'] == 'Inventory'
with pytest.raises(ValueError, match='Inventory worksheet not found'):
parse_inventory_excel_with_meta(
path, field_mapping=mapping, header_row_index=1, sheet_name='Missing',
)
def test_match_extracts_reservation_id_suffix():
notice = [{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}]
inventory = [{"part_number": "A001", "reservation_id": "ADU_S-ENCWIW260528126265@1000140351", "available_qty": 1}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["available_qty"] == 1.0
"""通用库存匹配不再对某个字段名称执行隐藏的 Reservation 特殊截取。"""
notice = [{"order-part": "A001", "order-ref": "1000140351", "__required_qty": 1}]
inventory = [{"601": "A001", "602": "ADU_S-ENCWIW260528126265@1000140351", "603": 1}]
status, results, _ = match_notice_lines(
notice, inventory,
match_keys=[
{'order_field_id': 'order-part', 'inventory_field_id': '601'},
{'order_field_id': 'order-ref', 'inventory_field_id': '602'},
],
quantity_field_id='603',
)
assert status == "unfulfillable"
assert results[0]["available_qty"] == 0.0
@@ -125,7 +125,7 @@ def test_serialize_run_reads_inventory_raw_zip_available_from_summary(app):
def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path):
"""finalize 预生成应落盘 ZIP 并返回 summary 字段。"""
archive_dir = tmp_path / "inventory_archives"
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
xlsx = tmp_path / "inventory.xlsx"
xlsx.write_bytes(b"fake-xlsx-content")
@@ -169,7 +169,7 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p
def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
"""无可读快照时不生成 ZIP。"""
archive_dir = tmp_path / "inventory_archives"
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
with app.app_context():
run = _make_inventory_run_with_created(
@@ -186,7 +186,7 @@ def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_fi
def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp_path):
"""created 有记录但磁盘文件缺失时不应生成 ZIP。"""
archive_dir = tmp_path / "inventory_archives"
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
with app.app_context():
run = _make_inventory_run_with_created(
@@ -212,7 +212,7 @@ def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp
def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path):
"""下载解析应返回归档路径与建议文件名。"""
archive_dir = tmp_path / "inventory_archives"
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
xlsx = tmp_path / "inventory.xlsx"
xlsx.write_bytes(b"fake-xlsx-content")
@@ -253,7 +253,7 @@ def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app):
def test_resolve_inventory_raw_zip_download_rejects_path_outside_archive_dir(app, tmp_path):
"""summary 指向归档目录外的真实文件时必须 404。"""
archive_dir = tmp_path / "inventory_archives"
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
outside_zip = tmp_path / "outside.zip"
outside_zip.write_bytes(b"fake-zip")
@@ -277,7 +277,7 @@ def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path
"""summary 指向非 .zip 后缀文件时必须 404。"""
archive_dir = tmp_path / "inventory_archives"
archive_dir.mkdir(parents=True)
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
fake_file = archive_dir / "RUN-ARCH-RESOLVE-BAD.txt"
fake_file.write_bytes(b"not-a-zip")
@@ -405,7 +405,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
app.config["WECOM_NOTIFY_ENABLED"] = True
app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com"
app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/"
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
user = User(
username="wecom_jump_user",
@@ -473,7 +473,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
):
"""admin 鉴权通过时应返回 application/zip 且文件名与 run_no 一致。"""
archive_dir = tmp_path / "inventory_archives"
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
xlsx = tmp_path / "inventory.xlsx"
xlsx.write_bytes(b"fake-xlsx-content")
@@ -1,7 +1,7 @@
"""shipping_notice inventory_rpa_workflow 单测。
覆盖 RPA 库存子模块与 inventory_workflow 的委托边界:
1. ensure_inventory(mode=auto) 触发 running 并写入 trigger 事件。
1. ensure_inventory(mode=auto) 仅复用已有快照,绝不触发 RPA。
2. rpa_report_inventory 回调会把文件正式落到 inventory_uploads,并进入字段映射确认。
"""
@@ -11,7 +11,10 @@ from pathlib import Path
import pytest
from app import db
from app.models import ShippingCustomer, ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
from app.models import (
ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
ShippingRpaProfile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink,
)
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source
@@ -19,6 +22,30 @@ def _tool_headers():
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
def _confirm_direct_rpa_task_customer(task: ShippingTask) -> None:
"""为直接构造的 RPA 回调任务补齐已确认客户。
核心逻辑:测试不经建单工作流时,显式创建 business case 与激活客户,
使回调测试只验证 RPA 契约,而不绕过客户身份门禁。
"""
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name='RPA 直接回调测试客户', short_code='RPC', status='active',
)
db.session.add(customer)
db.session.flush()
case = ShippingCase(
case_no=f'CASE-{task.task_no}', customer=customer,
customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code,
)
task.shipping_case = case
task.customer_resolution_status = 'confirmed'
task.customer_resolution_method = 'test_fixture'
db.session.add_all([case, task])
db.session.flush()
@pytest.fixture(autouse=True)
def _confirmed_customer_for_rpa_flows(app, monkeypatch):
"""为本模块新建的业务单绑定测试客户,使用例聚焦客户门禁之后的 RPA 行为。"""
@@ -69,15 +96,15 @@ def test_inventory_rpa_single_attempt_messages_hide_fraction():
) == "已触发库存获取。若长时间无结果,可手动重试,或上传库存 Excel。"
def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path, monkeypatch):
"""mode=auto 应返回 running 并在 DB 留下 inventory_rpa_triggered 事件。"""
def test_ensure_inventory_auto_does_not_trigger_rpa_when_snapshot_is_missing(app, client, tmp_path, monkeypatch):
"""正常 auto 未命中库存快照时应转缺库存,且不得写入 RPA trigger。"""
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
lambda *args, **kwargs: None,
)
trigger = tmp_path / "triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
@@ -112,34 +139,155 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path, monke
json={"task_id": task_id, "mode": "auto"},
)
body = inv_res.get_json()
assert body["status"] == "running"
assert body.get("data", {}).get("rpa", {}).get("attempts") == 1
assert "1/1" not in body.get("message", "")
assert "360s" not in body.get("message", "")
assert "长时间无结果" in body.get("message", "")
assert body["status"] == "needs_human"
assert "暂无可用库存数据" in body.get("message", "")
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.pending_human_reason == "rpa_pending"
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
assert progress.get("detail") == "当前配置为单次自动尝试"
events = (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered")
.all()
)
assert len(events) == 1
assert len(events) == 0
assert not list(trigger.glob("inventory_export_*.json"))
def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_path, monkeypatch):
"""RPA 回调成功落盘后应进入字段映射确认(align_review / map_infer)。"""
def test_ensure_inventory_auto_reuses_snapshot_without_rpa(app, client, monkeypatch):
"""正常 auto 命中已有快照时应直接返回复用结果,不得进入 RPA 编排。"""
captured: dict[str, object] = {}
def _reuse(task, source, *, mode):
captured.update({"task_no": task.task_no, "source": source, "mode": mode})
return {"status": "ok", "message": "已复用库存快照", "data": {"reused": True}}
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
_reuse,
)
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa",
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("auto must not invoke RPA")),
)
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
headers = _tool_headers()
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"destination": {"port_code": "DUB", "city": "Dublin"},
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
result = client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "mode": "auto"},
).get_json()
assert result["status"] == "ok"
assert result["data"]["reused"] is True
assert captured["task_no"] == task_id
assert captured["mode"] == "auto"
def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantity_selection(app, tmp_path):
"""多个 Source 候选仅按 Reservation + PN 的唯一快照命中确定,数量为零也不改选其他 Source。"""
from app.services.shipping_notice.inventory_source_rules import (
InventorySourceAdjudication,
resolve_ambiguous_source_from_ready_snapshots,
)
source_file = tmp_path / 'source-a.xlsx'
other_file = tmp_path / 'source-b.xlsx'
source_file.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
other_file.write_bytes(inventory_xlsx_with_warehouse('AWSRTM').getvalue())
with app.app_context():
profile = ShippingRpaProfile(
profile_code='DBS_RTM_MATCH_TEST', display_name='DBS RTM', connector_type='dbs',
login_url='https://test.invalid/rtm', login_config_json={'auth_mode': 'password'},
)
from app.models import ShippingExcelTemplate, ShippingInventoryParsingProfile
parsing_profile = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first()
excel_template = ShippingExcelTemplate.query.filter_by(template_code='TEST_RUNTIME').first()
rtm_source = ShippingInventorySource(
source_code='DSV360_AWSRTM', display_name='DBS Rotterdam AWSRTM', connector_type='dbs',
rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSRTM',
report_path_json={
'program_group': 'Bison', 'program_label': 'AWSRTM',
'report_group': 'Inventory', 'report_name': 'On Hand',
},
)
task = ShippingTask(
task_no='SN-SNAPSHOT-SOURCE-UNIQUE', source_type='manual',
lines_json=[{'part_number': 'A001', 'reservation_id': '1000123456', 'qty': 1}],
)
source_snapshot = ShippingInventoryFile(
inventory_file_no='SIF-SOURCE-UNIQUE', storage_path=str(source_file), snapshot_status='ready',
source_code='DSV360_AWSDU', warehouse_id='AWSDU', exported_at=datetime.utcnow(),
inventory_lines_json=[{
'part_number': 'A001', 'reservation_id': '1000123456',
'available_qty': 0, 'warehouse_id': 'AWSDU',
}], schema_preview_json={},
)
other_snapshot = ShippingInventoryFile(
inventory_file_no='SIF-OTHER-UNIQUE', storage_path=str(other_file), snapshot_status='ready',
source_code='DSV360_AWSRTM', warehouse_id='AWSRTM', exported_at=datetime.utcnow(),
inventory_lines_json=[{
'part_number': 'OTHER', 'reservation_id': '1000123456',
'available_qty': 999, 'warehouse_id': 'AWSRTM',
}], schema_preview_json={},
)
db.session.add_all([profile, rtm_source, task, source_snapshot, other_snapshot])
db.session.commit()
result = resolve_ambiguous_source_from_ready_snapshots(
task,
InventorySourceAdjudication(
status='ambiguous',
candidates=[
{'source_code': 'DSV360_AWSDU'},
{'source_code': 'DSV360_AWSRTM'},
],
),
)
assert result.status == 'resolved'
assert result.method == 'snapshot_match'
assert result.source_code == 'DSV360_AWSDU'
assert result.warehouse_id == 'AWSDU'
evidence = result.evidence[-1]['snapshot_candidate_check']
assert {item['source_code']: item['matched'] for item in evidence} == {
'DSV360_AWSDU': True,
'DSV360_AWSRTM': False,
}
def test_rpa_report_inventory_callback_uses_published_profile(app, client, tmp_path, monkeypatch):
"""RPA 回调必须按库存站点已发布方案解析,不再进入任务级字段映射确认。"""
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
lambda *args, **kwargs: None,
)
drop = tmp_path / "drop"
drop.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
@@ -166,15 +314,8 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
},
)
from openpyxl import Workbook
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "料号", "Reservation ID", "可用数量"])
ws.append(["AWSDU", "A001", "R-1", 20])
wb.save(inv_file)
wb.close()
inv_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU", qty=20).getvalue())
with app.app_context():
from app import db
@@ -195,15 +336,14 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
"file_path": str(inv_file),
"run_no": run_no,
"source_code": "DSV360_AWSDU",
"site_id": "AWSDU",
"warehouse_id": "AWSDU",
"rpa_mode": "browser",
},
)
data = cb_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") in {"align_review", "map_infer"}
assert "confirm_inventory_mapping" in (data.get("human_options") or [])
assert data["status"] == "ok"
assert data.get("checkpoint") == "ready_to_match"
assert "confirm_inventory_mapping" not in (data.get("human_options") or [])
assert data.get("data", {}).get("rpa_runtime", {}).get("mode") == "browser"
assert data.get("data", {}).get("rpa_runtime", {}).get("label") == "真实 RPA"
@@ -227,6 +367,91 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
assert task.inventory_snapshot_id == inv_file.id
def test_manual_task_inventory_upload_uses_published_profile_without_mapping_review(app, tmp_path):
"""任务级人工上传必须复用库存站点发布方案,并直接进入待匹配状态。"""
from io import BytesIO
from werkzeug.datastructures import FileStorage
from app.services.shipping_notice.inventory_workflow import upload_inventory_file
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
with app.app_context():
task = ShippingTask(
task_no='SN-MANUAL-PROFILE-001', source_type='manual', process_status='waiting_inventory',
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
db.session.add(task)
db.session.commit()
upload = FileStorage(
stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', qty=8).getvalue()),
filename='manual-stock.xlsx',
)
result = upload_inventory_file(task.task_no, upload)
db.session.refresh(task)
assert result['status'] == 'ok'
assert result['checkpoint'] == 'ready_to_match'
assert task.process_status == 'inventory_ready'
assert task.review_status is None
assert task.pending_human_reason is None
snapshot = db.session.get(ShippingInventoryFile, task.inventory_snapshot_id)
assert snapshot is not None
assert snapshot.mapping_source == 'parsing_profile'
assert snapshot.mapping_confirmed is True
fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
assert snapshot.inventory_lines_json[0][fields['part_number']] == 'A001'
assert snapshot.inventory_lines_json[0][fields['reservation_id']] == 'R-1'
assert snapshot.inventory_lines_json[0][fields['available_qty']] == 8
def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
"""任务级人工上传表头漂移时不得留下快照、任务链接或库存投影。"""
from io import BytesIO
from openpyxl import Workbook
from werkzeug.datastructures import FileStorage
from app.services.shipping_notice.inventory_workflow import upload_inventory_file
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
stream = BytesIO()
workbook = Workbook()
sheet = workbook.active
sheet.append(['Warehouse ID', 'Unexpected Part', 'Reservation ID', 'Qty'])
sheet.append(['AWSDU', 'A001', 'R-1', 8])
workbook.save(stream)
workbook.close()
stream.seek(0)
with app.app_context():
task = ShippingTask(
task_no='SN-MANUAL-DRIFT-001', source_type='manual', process_status='waiting_inventory',
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
db.session.add(task)
db.session.commit()
result = upload_inventory_file(
task.task_no,
FileStorage(stream=stream, filename='drifted-stock.xlsx'),
)
db.session.refresh(task)
assert result['status'] == 'failed'
assert '结构' in result['message'] or '解析' in result['message']
assert task.inventory_snapshot_id is None
assert task.inventory_lines_json in (None, [])
assert ShippingInventoryFile.query.count() == 0
assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 0
assert not list((tmp_path / 'storage' / 'inventory_uploads').glob('**/inventory.*'))
def test_rpa_callback_gate_rechecks_order_drift_after_trigger(app, client):
"""RPA 触发后新增 Reservation 异常或字段冲突时,旧回调必须停止入库。"""
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
@@ -297,7 +522,7 @@ def test_rpa_callback_gate_rechecks_order_drift_after_trigger(app, client):
def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client, tmp_path):
"""无库存 skipped 回调应提示人工上传,且不计入 inventory_rpa_failed。"""
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "drop")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "drop")
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
@@ -346,7 +571,6 @@ def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client,
"message": "DSV report has no inventory data",
"run_no": "RUN-SKIPPED",
"source_code": "DSV360_AWSDU",
"site_id": "AWSDU",
"warehouse_id": "AWSDU",
"rpa_mode": "browser",
},
@@ -422,7 +646,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_mixed.xlsx"
@@ -505,8 +729,8 @@ def test_resolve_rpa_inventory_batch_response_outcome_prefers_finalize_run_statu
assert outcome["failed_count"] == 2
def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch):
"""确认库存源后应立即进入 RPA pending,并写出库存导出 trigger。"""
def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, monkeypatch):
"""确认库存源只完成路由,不得隐式进入 RPA pending 或写出 trigger。"""
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
lambda *args, **kwargs: None,
@@ -516,7 +740,7 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch
trigger = tmp_path / "triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
@@ -547,21 +771,14 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch
result = confirm_inventory_source({"task_id": task.task_no, "source_code": "DSV360_AWSDU"})
db.session.refresh(task)
assert result["status"] == "running"
assert "已触发库存获取" in result["message"]
assert "长时间无结果" in result["message"]
assert "360s" not in result["message"]
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert result["status"] == "ok"
assert "库存源已确认" in result["message"]
assert task.process_status == "parsed"
assert task.pending_human_reason is None
assert task.error_message is None
assert task.step_payload_json["rpa_inventory_source"]["source_code"] == "DSV360_AWSDU"
assert task.step_payload_json["current_step_progress"]["detail"] == "当前配置为单次自动尝试"
events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all()
assert len(events) == 1
assert (
list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json"))
or list(trigger.glob("inventory_export_batch_TASK-SN-CONFIRM-SOURCE-RPA*.json"))
)
assert len(events) == 0
assert not list(trigger.glob("inventory_export_*.json"))
def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
@@ -571,7 +788,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "batch_task_success.xlsx"
@@ -586,6 +803,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
@@ -600,10 +818,9 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
"task_no": task.task_no,
"status": "success",
"success": True,
"file_path": str(sample),
"source_code": task.inventory_source_code,
"site_id": task.inventory_site_id,
"warehouse_id": task.inventory_warehouse_id,
"file_path": str(sample),
"source_code": task.inventory_source_code,
"warehouse_id": task.inventory_warehouse_id,
}],
})
db.session.refresh(task)
@@ -628,6 +845,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
@@ -671,6 +889,7 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-FAIL-NO-IDENT")
db.session.add(task)
@@ -686,6 +905,8 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "upload_req"
assert task.pending_human_reason == "rpa_exhausted"
failed_events = ShippingTaskEvent.query.filter_by(
task_id=task.id,
event_type="inventory_rpa_failed",
@@ -701,7 +922,7 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "orphan_task.xlsx"
with open(sample, "wb") as handle:
@@ -718,7 +939,6 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path):
"success": True,
"file_path": str(sample),
"source_code": "DSV360_AWSDU",
"site_id": "DSV360",
"warehouse_id": "AWSDU",
}],
})
@@ -779,7 +999,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "reuse_ingest_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -852,7 +1072,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
run_no = "RUN-REUSE-MISMATCH"
@@ -940,6 +1160,8 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task_a)
_confirm_direct_rpa_task_customer(task_b)
seed_task_inventory_source(task_a, source_code="DSV360_AWSDU")
seed_task_inventory_source(task_b, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task_a, run_no=run_no)
@@ -1003,6 +1225,8 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task_ok)
_confirm_direct_rpa_task_customer(task_fail)
seed_task_inventory_source(task_ok, source_code="DSV360_AWSDU")
seed_task_inventory_source(task_fail, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task_ok, run_no=run_no)
@@ -1062,7 +1286,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "post_commit.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -1083,6 +1307,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-POST-COMMIT")
db.session.add(task)
@@ -1106,7 +1331,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "promote_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -1127,6 +1352,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-PROMOTE-FAIL")
db.session.add(task)
@@ -1135,7 +1361,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-PROMOTE-FAIL"))
attachment = resolve_task_inventory_upload_path(task.task_no)
assert result["status"] == "needs_human"
assert result["status"] == "ok"
warnings = result.get("data", {}).get("post_commit_warnings") or []
assert any("promote_recovered_via_snapshot_rebuild" in item for item in warnings)
assert attachment is not None and attachment.is_file()
@@ -1169,10 +1395,9 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
inv_file = ShippingInventoryFile(
inventory_file_no="SIF-REPAIR-TEST",
storage_path=str(snap_file),
snapshot_status="ready",
source_code="DSV360_AWSDU",
site_id="AWSDU",
warehouse_id="AWSDU",
snapshot_status="ready",
source_code="DSV360_AWSDU",
warehouse_id="AWSDU",
share_mode="task_only",
schema_preview_json={},
exported_at=datetime.utcnow(),
@@ -1201,7 +1426,7 @@ def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "move_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -1240,7 +1465,7 @@ def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, m
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "quarantine_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -1330,7 +1555,6 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
storage_path=str(active_file),
snapshot_status="ready",
source_code="DSV360_AWSDU",
site_id="AWSDU",
warehouse_id="AWSDU",
share_mode="task_only",
schema_preview_json={},
@@ -1341,7 +1565,6 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
storage_path=str(other_file),
snapshot_status="ready",
source_code="DSV360_AWSDU",
site_id="AWSDU",
warehouse_id="AWSDU",
share_mode="task_only",
schema_preview_json={},
@@ -1372,7 +1595,7 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat
processed_dir = tmp_path / "processed"
drop_dir.mkdir()
processed_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir)
quarantine = drop_dir / ".hxops_quarantine"
@@ -80,7 +80,7 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
"""排程 executor 应写入 inventory_export_batch trigger。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
@@ -112,13 +112,13 @@ def test_run_task_now_defers_inventory_rpa_until_callback(app, tmp_path):
"""run_task_now 写 trigger 后应保持 running 且 awaiting_rpa=true。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-DEFER",
username="schedule_inv_defer_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
db.session.commit()
result = run_task_now(task, trigger_type="manual", triggered_by_user_id=None)
@@ -134,13 +134,13 @@ def test_deferred_run_sets_started_at_when_missing(app, tmp_path):
"""复用无 started_at 的 run 时,defer 应补写 started_at,避免立即超时回收。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-STARTED-AT",
username="schedule_inv_started_at_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
run = ScheduleRun(
run_no="RUN20260709080400",
@@ -221,11 +221,11 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
"""全部 source 成功但 Excel 导出失败时应降为 partial_failed 并写入 error_message。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_excel_fail.xlsx"
_write_sample_inventory(sample, "BYAWSATL01")
_write_sample_inventory(sample, "AWSDU")
def _excel_boom(*_args, **_kwargs):
raise RuntimeError("excel exploded")
@@ -239,7 +239,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-EXCEL-FAIL",
username="schedule_inv_excel_fail_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
run = ScheduleRun(
run_no="RUN20260709080700",
@@ -250,8 +250,8 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
"display_name": "ATL01",
}],
},
@@ -265,7 +265,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
"DSV360_AWSDU",
success=True,
file_path=str(sample),
)],
@@ -286,11 +286,11 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
"""finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_fail_finalize.xlsx"
_write_sample_inventory(sample, "BYAWSATL01")
_write_sample_inventory(sample, "AWSDU")
def _boom(*_args, **_kwargs):
raise RuntimeError("finalize exploded")
@@ -304,7 +304,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FINALIZE-FAIL",
username="schedule_inv_finalize_fail_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
run = ScheduleRun(
run_no="RUN20260709080600",
@@ -315,8 +315,8 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
"display_name": "ATL01",
}],
},
@@ -330,7 +330,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
"DSV360_AWSDU",
success=True,
file_path=str(sample),
)],
@@ -350,17 +350,17 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
drop_dir.mkdir()
processed_dir = drop_dir / "processed"
processed_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_sample.xlsx"
_write_sample_inventory(sample, "BYAWSATL01")
_write_sample_inventory(sample, "AWSDU")
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FINALIZE",
username="schedule_inv_finalize_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
run = ScheduleRun(
run_no="RUN20260709080000",
@@ -371,8 +371,8 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
"display_name": "ATL01",
}],
},
@@ -386,7 +386,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
"DSV360_AWSDU",
success=True,
file_path=str(sample),
)],
@@ -493,7 +493,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
"""回调结果少于触发源数时,排程应 partial_failed。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_partial.xlsx"
@@ -562,8 +562,8 @@ def test_finalize_inventory_rpa_schedule_run_with_skipped_callback(app):
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
"display_name": "ATL01",
}],
},
@@ -577,8 +577,8 @@ def test_finalize_inventory_rpa_schedule_run_with_skipped_callback(app):
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
"status": "skipped",
"skip_reason": "no_inventory_data",
"message": "DSV report has no inventory data",
@@ -644,37 +644,11 @@ def test_filter_sources_by_source_codes(app):
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FILTER-SRC",
username="schedule_inv_filter_src",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
def test_filter_sources_by_warehouse_id(app):
"""兼容占位符常用的 warehouse_id(如 BYAWSATL01)。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FILTER-WH",
username="schedule_inv_filter_wh",
api_body_template='{"source_codes": ["BYAWSATL01"]}',
)
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
def test_filter_sources_by_match_aliases(app):
"""兼容误填 match_aliases 的历史排程参数。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FILTER-ALIAS",
username="schedule_inv_filter_alias",
api_body_template='{"match_aliases": ["ATL01"]}',
)
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
assert [item.get("source_code") for item in sources] == ["DSV360_AWSDU"]
def test_build_schedule_run_wecom_description_includes_skipped_count():
@@ -732,24 +706,23 @@ def test_schedule_batch_rejects_mismatched_run_no(app, tmp_path):
assert run.status == "running"
def test_scheduled_batch_success_rejects_missing_site_id(app, tmp_path):
"""定时 batch 成功项缺少 site_id 时必须拒绝,不得仅靠 source_code 入库。"""
def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
"""定时 batch 成功项缺少 Warehouse 时必须拒绝,不能仅凭 Source 入库。"""
from app.models import ShippingInventoryFile
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "missing_site.xlsx"
_write_sample_inventory(sample, "BYAWSATL01")
sample = drop_dir / "missing_warehouse.xlsx"
_write_sample_inventory(sample, "AWSDU")
with app.app_context():
before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
result = rpa_report_inventory_batch({
"run_no": "RUN-MISSING-SITE",
"run_no": "RUN-MISSING-WAREHOUSE",
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"source_code": "DSV360_AWSDU",
"success": True,
"file_path": str(sample),
}],
@@ -758,7 +731,7 @@ def test_scheduled_batch_success_rejects_missing_site_id(app, tmp_path):
assert result["status"] == "ok"
assert result["failed_count"] == 1
assert result["data"]["failed"][0]["error"] == "site_id_missing"
assert result["data"]["failed"][0]["error"] == "warehouse_id_missing"
assert after == before
@@ -768,10 +741,10 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "retry_snapshot.xlsx"
_write_sample_inventory(sample, "BYAWSATL01")
_write_sample_inventory(sample, "AWSDU")
def _boom(*_args, **_kwargs):
raise RuntimeError("finalize exploded")
@@ -785,7 +758,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-RETRY-SNAPSHOT",
username="schedule_inv_retry_snapshot_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
run = ScheduleRun(
run_no="RUN20260713163000",
@@ -804,7 +777,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
"DSV360_AWSDU",
success=True,
file_path=str(sample),
)],
@@ -813,9 +786,8 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
second = rpa_report_inventory_batch(payload)
count = ShippingInventoryFile.query.filter_by(
rpa_run_no=run.run_no,
source_code="DSV360_AWSBI_BYAWSATL01",
site_id="AWSBI",
warehouse_id="BYAWSATL01",
source_code="DSV360_AWSDU",
warehouse_id="AWSDU",
snapshot_status="ready",
).count()
@@ -832,10 +804,10 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "retry_move.xlsx"
_write_sample_inventory(sample, "BYAWSATL01")
_write_sample_inventory(sample, "AWSDU")
processed_dir = drop_dir / "processed"
original_finalize = finalize_mod.finalize_shipping_inventory_schedule_run
@@ -862,7 +834,7 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-RETRY-MOVE",
username="schedule_inv_retry_move_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
run = ScheduleRun(
run_no="RUN20260713170000",
@@ -881,7 +853,7 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
"DSV360_AWSDU",
success=True,
file_path=str(sample),
)],
@@ -1,233 +0,0 @@
"""
backend/tests/test_shipping_notice_inventory_snapshot_reuse.py
用途:验证库存连接器身份下的快照 TTL、动态库位与任务复用规则。
依赖:ShippingTask、inventory_snapshot_store、inventory_sources、测试 Excel 夹具。
逻辑:构造稳定 inventory_connector_type 身份并检查快照查找、绑定和过期行为。
"""
from datetime import datetime, timedelta
from pathlib import Path
from app import db
from app.models import ShippingTask
from app.services.shipping_notice.inventory_snapshot_store import (
create_inventory_snapshot_from_rpa,
find_latest_ready_snapshot,
is_snapshot_fresh,
link_snapshot_to_task,
snapshot_expires_at,
)
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
from tests.conftest import inventory_xlsx_with_warehouse, seed_task_inventory_source
def _write_inventory_xlsx(path: Path, warehouse_id: str, *, sku: str = "A001", qty: int = 10) -> None:
with open(path, "wb") as handle:
handle.write(inventory_xlsx_with_warehouse(warehouse_id, sku=sku, qty=qty).getvalue())
def _task_with_inventory_source(
task_no: str,
*,
source_code: str,
connector_type: str | None = None,
site_id: str | None = None,
warehouse_id: str = "",
) -> ShippingTask:
"""构造已通过库存源门禁的任务,供快照关联测试使用。"""
task = ShippingTask(
task_no=task_no,
source_type="manual",
process_status="parsed",
)
seed_task_inventory_source(task, source_code=source_code)
if site_id:
task.inventory_site_id = site_id
if warehouse_id:
task.inventory_warehouse_id = warehouse_id
if connector_type:
task.inventory_connector_type = connector_type
return task
def test_fresh_snapshot_is_reused(app, tmp_path):
"""未过期 ready 快照应被 find_latest_ready_snapshot 按 source+site 命中。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 24
xlsx = tmp_path / "stock.xlsx"
_write_inventory_xlsx(xlsx, "AWSDU")
source = build_rpa_inventory_source("DSV360_AWSDU")
assert source is not None
with app.app_context():
inv = create_inventory_snapshot_from_rpa(
source=source,
local_path=xlsx,
trigger_type="scheduled",
success=True,
)
db.session.commit()
found = find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU")
assert found is not None
assert found.inventory_file_no == inv.inventory_file_no
assert found.site_id == "AWSDU"
assert is_snapshot_fresh(found)
def test_snapshot_separates_site_id_and_warehouse_id(app, tmp_path):
"""DSV 子仓快照应分别落库 site_id 与 warehouse_id,禁止混用。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
xlsx = tmp_path / "stock.xlsx"
_write_inventory_xlsx(xlsx, "BYAWSATL01")
source = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01")
assert source is not None
assert source["site_id"] == "AWSBI"
assert source["warehouse_id"] == "BYAWSATL01"
with app.app_context():
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
task = _task_with_inventory_source(
"SN-SNAPSHOT-SITE",
source_code="DSV360_AWSBI_BYAWSATL01",
connector_type="dsv360",
site_id="AWSBI",
warehouse_id="BYAWSATL01",
)
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="reuse_latest")
db.session.commit()
assert inv.site_id == "AWSBI"
assert inv.warehouse_id == "BYAWSATL01"
assert (inv.source_query_json or {}).get("export_warehouse_id") == "BYAWSATL01"
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01") is not None
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01_WRONG") is None
assert link is not None
assert link.matched_site_id == "AWSBI"
assert link.matched_warehouse_id == "BYAWSATL01"
def test_crane_runtime_source_carries_dynamic_warehouse(app, tmp_path):
"""Crane 运行时 RPA source 应携带任务动态库位 TZR2。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
from openpyxl import Workbook
from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
xlsx = tmp_path / "crane_stock.xlsx"
wb = Workbook()
wb.active.append(["Warehouse ID", "sku", "qty"])
wb.active.append(["TZR2", "A001", 10])
wb.save(xlsx)
wb.close()
with app.app_context():
task = ShippingTask(
task_no="SN-SNAPSHOT-CRANE-RUNTIME",
source_type="manual",
process_status="parsed",
ship_to="TZR2 footprint",
)
seed_task_inventory_source(task, source_code="CRANE")
runtime_source = build_task_rpa_inventory_source(task)
assert runtime_source is not None
assert runtime_source["site_id"] == "CRANE"
assert runtime_source["warehouse_id"] == "TZR2"
assert runtime_source["query"]["warehouse_code"] == "TZR2"
inv = create_inventory_snapshot_from_rpa(
source=runtime_source,
local_path=xlsx,
trigger_type="on_demand",
success=True,
)
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="rpa_callback")
db.session.commit()
assert inv.warehouse_id == "TZR2"
assert (inv.source_query_json or {}).get("warehouse_id_source") == "task_identity_excel_verified"
assert (inv.source_query_json or {}).get("excel_warehouse_verified") is True
assert link is not None
assert link.matched_warehouse_id == "TZR2"
def test_different_inventory_source_cannot_reuse_snapshot(app, tmp_path):
"""相同 SKU 但库存源不同不能复用快照。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
xlsx = tmp_path / "stock.xlsx"
_write_inventory_xlsx(xlsx, "AWSDU")
with app.app_context():
source = build_rpa_inventory_source("DSV360_AWSDU")
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
task = _task_with_inventory_source(
"SN-SNAPSHOT-MISMATCH",
source_code="DSV360_AWSAMS",
connector_type="dsv360",
site_id="AWSAMS",
)
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="reuse_latest")
db.session.commit()
assert link is None
assert inv.identity_status == "mismatch"
def test_expired_snapshot_not_reused(app, tmp_path):
"""过期快照不应被 find_latest_ready_snapshot 返回。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 1
xlsx = tmp_path / "stock.xlsx"
_write_inventory_xlsx(xlsx, "AWSDU")
source = build_rpa_inventory_source("DSV360_AWSDU")
with app.app_context():
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, success=True)
inv.exported_at = datetime.utcnow() - timedelta(hours=2)
inv.expires_at = snapshot_expires_at(inv.exported_at)
db.session.commit()
assert not is_snapshot_fresh(inv)
assert find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU") is None
def test_link_snapshot_writes_audit_fields(app, tmp_path):
"""任务与快照 link 应写入 link_reason 与 audit_payload。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
xlsx = tmp_path / "stock.xlsx"
_write_inventory_xlsx(xlsx, "AWSDU")
with app.app_context():
task = _task_with_inventory_source(
"SN-SNAPSHOT-LINK",
source_code="DSV360_AWSDU",
connector_type="dsv360",
site_id="AWSDU",
)
db.session.add(task)
db.session.commit()
source = build_rpa_inventory_source("DSV360_AWSDU")
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
link = link_snapshot_to_task(task, inv, reason="reuse_latest", audit_payload={"mode": "auto"})
db.session.commit()
assert link is not None
assert link.link_reason == "reuse_latest"
assert link.matched_site_id == "AWSDU"
assert link.matched_source_code == "DSV360_AWSDU"
assert link.audit_payload_json["source_code"] == "DSV360_AWSDU"
File diff suppressed because it is too large. Load diff
@@ -1,199 +0,0 @@
"""
backend/tests/test_shipping_notice_inventory_sources_config.py
用途:验证库存连接器 YAML/JSON 配置加载、校验与缓存刷新。
依赖:inventory_sources、pytest tmp_path/app 夹具。
逻辑:以 connector_type 配置样本覆盖 DSV/Crane 身份约束及 worker 兼容 query。
"""
from pathlib import Path
import pytest
from app.services.shipping_notice.inventory_sources import (
InventorySourceConfigError,
build_rpa_inventory_source,
get_inventory_source,
list_inventory_sources,
reload_inventory_sources_config,
)
def test_inventory_sources_yaml_loads(app):
"""默认 YAML 配置应成功加载并包含 DSV360_AWSDU。"""
with app.app_context():
reload_inventory_sources_config()
source = get_inventory_source("DSV360_AWSDU")
assert source is not None
assert source["connector_type"] == "dsv360"
assert source["site_id"] == "AWSDU"
assert source["warehouse_id"] == "AWSDU"
assert source["query"]["program_label"]
def test_build_rpa_inventory_source_keeps_legacy_query(app):
"""build_rpa_inventory_source 应返回 worker 兼容 query,AWSBI 子仓仅含 Warehouse 参数。"""
with app.app_context():
payload = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01")
assert payload is not None
assert payload["site_id"] == "AWSBI"
assert payload["warehouse_id"] == "BYAWSATL01"
assert payload["query"]["warehouse_code"] == "BYAWSATL01"
assert payload["query"]["program_label"] == "AWSBI"
assert "owner_code" not in payload["query"]
assert len(payload["parameters"]) == 1
assert payload["parameters"][0]["name"] == "Warehouse"
def test_awsams_warehouse_uses_multi_select_all(app):
"""AWSAMS Warehouse 是 SSRS checkbox 下拉,配置应显式走 multi_select + select_all。"""
with app.app_context():
reload_inventory_sources_config()
payload = build_rpa_inventory_source("DSV360_AWSAMS")
assert payload is not None
warehouse_param = next(item for item in payload["parameters"] if item["name"] == "Warehouse")
assert warehouse_param["mode"] == "multi_select"
assert warehouse_param["select_all"] is True
assert warehouse_param["values"] == ["RTM"]
assert warehouse_param["selectors"] == {
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
}
def test_duplicate_source_code_raises(app, tmp_path):
"""source_code 重复时加载应报错。"""
bad = tmp_path / "bad_sources.json"
bad.write_text(
"""
{
"version": 1,
"sources": [
{"source_code": "X1", "enabled": true, "connector_type": "dsv360", "site_id": "S1", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []},
{"source_code": "X1", "enabled": true, "connector_type": "dsv360", "site_id": "S1", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []}
]
}
""",
encoding="utf-8",
)
app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad)
with app.app_context():
with pytest.raises(InventorySourceConfigError, match="duplicate"):
reload_inventory_sources_config()
def test_dsv_source_requires_site_id(app, tmp_path):
"""DSV 源必须显式配置 site_id,避免把站点和仓库混用。"""
bad = tmp_path / "bad_sources.yaml"
bad.write_text(
"""
version: 1
sources:
- source_code: DSV360_BAD
enabled: true
connector_type: dsv360
warehouse_id: AWSBI
entry_url: http://x
navigation: {}
parameters: []
""",
encoding="utf-8",
)
app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad)
with app.app_context():
with pytest.raises(InventorySourceConfigError, match="site_id is required"):
reload_inventory_sources_config()
def test_dsv_source_requires_warehouse_id(app, tmp_path):
"""DSV 源必须显式配置 warehouse_id。"""
bad = tmp_path / "bad_sources.yaml"
bad.write_text(
"""
version: 1
sources:
- source_code: DSV360_BAD
enabled: true
connector_type: dsv360
site_id: AWSBI
entry_url: http://x
navigation: {}
parameters: []
""",
encoding="utf-8",
)
app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad)
with app.app_context():
with pytest.raises(InventorySourceConfigError, match="warehouse_id is required"):
reload_inventory_sources_config()
def test_build_rpa_inventory_source_crane_has_site_and_alias_resolution(app):
"""Crane 源须配置 site_id 与 match_aliases,库位由订单别名解析。"""
with app.app_context():
reload_inventory_sources_config()
payload = build_rpa_inventory_source("CRANE")
assert payload is not None
assert payload["connector_type"] == "crane_footprint"
assert payload["site_id"] == "CRANE"
assert payload["warehouse_id"] == ""
assert payload["warehouse_resolution"] == "alias_match"
assert payload.get("allowed_warehouse_ids") == ["TZR", "TZR2", "TZR3"]
assert payload["parameters"] == []
assert payload["navigation"]["download_mode"] == "scheduled_report"
def test_match_aliases_available_via_list(app):
"""list_inventory_sources 应包含 match_aliases 供规则匹配。"""
with app.app_context():
reload_inventory_sources_config()
codes = {item["source_code"] for item in list_inventory_sources()}
assert "DSV360_AWSDU" in codes
assert "DSV360_AWSBI_BYAWSATL01" in codes
assert "CRANE" in codes
awsbi_count = sum(1 for item in list_inventory_sources() if str(item.get("source_code", "")).startswith("DSV360_AWSBI_"))
assert awsbi_count == 25
def test_inventory_sources_cache_refreshes_when_content_changes_with_same_mtime(app, tmp_path, monkeypatch):
"""配置内容变化但 mtime 不变时,缓存仍须刷新。"""
import os
from app.services.shipping_notice import inventory_sources as mod
cfg = tmp_path / "sources.yaml"
cfg.write_text(
"""
version: 1
sources:
- source_code: CACHE_TEST
enabled: true
connector_type: dsv360
site_id: S1
warehouse_id: W1
entry_url: http://example.com
navigation: {}
parameters: []
""",
encoding="utf-8",
)
fixed_mtime = 1_700_000_000.0
os.utime(cfg, (fixed_mtime, fixed_mtime))
app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(cfg)
with app.app_context():
mod._CONFIG_CACHE = None
mod._CONFIG_PATH = None
mod._CONFIG_RAW_DIGEST = None
first = mod.reload_inventory_sources_config()
assert first["sources"]["CACHE_TEST"]["warehouse_id"] == "W1"
cfg.write_text(
cfg.read_text(encoding="utf-8").replace("warehouse_id: W1", "warehouse_id: W2"),
encoding="utf-8",
)
os.utime(cfg, (fixed_mtime, fixed_mtime))
second = mod.reload_inventory_sources_config()
assert second["sources"]["CACHE_TEST"]["warehouse_id"] == "W2"
assert second is not first
@@ -1,34 +1,20 @@
from app.services.shipping_notice.match_rule_desc import (
build_match_rule_fallback,
extract_mapping_payload_extras,
resolve_match_rule,
)
def test_extract_mapping_payload_extras():
payload = {
"part_number": "Supplier Sku",
"aws_part_number": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
"match_rule": "以 Reservation Order 对齐订单 reservation_id,汇总 Qty Available 与订单 qty 比对。",
}
extras = extract_mapping_payload_extras(payload)
assert extras["match_rule"].startswith("以 Reservation Order")
assert "match_key" not in extras
def test_resolve_match_rule_prefers_llm():
def test_resolve_match_rule_uses_configured_mapping_only():
mapping = {
"part_number": "Supplier Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
llm_rule = "LLM 自定义匹配说明。"
rule, keys, source = resolve_match_rule(mapping, llm_match_rule=llm_rule)
assert rule == llm_rule
rule, keys, source = resolve_match_rule(mapping)
assert "Supplier Sku" in rule
assert "Reservation Order" in rule
assert keys == ["part_number", "reservation_id"]
assert source == "llm"
assert source == "configured_mapping"
def test_build_match_rule_fallback_uses_column_names():
@@ -1,7 +1,7 @@
"""
tests/test_shipping_notice_openapi_contract.py
用途:锁定发货通知 v2 订单行、单一路由线索与库存连接器 OpenAPI 命名契约。
用途:锁定发货通知动态订单字段、证据观察值与库存连接器 OpenAPI 命名契约。
依赖:Flask 测试 client、静态 Dify OpenAPI JSON。
逻辑:分别校验动态 builder 输出与脚本生成的静态快照,防止两者发生漂移。
"""
@@ -17,7 +17,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
"""
校验订单行与库存连接器的字段边界。
核心逻辑:订单行只接受 part_number 与可选外部料号/inventory_source_hint;
核心逻辑:订单行只接受动态 fields 数组,每个字段携带稳定 field_id 和 observations;
任务状态说明使用 inventory_connector_type,并拒绝旧 inventory_source_type 命名。
Args:
@@ -31,15 +31,12 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
]["schema"]["properties"]["orders"]["items"]
line_properties = order_schema["properties"]["lines"]["items"]["properties"]
assert order_schema["properties"]["lines"]["items"]["additionalProperties"] is False
assert set(line_properties) == {
"part_number",
"customer_part_number",
"aws_part_number",
"qty",
"reservation_id",
"inventory_source_hint",
}
assert "库存来源提示" in line_properties["inventory_source_hint"]["description"]
assert set(line_properties) == {"fields"}
assert line_properties["fields"]["type"] == "array"
field_item = line_properties["fields"]["items"]
assert {"field_id", "observations"} <= set(field_item["properties"])
observation = field_item["properties"]["observations"]["items"]
assert {"value", "document_id", "quote", "confidence"} <= set(observation["properties"])
assert not {"sku", "vendor_part_number", "source_type", "hub_code"} & set(line_properties)
request_schema = spec["paths"]["/tools/submit_order_extraction"]["post"]["requestBody"]["content"][
@@ -27,6 +27,7 @@ from app.models import (
ShippingNoticeIntake,
ShippingTask,
ShippingTaskEvent,
ShippingOrderSchemaVersion,
User,
)
from app.services.agent_runtime_context.builder import build_agent_runtime_context, serialize_for_dify
@@ -55,6 +56,49 @@ from app.services.shipping_notice.intake_service import get_intake_statuses, lis
from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.query_service import resolve_order_extraction_ui_target
from app.services.shipping_notice.task_workflow import update_notice_line
from app.services.shipping_notice.order_schema import service as order_schema_service
def _ensure_order_schema() -> dict[str, str]:
"""为订单抽取集成测试发布最小动态 Schema,并返回 field_code 到稳定 ID 的映射。"""
published = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
if published is not None:
return {
str(item['field_code']): str(item['field_id'])
for item in (published.definition_json or {}).get('fields') or []
}
order_schema_service.initialize_schema({'display_name': '订单抽取测试字段'}, actor_id=None)
definitions = [
('po_number', 'header', 'string', False, 'trim', [], 'normalized_text'),
('part_number', 'line', 'string', True, 'uppercase_trim', ['non_empty'], 'normalized_text'),
('qty', 'line', 'decimal', True, 'decimal', ['positive_decimal'], 'decimal'),
('reservation_id', 'line', 'string', False, 'reservation_id', ['reservation_id'], 'reservation_id'),
('inventory_source_hint', 'line', 'string', False, 'trim', [], 'normalized_text'),
]
fields = {}
configs = []
for code, scope, value_type, required, normalizer, validators, comparator in definitions:
field = order_schema_service.save_field(
{'field_code': code, 'scope': scope, 'value_type': value_type}, actor_id=None,
)
fields[code] = field['id']
configs.append({
'field_id': field['id'], 'display_name': code, 'required': required, 'aliases': [],
'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_text', 'backend_table', 'dify_llm'],
'conflict_policy': 'block', 'allow_single_source': True,
},
'relation_role': None, 'comparator_key': comparator,
})
draft = order_schema_service.create_draft({}, actor_id=None)
saved_schema = order_schema_service.save_draft(draft['id'], {
'fields': configs, 'expected_lock_version': draft['lock_version'],
})
order_schema_service.publish(
draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
)
return fields
def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it():
@@ -104,6 +148,7 @@ def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, S
Returns:
用户、会话、Intake、Document 与序列化 agent_runtime_context。
"""
_ensure_order_schema()
user = User(username='order-extraction-user', email='order-extraction@example.com', password_hash='x')
agent = Agent(
name='Shipping Notice',
@@ -187,34 +232,68 @@ def _order(
confidence: float = 0.99,
include_process_fields: bool,
) -> dict:
"""构造符合 Chatflow V2 契约的单个订单结果。"""
line = {'part_number': part_number, 'qty': qty}
if include_process_fields:
line.update({'reservation_id': 'R-100', 'inventory_source_hint': 'AWS Dublin'})
evidence = [
{'field': 'lines[0].part_number', 'quote': f'SKU {part_number}', 'document_id': document_id},
{'field': 'lines[0].qty', 'quote': f'QTY {qty}', 'document_id': document_id},
"""构造符合动态订单 Schema 契约的单个订单结果。"""
fields = _ensure_order_schema()
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
document = db.session.get(ShippingNoticeDocument, document_id)
po_quote = f'PO {po_number}'
line_fields = [
{'field_id': fields['part_number'], 'observations': [
{'value': part_number, 'quote': f'SKU {part_number}', 'document_id': document_id, 'confidence': confidence},
]},
{'field_id': fields['qty'], 'observations': [
{'value': qty, 'quote': f'QTY {qty}', 'document_id': document_id, 'confidence': confidence},
]},
]
if include_process_fields:
evidence.append({
'field': 'lines[0].reservation_id',
'quote': 'R-100',
'document_id': document_id,
})
line_fields.extend([
{'field_id': fields['reservation_id'], 'observations': [
{'value': 'R-100', 'quote': 'R-100', 'document_id': document_id, 'confidence': confidence},
]},
{'field_id': fields['inventory_source_hint'], 'observations': [
{'value': 'AWS Dublin', 'quote': 'AWS Dublin', 'document_id': document_id, 'confidence': confidence},
]},
])
return {
'schema_version_id': int(version.id),
'schema_checksum': version.checksum,
'source_intake_no': intake_no,
'primary_document_id': document_id,
'candidate_key_hint': po_number,
'classification': 'shipping_request',
'classification_confidence': confidence,
'field_confidence': {'part_number': confidence, 'qty': confidence},
'po_number': po_number,
'lines': [line],
'evidence': evidence,
'header_fields': ([{'field_id': fields['po_number'], 'observations': [
{'value': po_number, 'quote': po_quote, 'document_id': document_id, 'confidence': confidence},
]}] if document is not None and po_quote in str(document.extracted_text or '') else []),
'lines': [{'fields': line_fields}],
'conflicts': [],
}
def _set_dynamic_line_field(order: dict, code: str, value, *, quote: str | None = None) -> None:
"""替换动态订单首行指定 field_code 的 Observation 值与原文证据。"""
field_id = _ensure_order_schema()[code]
field = next(item for item in order['lines'][0]['fields'] if item['field_id'] == field_id)
field['observations'][0]['value'] = value
if quote is not None:
field['observations'][0]['quote'] = quote
def _remove_dynamic_line_field(order: dict, code: str) -> None:
"""从动态订单首行移除指定 field_code,模拟 LLM 缺失或无可信证据。"""
field_id = _ensure_order_schema()[code]
order['lines'][0]['fields'] = [
item for item in order['lines'][0]['fields'] if item['field_id'] != field_id
]
def _invalidate_dynamic_line_evidence(order: dict, code: str) -> None:
"""保留字段候选但使 quote 无法命中原文,验证动态证据门禁。"""
field_id = _ensure_order_schema()[code]
field = next(item for item in order['lines'][0]['fields'] if item['field_id'] == field_id)
field['observations'][0]['quote'] = 'NOT-IN-SOURCE'
def _add_extraction_intake(
*,
user: User,
@@ -710,6 +789,33 @@ def test_superseded_order_extraction_request_cannot_read_or_submit(app):
assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 0
def test_consumed_intake_is_not_reported_as_preprocessing_pending(app):
"""已完成的 Intake 重入读取时必须提示查看既有结果,不能伪装成预处理未完成。"""
with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
part_number='SKU-A',
qty=10,
include_process_fields=True,
),
],
})
with pytest.raises(ConflictError) as error:
get_order_extraction_context({'agent_runtime_context': runtime_context})
assert error.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED'
assert '已完成' in error.value.message
def test_submit_order_extraction_supports_multiple_orders_partial_success_and_replay(app):
"""一个附件可产生多 Candidate;高置信订单自动建单,低置信订单保留,重试只回放。"""
with app.app_context():
@@ -913,7 +1019,7 @@ def test_submit_order_extraction_reports_opened_existing_without_claiming_creati
assert result['created'] == []
assert result['created_count'] == 0
assert result['auto_created_count'] == 0
assert result['opened_existing_count'] == 1
assert result['opened_existing_count'] == 1, result
assert result['pending_count'] == 0
assert result['message'] == '已打开 1 个已有任务。'
assert result['opened_existing'][0]['task_no'] == existing.task_no
@@ -1176,7 +1282,7 @@ def test_order_extraction_terminal_history_payload_persists_open_existing_anchor
include_process_fields=True,
)],
})
assert result['opened_existing_count'] == 1
assert result['opened_existing_count'] == 1, result
load_handlers()
handler = get_handler('shipping_notice')
@@ -1265,7 +1371,10 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
db.session.add(existing)
db.session.commit()
document.extracted_text = f"{document.extracted_text}\nReservation ID 1000140351"
document.extracted_text = (
f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 "
"Reservation ID 1000140351 Source DBS DUB"
)
db.session.commit()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
@@ -1276,9 +1385,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
qty=24,
include_process_fields=True,
)
order['lines'][0]['reservation_id'] = '1000140351'
order['lines'][0]['inventory_source_hint'] = 'DBS DUB'
order['evidence'][-1]['quote'] = '1000140351'
_set_dynamic_line_field(order, 'reservation_id', '1000140351', quote='1000140351')
_set_dynamic_line_field(order, 'inventory_source_hint', 'DBS DUB', quote='DBS DUB')
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
@@ -1287,7 +1395,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
db.session.refresh(existing)
assert result['created_count'] == 0
assert result['opened_existing_count'] == 1
assert not result['pending_orders'], result['pending_orders']
assert result['opened_existing_count'] == 1, result
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1
candidate = ShippingNoticeCandidate.query.filter_by(consumed_task_id=int(existing.id)).one()
candidate_line = candidate.structured_result_json['business_summary']['lines'][0]
@@ -1322,11 +1431,7 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide
qty=10,
include_process_fields=True,
)
order['evidence'] = [
item
for item in order['evidence']
if item['field'] != 'lines[0].reservation_id'
]
_invalidate_dynamic_line_evidence(order, 'reservation_id')
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
@@ -1336,7 +1441,7 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide
assert result['created_count'] == 0
assert result['pending_count'] == 1
assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons']
assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons']
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
@@ -1370,13 +1475,13 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
assert result['pending_count'] == 1
assert 'blocking_conflict' in result['pending_orders'][0]['reasons']
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.conflicts_json[0]['reason'] == 'cross_source_conflict'
assert any(item['reason'] == 'cross_source_conflict' for item in candidate.conflicts_json)
adjudication = candidate.structured_result_json['extraction']['field_adjudication']
reservation_observations = [
item for item in adjudication['observations']
if item['field'] == 'reservation_id'
if item['field_id'] == _ensure_order_schema()['reservation_id']
]
assert {item['source'] for item in reservation_observations} == {'backend_table', 'dify_llm'}
assert {item['source_type'] for item in reservation_observations} == {'backend_table', 'attachment_text'}
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
@@ -1574,8 +1679,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
qty=24,
include_process_fields=True,
)
order['lines'][0]['reservation_id'] = '1000140351'
order['evidence'][-1]['quote'] = '1000140351'
_set_dynamic_line_field(order, 'reservation_id', '1000140351', quote='1000140351')
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
@@ -1593,8 +1697,8 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
def test_order_extraction_requires_verified_pair_after_reservation_adjudication(app, monkeypatch):
"""裁决改写 Reservation 后,必须按 (line_index, 新值) 核验证据,不能只认行号。"""
def test_order_extraction_requires_verified_dynamic_reservation_observation(app):
"""动态 Reservation Observation 的 quote 不命中原文时必须阻断,不能只认字段 ID。"""
with app.app_context():
user, _session, intake, document, runtime_context = _seed_extraction_input()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
@@ -1606,21 +1710,7 @@ def test_order_extraction_requires_verified_pair_after_reservation_adjudication(
qty=10,
include_process_fields=True,
)
order['lines'][0]['reservation_id'] = '1000140351'
order['evidence'][-1]['quote'] = '1000140351'
def _rewrite_reservation(summary, *, documents):
rewritten = dict(summary)
lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)]
if lines:
lines[0]['reservation_id'] = '3000092917'
rewritten['lines'] = lines
return rewritten, []
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction.adjudicate_order_reservations',
_rewrite_reservation,
)
_set_dynamic_line_field(order, 'reservation_id', '1000140351', quote='1000140351')
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
@@ -1631,7 +1721,7 @@ def test_order_extraction_requires_verified_pair_after_reservation_adjudication(
assert result['created_count'] == 0
assert result['opened_existing_count'] == 0
assert result['pending_count'] == 1
assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons']
assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons']
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.selected is False
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
@@ -1662,6 +1752,10 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
db.session.add(existing)
db.session.commit()
document.extracted_text = (
f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 Reservation ID 1000140351"
)
db.session.commit()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
intake_no=intake.intake_no,
@@ -1671,10 +1765,8 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
qty=24,
include_process_fields=True,
)
order['lines'][0]['reservation_id'] = '1000140351'
order['evidence'] = [
item for item in order['evidence'] if item['field'] != 'lines[0].reservation_id'
]
_set_dynamic_line_field(order, 'reservation_id', '1000140351')
_invalidate_dynamic_line_evidence(order, 'reservation_id')
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
@@ -1689,7 +1781,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
assert candidate.consumed_task_id is None
assert result['opened_existing_count'] == 0
assert result['pending_count'] == 1
assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons']
assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons']
assert 'reservation_id' not in (existing.lines_json[0] or {})
@@ -8,6 +8,7 @@ from app.services.shipping_notice.query_service import (
extract_task_no_from_text,
get_task_by_ref,
get_task_in_batch,
list_tasks_for_user,
list_batch_task_summaries,
resolve_task_from_payload,
serialize_batch,
@@ -80,6 +81,33 @@ def test_get_task_in_batch_rejects_foreign_task(app):
assert get_task_in_batch("SB-B", "SN-FOREIGN") is None
def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
"""库存缺口筛选应读取复核状态,而不是要求不存在的 process_status。"""
with app.app_context():
from app import db
shortage = ShippingTask(
task_no="SN-FILTER-SHORTAGE",
process_status="pending_review",
review_status="shortage_review",
pending_human_reason="shortage",
source_type="manual",
)
ordinary = ShippingTask(
task_no="SN-FILTER-PARSE",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
)
db.session.add_all([shortage, ordinary])
db.session.commit()
rows = list_tasks_for_user(999999, process_status="shortage_review")
assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"]
def test_task_export_error_message_distinct_for_missing_path(app):
"""无导出路径与磁盘缺失应返回不同错误文案。"""
with app.app_context():
@@ -92,7 +120,7 @@ def test_task_export_error_message_distinct_for_missing_path(app):
source_type="manual",
export_file_path="/tmp/not-a-real-shipping-export.xlsx",
)
assert task_export_error_message(missing) == "export file missing on disk"
assert task_export_error_message(missing) == "export file not found" # 未落库 Task 不具备 Artifact 身份。
def test_task_projection_tool_strips_internal_fields(app):
@@ -7,11 +7,17 @@ from app.services.shipping_notice.reservation_id import (
def test_match_numeric_reservation_id():
notice = [{"part_number": "D4-A08AR12000002", "reservation_id": "1000140351", "qty": 2}]
inventory = [{"part_number": "D4-A08AR12000002", "reservation_id": 1000140351.0, "available_qty": 3}]
status, results, _ = match_notice_lines(notice, inventory)
notice = [{"order-part": "D4-A08AR12000002", "order-reservation": "1000140351", "__required_qty": 2}]
inventory = [{"101": "D4-A08AR12000002", "102": "1000140351", "103": 3}]
status, results, _ = match_notice_lines(
notice, inventory,
match_keys=[
{'order_field_id': 'order-part', 'inventory_field_id': '101'},
{'order_field_id': 'order-reservation', 'inventory_field_id': '102'},
],
quantity_field_id='103',
)
assert status == "fulfillable"
assert results[0]["reservation_id"] == "1000140351"
assert results[0]["available_qty"] == 3
@@ -12,7 +12,7 @@ from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_
def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path):
"""batch 开启时单票按需应写 inventory_export_batch trigger。"""
trigger_dir = tmp_path / "triggers"
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
source = {
@@ -41,7 +41,7 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path):
def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path):
"""batch 关闭时仍写 legacy inventory_export trigger。"""
trigger_dir = tmp_path / "triggers"
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
@@ -49,3 +49,24 @@ def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path):
path = write_inventory_export_trigger_for_task("SN-LEGACY-1", source)
assert path
assert list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json"))
def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_path):
"""平台 trigger 仅保留业务 connector,且明确给 worker 兼容的 driver 与登录入口。"""
import json
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
trigger_dir = tmp_path / "triggers"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
path = write_inventory_export_batch_trigger("RUN-DBS", [{
"source_code": "UNKNOWN_FOR_TEST", "connector_type": "dbs", "rpa_profile_code": "DBS_TEST",
"fixed_warehouse_id": "DUB", "login_url": "https://example.invalid/dbs",
}])
assert path
item = json.loads((trigger_dir / "inventory_export_batch_RUN-DBS.json").read_text(encoding="utf-8"))["inventory_sources"][0]
assert item["connector_type"] == "dbs"
assert item["worker_connector_type"] == "dsv360"
assert item["entry_url"] == "https://example.invalid/dbs"
assert "username" not in item
assert "password" not in item
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,161 @@
"""
backend/tests/test_shipping_order_customer_matching.py
用途:验证订单 Bill-to / Ship-to 与货代客户主数据的角色化匹配。
依赖:订单 Schema 模型、客户主数据模型、order_customer_matching 服务。
逻辑:覆盖标准名称、审核别名、歧义、未命中和人工确认快照。
"""
from app import db
from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
ShippingOrderExtraction,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
)
from app.services.shipping_notice.customer_normalization import normalize_customer_name
from app.services.shipping_notice.order_customer_matching import (
confirm_order_customer_match,
refresh_order_customer_matches,
)
def _extraction() -> ShippingOrderExtraction:
"""构造角色化客户匹配测试所需的最小订单解析记录。"""
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单字段')
db.session.add(schema)
db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='draft', definition_json={})
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
return extraction
def test_order_customer_matching_resolves_roles_and_short_codes(app):
"""Bill-to/Ship-to 应可命中不同客户,简称必须来自主数据。"""
with app.app_context():
bill_to = ShippingCustomer(standard_name='Amazon Web Services', short_code='AWS')
db.session.add(bill_to)
db.session.flush()
ship_to = ShippingCustomerSite(
customer_id=bill_to.id, site_name='Amazon Dublin DC', site_code='DUB01', status='active',
)
db.session.add(ship_to)
db.session.flush()
db.session.add(ShippingCustomerSiteIdentifier(
site_id=ship_to.id,
identifier_type='name_alias', source_system='',
raw_value='AWS Dublin DC',
normalized_value=normalize_customer_name('AWS Dublin DC'),
status='approved',
))
extraction = _extraction()
results = refresh_order_customer_matches(extraction, {
'bill_to_customer': 'Amazon Web Services',
'ship_to_customer': 'AWS Dublin DC',
})
by_role = {item['role']: item for item in results}
assert by_role['bill_to']['customer_id'] == bill_to.id
assert by_role['bill_to']['short_code'] == 'AWS'
assert by_role['ship_to']['customer_id'] == bill_to.id
assert by_role['ship_to']['site_id'] == ship_to.id
assert by_role['ship_to']['short_code'] == 'AWS'
def test_order_customer_matching_keeps_ambiguous_and_manual_confirmation(app):
"""同一别名对应多个客户时不得自动选择,人工确认后锁定标准名称和简称。"""
with app.app_context():
first = ShippingCustomer(standard_name='Customer One', short_code='ONE')
second = ShippingCustomer(standard_name='Customer Two', short_code='TWO')
db.session.add_all([first, second])
db.session.flush()
normalized = normalize_customer_name('Shared Alias')
db.session.add_all([
ShippingCustomerIdentifier(
customer_id=first.id, identifier_type='name_alias', raw_value='Shared Alias',
normalized_value=normalized, status='approved',
),
ShippingCustomerIdentifier(
customer_id=second.id, identifier_type='name_alias', raw_value='Shared Alias',
normalized_value=normalized, status='approved',
),
])
extraction = _extraction()
results = refresh_order_customer_matches(extraction, {'bill_to_customer': 'Shared Alias'})
bill_to = next(item for item in results if item['role'] == 'bill_to')
assert bill_to['status'] == 'ambiguous'
assert bill_to['customer_id'] is None
assert len(bill_to['candidates']) == 2
confirmed = confirm_order_customer_match(
extraction.id, role='bill_to', customer_id=second.id, actor_id=None,
)
assert confirmed['status'] == 'confirmed'
assert confirmed['standard_name'] == 'Customer Two'
assert confirmed['short_code'] == 'TWO'
def test_order_customer_matching_prefers_external_customer_and_site_codes(app):
"""外部客户编码和 Ship-to Code 应优先于不可靠的原文名称。"""
with app.app_context():
customer = ShippingCustomer(standard_name='Canonical Customer', short_code='CAN')
db.session.add(customer)
db.session.flush()
db.session.add(ShippingCustomerExternalRef(
customer_id=customer.id, source_system='ERP', legacy_customer_key='C001',
))
site = ShippingCustomerSite(
customer_id=customer.id, site_name='Dublin Site', site_code='DUB01', status='active',
)
db.session.add(site)
db.session.flush()
db.session.add(ShippingCustomerSiteIdentifier(
site_id=site.id, identifier_type='external_code', source_system='ERP',
raw_value='DUB-EXT', normalized_value='DUB-EXT', status='approved',
))
extraction = _extraction()
results = refresh_order_customer_matches(extraction, {
'bill_to_customer': 'Wrong Name', 'bill_to_customer_code': 'c001', 'bill_to_source_system': 'erp',
'ship_to_customer': 'Wrong Site', 'ship_to_code': 'dub-ext', 'ship_to_source_system': 'erp',
})
by_role = {item['role']: item for item in results}
assert by_role['bill_to']['customer_id'] == customer.id
assert by_role['bill_to']['resolution_method'] == 'external_customer_code'
assert by_role['ship_to']['site_id'] == site.id
assert by_role['ship_to']['resolution_method'] == 'external_site_code'
def test_ship_to_matching_falls_back_to_name_when_external_code_misses(app):
"""Ship-to 外部编码未命中时应继续使用站点标准名称,避免有效站点被错误判为未匹配。"""
with app.app_context():
customer = ShippingCustomer(standard_name='Fallback Customer', short_code='FBC')
db.session.add(customer)
db.session.flush()
site = ShippingCustomerSite(
customer_id=customer.id, site_name='Fallback Delivery Site', site_code='FBS01', status='active',
)
db.session.add(site)
extraction = _extraction()
results = refresh_order_customer_matches(extraction, {
'ship_to_customer': 'Fallback Delivery Site',
'ship_to_code': 'UNKNOWN-CODE',
'ship_to_source_system': 'ERP',
})
ship_to = next(item for item in results if item['role'] == 'ship_to')
assert ship_to['site_id'] == site.id
assert ship_to['resolution_method'] == 'site_name'
+445
View File
@@ -0,0 +1,445 @@
"""
backend/tests/test_shipping_order_schema.py
用途:验证唯一订单 Schema、动态字段、不可变版本和管理员 API 门禁。
依赖:Flask 测试客户端、订单 Schema service/models、测试数据库。
逻辑:覆盖初始化、草稿发布、稳定 checksum、字段冻结、权限与动态结果唯一约束。
"""
from __future__ import annotations
from decimal import Decimal
import pytest
from sqlalchemy.exc import IntegrityError
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderSchemaAuditEvent,
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice.order_schema import service
from tests.conftest import parse_api_data, parse_api_error
def _headers(username: str, role: str) -> dict[str, str]:
"""构造管理 API 测试使用的遗留 Header 身份。"""
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
def _seed_users() -> None:
"""创建订单 Schema 权限测试所需管理员和普通用户。"""
db.session.add_all([
User(username='schema-admin', email='schema-admin@example.com', role='admin', status='active'),
User(username='schema-user', email='schema-user@example.com', role='user', status='active'),
])
db.session.commit()
def _field_config(field_id: str, *, name: str = '需求数量') -> dict:
"""构造可发布的行字段配置,关键证据策略显式启用。"""
return {
'field_id': field_id,
'display_name': name,
'required': True,
'aliases': ['Qty', 'Quantity'],
'normalizer_key': 'decimal',
'validator_keys': ['positive_decimal'],
'enum_options': [],
'evidence_policy': {
'required': True,
'source_precedence': ['attachment_table', 'email_body_table', 'dify_llm'],
'conflict_policy': 'block',
'allow_single_source': True,
},
'relation_role': None,
'comparator_key': 'decimal',
'extraction_instruction': '仅提取订单行明确出现的正数数量',
}
def _save_draft(version_id: int, fields: list[dict], *, change_note: str | None = None) -> dict:
"""使用数据库当前锁版本保存草稿,模拟正常管理端请求。"""
version = db.session.get(ShippingOrderSchemaVersion, version_id)
assert version is not None
return service.save_draft(version_id, {
'fields': fields,
'change_note': change_note,
'expected_lock_version': version.lock_version,
})
def _publish_draft(version_id: int) -> dict:
"""使用数据库当前锁版本发布草稿,避免测试绕过乐观锁门禁。"""
version = db.session.get(ShippingOrderSchemaVersion, version_id)
assert version is not None
return service.publish(version_id, actor_id=None, expected_lock_version=version.lock_version)
def test_order_schema_publish_keeps_history_when_field_code_changes(app):
"""发布后可重命名系统标识,但旧契约快照保持原名称且位置/类型仍锁定。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({
'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal',
}, actor_id=None)
draft = service.create_draft({'change_note': '初始字段'}, actor_id=None)
_save_draft(draft['id'], [_field_config(field['id'])])
published = _publish_draft(draft['id'])
assert published['status'] == 'published'
assert len(published['checksum']) == 64
contract = service.get_published_contract()
assert contract['fields'][0]['field_code'] == 'request_qty'
assert contract['fields'][0]['scope'] == 'line'
renamed = service.save_field({
'field_code': 'renamed_qty', 'scope': 'line', 'value_type': 'decimal',
}, actor_id=None, field_id=field['id'])
assert renamed['field_code'] == 'renamed_qty'
assert service.get_published_contract()['fields'][0]['field_code'] == 'request_qty'
with pytest.raises(Exception) as exc_info:
service.save_field({
'field_code': 'renamed_qty', 'scope': 'header', 'value_type': 'decimal',
}, actor_id=None, field_id=field['id'])
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_IMMUTABLE'
def test_order_schema_excluded_field_config_is_saved_but_not_published(app):
"""未纳入字段仍保存版本显示名称和规则,但发布契约不得包含该字段。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
included = service.save_field({
'field_code': 'po_number', 'scope': 'header', 'value_type': 'string',
}, actor_id=None)
excluded = service.save_field({
'field_code': 'customer_note', 'scope': 'header', 'value_type': 'string',
}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
included_config = _field_config(included['id'], name='采购订单号')
included_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'})
excluded_config = _field_config(excluded['id'], name='下个版本客户备注')
excluded_config.update({
'enabled': False,
'normalizer_key': 'trim',
'validator_keys': [],
'comparator_key': 'normalized_text',
})
saved = _save_draft(draft['id'], [included_config, excluded_config])
saved_excluded = next(item for item in saved['definition']['fields'] if item['field_id'] == excluded['id'])
assert saved_excluded['enabled'] is False
assert saved_excluded['display_name'] == '下个版本客户备注'
assert saved['field_count'] == 1
published = _publish_draft(draft['id'])
assert [item['field_id'] for item in published['definition']['fields']] == [included['id'], excluded['id']]
assert service.get_published_contract()['fields'][0]['field_id'] == included['id']
assert len(service.get_published_contract()['fields']) == 1
def test_order_schema_new_publish_retires_previous_version(app):
"""新版本发布后应自动退役旧版本,数据库最多只有一个 published。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({
'field_code': 'po_number', 'scope': 'header', 'value_type': 'string',
}, actor_id=None)
first = service.create_draft({}, actor_id=None)
config = _field_config(field['id'], name='订单号')
config.update({'normalizer_key': 'trim', 'validator_keys': ['non_empty'], 'comparator_key': 'normalized_text'})
_save_draft(first['id'], [config])
_publish_draft(first['id'])
second = service.create_draft({'copy_from_version_id': first['id']}, actor_id=None)
_publish_draft(second['id'])
rows = ShippingOrderSchemaVersion.query.order_by(ShippingOrderSchemaVersion.version).all()
assert [item.status for item in rows] == ['retired', 'published']
def test_order_schema_admin_api_permissions_and_validation(app, client):
"""普通用户不得访问配置;管理员可初始化并收到结构化字段错误。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_seed_users()
forbidden = client.get('/api/admin/shipping-order-schema', headers=_headers('schema-user', 'user'))
assert forbidden.status_code == 403
assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN'
created = client.post(
'/api/admin/shipping-order-schema',
headers=_headers('schema-admin', 'admin'),
json={'display_name': '发货订单字段'},
)
assert created.status_code == 201
assert parse_api_data(created.get_json())['schema']['schema_code'] == 'SHIPPING_ORDER'
invalid = client.post(
'/api/admin/shipping-order-schema/fields',
headers=_headers('schema-admin', 'admin'),
json={'field_code': 'Bad Code', 'scope': 'line', 'value_type': 'string'},
)
assert invalid.status_code == 400
assert parse_api_error(invalid.get_json())['code'] == 'SHIPPING.ORDER_FIELD_INVALID'
def test_dynamic_header_field_value_is_unique(app):
"""Header 动态字段值必须按 extraction+field 唯一,避免 NULL 绕过唯一约束。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({
'field_code': 'po_number', 'scope': 'header', 'value_type': 'string',
}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
config = _field_config(field['id'], name='订单号')
config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'})
_save_draft(draft['id'], [config])
_publish_draft(draft['id'])
extraction = ShippingOrderExtraction(
schema_version_id=draft['id'], input_snapshot_hash='a' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, field_id=field['id'], decision_status='accepted',
supporting_observation_ids_json=[], resolved_value_json='PO-1',
)
db.session.add(decision)
db.session.flush()
db.session.add_all([
ShippingOrderFieldValue(
extraction_id=extraction.id, field_id=field['id'], decision_id=decision.id, value_text='PO-1',
),
ShippingOrderFieldValue(
extraction_id=extraction.id, field_id=field['id'], decision_id=decision.id,
value_text='PO-2', value_decimal=Decimal('2'),
),
])
with pytest.raises(IntegrityError):
db.session.commit()
db.session.rollback()
def test_order_schema_rejects_non_boolean_required_and_referenced_retire(app):
"""草稿字段 required 必须为布尔值,且草稿引用字段不可退役。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({
'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal',
}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
invalid = _field_config(field['id'])
invalid['required'] = 'false'
with pytest.raises(Exception) as exc_info:
_save_draft(draft['id'], [invalid])
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
_save_draft(draft['id'], [_field_config(field['id'])])
with pytest.raises(Exception) as retire_exc:
service.retire_field(field['id'])
assert getattr(retire_exc.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
def test_delete_unused_order_field_removes_draft_config_and_catalog_row(app):
"""未发布且无任何引用的字段应物理删除,并在同一事务移出当前草稿。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({
'field_code': 'temporary_note', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
config = _field_config(field['id'], name='临时备注')
config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'})
_save_draft(draft['id'], [config])
result = service.delete_field(field['id'])
assert result == {'field_id': field['id'], 'action': 'deleted'}
assert db.session.get(ShippingOrderField, field['id']) is None
assert service.get_state()['fields'] == []
assert service.get_state()['versions'][0]['field_count'] == 0
def test_delete_historical_order_field_archives_and_hides_current_catalog(app):
"""已发布字段删除时须保留历史契约,但不再返回当前配置清单。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({
'field_code': 'po_number', 'scope': 'header', 'value_type': 'string',
}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
config = _field_config(field['id'], name='订单号')
config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'})
_save_draft(draft['id'], [config])
_publish_draft(draft['id'])
next_draft = service.create_draft({}, actor_id=None)
result = service.delete_field(field['id'])
assert result == {'field_id': field['id'], 'action': 'archived'}
assert db.session.get(ShippingOrderField, field['id']).status == 'retired'
assert service.get_state()['fields'] == []
assert service.get_state()['versions'][0]['id'] == next_draft['id']
assert service.get_state()['versions'][0]['field_count'] == 0
def test_order_field_retire_is_blocked_by_active_cross_domain_config(app):
"""库存解析匹配键和 Excel 映射引用稳定字段时,字段不得退役。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
match_field = service.save_field({
'field_code': 'odm_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
template_field = service.save_field({
'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal',
}, actor_id=None)
db.session.add_all([
ShippingInventoryParsingProfile(
profile_code='shared-stock', display_name='共享库存解析', status='published',
definition_json={
'match_keys': [{
'order_field_id': match_field['id'],
'inventory_field': 'odm',
}],
},
),
ShippingExcelTemplate(
template_code='forwarder-a', display_name='货代模板 A', status='draft',
storage_provider='minio', storage_bucket='test-private',
storage_key='shipping/templates/test.xlsx', original_filename='test.xlsx',
file_checksum='a' * 64,
definition_json={
'mappings': [{
'source_kind': 'order_field',
'source_key': template_field['id'],
'target': {'sheet': 'Sheet1', 'cell': 'A2'},
}],
},
),
])
db.session.commit()
for field_id in (match_field['id'], template_field['id']):
with pytest.raises(Exception) as exc_info:
service.retire_field(field_id)
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app):
"""新 Schema 版本移除下游仍在使用的字段时,发布必须在运行前阻断。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
referenced = service.save_field({
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
replacement = service.save_field({
'field_code': 'new_part_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
first = service.create_draft({}, actor_id=None)
referenced_config = _field_config(referenced['id'])
referenced_config.update({'normalizer_key': 'trim', 'comparator_key': 'normalized_text', 'validator_keys': []})
_save_draft(first['id'], [referenced_config])
_publish_draft(first['id'])
db.session.add(ShippingInventoryParsingProfile(
profile_code='schema-gate', display_name='Schema Gate', status='published',
definition_json={'match_keys': [{
'order_field_id': referenced['id'], 'inventory_field': 'part_number',
}]},
))
db.session.commit()
second = service.create_draft({}, actor_id=None)
replacement_config = _field_config(replacement['id'])
replacement_config.update({'normalizer_key': 'trim', 'comparator_key': 'normalized_text', 'validator_keys': []})
_save_draft(second['id'], [replacement_config])
with pytest.raises(Exception) as exc_info:
_publish_draft(second['id'])
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED'
assert service.get_published_contract()['fields'][0]['field_id'] == referenced['id']
def test_order_schema_rejects_type_incompatible_rules_and_can_delete_draft(app):
"""字段规则须与类型兼容,错误草稿可删除后重新创建。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({
'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal',
}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
invalid = _field_config(field['id'])
invalid['normalizer_key'] = 'uppercase_trim'
with pytest.raises(Exception) as exc_info:
_save_draft(draft['id'], [invalid])
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
service.delete_draft(draft['id'])
replacement = service.create_draft({}, actor_id=None)
assert replacement['version'] == 1
def test_order_schema_draft_save_replaces_previous_field_configs(app):
"""重复保存草稿必须整体替换字段配置,不得残留 ORM 旧行。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
qty = service.save_field({
'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal',
}, actor_id=None)
po = service.save_field({
'field_code': 'po_number', 'scope': 'header', 'value_type': 'string',
}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
_save_draft(draft['id'], [_field_config(qty['id'])])
po_config = _field_config(po['id'], name='订单号')
po_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'})
saved = _save_draft(draft['id'], [po_config])
assert saved['field_count'] == 1
assert saved['definition']['fields'][0]['field_id'] == po['id']
def test_order_schema_draft_uses_optimistic_lock_and_writes_audit(app):
"""过期锁版本必须拒绝覆盖,成功保存和发布均产生不可变审计事件。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({
'field_code': 'po_number', 'scope': 'header', 'value_type': 'string',
}, actor_id=None, request_id='field-request')
draft = service.create_draft({}, actor_id=None, request_id='create-request')
config = _field_config(field['id'], name='订单号')
config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'})
saved = service.save_draft(draft['id'], {
'fields': [config], 'expected_lock_version': draft['lock_version'],
}, actor_id=None, request_id='save-request')
with pytest.raises(Exception) as exc_info:
service.save_draft(draft['id'], {
'fields': [config], 'expected_lock_version': draft['lock_version'],
})
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_CONFLICT'
service.publish(
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], request_id='publish-request',
)
events = ShippingOrderSchemaAuditEvent.query.order_by(ShippingOrderSchemaAuditEvent.id).all()
assert [event.event_type for event in events][-3:] == ['draft_created', 'draft_saved', 'published']
assert events[-2].request_id == 'save-request'
assert events[-2].before_snapshot_json != events[-2].after_snapshot_json
def test_order_schema_catalog_exposes_type_compatible_rules(app):
"""管理端目录必须提供类型兼容矩阵,避免页面构造后端必然拒绝的规则。"""
with app.app_context():
state = service.get_state()
assert state['catalog']['type_normalizers']['integer'] == ['integer']
assert state['catalog']['type_comparators']['date'] == ['date']
assert state['catalog']['type_validators']['boolean'] == []
@@ -0,0 +1,147 @@
"""
backend/tests/test_shipping_order_schema_diff.py
用途:验证订单 Schema 版本字段语义差异与审计时间线管理 API。
依赖:纯 diff 引擎、Flask 管理 API、订单 Schema service。
逻辑:覆盖稳定字段重命名、集合/顺序变更、版本过滤和管理员权限边界。
"""
from __future__ import annotations
from app import db
from app.models import User
from app.services.shipping_notice.order_schema import service
from app.services.shipping_notice.order_schema.diff import compare_definitions
from tests.conftest import parse_api_data, parse_api_error
def _headers(username: str, role: str) -> dict[str, str]:
"""构造管理 API 测试使用的遗留 Header 身份。"""
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
def _field(field_id: str, *, code: str = 'po_number', display_name: str = '采购订单号') -> dict:
"""构造可发布的 Header 文本字段配置,便于聚焦版本差异断言。"""
return {
'field_id': field_id,
'display_name': display_name,
'required': True,
'aliases': ['PO', 'Order Number'],
'normalizer_key': 'trim',
'validator_keys': ['non_empty'],
'enum_options': [],
'evidence_policy': {
'required': True,
'source_precedence': ['attachment_table', 'dify_llm'],
'conflict_policy': 'block',
'allow_single_source': True,
},
'relation_role': None,
'comparator_key': 'normalized_text',
'extraction_instruction': '读取订单号',
# field_code is supplied by the service from the stable field catalog.
'field_code': code,
}
def test_compare_definitions_distinguishes_rename_set_and_order_changes():
"""相同 field_id 的系统标识改名应为修改,集合项与顺序均应可审计。"""
before = {'fields': [
{
**_field('field-1'), 'field_code': 'po_number', 'sequence': 1,
'description': None, 'enabled': True, 'scope': 'header', 'value_type': 'string',
},
{**_field('field-2'), 'sequence': 2, 'enabled': True, 'scope': 'header', 'value_type': 'string'},
]}
after = {'fields': [
{
**_field('field-1', code='purchase_order', display_name='客户订单号'),
'field_code': 'purchase_order', 'sequence': 2, 'description': '', 'enabled': False,
'scope': 'header', 'value_type': 'string', 'aliases': ['Order Number', 'PO'],
'evidence_policy': {
'required': False,
'source_precedence': ['dify_llm', 'attachment_table'],
'conflict_policy': 'review',
'allow_single_source': True,
},
},
{**_field('field-3'), 'sequence': 1, 'enabled': True, 'scope': 'header', 'value_type': 'string'},
]}
result = compare_definitions(before, after)
assert result['summary'] == {'added': 1, 'removed': 1, 'modified': 1, 'unchanged': 0}
renamed = next(item for item in result['fields'] if item['field_id'] == 'field-1')
assert renamed['change_type'] == 'modified'
assert next(item for item in renamed['changes'] if item['key'] == 'field_code') == {
'key': 'field_code', 'kind': 'value', 'before': 'po_number', 'after': 'purchase_order',
}
aliases = next(item for item in renamed['changes'] if item['key'] == 'aliases')
assert aliases['added'] == [] and aliases['removed'] == [] and aliases['order_changed'] is True
sources = next(item for item in renamed['changes'] if item['key'] == 'evidence_policy.source_precedence')
assert sources['order_changed'] is True
def test_admin_can_compare_versions_and_read_filtered_audit_timeline(app, client):
"""差异和审计接口只对管理员开放,版本过滤返回指定版本的追加事件。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
db.session.add_all([
User(id=1, username='schema-diff-admin', email='schema-diff-admin@example.com', role='admin', status='active'),
User(id=2, username='schema-diff-user', email='schema-diff-user@example.com', role='user', status='active'),
])
db.session.commit()
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=1)
field = service.save_field({'field_code': 'po_number', 'scope': 'header', 'value_type': 'string'}, actor_id=1)
first_draft = service.create_draft({}, actor_id=1)
first_saved = service.save_draft(first_draft['id'], {
'fields': [_field(field['id'])], 'expected_lock_version': first_draft['lock_version'],
}, actor_id=1)
first = service.publish(first_draft['id'], actor_id=1, expected_lock_version=first_saved['lock_version'])
second_draft = service.create_draft({'copy_from_version_id': first['id']}, actor_id=1)
service.save_field({
'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string',
}, actor_id=1, field_id=field['id'])
second = service.get_version_detail(second_draft['id'])
forbidden = client.get(
f"/api/admin/shipping-order-schema/versions/{first['id']}/diff?against_version_id={second['id']}",
headers=_headers('schema-diff-user', 'user'),
)
assert forbidden.status_code == 403
assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN'
forbidden_audit = client.get(
'/api/admin/shipping-order-schema/audit-events', headers=_headers('schema-diff-user', 'user'),
)
assert forbidden_audit.status_code == 403
assert parse_api_error(forbidden_audit.get_json())['code'] == 'AUTH.FORBIDDEN'
diff_response = client.get(
f"/api/admin/shipping-order-schema/versions/{first['id']}/diff?against_version_id={second['id']}",
headers=_headers('schema-diff-admin', 'admin'),
)
assert diff_response.status_code == 200
diff = parse_api_data(diff_response.get_json())
assert diff['summary']['modified'] == 1
field_diff = diff['fields'][0]
assert field_diff['change_type'] == 'modified'
assert any(change['key'] == 'field_code' for change in field_diff['changes'])
audit_response = client.get(
f"/api/admin/shipping-order-schema/audit-events?page=1&page_size=20&version_id={second['id']}",
headers=_headers('schema-diff-admin', 'admin'),
)
assert audit_response.status_code == 200
audit = parse_api_data(audit_response.get_json())
assert audit['total'] >= 2
assert all(item['version']['id'] == second['id'] for item in audit['items'])
assert all('before_snapshot_json' not in item for item in audit['items'])
paged_audit = client.get(
'/api/admin/shipping-order-schema/audit-events?page=1&page_size=1',
headers=_headers('schema-diff-admin', 'admin'),
)
assert paged_audit.status_code == 200
page = parse_api_data(paged_audit.get_json())
assert page['page'] == 1 and page['page_size'] == 1 and len(page['items']) == 1
@@ -0,0 +1,55 @@
"""
backend/tests/test_shipping_order_schema_enabled_migration.py
用途:隔离验证订单 Schema 版本字段 enabled 迁移可安全往返。
依赖:Alembic Operations、SQLAlchemy 内存数据库、enabled 增量迁移。
逻辑:创建迁移前最小表,验证现有行回填为 true,并确认 downgrade 可移除新增列。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def _load_migration():
"""从文件加载 enabled 增量迁移模块。"""
path = Path(__file__).parents[1] / 'migrations' / 'versions' / 'f61b7c8d9e0a_add_schema_version_field_enabled.py'
spec = importlib.util.spec_from_file_location('shipping_order_schema_enabled_migration', path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _columns(connection) -> set[str]:
"""返回版本字段表的列名集合。"""
return {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_schema_version_fields')}
def test_shipping_order_schema_enabled_migration_round_trip():
"""迁移应把历史配置视为已纳入,并支持完整回滚。"""
engine = sa.create_engine('sqlite:///:memory:')
with engine.begin() as connection:
connection.execute(sa.text(
'CREATE TABLE shipping_order_schema_version_fields '
'(id INTEGER PRIMARY KEY, schema_version_id INTEGER NOT NULL, field_id VARCHAR(36) NOT NULL)'
))
connection.execute(sa.text(
"INSERT INTO shipping_order_schema_version_fields (id, schema_version_id, field_id) VALUES (1, 1, 'field-1')"
))
migration = _load_migration()
migration.op = Operations(MigrationContext.configure(connection))
migration.upgrade()
assert 'enabled' in _columns(connection)
assert connection.execute(sa.text(
'SELECT enabled FROM shipping_order_schema_version_fields WHERE id = 1'
)).scalar_one() in (True, 1)
migration.downgrade()
assert 'enabled' not in _columns(connection)
@@ -0,0 +1,73 @@
"""
backend/tests/test_shipping_order_schema_migration.py
用途:隔离验证订单 Schema 迁移在 SQLite 上可 upgrade/downgrade。
依赖:Alembic Operations、SQLAlchemy 内存数据库、阶段 1 迁移模块。
逻辑:先创建上一版本所需最小依赖表,再直接执行本迁移,断言新增表和 Task 引用可完整往返。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def _load_migration():
"""从文件加载数字开头的 Alembic 迁移模块。"""
path = Path(__file__).parents[1] / 'migrations' / 'versions' / '9b0c1d2e3f4a_add_shipping_order_schema.py'
spec = importlib.util.spec_from_file_location('shipping_order_schema_migration', path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _create_baseline(connection) -> None:
"""创建阶段 1 迁移所需的上一版本最小外键目标表。"""
metadata = sa.MetaData()
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_notice_intakes', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_notice_documents', metadata, sa.Column('id', sa.Integer(), primary_key=True))
metadata.create_all(connection)
def _table_names(connection) -> set[str]:
"""返回当前连接可见的业务表集合。"""
return set(sa.inspect(connection).get_table_names())
def _task_columns(connection) -> set[str]:
"""返回 shipping_tasks 当前列名集合。"""
return {item['name'] for item in sa.inspect(connection).get_columns('shipping_tasks')}
def test_shipping_order_schema_migration_round_trip():
"""本阶段迁移必须能新增并完整移除动态订单结构。"""
engine = sa.create_engine('sqlite:///:memory:')
with engine.begin() as connection:
_create_baseline(connection)
context = MigrationContext.configure(connection)
migration = _load_migration()
migration.op = Operations(context)
# 关键断言:upgrade 创建全部核心表和 Task 当前解析引用。
migration.upgrade()
tables = _table_names(connection)
assert {
'shipping_order_schemas', 'shipping_order_fields', 'shipping_order_schema_versions',
'shipping_order_extractions', 'shipping_order_field_observations',
'shipping_order_field_decisions', 'shipping_order_field_values',
}.issubset(tables)
assert 'current_order_extraction_id' in _task_columns(connection)
# 回滚必须只移除本阶段对象,保留上一版本业务表。
migration.downgrade()
tables = _table_names(connection)
assert 'shipping_order_schemas' not in tables
assert 'shipping_tasks' in tables
assert 'current_order_extraction_id' not in _task_columns(connection)
@@ -0,0 +1,144 @@
"""
backend/tests/test_shipping_order_schema_runtime.py
用途:验证已发布订单 Schema 编译、EML/PDF 动态字段交叉验证和类型化持久化。
依赖:order_schema service/runtime、ShippingNoticeDocument、动态订单模型。
逻辑:创建唯一 Schema 后提交稳定 field_id Observation,断言一致证据被接受、冲突被阻断且下游只得到 field_code 投影。
"""
from __future__ import annotations
from app import db
from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeIntake, ShippingOrderFieldValue, User
from app.services.shipping_notice.order_schema import service
from app.services.shipping_notice.order_schema.runtime import dify_contract, persist_dynamic_order, published_version
def _config(field_id: str, name: str, *, value_type: str) -> dict:
"""构造运行期测试使用的必填行字段配置。"""
return {
'field_id': field_id,
'display_name': name,
'required': True,
'aliases': [],
'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim',
'validator_keys': ['positive_decimal'] if value_type == 'decimal' else ['non_empty'],
'enum_options': [],
'evidence_policy': {
'required': True,
'source_precedence': ['attachment_text', 'email_body_text', 'backend_table', 'dify_llm'],
'conflict_policy': 'block',
'allow_single_source': True,
},
'relation_role': None,
'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text',
}
def _save_and_publish(draft: dict, fields: list[dict]) -> dict:
"""按乐观锁契约保存并发布运行时测试使用的 Schema。"""
saved = service.save_draft(draft['id'], {
'fields': fields, 'expected_lock_version': draft['lock_version'],
})
return service.publish(
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
)
def _seed_documents() -> tuple[int, list[ShippingNoticeDocument], int]:
"""创建同一 Intake 下的邮件正文和 PDF Document,供跨文档证据验证。"""
user = User(username='dynamic-runtime', email='dynamic-runtime@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-DYNAMIC-RUNTIME', owner_user_id=user.id, original_filename='order.eml',
storage_provider='minio', storage_bucket='test', storage_key='dynamic/order.eml',
content_hash='dynamic-runtime-hash', file_size=100, mime_type='message/rfc822',
upload_status='ready', lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-DYNAMIC-RUNTIME', asset_id=asset.id, user_id=user.id,
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
)
db.session.add(intake)
db.session.flush()
body = ShippingNoticeDocument(
intake_id=intake.id, asset_id=asset.id, document_type='body', attachment_key='body',
filename='body.txt', content_hash='dynamic-body', classification='order_notice',
parse_status='parsed', extracted_text='Please ship PART-100 quantity 10.',
)
pdf = ShippingNoticeDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='order.pdf',
filename='order.pdf', content_hash='dynamic-pdf', classification='order_notice',
parse_status='parsed', extracted_text='Part Number PART-100 Qty 10',
)
db.session.add_all([body, pdf])
db.session.flush()
return int(intake.id), [body, pdf], int(user.id)
def test_dynamic_schema_contract_and_cross_document_persistence(app):
"""同一字段在 EML 与 PDF 一致时应 corroborated,并生成类型化值与 field_code 投影。"""
with app.app_context():
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
published = _save_and_publish(draft, [
_config(part['id'], '内部料号', value_type='string'),
_config(qty['id'], '数量', value_type='decimal'),
])
intake_id, documents, actor_id = _seed_documents()
contract = dify_contract(published_version())
result = persist_dynamic_order(
raw_order={
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
'header_fields': [],
'lines': [{'fields': [
{'field_id': part['id'], 'observations': [
{'value': 'PART-100', 'document_id': documents[0].id, 'quote': 'PART-100', 'confidence': 0.9},
{'value': 'PART-100', 'document_id': documents[1].id, 'quote': 'PART-100', 'confidence': 0.9},
]},
{'field_id': qty['id'], 'observations': [
{'value': 10, 'document_id': documents[1].id, 'quote': 'Qty 10', 'confidence': 0.9},
]},
]}],
},
intake_id=intake_id, snapshot_hash='b' * 64, documents=documents, actor_id=actor_id,
)
assert contract['fields'][0]['field_id'] in {part['id'], qty['id']}
assert result['blocked_fields'] == []
assert result['lines'] == [{'part_number': 'PART-100', 'qty': '10'}]
assert result['extraction'].input_snapshot_json['documents'][0]['extracted_text'] == 'Please ship PART-100 quantity 10.'
assert any(item['status'] == 'corroborated' for item in result['decisions'])
assert len(result['decisions']) == 2
assert ShippingOrderFieldValue.query.filter_by(extraction_id=result['extraction'].id).count() == 2
def test_dynamic_schema_blocks_conflicting_documents(app):
"""EML 与 PDF 对同一字段给出不同可信值时必须保留 Observation 并阻断自动接受。"""
with app.app_context():
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
published = _save_and_publish(draft, [_config(part['id'], '内部料号', value_type='string')])
intake_id, documents, actor_id = _seed_documents()
documents[0].extracted_text = 'Please ship PART-200.'
result = persist_dynamic_order(
raw_order={
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
'header_fields': [],
'lines': [{'fields': [{'field_id': part['id'], 'observations': [
{'value': 'PART-200', 'document_id': documents[0].id, 'quote': 'PART-200'},
{'value': 'PART-100', 'document_id': documents[1].id, 'quote': 'PART-100'},
]}]}],
},
intake_id=intake_id, snapshot_hash='c' * 64, documents=documents, actor_id=actor_id,
)
assert result['blocked_fields'] == ['part_number']
assert result['decisions'][0]['status'] == 'blocked'
assert len(result['observations']) == 2
@@ -0,0 +1,189 @@
"""
backend/tests/test_shipping_order_schema_runtime_audit.py
用途:验证订单 Schema 版本使用统计、解析审计详情和历史版本复制草稿。
依赖:订单 Schema service、动态订单审计模型、Flask 管理 API。
逻辑:直接构造已锁定版本和解析裁决,断言历史展示只读取快照且管理员权限、分页和复制边界正确。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from app import db
from app.models import (
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldObservation,
ShippingOrderFieldValue,
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice.order_schema import service
from tests.conftest import parse_api_data, parse_api_error
def _headers(username: str, role: str) -> dict[str, str]:
"""构造管理 API 使用的测试身份 Header。"""
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
def _config(field_id: str, *, name: str = '采购订单号') -> dict:
"""构造可发布的 Header 文本字段版本规则。"""
return {
'field_id': field_id,
'display_name': name,
'required': True,
'aliases': ['PO'],
'normalizer_key': 'trim',
'validator_keys': ['non_empty'],
'enum_options': [],
'evidence_policy': {
'required': True,
'source_precedence': ['attachment_text'],
'conflict_policy': 'block',
'allow_single_source': True,
},
'relation_role': None,
'comparator_key': 'normalized_text',
'extraction_instruction': '读取采购订单号',
}
def _publish(field_id: str, *, name: str, source_version_id: int | None = None) -> dict:
"""创建、保存并发布版本,返回不可变版本快照。"""
draft = service.create_draft(
{'copy_from_version_id': source_version_id} if source_version_id else {}, actor_id=1,
)
saved = service.save_draft(draft['id'], {
'fields': [_config(field_id, name=name)], 'expected_lock_version': draft['lock_version'],
}, actor_id=1)
return service.publish(draft['id'], actor_id=1, expected_lock_version=saved['lock_version'])
def _persist_extraction(version: dict, field_id: str, *, status: str) -> int:
"""构造一条带 Observation/Decision/Value 的已锁定运行审计记录。"""
extraction = ShippingOrderExtraction(
schema_version_id=version['id'], input_snapshot_hash=f"{'a' if status == 'accepted' else 'b' * 64}",
input_snapshot_json={'snapshot_hash': 'a' * 64, 'documents': [{'id': 101, 'extracted_text': 'PO-001'}]},
status=status,
raw_llm_output_json={'header_fields': [{'field_id': field_id, 'value': 'PO-001'}]},
normalized_result_json={'header': {'po_number': 'PO-001'}, 'lines': []},
validation_result_json={'blocked_fields': [] if status == 'accepted' else ['po_number']},
created_at=datetime.utcnow() - timedelta(minutes=1 if status == 'accepted' else 0),
)
db.session.add(extraction)
db.session.flush()
observation = ShippingOrderFieldObservation(
extraction_id=extraction.id, field_id=field_id, source_type='attachment_text',
extractor='dify_dynamic_schema', raw_value_json='PO-001', normalized_value_json='PO-001',
evidence_quote='PO-001', confidence='0.9000', evidence_verified=True,
)
db.session.add(observation)
db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, field_id=field_id, decision_status='accepted',
selected_observation_id=observation.id, supporting_observation_ids_json=[observation.id],
resolved_value_json='PO-001',
)
db.session.add(decision)
db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, field_id=field_id, decision_id=decision.id, value_text='PO-001',
value_json='PO-001',
))
db.session.commit()
return int(extraction.id)
def test_version_usage_and_runtime_audit_read_locked_snapshots(app, client):
"""使用统计只聚合目标版本,解析详情保留输入、LLM、裁决、证据和冻结字段名称。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
db.session.add_all([
User(id=1, username='schema-audit-admin', email='schema-audit-admin@example.com', role='admin', status='active'),
User(id=2, username='schema-audit-user', email='schema-audit-user@example.com', role='user', status='active'),
])
db.session.commit()
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=1)
field = service.save_field({'field_code': 'po_number', 'scope': 'header', 'value_type': 'string'}, actor_id=1)
first = _publish(field['id'], name='采购订单号')
second = _publish(field['id'], name='客户订单号', source_version_id=first['id'])
extraction_id = _persist_extraction(first, field['id'], status='accepted')
_persist_extraction(second, field['id'], status='needs_review')
service.save_field({
'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string',
}, actor_id=1, field_id=field['id'])
forbidden_usage = client.get(
f"/api/admin/shipping-order-schema/versions/{first['id']}/usage", headers=_headers('schema-audit-user', 'user'),
)
assert forbidden_usage.status_code == 403
assert parse_api_error(forbidden_usage.get_json())['code'] == 'AUTH.FORBIDDEN'
usage_response = client.get(
f"/api/admin/shipping-order-schema/versions/{first['id']}/usage?page=1&page_size=1",
headers=_headers('schema-audit-admin', 'admin'),
)
assert usage_response.status_code == 200
usage = parse_api_data(usage_response.get_json())
assert usage['summary']['total'] == 1
assert usage['summary']['status_counts'] == {'accepted': 1}
assert usage['page'] == 1 and usage['page_size'] == 1 and usage['items'][0]['id'] == extraction_id
forbidden_audit = client.get(
f"/api/admin/shipping-order-schema/order-extractions/{extraction_id}", headers=_headers('schema-audit-user', 'user'),
)
assert forbidden_audit.status_code == 403
audit_response = client.get(
f"/api/admin/shipping-order-schema/order-extractions/{extraction_id}", headers=_headers('schema-audit-admin', 'admin'),
)
assert audit_response.status_code == 200
audit = parse_api_data(audit_response.get_json())
assert audit['schema_version']['id'] == first['id']
assert audit['input_snapshot']['documents'][0]['extracted_text'] == 'PO-001'
assert audit['input_snapshot']['snapshot_available'] is True
assert audit['raw_llm_output']['header_fields'][0]['value'] == 'PO-001'
assert audit['observations'][0]['evidence_quote'] == 'PO-001'
assert audit['decisions'][0]['decision_status'] == 'accepted'
assert audit['field_values'][0]['value'] == 'PO-001'
assert audit['decisions'][0]['field_code'] == 'po_number'
def test_only_immutable_version_can_be_copied_to_new_draft(app):
"""历史发布/退役版本可复制为独立草稿,草稿不能作为草稿来源以避免链式可变引用。"""
with app.app_context():
db.session.add(User(id=1, username='schema-copy-admin', email='schema-copy-admin@example.com', role='admin', status='active'))
db.session.commit()
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=1)
field = service.save_field({'field_code': 'po_number', 'scope': 'header', 'value_type': 'string'}, actor_id=1)
published = _publish(field['id'], name='采购订单号')
copied = service.create_draft({'copy_from_version_id': published['id'], 'change_note': '回溯复制'}, actor_id=1)
assert copied['status'] == 'draft'
assert copied['source_version_id'] == published['id']
assert copied['definition']['fields'][0]['display_name'] == '采购订单号'
service.delete_draft(copied['id'], actor_id=1)
open_draft = service.create_draft({}, actor_id=1)
try:
service.create_draft({'copy_from_version_id': open_draft['id']}, actor_id=1)
except Exception as exc:
assert getattr(exc, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
else:
raise AssertionError('Draft versions must not be valid copy sources')
service.delete_draft(open_draft['id'], actor_id=1)
try:
service.create_draft({'copy_from_version_id': 'not-a-version'}, actor_id=1)
except Exception as exc:
assert getattr(exc, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
else:
raise AssertionError('Malformed copy sources must be rejected instead of creating a blank draft')
try:
service.create_draft({'copy_from_version_id': 999999}, actor_id=1)
except Exception as exc:
assert getattr(exc, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
else:
raise AssertionError('Unknown copy sources must be rejected instead of creating a blank draft')
@@ -0,0 +1,49 @@
"""验证订单解析运行审计快照与版本使用索引迁移可往返执行。"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def _load_migration():
"""从文件加载阶段四迁移模块。"""
path = Path(__file__).parents[1] / 'migrations' / 'versions' / 'f99e4f5a6b7c_add_shipping_order_extraction_audit_snapshot.py'
spec = importlib.util.spec_from_file_location('shipping_order_schema_runtime_audit_migration', path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_runtime_audit_migration_round_trip():
"""迁移新增输入快照列和复合索引,降级必须完整移除二者。"""
engine = sa.create_engine('sqlite:///:memory:')
with engine.begin() as connection:
sa.MetaData().create_all(connection)
metadata = sa.MetaData()
sa.Table(
'shipping_order_extractions', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('schema_version_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
)
metadata.create_all(connection)
migration = _load_migration()
migration.op = Operations(MigrationContext.configure(connection))
migration.upgrade()
inspector = sa.inspect(connection)
assert 'input_snapshot_json' in {item['name'] for item in inspector.get_columns('shipping_order_extractions')}
assert 'ix_shipping_order_extractions_schema_version_created' in {
item['name'] for item in inspector.get_indexes('shipping_order_extractions')
}
migration.downgrade()
inspector = sa.inspect(connection)
assert 'input_snapshot_json' not in {item['name'] for item in inspector.get_columns('shipping_order_extractions')}
assert 'ix_shipping_order_extractions_schema_version_created' not in {
item['name'] for item in inspector.get_indexes('shipping_order_extractions')
}
@@ -0,0 +1,97 @@
"""
backend/tests/test_shipping_order_schema_version_governance_migration.py
用途:验证订单 Schema 单一版本定义与审计事件迁移在 SQLite 可往返执行。
依赖:Alembic Operations、SQLAlchemy 内存数据库、阶段一版本治理迁移。
逻辑:构造旧版草稿/发布版本及字段关联行;升级后仅保留发布版本并建立审计结构,回滚后恢复旧关联表。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def _load_migration():
"""从文件加载单一版本定义迁移模块。"""
path = Path(__file__).parents[1] / 'migrations' / 'versions' / 'f96b1c2d3e4f_unify_shipping_order_schema_versions.py'
spec = importlib.util.spec_from_file_location('shipping_order_schema_version_governance_migration', path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _create_baseline(connection) -> None:
"""创建迁移前所需最小表和一条草稿/发布版本数据。"""
metadata = sa.MetaData()
users = sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
schemas = sa.Table('shipping_order_schemas', metadata, sa.Column('id', sa.Integer(), primary_key=True))
versions = sa.Table(
'shipping_order_schema_versions', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id'), nullable=False),
sa.Column('status', sa.String(16), nullable=False),
)
fields = sa.Table('shipping_order_fields', metadata, sa.Column('id', sa.String(36), primary_key=True))
version_fields = sa.Table(
'shipping_order_schema_version_fields', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('schema_version_id', sa.Integer(), sa.ForeignKey('shipping_order_schema_versions.id'), nullable=False),
sa.Column('field_id', sa.String(36), sa.ForeignKey('shipping_order_fields.id'), nullable=False),
)
metadata.create_all(connection)
connection.execute(users.insert(), [{'id': 1}])
connection.execute(schemas.insert(), [{'id': 1}])
connection.execute(versions.insert(), [
{'id': 1, 'schema_id': 1, 'status': 'draft'},
{'id': 2, 'schema_id': 1, 'status': 'published'},
])
connection.execute(fields.insert(), [{'id': 'field-1'}])
connection.execute(version_fields.insert(), [
{'id': 1, 'schema_version_id': 1, 'field_id': 'field-1'},
{'id': 2, 'schema_version_id': 2, 'field_id': 'field-1'},
])
def _table_names(connection) -> set[str]:
"""返回连接中当前可见的表集合。"""
return set(sa.inspect(connection).get_table_names())
def _columns(connection, table_name: str) -> set[str]:
"""返回指定表的列名集合。"""
return {item['name'] for item in sa.inspect(connection).get_columns(table_name)}
def test_shipping_order_schema_version_governance_migration_round_trip():
"""升级清理旧草稿子记录并建立审计表,回滚恢复旧版本字段表。"""
engine = sa.create_engine('sqlite:///:memory:')
with engine.begin() as connection:
_create_baseline(connection)
migration = _load_migration()
migration.op = Operations(MigrationContext.configure(connection))
migration.upgrade()
assert 'shipping_order_schema_version_fields' not in _table_names(connection)
assert 'shipping_order_schema_audit_events' in _table_names(connection)
assert {'lock_version', 'source_version_id', 'retired_at'}.issubset(
_columns(connection, 'shipping_order_schema_versions')
)
assert connection.execute(sa.text(
'SELECT COUNT(*) FROM shipping_order_schema_versions WHERE status = \'draft\''
)).scalar_one() == 0
assert connection.execute(sa.text(
'SELECT COUNT(*) FROM shipping_order_schema_versions WHERE status = \'published\''
)).scalar_one() == 1
migration.downgrade()
assert 'shipping_order_schema_version_fields' in _table_names(connection)
assert 'shipping_order_schema_audit_events' not in _table_names(connection)
assert not {'lock_version', 'source_version_id', 'retired_at'} & _columns(
connection, 'shipping_order_schema_versions'
)
@@ -0,0 +1,78 @@
"""
用途:隔离验证库存解析 Profile 与发货模板/Artifact 迁移可连续 upgrade/downgrade。
依赖:Alembic Operations、SQLAlchemy SQLite、阶段四和阶段五迁移模块。
逻辑:创建真实前序所需最小表,连续执行两阶段迁移并逆序回滚,检查表、列和索引生命周期。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def _load(filename: str, module_name: str):
"""加载数字开头的迁移模块。"""
path = Path(__file__).parents[1] / 'migrations' / 'versions' / filename
spec = importlib.util.spec_from_file_location(module_name, path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _baseline(connection) -> None:
"""创建两个迁移引用的最小前序表及外键目标。"""
metadata = sa.MetaData()
for name in (
'users', 'shipping_tasks', 'shipping_batches', 'shipping_order_schema_versions',
'shipping_order_extractions', 'shipping_inventory_files',
):
sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'shipping_inventory_sources', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('source_code', sa.String(64), nullable=False),
sa.Column('enabled', sa.Boolean(), nullable=False, server_default=sa.true()),
)
metadata.create_all(connection)
def _columns(connection, table: str) -> set[str]:
return {item['name'] for item in sa.inspect(connection).get_columns(table)}
def test_inventory_profile_and_excel_template_migrations_round_trip():
"""阶段四、五迁移必须可连续升级并逆序完整回滚。"""
engine = sa.create_engine('sqlite:///:memory:')
with engine.begin() as connection:
_baseline(connection)
context = MigrationContext.configure(connection)
operations = Operations(context)
parsing = _load('b17e3d4c5a60_inventory_parsing_profiles.py', 'inventory_parsing_profile_migration')
excel = _load('c27e3d4c5a61_shipping_excel_templates.py', 'shipping_excel_template_migration')
parsing.op = operations
excel.op = operations
parsing.upgrade()
assert 'shipping_inventory_parsing_profiles' in sa.inspect(connection).get_table_names()
assert 'parsing_profile_id' in _columns(connection, 'shipping_inventory_sources')
excel.upgrade()
tables = set(sa.inspect(connection).get_table_names())
assert {'shipping_excel_templates', 'shipping_export_artifacts'}.issubset(tables)
assert 'excel_template_id' in _columns(connection, 'shipping_inventory_sources')
excel.downgrade()
tables = set(sa.inspect(connection).get_table_names())
assert 'shipping_excel_templates' not in tables
assert 'shipping_export_artifacts' not in tables
assert 'excel_template_id' not in _columns(connection, 'shipping_inventory_sources')
assert 'parsing_profile_id' in _columns(connection, 'shipping_inventory_sources')
parsing.downgrade()
assert 'shipping_inventory_parsing_profiles' not in sa.inspect(connection).get_table_names()
assert 'parsing_profile_id' not in _columns(connection, 'shipping_inventory_sources')
@@ -0,0 +1,371 @@
"""
tests/test_temporary_inventory_session.py
用途:验证对话库存候选会话的身份隔离、通用表格结构门禁和生产链路隔离。
依赖:临时库存会话服务、FileAsset、ChatSession、openpyxl。
逻辑:用户明确声明库存文件后只做结构门禁;覆盖同一资产幂等、跨会话不可读和能力映射确认。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from io import BytesIO
from pathlib import Path
import pytest
from openpyxl import Workbook
from app import db
from app.core.errors import NotFoundError
from app.models import (
Agent,
ChatSession,
FileAsset,
ShippingInventoryFile,
ShippingInventoryField,
ShippingTaskInventoryLink,
ShippingTemporaryInventorySession,
User,
)
from app.services.agent_runtime_context.builder import build_agent_runtime_context
from app.services.shipping_notice.inventory_temporary_session import (
create_temporary_inventory_session,
confirm_temporary_inventory_use,
create_parsing_profile_draft_from_temporary_session,
get_temporary_inventory_session,
submit_temporary_inventory_mapping_suggestion,
)
def _xlsx_bytes(headers: list[str], row: list[object]) -> bytes:
"""生成最小 Excel 文件,覆盖后端结构分析而不依赖真实库存数据。"""
stream = BytesIO()
workbook = Workbook()
worksheet = workbook.active
worksheet.append(headers)
worksheet.append(row)
workbook.save(stream)
workbook.close()
return stream.getvalue()
def _seed_context(*, suffix: str = 'owner') -> tuple[User, User, ChatSession, Agent, FileAsset]:
"""创建两个用户、货代 Agent、会话和私有文件资产,供访问隔离断言使用。"""
owner = User(username=f'temp-{suffix}', email=f'temp-{suffix}@example.com', role='user', status='active')
other = User(username=f'temp-other-{suffix}', email=f'temp-other-{suffix}@example.com', role='user', status='active')
agent = Agent(name=f'Temporary Inventory {suffix}', agent_code='shipping_notice', runtime_provider='dify')
db.session.add_all([owner, other, agent])
db.session.flush()
chat_session = ChatSession(session_id=f'chat-temp-{suffix}', user_id=owner.id, agent_id=agent.id, title='temporary')
asset = FileAsset(
asset_no=f'FAS-TEMP-{suffix}'.upper(), owner_user_id=owner.id, original_filename='inventory.xlsx',
storage_provider='minio', storage_bucket='test', storage_key=f'temporary/{suffix}/inventory.xlsx',
content_hash='a' * 64, file_size=10, extension='xlsx', upload_status='ready',
lifecycle_status='temporary', reference_count=0, expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add_all([chat_session, asset])
db.session.commit()
return owner, other, chat_session, agent, asset
def _runtime_context(session: ChatSession) -> dict:
"""构造与聊天入口一致的可信 runtime context,不伪造用户身份字段。"""
return build_agent_runtime_context(
agent_code='shipping_notice', scope='chat_turn', session_id=session.session_id,
refs={'capability': 'temporary_inventory'},
)
def test_inventory_candidate_is_idempotent_and_never_creates_production_snapshot(app, monkeypatch, tmp_path):
"""同一会话同一资产复用临时结果,且不创建生产库存文件或任务链接。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
_owner, _other, chat_session, _agent, asset = _seed_context(suffix='candidate')
content = _xlsx_bytes(['Supplier Sku', 'Qty Available', 'Reservation ID'], ['PN-1', 9, 'RES-1'])
monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content)
first = create_temporary_inventory_session({
'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no,
})
second = create_temporary_inventory_session({
'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no,
})
# 关键断言:初检只保存临时结构审计,绝不写入正式库存快照或任务库存关联。
assert first['status'] == 'awaiting_mapping_suggestion'
assert first['session_no'] == second['session_no']
# 字段目录未与来源表头同名时不生成正式映射建议;分类只证明该文件具备库存最低特征。
assert first['analysis']['suggested_mapping'] == {}
assert first['file_classification_status'] == 'inventory_candidate'
assert 'sample_values' not in first['analysis']['structure']['selected_columns'][0]
assert ShippingTemporaryInventorySession.query.count() == 1
assert ShippingInventoryFile.query.count() == 0
assert ShippingTaskInventoryLink.query.count() == 0
def test_legacy_xls_enters_temporary_analysis_without_format_rejection(app, monkeypatch, tmp_path):
"""对话临时库存必须直接分析旧 xls,不要求用户先转换为 xlsx 或 csv。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
template = Path(__file__).resolve().parents[1] / 'templates' / 'maintenance_record_history_template.xls'
with app.app_context():
_owner, _other, chat_session, _agent, asset = _seed_context(suffix='legacy-xls')
asset.original_filename = 'legacy-inventory.xls'
asset.extension = 'xls'
asset.storage_key = 'temporary/legacy-xls/legacy-inventory.xls'
content = template.read_bytes()
asset.file_size = len(content)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.inventory_temporary_session.read_asset_bytes',
lambda item: content,
)
result = create_temporary_inventory_session({
'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no,
})
# 关键断言:xls 已进入真实结构分析;是否属于库存仍由字段特征决定。
assert result['analysis']['file_format'] == 'xls'
assert result['file_classification_status'] in {'inventory_candidate', 'not_inventory'}
assert ShippingInventoryFile.query.count() == 0
assert ShippingTaskInventoryLink.query.count() == 0
def test_user_declared_inventory_with_custom_headers_enters_mapping_candidate(app, monkeypatch, tmp_path):
"""任意业务表头只要结构有效即可进入候选,后端不得依赖固定库存字段词典拒绝。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
_owner, _other, chat_session, _agent, asset = _seed_context(suffix='noninventory')
content = _xlsx_bytes(['PO Number', 'Customer', 'Unit Price'], ['PO-1', 'Customer A', 100])
monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content)
result = create_temporary_inventory_session({
'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no,
})
assert result['status'] == 'awaiting_mapping_suggestion'
assert result['file_classification_status'] == 'inventory_candidate'
assert ShippingInventoryFile.query.count() == 0
assert ShippingTaskInventoryLink.query.count() == 0
def test_table_without_data_rows_is_rejected(app, monkeypatch, tmp_path):
"""只有表头而没有数据行的文件不能进入字段候选确认。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
_owner, _other, chat_session, _agent, asset = _seed_context(suffix='empty-table')
content = _xlsx_bytes(['物料', '可承诺数'], ['', ''])
monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content)
result = create_temporary_inventory_session({
'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no,
})
assert result['status'] == 'rejected'
assert result['file_classification_status'] == 'not_inventory'
def test_temporary_session_cannot_be_read_from_another_chat_session(app, monkeypatch, tmp_path):
"""临时会话必须同时绑定用户与聊天会话,避免猜中编号后跨会话读取。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
owner, other, chat_session, agent, asset = _seed_context(suffix='isolation')
content = _xlsx_bytes(['Supplier Sku', 'Qty Available'], ['PN-1', 9])
monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content)
created = create_temporary_inventory_session({
'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no,
})
other_session = ChatSession(session_id='chat-temp-other-isolation', user_id=other.id, agent_id=agent.id, title='other')
db.session.add(other_session)
db.session.commit()
with pytest.raises(NotFoundError) as exc_info:
get_temporary_inventory_session({
'agent_runtime_context': _runtime_context(other_session),
'temporary_session_no': created['session_no'],
})
assert exc_info.value.code == 'SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND'
def test_mapping_suggestion_only_accepts_catalog_fields_and_real_headers(app, monkeypatch, tmp_path):
"""Dify 映射建议只能引用返回的字段目录和真实表头,且保存后仍不是正式库存。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
_owner, _other, chat_session, _agent, asset = _seed_context(suffix='mapping')
content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9])
monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content)
context = _runtime_context(chat_session)
created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no})
field_ids = {
item.field_code: str(item.id)
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
).all()
}
saved = submit_temporary_inventory_mapping_suggestion({
'agent_runtime_context': context,
'temporary_session_no': created['session_no'],
'field_mapping': {
field_ids['part_number']: 'Supplier Sku',
field_ids['reservation_id']: 'Reservation ID',
field_ids['available_qty']: 'Qty Available',
},
})
assert saved['status'] == 'awaiting_mapping_confirmation'
assert saved['mapping_suggestion']['origin'] == 'dify_candidate'
assert ShippingInventoryFile.query.count() == 0
assert ShippingTaskInventoryLink.query.count() == 0
def test_mapping_confirmation_session_is_idempotent_for_the_same_asset(app, monkeypatch, tmp_path):
"""映射建议已保存时重试创建必须复用会话,避免产生多条待确认记录。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
_owner, _other, chat_session, _agent, asset = _seed_context(suffix='mapping-idempotent')
content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9])
monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content)
context = _runtime_context(chat_session)
created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no})
field_ids = {
item.field_code: str(item.id)
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
).all()
}
submit_temporary_inventory_mapping_suggestion({
'agent_runtime_context': context, 'temporary_session_no': created['session_no'],
'field_mapping': {
field_ids['part_number']: 'Supplier Sku',
field_ids['reservation_id']: 'Reservation ID',
field_ids['available_qty']: 'Qty Available',
},
})
retried = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no})
assert retried['session_no'] == created['session_no']
assert retried['status'] == 'awaiting_mapping_confirmation'
assert ShippingTemporaryInventorySession.query.count() == 1
def test_confirmed_temporary_use_passes_quality_without_creating_production_inventory(app, monkeypatch, tmp_path):
"""用户确认后只锁定临时质量审计,不能写入正式快照、任务关联或库存行投影。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
_owner, _other, chat_session, _agent, asset = _seed_context(suffix='confirm')
content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9])
monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content)
context = _runtime_context(chat_session)
created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no})
field_ids = {
item.field_code: str(item.id)
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
).all()
}
submit_temporary_inventory_mapping_suggestion({
'agent_runtime_context': context, 'temporary_session_no': created['session_no'],
'field_mapping': {
field_ids['part_number']: 'Supplier Sku',
field_ids['reservation_id']: 'Reservation ID',
field_ids['available_qty']: 'Qty Available',
},
})
confirmed = confirm_temporary_inventory_use({
'agent_runtime_context': context, 'temporary_session_no': created['session_no'],
})
assert confirmed['status'] == 'confirmed_for_temporary_use'
assert confirmed['confirmed_usage']['usage_scope'] == 'conversation'
assert 'task_no' not in confirmed['confirmed_usage']
assert confirmed['confirmed_usage']['quality']['passed'] is True
assert confirmed['confirmed_usage']['quality']['valid_line_count'] == 1
assert ShippingInventoryFile.query.count() == 0
assert ShippingTaskInventoryLink.query.count() == 0
def test_temporary_confirmation_ignores_task_anchor_and_never_links_inventory(app, monkeypatch, tmp_path):
"""临时库存确认即使收到 task_no 也保持对话隔离,不能形成任务语义或任务关联。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
_owner, _other, chat_session, _agent, asset = _seed_context(suffix='ignore-task')
content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9])
monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content)
context = _runtime_context(chat_session)
created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no})
field_ids = {
item.field_code: str(item.id)
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
).all()
}
submit_temporary_inventory_mapping_suggestion({
'agent_runtime_context': context, 'temporary_session_no': created['session_no'],
'field_mapping': {
field_ids['part_number']: 'Supplier Sku',
field_ids['reservation_id']: 'Reservation ID',
field_ids['available_qty']: 'Qty Available',
},
})
confirmed = confirm_temporary_inventory_use({
'agent_runtime_context': context,
'temporary_session_no': created['session_no'],
'task_no': 'SN-SHOULD-NOT-BIND',
})
row = ShippingTemporaryInventorySession.query.filter_by(session_no=created['session_no']).one()
assert confirmed['confirmed_usage']['usage_scope'] == 'conversation'
assert 'task_no' not in confirmed['confirmed_usage']
assert row.task_id is None
assert ShippingInventoryFile.query.count() == 0
assert ShippingTaskInventoryLink.query.count() == 0
def test_confirmed_session_promotes_only_to_parsing_profile_draft(app, monkeypatch, tmp_path):
"""管理员沉淀必须复用临时会话锁定映射,且结果只能是未发布解析方案草稿。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
owner, _other, chat_session, _agent, asset = _seed_context(suffix='promote')
content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9])
monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content)
context = _runtime_context(chat_session)
created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no})
field_ids = {
item.field_code: str(item.id)
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
).all()
}
submit_temporary_inventory_mapping_suggestion({
'agent_runtime_context': context, 'temporary_session_no': created['session_no'],
'field_mapping': {
field_ids['part_number']: 'Supplier Sku',
field_ids['reservation_id']: 'Reservation ID',
field_ids['available_qty']: 'Qty Available',
},
})
confirm_temporary_inventory_use({'agent_runtime_context': context, 'temporary_session_no': created['session_no']})
from app.services.shipping_notice.order_schema import service as order_schema_service
# 匹配键必须引用当前订单字段 Schema 中的稳定字段身份。
order_schema_service.initialize_schema({'display_name': '临时库存测试字段'}, actor_id=owner.id)
order_field = order_schema_service.save_field({
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=owner.id)
draft = create_parsing_profile_draft_from_temporary_session(created['session_no'], {
'profile_code': 'TEMP_CONVERSATION', 'display_name': '对话库存草稿',
'match_keys': [{'order_field_id': order_field['id'], 'inventory_field_id': field_ids['part_number']}],
'field_mapping': {'forged': 'Forged Header'},
}, actor_id=owner.id)
assert draft['status'] == 'draft'
assert draft['definition']['field_mapping'][field_ids['part_number']] == 'Supplier Sku'
assert 'forged' not in draft['definition']['field_mapping']
assert ShippingInventoryFile.query.count() == 0
assert ShippingTaskInventoryLink.query.count() == 0