""" 收料报表配置管理接口测试。 用途:验证站点内独立收料配置的权限、DBS/Crane 规则及不可影响库存配置的边界。 依赖:Flask 管理 API、库存站点测试种子、货代统一审计事件。 逻辑:配置保存只更新 shipping_receipt_report_configs,并留存前后快照审计。 """ from __future__ import annotations from app.models import ShippingAuditEvent, ShippingInventorySource, User 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 _create_users() -> None: """创建管理员和普通接收人,验证收料配置不向业务用户开放。""" from app import db db.session.add_all([ User(username='receipt-admin', email='receipt-admin@example.com', role='admin', status='active'), User(username='receipt-user', email='receipt-user@example.com', role='user', status='active'), ]) db.session.commit() def _dbs_payload() -> dict: """构造 DBS 收料配置;Warehouse 为可选筛选条件,日期未出现表示保持系统页面默认。""" return { 'report_path_json': { 'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail', }, 'query_parameters_json': [ {'name': 'Warehouse', 'mode': 'multi_text', 'values': ['AWSDU', 'AWSDU-02'], 'required': False, 'select_all': False}, {'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}, ], } def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client): """DBS 收料配置按站点保存,不能变更既有库存路径、条件或版本。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id inventory_before = { 'path': dict(source.report_path_json), 'parameters': list(source.query_parameters_json), 'config_version': source.config_version, } forbidden = client.put( f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', json=_dbs_payload(), headers=_headers('receipt-user', 'user'), ) assert forbidden.status_code == 403 response = client.put( f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', json=_dbs_payload(), headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 config = parse_api_data(response.get_json()) # 关键断言:Warehouse 条件原样保存(可选筛选,不作为单元门禁)。 warehouse_condition = next(item for item in config['query_parameters_json'] if item['name'] == 'Warehouse') assert warehouse_condition['values'] == ['AWSDU', 'AWSDU-02'] assert config['report_path_json']['report_group'] == 'Inbound' with app.app_context(): source = ShippingInventorySource.query.get(source_id) # 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义。 assert source.report_path_json == inventory_before['path'] assert source.query_parameters_json == inventory_before['parameters'] assert source.config_version == inventory_before['config_version'] audit = ShippingAuditEvent.query.filter_by( event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id), ).one() assert audit.before_snapshot_json is None assert audit.after_snapshot_json['query_parameters_json'][0]['values'] == ['AWSDU', 'AWSDU-02'] def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, client): """拒绝日期/selector 等 Driver 细节;DBS Warehouse 可选,Crane 禁止查询条件。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() dbs_id = dbs.id from app import db crane_profile = dbs.rpa_profile.__class__( profile_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane', login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'}, ) crane_source = ShippingInventorySource( source_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane', rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=False, ) db.session.add(crane_source) db.session.commit() crane_id = crane_source.id invalid_date = _dbs_payload() invalid_date['query_parameters_json'] = [{'name': 'Report Date', 'mode': 'single', 'values': ['2026-08-19'], 'required': False, 'select_all': False}] response = client.put( f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', json=invalid_date, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' invalid_selector = _dbs_payload() invalid_selector['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': [], 'selector': '#owner'}] response = client.put( f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', json=invalid_selector, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' # 关键断言:Warehouse 条件由管理员自行维护——缺失/空值允许保存,不再强制拦截。 missing_warehouse = _dbs_payload() missing_warehouse['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}] response = client.put( f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', json=missing_warehouse, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 saved_missing = parse_api_data(response.get_json())['query_parameters_json'] assert len(saved_missing) == 1 and saved_missing[0]['name'] == 'Owner' empty_warehouse = _dbs_payload() empty_warehouse['query_parameters_json'] = [{'name': 'Warehouse', 'mode': 'multi_text', 'values': [], 'required': False, 'select_all': False}] response = client.put( f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', json=empty_warehouse, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 saved_empty = parse_api_data(response.get_json())['query_parameters_json'] assert len(saved_empty) == 1 and saved_empty[0]['name'] == 'Warehouse' and saved_empty[0]['values'] == [] invalid_crane = { 'report_path_json': {'report_name': 'Other Report'}, 'query_parameters_json': [], } response = client.put( f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config', json=invalid_crane, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' def _create_movement_profile(profile_code: str, *, status: str, purpose: str): """创建异动/库存解析 Profile 种子;定义仅用于绑定校验,不参与解析。""" from app import db from app.models import ShippingInventoryParsingProfile profile = ShippingInventoryParsingProfile( purpose=purpose, profile_code=profile_code, display_name=f'{profile_code} 规则', version=1, status=status, file_format='xlsx', definition_json={'sheet_name': 'Movement', 'header_row_index': 1, 'field_mapping': {'doc_no': '单据编号', 'material_code': '料号', 'quantity': '数量', 'movement_date': '异动日期'}, 'match_keys': []}, ) db.session.add(profile) db.session.commit() return profile def test_receipt_config_binds_published_movement_profile(app, client): """绑定已发布 movement 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id profile = _create_movement_profile('CRANE_MOVE_STD', status='published', purpose='movement') profile_id = profile.id payload = {**_dbs_payload(), 'parsing_profile_id': profile_id} response = client.put( f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', json=payload, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 config = parse_api_data(response.get_json()) # 关键断言:绑定 id 与规则摘要(码/版本/状态)必须回显,供抽屉展示当前绑定。 assert config['parsing_profile_id'] == profile_id assert config['parsing_profile']['profile_code'] == 'CRANE_MOVE_STD' assert config['parsing_profile']['status'] == 'published' from app.models import ShippingAuditEvent audit = ShippingAuditEvent.query.filter_by( event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id), ).order_by(ShippingAuditEvent.id.desc()).first() assert audit.metadata_json['parsing_profile_id'] == profile_id def test_receipt_config_rejects_draft_or_non_movement_profile(app, client): """draft/库存用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id draft = _create_movement_profile('MOVE_DRAFT', status='draft', purpose='movement') inventory_profile = _create_movement_profile('INV_PUBLISHED', status='published', purpose='inventory') cases = [draft.id, inventory_profile.id, 999999] for profile_id in cases: response = client.put( f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', json={**_dbs_payload(), 'parsing_profile_id': profile_id}, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400, f'profile_id={profile_id}' # 关键断言:非"已发布 movement"绑定必须走统一错误码,fail-closed。 assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID' def test_receipt_config_empty_profile_id_unbinds(app, client): """parsing_profile_id 传 None → 解绑(置空),不做校验也不报错。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id profile = _create_movement_profile('MOVE_UNBIND', status='published', purpose='movement') profile_id = profile.id bound = client.put( f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', json={**_dbs_payload(), 'parsing_profile_id': profile_id}, headers=_headers('receipt-admin', 'admin'), ) assert bound.status_code == 200 unbound = client.put( f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', json={**_dbs_payload(), 'parsing_profile_id': None}, headers=_headers('receipt-admin', 'admin'), ) assert unbound.status_code == 200 # 关键断言:None 表示显式解绑,payload 的绑定字段回到空值。 assert parse_api_data(unbound.get_json())['parsing_profile_id'] is None def test_crane_receipt_config_rejects_query_parameters(app, client): """Crane 固定使用页面默认值直接 Run Report,管理员不能维护查询条件。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() from app import db dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() crane_profile = dbs.rpa_profile.__class__( profile_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane', login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'}, ) crane_source = ShippingInventorySource( source_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane', rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=False, ) db.session.add(crane_source) db.session.commit() crane_id = crane_source.id default_query = { 'report_path_json': {'report_name': 'Inbound Details'}, 'query_parameters_json': [], } response = client.put( f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config', json=default_query, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 assert parse_api_data(response.get_json())['query_parameters_json'] == [] configured = {**default_query, 'query_parameters_json': [ {'name': 'material', 'mode': 'single', 'values': ['PN-01'], 'required': False, 'select_all': False}, ]} rejected = client.put( f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config', json=configured, headers=_headers('receipt-admin', 'admin'), ) assert rejected.status_code == 400 assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'