Files
syops/backend/tests/test_shipping_onhand_configuration.py
T
hugoandCursor 39fe3c05f2 feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 10:46:06 +08:00

435 lines
22 KiB
Python

"""
tests/test_shipping_inventory_configuration.py
用途:验证库存源主数据、外部系统映射约束和 RPA 凭据加密的阶段一契约。
依赖:Flask app/db、库存配置模型、freight_rpa.common.credential_crypto、onhand_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, FreightRpaOnhandExternalMapping, FreightRpaOnhandReportFile,
FreightRpaOnhandField, FreightRpaOnhandReportConfig, FreightRpaParsingProfile, FreightRpaSource,
ShippingCustomer, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingOrderTask, FreightRpaProfile,
)
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source
from app.services.shipping_notice.onhand_external_mapping import resolve_external_warehouse
from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import seed_task_inventory_source
def _profile(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> FreightRpaProfile:
"""构造最小可持久化 RPA Profile,避免测试包含明文真实凭据。"""
return FreightRpaProfile(
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: FreightRpaProfile, *, code: str = 'DBS_DUB', mode: str = 'fixed') -> FreightRpaSource:
"""构造固定或动态 Warehouse 的库存源,供约束测试复用。"""
parsing = FreightRpaParsingProfile(
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,
)
source = FreightRpaSource(
source_code=code,
display_name=code,
connector_type=profile.connector_type,
rpa_profile=profile,
excel_template=template,
warehouse_resolution_mode=mode,
fixed_warehouse_id='DUB' if mode == 'fixed' else None,
)
# s18 起解析方案绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行;
# 经关系级联随站点一并入库,调用方只需 add(source)。
FreightRpaOnhandReportConfig(
source=source, parsing_profile=parsing,
report_path_json={}, query_parameters_json=[],
)
return source
def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
"""为动态仓库存解析测试构造已接受 FieldValue,禁止通过固定任务行投影绕过履约门禁。"""
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
if version is None:
order_schema_service.initialize_schema({'display_name': '库存动态仓测试订单'}, actor_id=None)
fields = {
code: order_schema_service.save_field(
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
)
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
}
draft = order_schema_service.create_draft({}, actor_id=None)
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
saved = order_schema_service.save_draft(draft['id'], {
'fields': [{
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
} for code, field in fields.items()],
'expected_lock_version': draft['lock_version'],
}, actor_id=None)
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
field_ids = {
str(item['field_code']): str(item['field_id'])
for item in (version.definition_json or {}).get('fields') or []
}
owner = task
extraction = ShippingOrderExtraction(
task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
db.session.add(line)
db.session.flush()
for code, value in {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}.items():
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
supporting_observation_ids_json=[], resolved_value_json=value,
)
db.session.add(decision)
db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
value_json=value,
))
owner.current_order_extraction_id = extraction.id
db.session.flush()
def _confirm_direct_rpa_task_customer(task: ShippingOrderTask) -> None:
"""为直接构造的库存任务补齐已确认客户,避免绕过客户身份门禁。"""
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name='库存动态仓测试客户', short_code='RPC', status='active',
)
db.session.add(customer)
db.session.flush()
from tests.conftest import confirm_test_customer_resolution
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
task._test_customer_confirmed = True
def test_encrypt_credential_round_trip_requires_runtime_key(app):
"""凭据必须依赖环境主密钥加密,且可在受控运行时回读。"""
app.config['FREIGHT_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['FREIGHT_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.ONHAND_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 = FreightRpaOnhandExternalMapping(
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)
# s18 起报表路径/查询条件写在站点的 onhand_report_config 配置行上。
source.onhand_report_config.report_path_json = {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'Source Report',
}
source.onhand_report_config.query_parameters_json = [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
]
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 '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 = FreightRpaOnhandExternalMapping(
source=source, freight_warehouse_id='FRA', external_system_code='TOPGP',
external_warehouse_code='FRA01', external_warehouse_name='Frankfurt',
)
fallback = FreightRpaOnhandExternalMapping(
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.onhand_snapshot_store import link_snapshot_to_task
with app.app_context():
base_source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
crane_profile = FreightRpaProfile(
profile_code='CRANE_DYNAMIC_PN', display_name='Crane Dynamic PN',
connector_type='crane', login_url='https://test.invalid/crane',
login_config_json={'auth_mode': 'password'},
)
# s18 起解析方案绑定挂在 base_source 的 onhand_report_config 配置行上。
base_profile = base_source.onhand_report_config.parsing_profile
crane_source = FreightRpaSource(
source_code='CRANE', display_name='Crane', connector_type='crane',
rpa_profile=crane_profile,
excel_template=base_source.excel_template,
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
enabled=True,
)
# Crane 站点复用同一解析方案;报表路径/查询条件归配置行且 Crane 恒为空。
FreightRpaOnhandReportConfig(
source=crane_source, parsing_profile=base_profile,
report_path_json={}, query_parameters_json=[],
)
task = ShippingOrderTask(
task_no='OT-DYNAMIC-WH', user_id=1, source_type='direct_pdf', status='ready',
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
_confirm_direct_rpa_task_customer(task)
db.session.add_all([crane_profile, crane_source])
db.session.flush()
seed_task_inventory_source(task, source_code='CRANE')
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
schema_fields = (order_snapshot.schema_version.definition_json or {}).get('fields') or []
order_field_ids = {
str(item.get('field_code') or ''): str(item.get('field_id') or '')
for item in schema_fields
}
definition = dict(base_profile.definition_json or {})
definition['match_keys'] = [
{'order_field_id': order_field_ids['part_number'], 'inventory_field_id': definition['match_keys'][0]['inventory_field_id']},
{'order_field_id': order_field_ids['reservation_id'], 'inventory_field_id': definition['match_keys'][1]['inventory_field_id']},
]
base_profile.definition_json = definition
db.session.commit()
inventory_fields = {item.field_code: str(item.id) for item in FreightRpaOnhandField.query.all()}
path = tmp_path / 'dynamic.xlsx'
path.write_bytes(b'not-parsed-in-this-test')
snapshot = FreightRpaOnhandReportFile(
onhand_file_no='SIF-DYNAMIC-WH', storage_path=str(path), snapshot_status='ready',
source_code='CRANE', warehouse_id=None, share_mode='warehouse_pool',
onhand_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(snapshot)
db.session.commit()
link = link_snapshot_to_task(task, snapshot, reason='dynamic_test')
assert link is not None
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.onhand_snapshot_store import link_snapshot_to_task
with app.app_context():
base_source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
crane_profile = FreightRpaProfile(
profile_code='CRANE_AMBIG_PROFILE', display_name='Crane Ambiguous Profile',
connector_type='crane', login_url='https://test.invalid/crane',
login_config_json={'auth_mode': 'password'},
)
# s18 起解析方案绑定挂在 base_source 的 onhand_report_config 配置行上。
base_profile = base_source.onhand_report_config.parsing_profile
crane_source = FreightRpaSource(
source_code='CRANE_AMBIG', display_name='Crane Ambiguous', connector_type='crane',
rpa_profile=crane_profile,
excel_template=base_source.excel_template,
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
enabled=True,
)
# Crane 站点复用同一解析方案;报表路径/查询条件归配置行且 Crane 恒为空。
FreightRpaOnhandReportConfig(
source=crane_source, parsing_profile=base_profile,
report_path_json={}, query_parameters_json=[],
)
task = ShippingOrderTask(
task_no='OT-DYNAMIC-AMBIG', user_id=1, source_type='direct_pdf', status='ready',
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
_confirm_direct_rpa_task_customer(task)
db.session.add_all([crane_profile, crane_source])
db.session.flush()
seed_task_inventory_source(task, source_code='CRANE_AMBIG')
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
schema_fields = (order_snapshot.schema_version.definition_json or {}).get('fields') or []
order_field_ids = {
str(item.get('field_code') or ''): str(item.get('field_id') or '')
for item in schema_fields
}
definition = dict(base_profile.definition_json or {})
definition['match_keys'] = [
{'order_field_id': order_field_ids['part_number'], 'inventory_field_id': definition['match_keys'][0]['inventory_field_id']},
{'order_field_id': order_field_ids['reservation_id'], 'inventory_field_id': definition['match_keys'][1]['inventory_field_id']},
]
base_profile.definition_json = definition
db.session.commit()
inventory_fields = {item.field_code: str(item.id) for item in FreightRpaOnhandField.query.all()}
path = tmp_path / 'ambiguous.xlsx'
path.write_bytes(b'not-parsed-in-this-test')
snapshot = FreightRpaOnhandReportFile(
onhand_file_no='SIF-DYNAMIC-AMBIG', storage_path=str(path), snapshot_status='ready',
source_code='CRANE_AMBIG', warehouse_id=None, share_mode='warehouse_pool',
onhand_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']: 'A001', inventory_fields['reservation_id']: 'R-1',
inventory_fields['warehouse_id']: 'SIN', inventory_fields['available_qty']: 1,
},
],
)
db.session.add(snapshot)
db.session.commit()
assert link_snapshot_to_task(task, snapshot, reason='dynamic_test') is None
def test_dynamic_snapshot_is_idempotent_per_rpa_run(app, tmp_path):
"""同一 RPA run 的动态多仓文件只能入库一次,避免回调重放产生重复快照。"""
with app.app_context():
first = FreightRpaOnhandReportFile(
onhand_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 = FreightRpaOnhandReportFile(
onhand_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()