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>
This commit is contained in:
hugoandCursor committed 2026-10-19 10:46:06 +08:00
1 parent ffc0d4a430
commit 39fe3c05f2
453 files changed
+17945 -8646

No files matched your search

@@ -2,7 +2,7 @@
tests/services/admin/test_shipping_inventory_service.py
用途:验证库存主数据管理服务的安全性和关键业务约束。
依赖:Flask app/db、shipping_inventory_service、库存配置模型。
依赖:Flask app/db、shipping_onhand_admin_service、库存配置模型。
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
"""
@@ -12,16 +12,16 @@ from cryptography.fernet import Fernet
import pytest
from app.core.errors import ConflictError, ValidationError
from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import inventory_parsing_profile
from app.services.admin import shipping_onhand_admin_service
from app.services.shipping_notice import onhand_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingInventoryField,
ShippingInventorySource,
ShippingInventorySourceParsingBindingAudit,
ShippingInventoryStructureAnalysis,
FreightRpaOnhandField,
FreightRpaSource,
FreightRpaSourceParsingBindingAudit,
FreightRpaOnhandStructureAnalysis,
)
@@ -35,7 +35,7 @@ def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict:
def _sample_evidence() -> int:
"""创建最小表头证据,确保库存源服务测试不绕过解析方案样本门禁。"""
item = ShippingInventoryStructureAnalysis(
item = FreightRpaOnhandStructureAnalysis(
source_kind='sample_upload', source_file_name='service-sample.xlsx', storage_path=None,
file_checksum='b' * 64, file_format='xlsx', analysis_status='ready',
structure_json={'candidates': [{
@@ -88,13 +88,13 @@ def _parsing_profile() -> dict:
)
inventory_fields = {
item.field_code: str(item.id)
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
ShippingInventoryField.status == 'active',
for item in FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
FreightRpaOnhandField.status == 'active',
).all()
}
assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'}
draft = inventory_parsing_profile.save_draft({
draft = onhand_parsing_profile.save_draft({
'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx',
'sample_analysis_id': _sample_evidence(),
'definition': {
@@ -110,7 +110,7 @@ def _parsing_profile() -> dict:
}],
},
}, actor_id=None)
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
return onhand_parsing_profile.publish(draft['id'], actor_id=None)
def _excel_template_id() -> int:
@@ -133,17 +133,21 @@ def _excel_template_id() -> int:
def _source_data(profile_id: int, *, parsing_profile_id: int | None = None, code: str = 'DBS_DUB', connector_type: str = 'dbs') -> dict:
return {
'source_code': code, 'display_name': code, 'connector_type': connector_type,
'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'],
'rpa_profile_id': profile_id,
'excel_template_id': _excel_template_id(),
'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 Inventory By Location 3lv',
# s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行,站点载荷不再平铺。
'onhand_report_config': {
'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'],
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
},
'query_parameters_json': [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
],
},
'query_parameters_json': [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
],
}
@@ -160,7 +164,7 @@ def test_profile_credentials_are_not_returned(app):
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
payload = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
assert payload['password_configured'] is True
assert payload['username_masked'] == 'configured'
assert 'password' not in payload
@@ -174,7 +178,7 @@ def test_profile_rejects_page_operation_configuration(app):
payload = _profile_data()
payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}}
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_profile(payload, actor_id=None)
shipping_onhand_admin_service.save_profile(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_CONFIG_INVALID'
@@ -182,10 +186,10 @@ def test_multiple_dbs_profiles_bind_independent_sources(app):
"""同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
second = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
first_source = shipping_inventory_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None)
second_source = shipping_inventory_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None)
first = shipping_onhand_admin_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
second = shipping_onhand_admin_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
first_source = shipping_onhand_admin_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None)
second_source = shipping_onhand_admin_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None)
assert first_source['rpa_profile_id'] == first['id']
assert second_source['rpa_profile_id'] == second['id']
@@ -194,34 +198,36 @@ def test_source_rejects_profile_connector_mismatch(app):
"""库存源不能绑定不同 Driver 的 Profile。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH'
shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH'
def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
"""禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
login = shipping_onhand_admin_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='DRAFT_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
draft = shipping_inventory_service.save_source(payload, actor_id=None)
payload.update({'enabled': False, 'excel_template_id': None})
payload['onhand_report_config']['parsing_profile_id'] = None
draft = shipping_onhand_admin_service.save_source(payload, actor_id=None)
assert draft['enabled'] is False
assert draft['parsing_profile_id'] is None
assert draft['onhand_report_config']['parsing_profile_id'] is None
assert draft['excel_template_id'] is None
payload.update({'enabled': True})
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id'])
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED'
shipping_onhand_admin_service.save_source(payload, actor_id=None, source_id=draft['id'])
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'
# 拒绝后回滚脏会话(等价于请求边界回滚):s18 服务在赋值后才触发启用门禁,
# 不回滚会让后续查询的 autoflush 把 enabled=True + 空模板撞 CHECK。
db.session.rollback()
payload.update({
'parsing_profile_id': _parsing_profile()['id'],
'excel_template_id': _excel_template_id(),
})
enabled = shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id'])
payload['onhand_report_config']['parsing_profile_id'] = _parsing_profile()['id']
payload['excel_template_id'] = _excel_template_id()
enabled = shipping_onhand_admin_service.save_source(payload, actor_id=None, source_id=draft['id'])
assert enabled['enabled'] is True
@@ -229,22 +235,23 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
"""普通保存只能保留停用站点;独立启用动作必须返回尚未完成的硬门槛。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
login = shipping_onhand_admin_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='ACTIVATION_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
payload.update({'enabled': False, 'excel_template_id': None})
payload['onhand_report_config']['parsing_profile_id'] = None
draft = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
assert draft['activation']['ready'] is False
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template']
payload['enabled'] = True
saved = shipping_inventory_service.save_source(
saved = shipping_onhand_admin_service.save_source(
payload, actor_id=None, source_id=draft['id'], allow_enable_transition=False,
)
assert saved['enabled'] is False
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.activate_source(draft['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
shipping_onhand_admin_service.activate_source(draft['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED'
assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template']
@@ -252,18 +259,23 @@ def test_activation_status_exposes_only_hard_gate_checks(app):
"""启用门禁仅暴露连接/解析/发货模板硬门槛,不再包含测试导出或后续准备项。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
login = shipping_onhand_admin_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
payload = {
'source_code': 'CHECKS_SOURCE', 'display_name': 'Checks Source', 'connector_type': 'dbs',
'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None,
'rpa_profile_id': login['id'], 'excel_template_id': None,
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand',
# s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行。
'onhand_report_config': {
'parsing_profile_id': None,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand',
},
'query_parameters_json': [],
},
'query_parameters_json': [], 'enabled': False,
'enabled': False,
}
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
draft = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
checks = {item['code']: item for item in draft['activation']['checks']}
@@ -280,11 +292,11 @@ def test_enabled_source_rejects_disabled_rpa_profile(app):
"""启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(
profile = shipping_onhand_admin_service.save_profile(
{**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None,
)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None)
shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None)
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLED'
@@ -292,10 +304,11 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app):
"""数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
assert source['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv'
assert source['query_parameters_json'] == [
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
# s18 起报表路径/查询条件挂在响应的 onhand_report_config 嵌套对象上。
assert source['onhand_report_config']['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv'
assert source['onhand_report_config']['query_parameters_json'] == [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
]
@@ -304,52 +317,54 @@ def test_source_rejects_driver_selector_in_business_parameters(app):
"""业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
payload = _source_data(profile['id'])
payload['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
payload['onhand_report_config']['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
shipping_onhand_admin_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID'
def test_crane_source_rejects_dbs_report_path(app):
"""动态仓 Crane 库存源不得误填 DBS 四级报表路径。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
payload = _source_data(profile['id'], code='CRANE', connector_type='crane')
payload['warehouse_resolution_mode'] = 'inventory_match'
payload['fixed_warehouse_id'] = None
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
shipping_onhand_admin_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID'
def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app):
"""停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
login = shipping_onhand_admin_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None})
source = shipping_inventory_service.save_source(payload, actor_id=7, allow_enable_transition=False)
payload.update({'enabled': False})
payload['onhand_report_config']['parsing_profile_id'] = None
source = shipping_onhand_admin_service.save_source(payload, actor_id=7, allow_enable_transition=False)
profile = _parsing_profile()
bound = shipping_inventory_service.bind_source_parsing_profile(
bound = shipping_onhand_admin_service.bind_source_parsing_profile(
[source['id']], profile['id'], actor_id=7, operation='direct',
)
# 关键断言:直接绑定只配置解析定义,绝不绕过独立启用门禁。
assert bound[0]['enabled'] is False
assert bound[0]['parsing_profile_id'] == profile['id']
# s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。
assert bound[0]['onhand_report_config']['parsing_profile_id'] == profile['id']
assert bound[0]['config_version'] == source['config_version'] + 1
audit = ShippingInventorySourceParsingBindingAudit.query.one()
audit = FreightRpaSourceParsingBindingAudit.query.one()
assert audit.operation == 'direct'
# 关键断言:审计保留系统动作说明,不要求管理员额外填写“绑定原因”。
assert audit.reason == '管理员直接绑定已发布解析方案'
assert audit.before_snapshot_json['parsing_profile_id'] is None
assert audit.after_snapshot_json['parsing_profile_id'] == profile['id']
history = shipping_inventory_service.get_source_parsing_binding_audits(source['id'])
history = shipping_onhand_admin_service.get_source_parsing_binding_audits(source['id'])
assert history[0]['actor_id'] == 7
assert history[0]['source_config_version_after'] == bound[0]['config_version']
@@ -358,33 +373,36 @@ def test_bulk_parsing_profile_binding_allows_enabled_sites(app):
"""批量绑定允许包含已启用站点;全部预检通过后原子写入。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
login = shipping_onhand_admin_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED')
disabled_payload.update({'enabled': False, 'parsing_profile_id': None})
disabled = shipping_inventory_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False)
enabled = shipping_inventory_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None)
disabled_payload.update({'enabled': False})
disabled_payload['onhand_report_config']['parsing_profile_id'] = None
disabled = shipping_onhand_admin_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False)
enabled = shipping_onhand_admin_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None)
profile = _parsing_profile()
bound = shipping_inventory_service.bind_source_parsing_profile(
bound = shipping_onhand_admin_service.bind_source_parsing_profile(
[disabled['id'], enabled['id']], profile['id'], actor_id=None,
reason='批量迁移同类报表', operation='bulk',
)
# 关键断言:已启用站点可直接换绑;两站同步写入且留下审计。
assert {row['id'] for row in bound} == {disabled['id'], enabled['id']}
assert all(row['parsing_profile_id'] == profile['id'] for row in bound)
assert db.session.get(ShippingInventorySource, enabled['id']).enabled is True
assert ShippingInventorySourceParsingBindingAudit.query.count() == 2
# s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。
assert all(row['onhand_report_config']['parsing_profile_id'] == profile['id'] for row in bound)
assert db.session.get(FreightRpaSource, enabled['id']).enabled is True
assert FreightRpaSourceParsingBindingAudit.query.count() == 2
def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app):
"""直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
login = shipping_onhand_admin_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None})
source = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
payload.update({'enabled': False})
payload['onhand_report_config']['parsing_profile_id'] = None
source = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
template = db.session.get(ShippingExcelTemplate, source['excel_template_id'])
template.definition_json = {
'filename_pattern': '{business_no}.xlsx',
@@ -393,50 +411,51 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app
db.session.commit()
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.bind_source_parsing_profile(
shipping_onhand_admin_service.bind_source_parsing_profile(
[source['id']], _parsing_profile()['id'], actor_id=None,
reason='模板字段契约预检', operation='direct',
)
# 关键断言:模板依赖缺失必须在绑定时拒绝,不能产生半成品站点绑定。
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID'
assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None
assert ShippingInventorySourceParsingBindingAudit.query.count() == 0
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID'
# s18 起解析绑定归 onhand_report_config 配置行;被拒后配置行必须保持未绑定。
assert db.session.get(FreightRpaSource, source['id']).onhand_report_config.parsing_profile_id is None
assert FreightRpaSourceParsingBindingAudit.query.count() == 0
def test_published_rule_cannot_be_mutated_in_place(app):
"""发布规则必须依靠新版本演进,避免改写历史任务依据。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
reservation_field_id = _published_route_field_id()
rule = shipping_inventory_service.save_rule({
rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Reservation starts with 1', 'scope': 'line',
'priority': 100, 'match_mode': 'all', 'action_type': 'add_source_candidates',
'action_payload_json': {'source_codes': [source['source_code']]}, 'version': 1,
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None)
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None)
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.save_rule({
shipping_onhand_admin_service.save_rule({
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Changed', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None, rule_id=rule['id'])
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_IMMUTABLE'
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_IMMUTABLE'
def test_draft_rule_update_keeps_the_same_draft(app):
"""草稿更新应原地替换条件,不能偷偷新增同版本规则记录。"""
with app.app_context():
reservation_field_id = _published_route_field_id()
rule = shipping_inventory_service.save_rule({
rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'Before', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'DUB'}],
}, actor_id=None)
updated = shipping_inventory_service.save_rule({
updated = shipping_onhand_admin_service.save_rule({
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'After', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'FRA'}],
@@ -450,7 +469,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
"""列表、长度和空值操作符必须保存受控值类型,不能把配置错误拖到运行期。"""
with app.app_context():
reservation_field_id = _published_route_field_id()
rule = shipping_inventory_service.save_rule({
rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'RSV_IN', 'rule_name': 'Reservation list', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': ['1001', '1002']}],
@@ -458,106 +477,107 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
assert rule['conditions'][0]['expected_value_json'] == ['1001', '1002']
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_rule({
shipping_onhand_admin_service.save_rule({
'rule_code': 'RSV_BAD_IN', 'rule_name': 'Invalid list', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': '1001'}],
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_CONDITION_INVALID'
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_CONDITION_INVALID'
def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
"""未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
shipping_inventory_service.delete_profile(unused['id'])
assert all(item['profile_code'] != 'UNUSED' for item in shipping_inventory_service.list_profiles())
unused = shipping_onhand_admin_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
shipping_onhand_admin_service.delete_profile(unused['id'])
assert all(item['profile_code'] != 'UNUSED' for item in shipping_onhand_admin_service.list_profiles())
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.delete_profile(profile['id'])
shipping_onhand_admin_service.delete_profile(profile['id'])
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DELETE_BLOCKED'
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id'])
shipping_onhand_admin_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id'])
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLE_BLOCKED'
reservation_field_id = _published_route_field_id()
rule = shipping_inventory_service.save_rule({
rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'RETIRE_ME', 'rule_name': 'Retire me', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None)
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
retired = shipping_inventory_service.retire_rule(rule['id'], actor_id=None)
shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None)
retired = shipping_onhand_admin_service.retire_rule(rule['id'], actor_id=None)
assert retired['status'] == 'retired'
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.delete_draft_rule(rule['id'])
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_DELETE_BLOCKED'
shipping_onhand_admin_service.delete_draft_rule(rule['id'])
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_DELETE_BLOCKED'
def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
"""发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None)
disabled_payload = _source_data(profile['id'], code='DISABLED_ROUTE_SOURCE')
disabled_payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
shipping_inventory_service.save_source(disabled_payload, actor_id=None)
disabled_payload.update({'enabled': False, 'excel_template_id': None})
disabled_payload['onhand_report_config']['parsing_profile_id'] = None
shipping_onhand_admin_service.save_source(disabled_payload, actor_id=None)
reservation_field_id = _published_route_field_id()
missing_rule = shipping_inventory_service.save_rule({
missing_rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'MISSING_SOURCE', 'rule_name': 'Missing source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['MISSING_SOURCE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.publish_rule(missing_rule['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID'
shipping_onhand_admin_service.publish_rule(missing_rule['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_SOURCE_INVALID'
disabled_rule = shipping_inventory_service.save_rule({
disabled_rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'DISABLED_SOURCE', 'rule_name': 'Disabled source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DISABLED_ROUTE_SOURCE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '2'}],
}, actor_id=None)
assert shipping_inventory_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published'
assert shipping_onhand_admin_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published'
valid_rule = shipping_inventory_service.save_rule({
valid_rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'VALID_SOURCE', 'rule_name': 'Valid source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '9'}],
}, actor_id=None)
assert shipping_inventory_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published'
assert shipping_onhand_admin_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published'
def test_active_default_external_mapping_is_unique_per_source(app):
"""同一库存源同一货代仓库身份只能有一条启用的映射。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
payload = {
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
'external_organization_code': None, 'external_site_code': 'EU01',
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
'in_transit_warehouse_code': 'TZR2', 'enabled': True,
}
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None)
with pytest.raises(ConflictError):
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None)
def test_external_mapping_allows_empty_freight_warehouse(app):
"""货代仓库改为可选:空值保存为 NULL(空库位默认映射行),供 inventory_match 源兜底匹配。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
# [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。
mapping = shipping_inventory_service.save_external_mapping({
'inventory_source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
mapping = shipping_onhand_admin_service.save_external_mapping({
'source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
'in_transit_warehouse_code': 'tzr2', 'enabled': True,
}, actor_id=None)
@@ -569,12 +589,12 @@ def test_external_mapping_requires_in_transit_warehouse_code(app):
"""在途仓编码是在途调拨拨出库位来源——缺省必须在保存端拒绝(fail-closed 前置)。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
# [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。
with pytest.raises(ValidationError):
shipping_inventory_service.save_external_mapping({
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
shipping_onhand_admin_service.save_external_mapping({
'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
}, actor_id=None)
@@ -583,10 +603,10 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app):
"""配置端小写货代仓应与收料文件仓库值(大写归一后)使用同一精确映射身份。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
mapping = shipping_inventory_service.save_external_mapping({
'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub',
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
mapping = shipping_onhand_admin_service.save_external_mapping({
'source_id': source['id'], 'freight_warehouse_id': 'dub',
'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01',
'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True,
}, actor_id=None)
@@ -597,32 +617,32 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
"""连接级上传配置(upload_config_json)变更不递增 config_version。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
base_version = profile['config_version']
upload_cfg = {
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
}
updated = shipping_inventory_service.save_profile(
updated = shipping_onhand_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
)
assert updated['config_version'] == base_version
assert updated['upload_config_json']['enabled'] is True
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
bumped = shipping_inventory_service.save_profile(
bumped = shipping_onhand_admin_service.save_profile(
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
actor_id=None, profile_id=profile['id'],
)
assert bumped['config_version'] == base_version + 1
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
with pytest.raises(ValidationError):
shipping_inventory_service.save_profile(
shipping_onhand_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
actor_id=None, profile_id=profile['id'],
)
with pytest.raises(ValidationError):
shipping_inventory_service.save_profile(
shipping_onhand_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
actor_id=None, profile_id=profile['id'],
)
@@ -1,9 +1,12 @@
"""freight_rpa 包 import 边界适应度测试。
用途:锁死阶段 A 验收标准——freight_rpa 不寄生业务编排。
用途:锁死阶段 B 验收标准——freight_rpa 不寄生业务编排。
依赖:app/services/freight_rpa 包、ast。
逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败;
白名单是 RPA 归档/凭据所需的两块业务工具(阶段 B 收敛为零)。
白名单为空集(批次 B Task 6 起审计写入已下沉本包
common/report_audit,包内不再引用任何 shipping_notice 业务模块;
历史 file_assets 白名单条目随迁移一并删除——包内只引用
app.services.file_assets,不属 shipping_notice 命名空间)。
"""
from __future__ import annotations
@@ -12,10 +15,9 @@ from pathlib import Path
PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa"
ALLOWED_SHIPPING_NOTICE = {
"app.services.shipping_notice.audit_service",
"app.services.shipping_notice.file_assets",
}
# 空集:freight_rpa 禁止 import 任何 app.services.shipping_notice.* 模块
# (审计写入走本包 common/report_audit;模型 import 走 app.models,不在此列)。
ALLOWED_SHIPPING_NOTICE: set[str] = set()
def _imported_modules(path: Path) -> set[str]:
@@ -28,7 +30,6 @@ def _imported_modules(path: Path) -> set[str]:
mods.add(node.module)
return mods
def test_freight_rpa_import_boundary():
assert PKG.exists(), "freight_rpa 包不存在"
violations: list[str] = []
@@ -0,0 +1,196 @@
"""tests/services/freight_rpa/test_report_fact_dispatch.py
用途:锁定阶段 B Task 6——inbound 回调「先提交文件/终态,再投递事实」的顺序契约。
依赖:pytest、tests/conftest 的 app 夹具(种子站点 DSV360_AWSDU)、
app.core.errors.AppError、app.services.freight_rpa.reports.facts.ReportFact、
freight_rpa.reports.dispatch.register_report_handler(Task 6 新增)、
freight_rpa.inbound.report_archive.ingest_inbound_callback。
逻辑:(1)处理函数抛异常时已 commit 的归档文件行仍在(不回滚)且异常原样外抛;
(2)同一 unit_run_id + sha256 重复回调不插第二行,事实仍重复投递 ok=True
(供处理函数重试);(3)kind 未注册处理函数时 404
FREIGHT_RPA.SINK_NOT_REGISTERED,已提交文件行不受影响;
(4)empty 终态同样先 commit 再投递 ok=False 事实。
"""
from __future__ import annotations
import hashlib
import pytest
from app.services.freight_rpa.reports.facts import ReportFact
SEED_SOURCE_CODE = "DSV360_AWSDU"
# 归档 IO 替身的注入字节:_fake_archive_io 夹具把它喂给
# _read_inbound_callback_file,_success_payload 按需覆写。
_FAKE_FILE_BYTES: dict[str, bytes] = {"data": b"abc"}
# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。
_CALLBACK_SEQ: dict[str, int] = {"n": 0}
@pytest.fixture
def db_session(app):
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
@pytest.fixture(autouse=True)
def _reset_report_handlers():
"""每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。
[断言意图] 缺处理器用例必须跑在"干净注册表"上——否则前序用例注册的
inbound 处理函数会让 404 用例假绿。
"""
from app.services.freight_rpa.reports import dispatch as dispatch_module
saved = dict(dispatch_module._REPORT_HANDLERS)
dispatch_module._REPORT_HANDLERS.clear()
yield
dispatch_module._REPORT_HANDLERS.clear()
dispatch_module._REPORT_HANDLERS.update(saved)
@pytest.fixture(autouse=True)
def _fake_archive_io(monkeypatch):
"""替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。
核心逻辑:与旧回调测试同一 monkeypatch 姿态(patch report_archive 模块属性),
使 ingest 的 success 分支可脱离真实文件系统与对象存储走完全程。
"""
from app.services.freight_rpa.inbound import report_archive
monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: _FAKE_FILE_BYTES["data"])
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
def _next_callback_id(prefix: str) -> str:
"""生成跨用例唯一的 callback_id(满足 unit run 唯一约束)。"""
_CALLBACK_SEQ["n"] += 1
return f"{prefix}-{_CALLBACK_SEQ['n']}"
def _awaiting_unit(*, source_code: str = "DSV"):
"""构造一个处于 awaiting_rpa 的 inbound 执行单元(挂种子站点满足外键)。
核心逻辑:source_code 列允许测试值(如 "DSV"),source_id 外键挂种子站点
DSV360_AWSDU——与 test_report_queries.py 的 _inbound_file 同构。
"""
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
return FreightRpaInboundUnitRun(
source_id=source.id,
source_code=source_code,
connector_type="dbs",
callback_id=_next_callback_id("report-fact-dispatch"),
status="awaiting_rpa",
config_snapshot_json={},
)
def _success_payload(unit, *, sha256_file: bytes = b"abc") -> dict:
"""构造通过 schema 校验的 success 回调载荷;sha256_file 即被模拟读取的 xlsx 字节。"""
_FAKE_FILE_BYTES["data"] = sha256_file
return {
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": f"receipt_{unit.id or 'x'}.xlsx",
"original_filename": "receipt.xlsx",
"sha256": hashlib.sha256(sha256_file).hexdigest(),
}
def test_handler_failure_keeps_committed_file(app, db_session, monkeypatch):
"""处理函数失败绝不回滚已 commit 的归档文件行,异常原样外抛(不吞)。"""
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
def boom(fact: ReportFact) -> None:
raise RuntimeError("handler down")
register_report_handler("inbound", boom)
with pytest.raises(RuntimeError, match="handler down"):
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
# [断言意图] 异常外抛但文件行已提交:count==1 锁死「先 commit 再投递」顺序。
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
def test_second_delivery_does_not_insert_another_file(app, db_session):
"""同一回调重放不插第二行文件,事实仍重复投递(同一 file_id、ok=True)。"""
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
seen: list[ReportFact] = []
register_report_handler("inbound", seen.append)
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
payload = _success_payload(unit, sha256_file=b"abc")
ingest_inbound_callback(payload)
ingest_inbound_callback(payload)
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
# [断言意图] 幂等重放仍两次投递 ok=True 事实(同一 file_id),供处理函数重试。
assert [fact.file_id for fact in seen] == [seen[0].file_id, seen[0].file_id]
assert all(fact.ok is True for fact in seen)
def test_missing_handler_raises_sink_not_registered(app, db_session):
"""kind 未注册处理函数 → 404 FREIGHT_RPA.SINK_NOT_REGISTERED,文件行已提交。"""
from app.core.errors import AppError
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
with pytest.raises(AppError) as exc:
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
# [断言意图] 分发失败不回滚归档:文件行保留,Worker 重试整笔回调即可补投递。
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
def test_empty_callback_dispatches_failure_fact(app, db_session):
"""empty 终态同样先 commit 再投递 ok=False 事实(error_code 随载荷落库值)。"""
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
seen: list[ReportFact] = []
register_report_handler("inbound", seen.append)
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
result = ingest_inbound_callback(
{
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "empty",
"error_code": "no_receipt_data",
"error_message": "no_receipt_data",
}
)
assert result["status"] == "empty"
assert len(seen) == 1
fact = seen[0]
# [断言意图] empty 是合法业务结果 → ok=False + error_code=no_receipt_data 的事实。
assert fact.report_kind == "inbound"
assert fact.source_code == "DSV"
assert fact.ok is False
assert fact.file_id is None
assert fact.sha256 is None
assert fact.error_code == "no_receipt_data"
assert fact.error_message == "no_receipt_data"
@@ -0,0 +1,282 @@
"""tests/services/freight_rpa/test_report_queries.py
用途:锁定阶段 B Task 3——freight_rpa.reports 只读查询模块的行为契约。
依赖:pytest、app fixture(tests/conftest)、app.core.errors、
app.services.freight_rpa.reports(待实现模块)。
逻辑:覆盖(1)latest_usable_inbound_file 的可用门禁——未删除、当天
(Asia/Shanghai 业务日)抓取、未过期、最新优先;(2)require_report_kind 的
白名单校验;(3)站点/在手/入站配置只读视图;(4)按 storage_key 读文件
字节 + 缺文件 NotFoundError;(5)解析失败三列的标记与清除(仅 flush
不 commit)。(6)业务日窗口内外的定向拒收/放行。
时间口径:查询的 now 参数显式传 naive UTC;文件 created_at 也按 naive UTC
存入,两者用同一业务日窗口锚点(now=2026-10-05 12:00 UTC → 上海业务日
10-05,UTC 窗口 [10-04 16:00, 10-05 16:00))。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app.core.errors import NotFoundError, ValidationError
from app.services.freight_rpa.reports import (
clear_inbound_parse_failure,
get_inbound_config,
get_onhand_config,
get_site,
latest_usable_inbound_file,
mark_inbound_parse_failure,
read_inbound_file_bytes,
require_report_kind,
)
SEED_SOURCE_CODE = "DSV360_AWSDU"
# 业务日窗口锚点(naive UTC):2026-10-05 12:00 UTC = 上海 10-05 20:00,
# 对应业务日 2026-10-05 的 UTC 存储窗口 [10-04 16:00, 10-05 16:00)。
FROZEN_NOW = datetime(2026, 10, 5, 12, 0, 0)
@pytest.fixture
def db_session(app):
"""复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
def _inbound_file(*, source_code: str, sha256: str, created_at: datetime, **overrides):
"""构造一条挂在指定 source_code 执行单元下的入站归档文件(含 unit run)。
核心逻辑:外键要求文件必须挂在 FreightRpaInboundUnitRun 下,unit run 再挂
种子站点(DSV360_AWSDU);source_code 写进 unit run 列(非外键,允许 "DSV"
等测试值),便于验证查询按 unit run 的 source_code 过滤。
"""
from app import db
from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
unit = FreightRpaInboundUnitRun(
source_id=source.id,
source_code=source_code,
connector_type="dbs",
callback_id=f"test-callback:{source_code}:{sha256[:8]}",
status="success",
config_snapshot_json={},
**overrides,
)
db.session.add(unit)
db.session.flush()
report_file = FreightRpaInboundReportFile(
unit_run_id=unit.id,
storage_provider="minio",
storage_bucket="test",
storage_key=f"freight_rpa/inbound/{source_code}/{sha256[:12]}.xlsx",
original_filename=f"{sha256[:8]}.xlsx",
file_size=16,
sha256=sha256,
created_at=created_at,
)
db.session.add(report_file)
return report_file
def test_latest_usable_inbound_file_returns_newest(app, db_session):
"""同一业务日窗口内的两份可用文件 → 按 created_at 倒序取最新一份。
[断言意图] 两份文件的 created_at 均落在 FROZEN_NOW 的业务日 UTC 窗口
([10-04 16:00, 10-05 16:00))内,证明「最新优先」在当天门禁内生效,
而不是因为当天新鲜度被丢掉才命中。
"""
older = _inbound_file(source_code="DSV", sha256="a" * 64, created_at=datetime(2026, 10, 4, 18, 0, 0))
newer = _inbound_file(source_code="DSV", sha256="b" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0))
db_session.add_all([older, newer])
db_session.commit()
view = latest_usable_inbound_file("DSV", now=FROZEN_NOW)
assert view is not None
assert view.file_id == newer.id
assert view.sha256 == "b" * 64
def test_latest_usable_inbound_file_rejects_out_of_business_day(app, db_session):
"""「当天(Asia/Shanghai 业务日)抓取」是可用门禁的一部分:隔日文件不可用。
[断言意图] 同一份文件(expries 为空、未删除)在非当天业务日查 → None;
把判定时刻推回文件被抓取的那个业务日 → 又可用;差异只能来自当天窗口,
锁死修复轮补回的新鲜度条件。
"""
report = _inbound_file(source_code="STL", sha256="0" * 64, created_at=datetime(2026, 10, 3, 10, 0, 0))
db_session.commit()
# FROZEN_NOW(业务日 10-05)下,10-03 抓取的文件是隔日旧文件 → 不可用。
assert latest_usable_inbound_file("STL", now=FROZEN_NOW) is None
# 业务日 10-03 的窗口为 UTC [10-02 16:00, 10-03 16:00):10-03 10:00 UTC 在窗口内 → 可用。
in_day_now = datetime(2026, 10, 3, 12, 0, 0)
view = latest_usable_inbound_file("STL", now=in_day_now)
assert view is not None
assert view.file_id == report.id
def test_latest_usable_inbound_file_skips_deleted_and_expired(app, db_session):
"""已删除/已过期的文件不得被当作可用文件返回;同来源保留最新可用一份。"""
# [断言意图] 三份文件都在 FROZEN_NOW 的业务日窗口内,且已删除/已过期两份
# 更新——若门禁失效,“最新优先”会先命中它们;断言只能命中唯一的可用文件。
usable = _inbound_file(source_code="CRN", sha256="c" * 64, created_at=datetime(2026, 10, 4, 20, 0, 0))
deleted = _inbound_file(source_code="CRN", sha256="d" * 64, created_at=datetime(2026, 10, 5, 1, 0, 0))
deleted.archive_deleted_at = datetime(2026, 10, 5, 5, 0, 0)
expired = _inbound_file(source_code="CRN", sha256="e" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0))
# 保留期早于判定时刻(仍未被清理任务删除)→ 过期不可用。
expired.archive_expires_at = FROZEN_NOW - timedelta(hours=1)
db_session.add_all([usable, deleted, expired])
db_session.commit()
view = latest_usable_inbound_file("CRN", now=FROZEN_NOW)
assert view is not None
assert view.sha256 == "c" * 64
assert view.source_code == "CRN"
assert view.storage_key.endswith(f"{'c' * 12}.xlsx")
assert view.original_filename == f"{'c' * 8}.xlsx"
assert view.created_at == datetime(2026, 10, 4, 20, 0, 0)
def test_latest_usable_inbound_file_no_match_returns_none(app, db_session):
"""来源无任何归档文件(或全部不可用)时返回 None,不抛异常。"""
assert latest_usable_inbound_file("NOPE") is None
def test_report_kind_rejects_shipment():
with pytest.raises(ValidationError):
require_report_kind("shipment")
assert require_report_kind("outbound") == "outbound"
def test_get_site_returns_view_of_seeded_source(app):
"""get_site 返回站点连接与模板绑定的只读视图;未知来源返回 None。"""
view = get_site(SEED_SOURCE_CODE)
assert view is not None
assert view.source_code == SEED_SOURCE_CODE
assert view.display_name == "DBS Dublin AWSDU"
assert view.connector_type == "dbs"
assert view.excel_template_id is not None
assert view.enabled is True
assert get_site("NOPE") is None
def test_get_onhand_config_returns_report_definition(app):
"""get_onhand_config 返回 s18 起挂在配置行上的报表路径/查询条件/解析方案。"""
config = get_onhand_config(SEED_SOURCE_CODE)
assert config is not None
assert config.report_path_json.get("program_group") == "Bison"
assert config.query_parameters_json == [
{"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "required": True, "select_all": False},
]
assert config.parsing_profile_id is not None
# [断言意图] 未知来源与存在但未配置报表的来源都必须返回 None(fail-closed)。
assert get_onhand_config("NOPE") is None
def test_get_inbound_config_returns_none_without_config_row(app):
"""种子站点没有入站报表配置行 → get_inbound_config 返回 None。"""
from app import db
from app.models import FreightRpaInboundReportConfig, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
assert get_inbound_config(SEED_SOURCE_CODE) is None
# [断言意图] 补一条配置行后即可读出三个字段(与在手配置视图同构)。
db.session.add(FreightRpaInboundReportConfig(
source=source,
report_path_json={"program_group": "Bison", "report_name": "Receipt"},
query_parameters_json=[{"name": "Date", "mode": "range"}],
parsing_profile_id=None,
))
db.session.commit()
config = get_inbound_config(SEED_SOURCE_CODE)
assert config is not None
assert config.report_path_json["report_name"] == "Receipt"
assert config.query_parameters_json == [{"name": "Date", "mode": "range"}]
assert config.parsing_profile_id is None
def test_read_inbound_file_bytes_reads_by_storage_key(app, db_session, monkeypatch):
"""read_inbound_file_bytes 按文件的 storage_key 调 file_asset_storage 读取。"""
from app.services.freight_rpa.reports import queries as queries_module
report_file = _inbound_file(source_code="DSV", sha256="f" * 64, created_at=datetime(2026, 10, 6))
db_session.commit()
captured: dict[str, bytes] = {}
def fake_get_bytes(storage_key):
captured["key"] = storage_key
return b"xlsx-bytes"
monkeypatch.setattr(queries_module.file_asset_storage, "get_bytes", fake_get_bytes)
assert read_inbound_file_bytes(report_file.id) == b"xlsx-bytes"
assert captured["key"] == report_file.storage_key
def test_read_inbound_file_bytes_missing_file_raises(app):
"""文件 id 不存在 → NotFoundError(fail-closed,不吞 404)。"""
with pytest.raises(NotFoundError):
read_inbound_file_bytes(999999)
def test_mark_and_clear_inbound_parse_failure_roundtrip(app, db_session):
"""mark 写入三列并 flush(不 commit 由调用方决定);clear 清空恢复。"""
from datetime import timedelta
report_file = _inbound_file(source_code="DSV", sha256="9" * 64, created_at=datetime(2026, 10, 7))
db_session.commit()
file_id = report_file.id
mark_inbound_parse_failure(
file_id,
error_code="X" * 80,
error_message="m" * 2500,
)
# [断言意图] 只 flush 不 commit——新开的同一事务查询立即可见,且列宽截断生效。
from app import db
from app.models import FreightRpaInboundReportFile
marked = db.session.get(FreightRpaInboundReportFile, file_id)
assert marked.parse_failed_at is not None
assert marked.parse_failed_at > datetime.utcnow() - timedelta(minutes=1)
assert marked.parse_error_code == "X" * 64
assert marked.parse_error_message == "m" * 2000
db_session.commit()
clear_inbound_parse_failure(file_id)
cleared = db.session.get(FreightRpaInboundReportFile, file_id)
assert cleared.parse_failed_at is None
assert cleared.parse_error_code is None
assert cleared.parse_error_message is None
db_session.commit()
def test_mark_inbound_parse_failure_missing_file_raises(app):
"""文件 id 不存在 → NotFoundError,与其他按 id 操作一致。"""
with pytest.raises(NotFoundError):
mark_inbound_parse_failure(999999, error_code="E", error_message="m")
def test_import_boundary_no_business_module_imports():
"""本模块(发货与调拨读报表唯一入口)不得 import shipping_notice / in_transit_transfer。"""
import ast
from pathlib import Path
pkg = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa" / "reports"
assert pkg.exists()
for py in pkg.rglob("*.py"):
tree = ast.parse(py.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
mods = [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom) and node.module:
mods = [node.module]
else:
continue
for mod in mods:
assert not mod.startswith("app.services.shipping_notice"), f"{py.name}: {mod}"
assert not mod.startswith("app.services.in_transit_transfer"), f"{py.name}: {mod}"
@@ -0,0 +1,59 @@
"""
backend/tests/services/freight_rpa/test_upload_trigger_contract.py
用途:锁死 upload trigger 写入契约——action 与心跳能力 freight_rpa_upload 对齐,schema 为 freight_rpa.upload.v1。
依赖:app.services.freight_rpa.upload.trigger_io、Flask app fixture。
逻辑:断言模块常量;write_upload_trigger 落盘后 JSON 的 action/schema_version 与常量一致。
"""
from __future__ import annotations
import json
from pathlib import Path
from app.services.freight_rpa.common.worker_heartbeat import FREIGHT_RPA_UPLOAD_CAPABILITY
from app.services.freight_rpa.upload import trigger_io
def test_upload_trigger_constants_align_with_heartbeat_capability():
"""upload action 必须与 Worker 心跳能力串 freight_rpa_upload 一致。"""
assert trigger_io.SCHEMA == "freight_rpa.upload.v1"
assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == "freight_rpa_upload"
assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == FREIGHT_RPA_UPLOAD_CAPABILITY
assert "outbound_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD
assert "shipment_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD
def test_write_upload_trigger_persists_freight_upload_action(app, tmp_path):
"""落盘 trigger JSON 的 action/schema_version 须与模块常量一致。"""
export_file = tmp_path / "queue_src" / "SN-001.xlsx"
export_file.parent.mkdir(parents=True)
export_file.write_bytes(b"fake-xlsx")
upload_queue = tmp_path / "upload_queue"
upload_trigger = tmp_path / "upload_triggers"
upload_queue.mkdir()
upload_trigger.mkdir()
with app.app_context():
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
queue_path, trigger_path, callback_id = trigger_io.write_upload_trigger(
"TASK-UP-1",
str(export_file),
attempt_id=10,
artifact_id=20,
connector_type="dbs",
callback_id="upload-cb-1",
)
assert queue_path
assert trigger_path
assert callback_id == "upload-cb-1"
payload = json.loads(Path(trigger_path).read_text(encoding="utf-8"))
# [断言意图] Worker 侧不校验 action 字面量,但双侧契约文档须与心跳能力 freight_rpa_upload 对齐。
assert payload["action"] == trigger_io.ACTION_FREIGHT_RPA_UPLOAD
assert payload["schema_version"] == trigger_io.SCHEMA
assert payload["action"] == "freight_rpa_upload"
assert payload["schema_version"] == "freight_rpa.upload.v1"
@@ -15,7 +15,7 @@ import pytest
from app.core.errors import ServiceUnavailableError
from app.services.freight_rpa.common.worker_heartbeat import (
FREIGHT_UPLOAD_CAPABILITY,
FREIGHT_RPA_UPLOAD_CAPABILITY,
ONHAND_EXPORT_CAPABILITY,
INBOUND_EXPORT_CAPABILITY,
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
@@ -306,7 +306,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
from app.services.freight_rpa.common.worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
@@ -337,7 +337,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
db.session.add(run)
db.session.commit()
total, success, failed, skipped, _details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
total, success, failed, skipped, _details, errors, logs = run_freight_rpa_onhand_schedule(task, run)
assert total >= 1
assert success == 0
assert failed >= 1
@@ -461,20 +461,20 @@ def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app,
)
)
result = check_freight_upload_rpa_ready()
# 关键断言:缺少 freight_upload 能力必须阻断自动上传。
# 关键断言:缺少 freight_rpa_upload 能力必须阻断自动上传。
assert result.ready is False
assert any("missing_freight_upload_capability" in reason for reason in result.reasons)
assert any("missing_freight_rpa_upload_capability" in reason for reason in result.reasons)
def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
"""Worker 声明 freight_upload 且目录/凭据齐全时应 ready。"""
"""Worker 声明 freight_rpa_upload 且目录/凭据齐全时应 ready。"""
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_RPA_UPLOAD_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()
@@ -129,8 +129,9 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
"""建「启用来源 + 已发布 inbound 解析规则 + 收料配置绑定」全套种子(幂等)。
用途:清空并重新解析(spec §6)服务/端点用例的来源侧种子;来源自身
parsing_profile(在手口径)按约束置最小占位行,真实重建规则挂
ShippingReceiptReportConfig.parsing_profile_id(与运行期口径一致)。
在手解析绑定(在手口径)按约束置最小占位配置行(s18 起归
FreightRpaOnhandReportConfig),真实重建规则挂
FreightRpaInboundReportConfig.parsing_profile_id(与运行期口径一致)。
Args:
source_code: 来源实例编码。
@@ -140,29 +141,30 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
sheet_name / header_row_index: definition_json 结构参数。
status: 入站规则状态(缺省 published;用例可注入 draft 验证 abort)。
Returns:
(ShippingInventorySource, ShippingInventoryParsingProfile) 元组。
(FreightRpaSource, FreightRpaParsingProfile) 元组。
"""
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingRpaProfile,
ShippingReceiptReportConfig,
FreightRpaOnhandReportConfig,
FreightRpaParsingProfile,
FreightRpaSource,
FreightRpaProfile,
FreightRpaInboundReportConfig,
)
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
source = FreightRpaSource.query.filter_by(source_code=source_code).first()
if source is not None:
config = source.receipt_report_config
config = source.inbound_report_config
return source, (config.parsing_profile if config else None)
resolved_code = profile_code or f"MV_{source_code}"
onhand = ShippingInventoryParsingProfile(
onhand = FreightRpaParsingProfile(
purpose="onhand", profile_code=f"ONHAND_{source_code}", display_name=source_code,
version=1, status="published", file_format="xlsx",
definition_json={}, structure_definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile = FreightRpaParsingProfile(
purpose="inbound", profile_code=resolved_code, display_name=resolved_code,
version=version, status=status, file_format="xlsx",
definition_json={
@@ -172,7 +174,7 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
},
structure_definition_json={},
)
rpa = ShippingRpaProfile(
rpa = FreightRpaProfile(
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="dbs",
login_url="https://test.invalid/dbs", login_config_json={"auth_mode": "password"},
)
@@ -182,15 +184,20 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
storage_key=f"test/{source_code}/template.xlsx", original_filename="template.xlsx",
file_checksum="0" * 64, definition_json={}, definition_checksum="0" * 64,
)
source = ShippingInventorySource(
source = FreightRpaSource(
source_code=source_code, display_name=source_code, connector_type="dbs",
rpa_profile=rpa, parsing_profile=onhand, excel_template=template,
rpa_profile=rpa, excel_template=template,
warehouse_resolution_mode="fixed", fixed_warehouse_id="AWSDU", enabled=True,
)
db.session.add_all([onhand, profile, rpa, template, source])
db.session.flush()
db.session.add(ShippingReceiptReportConfig(
inventory_source_id=source.id, parsing_profile_id=profile.id))
# s18 起在手解析方案绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载。
db.session.add(FreightRpaOnhandReportConfig(
source_id=source.id, parsing_profile_id=onhand.id,
report_path_json={}, query_parameters_json=[],
))
db.session.add(FreightRpaInboundReportConfig(
source_id=source.id, parsing_profile_id=profile.id))
db.session.commit()
return source, profile
@@ -213,20 +220,20 @@ def seed_reparse_archive_file(source, *, sha: str, storage_key: str, created_at:
archive_deleted_at: 清理时间;None=未清理。
callback_id: 收料执行单元回调键(缺省按 sha 派生保证唯一)。
Returns:
已入库的 ShippingReceiptReportFile。
已入库的 FreightRpaInboundReportFile。
"""
from app import db
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code,
unit = FreightRpaInboundUnitRun(
source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type,
callback_id=callback_id or f"cb-{sha[:12]}",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = ShippingReceiptReportFile(
report = FreightRpaInboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=storage_key, original_filename=f"{callback_id or 'cb'}.xlsx",
file_size=16, sha256=sha, created_at=created_at,
@@ -57,24 +57,24 @@ def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str):
sha: 归档文件 sha256(与 Fake 仓库 checksum 保持同值,模拟同一份文件)。
callback_id: 收料执行单元回调键(唯一约束,用例间取不同值)。
Returns:
已入库的 ShippingReceiptReportFile。
已入库的 FreightRpaInboundReportFile。
"""
from app import db
from app.models import (
ShippingInventorySource,
ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
FreightRpaSource,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
source = ShippingInventorySource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source_code,
source = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = FreightRpaInboundUnitRun(
source_id=source.id, source_code=source_code,
connector_type="dbs", callback_id=callback_id,
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = ShippingReceiptReportFile(
report = FreightRpaInboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=f"shipping/receipt/{callback_id}.xlsx",
original_filename=f"{callback_id}.xlsx", file_size=16, sha256=sha,
@@ -262,7 +262,7 @@ def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m
# 独立 commit 落到当前可用文件(parse_failed 三列),来源投影转 parse_failed;
# 同步数据已回滚(桥隔离保持)。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
from app.services.in_transit_transfer import evidence_sync
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
@@ -282,7 +282,7 @@ def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m
assert ok is False # [断言意图] 同步失败被吞(桥隔离)
assert TransferMovementLedger.query.count() == 0 # [断言意图] 坏行未落档(同步数据已回滚)
db.session.expire_all() # 标记经桥内独立 commit:失效缓存重读
row = db.session.query(ShippingReceiptReportFile).filter_by(id=report.id).one()
row = db.session.query(FreightRpaInboundReportFile).filter_by(id=report.id).one()
assert row.parse_failed_at is not None # [断言意图] 失败事实已落库
assert row.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID"
assert row.parse_error_message
@@ -0,0 +1,320 @@
"""tests/services/in_transit_transfer/test_inbound_report_handler.py
用途:阶段 B Task 7——inbound 报表事实处理函数(handle_inbound_report)的契约测试:
未注册不推进、处理函数先失败后成功只推进一次且文件只留一行、无等待任务时回调成功、
同来源两单元分属两排程 run 时收口只打「本次回调收尾的单元」的 run(修复轮)。
依赖:app(SQLite)fixture、freight_rpa.reports.dispatch(注册表)、
freight_rpa.inbound.report_archive.ingest_inbound_callback(归档+投递入口)、
in_transit_transfer.inbound_callback_bridge / TransferSourceJob(调拨侧事实)。
逻辑:复刻 test_report_fact_dispatch 的注册表隔离与归档 IO 替身——组合根
(create_app→register_inbound_sinks)启动即注册 handle_inbound_report,
未注册用例必须先清空注册表,否则 404 断言假绿;success 归档走替身 IO
(drop 根读取返回注入字节、MinIO 上传 no-op),不依赖真实文件系统;
收口定位用例构造两个 awaiting 排程 run(各挂一个同来源单元),
对旧单元回调后断言只有旧 run 被收口、新 run 保持等待。
"""
from __future__ import annotations
import hashlib
import pytest
@pytest.fixture
def db_session(app):
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
@pytest.fixture(autouse=True)
def _reset_report_handlers():
"""每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。
[断言意图] 未注册用例必须跑在"干净注册表"上——组合根启动已注册
handle_inbound_report,不清空会让 FREIGHT_RPA.SINK_NOT_REGISTERED 断言假绿。
"""
from app.services.freight_rpa.reports import dispatch as dispatch_module
saved = dict(dispatch_module._REPORT_HANDLERS)
dispatch_module._REPORT_HANDLERS.clear()
yield
dispatch_module._REPORT_HANDLERS.clear()
dispatch_module._REPORT_HANDLERS.update(saved)
@pytest.fixture(autouse=True)
def _fake_archive_io(monkeypatch):
"""替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。
核心逻辑:与 test_report_fact_dispatch 同一 monkeypatch 姿态(patch
report_archive 模块属性),使 success 归档分支脱离真实文件系统与对象存储。
"""
from app.services.freight_rpa.inbound import report_archive
monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: b"handler-bytes")
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。
_CALLBACK_SEQ: dict[str, int] = {"n": 0}
def _next_callback_id() -> str:
"""生成跨用例唯一的 callback_id(unit run 唯一约束)。"""
_CALLBACK_SEQ["n"] += 1
return f"inbound-handler-{_CALLBACK_SEQ['n']}"
def _waiting_job(source_code: str):
"""构造一个未落库的 waiting_rpa_callback 来源任务(先建 TransferRun 满足外键)。
核心逻辑:TransferRun 只 add+flush(拿 run_id);TransferSourceJob 由调用方
add+commit——与用例体里的 db_session.add(job) 契约一致。
"""
from app import db
from app.models import TransferRun, TransferSourceJob
run = TransferRun(
run_no=f"RUN-HANDLER-{_next_callback_id()}",
business_date="2026-09-17",
status="preparing_files",
trigger_type="manual",
)
db.session.add(run)
db.session.flush()
return TransferSourceJob(run_id=run.id, source_code=source_code, status="waiting_rpa_callback")
def _success_payload_for(source_code: str) -> dict:
"""构造一个挂种子站点的 awaiting 单元及其 success 回调载荷(可通过 schema 校验)。
核心逻辑:source_code 列允许测试值(如 "DSV",与调拨任务匹配),source_id
外键挂 conftest 种子站点 DSV360_AWSDU;替身 IO 注入字节与 sha256 对齐。
"""
from app import db
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = FreightRpaInboundUnitRun(
source_id=anchor.id,
source_code=source_code,
connector_type="dbs",
callback_id=_next_callback_id(),
status="awaiting_rpa",
config_snapshot_json={},
)
db.session.add(unit)
db.session.commit()
data = b"handler-bytes"
return {
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": f"receipt_{unit.id}.xlsx",
"original_filename": "receipt.xlsx",
"sha256": hashlib.sha256(data).hexdigest(),
}
def test_unregistered_transfer_handler_leaves_job_waiting(app, db_session):
"""未注册处理函数:归档 404 后调拨任务必须原地保持 waiting_rpa_callback。"""
from app.core.errors import AppError
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
job = _waiting_job(source_code="DSV")
db_session.add(job)
db_session.commit()
# 不注册 handle_inbound_report
with pytest.raises(AppError) as exc:
ingest_inbound_callback(_success_payload_for("DSV"))
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
db_session.refresh(job)
assert job.status == "waiting_rpa_callback"
def test_handler_fail_then_success_advances_once(app, db_session, monkeypatch):
"""处理函数先失败后成功:文件只留一行,调拨任务只推进一次到 file_ready。"""
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
job = _waiting_job(source_code="DSV")
db_session.add(job)
db_session.commit()
calls = {"n": 0}
def flaky(fact: ReportFact) -> None:
calls["n"] += 1
if calls["n"] == 1:
raise RuntimeError("once")
handle_inbound_report(fact)
register_report_handler("inbound", flaky)
payload = _success_payload_for("DSV")
with pytest.raises(RuntimeError):
ingest_inbound_callback(payload)
ingest_inbound_callback(payload)
db_session.refresh(job)
assert job.status == "file_ready"
assert FreightRpaInboundReportFile.query.count() == 1
def test_no_waiting_job_is_success(app, db_session):
"""无等待中的调拨任务:处理函数照常成功返回,且不产生任何调拨来源任务行。"""
from app.models import TransferSourceJob
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
register_report_handler("inbound", handle_inbound_report)
ingest_inbound_callback(_success_payload_for("DSV"))
assert TransferSourceJob.query.filter_by(source_code="DSV").count() == 0
def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaiting: bool = True):
"""构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_receipt_rpa 等待态。"""
from app.models import ScheduleRun, ScheduleTask
task = ScheduleTask(
schedule_no=schedule_no, name=f'Receipt {schedule_no}', schedule_type='platform_job',
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
)
db_session.add(task)
db_session.flush()
run = ScheduleRun(
run_no=run_no, schedule_task_id=task.id, status='running', total_count=1,
success_count=0, failed_count=0, skipped_count=0,
response_summary_json={'awaiting_receipt_rpa': awaiting},
)
db_session.add(run)
db_session.commit()
return run
def _unit_on_run(db_session, run, *, callback_id: str):
"""在指定排程 run 下造一个挂种子站点的 awaiting 收料单元(source_code=DSV)。"""
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id, source_id=anchor.id, source_code="DSV",
connector_type="dbs", callback_id=callback_id,
status="awaiting_rpa", config_snapshot_json={},
)
db_session.add(unit)
db_session.commit()
return unit
def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch):
"""同来源两个单元分属两个排程 run:本回调收尾的单元(按文件反查)只收口它自己的 run。
[断言意图] 修复「按来源取最新单元」的错位:旧逻辑会把收口打到更新单元的 run,
本回调刚完成的 run 永久滞留 awaiting_receipt_rpa。
"""
from app.models import ScheduleRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file",
lambda _path: b"handler-bytes",
)
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
register_report_handler("inbound", handle_inbound_report)
run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-OLD", run_no="RUN-ONHAND-OLD")
run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-NEW", run_no="RUN-ONHAND-NEW")
unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-old")
_unit_on_run(db_session, run_new, callback_id="inbound-handler-new")
ingest_inbound_callback({
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit_old.callback_id,
"status": "success",
"file_path": "receipt_old.xlsx",
"original_filename": "receipt.xlsx",
"sha256": hashlib.sha256(b"handler-bytes").hexdigest(),
})
db_session.rollback()
db_session.expire_all()
# [断言意图] 本回调收尾的是旧单元:只有旧 run 被收口(全终态 → success)。
refreshed_old = db_session.get(ScheduleRun, run_old.id)
assert refreshed_old.status == "success"
assert not (refreshed_old.response_summary_json or {}).get("awaiting_receipt_rpa")
# 新单元的 run 原样保持等待态——未被本次回调误收口。
refreshed_new = db_session.get(ScheduleRun, run_new.id)
assert refreshed_new.status == "running"
assert (refreshed_new.response_summary_json or {}).get("awaiting_receipt_rpa") is True
def test_finalize_targets_failed_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch):
"""同来源两单元、同失败错误文本、分属两 run:失败回调只收口本单元(unit_run_id)的 run。
[断言意图] 修复「按来源+终态+错误文本取最新单元」的错位:错误文本碰撞时旧回调
会收口新单元的 run,本回调刚失败的 run 永久滞留 awaiting_receipt_rpa。
"""
from datetime import datetime
from app.models import ScheduleRun, FreightRpaInboundUnitRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file",
lambda _path: b"handler-bytes",
)
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
register_report_handler("inbound", handle_inbound_report)
run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-OLD", run_no="RUN-FAIL-OLD")
run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-NEW", run_no="RUN-FAIL-NEW")
unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-fail-old")
unit_new = _unit_on_run(db_session, run_new, callback_id="inbound-handler-fail-new")
# [RED 场景] 新单元已先以同错误文本终态失败落库——旧逻辑按 (来源, 终态, 错误文本)
# 取最新单元会命中新单元,把收口打到新 run。
unit_new.status = "failed"
unit_new.error_code = "RPA_TEST_FAIL"
unit_new.error_message = "boom"
unit_new.finished_at = datetime.utcnow()
db_session.commit()
result = ingest_inbound_callback({
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit_old.callback_id,
"status": "failed",
"error_code": "RPA_TEST_FAIL",
"error_message": "boom",
})
assert result["status"] == "failed"
db_session.rollback()
db_session.expire_all()
# [断言意图] 只有旧单元的 run 被收口(唯一单元终态失败 → failed、awaiting 清除)。
refreshed_old = db_session.get(ScheduleRun, run_old.id)
assert refreshed_old.status == "failed"
assert not (refreshed_old.response_summary_json or {}).get("awaiting_receipt_rpa")
refreshed_saved_old = db_session.get(FreightRpaInboundUnitRun, unit_old.id)
assert refreshed_saved_old.status == "failed"
assert refreshed_saved_old.error_code == "RPA_TEST_FAIL"
# 新单元的 run 原样保持等待态——未被本次回调误收口(新单元自身终态由其回调收口)。
refreshed_new = db_session.get(ScheduleRun, run_new.id)
assert refreshed_new.status == "running"
assert (refreshed_new.response_summary_json or {}).get("awaiting_receipt_rpa") is True
@@ -0,0 +1,36 @@
"""tests/services/in_transit_transfer/test_inbound_report_read_boundary.py
用途:锁定阶段 B Task 4——in_transit_transfer 包不得引用 freight_rpa 报表模型
(站点与报表文件/配置的读取一律改走 app.services.freight_rpa.reports
只读入口,业务方只按 source_code / file_id 消费)。
依赖:pathlib(纯文本扫描;无 app/DB fixture,秒级运行)。
逻辑:对包内全部 .py 逐文件做 banned 字符串扫描(含注释/docstring——模型名
出现在任何位置都算引用面),命中即 fail 并按「文件名: 模型名」逐条列出,
防止调拨域绕过只读入口直接 import 报表模型造成域间漂移。
"""
from __future__ import annotations
from pathlib import Path
def test_in_transit_does_not_import_rpa_report_models():
"""in_transit_transfer 包内任何 .py 不得出现 freight_rpa 报表模型名。
banned 集合与计划 Task 4 冻结一致:入站归档文件、入站报表配置、库存站点、
在手报表配置四类模型自本任务起归 freight_rpa 域读写;调拨域(含注释与
docstring)不得再引用其类名——命中即边界破坏,须收敛到
freight_rpa.reports.queries 的只读函数。
"""
root = Path(__file__).resolve().parents[3] / "app" / "services" / "in_transit_transfer"
banned = ("FreightRpaInboundReportFile", "FreightRpaInboundReportConfig",
"FreightRpaSource", "FreightRpaOnhandReportConfig")
hits = []
for path in root.rglob("*.py"):
text = path.read_text(encoding="utf-8")
for name in banned:
if name in text:
hits.append(f"{path.name}: {name}")
# [断言意图] hits 必须为空:任一命中都意味着调拨域仍在直接引用
# freight_rpa 报表模型(import、类型标注或文档残句),边界未闭合。
assert hits == []
@@ -1,10 +1,10 @@
"""真实收料 RPA 触发服务测试。
用途:验证 trigger_inbound_rpa / trigger_inbound_rpa_batch 按来源装配收料 trigger unit
并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
并调用写者;触发先落 FreightRpaInboundUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
依赖:app(SQLite)fixture、inbound_trigger_service.trigger_inbound_rpa(_batch)、
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
既有测试种子(FreightRpaProfile/FreightRpaSource)。
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False;
批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批,
parse_failed 先本地重解析不触发 RPA)。
@@ -14,7 +14,7 @@ from __future__ import annotations
import pytest
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
from app.services.in_transit_transfer.inbound_trigger_service import (
trigger_inbound_rpa,
trigger_inbound_rpa_batch,
@@ -24,10 +24,10 @@ from app.services.in_transit_transfer.inbound_trigger_service import (
@pytest.fixture
def receipt_source():
"""复用种子来源并为其创建收料配置。"""
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
assert source is not None
config = ShippingReceiptReportConfig(
inventory_source_id=source.id,
config = FreightRpaInboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
)
@@ -67,7 +67,7 @@ def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source):
def test_trigger_inbound_rpa_disabled_source_fails_closed(app):
"""来源停用 → ok=False,不写 trigger。"""
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
source.enabled = False
from app import db
@@ -84,9 +84,9 @@ def test_trigger_inbound_rpa_missing_config_fails_closed(app):
def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
"""触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
"""触发必须先落 FreightRpaInboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
captured: dict = {}
@@ -101,22 +101,22 @@ def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receip
reason="transfer_retry_inbound", writer=fake_writer,
)
assert outcome["ok"] is True
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
assert unit.status == "awaiting_rpa"
# [断言意图] 按需触发无排程 run,schedule_run_id 必须为 NULL——
# PostgreSQL 上 FK 禁止 0 占位(SQLite 测试库不强制 FK,需显式守住列可空契约)。
assert unit.schedule_run_id is None
assert ShippingReceiptRpaUnitRun.__table__.columns['schedule_run_id'].nullable is True
assert FreightRpaInboundUnitRun.__table__.columns['schedule_run_id'].nullable is True
assert captured["units"][0]["unit_run_id"] == unit.id
assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id
def _bind_published_inbound_profile(config: ShippingReceiptReportConfig) -> None:
def _bind_published_inbound_profile(config: FreightRpaInboundReportConfig) -> None:
"""给收料配置绑定一条已发布 inbound 规则(仅满足守卫校验,不参与解析)。"""
from app import db
from app.models import ShippingInventoryParsingProfile
from app.models import FreightRpaParsingProfile
profile = ShippingInventoryParsingProfile(
profile = FreightRpaParsingProfile(
purpose='inbound', profile_code='MOVE_TRIGGER_STD', display_name='入站解析规则',
version=1, status='published', file_format='xlsx',
definition_json={'sheet_name': None, 'header_row_index': 1,
@@ -135,8 +135,8 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
with app.app_context():
config = ShippingReceiptReportConfig.query.filter_by(
inventory_source_id=receipt_source.id).one()
config = FreightRpaInboundReportConfig.query.filter_by(
source_id=receipt_source.id).one()
_bind_published_inbound_profile(config)
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
@@ -165,15 +165,15 @@ def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_
def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
outcome = trigger_inbound_rpa(
source_code=receipt_source.source_code, business_date="2026-09-17",
reason="transfer_retry_inbound", writer=lambda *a, **k: None,
)
assert outcome["ok"] is False
unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
ShippingReceiptRpaUnitRun.id.desc()).first()
unit = FreightRpaInboundUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
FreightRpaInboundUnitRun.id.desc()).first()
assert unit.status == "failed"
assert unit.error_code == "RPA_INBOUND_TRIGGER_UNAVAILABLE"
@@ -185,28 +185,35 @@ def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, rec
@pytest.fixture
def second_receipt_source(app):
"""再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定
解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。"""
"""再造一个启用来源 + 收料配置(批量用例需要多来源);s18 起启用态要求
Excel 模板绑定(ck_freight_rpa_sources_enabled_template),解析绑定复用种子源配置行。"""
from app import db
from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig
from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaInboundReportConfig
seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
profile = ShippingRpaProfile(
seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
profile = FreightRpaProfile(
profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs',
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
)
source = ShippingInventorySource(
source = FreightRpaSource(
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
rpa_profile=profile,
parsing_profile=seed.parsing_profile, excel_template=seed.excel_template,
excel_template=seed.excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
enabled=True,
)
# s18 起在手解析绑定/报表路径归配置行,复用种子源绑定形态。
seed_config = seed.onhand_report_config
FreightRpaOnhandReportConfig(
source=source,
parsing_profile=seed_config.parsing_profile if seed_config is not None else None,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[],
)
db.session.add_all([profile, source])
db.session.flush() # 先取 source.id(新建对象 flush 前无主键)
config = ShippingReceiptReportConfig(
inventory_source_id=source.id,
config = FreightRpaInboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[],
)
@@ -217,7 +224,7 @@ def second_receipt_source(app):
def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
calls: list = []
@@ -238,7 +245,7 @@ def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
callback_ids = {u['callback_id'] for u in calls[0]['units']}
assert len(callback_ids) == 2
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_(
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
assert {row.status for row in rows} == {'awaiting_rpa'}
assert all(row.schedule_run_id is None for row in rows)
@@ -278,7 +285,7 @@ def test_trigger_inbound_rpa_batch_all_invalid_no_trigger(app):
def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
@@ -286,7 +293,7 @@ def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, rece
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_(
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
assert {row.status for row in rows} == {'failed'}
assert {row.error_code for row in rows} == {'RPA_INBOUND_TRIGGER_UNAVAILABLE'}
@@ -4,7 +4,7 @@
拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码;
inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配,
匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。
依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。
依赖:app fixture 种子站点、FreightRpaOnhandExternalMapping、DefaultRouteResolver。
逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。
"""
@@ -13,18 +13,18 @@ from __future__ import annotations
import pytest
from app.extensions import db
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource
from app.services.in_transit_transfer.deps import DefaultRouteResolver
from app.services.in_transit_transfer.matching_service import RouteNotResolvedError
def _seed_mapping(
source: ShippingInventorySource, *, freight_warehouse_id: str | None,
source: FreightRpaSource, *, freight_warehouse_id: str | None,
in_transit_warehouse_code: str = 'TZT-01',
) -> ShippingInventoryExternalMapping:
) -> FreightRpaOnhandExternalMapping:
"""在既有种子来源上挂一条启用映射。"""
mapping = ShippingInventoryExternalMapping(
inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id,
mapping = FreightRpaOnhandExternalMapping(
source_id=source.id, freight_warehouse_id=freight_warehouse_id,
external_system_code='TOPGP', external_organization_code='TGHX',
external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓',
in_transit_warehouse_code=in_transit_warehouse_code, enabled=True,
@@ -34,12 +34,13 @@ def _seed_mapping(
return mapping
def _seed_inventory_match_source() -> ShippingInventorySource:
def _seed_inventory_match_source() -> FreightRpaSource:
"""以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。"""
template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = ShippingInventorySource(
template = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
# s18 起站点行不再承载 parsing_profile_id;路由解析只读外部映射,无需在手配置行。
source = FreightRpaSource(
source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane',
rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id,
rpa_profile_id=template.rpa_profile_id,
excel_template_id=template.excel_template_id,
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True,
)
@@ -51,7 +52,7 @@ def _seed_inventory_match_source() -> ShippingInventorySource:
def test_fixed_source_uses_single_mapping_in_transit_code(app):
"""fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。"""
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
# 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。
_seed_mapping(source, freight_warehouse_id='TZR2')
@@ -118,7 +119,7 @@ def test_inventory_match_fails_closed_without_any_match(app):
def test_route_resolver_fails_closed_without_in_transit_code(app):
"""映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。"""
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='')
with pytest.raises(RouteNotResolvedError):
@@ -46,12 +46,12 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
"""创建可参与收料的最小库存源(rpa_profile_id 非空,须先建 Profile)。"""
from app.models import (
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingRpaProfile,
FreightRpaParsingProfile,
FreightRpaSource,
FreightRpaProfile,
)
profile = ShippingRpaProfile(
profile = FreightRpaProfile(
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="crane",
login_url="https://test.invalid/login", login_config_json={"auth_mode": "password"},
)
@@ -62,7 +62,7 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
"rpa_profile_id": profile.id, "enabled": enabled,
}
if enabled:
parsing = ShippingInventoryParsingProfile(
parsing = FreightRpaParsingProfile(
profile_code=f"PARSE_{source_code}", display_name=source_code, version=1,
status="published", file_format="xlsx",
definition_json={"field_mapping": {}, "match_keys": []},
@@ -79,27 +79,35 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
db.session.add_all([parsing, template])
db.session.flush()
source_kwargs.update(
parsing_profile_id=parsing.id, excel_template_id=template.id,
excel_template_id=template.id,
warehouse_resolution_mode="fixed", fixed_warehouse_id="WH1",
)
else:
source_kwargs.update(warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None)
source = ShippingInventorySource(**source_kwargs)
source = FreightRpaSource(**source_kwargs)
db.session.add(source)
if enabled:
# s18 起解析方案绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行;
# 经关系级联随站点一并入库。
from app.models import FreightRpaOnhandReportConfig
FreightRpaOnhandReportConfig(
source=source, parsing_profile=parsing,
report_path_json={}, query_parameters_json=[],
)
return source
def test_list_inbound_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
"""缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。"""
from app.models import ShippingReceiptReportConfig
from app.models import FreightRpaInboundReportConfig
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True)
_make_receipt_source(transfer_db, "DBS_OFF", enabled=False)
_make_receipt_source(transfer_db, "CRANE_NOCONF", enabled=True)
transfer_db.session.flush()
transfer_db.session.add(ShippingReceiptReportConfig(
inventory_source_id=enabled.id, report_path_json={}, query_parameters_json=[],
transfer_db.session.add(FreightRpaInboundReportConfig(
source_id=enabled.id, report_path_json={}, query_parameters_json=[],
))
transfer_db.session.commit()
@@ -3,7 +3,7 @@
用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile),
按来源投影 ready/fetching/failed/expired/parse_failed/none,并验证解析失败
标记 record/clear 的往返语义。调拨不维护独立抓取状态表。
依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
逻辑:有当天(业务日)抓取且未过期文件→ready(若标记解析失败→parse_failed);
有进行中单元→fetching;最新单元失败终态→failed;
保留期已到或隔日旧文件(未清理)→expired;否则→none。
@@ -25,9 +25,9 @@ SOURCE_CODE = 'DSV360_AWSDU'
def receipt_unit_run():
"""构造一条收料执行单元(含排程/来源上下文)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
task = ScheduleTask(
schedule_no='SCH-SOURCE-STATUS', name='Source status test', schedule_type='platform_job',
owner_user_id=1, cron_expr='0 8 * * *', job_params={},
@@ -37,8 +37,8 @@ def receipt_unit_run():
run = ScheduleRun(run_no='RUN-SOURCE-STATUS', schedule_task_id=task.id, status='awaiting_callback')
db.session.add(run)
db.session.flush()
unit = ShippingReceiptRpaUnitRun(
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id, source_id=source.id, source_code=source.source_code,
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-status-001',
status='awaiting_rpa', config_snapshot_json={},
)
@@ -64,7 +64,7 @@ def test_running_unit_is_fetching(app, receipt_unit_run):
def test_failed_latest_unit_is_failed(app, receipt_unit_run):
"""最新单元为失败终态且无文件 → failed。"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
receipt_unit_run.status = 'failed'
db.session.commit()
@@ -75,11 +75,11 @@ def test_failed_latest_unit_is_failed(app, receipt_unit_run):
def test_report_file_is_ready(app, receipt_unit_run):
"""有收料归档文件 → ready,且带 file_no/sha256。"""
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'receipt workbook').hexdigest()
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/test.xlsx', original_filename='receipt.xlsx',
file_size=16, sha256=digest,
@@ -96,10 +96,10 @@ def test_expired_report_is_expired(app, receipt_unit_run):
"""保留期已到但清理任务未删 → expired,不得误报 ready。"""
# [断言意图] 过期判定只看 archive_expires_at,不依赖保留期清理任务是否已落位。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
@@ -115,17 +115,17 @@ def test_newer_valid_report_wins_over_expired(app, receipt_unit_run):
"""过期文件之后又抓到未过期文件 → 以最新未过期文件为准(ready)。"""
# [断言意图] ready 查询过滤掉过期记录后仍按 created_at/id 倒序取最新一条。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'fresh workbook').hexdigest()
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
archive_expires_at=datetime.utcnow() - timedelta(days=1),
))
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/fresh.xlsx', original_filename='fresh.xlsx',
file_size=16, sha256=digest,
@@ -143,10 +143,10 @@ def test_stale_report_is_expired(app, receipt_unit_run):
# [断言意图] 新鲜度按 Asia/Shanghai 业务日窗口判定(UTC 库存时间须换算):
# 隔日抓取的文件对 D+1 预检是旧数据,投影 expired 引导重试重抓。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/stale.xlsx', original_filename='stale.xlsx',
file_size=16, sha256=hashlib.sha256(b'stale workbook').hexdigest(),
@@ -161,11 +161,11 @@ def test_stale_report_is_expired(app, receipt_unit_run):
def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_unit_run):
"""可用归档文件若已标记 parse_failed_at → file_status=parse_failed 且不可当 ready。"""
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'bad workbook').hexdigest()
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/bad.xlsx', original_filename='bad.xlsx',
file_size=16, sha256=digest,
@@ -183,7 +183,7 @@ def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_uni
def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
"""record 写入三列;clear 清空后投影回 ready。"""
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
from app.services.in_transit_transfer.source_file_status import (
clear_inbound_parse_failure,
record_inbound_parse_failure,
@@ -192,7 +192,7 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'roundtrip').hexdigest()
report = ShippingReceiptReportFile(
report = FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/ok.xlsx', original_filename='ok.xlsx',
file_size=16, sha256=digest,
@@ -228,14 +228,14 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
门禁)永久锁死;回收后必须翻转 failed 解锁重新触发 RPA。
"""
from app import db
from app.models import ShippingInventorySource, ShippingReceiptRpaUnitRun
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units
from app.models import FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
db.session.add(ShippingReceiptRpaUnitRun(
schedule_run_id=None, inventory_source_id=source.id, source_code=source.source_code,
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
db.session.add(FreightRpaInboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
connector_type='dbs', callback_id='inbound-orphan-status', status='awaiting_rpa',
config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=5),
))
@@ -4,7 +4,7 @@
可空成分 NOT NULL + default ''/transfer_executed 默认 false/
source_file_id FK ON DELETE SET NULL(文件清理后档事实留存)。
依赖:app_ctx(根 conftest app fixture 上下文别名)、transfer_db(SQLite 内存库)、
models/in_transit_transfer、models/shipping_receipt_report。
models/in_transit_transfer、models/shipping_inbound_report。
逻辑:纯元数据断言(不落库)+ 真库往返(默认值/唯一约束/FK SET NULL 行为)。
"""
@@ -15,7 +15,7 @@ from sqlalchemy import inspect, text
from sqlalchemy.exc import IntegrityError
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
from app.models.in_transit_transfer import TransferMovementLedger
# 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维):8 成分全部 NOT NULL,
@@ -106,13 +106,13 @@ def test_scope_indexes_declared(app_ctx):
def test_source_file_fk_on_delete_set_null(app_ctx):
"""source_file_id FK 指向 shipping_receipt_report_files 且 ON DELETE SET NULL(档事实留存)。"""
"""source_file_id FK 指向 freight_rpa_inbound_report_files 且 ON DELETE SET NULL(档事实留存)。"""
cols = _column_map()
fk = next(
fk for fk in TransferMovementLedger.__table__.foreign_keys
if fk.parent.name == 'source_file_id'
)
assert fk.target_fullname == 'shipping_receipt_report_files.id'
assert fk.target_fullname == 'freight_rpa_inbound_report_files.id'
assert fk.ondelete == 'SET NULL'
assert cols['source_file_id'].nullable is True
@@ -164,17 +164,17 @@ def test_duplicate_natural_key_rejected(transfer_db):
def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
"""source_file relationship 可导航;来源文件删除后档记录留存且 source_file_id 置 NULL。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
unit_run = ShippingReceiptRpaUnitRun(
inventory_source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行
unit_run = FreightRpaInboundUnitRun(
source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行
source_code='DBS-AWSBI',
connector_type='rpa',
callback_id='CB-LEDGER-001',
)
db.session.add(unit_run)
db.session.flush()
report_file = ShippingReceiptReportFile(
report_file = FreightRpaInboundReportFile(
unit_run_id=unit_run.id,
storage_provider='minio',
storage_bucket='receipts',
@@ -198,7 +198,7 @@ def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
db.session.commit()
loaded = db.session.get(TransferMovementLedger, ledger.id)
assert loaded.source_file.id == report_file.id # relationship 目标 ShippingReceiptReportFile
assert loaded.source_file.id == report_file.id # relationship 目标 FreightRpaInboundReportFile
# ON DELETE SET NULL 行为:开启 SQLite FK 强制后原样删文件(文件资产保留策略)。
# PRAGMA 是连接级开关且事务内为 no-op:必须走 AUTOCOMMIT 连接执行,归还连接池
@@ -208,7 +208,7 @@ def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
with db.engine.connect().execution_options(isolation_level='AUTOCOMMIT') as conn:
conn.execute(text('PRAGMA foreign_keys=ON'))
conn.execute(
text('DELETE FROM shipping_receipt_report_files WHERE id = :id'),
text('DELETE FROM freight_rpa_inbound_report_files WHERE id = :id'),
{'id': file_id},
)
conn.execute(text('PRAGMA foreign_keys=OFF'))
@@ -1,5 +1,5 @@
"""
tests/services/shipping_notice/test_inventory_candidate_projection.py
tests/services/shipping_notice/test_onhand_candidate_projection.py
用途:验证正式 Task 的 active CandidateSet 读取、缺失阻断与版本化候选事实投影。
依赖:Flask app fixture、ShippingNotice / CandidateSet / CandidateLine ORM、候选 projector。
@@ -10,19 +10,19 @@ from __future__ import annotations
from app import db
from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingOnhandCandidateLine,
ShippingOnhandCandidateSet,
ShippingOnhandCandidateSource,
ShippingOrderTask,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingNoticeLineInventoryMatch,
ShippingInventoryFile,
ShippingNoticeLineOnhandMatch,
FreightRpaOnhandReportFile,
)
from app.services.shipping_notice.inventory_candidate_projection import (
from app.services.shipping_notice.onhand_candidate_projection import (
project_inventory_candidate_facts,
)
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines
def _task(task_no: str) -> ShippingOrderTask:
@@ -36,8 +36,8 @@ def _task(task_no: str) -> ShippingOrderTask:
return task
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet:
row = ShippingInventoryCandidateSet(
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingOnhandCandidateSet:
row = ShippingOnhandCandidateSet(
task_id=int(task.id),
set_version=version,
lifecycle_status='frozen',
@@ -50,12 +50,12 @@ def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInvento
return row
def test_prepare_candidate_inventory_lines_blocks_without_active_set(app):
def test_prepare_candidate_onhand_lines_blocks_without_active_set(app):
with app.app_context():
task = _task('SN-CAND-001')
db.session.commit()
result = prepare_candidate_inventory_lines(task)
result = prepare_candidate_onhand_lines(task)
assert result['status'] == 'blocked'
assert result['error_code'] == 'inventory_candidates_missing'
@@ -66,13 +66,13 @@ def test_project_inventory_candidate_facts_reads_current_structured_set(app):
with app.app_context():
task = _task('SN-CAND-002')
candidate_set = _candidate_set(task, version=2)
source = ShippingInventoryCandidateSource(
source = ShippingOnhandCandidateSource(
candidate_set_id=int(candidate_set.id),
source_code='DBS_DUB',
candidate_order=1,
candidate_origin='rule',
)
line = ShippingInventoryCandidateLine(
line = ShippingOnhandCandidateLine(
candidate_set_id=int(candidate_set.id),
line_no=1,
source_line_no='00010',
@@ -99,14 +99,14 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
with app.app_context():
task = _task('SN-CAND-003')
old_set = _candidate_set(task, version=1)
old_line = ShippingInventoryCandidateLine(
old_line = ShippingOnhandCandidateLine(
candidate_set_id=int(old_set.id),
line_no=1,
source_codes_json=['DBS_OLD'],
)
db.session.add(old_line)
db.session.flush()
new_set = ShippingInventoryCandidateSet(
new_set = ShippingOnhandCandidateSet(
task_id=int(task.id),
set_version=2,
lifecycle_status='frozen',
@@ -116,7 +116,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
db.session.flush()
task.active_inventory_candidate_set_id = int(new_set.id)
db.session.flush()
new_line = ShippingInventoryCandidateLine(
new_line = ShippingOnhandCandidateLine(
candidate_set_id=int(new_set.id),
line_no=1,
source_codes_json=['DBS_NEW'],
@@ -132,7 +132,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
db.session.add(ShippingNoticeLineOnhandMatch(
task_id=int(task.id),
snapshot_line_id=int(snapshot_line.id),
line_no=1,
@@ -141,8 +141,8 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
candidate_set_version=1,
candidate_line_id=int(old_line.id),
match_result='matched',
inventory_status='ready',
inventory_source_code='DBS_OLD',
onhand_status='ready',
source_code='DBS_OLD',
is_current=True,
allowed_source_codes_snapshot=['DBS_OLD'],
detail_json={'disposition': 'ok'},
@@ -161,12 +161,12 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
with app.app_context():
task = _task('SN-CAND-EVIDENCE')
candidate_set = _candidate_set(task)
db.session.add(ShippingInventoryCandidateLine(
db.session.add(ShippingOnhandCandidateLine(
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
))
db.session.flush()
inventory_file = ShippingInventoryFile(
inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
inventory_file = FreightRpaOnhandReportFile(
onhand_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64,
)
db.session.add(inventory_file)
@@ -180,11 +180,11 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
db.session.add(ShippingNoticeLineOnhandMatch(
task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1,
candidate_set_id=int(candidate_set.id),
candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched',
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no,
candidate_set_version=1, onhand_snapshot_id=int(inventory_file.id), match_result='matched',
onhand_status='ready', source_code='DBS_DUB', matched_file_no=inventory_file.onhand_file_no,
matched_row_index=9, is_current=True, detail_json={},
))
db.session.commit()
@@ -0,0 +1,791 @@
"""tests/services/shipping_notice/test_onhand_report_handler.py
用途:阶段 B Task 7 修复轮——onhand 报表事实投递接线与处理函数契约测试:
单回调/批量 worker 在文件行 commit 后投递事实(先 commit 再投递、处理函数
失败外抛且文件行保留)、success 事实 settle 等待中的候选准备并同步门禁
(处理函数自行 commit、重放不重复候选行)、失败事实不发明候选行;
修复轮 2 补批量契约:单文件处理函数失败不跳过其余文件投递与排程收口、
Job 意外异常 requeue 可重试;修复轮 3 补:失败点回滚半途写(不被后续
commit 持久化)、drop 文件清理先于错误外抛、Job 重试「只重投失败文件」
通道(callback_id 已消费拦不住重投、未完成绝不返回 ok)。
依赖:app(SQLite)fixture、freight_rpa.reports.dispatch / facts、
freight_rpa.onhand.report_store(候选 settle 所绑文件行的唯一插入入口)、
onhand_rpa_workflow(回调入口 + 重试通道/专用异常)、onhand_recovery_service
(候选准备表)、jobs.handlers.freight_rpa_onhand_callback_process(Job 收口)。
逻辑:直接处理函数用例以 monkeypatch 替身 gate 同步记录调用(不断言 Gate 全链);
e2e 投递用例复用 test_shipping_notice_inventory_rpa_workflow 的动态订单/
客户确认/库存源种子 harness,跑通 rpa_report_inventory /
process_rpa_report_inventory_batch 全程后在注册表注入记录器断言事实字段;
批量失败用例以替身 finalize 记录收口调用(内部预存在 NameError 与本契约无关)。
"""
from __future__ import annotations
import pytest
from tests.conftest import inventory_xlsx_with_warehouse
@pytest.fixture
def db_session(app):
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
@pytest.fixture(autouse=True)
def _fake_gate_sync(monkeypatch):
"""替身门禁同步:记录 (execution_id) 调用序列,不跑 Gate 全链(聚焦候选/提交契约)。"""
calls: list[int] = []
def _record(**kwargs):
calls.append(int(kwargs['execution'].id))
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
_record,
)
return calls
def _seed_waiting_preparation(db_session, *, task_no: str, execution_no: str):
"""构造「任务 + 活动执行 + 等待中候选准备轮次(waiting SourceAttempt)」。
Returns:
(task, execution, preparation, source_row) 四元组。
"""
from app.models import (
ShippingOnhandPreparationAttempt,
ShippingOnhandPreparationSourceAttempt,
ShippingOrderTask,
ShippingProcessExecution,
)
task = ShippingOrderTask(
task_no=task_no, user_id=1, source_type='direct_pdf', status='ready',
)
db_session.add(task)
db_session.flush()
execution = ShippingProcessExecution(
execution_no=execution_no, task_id=task.id, status='active',
)
db_session.add(execution)
db_session.flush()
task.active_process_execution_id = execution.id
preparation = ShippingOnhandPreparationAttempt(
task_id=task.id, attempt_no=1, status='waiting_external',
)
db_session.add(preparation)
db_session.flush()
source_row = ShippingOnhandPreparationSourceAttempt(
preparation_attempt_id=preparation.id, source_code='DSV360_AWSDU', status='waiting',
)
db_session.add(source_row)
db_session.commit()
return task, execution, preparation, source_row
def _onhand_file_id(*, source_code: str = 'DSV360_AWSDU') -> int:
"""经唯一插入入口 report_store 落一行 ready onhand 报表文件并 commit,返回 file_id。"""
from app import db
from app.services.freight_rpa.onhand.report_store import insert_onhand_report
from app.services.shipping_notice.onhand_file_store import generate_inventory_file_no
file_id = insert_onhand_report(
onhand_file_no=generate_inventory_file_no(),
storage_path='handler://onhand-report-fact.xlsx',
source_code=source_code,
snapshot_status='ready',
file_sha256='a' * 64,
)
db.session.commit()
return file_id
def test_onhand_fact_settles_waiting_candidates_and_syncs_gates(app, db_session, _fake_gate_sync):
"""success 事实:settle 等待候选(ready + 绑文件)→ 聚合准备轮次 → 门禁同步 → 自行 commit。"""
from app.models import ShippingOnhandPreparationAttempt, ShippingOnhandPreparationSourceAttempt
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
task, execution, preparation, source_row = _seed_waiting_preparation(
db_session, task_no='OT-ONHAND-FACT-SETTLE', execution_no='EX-ONHAND-FACT-SETTLE',
)
file_id = _onhand_file_id()
handle_onhand_report(ReportFact(
report_kind='onhand', source_code='DSV360_AWSDU',
file_id=file_id, sha256='a' * 64, ok=True,
))
# [断言意图] 处理函数必须自行 commit:rollback + expire_all 后 settle 仍可见。
db_session.rollback()
db_session.expire_all()
refreshed_source = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
assert refreshed_source.status == 'ready'
assert refreshed_source.onhand_file_id == file_id
refreshed_prep = db_session.get(ShippingOnhandPreparationAttempt, preparation.id)
assert refreshed_prep.status == 'succeeded'
assert refreshed_prep.completed_at is not None
# [断言意图] 门禁同步覆盖 settle 受影响的准备轮次任务(execution 绑定同任务)。
assert _fake_gate_sync == [execution.id]
# [重放] 同一事实重复投递:等待集已空——不重复 settle、不重复候选行(幂等)。
handle_onhand_report(ReportFact(
report_kind='onhand', source_code='DSV360_AWSDU',
file_id=file_id, sha256='a' * 64, ok=True,
))
db_session.rollback()
db_session.expire_all()
assert ShippingOnhandPreparationSourceAttempt.query.count() == 1
assert db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id).onhand_file_id == file_id
assert db_session.get(ShippingOnhandPreparationAttempt, preparation.id).status == 'succeeded'
def test_onhand_failure_fact_invents_no_candidate_rows(app, db_session, _fake_gate_sync):
"""失败/空事实:无文件可挂——不发明候选行(SourceAttempt 保持 waiting、不绑文件),仅重投影门禁。"""
from app.models import ShippingOnhandPreparationSourceAttempt
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
task, execution, preparation, source_row = _seed_waiting_preparation(
db_session, task_no='OT-ONHAND-FACT-FAIL', execution_no='EX-ONHAND-FACT-FAIL',
)
handle_onhand_report(ReportFact(
report_kind='onhand', source_code='DSV360_AWSDU',
file_id=None, sha256=None, ok=False,
error_code='rpa_export_failed', error_message='boom',
))
db_session.rollback()
db_session.expire_all()
# [断言意图] 失败事实没有文件身份:不得发明/改写候选行——仍是唯一一行、
# 状态保持 waiting、未绑定任何文件;门禁重投影(失败路径门禁更新归处理函数)。
assert ShippingOnhandPreparationSourceAttempt.query.count() == 1
refreshed = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
assert refreshed.status == 'waiting'
assert refreshed.onhand_file_id is None
assert _fake_gate_sync == [execution.id]
def _seed_direct_rpa_task(db, *, task_no: str, run_no: str, sample) -> None:
"""复用动态订单 harness:直建 OT + 动态订单 + 客户确认 + 库存源种子 + RPA 触发种子。"""
from app.models import ShippingOrderTask
from tests.conftest import seed_rpa_inventory_trigger, seed_task_inventory_source
from tests.test_shipping_notice_inventory_rpa_workflow import (
_attach_dynamic_order,
_confirm_direct_rpa_task_customer,
)
task = ShippingOrderTask(
task_no=task_no, 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='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
seed_rpa_inventory_trigger(task, run_no=run_no)
db.session.add(task)
db.session.commit()
def _stub_structure_validation(monkeypatch):
"""替身结构校验:onhand_structure_drift 仍读已删站点列(Task 2 已记录的 deferred
minor,legacy 套件待 s18 改写)——与本修复无关;本测试聚焦 commit 后投递接线。
返回与真实 validate_production_inventory_structure 同形状的确定性解析参数:
field_mapping 用 conftest 种子字段 ID 对齐样例 xlsx 列头
(Warehouse ID / SKU / Reservation ID / Qty,表头行 1,默认 sheet)。
"""
from app.models import FreightRpaOnhandField
fields = {
row.field_code: row
for row in FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.field_code.in_(
['part_number', 'reservation_id', 'available_qty', 'warehouse_id'],
)
)
}
structure_check = {
'field_mapping': {
str(fields['part_number'].id): 'SKU',
str(fields['reservation_id'].id): 'Reservation ID',
str(fields['available_qty'].id): 'Qty',
str(fields['warehouse_id'].id): 'Warehouse ID',
},
'header_row_index': 1,
'sheet_name': 'Sheet',
'level': 'exact',
'difference': {},
'warnings': [],
}
monkeypatch.setattr(
'app.services.shipping_notice.onhand_structure_drift.validate_production_inventory_structure',
lambda **_kwargs: structure_check,
)
def test_single_callback_dispatches_onhand_fact_after_file_commit(app, tmp_path, monkeypatch):
"""rpa_report_inventory:文件行 commit 后同请求投递 onhand 事实,字段与已提交行对齐。"""
from app import db
from app.models import FreightRpaOnhandReportFile
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory
from tests.conftest import rpa_callback_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'onhand-fact.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
seen: list[ReportFact] = []
register_report_handler('onhand', seen.append)
with app.app_context():
from app.models import ShippingOrderTask
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-DISPATCH', run_no='RUN-ONHAND-FACT', sample=sample)
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-DISPATCH').one()
result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT'))
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='RUN-ONHAND-FACT', snapshot_status='ready',
).first()
assert snap is not None
assert result.get('status') == 'ok'
# [断言意图] commit 后投递:恰好一条事实、字段与已提交文件行逐项对齐。
assert len(seen) == 1
fact = seen[0]
assert fact.report_kind == 'onhand'
assert fact.ok is True
assert fact.file_id == snap.id
assert fact.source_code == 'DSV360_AWSDU'
assert fact.sha256 == snap.file_sha256
# 文件行已提交:rollback 后重查仍在(先 commit 再投递的顺序契约)。
db.session.rollback()
db.session.expire_all()
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
def test_single_callback_handler_failure_propagates_and_keeps_file_row(app, tmp_path, monkeypatch):
"""处理函数抛错:异常原样外抛(不折进 post_commit_warnings),已提交文件行保留。"""
from app import db
from app.models import FreightRpaOnhandReportFile, ShippingOrderTask
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory
from tests.conftest import rpa_callback_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'onhand-fact-fail.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
def boom(_fact) -> None:
raise RuntimeError('onhand handler down')
register_report_handler('onhand', boom)
with app.app_context():
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-RAISE', run_no='RUN-ONHAND-FACT-RAISE', sample=sample)
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-RAISE').one()
# [断言意图] 异常必须外抛(供 Worker 重试整笔回调),绝不折进 warnings 后返回 ok。
with pytest.raises(RuntimeError, match='onhand handler down'):
rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT-RAISE'))
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='RUN-ONHAND-FACT-RAISE', snapshot_status='ready',
).first()
assert snap is not None
db.session.rollback()
db.session.expire_all()
# [断言意图] 处理函数失败不回滚已提交文件行。
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
def test_batch_worker_dispatches_onhand_fact_after_commit(app, tmp_path, monkeypatch):
"""process_rpa_report_inventory_batch:整批事务 commit 后逐文件投递 onhand 事实。"""
from app import db
from app.models import FreightRpaOnhandReportFile
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'onhand-fact-batch.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
seen: list[ReportFact] = []
register_report_handler('onhand', seen.append)
with app.app_context():
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-BATCH', run_no='RUN-ONHAND-FACT-BATCH', sample=sample)
task_no = 'OT-ONHAND-FACT-BATCH'
result = process_rpa_report_inventory_batch(v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-FACT-BATCH',
'trigger_type': 'on_demand',
'results': [scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample), task_no=task_no,
)],
}))
assert result.get('status') == 'ok'
assert result.get('data', {}).get('success_count') == 1
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='RUN-ONHAND-FACT-BATCH', snapshot_status='ready',
).first()
assert snap is not None
# [断言意图] 整批 commit 后逐文件投递:恰一条 ok=True 事实,file_id 对齐已提交行。
assert [fact.file_id for fact in seen] == [snap.id]
assert all(fact.report_kind == 'onhand' and fact.ok is True for fact in seen)
db.session.rollback()
db.session.expire_all()
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
def test_batch_handler_failure_does_not_skip_remaining_dispatch_or_finalize(app, tmp_path, monkeypatch):
"""批量内单文件处理函数失败:其余已提交文件仍投递、排程收口仍执行、错误仍外抛、文件行保留。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample_a = drop_dir / 'onhand-fact-batch-a.xlsx'
sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
sample_b = drop_dir / 'onhand-fact-batch-b.xlsx'
sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
# [断言意图·观测点] 排程收口必须仍被调用(内部预存在 NameError 与本契约无关)。
finalize_calls: list = []
monkeypatch.setattr(
'app.services.schedule.freight_rpa_onhand_finalize.finalize_shipping_inventory_schedule_run',
lambda schedule_run_id, **_kwargs: (
finalize_calls.append(schedule_run_id)
or {'ok': True, 'schedule_finalize_status': 'finalized'}
),
)
# [断言意图·观测点] 首个文件处理函数失败,第二个必须照常收到事实。
seen: list[ReportFact] = []
calls = {'n': 0}
def flaky(fact: ReportFact) -> None:
calls['n'] += 1
seen.append(fact)
if calls['n'] == 1:
raise RuntimeError('onhand handler down mid-batch')
register_report_handler('onhand', flaky)
with app.app_context():
_stub_structure_validation(monkeypatch)
task = ScheduleTask(
schedule_no='SCH-ONHAND-BATCH-FAIL', name='Onhand batch fail', schedule_type='platform_job',
platform_api_path='freight-rpa-onhand', owner_user_id=1, cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no='RUN-ONHAND-BATCH-FAIL', schedule_task_id=task.id, status='running',
total_count=2, success_count=0, failed_count=0, skipped_count=0,
response_summary_json={'awaiting_rpa': True},
)
db.session.add(run)
db.session.commit()
# [断言意图] 处理函数异常必须外抛(调用方/Job 见到失败)——但不得因此跳过
# 其余文件投递与排程收口(断言在 pytest.raises 之后进行)。
with pytest.raises(RuntimeError, match='onhand handler down mid-batch'):
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-BATCH-FAIL',
'schedule_run_id': run.id,
'trigger_type': 'scheduled',
'results': [
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-BATCH-FAIL-A',
),
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-BATCH-FAIL-B',
),
],
}))
snaps = FreightRpaOnhandReportFile.query.filter(
FreightRpaOnhandReportFile.snapshot_status == 'ready',
FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B')),
).order_by(FreightRpaOnhandReportFile.id).all()
# [断言意图] 两个文件行都已落库并保留(commit 先于投递,失败不回滚)。
assert [snap.rpa_run_no for snap in snaps] == ['SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B']
# [断言意图] 两个文件的事实都投递了(首文件失败不跳过次文件投递)。
assert [fact.file_id for fact in seen] == [snap.id for snap in snaps]
# [断言意图] 排程收口仍执行(不被处理函数失败跳过)。
assert finalize_calls == [run.id]
db.session.rollback()
db.session.expire_all()
assert {db.session.get(FreightRpaOnhandReportFile, snap.id) is not None for snap in snaps} == {True}
def test_callback_process_job_requeues_on_unexpected_exception(app, monkeypatch):
"""Job 意外异常(含批量 commit 后处理函数失败重抛)必须可重试 requeue,而非终态 failed。"""
from app import db
from app.jobs.context import JobContext
from app.jobs.handlers import freight_rpa_onhand_callback_process as handler
from app.models import Job
with app.app_context():
job = Job(
domain='shipping_notice',
job_type='freight_rpa_onhand_callback_process',
status='running',
attempts=1,
max_attempts=3,
business_ref='inventory-callback:retryable-check',
payload_json={'callback_id': 'retryable-check'},
)
db.session.add(job)
db.session.commit()
def _boom(_payload):
raise RuntimeError('dispatch re-raise after commit')
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch',
_boom,
)
handler.run_shipping_inventory_callback_process(
JobContext(config={}, logger=None, extras={}), {'job_id': job.id},
)
db_session = db.session
db_session.expire_all()
# [断言意图] retryable=True → requeue(attempts 未耗尽时回到 queued 等待重试),
# 绝不落终态 failed——批量文件行已提交,重放按幂等契约补齐收口。
refreshed = db_session.get(Job, job.id)
assert refreshed.status == 'queued'
def test_batch_handler_failure_rolls_back_partial_writes_and_next_file_dispatches(app, db_session, tmp_path, monkeypatch):
"""批量内处理函数「先 bind 候选再抛错」:半途 flush 写必须回滚(不得被后续 commit 持久化),次文件照常投递。"""
from app import db
from app.models import FreightRpaOnhandReportFile, ShippingOnhandPreparationSourceAttempt
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample_a = drop_dir / 'rollback-a.xlsx'
sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
sample_b = drop_dir / 'rollback-b.xlsx'
sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
seen: list[ReportFact] = []
calls = {'n': 0}
def bind_then_raise_or_settle(fact: ReportFact) -> None:
calls['n'] += 1
seen.append(fact)
if calls['n'] == 1:
# [RED 场景] 模拟「先 bind 候选再抛错」的处理函数:半途 flush(不 commit)。
from app.models import ShippingOnhandPreparationSourceAttempt as _Row
row = (
_Row.query.filter_by(source_code='DSV360_AWSDU')
.order_by(_Row.id)
.first()
)
row.status = 'ready'
row.onhand_file_id = int(fact.file_id)
db.session.flush()
raise RuntimeError('bind then raise mid-batch')
# 次文件走真实处理函数:内部 settle(等待集)→ 门禁同步 → 自行 commit。
handle_onhand_report(fact)
register_report_handler('onhand', bind_then_raise_or_settle)
with app.app_context():
_stub_structure_validation(monkeypatch)
_task, _execution, _preparation, source_row = _seed_waiting_preparation(
db_session, task_no='OT-ONHAND-ROLLBACK', execution_no='EX-ONHAND-ROLLBACK',
)
with pytest.raises(RuntimeError, match='bind then raise mid-batch'):
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-ROLLBACK',
'trigger_type': 'on_demand',
'results': [
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-ROLLBACK-A',
),
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-ROLLBACK-B',
),
],
}))
snaps = FreightRpaOnhandReportFile.query.filter(
FreightRpaOnhandReportFile.snapshot_status == 'ready',
FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-ROLLBACK-A', 'SR-ROLLBACK-B')),
).order_by(FreightRpaOnhandReportFile.id).all()
# [断言意图] 次文件照常投递:两个已提交文件的事实都送达处理函数。
assert [fact.file_id for fact in seen] == [snap.id for snap in snaps]
db.session.rollback()
db.session.expire_all()
# [断言意图] 首文件半途 bind 已回滚——不得被次文件处理函数的 commit 持久化成
# file-A 绑定;次文件真实 settle 落到 file B(等待集在回滚后原样可 settle)。
refreshed = db.session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
assert refreshed.status == 'ready'
assert refreshed.onhand_file_id == snaps[1].id
def test_batch_handler_failure_still_flushes_drop_file_cleanup_before_raise(app, tmp_path, monkeypatch):
"""处理函数抛错:drop 文件清理(消费标记+移动/入队)必须先于错误外抛完成。"""
from app import db
from app.models import FreightRpaOnhandReportFile
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'cleanup-before-raise.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
def boom(_fact) -> None:
raise RuntimeError('onhand handler down cleanup')
register_report_handler('onhand', boom)
with app.app_context():
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-CLEANUP', run_no='RUN-ONHAND-CLEANUP', sample=sample)
with pytest.raises(RuntimeError, match='onhand handler down cleanup'):
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-CLEANUP',
'trigger_type': 'on_demand',
'results': [scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-CLEANUP',
)],
}))
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='RUN-ONHAND-CLEANUP', snapshot_status='ready',
).first()
assert snap is not None
# [断言意图] 错误已外抛,但 drop 文件清理先行完成:消费标记/移动先于重抛,
# 文件离开 drop 根、落入 processed 归档(移动失败时则入持久化 cleanup 队列)。
assert not sample.exists()
assert (drop_dir / 'processed' / sample.name).exists()
def test_batch_retry_channel_redispatches_file_despite_consumed_callback_id(app, tmp_path, monkeypatch):
"""重试通道:task-linked 项 Attempt 已消费 callback_id(整批重放必被跳过)时,失败文件仍重投事实。"""
from datetime import datetime
from app import db
from app.models import FreightRpaOnhandReportFile, ShippingOrderTask, FreightRpaOnhandTaskAttempt
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_rpa_workflow import (
OnhandReportDispatchAfterCommitError,
process_rpa_report_inventory_batch,
)
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'retry-callback-id.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
seen: list[ReportFact] = []
calls = {'n': 0}
def flaky(fact: ReportFact) -> None:
calls['n'] += 1
seen.append(fact)
if calls['n'] == 1:
raise RuntimeError('onhand handler down first pass')
register_report_handler('onhand', flaky)
with app.app_context():
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-RETRY', run_no='RUN-ONHAND-RETRY', sample=sample)
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-RETRY').one()
candidate_set_id = int(task.active_inventory_candidate_set_id or 1)
# [RED 场景] 结构化 per-source Attempt(v2 身份字段与回调 item 对齐):
# pass 1 的回调确认会把 attempt.callback_id 写入——整批重放随即被 replay 检查跳过。
# source_run_no 用与批量 run_no 不同的 PSR 轮次号(与真实 Worker 形态一致:
# run_no=批量轮次、source_run_no=逐源轮次——run_no 消费标记按 source_run_no
# 匹配,不会误吞本 Attempt)。
attempt = FreightRpaOnhandTaskAttempt(
task_no='OT-ONHAND-RETRY',
source_code='DSV360_AWSDU',
attempt_no=1,
source_run_no='PSR-ONHAND-RETRY-1',
status='queued',
triggered_at=datetime.utcnow(),
lease_token='test-lease-token',
execution_phase='trigger_written',
extra_json={
'trigger_mode': 'test',
'candidate_set_id': candidate_set_id,
'execution_id': 1,
'gate_id': 1,
},
)
db.session.add(attempt)
db.session.commit()
batch_payload = v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-RETRY',
'trigger_type': 'on_demand',
'results': [dict(
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-RETRY',
),
callback_id='test-callback:RUN-ONHAND-RETRY',
source_run_no='PSR-ONHAND-RETRY-1',
attempt_no=1,
lease_token='test-lease-token',
candidate_set_id=candidate_set_id,
execution_id=1,
gate_id=1,
)],
})
# [STEP 1] 首轮:文件落地+回调确认(写 callback_id)+投递失败 → 专用异常携带清单外抛。
with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo:
process_rpa_report_inventory_batch(batch_payload)
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='PSR-ONHAND-RETRY-1', snapshot_status='ready',
).first()
assert snap is not None
assert excinfo.value.failed_files == [{
'source_code': 'DSV360_AWSDU',
'file_id': snap.id,
'sha256': (snap.file_sha256 or None),
}]
# [断言意图·RED 场景] Attempt 已消费 callback_id——整批重放会被 replay 检查跳过。
db.session.expire(attempt)
assert str(attempt.callback_id or '').strip()
armed_callback_id = str(attempt.callback_id)
# [STEP 2] 整批重放(不带重试清单):item 被 replay 检查跳过——不落地、不投递,
# 证明整批重放无法补投(这正是「只重投失败文件」通道存在的原因)。
replay_result = process_rpa_report_inventory_batch(dict(batch_payload))
assert [fact.file_id for fact in seen] == [snap.id]
assert replay_result.get('data', {}).get('created') == []
assert armed_callback_id == str(
FreightRpaOnhandTaskAttempt.query.filter_by(
task_no='OT-ONHAND-RETRY', source_code='DSV360_AWSDU',
).order_by(FreightRpaOnhandTaskAttempt.id.desc()).first().callback_id or '',
)
# [STEP 3] 重试通道(Job 处理器写回的 retry_dispatch_files):只重投失败文件。
retry_payload = {**batch_payload, 'retry_dispatch_files': excinfo.value.failed_files}
result = process_rpa_report_inventory_batch(retry_payload)
assert result.get('status') == 'ok'
assert result.get('data', {}).get('result_status') == 'retried'
# [断言意图] 同一 file_id 的事实再次送达处理函数(callback_id 已消费拦不住重投)。
assert [fact.file_id for fact in seen] == [snap.id, snap.id]
def test_batch_retry_channel_reraises_while_handler_still_failing(app, monkeypatch):
"""重试通道:处理函数仍未成功时必须继续携带清单重抛,绝不在未完成时返回 ok。"""
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.shipping_notice.onhand_rpa_workflow import (
OnhandReportDispatchAfterCommitError,
process_rpa_report_inventory_batch,
)
def boom(_fact) -> None:
raise RuntimeError('onhand handler still down')
register_report_handler('onhand', boom)
with app.app_context():
file_id = _onhand_file_id()
marker = {'source_code': 'DSV360_AWSDU', 'file_id': file_id, 'sha256': None}
# [断言意图] 处理函数持续失败:重试通道继续抛专用异常(携带同一未成功清单,
# Job 据此继续 requeue 直至 attempts 耗尽落终态 failed)——绝不返回 ok。
with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo:
process_rpa_report_inventory_batch({'retry_dispatch_files': [marker]})
assert excinfo.value.failed_files == [marker]
def test_callback_process_job_records_failed_files_for_retry(app, monkeypatch):
"""Job 收口:投递失败重抛的清单写回 payload(retry_dispatch_files)并 requeue 可重试。"""
from app import db
from app.jobs.context import JobContext
from app.jobs.handlers import freight_rpa_onhand_callback_process as handler
from app.models import Job
from app.services.shipping_notice.onhand_rpa_workflow import OnhandReportDispatchAfterCommitError
marker = {'source_code': 'DSV360_AWSDU', 'file_id': 4242, 'sha256': 'a' * 64}
with app.app_context():
job = Job(
domain='shipping_notice',
job_type='freight_rpa_onhand_callback_process',
status='running',
attempts=1,
max_attempts=3,
business_ref='inventory-callback:dispatch-retry-check',
payload_json={'callback_id': 'dispatch-retry-check'},
)
db.session.add(job)
db.session.commit()
def _raise_dispatch_error(_payload):
raise OnhandReportDispatchAfterCommitError(
'onhand handler down after commit', failed_files=[dict(marker)],
)
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch',
_raise_dispatch_error,
)
handler.run_shipping_inventory_callback_process(
JobContext(config={}, logger=None, extras={}), {'job_id': job.id},
)
db.session.expire_all()
# [断言意图] 清单写回 payload(重试只重投这些文件)+ requeue 可重试。
refreshed = db.session.get(Job, job.id)
assert refreshed.status == 'queued'
assert refreshed.payload_json['retry_dispatch_files'] == [marker]
@@ -418,7 +418,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta
facts = _project_case_formal_gate_facts({
'current_gate': {
'gate_code': 'inventory_source_routing',
'gate_code': 'onhand_source_routing',
'status': 'pending',
'blocking_reason_code': None,
'next_action_code': None,
@@ -430,7 +430,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta
assert facts is not None
current_gate, blocking_reason, user_status = facts
assert current_gate['gate_code'] == 'inventory_source_routing'
assert current_gate['gate_code'] == 'onhand_source_routing'
assert blocking_reason['code'] is None
assert user_status == 'running'
@@ -0,0 +1,32 @@
"""
tests/services/shipping_notice/test_report_model_boundary.py
用途:阶段 B Task 5 边界门禁——禁止发货域(shipping_notice)源码直接构造
货代 RPA 报表模型行(FreightRpaOnhandReportFile / FreightRpaInboundReportFile /
FreightRpaInboundReportConfig 的构造调用)。插入必须经
freight_rpa/onhand/report_store,读取/下载必须走 freight_rpa/reports 查询面。
依赖:无运行时依赖(纯文件系统扫描);backend/app/services/shipping_notice 源码。
逻辑:rglob 全部 *.py 逐文件搜禁词构造片段;命中即失败并列出文件与片段,
保证违规时能一眼定位,而不是只报一个计数。
"""
from __future__ import annotations
from pathlib import Path
import pytest
pytestmark = pytest.mark.pure_unit
def test_shipping_notice_does_not_construct_rpa_report_rows():
root = Path(__file__).resolve().parents[3] / "app" / "services" / "shipping_notice"
banned_snippets = ("FreightRpaOnhandReportFile(", "FreightRpaInboundReportFile(", "FreightRpaInboundReportConfig(")
hits = []
for path in root.rglob("*.py"):
text = path.read_text(encoding="utf-8")
for snippet in banned_snippets:
if snippet in text:
hits.append(f"{path.name}: {snippet}")
# 关键断言:三类 RPA 报表行的构造调用必须全部消失(插入已收敛进 report_store)。
assert hits == []