Files
syops/backend/tests/test_admin_shipping_inventory.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

211 lines
11 KiB
Python

"""
tests/test_admin_shipping_inventory.py
用途:验证货代 RPA 管理端只读快照/导出记录、配置目录与站点保存接口。
依赖:Flask 测试客户端、库存文件和排程运行模型。
逻辑:请求打到 /api/admin/freight-rpa/;快照来自在手文件,失败排程即使没有文件也出现在导出记录中。
"""
from __future__ import annotations
from datetime import datetime
from pathlib import Path
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, User
from app.models import FreightRpaSource, FreightRpaProfile
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 = FreightRpaOnhandReportFile(
onhand_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='freight-rpa-onhand',
)
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/freight-rpa/onhand/snapshots', '/api/admin/freight-rpa/onhand/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/freight-rpa/onhand/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/freight-rpa/onhand/snapshots/1/download', headers=_headers('inventory-admin', 'admin'))
assert downloaded.status_code == 200
assert downloaded.data == b'admin-snapshot'
exports = client.get('/api/admin/freight-rpa/onhand/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/freight-rpa/onhand/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/freight-rpa/onhand/routing-fields',
'/api/admin/freight-rpa/onhand/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 = FreightRpaProfile(
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/freight-rpa/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']
assert 'configuration_test' not in {item['code'] for item in source['activation']['checks']}
activation = client.post(
f"/api/admin/freight-rpa/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.ONHAND_SOURCE_ACTIVATION_BLOCKED'
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template']
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 = FreightRpaProfile(
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)
# s18 起站点行不再承载报表路径/查询条件;本用例只验证权限与空 envelope,无需配置行。
source = FreightRpaSource(
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',
enabled=False,
)
db.session.add(source)
db.session.commit()
source_id = source.id
forbidden = client.get(f'/api/admin/freight-rpa/sources/{source_id}/test-export/latest')
assert forbidden.status_code in {401, 403}
response = client.get(
f'/api/admin/freight-rpa/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