- AGENTS.md §8.1 红线改写:env 命名空间恢复 FREIGHT_RPA_*,SHIPPING_NOTICE_RPA_* 一刀切废弃、不设兼容层
- 全仓机械前缀替换(70 文件)并删除兼容层;4 个既有基线测试失败一并清零(过期桩/存储隔离/排程 fail-fast 接线)
- 运行期数据目录统一 freight_rpa/{inventory,receipt,common}:settings 默认、4 个 env、2 个 ps1 三侧一致
- 代码目录 scripts/rpa 更名 scripts/freight_rpa 与数据根对齐;全仓路径引用同步,README 部署走查与升级小节
- 收料部署对齐库存:计划任务注册脚本(独立任务名)、可选 -SessionReuse 会话复用、DSV 老别名链移除
- readiness 加固:排程离线立即 failed(不挂 awaiting);无 Redis 时追加进程内存储原因码与本地测试指引
- DSV 会话准备遇 SSO 重定向中止时改走自动登录,首源不再因未登录判死
414 lines
21 KiB
Python
414 lines
21 KiB
Python
"""
|
|
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,
|
|
ShippingCustomer, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
|
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
|
|
ShippingOrderSnapshotLine, ShippingOrderTask, ShippingRpaProfile,
|
|
)
|
|
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
|
|
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') -> 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 _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.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},
|
|
]
|
|
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 = 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
|
|
|
|
with app.app_context():
|
|
base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
|
crane_profile = ShippingRpaProfile(
|
|
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'},
|
|
)
|
|
crane_source = ShippingInventorySource(
|
|
source_code='CRANE', display_name='Crane', connector_type='crane',
|
|
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
|
|
excel_template=base_source.excel_template,
|
|
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
|
|
report_path_json={}, query_parameters_json=[], enabled=True,
|
|
)
|
|
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_source.parsing_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_source.parsing_profile.definition_json = definition
|
|
db.session.commit()
|
|
|
|
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
|
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=None, 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(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.inventory_snapshot_store import link_snapshot_to_task
|
|
|
|
with app.app_context():
|
|
base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
|
crane_profile = ShippingRpaProfile(
|
|
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'},
|
|
)
|
|
crane_source = ShippingInventorySource(
|
|
source_code='CRANE_AMBIG', display_name='Crane Ambiguous', connector_type='crane',
|
|
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
|
|
excel_template=base_source.excel_template,
|
|
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
|
|
report_path_json={}, query_parameters_json=[], enabled=True,
|
|
)
|
|
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_source.parsing_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_source.parsing_profile.definition_json = definition
|
|
db.session.commit()
|
|
|
|
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
|
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=None, 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']: '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 = 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()
|