209 lines
10 KiB
Python
209 lines
10 KiB
Python
"""
|
|
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': [],
|
|
}
|
|
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']
|
|
|
|
|
|
def test_latest_inventory_configuration_test_is_admin_only(app, client):
|
|
"""最近测试状态仅允许管理员读取,且没有测试记录时仍返回标准空数据 envelope。"""
|
|
app.config['AUTH_JWT_REQUIRED'] = False
|
|
with app.app_context():
|
|
_create_users()
|
|
profile = ShippingRpaProfile(
|
|
profile_code='API_LATEST_TEST_LOGIN', display_name='Latest Test', connector_type='dbs',
|
|
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
|
|
)
|
|
db.session.add(profile)
|
|
source = ShippingInventorySource(
|
|
source_code='API_LATEST_TEST_SOURCE', display_name='Latest Test Source', connector_type='dbs',
|
|
rpa_profile=profile, 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=[], enabled=False,
|
|
)
|
|
db.session.add(source)
|
|
db.session.commit()
|
|
source_id = source.id
|
|
|
|
forbidden = client.get(f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest')
|
|
assert forbidden.status_code in {401, 403}
|
|
response = client.get(
|
|
f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest',
|
|
headers=_headers('inventory-admin', 'admin'),
|
|
)
|
|
assert response.status_code == 200
|
|
assert parse_api_data(response.get_json()) is None
|