feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务

- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
This commit is contained in:
hugo committed 2026-10-19 18:45:16 +08:00
1 parent 39fe3c05f2
commit 911afa0f73
152 files changed
+9861 -2984

No files matched your search

+5 -5
View File
@@ -212,7 +212,7 @@ def test_onhand_repair_envelope_matches_legacy(client, tool_auth_headers):
# ---------------------------------------------------------------------------
def test_inbound_unit_progress_envelope_matches_legacy(client, tool_auth_headers):
"""inbound-unit-progress(旧直连 jsonify({'success':True,'data':mark_receipt_unit_processing(p)})):
"""inbound-unit-progress(旧直连 jsonify({'success':True,'data':mark_inbound_unit_processing(p)})):
schema 非法分支 data={'updated':False,'reason':'callback_schema_invalid'},证明 sink 已注册
(未注册会是 404 FREIGHT_RPA.SINK_NOT_REGISTERED)且 envelope 未漂移。"""
resp = client.post("/api/freight-rpa/inbound-unit-progress", json={}, headers=tool_auth_headers)
@@ -235,17 +235,17 @@ def test_inbound_batch_progress_envelope_matches_legacy(client, tool_auth_header
def test_inbound_batch_ready_schema_invalid_reaches_business_validation(client, tool_auth_headers):
"""inbound-batch-ready sink 已注册:schema 非法穿透到业务校验(400 +
SHIPPING.RECEIPT_CALLBACK_INVALID),而非未注册 404;错误 envelope 与拆分前同形
SHIPPING.INBOUND_CALLBACK_INVALID),而非未注册 404;错误 envelope 与拆分前同形
(旧端点在 jsonify 之前由 ingest 抛 ValidationError → 全局 AppError handler)。"""
resp = client.post("/api/freight-rpa/inbound-batch-ready", json={}, headers=tool_auth_headers)
assert resp.status_code == 400
body = resp.get_json()
assert body["success"] is False
assert body["error"]["code"] == "SHIPPING.RECEIPT_CALLBACK_INVALID"
assert body["error"]["code"] == "SHIPPING.INBOUND_CALLBACK_INVALID"
def test_inbound_batch_ready_unknown_unit_is_404(client, tool_auth_headers):
"""inbound-batch-ready 未知 callback_id:404 + SHIPPING.RECEIPT_UNIT_NOT_FOUND,
"""inbound-batch-ready 未知 callback_id:404 + SHIPPING.INBOUND_UNIT_NOT_FOUND,
与拆分前 ingest 直连时的 NotFoundError 路径逐字一致。"""
resp = client.post(
"/api/freight-rpa/inbound-batch-ready",
@@ -254,7 +254,7 @@ def test_inbound_batch_ready_unknown_unit_is_404(client, tool_auth_headers):
)
assert resp.status_code == 404
body = resp.get_json()
assert body["error"]["code"] == "SHIPPING.RECEIPT_UNIT_NOT_FOUND"
assert body["error"]["code"] == "SHIPPING.INBOUND_UNIT_NOT_FOUND"
@pytest.mark.pure_unit
@@ -2,7 +2,7 @@
tests/services/admin/test_shipping_inventory_service.py
用途:验证库存主数据管理服务的安全性和关键业务约束。
依赖:Flask app/db、shipping_onhand_admin_service、库存配置模型。
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
"""
@@ -12,8 +12,8 @@ from cryptography.fernet import Fernet
import pytest
from app.core.errors import ConflictError, ValidationError
from app.services.admin import shipping_onhand_admin_service
from app.services.shipping_notice import onhand_parsing_profile
from app.services.admin import freight_rpa_source_admin_service, shipping_onhand_admin_service
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service
from app import db
from app.models import (
@@ -164,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_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
payload = freight_rpa_source_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
@@ -178,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_onhand_admin_service.save_profile(payload, actor_id=None)
freight_rpa_source_admin_service.save_profile(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_CONFIG_INVALID'
@@ -186,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_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)
first = freight_rpa_source_admin_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
second = freight_rpa_source_admin_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
first_source = freight_rpa_source_admin_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None)
second_source = freight_rpa_source_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']
@@ -198,9 +198,9 @@ 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_onhand_admin_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH'
@@ -208,18 +208,18 @@ 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_onhand_admin_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
login = freight_rpa_source_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, 'excel_template_id': None})
payload['onhand_report_config']['parsing_profile_id'] = None
draft = shipping_onhand_admin_service.save_source(payload, actor_id=None)
draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None)
assert draft['enabled'] is False
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_onhand_admin_service.save_source(payload, actor_id=None, source_id=draft['id'])
freight_rpa_source_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。
@@ -227,7 +227,7 @@ def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
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'])
enabled = freight_rpa_source_admin_service.save_source(payload, actor_id=None, source_id=draft['id'])
assert enabled['enabled'] is True
@@ -235,22 +235,22 @@ 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_onhand_admin_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
login = freight_rpa_source_admin_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='ACTIVATION_SOURCE')
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)
draft = freight_rpa_source_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_onhand_admin_service.save_source(
saved = freight_rpa_source_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_onhand_admin_service.activate_source(draft['id'], actor_id=None)
freight_rpa_source_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']
@@ -259,7 +259,7 @@ 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_onhand_admin_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
login = freight_rpa_source_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'], 'excel_template_id': None,
@@ -275,7 +275,7 @@ def test_activation_status_exposes_only_hard_gate_checks(app):
},
'enabled': False,
}
draft = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
checks = {item['code']: item for item in draft['activation']['checks']}
@@ -292,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_onhand_admin_service.save_profile(
profile = freight_rpa_source_admin_service.save_profile(
{**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None,
)
with pytest.raises(ValidationError) as exc_info:
shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None)
freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None)
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLED'
@@ -304,8 +304,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_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'] == [
@@ -317,11 +317,11 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
payload = _source_data(profile['id'])
payload['onhand_report_config']['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
with pytest.raises(ValidationError) as exc_info:
shipping_onhand_admin_service.save_source(payload, actor_id=None)
freight_rpa_source_admin_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID'
@@ -329,12 +329,12 @@ 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_onhand_admin_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
profile = freight_rpa_source_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_onhand_admin_service.save_source(payload, actor_id=None)
freight_rpa_source_admin_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID'
@@ -342,14 +342,14 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a
"""停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_onhand_admin_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
login = freight_rpa_source_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})
payload['onhand_report_config']['parsing_profile_id'] = None
source = shipping_onhand_admin_service.save_source(payload, actor_id=7, allow_enable_transition=False)
source = freight_rpa_source_admin_service.save_source(payload, actor_id=7, allow_enable_transition=False)
profile = _parsing_profile()
bound = shipping_onhand_admin_service.bind_source_parsing_profile(
bound = freight_rpa_source_admin_service.bind_source_parsing_profile(
[source['id']], profile['id'], actor_id=7, operation='direct',
)
@@ -364,7 +364,7 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a
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_onhand_admin_service.get_source_parsing_binding_audits(source['id'])
history = freight_rpa_source_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']
@@ -373,15 +373,15 @@ 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_onhand_admin_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
login = freight_rpa_source_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})
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)
disabled = freight_rpa_source_admin_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False)
enabled = freight_rpa_source_admin_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None)
profile = _parsing_profile()
bound = shipping_onhand_admin_service.bind_source_parsing_profile(
bound = freight_rpa_source_admin_service.bind_source_parsing_profile(
[disabled['id'], enabled['id']], profile['id'], actor_id=None,
reason='批量迁移同类报表', operation='bulk',
)
@@ -398,11 +398,11 @@ 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_onhand_admin_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
login = freight_rpa_source_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})
payload['onhand_report_config']['parsing_profile_id'] = None
source = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
source = freight_rpa_source_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',
@@ -411,7 +411,7 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app
db.session.commit()
with pytest.raises(ValidationError) as exc_info:
shipping_onhand_admin_service.bind_source_parsing_profile(
freight_rpa_source_admin_service.bind_source_parsing_profile(
[source['id']], _parsing_profile()['id'], actor_id=None,
reason='模板字段契约预检', operation='direct',
)
@@ -427,8 +427,8 @@ 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_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)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
reservation_field_id = _published_route_field_id()
rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Reservation starts with 1', 'scope': 'line',
@@ -489,17 +489,17 @@ 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_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())
unused = freight_rpa_source_admin_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
freight_rpa_source_admin_service.delete_profile(unused['id'])
assert all(item['profile_code'] != 'UNUSED' for item in freight_rpa_source_admin_service.list_profiles())
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)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
with pytest.raises(ConflictError) as exc_info:
shipping_onhand_admin_service.delete_profile(profile['id'])
freight_rpa_source_admin_service.delete_profile(profile['id'])
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DELETE_BLOCKED'
with pytest.raises(ConflictError) as exc_info:
shipping_onhand_admin_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id'])
freight_rpa_source_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()
@@ -520,12 +520,12 @@ 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_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)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
source = freight_rpa_source_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, 'excel_template_id': None})
disabled_payload['onhand_report_config']['parsing_profile_id'] = None
shipping_onhand_admin_service.save_source(disabled_payload, actor_id=None)
freight_rpa_source_admin_service.save_source(disabled_payload, actor_id=None)
reservation_field_id = _published_route_field_id()
missing_rule = shipping_onhand_admin_service.save_rule({
@@ -556,8 +556,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
payload = {
'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
'external_organization_code': None, 'external_site_code': 'EU01',
@@ -573,8 +573,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
# [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。
mapping = shipping_onhand_admin_service.save_external_mapping({
'source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
@@ -589,8 +589,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
# [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。
with pytest.raises(ValidationError):
shipping_onhand_admin_service.save_external_mapping({
@@ -603,8 +603,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_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',
@@ -617,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_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
profile = freight_rpa_source_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_onhand_admin_service.save_profile(
updated = freight_rpa_source_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_onhand_admin_service.save_profile(
bumped = freight_rpa_source_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_onhand_admin_service.save_profile(
freight_rpa_source_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_onhand_admin_service.save_profile(
freight_rpa_source_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'],
)
@@ -0,0 +1,16 @@
"""
tests/services/freight_rpa/test_outbound_trigger_contract.py
用途:出站 RPA trigger_io 与 Worker 心跳能力串的契约常量回归。
依赖:freight_rpa.outbound.trigger_io、worker_heartbeat.OUTBOUND_EXPORT_CAPABILITY。
逻辑:Task 7 接口清单的单一真相,防止 schema/action/能力名漂移。
"""
from app.services.freight_rpa.outbound import trigger_io
from app.services.freight_rpa.common.worker_heartbeat import OUTBOUND_EXPORT_CAPABILITY
def test_outbound_trigger_constants():
"""出站 trigger schema/action 与 Worker outbound_export 能力须与设计 spec 一致。"""
assert trigger_io.SCHEMA == "freight_rpa.outbound.v1"
assert trigger_io.ACTION_OUTBOUND_EXPORT_BATCH == "outbound_export_batch"
assert OUTBOUND_EXPORT_CAPABILITY == "outbound_export"
@@ -179,18 +179,18 @@ def test_empty_callback_dispatches_failure_fact(app, db_session):
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "empty",
"error_code": "no_receipt_data",
"error_message": "no_receipt_data",
"error_code": "no_inbound_data",
"error_message": "no_inbound_data",
}
)
assert result["status"] == "empty"
assert len(seen) == 1
fact = seen[0]
# [断言意图] empty 是合法业务结果 → ok=False + error_code=no_receipt_data 的事实。
# [断言意图] empty 是合法业务结果 → ok=False + error_code=no_inbound_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"
assert fact.error_code == "no_inbound_data"
assert fact.error_message == "no_inbound_data"
@@ -202,13 +202,13 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path
assert (exc_info.value.details or {}).get("detail_message")
def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
def test_assert_inbound_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
"""收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。"""
from app.core.errors import ServiceUnavailableError
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_receipt_rpa_worker_ready,
assert_inbound_rpa_worker_ready,
reset_rpa_worker_heartbeat_state_for_tests,
)
@@ -224,7 +224,7 @@ def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path,
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
assert_receipt_rpa_worker_ready()
assert_inbound_rpa_worker_ready()
# [断言意图] 与库存同构的用户可见文案与 reasons;缺哨兵与无心跳同时暴露,
# 对应部署侧必须由 ps1 注入 FREIGHT_RPA_SHARED_SCOPE_ID 写哨兵。
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
@@ -502,7 +502,7 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
"""收料 ready 与库存同口径:要求共享哨兵;仅有库存 Worker 不能冒充收料在线。"""
from app.services.freight_rpa.common.worker_heartbeat import (
check_receipt_rpa_worker_ready,
check_inbound_rpa_worker_ready,
reset_rpa_worker_heartbeat_state_for_tests,
serialize_rpa_worker_status,
)
@@ -528,7 +528,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
trigger_dir=str(inventory_trigger),
shared_scope_id="hxops-rpa-test-data",
))
receipt_offline = check_receipt_rpa_worker_ready()
receipt_offline = check_inbound_rpa_worker_ready()
assert receipt_offline.ready is False
assert receipt_offline.workers == []
@@ -539,11 +539,11 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
shared_scope_id="hxops-rpa-test-data",
capabilities=[INBOUND_EXPORT_CAPABILITY],
))
without_sentinel = check_receipt_rpa_worker_ready()
without_sentinel = check_inbound_rpa_worker_ready()
assert without_sentinel.ready is False
_write_shared_sentinel(receipt_trigger, scope_id="hxops-rpa-test-data")
receipt_ready = check_receipt_rpa_worker_ready()
receipt_ready = check_inbound_rpa_worker_ready()
assert receipt_ready.ready is True
assert [w["worker_id"] for w in receipt_ready.workers] == ["HOST-receipt"]
@@ -557,7 +557,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tmp_path):
"""未注入 *-receipt 身份时,仍可用收料 trigger_dir 识别在线收料 Worker。"""
from app.services.freight_rpa.common.worker_heartbeat import (
check_receipt_rpa_worker_ready,
check_inbound_rpa_worker_ready,
reset_rpa_worker_heartbeat_state_for_tests,
)
@@ -579,6 +579,6 @@ def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tm
shared_scope_id="",
capabilities=[INBOUND_EXPORT_CAPABILITY],
))
result = check_receipt_rpa_worker_ready()
result = check_inbound_rpa_worker_ready()
assert result.ready is True
assert [w["worker_id"] for w in result.workers] == ["Hugo-30820"]
@@ -180,7 +180,7 @@ def test_no_waiting_job_is_success(app, db_session):
def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaiting: bool = True):
"""构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_receipt_rpa 等待态。"""
"""构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_inbound_rpa 等待态。"""
from app.models import ScheduleRun, ScheduleTask
task = ScheduleTask(
@@ -192,7 +192,7 @@ def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaitin
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},
response_summary_json={'awaiting_inbound_rpa': awaiting},
)
db_session.add(run)
db_session.commit()
@@ -218,7 +218,7 @@ def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session,
"""同来源两个单元分属两个排程 run:本回调收尾的单元(按文件反查)只收口它自己的 run。
[断言意图] 修复「按来源取最新单元」的错位:旧逻辑会把收口打到更新单元的 run,
本回调刚完成的 run 永久滞留 awaiting_receipt_rpa。
本回调刚完成的 run 永久滞留 awaiting_inbound_rpa。
"""
from app.models import ScheduleRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
@@ -254,18 +254,18 @@ def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session,
# [断言意图] 本回调收尾的是旧单元:只有旧 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")
assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_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
assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_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。
会收口新单元的 run,本回调刚失败的 run 永久滞留 awaiting_inbound_rpa。
"""
from datetime import datetime
@@ -310,11 +310,11 @@ def test_finalize_targets_failed_unit_of_this_callback_not_newest_unit(app, db_s
# [断言意图] 只有旧单元的 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")
assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_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
assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_rpa") is True
@@ -0,0 +1,316 @@
"""出站 RPA 触发服务与报表处理函数测试。
用途:验证 trigger_outbound_rpa / trigger_outbound_rpa_batch 按来源装配出站
trigger unit 并调用写者;站点停用 / 出站配置缺失 / 登录连接缺失 fail-closed;
handle_outbound_report 把等待中的 TransferSourceJob 从 waiting_rpa_callback
推进到 file_ready(无等待任务 no-op,可重入)。
依赖:app(SQLite)fixture、outbound_trigger_service、outbound_report_handler、
既有测试种子(FreightRpaProfile/FreightRpaSource)。
逻辑:对照 test_inbound_trigger_service;出站配置行挂 FreightRpaOutboundReportConfig;
写者协议与入站一致(payload= 附加字段);handler 只改调拨等待行,不写新状态。
"""
from __future__ import annotations
import pytest
from app.models import FreightRpaSource, FreightRpaOutboundReportConfig
from app.services.in_transit_transfer.outbound_trigger_service import (
trigger_outbound_rpa,
trigger_outbound_rpa_batch,
)
@pytest.fixture
def outbound_source():
"""复用种子来源并为其创建出站配置。"""
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
assert source is not None
config = FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'},
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
)
from app import db
db.session.add(config)
db.session.commit()
return source
def test_trigger_outbound_rpa_disabled_source_fails_closed(app):
"""来源停用 → ok=False,不写 trigger。"""
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
source.enabled = False
from app import db
db.session.commit()
result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_missing_config_fails_closed(app):
"""来源启用但无出站配置 → ok=False。"""
result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_missing_login_fails_closed(app, outbound_source):
"""出站配置存在但登录连接停用 → ok=False,不写 trigger。"""
from app import db
outbound_source.rpa_profile.enabled = False
db.session.commit()
result = trigger_outbound_rpa(
source_code='DSV360_AWSDU', business_date='2026-08-06',
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
)
assert result['ok'] is False
assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_writes_batch_trigger(app, outbound_source):
"""来源有效 → 写入 trigger 并返回 callback_id / trigger_path。"""
calls = {}
def fake_writer(run_no, units, payload=None):
calls['run_no'] = run_no
calls['units'] = units
calls['payload'] = payload or {}
return f'/tmp/trigger/{run_no}.json'
result = trigger_outbound_rpa(
source_code='DSV360_AWSDU', business_date='2026-08-06',
reason='transfer_retry_outbound', writer=fake_writer,
)
assert result['ok'] is True
assert result['callback_id']
assert result['trigger_path'].endswith('.json')
assert calls['units'][0]['source_code'] == 'DSV360_AWSDU'
assert calls['units'][0]['warehouse_id'] is None
assert calls['units'][0]['query_parameters_json'] == [
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
]
assert calls['units'][0]['credential_envelope']
assert calls['payload']['schema_version'] == 'freight_rpa.outbound.v1'
def test_trigger_outbound_rpa_creates_unit_run_before_writing_trigger(app, outbound_source):
"""触发必须先落 FreightRpaOutboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
from app.models import FreightRpaOutboundUnitRun
captured: dict = {}
def fake_writer(run_no, units, payload=None):
captured['units'] = units
return 'trigger.json'
outcome = trigger_outbound_rpa(
source_code=outbound_source.source_code, business_date='2026-10-19',
reason='transfer_retry_outbound', writer=fake_writer,
)
assert outcome['ok'] is True
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=outcome['callback_id']).one()
assert unit.status == 'awaiting_rpa'
assert unit.schedule_run_id is None
assert FreightRpaOutboundUnitRun.__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 test_trigger_outbound_rpa_marks_unit_failed_when_trigger_unavailable(app, outbound_source):
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
from app.models import FreightRpaOutboundUnitRun
outcome = trigger_outbound_rpa(
source_code=outbound_source.source_code, business_date='2026-10-19',
reason='transfer_retry_outbound', writer=lambda *a, **k: None,
)
assert outcome['ok'] is False
unit = FreightRpaOutboundUnitRun.query.filter_by(source_code=outbound_source.source_code).order_by(
FreightRpaOutboundUnitRun.id.desc()).first()
assert unit.status == 'failed'
assert unit.error_code == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
@pytest.fixture
def second_outbound_source(app):
"""再造一个启用来源 + 出站配置(批量用例需要多来源)。"""
from app import db
from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaOutboundReportConfig
seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
profile = FreightRpaProfile(
profile_code='DBS_SG_OUT_TEST', display_name='DBS SG Out', connector_type='dbs',
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
)
source = FreightRpaSource(
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
rpa_profile=profile,
excel_template=seed.excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
enabled=True,
)
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()
config = FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'},
query_parameters_json=[],
)
db.session.add(config)
db.session.commit()
return source
def test_trigger_outbound_rpa_batch_writes_one_trigger_for_all_units(app, outbound_source, second_outbound_source):
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
from app.models import FreightRpaOutboundUnitRun
calls: list = []
def fake_writer(run_no, units, payload=None):
calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}})
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19',
reason='transfer_retry_outbound', writer=fake_writer,
)
assert len(calls) == 1
assert outcome['ok'] is True and outcome['triggered'] is True
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
assert calls[0]['payload']['schema_version'] == 'freight_rpa.outbound.v1'
callback_ids = {u['callback_id'] for u in calls[0]['units']}
assert len(callback_ids) == 2
rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.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)
assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']}
def test_trigger_outbound_rpa_batch_skips_invalid_source(app, outbound_source):
"""单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。"""
captured: dict = {}
def fake_writer(run_no, units, payload=None):
captured['units'] = units
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-19',
writer=fake_writer,
)
assert outcome['ok'] is True and outcome['triggered'] is True
assert [u['source_code'] for u in captured['units']] == ['DSV360_AWSDU']
by_code = {item['source_code']: item for item in outcome['results']}
assert by_code['DSV360_AWSDU']['ok'] is True
assert by_code['DSV360_NOPE']['ok'] is False
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_batch_all_invalid_no_trigger(app):
"""全部来源无效 → 不写 trigger,ok=False + RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE。"""
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_NOPE'], business_date='2026-10-19',
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE'
def test_trigger_outbound_rpa_batch_writer_unavailable_marks_all_failed(app, outbound_source, second_outbound_source):
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
from app.models import FreightRpaOutboundUnitRun
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19',
writer=lambda *a, **k: None,
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.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_OUTBOUND_TRIGGER_UNAVAILABLE'}
def _waiting_job(source_code: str):
"""构造一个未落库的 waiting_rpa_callback 来源任务。"""
from app import db
from app.models import TransferRun, TransferSourceJob
run = TransferRun(
run_no=f'RUN-OUT-{source_code}',
business_date='2026-10-19',
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 test_handle_outbound_report_advances_waiting_job_to_file_ready(app):
"""ok 事实把等待中的 SourceJob 从 waiting_rpa_callback 推进到 file_ready。"""
from app import db
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
job = _waiting_job('DSV')
db.session.add(job)
db.session.commit()
handle_outbound_report(ReportFact(
report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True,
))
db.session.refresh(job)
assert job.status == 'file_ready'
assert job.file_no == '42'
assert job.file_sha256 == 'abc'
def test_handle_outbound_report_noop_without_waiting_job(app):
"""无等待中的调拨任务:处理函数 no-op,不产生任何调拨来源任务行。"""
from app.models import TransferSourceJob
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
handle_outbound_report(ReportFact(
report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True,
))
assert TransferSourceJob.query.filter_by(source_code='DSV').count() == 0
def test_handle_outbound_report_is_reentrant(app):
"""第二次投递时该行已离开等待态,不再改(可重入)。"""
from app import db
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
job = _waiting_job('DSV')
db.session.add(job)
db.session.commit()
fact = ReportFact(report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True)
handle_outbound_report(fact)
db.session.refresh(job)
first_finished = job.finished_at
handle_outbound_report(ReportFact(
report_kind='outbound', source_code='DSV', file_id=99, sha256='zzz', ok=True,
))
db.session.refresh(job)
assert job.status == 'file_ready'
assert job.file_no == '42'
assert job.file_sha256 == 'abc'
assert job.finished_at == first_finished
@@ -0,0 +1,51 @@
"""
tests/services/in_transit_transfer/test_rpa_sinks_ownership.py
用途:锁定入站/出站 sink 组合根归属——住在 in_transit_transfer,不在 shipping_notice;
inbound-batch-ready 直挂 freight_rpa 归档入口(无 shipping_notice Middle Man)。
"""
from __future__ import annotations
import importlib
import pytest
def test_shipping_notice_rpa_sinks_only_exposes_onhand_registration():
"""发货包只保留 onhand 注册入口,不再导出 inbound/outbound 注册。"""
sinks = importlib.import_module('app.services.shipping_notice.rpa_sinks')
assert hasattr(sinks, 'register_onhand_sinks')
assert not hasattr(sinks, 'register_inbound_sinks')
assert not hasattr(sinks, 'register_outbound_sinks')
def test_shipping_notice_inbound_report_storage_module_removed():
"""入站 Middle Man 模块已删除,生产与测试均直连 freight_rpa / 调拨处理函数。"""
with pytest.raises(ModuleNotFoundError):
importlib.import_module('app.services.shipping_notice.inbound_report_storage')
def test_register_inbound_sinks_binds_archive_and_transfer_handler(app):
"""register_inbound_sinks 把归档入口与调拨 handler 接到 inbound kinds。"""
from app.services.freight_rpa.common import callback_sinks
from app.services.freight_rpa.reports import dispatch as dispatch_module
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
from app.services.in_transit_transfer.rpa_sinks import register_inbound_sinks
dispatch_module._REPORT_HANDLERS.pop('inbound', None)
callback_sinks._SINKS.pop('inbound-batch-ready', None)
register_inbound_sinks()
assert dispatch_module._REPORT_HANDLERS.get('inbound') is handle_inbound_report
assert 'inbound-batch-ready' in callback_sinks._SINKS
def test_register_outbound_sinks_binds_outbound_handler(app):
"""register_outbound_sinks 把 handle_outbound_report 接到 outbound kind。"""
from app.services.freight_rpa.reports import dispatch as dispatch_module
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
from app.services.in_transit_transfer.rpa_sinks import register_outbound_sinks
dispatch_module._REPORT_HANDLERS.pop('outbound', None)
register_outbound_sinks()
assert dispatch_module._REPORT_HANDLERS.get('outbound') is handle_outbound_report
@@ -229,7 +229,7 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
"""
from app import db
from app.models import FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_inbound_units
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
@@ -244,6 +244,6 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'fetching'
# [断言意图] 回收扫描后投影必须翻转为 failed:这是前端重试门禁
# (file_status !== 'fetching')解锁的依据,也是本测试与事故的直接回归点。
assert recover_all_stale_orphan_receipt_units() == 1
assert recover_all_stale_orphan_inbound_units() == 1
db.session.expire_all()
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'failed'
@@ -3,8 +3,9 @@ tests/test_admin_freight_rpa_onhand_config.py
用途:锁定 s18 后库存站点启用门禁与在手报表配置行(FreightRpaOnhandReportConfig)的服务层行为。
依赖:conftest 的 app fixture(建表并播种 TEST_RUNTIME 配置)、app.core.errors.ValidationError、
shipping_onhand_admin_service(assert_onhand_source_can_enable / save_onhand_report_config /
save_receipt_report_config)、FreightRpaOnhandReportConfig / FreightRpaSource 等模型。
freight_rpa_source_admin_service(assert_onhand_source_can_enable / save_onhand_report_config)、
freight_rpa_report_config_service.save_inbound_report_config、
FreightRpaOnhandReportConfig / FreightRpaSource 等模型。
逻辑:验证启用中站点缺模板/缺配置行/缺解析绑定时 fail-closed;保存在手配置只写配置行、
不写站点已删除的三列,并递增配置行 config_version;在手与入站两侧解析方案 purpose 互斥。
"""
@@ -19,8 +20,9 @@ from app.core.errors import ValidationError
from app.models import (
FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaParsingProfile, FreightRpaProfile,
)
from app.services.admin.shipping_onhand_admin_service import (
assert_onhand_source_can_enable, save_onhand_report_config, save_receipt_report_config,
from app.services.admin.freight_rpa_report_config_service import save_inbound_report_config
from app.services.admin.freight_rpa_source_admin_service import (
assert_onhand_source_can_enable, save_onhand_report_config,
)
# 站点/连接编码自增,保证同一测试内多次构造不撞唯一约束。
@@ -184,13 +186,13 @@ def test_save_onhand_report_config_rejects_non_onhand_parsing_profile(app, db_se
assert FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).count() == 0
def test_save_receipt_report_config_keeps_inbound_only_binding(app, db_session):
"""收料配置保存继续只接受 purpose='inbound' 的解析方案(在手/入站互斥回归)。"""
def test_save_inbound_report_config_keeps_inbound_only_binding(app, db_session):
"""入站配置保存继续只接受 purpose='inbound' 的解析方案(在手/入站互斥回归)。"""
source = _source(enabled=False, excel_template_id=9)
db_session.add(source)
db_session.commit()
with pytest.raises(ValidationError) as exc:
save_receipt_report_config(source.id, {
save_inbound_report_config(source.id, {
# 先给合法 DBS 四段路径,确保失败点落在解析绑定校验(purpose 互斥)而非路径校验。
"report_path_json": {
"program_group": "Bison", "program_label": "AWSBI",
@@ -76,11 +76,12 @@ def test_freight_rpa_admin_routes_moved_and_old_paths_404(app, client):
assert fields.status_code == 200
assert fields.get_json()['success'] is True
# [断言意图] 临时会话只改词根,仍留在 shipping-notice;Excel 模板与异动字段不动。
# [断言意图] 临时会话只改词根,仍留在 shipping-notice;Excel 模板不动;异动字段归 freight-rpa。
assert '/api/admin/shipping-notice/temporary-onhand-sessions' in rules
assert '/api/admin/shipping-notice/temporary-inventory-sessions' not in rules
assert '/api/admin/shipping-notice/excel-templates' in rules
assert '/api/admin/shipping-notice/movement-fields' in rules
assert '/api/admin/freight-rpa/movement-fields' in rules
assert '/api/admin/shipping-notice/movement-fields' not in rules
# [断言意图] rpa-profiles 仍在 freight-rpa,不重复注册到 shipping-notice。
assert '/api/admin/freight-rpa/rpa-profiles' in rules
assert '/api/admin/shipping-notice/rpa-profiles' not in rules
+3 -3
View File
@@ -1,7 +1,7 @@
"""
标准异动字段目录接口测试。
用途:验证 GET /api/admin/shipping-notice/movement-fields 下发只读领域契约。
用途:验证 GET /api/admin/freight-rpa/movement-fields 下发只读领域契约。
依赖:Flask 管理 API、movement_contract 契约常量。
逻辑:字段目录是 immutable 常量的投影——码/类型/必填/身份标记与契约逐项一致,
不提供任何增删改入口,字段 label 由前端 i18n 渲染。
@@ -27,7 +27,7 @@ def test_movement_fields_returns_fixed_catalog(app, client):
db.session.add(User(username='movement-admin', email='movement-admin@example.com', role='admin', status='active'))
db.session.commit()
response = client.get('/api/admin/shipping-notice/movement-fields', headers=_headers())
response = client.get('/api/admin/freight-rpa/movement-fields', headers=_headers())
assert response.status_code == 200
data = parse_api_data(response.get_json())
# [断言意图] 字段码与顺序是前后端共同契约——后端 movement_contract 变更必须显式同步本断言。
@@ -53,7 +53,7 @@ def test_movement_fields_rejects_non_admin(app, client):
db.session.add(User(username='movement-user', email='movement-user@example.com', role='user', status='active'))
db.session.commit()
response = client.get('/api/admin/shipping-notice/movement-fields', headers={
response = client.get('/api/admin/freight-rpa/movement-fields', headers={
'X-Username': 'movement-user', 'X-Role': 'user', 'Content-Type': 'application/json',
})
assert response.status_code == 403
@@ -118,7 +118,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
json=invalid_date, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID'
invalid_selector = _dbs_payload()
invalid_selector['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': [], 'selector': '#owner'}]
@@ -127,7 +127,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
json=invalid_selector, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID'
# 关键断言:Warehouse 条件由管理员自行维护——缺失/空值允许保存,不再强制拦截。
missing_warehouse = _dbs_payload()
@@ -159,7 +159,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
json=invalid_crane, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID'
def _create_parsing_profile(profile_code: str, *, status: str, purpose: str):
@@ -298,7 +298,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
json=configured, headers=_headers('receipt-admin', 'admin'),
)
assert rejected.status_code == 400
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID'
def test_retire_rejects_profile_bound_by_receipt_report_config(app):
@@ -311,7 +311,7 @@ def test_retire_rejects_profile_bound_by_receipt_report_config(app):
"""
from app import db
from app.models import FreightRpaInboundReportConfig
from app.services.shipping_notice import onhand_parsing_profile
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
+67 -128
View File
@@ -1,4 +1,10 @@
"""收料文件下载和人工补偿的权限/审计契约测试。"""
"""
backend/tests/test_freight_receipt_rpa_access.py
用途:入站 RPA 管理员补偿 API 契约(失败单元列表/重试);工作台收料文件与 resend 已拆除。
依赖:Flask test client、freight_rpa 入站模型与 schedule runs 路由。
逻辑:仅覆盖 /api/admin/inbound-rpa-units 与 retry;审计 surface 为 admin_inbound_rpa_units。
"""
from __future__ import annotations
@@ -7,131 +13,6 @@ def _headers(username: str, role: str) -> dict[str, str]:
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client, monkeypatch):
"""排程接收人可下载原样文件;非接收人不可通过猜测 ID 越权。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
recipient = User(username='receipt-download-user', email='receipt-download@example.com', role='user', status='active')
other = User(username='receipt-other-user', email='receipt-other@example.com', role='user', status='active')
db.session.add_all([recipient, other]); db.session.flush()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-DL', schedule_task_id=task.id, status='success')
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-download', status='success', config_snapshot_json={})
db.session.add(unit); db.session.flush()
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/download.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='b' * 64)
db.session.add(report_file); db.session.commit()
file_id = report_file.id
# 阶段 B Task 5:inbound_report_access 改经 freight_rpa/reports.read_inbound_file_bytes 读字节,
# monkeypatch 目标随之改到存储单例本身(所有 import 方共享同一实例,补丁全链路生效)。
monkeypatch.setattr('app.services.file_assets.storage.file_asset_storage.get_bytes', lambda _key: b'xlsx')
allowed = client.get(f'/api/workspace/inbound-report-files/{file_id}/download', headers=_headers('receipt-download-user', 'user'))
denied = client.get(f'/api/workspace/inbound-report-files/{file_id}/download', headers=_headers('receipt-other-user', 'user'))
assert allowed.status_code == 200
assert allowed.data == b'xlsx'
assert denied.status_code == 403
def test_receipt_recipient_lists_only_own_archived_files(app, client):
"""接收人文件列表仅返回本人排程归档,并且不得泄露对象存储定位。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
recipient = User(username='receipt-list-user', email='receipt-list@example.com', role='user', status='active')
other = User(username='receipt-list-other', email='receipt-list-other@example.com', role='user', status='active')
db.session.add_all([recipient, other]); db.session.flush()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
db.session.add_all([own_task, other_task]); db.session.flush()
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OWN', schedule_task_id=own_task.id, status='success')
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OTHER', schedule_task_id=other_task.id, status='success')
db.session.add_all([own_run, other_run]); db.session.flush()
own_unit = FreightRpaInboundUnitRun(schedule_run_id=own_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-list-own', status='success', config_snapshot_json={})
other_unit = FreightRpaInboundUnitRun(schedule_run_id=other_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-list-other', status='success', config_snapshot_json={})
db.session.add_all([own_unit, other_unit]); db.session.flush()
own_file = FreightRpaInboundReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='d' * 64)
db.session.add_all([own_file, FreightRpaInboundReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-other.xlsx', original_filename='other.xlsx', file_size=4, sha256='e' * 64)])
db.session.commit()
own_file_id = own_file.id
response = client.get('/api/workspace/inbound-report-files', headers=_headers('receipt-list-user', 'user'))
assert response.status_code == 200
items = response.get_json()['data']['items']
# 关键断言:列表投影不能泄露非接收人的文件或对象存储定位。
assert [item['id'] for item in items] == [own_file_id]
assert 'storage_key' not in items[0]
assert items[0]['download_url'].endswith(f'/inbound-report-files/{own_file_id}/download')
def test_receipt_file_list_filters_before_applying_limit(app):
"""其他人的新文件再多,也不能挤掉接收人较早的可见归档。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User
from app.services.shipping_notice.inbound_report_access import list_receipt_report_files
with app.app_context():
recipient = User(username='receipt-limit-user', email='receipt-limit@example.com', role='user', status='active')
other = User(username='receipt-limit-other', email='receipt-limit-other@example.com', role='user', status='active')
db.session.add_all([recipient, other]); db.session.flush()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
db.session.add_all([own_task, other_task]); db.session.flush()
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OWN', schedule_task_id=own_task.id, status='success')
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OTHER', schedule_task_id=other_task.id, status='success')
db.session.add_all([own_run, other_run]); db.session.flush()
own_unit = FreightRpaInboundUnitRun(schedule_run_id=own_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-limit-own', status='success', config_snapshot_json={})
other_unit = FreightRpaInboundUnitRun(schedule_run_id=other_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-limit-other', status='success', config_snapshot_json={})
db.session.add_all([own_unit, other_unit]); db.session.flush()
own_file = FreightRpaInboundReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/limit-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='f' * 64)
db.session.add(own_file); db.session.flush()
for index in range(3):
db.session.add(FreightRpaInboundReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'receipt/limit-other-{index}.xlsx', original_filename=f'other-{index}.xlsx', file_size=4, sha256=f'{index + 1}' * 64))
db.session.commit()
items = list_receipt_report_files(recipient, limit=1)
# 关键断言:授权过滤发生在截断之前,避免被其他排程的归档饿死。
assert [item['id'] for item in items] == [own_file.id]
def test_admin_can_resend_without_reexporting(app, client, monkeypatch):
"""管理员重发只调用文件投递,不创建 RPA 单元或 trigger。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
admin = User(username='receipt-resend-admin', email='receipt-resend-admin@example.com', role='admin', status='active')
db.session.add(admin); db.session.flush()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id])
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-RESEND', schedule_task_id=task.id, status='success')
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-resend', status='success', config_snapshot_json={})
db.session.add(unit); db.session.flush()
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/resend.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='c' * 64)
db.session.add(report_file); db.session.commit()
file_id = report_file.id
calls = []
monkeypatch.setattr('app.api.schedule.runs.deliver_inbound_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0})
response = client.post(f'/api/admin/inbound-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin'))
assert response.status_code == 200
assert calls == [(file_id, True)]
def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, client, monkeypatch):
"""失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。"""
from app import db
@@ -158,6 +39,7 @@ def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, clien
retry = FreightRpaInboundUnitRun.query.filter_by(retry_of_id=failed_id).one()
assert retry.status == 'awaiting_rpa'
assert retry.callback_id != 'receipt-failed'
assert retry.callback_id.startswith('inbound:')
assert captured and captured[0][1][0]['callback_id'] == retry.callback_id
@@ -175,7 +57,7 @@ def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client):
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-UNITS', schedule_task_id=task.id, status='failed')
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', config_snapshot_json={})
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.INBOUND_EXPORT_FAILED', config_snapshot_json={})
db.session.add(unit); db.session.commit()
unit_id = unit.id
@@ -184,4 +66,61 @@ def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client):
assert response.status_code == 200
assert [item['id'] for item in response.get_json()['data']['items']] == [unit_id]
with app.app_context():
assert ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_units_listed').count() == 1
listed = ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_units_listed').one()
assert listed.metadata_json.get('surface') == 'admin_inbound_rpa_units'
def test_admin_retry_inbound_unit_messages_use_inbound_not_receipt(app, client):
"""入站 retry 面向用户的英文错误须用 Inbound,不得再写 Receipt。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, User
from tests.conftest import parse_api_error
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
admin = User(
username='inbound-retry-msg-admin',
email='inbound-retry-msg-admin@example.com',
role='admin',
status='active',
)
db.session.add(admin)
db.session.flush()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(
schedule_no='SCH-INBOUND-RETRY-MSG',
name='Inbound retry messages',
schedule_type='platform_job',
platform_api_path='freight-rpa-inbound',
owner_user_id=admin.id,
cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(run_no='RUN-INBOUND-RETRY-MSG', schedule_task_id=task.id, status='failed')
db.session.add(run)
db.session.flush()
success = FreightRpaInboundUnitRun(
schedule_run_id=run.id, source_id=source.id, source_code=source.source_code,
connector_type='dbs', warehouse_id='A', callback_id='inbound-success-no-retry',
status='success', config_snapshot_json={},
)
db.session.add(success)
db.session.commit()
success_id = success.id
missing = client.post(
'/api/admin/inbound-rpa-units/999999/retry',
json={'reason': 'should 404'},
headers=_headers('inbound-retry-msg-admin', 'admin'),
)
assert missing.status_code == 404
assert parse_api_error(missing.get_json())['message'] == 'Inbound RPA unit not found'
blocked = client.post(
f'/api/admin/inbound-rpa-units/{success_id}/retry',
json={'reason': 'should conflict'},
headers=_headers('inbound-retry-msg-admin', 'admin'),
)
assert blocked.status_code == 409
assert parse_api_error(blocked.get_json())['message'] == 'Only failed inbound RPA units can be retried'
@@ -7,30 +7,17 @@ import hashlib
import pytest
def _register_legacy_terminal_handler(unit):
"""注册测试用 inbound 事实处理函数,复刻拆分前的终态收尾(桥 + 证据同步 + finalize)。
def _register_inbound_report_handler():
"""注册生产用 inbound 事实处理函数(调拨侧 handle_inbound_report)。
核心逻辑:Task 6 起 ingest_inbound_callback 不再收 on_terminal 钩子,本文件
的桥接/进度断言改经 register_report_handler 注入留守的
inbound_report_storage._finish_inbound_callback_terminal(Task 7 将平移为
in_transit_transfer 的 handle_inbound_report);fact → 旧钩子实参逐字段换算,
行为与拆分前逐点一致。
核心逻辑:归档入口终态 commit 后经 dispatch_report_fact 投递;测试在调用
ingest_inbound_callback 前显式注册,避免依赖 create_app 全局状态顺序。
"""
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.shipping_notice.inbound_report_storage import _finish_inbound_callback_terminal
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
def _handle(fact) -> None:
_finish_inbound_callback_terminal(
unit,
ok=fact.ok,
file_no=str(fact.file_id) if fact.file_id is not None else None,
file_sha256=fact.sha256,
error_code=fact.error_code,
error_message=fact.error_message,
)
register_report_handler("inbound", _handle)
return _handle
register_report_handler('inbound', handle_inbound_report)
return handle_inbound_report
def test_receipt_unit_processing_and_batch_progress(app):
@@ -38,8 +25,8 @@ def test_receipt_unit_processing_and_batch_progress(app):
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import (
mark_receipt_unit_processing,
report_receipt_batch_progress,
mark_inbound_unit_processing,
report_inbound_batch_progress,
)
with app.app_context():
@@ -53,7 +40,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
run = ScheduleRun(
run_no='RUN-RECEIPT-LIVE', schedule_task_id=task.id, status='running',
total_count=2, success_count=0, failed_count=0, skipped_count=0,
response_summary_json={'awaiting_receipt_rpa': True},
response_summary_json={'awaiting_inbound_rpa': True},
)
db.session.add(run)
db.session.flush()
@@ -65,7 +52,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
db.session.add(unit)
db.session.commit()
marked = mark_receipt_unit_processing({
marked = mark_inbound_unit_processing({
'schema_version': 'freight_rpa.inbound.v1',
'callback_id': unit.callback_id,
'status': 'processing',
@@ -74,7 +61,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
db.session.expire_all()
assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'processing'
progressed = report_receipt_batch_progress({
progressed = report_inbound_batch_progress({
'schema_version': 'freight_rpa.inbound.v1',
'schedule_run_id': run.id,
'batch_run_no': run.run_no,
@@ -93,7 +80,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
"""success 回调在 finalize 前须回写 ScheduleRun 进度计数(对齐 empty/failed)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
@@ -106,7 +93,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
run = ScheduleRun(
run_no='RUN-RECEIPT-PROG', 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': True},
response_summary_json={'awaiting_inbound_rpa': True},
)
db.session.add(run)
db.session.flush()
@@ -125,7 +112,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes',
lambda **_kwargs: None,
)
_register_legacy_terminal_handler(unit)
_register_inbound_report_handler()
payload = {
'schema_version': 'freight_rpa.inbound.v1',
'callback_id': unit.callback_id,
@@ -134,7 +121,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
'original_filename': 'receipt.xlsx',
'sha256': hashlib.sha256(b'receipt-bytes').hexdigest(),
}
ingest_receipt_callback(payload)
ingest_inbound_callback(payload)
db.session.expire_all()
refreshed = db.session.get(ScheduleRun, run.id)
# [断言意图] success 后进度至少抬升 success_count;终态可能已 finalize 清 awaiting。
@@ -145,7 +132,7 @@ def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch)
"""同一 callback 重放只归档一条收料文件,绝不创建库存快照。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
@@ -157,10 +144,10 @@ def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch)
db.session.add(unit); db.session.commit()
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
_register_legacy_terminal_handler(unit)
_register_inbound_report_handler()
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
first = ingest_receipt_callback(payload)
second = ingest_receipt_callback(payload)
first = ingest_inbound_callback(payload)
second = ingest_inbound_callback(payload)
assert first['file_id'] == second['file_id']
assert FreightRpaOnhandReportFile.query.count() == 0
@@ -169,7 +156,7 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
"""收料回调 success 落归档后,必须推进调拨 waiting 来源任务(B3 接线)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
@@ -185,10 +172,10 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
db.session.add(job); db.session.commit()
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
_register_legacy_terminal_handler(unit)
_register_inbound_report_handler()
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
result = ingest_receipt_callback(payload)
result = ingest_inbound_callback(payload)
# [断言意图] 桥接发生:收料归档后调拨任务状态推进 file_ready,file_no 为归档文件 id
db.session.expire_all()
advanced = db.session.get(TransferSourceJob, job.id)
@@ -200,7 +187,7 @@ def test_ingest_failed_advance_is_durable(app):
"""failed 回调推进调拨任务后必须已 commit——rollback 不得丢弃该推进(B3 持久性)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
@@ -214,10 +201,10 @@ def test_ingest_failed_advance_is_durable(app):
db.session.add(transfer_run); db.session.flush()
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
db.session.add(job); db.session.commit()
_register_legacy_terminal_handler(unit)
_register_inbound_report_handler()
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
result = ingest_receipt_callback(payload)
result = ingest_inbound_callback(payload)
assert result['status'] == 'failed'
# [断言意图] 推进必须已落库而非仅 flush:rollback 丢弃会话内未提交变更,
# 只有真正 commit 过的推进才能在 expire_all 后被新查询读到。
@@ -240,19 +227,19 @@ def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
outside = tmp_path / 'outside.xlsx'
outside.write_bytes(b'not-a-real-xlsx')
with pytest.raises(ValidationError, match='receipt callback file'):
with pytest.raises(ValidationError, match='inbound callback file'):
_read_inbound_callback_file(str(outside))
def test_ingest_empty_persists_no_receipt_data(app):
def test_ingest_empty_persists_no_inbound_data(app):
"""
empty 回调须落库 no_receipt_data(对齐库存 no_inventory_data)。
empty 回调须落库 no_inbound_data(对齐库存 no_inventory_data)。
[断言意图] 单元 status=empty 且 error_code/error_message 为 no_receipt_data,供管理端展示跳过原因。
[断言意图] 单元 status=empty 且 error_code/error_message 为 no_inbound_data,供管理端展示跳过原因。
"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
@@ -281,22 +268,22 @@ def test_ingest_empty_persists_no_receipt_data(app):
)
db.session.add(unit)
db.session.commit()
_register_legacy_terminal_handler(unit)
_register_inbound_report_handler()
result = ingest_receipt_callback({
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',
'error_code': 'no_inbound_data',
'error_message': 'no_inbound_data',
})
assert result['status'] == 'empty'
db.session.expire_all()
saved = db.session.get(FreightRpaInboundUnitRun, unit.id)
assert saved is not None
assert saved.status == 'empty'
assert saved.error_code == 'no_receipt_data'
assert saved.error_message == 'no_receipt_data'
assert saved.error_code == 'no_inbound_data'
assert saved.error_message == 'no_inbound_data'
def test_receipt_progress_routes_are_registered(app):
@@ -343,5 +330,5 @@ def test_read_receipt_callback_file_resolves_drop_root_filename(app, tmp_path):
) == b'receipt-bytes'
outside = tmp_path / 'outside.xlsx'
outside.write_bytes(b'x')
with pytest.raises(ValidationError, match='receipt callback file'):
with pytest.raises(ValidationError, match='inbound callback file'):
_read_inbound_callback_file(str(outside))
@@ -1,70 +1,14 @@
"""收料文件企微投递和授权下载契约测试。"""
"""
backend/tests/test_freight_receipt_rpa_notifications.py
用途:入站排程终态企微通知与 finalize 汇总 Excel 契约(统一排程出口)。
依赖:freight_rpa_inbound_finalize、scheduler_service 企微门禁。
逻辑:per-file deliver_inbound_file 已拆除;本文件不再覆盖单文件投递/resend。
"""
from __future__ import annotations
def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipients(app, monkeypatch):
"""同一文件只向排程接收人发送一次,重放不会重复调用企微。"""
from app import db
from app.models import (
ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile,
FreightRpaInboundUnitRun, User,
)
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
with app.app_context():
recipient = User(username='receipt-recipient', email='recipient@example.com', role='user', status='active', wecom_userid='receipt-user')
db.session.add(recipient); db.session.flush()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY', schedule_task_id=task.id, status='running')
db.session.add(run); db.session.flush()
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-notify-callback', status='success', config_snapshot_json={})
db.session.add(unit); db.session.flush()
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64)
db.session.add(report_file); db.session.commit()
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.upload_wecom_temp_media', lambda *_args: 'media-1')
calls: list[tuple] = []
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0})
assert deliver_inbound_file(report_file.id)['success_count'] == 1
assert deliver_inbound_file(report_file.id)['success_count'] == 1
assert len(calls) == 1
def test_receipt_notification_failure_is_audited(app, monkeypatch):
"""企微投递失败也必须保留接收人、时间、失败码和文件身份审计。"""
from app import db
from app.models import (
ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundReportFile,
FreightRpaInboundUnitRun, User,
)
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
with app.app_context():
recipient = User(username='receipt-unbound-recipient', email='receipt-unbound@example.com', role='user', status='active')
db.session.add(recipient); db.session.flush()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY-FAIL', schedule_task_id=task.id, status='running')
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-notify-fail', status='success', config_snapshot_json={})
db.session.add(unit); db.session.flush()
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64)
db.session.add(report_file); db.session.commit()
outcome = deliver_inbound_file(report_file.id)
assert outcome['failed_count'] == 1
audit = ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_file_notification_attempted', aggregate_id=str(report_file.id)).one()
# 审计结果遵循统一枚举;业务投递状态仍保留为 failed。
assert audit.result == 'failure'
assert audit.after_snapshot_json['error_code'] == 'WECOM_USER_UNBOUND'
def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *, awaiting: bool = True):
"""构造一个收料排程任务+run+成功单元+归档文件的最小通知夹具。"""
from app.models import (
@@ -75,7 +19,7 @@ def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_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', response_summary_json={'awaiting_receipt_rpa': True} if awaiting else None)
run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_inbound_rpa': True} if awaiting else None)
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id=callback_id, status='success', config_snapshot_json={})
db.session.add(unit); db.session.flush()
@@ -115,7 +59,7 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_
"""收料 run 终态后经通用排程出口一次性发 textcard+收料 ZIP;重复归集不重发。"""
from app import db
from app.models import User
from app.services.schedule.freight_rpa_inbound_finalize import finalize_receipt_schedule_run_if_complete
from app.services.schedule.freight_rpa_inbound_finalize import finalize_inbound_schedule_run_if_complete
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives')
@@ -130,27 +74,27 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_
app.config['WECOM_PUBLIC_BASE_URL'] = 'https://hxops.example.com'
textcards, media_uploads, file_sends = _patch_unified_wecom(monkeypatch, enabled_events=True)
outcome = finalize_receipt_schedule_run_if_complete(run.id)
outcome = finalize_inbound_schedule_run_if_complete(run.id)
# [断言意图] 一次性出口:单条 textcard + 结果 Excel + 单个收料 ZIP,与库存排程同通道同门禁。
assert outcome == {'finalized': True, 'status': 'success'}
assert len(textcards) == 1
assert '原始收料包:已随本通知发送' in textcards[0][1]
assert '原始入站包:已随本通知发送' in textcards[0][1]
assert len(media_uploads) == 2
assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-结果.xlsx')
assert media_uploads[1].startswith('收料RPA-') and media_uploads[1].endswith('-收料.zip')
assert media_uploads[0].startswith('入站RPA-') and media_uploads[0].endswith('-结果.xlsx')
assert media_uploads[1].startswith('入站RPA-') and media_uploads[1].endswith('-入站.zip')
assert file_sends == ['media-1', 'media-2']
assert run.wecom_notified is True
assert run.response_summary_json.get('raw_receipt_zip_available') is True
assert run.response_summary_json.get('raw_inbound_zip_available') is True
# [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。
outcome_again = finalize_receipt_schedule_run_if_complete(run.id)
assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
outcome_again = finalize_inbound_schedule_run_if_complete(run.id)
assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_inbound_callback'}
assert len(textcards) == 1 and len(file_sends) == 2
def test_receipt_finalize_generates_summary_excel(app, tmp_path):
"""收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 收料RPA-*-结果.xlsx。"""
"""收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 入站RPA-*-结果.xlsx。"""
from io import BytesIO
from openpyxl import load_workbook
@@ -160,28 +104,28 @@ def test_receipt_finalize_generates_summary_excel(app, tmp_path):
ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
from app.services.schedule.freight_rpa_inbound_finalize import finalize_receipt_schedule_run_if_complete
from app.services.schedule.freight_rpa_inbound_finalize import finalize_inbound_schedule_run_if_complete
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', 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-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True})
run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_inbound_rpa': True})
db.session.add(run); db.session.flush()
unit_ok = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={})
unit_empty = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={})
unit_fail = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={})
unit_fail = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.INBOUND_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={})
db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush()
db.session.add(FreightRpaInboundReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64))
db.session.commit()
outcome = finalize_receipt_schedule_run_if_complete(run.id)
outcome = finalize_inbound_schedule_run_if_complete(run.id)
# [断言意图] finalize 生成汇总 Excel,并携带与库存同名的 summary 契约键。
assert outcome == {'finalized': True, 'status': 'partial_failed'}
assert run.excel_file_data
assert run.excel_file_name.startswith('收料RPA-') and run.excel_file_name.endswith('-结果.xlsx')
assert run.excel_file_name.startswith('入站RPA-') and run.excel_file_name.endswith('-结果.xlsx')
assert run.response_summary_json['excel_export_status'] == 'ok'
assert run.response_summary_json['excel_failed'] is False
@@ -189,7 +133,7 @@ def test_receipt_finalize_generates_summary_excel(app, tmp_path):
workbook = load_workbook(BytesIO(run.excel_file_data))
sheet = workbook.active
header = [cell.value for cell in sheet[1]]
assert header[:2] == ['收料源', '仓库']
assert header[:2] == ['入站源', '仓库']
rows = {row[0]: row for row in sheet.iter_rows(min_row=2, values_only=True)}
assert rows['DSV360_AWSDU'][3] == 1 and rows['DSV360_AWSDU'][4] == 'success'
assert rows['DSV360_AWSCV'][4] == 'skipped'
@@ -9,7 +9,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
"""一源一单元:有/无 Warehouse 条件均产出 unit;多值 Warehouse 不拆分。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaProfile
from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule
with app.app_context():
dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
@@ -66,7 +66,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
'app.services.schedule.freight_rpa_inbound_job.write_inbound_export_batch_trigger',
lambda run_no, units, payload: captured.update(run_no=run_no, units=units, payload=payload) or 'receipt-trigger.json',
)
total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run)
total, success, failed, skipped, details, errors, logs = run_freight_rpa_inbound_schedule(task, run)
# 关键断言:三源三单元;多值 Warehouse 不拆;空 query_parameters 仍产出。
assert (total, success, failed, skipped, errors) == (3, 0, 0, 0, [])
@@ -96,7 +96,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule
from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
with app.app_context():
@@ -122,11 +122,11 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
trigger_calls = []
monkeypatch.setattr(
'app.services.schedule.freight_rpa_inbound_job.assert_receipt_rpa_worker_ready',
'app.services.schedule.freight_rpa_inbound_job.assert_inbound_rpa_worker_ready',
lambda: (_ for _ in ()).throw(ServiceUnavailableError(
RPA_WORKER_OFFLINE_MESSAGE,
code='RPA.WORKER_OFFLINE',
details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'receipt worker offline'},
details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'inbound worker offline'},
)),
)
monkeypatch.setattr(
@@ -134,18 +134,18 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json',
)
total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run)
total, success, failed, skipped, details, errors, logs = run_freight_rpa_inbound_schedule(task, run)
# [断言意图] fail-fast:计 failed、不入库 unit、不写 trigger、不进入 awaiting。
assert (total, success, failed, skipped) == (1, 0, 1, 0)
assert details == []
assert errors == ['receipt worker offline']
assert errors == ['inbound worker offline']
assert trigger_calls == []
assert FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0
failed_log = next(log for log in logs if isinstance(log, dict) and log.get('status') == 'failed')
assert failed_log['detail'].get('reasons') == ['no_worker_heartbeat']
assert not any(
isinstance(log, dict) and log.get('status') == 'awaiting_receipt_rpa'
isinstance(log, dict) and log.get('status') == 'awaiting_inbound_rpa_callback'
for log in logs
)
@@ -174,24 +174,24 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
"""无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_stale_receipt_rpa_schedule_runs
from app.services.schedule.freight_rpa_inbound_finalize import recover_stale_inbound_rpa_schedule_runs
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', 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-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_receipt_rpa': True})
run = ScheduleRun(run_no='RUN-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_inbound_rpa': True})
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={})
db.session.add(unit); db.session.commit()
assert recover_stale_receipt_rpa_schedule_runs(task) == 1
assert recover_stale_inbound_rpa_schedule_runs(task) == 1
db.session.refresh(run); db.session.refresh(unit)
assert run.status == 'failed'
assert unit.status == 'failed'
assert unit.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT'
assert unit.error_code == 'RPA.INBOUND_CALLBACK_TIMEOUT'
assert FreightRpaInboundUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0
assert ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1
@@ -212,38 +212,38 @@ def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app):
"""全量扫描(每轮 tick 路径)无需任务再次执行/进程重启即可收口超时收料 run。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_receipt_rpa_schedule_runs
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_inbound_rpa_schedule_runs
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', 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-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_receipt_rpa': True})
run = ScheduleRun(run_no='RUN-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_inbound_rpa': True})
db.session.add(run); db.session.flush()
db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={}))
db.session.commit()
# [断言意图] 全量扫描不依赖 task 入参、进程重启或同排程再次执行(点B 修复口径);
# 超时窗(60s)过后扫描即收口为 failed 并写 recovered_reason。
assert recover_all_stale_receipt_rpa_schedule_runs() == 1
assert recover_all_stale_inbound_rpa_schedule_runs() == 1
db.session.refresh(run)
assert run.status == 'failed'
assert run.response_summary_json.get('recovered_reason') == 'receipt_rpa_callback_timeout'
assert run.response_summary_json.get('recovered_reason') == 'inbound_rpa_callback_timeout'
def test_receipt_recovery_respects_fresh_activity_of_long_batch(app):
def test_inbound_recovery_respects_fresh_activity_of_long_batch(app):
"""长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_receipt_rpa_schedule_runs
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_inbound_rpa_schedule_runs
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', 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-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_receipt_rpa': True})
run = ScheduleRun(run_no='RUN-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_inbound_rpa': True})
db.session.add(run); db.session.flush()
# 单元1:30 秒前终态(笔间活动新鲜);单元2:45 秒前进入 processing(在飞,started_at 为锚)
db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30)))
@@ -252,12 +252,12 @@ def test_receipt_recovery_respects_fresh_activity_of_long_batch(app):
# [断言意图] run.started_at(30min 前) 已远超 60s 窗,但最后活动仅 30~45s——
# 笔间静默口径下健康长批次必须不被回收(旧口径按 started_at 会误杀)。
assert recover_all_stale_receipt_rpa_schedule_runs() == 0
assert recover_all_stale_inbound_rpa_schedule_runs() == 0
db.session.refresh(run)
assert run.status == 'running'
def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only():
def test_inbound_recovery_is_wired_into_per_tick_maintenance_not_startup_only():
"""哨兵回归:收料超时对账必须挂在每轮领取维护区,不得回流启动一次性分支。"""
import inspect
@@ -266,16 +266,16 @@ def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only():
source = inspect.getsource(queue_service)
marker_init = source.index("_worker_initialized = True")
# [断言意图] 调用点必须位于一次性分支竖旗之后(每轮维护区);
# 回流旧写法(receipt_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。
assert source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()") > marker_init
assert "receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()" not in source
# 回流旧写法(inbound_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。
assert source.index("inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()") > marker_init
assert "inbound_recovered = recover_all_stale_inbound_rpa_schedule_runs()" not in source
def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
"""按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。"""
from app import db
from app.models import ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_inbound_units
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
@@ -303,16 +303,16 @@ def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
db.session.commit()
# [断言意图] 调拨工作台按需触发单元 schedule_run_id=NULL,不在 run 级扫描
# (recover_all_stale_receipt_rpa_schedule_runs 按 run 遍历)范围内;网页异常
# (recover_all_stale_inbound_rpa_schedule_runs 按 run 遍历)范围内;网页异常
# 关闭后回调永不到达,必须由本扫描终态化(2026-10-16 事故回归),健康单元原样;
# 与 run 级回收同口径:只标失败、写审计,绝不自动创建重试单元。
assert recover_all_stale_orphan_receipt_units() == 2
assert recover_all_stale_orphan_inbound_units() == 2
db.session.refresh(stale_queued)
db.session.refresh(stale_processing)
db.session.refresh(fresh_processing)
assert stale_queued.status == 'failed'
assert stale_queued.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT'
assert stale_queued.error_code == 'RPA.INBOUND_CALLBACK_TIMEOUT'
assert stale_queued.finished_at is not None
assert stale_processing.status == 'failed'
assert fresh_processing.status == 'processing'
@@ -325,7 +325,7 @@ def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
assert (timeout_event.after_snapshot_json or {}).get('status') == 'failed'
def test_orphan_receipt_recovery_is_wired_into_per_tick_maintenance():
def test_orphan_inbound_recovery_is_wired_into_per_tick_maintenance():
"""哨兵回归:孤儿单元回收必须挂在每轮领取维护区(与 run 级扫描同区同轮)。"""
import inspect
@@ -334,5 +334,5 @@ def test_orphan_receipt_recovery_is_wired_into_per_tick_maintenance():
source = inspect.getsource(queue_service)
# [断言意图] 调用点必须与 run 级收料扫描同在每轮维护区且在其后;
# 缺席或回流启动一次性分支都会复现「长驻进程期间来源永久 fetching」事故。
marker_run_scan = source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()")
assert source.index("recover_all_stale_orphan_receipt_units()") > marker_run_scan
marker_run_scan = source.index("inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()")
assert source.index("recover_all_stale_orphan_inbound_units()") > marker_run_scan
@@ -91,7 +91,7 @@ def test_receipt_worker_save_download_uses_directory_fallback():
def test_receipt_worker_validates_excel_and_reports_empty():
"""收料落盘后必须结构校验;无明细走 NoReceiptDataError → empty/no_receipt_data。"""
"""收料落盘后必须结构校验;无明细走 NoReceiptDataError → empty/no_inbound_data。"""
text = (
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py'
).read_text(encoding='utf-8')
@@ -105,9 +105,9 @@ def test_receipt_worker_validates_excel_and_reports_empty():
assert 'def _validate_inbound_excel(' in text
assert 'from inbound_excel_empty import' in text
assert 'class NoInboundDataError' in empty_mod
assert 'no_receipt_data' in empty_mod
assert 'no_inbound_data' in empty_mod
assert 'is_inbound_excel_header_row' in empty_mod
assert "'error_code': 'no_receipt_data'" in text
assert "'error_code': 'no_inbound_data'" in text
assert "_post_callback({" in text and "'status': 'empty'" in text
assert '_EXPORT_UNIT_MAX_ATTEMPTS = 2' in text
assert 'retry with clean page' in text
@@ -0,0 +1,68 @@
"""
tests/test_freight_rpa_admin_ownership_gate.py
用途:锁定货代 RPA 管理归属——入站/出站配置、报表规则、来源站点/登录连接不再寄宿 shipping_onhand 命名空间。
依赖:pathlib、importlib、pytest。
"""
from __future__ import annotations
import importlib
from pathlib import Path
BACKEND_ROOT = Path(__file__).resolve().parents[1]
def test_parsing_profile_lives_under_freight_rpa():
"""报表规则模块在 freight_rpa,shipping_notice 不再保留 onhand_parsing_profile 文件。"""
assert (BACKEND_ROOT / 'app/services/freight_rpa/parsing_profile.py').is_file()
assert not (BACKEND_ROOT / 'app/services/shipping_notice/onhand_parsing_profile.py').exists()
mod = importlib.import_module('app.services.freight_rpa.parsing_profile')
assert callable(mod.save_draft)
assert callable(mod.list_profiles)
def test_inbound_outbound_report_config_not_on_shipping_onhand_admin():
"""入站/出站配置 CRUD 在 freight_rpa_report_config_service,不在 onhand admin。"""
onhand = importlib.import_module('app.services.admin.shipping_onhand_admin_service')
report = importlib.import_module('app.services.admin.freight_rpa_report_config_service')
for name in (
'get_inbound_report_config',
'save_inbound_report_config',
'get_outbound_report_config',
'save_outbound_report_config',
):
assert not hasattr(onhand, name)
assert callable(getattr(report, name))
def test_movement_fields_route_under_freight_rpa_not_shipping_notice():
"""异动字段目录挂在 /freight-rpa/,不在 /shipping-notice/。"""
freight = (BACKEND_ROOT / 'app/api/admin_freight_rpa.py').read_text(encoding='utf-8')
shipping = (BACKEND_ROOT / 'app/api/admin/shipping_notice_admin.py').read_text(encoding='utf-8')
assert "/freight-rpa/movement-fields" in freight
assert "/shipping-notice/movement-fields" not in shipping
def test_source_profile_admin_not_on_shipping_onhand():
"""登录连接与来源站点 CRUD 在 freight_rpa_source_admin_service。"""
onhand = importlib.import_module('app.services.admin.shipping_onhand_admin_service')
source = importlib.import_module('app.services.admin.freight_rpa_source_admin_service')
for name in (
'list_profiles',
'save_profile',
'delete_profile',
'list_sources',
'save_source',
'delete_source',
'activate_source',
'deactivate_source',
'bind_source_parsing_profile',
'assert_onhand_source_can_enable',
'save_onhand_report_config',
):
assert not hasattr(onhand, name), name
assert callable(getattr(source, name)), name
for name in ('list_snapshots', 'list_rules', 'list_external_mappings'):
assert callable(getattr(onhand, name)), name
assert not hasattr(source, name), name
@@ -47,6 +47,18 @@ def test_build_heartbeat_payload_inbound_worker_declares_inbound_export(monkeypa
assert payload["worker_id"].endswith("-inbound")
def test_build_heartbeat_payload_outbound_worker_declares_outbound_export(monkeypatch):
"""outbound Worker(*-outbound 或 outbound trigger 路径)须声明 outbound_export。"""
module = _load_freight_rpa_heartbeat_module()
monkeypatch.setenv("FREIGHT_RPA_WORKER_ID", "WIN-RPA-01-outbound")
payload = module.build_heartbeat_payload(
trigger_dir=r"C:\HxopsRpaTest\data\freight_rpa\outbound\triggers",
drop_dir=r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop",
)
assert payload["capabilities"] == ["outbound_export"]
assert payload["worker_id"].endswith("-outbound")
def test_build_heartbeat_payload_adds_freight_rpa_upload_when_upload_enabled(monkeypatch):
"""开启上传时心跳能力是 freight_rpa_upload,不再上报 freight_upload。"""
module = _load_freight_rpa_heartbeat_module()
@@ -0,0 +1,29 @@
"""
backend/tests/test_freight_rpa_inbound_slim_gate.py
用途:Task 2 回归门禁——确认入站 per-file 企微投递模型/符号与工作台收料 API 已从 backend/app 拆除。
依赖:pathlib、pytest。
逻辑:仅扫描 Python 源码字符串,不断言 DB 表是否已 DROP(迁移归属 Task 4)。
"""
from __future__ import annotations
from pathlib import Path
BACKEND_ROOT = Path(__file__).resolve().parents[1]
def test_no_inbound_notification_delivery_symbol():
"""backend/app 内不得再出现投递模型符号或 deliver_inbound_file 实现。"""
hits = []
for path in (BACKEND_ROOT / 'app').rglob('*.py'):
text = path.read_text(encoding='utf-8')
if 'InboundNotificationDelivery' in text or 'deliver_inbound_file' in text:
hits.append(str(path))
assert hits == []
def test_no_workspace_inbound_report_routes():
"""工作台 shipping_notice 蓝图不得再暴露 inbound-report-files 路由。"""
text = (BACKEND_ROOT / 'app/api/workspace/shipping_notice.py').read_text(encoding='utf-8')
assert 'inbound-report-files' not in text
@@ -0,0 +1,183 @@
"""
backend/tests/test_freight_rpa_outbound_access.py
用途:出站 RPA 管理员补偿 API 契约(失败单元列表/重试)与 raw-zip 下载。
依赖:Flask test client、freight_rpa 出站模型与 schedule runs 路由。
逻辑:覆盖 /api/admin/outbound-rpa-units、retry 与 /schedule-runs/<id>/outbound-raw-zip。
"""
from __future__ import annotations
from urllib.parse import quote
import pytest
def _headers(username: str, role: str) -> dict[str, str]:
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
@pytest.fixture
def admin_jwt_headers(app):
"""创建 admin 用户并签发 Bearer JWT,供 raw-zip 下载走正式鉴权。"""
from app import db
from app.models import User
from app.core.auth.jwt import issue_local_access_token
with app.app_context():
user = db.session.query(User).filter_by(username='admin').first()
if not user:
user = User(
username='admin',
email='admin@example.com',
role='admin',
status='active',
)
user.set_password('admin')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
def test_admin_retry_creates_a_new_outbound_unit_linked_to_failed_unit(app, client, monkeypatch):
"""失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaOutboundUnitRun, User
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
admin = User(username='outbound-retry-admin', email='outbound-retry-admin@example.com', role='admin', status='active')
db.session.add(admin); db.session.flush()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-OUTBOUND-RETRY', name='Outbound retry', schedule_type='platform_job', platform_api_path='freight-rpa-outbound', owner_user_id=admin.id, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-OUTBOUND-RETRY', schedule_task_id=task.id, status='failed')
db.session.add(run); db.session.flush()
failed = FreightRpaOutboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='outbound-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []})
db.session.add(failed); db.session.commit()
failed_id = failed.id
captured = []
monkeypatch.setattr('app.api.schedule.runs.write_outbound_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json')
response = client.post(f'/api/admin/outbound-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('outbound-retry-admin', 'admin'))
assert response.status_code == 200
with app.app_context():
retry = FreightRpaOutboundUnitRun.query.filter_by(retry_of_id=failed_id).one()
assert retry.status == 'awaiting_rpa'
assert retry.callback_id != 'outbound-failed'
assert retry.callback_id.startswith('outbound:')
assert captured and captured[0][1][0]['callback_id'] == retry.callback_id
def test_admin_lists_failed_outbound_units_for_manual_compensation(app, client):
"""管理员可见失败单元用于人工补偿;该接口会记录管理员查看审计。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaOutboundUnitRun, User
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
admin = User(username='outbound-units-admin', email='outbound-units-admin@example.com', role='admin', status='active')
db.session.add(admin); db.session.flush()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-OUTBOUND-UNITS', name='Outbound units', schedule_type='platform_job', platform_api_path='freight-rpa-outbound', owner_user_id=admin.id, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-OUTBOUND-UNITS', schedule_task_id=task.id, status='failed')
db.session.add(run); db.session.flush()
unit = FreightRpaOutboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='outbound-admin-list', status='failed', error_code='RPA.OUTBOUND_EXPORT_FAILED', config_snapshot_json={})
db.session.add(unit); db.session.commit()
unit_id = unit.id
response = client.get('/api/admin/outbound-rpa-units?status=failed', headers=_headers('outbound-units-admin', 'admin'))
assert response.status_code == 200
assert [item['id'] for item in response.get_json()['data']['items']] == [unit_id]
with app.app_context():
assert ShippingAuditEvent.query.filter_by(event_type='shipping_outbound_rpa_units_listed').count() == 1
def test_serialize_run_reads_outbound_raw_zip_available_from_summary(app):
"""serialize_run 应暴露 outbound_raw_zip_available 供管理端深链/按钮。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.query_service import serialize_run
with app.app_context():
user = User(username='arch_outbound_ser', email='arch_outbound_ser@example.com')
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no='ARCH-OUT-SER',
name='Outbound archive serialize',
schedule_type='platform_job',
platform_api_path='freight-rpa-outbound',
owner_user_id=user.id,
cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no='RUN-OUT-SER',
schedule_task_id=task.id,
status='success',
response_summary_json={'raw_outbound_zip_available': True},
)
db.session.add(run)
db.session.commit()
payload = serialize_run(run)
assert payload['outbound_raw_zip_available'] is True
assert payload['inbound_raw_zip_available'] is False
def test_admin_can_download_outbound_raw_zip(app, client, admin_jwt_headers, tmp_path):
"""管理端 outbound-raw-zip 应返回 ZIP 与展示名。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_download_name
archive_dir = tmp_path / 'outbound_archives'
archive_dir.mkdir()
zip_path = archive_dir / 'RUNOUTDL1.zip'
zip_path.write_bytes(b'PK\x03\x04outbound-zip')
app.config['FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR'] = str(archive_dir)
with app.app_context():
user = User(username='outbound-zip-admin', email='outbound-zip-admin@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no='SCH-OUT-DL',
name='Outbound zip download',
schedule_type='platform_job',
platform_api_path='freight-rpa-outbound',
owner_user_id=user.id,
cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no='RUNOUTDL1',
schedule_task_id=task.id,
status='success',
response_summary_json={
'raw_outbound_zip_available': True,
'raw_outbound_zip_path': str(zip_path.resolve()),
},
)
db.session.add(run)
db.session.commit()
run_id = run.id
expected_name = outbound_raw_zip_download_name(run)
response = client.get(
f'/api/admin/schedule-runs/{run_id}/outbound-raw-zip',
headers=admin_jwt_headers,
)
assert response.status_code == 200
assert response.mimetype == 'application/zip'
disposition = response.headers.get('Content-Disposition') or ''
assert expected_name in disposition or quote(expected_name) in disposition
assert response.data == b'PK\x03\x04outbound-zip'
@@ -0,0 +1,228 @@
"""
tests/test_freight_rpa_outbound_callback.py
用途:锁定出站 RPA 回调跨机路径契约、schema 校验与 ingest 归档投递。
依赖:pytest、app 夹具、freight_rpa.outbound.report_archive、
freight_rpa.reports.dispatch、freight_rpa API 蓝图。
逻辑:Worker(Windows)与后端(Linux)分属两机;file_path 只认 outbound drop
根内文件名。本文件先锁 Windows 绝对路径 / 裸文件名 / 穿越拒绝,再锁
schema 4xx、ingest 归档后 dispatch_report_fact,以及三条回调路由鉴权。
"""
from __future__ import annotations
import hashlib
import pytest
@pytest.fixture(autouse=True)
def _isolate_callback_registries():
"""隔离 sink / report handler 注册表,避免测内临时 register 串扰其它用例。"""
from app.services.freight_rpa.common import callback_sinks
from app.services.freight_rpa.reports import dispatch as dispatch_module
saved_sinks = dict(callback_sinks._SINKS)
saved_handlers = dict(dispatch_module._REPORT_HANDLERS)
yield
callback_sinks._SINKS.clear()
callback_sinks._SINKS.update(saved_sinks)
dispatch_module._REPORT_HANDLERS.clear()
dispatch_module._REPORT_HANDLERS.update(saved_handlers)
def test_read_outbound_callback_file_accepts_windows_absolute_path(tmp_path, app):
"""Worker 上报 C:\\...\\drop\\foo.xlsx 时,Linux 侧只按文件名拼本机 drop 根。"""
drop = tmp_path / "outbound_drop"
drop.mkdir()
target = drop / "foo.xlsx"
target.write_bytes(b"PK\x03\x04fake")
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file
data = _read_outbound_callback_file(r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx")
assert data.startswith(b"PK")
def test_read_outbound_callback_file_accepts_bare_filename(tmp_path, app):
"""file_path 仅为 foo.xlsx 时同样定位到本机 outbound drop 根内同名文件。"""
drop = tmp_path / "outbound_drop"
drop.mkdir()
target = drop / "foo.xlsx"
target.write_bytes(b"PK\x03\x04fake")
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file
data = _read_outbound_callback_file("foo.xlsx")
assert data.startswith(b"PK")
def test_read_outbound_callback_file_rejects_traversal(tmp_path, app):
"""带 ..\\ 的路径必须拒绝,禁止按 Linux 路径打开 Worker 上报串。"""
drop = tmp_path / "outbound_drop"
drop.mkdir()
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file
from app.core.errors import ValidationError
with pytest.raises(ValidationError):
_read_outbound_callback_file(r"..\..\etc\passwd")
def test_ingest_outbound_callback_rejects_invalid_schema(app):
"""错误 schema_version 必须在 commit / 投递之前以 4xx ValidationError 失败。"""
from app.core.errors import ValidationError
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
with app.app_context():
with pytest.raises(ValidationError) as excinfo:
ingest_outbound_callback({"schema_version": "freight_rpa.inbound.v1", "callback_id": "x"})
assert excinfo.value.http_status == 400
assert excinfo.value.code == "SHIPPING.OUTBOUND_CALLBACK_INVALID"
TEST_TOOL_KEY = "test-tool-key"
SEED_SOURCE_CODE = "DSV360_AWSDU"
def _awaiting_outbound_unit(*, callback_id: str):
"""构造 awaiting_rpa 出站单元,source_id 挂种子站点以满足外键。"""
from app.models import FreightRpaOutboundUnitRun, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
return FreightRpaOutboundUnitRun(
source_id=source.id,
source_code=source.source_code,
connector_type="dbs",
callback_id=callback_id,
status="awaiting_rpa",
config_snapshot_json={},
)
def test_ingest_outbound_callback_archives_and_dispatches_fact(tmp_path, app, monkeypatch):
"""success 回调按 Windows 绝对路径只认文件名归档,并投递 report_kind=outbound 事实。"""
from app import db
from app.models import FreightRpaOutboundReportFile
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
drop = tmp_path / "outbound_drop"
drop.mkdir()
payload_bytes = b"PK\x03\x04fake"
(drop / "foo.xlsx").write_bytes(payload_bytes)
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
unit = _awaiting_outbound_unit(callback_id="outbound-cb-archive")
db.session.add(unit)
db.session.commit()
monkeypatch.setattr(
"app.services.freight_rpa.outbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
seen: list[ReportFact] = []
register_report_handler("outbound", seen.append)
result = ingest_outbound_callback({
"schema_version": "freight_rpa.outbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx",
"original_filename": "foo.xlsx",
"sha256": hashlib.sha256(payload_bytes).hexdigest(),
})
assert result["status"] == "success"
assert FreightRpaOutboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
assert len(seen) == 1
fact = seen[0]
assert fact.report_kind == "outbound"
assert fact.ok is True
assert fact.file_id == result["file_id"]
assert fact.unit_run_id == unit.id
def test_ingest_outbound_empty_dispatches_failure_fact(app):
"""empty 终态先 commit 再投递 ok=False 事实,不读 drop 文件。"""
from app import db
from app.models import FreightRpaOutboundUnitRun
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
with app.app_context():
unit = _awaiting_outbound_unit(callback_id="outbound-cb-empty")
db.session.add(unit)
db.session.commit()
seen: list[ReportFact] = []
register_report_handler("outbound", seen.append)
result = ingest_outbound_callback({
"schema_version": "freight_rpa.outbound.v1",
"callback_id": unit.callback_id,
"status": "empty",
"error_code": "no_outbound_data",
"error_message": "no_outbound_data",
})
assert result["status"] == "empty"
db.session.expire_all()
saved = db.session.get(FreightRpaOutboundUnitRun, unit.id)
assert saved.status == "empty"
assert saved.error_code == "no_outbound_data"
assert len(seen) == 1
assert seen[0].report_kind == "outbound"
assert seen[0].ok is False
assert seen[0].error_code == "no_outbound_data"
def test_outbound_callback_routes_require_auth(client, app):
"""三条出站回调路由与入站同 ToolApiKey:无 Header 必须 401。"""
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = TEST_TOOL_KEY
for path in (
"/api/freight-rpa/outbound-batch-ready",
"/api/freight-rpa/outbound-unit-progress",
"/api/freight-rpa/outbound-batch-progress",
):
assert client.post(path, json={}).status_code == 401, path
def test_outbound_callback_routes_are_registered(client, app):
"""组合根已注册 outbound sinks:空载荷不得 404 SINK_NOT_REGISTERED。
核心逻辑:batch-ready 空载荷穿透到 ingest 业务校验(400);
progress 空载荷走 schema 非法分支(200 + updated=False)。
"""
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = TEST_TOOL_KEY
headers = {"Authorization": f"Bearer {TEST_TOOL_KEY}"}
ready = client.post("/api/freight-rpa/outbound-batch-ready", json={}, headers=headers)
assert ready.status_code == 400, ready.get_json()
assert ready.get_json()["error"]["code"] == "SHIPPING.OUTBOUND_CALLBACK_INVALID"
for path in (
"/api/freight-rpa/outbound-unit-progress",
"/api/freight-rpa/outbound-batch-progress",
):
resp = client.post(path, json={}, headers=headers)
assert resp.status_code == 200, (path, resp.status_code, resp.get_json())
body = resp.get_json()
assert body["success"] is True
assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"}
def test_outbound_batch_ready_invalid_schema_is_400_when_sink_registered(client, app):
"""sink 在测内临时注册后,错误 schema 穿透到 ingest → 400 SHIPPING.OUTBOUND_CALLBACK_INVALID。"""
from app.services.freight_rpa.common.callback_sinks import register_sink
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
def _ready_sink(**payload):
return {"success": True, "data": ingest_outbound_callback(payload)}
register_sink("outbound-batch-ready", _ready_sink)
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = TEST_TOOL_KEY
resp = client.post(
"/api/freight-rpa/outbound-batch-ready",
json={},
headers={"Authorization": f"Bearer {TEST_TOOL_KEY}"},
)
assert resp.status_code == 400
assert resp.get_json()["error"]["code"] == "SHIPPING.OUTBOUND_CALLBACK_INVALID"
@@ -0,0 +1,183 @@
"""
backend/tests/test_freight_rpa_outbound_job.py
用途:锁定出站 RPA 排程 fail-closed 口径——空 eligible source 不进入 awaiting,
Worker 离线立即 failed 且不写 trigger / 不落 unit;并哨兵 scheduler/internal jobs 接线。
依赖:freight_rpa_outbound_job、FreightRpaOutbound* 模型、job_registry、scheduler_service、internal jobs。
逻辑:对照入站 test_freight_receipt_rpa_schedule 的空源/离线用例;被 pytest 直接导入。
"""
from __future__ import annotations
def test_outbound_schedule_fails_closed_when_no_eligible_sources(app, monkeypatch):
"""无已启用出站配置时排程跳过,不写 trigger、不落 unit、不进入 awaiting。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaOutboundUnitRun
from app.services.schedule.freight_rpa_outbound_job import (
AWAITING_OUTBOUND_RPA_CALLBACK_STATUS,
run_freight_rpa_outbound_schedule,
)
with app.app_context():
task = ScheduleTask(
schedule_no='SCH-OUTBOUND-EMPTY',
name='Outbound empty',
schedule_type='platform_job',
platform_api_path='freight-rpa-outbound',
owner_user_id=1,
cron_expr='0 8 * * *',
job_params={'source_codes': []},
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(run_no='RUN-OUTBOUND-EMPTY', schedule_task_id=task.id, status='running')
db.session.add(run)
db.session.commit()
trigger_calls = []
monkeypatch.setattr(
'app.services.schedule.freight_rpa_outbound_job.write_outbound_export_batch_trigger',
lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json',
)
total, success, failed, skipped, details, errors, logs = run_freight_rpa_outbound_schedule(task, run)
# [断言意图] 空 eligible source fail-closed:计 skipped、不入库 unit、不写 trigger。
assert (total, success, failed, skipped) == (0, 0, 0, 1)
assert details == []
assert errors == ['no enabled outbound report sources']
assert trigger_calls == []
assert FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0
assert any(isinstance(log, dict) and log.get('status') == 'skipped' for log in logs)
assert not any(
isinstance(log, dict) and log.get('status') == AWAITING_OUTBOUND_RPA_CALLBACK_STATUS
for log in logs
)
def test_outbound_schedule_fails_fast_when_worker_offline(app, monkeypatch):
"""出站 Worker 离线时排程立即 failed,不写 trigger、不落 unit。"""
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import (
ScheduleRun,
ScheduleTask,
FreightRpaSource,
FreightRpaOutboundReportConfig,
FreightRpaOutboundUnitRun,
)
from app.services.schedule.freight_rpa_outbound_job import (
AWAITING_OUTBOUND_RPA_CALLBACK_STATUS,
run_freight_rpa_outbound_schedule,
)
from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={
'program_group': 'Bison',
'program_label': 'AWSBI',
'report_group': 'Outbound',
'report_name': 'Outbound Detail',
},
query_parameters_json=[],
))
task = ScheduleTask(
schedule_no='SCH-OUTBOUND-OFFLINE',
name='Outbound offline',
schedule_type='platform_job',
platform_api_path='freight-rpa-outbound',
owner_user_id=1,
cron_expr='0 8 * * *',
job_params={'source_codes': [source.source_code]},
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(run_no='RUN-OUTBOUND-OFFLINE', schedule_task_id=task.id, status='running')
db.session.add(run)
db.session.commit()
trigger_calls = []
monkeypatch.setattr(
'app.services.schedule.freight_rpa_outbound_job.assert_outbound_rpa_worker_ready',
lambda: (_ for _ in ()).throw(ServiceUnavailableError(
RPA_WORKER_OFFLINE_MESSAGE,
code='RPA.WORKER_OFFLINE',
details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'outbound worker offline'},
)),
)
monkeypatch.setattr(
'app.services.schedule.freight_rpa_outbound_job.write_outbound_export_batch_trigger',
lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json',
)
total, success, failed, skipped, details, errors, logs = run_freight_rpa_outbound_schedule(task, run)
# [断言意图] fail-fast:计 failed、不入库 unit、不写 trigger、不进入 awaiting。
assert (total, success, failed, skipped) == (1, 0, 1, 0)
assert details == []
assert errors == ['outbound worker offline']
assert trigger_calls == []
assert FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0
failed_log = next(log for log in logs if isinstance(log, dict) and log.get('status') == 'failed')
assert failed_log['detail'].get('reasons') == ['no_worker_heartbeat']
assert failed_log['detail'].get('error_code') == 'RPA.WORKER_OFFLINE'
assert not any(
isinstance(log, dict) and log.get('status') == AWAITING_OUTBOUND_RPA_CALLBACK_STATUS
for log in logs
)
def test_outbound_platform_jobs_are_registered():
"""平台 Job 必须注册 freight-rpa-outbound 与 freight-rpa-outbound-retention。"""
from app.services.schedule.job_registry import get_platform_job
outbound = get_platform_job('freight-rpa-outbound')
retention = get_platform_job('freight-rpa-outbound-retention')
assert outbound is not None
assert retention is not None
assert outbound.key == 'freight-rpa-outbound'
assert retention.key == 'freight-rpa-outbound-retention'
def test_outbound_defer_is_wired_next_to_inbound_defer():
"""哨兵:出站 awaiting 延后终态与入队前超时回收必须挂在入站同路径。"""
import inspect
from app.api.internal import jobs as internal_jobs
from app.services.schedule import queue_service, scheduler_service
scheduler_src = inspect.getsource(scheduler_service)
jobs_src = inspect.getsource(internal_jobs)
queue_src = inspect.getsource(queue_service)
# [断言意图] recover / should_defer / apply_deferred 必须出现在入站同名调用之后,
# 否则出站 run 写完 trigger 会被立刻标 success,回调永远对不上等待态。
inbound_recover = scheduler_src.index('recover_stale_inbound_rpa_schedule_runs(task)')
assert scheduler_src.index('recover_stale_outbound_rpa_schedule_runs(task)') > inbound_recover
inbound_defer = scheduler_src.index('should_defer_inbound_schedule_run(task, step_logs)')
assert scheduler_src.index('should_defer_outbound_schedule_run(task, step_logs)') > inbound_defer
assert 'apply_deferred_outbound_schedule_run_state(' in scheduler_src
jobs_inbound_recover = jobs_src.index('recover_stale_inbound_rpa_schedule_runs(task)')
assert jobs_src.index('recover_stale_outbound_rpa_schedule_runs(task)') > jobs_inbound_recover
jobs_inbound_defer = jobs_src.index('should_defer_inbound_schedule_run(task, step_logs)')
assert jobs_src.index('should_defer_outbound_schedule_run(task, step_logs)') > jobs_inbound_defer
assert 'apply_deferred_outbound_schedule_run_state(' in jobs_src
assert "'awaiting_outbound_rpa_callback': True" in jobs_src
# [断言意图] 入队前两处(手动 enqueue / Cron 到期扫描)都必须回收出站超时 run,
# 否则同任务互斥会把后续 Cron/手动挡在过期 awaiting 上。
assert queue_src.count('recover_stale_inbound_rpa_schedule_runs(task)') == 2
assert queue_src.count('recover_stale_outbound_rpa_schedule_runs(task)') == 2
# [断言意图] 每轮领取维护区必须全量扫描出站超时 run 与孤儿单元,且位于启动竖旗之后。
marker_init = queue_src.index('_worker_initialized = True')
assert queue_src.index('recover_all_stale_outbound_rpa_schedule_runs()') > marker_init
assert queue_src.index('recover_all_stale_orphan_outbound_units()') > marker_init
assert queue_src.index('recover_all_stale_outbound_rpa_schedule_runs()') > queue_src.index(
'recover_all_stale_inbound_rpa_schedule_runs()'
)
@@ -0,0 +1,18 @@
"""
backend/tests/test_freight_rpa_outbound_models.py
用途:锁定出站 RPA 三模型的类导出与表名,防止建表时漂移或漏导出。
依赖:app.models 聚合导出的 FreightRpaOutbound* 类。
逻辑:被 pytest 直接导入;不连数据库。生产侧漏建类时本文件 import 即失败。
"""
from __future__ import annotations
from app.models import FreightRpaOutboundReportConfig, FreightRpaOutboundUnitRun, FreightRpaOutboundReportFile
def test_outbound_model_tablenames():
"""出站配置 / 单元运行 / 归档文件必须使用规格表名。"""
assert FreightRpaOutboundReportConfig.__tablename__ == "freight_rpa_outbound_report_configs"
assert FreightRpaOutboundUnitRun.__tablename__ == "freight_rpa_outbound_rpa_unit_runs"
assert FreightRpaOutboundReportFile.__tablename__ == "freight_rpa_outbound_report_files"
@@ -0,0 +1,103 @@
"""
backend/tests/test_freight_rpa_outbound_notifications.py
用途:锁定出站排程终态企微通知必须附带 raw outbound ZIP(与入站对称)。
依赖:scheduler_service._notify_schedule_run_wecom、outbound archive 下载名、企微 notify 门禁。
逻辑:直接调用通用排程出口;断言 textcard 文案、ZIP 上传/发送与 outbound_raw_zip 审计事件。
"""
from __future__ import annotations
def _patch_unified_wecom(monkeypatch):
"""拦截通用排程出口的企微调用,返回可断言的捕获列表。"""
textcards: list[tuple[str, str]] = []
media_uploads: list[str] = []
file_sends: list[str] = []
notify_mod = 'app.services.integrations.wecom.notify'
def _fake_send_textcard(_userid, _title, description, _jump_url):
textcards.append((_title, description))
return {'errcode': 0}
monkeypatch.setattr(f'{notify_mod}.send_wecom_textcard_message', _fake_send_textcard)
monkeypatch.setattr(f'{notify_mod}._get_enabled_events', lambda: {'schedule_completed'})
monkeypatch.setattr(
f'{notify_mod}.upload_wecom_temp_media',
lambda _data, filename: media_uploads.append(filename) or f'media-{len(media_uploads)}',
)
monkeypatch.setattr(
f'{notify_mod}.send_wecom_file_message',
lambda _userid, media_id: file_sends.append(media_id) or {'errcode': 0},
)
return textcards, media_uploads, file_sends
def test_notify_schedule_run_wecom_attaches_outbound_raw_zip(app, monkeypatch, tmp_path):
"""出站 run 企微完成通知须上传并发送 raw outbound ZIP,审计事件为 schedule_completed_outbound_raw_zip。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, User, WecomNotifyAudit
from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_download_name
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
archive_dir = tmp_path / 'outbound-archives'
archive_dir.mkdir()
zip_path = archive_dir / 'RUNOUTWECOM1.zip'
zip_path.write_bytes(b'PK\x03\x04outbound-notify')
with app.app_context():
app.config['FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR'] = str(archive_dir)
app.config['WECOM_NOTIFY_ENABLED'] = True
app.config['WECOM_PUBLIC_BASE_URL'] = 'https://hxops.example.com'
recipient = User(
username='outbound-zip-notify',
email='outbound-zip-notify@example.com',
role='user',
status='active',
wecom_userid='outbound-zip-user',
)
db.session.add(recipient)
db.session.flush()
task = ScheduleTask(
schedule_no='SCH-OUT-WECOM-ZIP',
name='Outbound wecom zip',
schedule_type='platform_job',
platform_api_path='freight-rpa-outbound',
owner_user_id=recipient.id,
cron_expr='0 8 * * *',
notify_enabled=True,
notify_user_ids_json=[recipient.id],
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no='RUNOUTWECOM1',
schedule_task_id=task.id,
status='success',
excel_file_data=b'excel-bytes',
excel_file_name='出站RPA-20261019-1546-结果.xlsx',
response_summary_json={
'raw_outbound_zip_available': True,
'raw_outbound_zip_path': str(zip_path.resolve()),
},
)
db.session.add(run)
db.session.commit()
expected_zip_name = outbound_raw_zip_download_name(run)
textcards, media_uploads, file_sends = _patch_unified_wecom(monkeypatch)
_notify_schedule_run_wecom(task, run)
# [断言意图] 与入站对称:textcard 提示包已随通知发送,并上传 Excel + 出站 ZIP。
assert len(textcards) == 1
assert '原始出站包:已随本通知发送' in textcards[0][1]
assert media_uploads[0] == run.excel_file_name
assert media_uploads[1] == expected_zip_name
assert file_sends == ['media-1', 'media-2']
assert run.wecom_notified is True
zip_audits = WecomNotifyAudit.query.filter_by(
event_type='schedule_completed_outbound_raw_zip',
).all()
assert len(zip_audits) == 1
assert zip_audits[0].content == f'[原始出站包] {expected_zip_name}'
assert zip_audits[0].status == 'sent'
@@ -0,0 +1,45 @@
"""
backend/tests/test_freight_rpa_outbound_rename_gate.py
用途:Task 14 单发布总闸门——grep 断言改名、出站异动解析分支、无 outbound 投递表引用。
依赖:pathlib、pytest。
逻辑:只读扫描 backend/app 与关键路由文件;不替代 inbound slim gate 或批次 S grep gate。
"""
from __future__ import annotations
from pathlib import Path
BACKEND_ROOT = Path(__file__).resolve().parents[1]
_OUTBOUND_DELIVERY_TOKENS = (
'freight_rpa_outbound_notification_deliveries',
'FreightRpaOutboundNotificationDelivery',
'outbound_notification_deliveries',
)
def test_no_receipt_raw_zip_route():
"""排程 run 下载路由已改为 inbound-raw-zip,不得保留 receipt-raw-zip。"""
text = (BACKEND_ROOT / 'app/api/schedule/runs.py').read_text(encoding='utf-8')
assert 'receipt-raw-zip' not in text
assert 'inbound-raw-zip' in text
def test_outbound_purpose_not_catalog_in_validate_docstring():
"""outbound 与 inbound 共用异动字段分支,而非库存字段目录。"""
text = (
BACKEND_ROOT / 'app/services/freight_rpa/parsing_profile.py'
).read_text(encoding='utf-8')
assert "purpose in {'inbound', 'outbound'}" in text or 'purpose in {"inbound", "outbound"}' in text
def test_no_outbound_notification_deliveries_table_reference():
"""backend/app 不得引用出站逐文件企微投递表或模型符号。"""
hits: list[str] = []
for path in (BACKEND_ROOT / 'app').rglob('*.py'):
text = path.read_text(encoding='utf-8')
for token in _OUTBOUND_DELIVERY_TOKENS:
if token in text:
hits.append(f'{path.relative_to(BACKEND_ROOT)}:{token}')
assert hits == []
@@ -0,0 +1,313 @@
"""
tests/test_freight_rpa_outbound_report_config_api.py
用途:锁定来源站点出站报表配置 Admin API 的绑定校验、路径规则与启用门禁边界。
依赖:Flask 管理 API、库存站点测试种子、FreightRpaOutboundReportConfig、货代统一审计事件。
逻辑:请求打到 /api/admin/freight-rpa/sources/<id>/outbound-report-config;
解析绑定必须 published 且 purpose=outbound;保存只写出站配置,不改在手/入站,也不进入启用硬门槛;
parsing_profile.retire 须拦截仍绑定出站配置的 published 规则。
"""
from __future__ import annotations
import pytest
from app import db
from app.models import (
FreightRpaInboundReportConfig,
FreightRpaOutboundReportConfig,
FreightRpaParsingProfile,
FreightRpaSource,
ShippingAuditEvent,
User,
)
from tests.conftest import parse_api_data, parse_api_error
def _headers(username: str, role: str) -> dict[str, str]:
"""构造当前管理 API 使用的 Header 身份上下文。"""
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
@pytest.fixture(autouse=True)
def _admin_user(app):
"""关闭 JWT 并播种 admin/user,使 conftest.admin_headers 的 X-Username=admin 可解析。"""
from app import db
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
if User.query.filter_by(username='admin').first() is None:
db.session.add(User(username='admin', email='admin@example.com', role='admin', status='active'))
if User.query.filter_by(username='outbound-user').first() is None:
db.session.add(User(
username='outbound-user', email='outbound-user@example.com', role='user', status='active',
))
db.session.commit()
@pytest.fixture
def source_id(app) -> int:
"""conftest 播种的 DBS 站点主键。"""
with app.app_context():
return FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one().id
@pytest.fixture
def onhand_profile_id(app) -> int:
"""conftest 播种的已发布 onhand 解析规则主键,用于证明出站拒绝跨 purpose 绑定。"""
with app.app_context():
profile = FreightRpaParsingProfile.query.filter_by(profile_code='TEST_RUNTIME', status='published').one()
assert profile.purpose == 'onhand'
return profile.id
def _dbs_payload() -> dict:
"""构造 DBS 出站配置;Warehouse 为可选筛选,日期不出现。"""
return {
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Outbound', 'report_name': 'Outbound Detail',
},
'query_parameters_json': [
{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['AWSDU'], 'required': False, 'select_all': False},
],
}
def _create_parsing_profile(profile_code: str, *, status: str, purpose: str) -> FreightRpaParsingProfile:
"""创建出站/入站/在手解析 Profile 种子;定义仅用于绑定校验。"""
profile = FreightRpaParsingProfile(
purpose=purpose, profile_code=profile_code, display_name=f'{profile_code} 规则',
version=1, status=status, file_format='xlsx',
definition_json={
'sheet_name': 'Movement', 'header_row_index': 1,
'field_mapping': {
'doc_no': '单据编号', 'material_code': '料号',
'quantity': '数量', 'movement_date': '异动日期',
},
'match_keys': [],
},
)
db.session.add(profile)
db.session.commit()
return profile
def test_put_outbound_report_config_requires_outbound_profile(client, admin_headers, source_id, onhand_profile_id):
"""绑定 onhand 解析规则时必须 400/422(出站只允许 purpose=outbound)。"""
resp = client.put(
f"/api/admin/freight-rpa/sources/{source_id}/outbound-report-config",
json={"parsing_profile_id": onhand_profile_id, "report_path_json": {}, "query_parameters_json": []},
headers=admin_headers,
)
assert resp.status_code in (400, 422)
def test_put_outbound_report_config_rejects_non_outbound_profile_with_valid_path(
client, admin_headers, source_id, onhand_profile_id, app,
):
"""合法 DBS 路径下仍拒绝 onhand / inbound / draft / 不存在的解析绑定。"""
with app.app_context():
inbound = _create_parsing_profile('OUT_CFG_INBOUND', status='published', purpose='inbound')
draft = _create_parsing_profile('OUT_CFG_DRAFT', status='draft', purpose='outbound')
cases = [onhand_profile_id, inbound.id, draft.id, 999999]
for profile_id in cases:
response = client.put(
f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config',
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
headers=admin_headers,
)
assert response.status_code == 400, f'profile_id={profile_id}'
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.OUTBOUND_PROFILE_INVALID'
def test_put_outbound_report_config_saves_published_outbound_and_audit(
client, admin_headers, source_id, app,
):
"""已发布 outbound 规则可保存;payload 回显绑定摘要,审计 event 为 shipping_outbound_report_config_saved。"""
with app.app_context():
profile = _create_parsing_profile('OUT_MOVE_STD', status='published', purpose='outbound')
profile_id = profile.id
source = db.session.get(FreightRpaSource, source_id)
onhand_before = {
'path': dict(source.onhand_report_config.report_path_json),
'parameters': list(source.onhand_report_config.query_parameters_json),
'config_version': source.config_version,
}
inbound_exists = FreightRpaInboundReportConfig.query.filter_by(source_id=source_id).count()
forbidden = client.put(
f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config',
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
headers=_headers('outbound-user', 'user'),
)
assert forbidden.status_code == 403
missing = client.get(
f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config',
headers=admin_headers,
)
assert missing.status_code == 200
assert parse_api_data(missing.get_json()) is None
response = client.put(
f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config',
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
headers=admin_headers,
)
assert response.status_code == 200
config = parse_api_data(response.get_json())
assert config['parsing_profile_id'] == profile_id
assert config['parsing_profile']['profile_code'] == 'OUT_MOVE_STD'
assert config['parsing_profile']['status'] == 'published'
assert config['report_path_json']['report_group'] == 'Outbound'
assert config['query_parameters_json'][0]['values'] == ['AWSDU']
fetched = client.get(
f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config',
headers=admin_headers,
)
assert fetched.status_code == 200
assert parse_api_data(fetched.get_json())['parsing_profile_id'] == profile_id
with app.app_context():
source = db.session.get(FreightRpaSource, source_id)
onhand_config = source.onhand_report_config
assert onhand_config.report_path_json == onhand_before['path']
assert onhand_config.query_parameters_json == onhand_before['parameters']
assert source.config_version == onhand_before['config_version']
assert FreightRpaInboundReportConfig.query.filter_by(source_id=source_id).count() == inbound_exists
assert FreightRpaOutboundReportConfig.query.filter_by(source_id=source_id).count() == 1
audit = ShippingAuditEvent.query.filter_by(
event_type='shipping_outbound_report_config_saved', aggregate_id=str(source_id),
).one()
assert audit.before_snapshot_json is None
assert audit.metadata_json['parsing_profile_id'] == profile_id
def test_outbound_report_config_empty_profile_id_unbinds(client, admin_headers, source_id, app):
"""parsing_profile_id 传 None → 解绑,不做校验也不报错。"""
with app.app_context():
profile = _create_parsing_profile('OUT_UNBIND', status='published', purpose='outbound')
profile_id = profile.id
bound = client.put(
f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config',
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
headers=admin_headers,
)
assert bound.status_code == 200
unbound = client.put(
f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config',
json={**_dbs_payload(), 'parsing_profile_id': None},
headers=admin_headers,
)
assert unbound.status_code == 200
assert parse_api_data(unbound.get_json())['parsing_profile_id'] is None
def test_outbound_report_config_rejects_date_filter(client, admin_headers, source_id):
"""出站与入站相同:拒绝日期筛选。"""
invalid_date = _dbs_payload()
invalid_date['query_parameters_json'] = [
{'name': 'Report Date', 'mode': 'single', 'values': ['2026-08-19'], 'required': False, 'select_all': False},
]
response = client.put(
f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config',
json=invalid_date, headers=admin_headers,
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID'
def test_crane_outbound_report_is_fixed_to_outbound_details(client, admin_headers, app):
"""Crane 固定 Outbound Details,拒绝查询条件与其它报表名。"""
from app import db
with app.app_context():
dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
crane_profile = dbs.rpa_profile.__class__(
profile_code='CRANE_OUTBOUND_CFG', display_name='Crane Outbound', connector_type='crane',
login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'},
)
crane_source = FreightRpaSource(
source_code='CRANE_OUTBOUND_CFG', display_name='Crane Outbound', connector_type='crane',
rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE',
enabled=False,
)
db.session.add(crane_source)
db.session.commit()
crane_id = crane_source.id
ok_payload = {
'report_path_json': {'report_name': 'Outbound Details'},
'query_parameters_json': [],
}
response = client.put(
f'/api/admin/freight-rpa/sources/{crane_id}/outbound-report-config',
json=ok_payload, headers=admin_headers,
)
assert response.status_code == 200
assert parse_api_data(response.get_json())['query_parameters_json'] == []
assert parse_api_data(response.get_json())['report_path_json']['report_name'] == 'Outbound Details'
inbound_name = client.put(
f'/api/admin/freight-rpa/sources/{crane_id}/outbound-report-config',
json={'report_path_json': {'report_name': 'Inbound Details'}, 'query_parameters_json': []},
headers=admin_headers,
)
assert inbound_name.status_code == 400
assert parse_api_error(inbound_name.get_json())['code'] == 'SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID'
with_query = client.put(
f'/api/admin/freight-rpa/sources/{crane_id}/outbound-report-config',
json={
'report_path_json': {'report_name': 'Outbound Details'},
'query_parameters_json': [
{'name': 'material', 'mode': 'single', 'values': ['PN-01'], 'required': False, 'select_all': False},
],
},
headers=admin_headers,
)
assert with_query.status_code == 400
assert parse_api_error(with_query.get_json())['code'] == 'SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID'
def test_activation_does_not_require_outbound_report_config(app, source_id):
"""出站配置不是来源站点启用硬门槛:缺出站行不得新增 blocking check。"""
from app.services.admin.freight_rpa_source_admin_service import get_source_activation_status
with app.app_context():
source = db.session.get(FreightRpaSource, source_id)
assert source.outbound_report_config is None
status = get_source_activation_status(source)
check_codes = [item['code'] for item in status['checks']]
assert all('outbound' not in code for code in check_codes)
assert all('outbound' not in str(item) for item in status['missing_requirements'])
def test_retire_rejects_profile_bound_by_outbound_report_config(app, source_id):
"""绑定出站报表配置的 published 解析 Profile 退役必须被拒(与入站守卫对称)。
背景:retire 此前只核查库存源与入站配置,遗漏 FreightRpaOutboundReportConfig。
守卫补查后三者任一绑定都返回 SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED。
"""
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
with app.app_context():
profile = _create_parsing_profile('OUT_RETIRE_GUARD', status='published', purpose='outbound')
db.session.add(FreightRpaOutboundReportConfig(
source_id=source_id, parsing_profile_id=profile.id,
report_path_json={}, query_parameters_json=[],
))
db.session.commit()
profile_id = profile.id
# 关键断言:仅绑定出站配置(无库存源/入站绑定)也必须拒绝退役。
with pytest.raises(Exception) as exc_info:
onhand_parsing_profile.retire(profile_id)
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED'
assert db.session.get(FreightRpaParsingProfile, profile_id).status == 'published'
assert FreightRpaOutboundReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1
@@ -0,0 +1,148 @@
"""
tests/test_freight_rpa_outbound_worker_contract.py
用途:Windows 出站 Worker 脚本静态契约——schema/action、回调 basename、
Crane 固定页、心跳能力、ps1 Worker ID。
依赖:scripts/freight_rpa/outbound/*、common/rpa_heartbeat.py、common/rpa_callbacks.py。
逻辑:Worker 无 pytest 运行时;本文件读常量与源码断言,对齐 inbound
test_freight_receipt_worker_contract.py。Task 12 闸门。
"""
from __future__ import annotations
import importlib.util
import sys
from pathlib import Path
_REPO_ROOT = Path(__file__).resolve().parents[2]
_OUTBOUND_DIR = _REPO_ROOT / "scripts" / "freight_rpa" / "outbound"
_COMMON_DIR = _REPO_ROOT / "scripts" / "freight_rpa" / "common"
def test_outbound_worker_uses_outbound_contract_and_dirs():
"""出站 Worker 只消费 freight_rpa.outbound.v1 / outbound_export_batch 与专用目录。"""
text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8")
assert "FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR" in text
assert "FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR" in text
assert "freight_rpa.outbound.v1" in text
assert "outbound_export_batch" in text
assert "from rpa_callbacks import" in text
assert "OUTBOUND_BATCH_READY" in text
assert "OUTBOUND_BATCH_PROGRESS" in text
assert "OUTBOUND_UNIT_PROGRESS" in text
assert "FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR" not in text
assert "FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR" not in text
assert "INBOUND_BATCH_READY" not in text
def test_outbound_callback_file_path_is_basename_only():
"""
回调 file_path 必须是 Path.name,禁止 Windows 绝对路径当契约主值。
[断言意图] spec §4.2 跨机路径:Worker 只报 drop 根内文件名;
若把 C:\\...\\drop\\xxx.xlsx 整串上报,Linux 后端按原样 open 会 400。
"""
text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8")
assert "'file_path': output.name" in text or '"file_path": output.name' in text
assert "§4.2" in text
assert "'file_path': str(output)" not in text
assert '"file_path": str(output)' not in text
assert "str(output.resolve())" not in text
def test_outbound_dbs_export_maps_report_path_to_navigation():
"""DBS 出站必须把配置 report_path_json 写入 navigation,不得写死库存/入站报表名。"""
text = (_OUTBOUND_DIR / "outbound_dbs_export.py").read_text(encoding="utf-8")
assert "'navigation': report_path" in text
assert "report_path = dict(unit.get('report_path_json') or {})" in text
assert "__export_kind__" in text
assert "'outbound'" in text
def test_outbound_crane_driver_forces_outbound_details_not_inbound():
"""Crane 出站固定 Outbound Details,禁止误用 Inbound Details / On Hand Details。"""
text = (_OUTBOUND_DIR / "outbound_crane_export.py").read_text(encoding="utf-8")
assert "'scheduled_report_name': 'Outbound Details'" in text
assert "outbound-details-query" in text
# 注释可提及禁令;契约主值不得把入站/库存页当出站报表名。
assert "'scheduled_report_name': 'Inbound Details'" not in text
assert "inbound-details-query" not in text
assert "on-hand-details-query" not in text
def test_outbound_crane_entry_url_rewrites_hash_to_outbound_details():
"""复用 Profile 登录地址时必须改写到出站页,不得停在门户首页或入站页。"""
sys.path.insert(0, str(_REPO_ROOT / "scripts" / "freight_rpa"))
spec = importlib.util.spec_from_file_location(
"freight_outbound_crane_export_test",
_OUTBOUND_DIR / "outbound_crane_export.py",
)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
assert module._outbound_details_entry_url("https://wms-portal.craneww.com/#/") == (
"https://wms-portal.craneww.com/#/outbound-details-query"
)
assert module._outbound_details_entry_url("https://wms-portal.craneww.com/") == (
"https://wms-portal.craneww.com/#/outbound-details-query"
)
assert module._outbound_details_entry_url(
"https://wms-portal.craneww.com/#/inbound-details-query"
) == "https://wms-portal.craneww.com/#/outbound-details-query"
def test_outbound_ps1_injects_worker_id_and_outbound_logs():
"""ps1 必须注入 FREIGHT_RPA_WORKER_ID=<host>-outbound 与 outbound logs 目录。"""
ps1 = (_OUTBOUND_DIR / "start_outbound_worker.ps1").read_text(encoding="utf-8")
assert "FREIGHT_RPA_WORKER_ID" in ps1
assert "-outbound" in ps1
assert r"outbound\logs\worker.log" in ps1
assert "FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR" in ps1
assert "FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR" in ps1
assert "start_inbound_worker.ps1" not in ps1
def test_outbound_register_script_has_distinct_task_names():
"""出站计划任务名独立,可与 onhand/inbound 同机并存。"""
receipt = (_OUTBOUND_DIR / "register_outbound_worker_tasks.ps1").read_text(encoding="utf-8")
assert '$TestTask = "HXOPS Freight Outbound RPA Worker TEST"' in receipt
assert '$ProdTask = "HXOPS Freight Outbound RPA Worker PROD"' in receipt
assert "start_outbound_worker.ps1" in receipt
assert "start_inbound_worker.ps1" not in receipt
assert "start_onhand_worker.ps1" not in receipt
assert "AtLogOn" in receipt and "Interactive" in receipt and "Headless" in receipt
def test_outbound_heartbeat_capability_is_outbound_export():
"""脚本心跳须按 *-outbound / outbound trigger 目录声明 outbound_export。"""
text = (_COMMON_DIR / "rpa_heartbeat.py").read_text(encoding="utf-8")
assert "outbound_export" in text
assert "is_outbound" in text or "-outbound" in text
def test_outbound_worker_uses_common_trigger_consumer():
"""出站 Worker 必须复用公共 claim/归档原语。"""
text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8")
assert "claim_trigger" in text
assert "archive_trigger" in text
def test_rpa_callbacks_export_outbound_paths():
"""rpa_callbacks 出站端点须与后端 /api/freight-rpa/outbound-* 对齐。"""
sys.path.insert(0, str(_COMMON_DIR))
import rpa_callbacks # noqa: E402
assert rpa_callbacks.OUTBOUND_BATCH_READY == "/api/freight-rpa/outbound-batch-ready"
assert rpa_callbacks.OUTBOUND_UNIT_PROGRESS == "/api/freight-rpa/outbound-unit-progress"
assert rpa_callbacks.OUTBOUND_BATCH_PROGRESS == "/api/freight-rpa/outbound-batch-progress"
def test_outbound_worker_ready_callback_outside_export_retry():
"""导出重试不得包裹 ready;成功后先 progress 再 basename ready。"""
text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8")
assert "def _post_unit_ready(" in text
assert "ready 回调禁止进入本循环" in text or "重试只覆盖导出/落盘/校验" in text
progress_at = text.find("progress_counts['success'] += 1")
ready_at = text.find("_post_unit_ready(unit, output)")
assert progress_at > 0 and ready_at > progress_at
+35 -35
View File
@@ -23,10 +23,10 @@ from app.models import (
FreightRpaProfile,
FreightRpaSource,
)
from app.services.admin import shipping_onhand_admin_service
from app.services.admin import freight_rpa_source_admin_service, shipping_onhand_admin_service
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
from app.services.shipping_notice import (
onhand_configuration_test,
onhand_parsing_profile,
onhand_structure_analysis,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
@@ -48,13 +48,13 @@ def _workbook(path: Path) -> None:
def _source(code: str = 'TEST_EXPORT_SOURCE', profile_code: str = 'TEST_EXPORT_LOGIN') -> dict:
"""创建一个保持停用的 DBS 库存站点。"""
login = shipping_onhand_admin_service.save_profile({
login = freight_rpa_source_admin_service.save_profile({
'profile_code': profile_code, 'display_name': 'Test Login', 'connector_type': 'dbs',
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
'username': 'user', 'password': 'password', 'enabled': True,
}, actor_id=None)
# s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行,站点载荷不再平铺。
return shipping_onhand_admin_service.save_source({
return freight_rpa_source_admin_service.save_source({
'source_code': code, 'display_name': 'Test Export Source', 'connector_type': 'dbs',
'rpa_profile_id': login['id'], 'excel_template_id': None,
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
@@ -187,7 +187,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend
'run_no': seed_run['run_no'], 'status': 'success', 'file_path': str(analysis_path),
})
profile = _publish_profile_from_analysis(seeded['analysis_id'], field_id, code='EMPTY_RESULT_PROFILE')
shipping_onhand_admin_service.bind_source_parsing_profile(
freight_rpa_source_admin_service.bind_source_parsing_profile(
[source['id']], profile['id'], actor_id=None, reason='空结果前已确认同类报表结构', operation='direct',
)
@@ -201,7 +201,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend
assert result['stage'] == 'empty_data_pending_validation'
assert result['result']['data_validation'] == 'pending_first_non_empty_export'
assert not FreightRpaOnhandReportFile.query.count()
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id'])
# 关键断言:空结果测试不自动启用;本例仍缺发货模板,硬门槛阻断启用。
assert current['enabled'] is False
assert current['activation']['missing_requirements'] == ['excel_template']
@@ -236,7 +236,7 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app,
seed_file = tmp_path / 'bound-profile-seed.xlsx'; _workbook(seed_file)
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BOUND_PROFILE_VERIFY')
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
verified = _complete_test_run(source, tmp_path)
# 关键断言:当前绑定方案无需再出现在候选确认列表,测试直接写入启用所需的确认事实。
@@ -256,16 +256,16 @@ def test_verified_current_profile_does_not_auto_enable_ready_source(app, tmp_pat
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_PROFILE')
template = _published_template(code='AUTO_ENABLE_TEMPLATE')
# s18 起解析绑定走配置行绑定服务,模板绑定仍走站点保存。
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
shipping_onhand_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id'])
freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id'])
freight_rpa_source_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id'])
verified = _complete_test_run(source, tmp_path)
source_model = db.session.get(FreightRpaSource, source['id'])
# 关键断言:测试只写入验证事实,站点保持停用直至管理员显式启用。
assert verified['stage'] == 'current_profile_verified'
assert source_model.enabled is False
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['ready'] is True
assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['ready'] is True
def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path):
@@ -278,13 +278,13 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm
seeded = _complete_test_run(source, tmp_path)
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_BLOCKED')
# s18 起解析绑定走配置行绑定服务;本例不绑模板以验证模板硬门槛。
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
_complete_test_run(source, tmp_path)
source_model = db.session.get(FreightRpaSource, source['id'])
# 关键断言:自动启用始终复用正式门禁,缺少模板不会被测试成功放行。
assert source_model.enabled is False
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path):
@@ -298,9 +298,9 @@ def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path):
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_EMPTY')
template = _published_template(code='AUTO_ENABLE_EMPTY_TEMPLATE')
# s18 起解析绑定走配置行绑定服务,模板绑定仍走站点保存。
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
shipping_onhand_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id'])
freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id'])
freight_rpa_source_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id'])
started = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
completed = onhand_configuration_test.report_test_export({'run_no': started['run_no'], 'status': 'empty'})
@@ -308,7 +308,7 @@ def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path):
# 关键断言:空库存是成功查询事实;硬门槛齐备时仍保持停用,等待显式开关。
assert completed['status'] == 'completed_empty'
assert source_model.enabled is False
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['ready'] is True
assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['ready'] is True
def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path):
@@ -329,7 +329,7 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app,
seed_file = tmp_path / 'batch-seed.xlsx'; _workbook(seed_file)
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BATCH_PROFILE')
shipping_onhand_admin_service.bind_source_parsing_profile(
freight_rpa_source_admin_service.bind_source_parsing_profile(
[first['id'], second['id'], third['id']], profile['id'], actor_id=None, reason='批量验证测试', operation='bulk',
)
@@ -364,7 +364,7 @@ def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
seed_file = tmp_path / 'retry-seed.xlsx'; _workbook(seed_file)
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RETRY_PROFILE')
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='重试测试', operation='bulk')
freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='重试测试', operation='bulk')
batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None)
run = batch['runs'][0]
onhand_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
@@ -386,7 +386,7 @@ def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app,
seed_file = tmp_path / 'stale-batch-seed.xlsx'; _workbook(seed_file)
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='STALE_BATCH_PROFILE')
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='过期回调测试', operation='bulk')
freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='过期回调测试', operation='bulk')
batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None)
run = batch['runs'][0]
source_model = db.session.get(FreightRpaSource, source['id'])
@@ -414,7 +414,7 @@ def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
seed_file = tmp_path / 'restore-batch-seed.xlsx'; _workbook(seed_file)
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RESTORE_BATCH_PROFILE')
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None)
# 关键断言:刷新期间读取服务端 active batch,会返回待 Worker 处理的真实运行。
assert onhand_configuration_test.get_latest_active_validation_batch()['id'] == batch['id']
@@ -436,7 +436,7 @@ def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path)
seed_file = tmp_path / 'progress-batch-seed.xlsx'; _workbook(seed_file)
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='PROGRESS_BATCH_PROFILE')
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None)
run = batch['runs'][0]
@@ -468,8 +468,8 @@ def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_
first = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
assert onhand_configuration_test.get_latest_test_run(source['id'])['run_no'] == first['run_no']
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
shipping_onhand_admin_service.save_source({**current, 'display_name': 'Changed before callback'}, actor_id=None, source_id=source['id'])
current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id'])
freight_rpa_source_admin_service.save_source({**current, 'display_name': 'Changed before callback'}, actor_id=None, source_id=source['id'])
# 关键断言:旧运行不再属于当前配置,重新测试必须创建新运行而不是误复用。
assert onhand_configuration_test.get_latest_test_run(source['id']) is None
@@ -523,7 +523,7 @@ def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, t
db.session.commit()
seed = _complete_test_run(first, tmp_path)
profile = _publish_profile_from_analysis(seed['analysis_id'], _published_order_field(), code='TIMEOUT_QUEUE_PROFILE')
shipping_onhand_admin_service.bind_source_parsing_profile([first['id'], second['id']], profile['id'], actor_id=None, operation='bulk')
freight_rpa_source_admin_service.bind_source_parsing_profile([first['id'], second['id']], profile['id'], actor_id=None, operation='bulk')
batch = onhand_configuration_test.start_batch_test_export([first['id'], second['id']], actor_id=None)
queued_run = FreightRpaOnhandConfigurationTestRun.query.filter_by(source_id=second['id']).one()
queued_run.created_at = datetime.utcnow() - timedelta(seconds=15)
@@ -553,9 +553,9 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
source_model = db.session.get(FreightRpaSource, source['id'])
# s18 起解析绑定归 onhand_report_config 配置行,站点行不再有 parsing_profile_id。
assert source_model.onhand_report_config.parsing_profile_id == profile['id']
assert 'configuration_test' not in shipping_onhand_admin_service.get_source_activation_status(source_model)['missing_requirements']
assert 'configuration_test' not in freight_rpa_source_admin_service.get_source_activation_status(source_model)['missing_requirements']
# 关键断言:外部仓库映射只在调拨前校验,不应出现在站点启用阻断清单。
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
template = ShippingExcelTemplate(
template_code='TEST_ACTIVATION', display_name='Activation Template', version=1, status='published',
@@ -570,10 +570,10 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
db.session.flush()
source_model.excel_template_id = template.id
db.session.commit()
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['ready'] is True
assert shipping_onhand_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True
assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['ready'] is True
assert freight_rpa_source_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True
assert 'configuration_test' not in {
item['code'] for item in shipping_onhand_admin_service.get_source_activation_status(source_model)['checks']
item['code'] for item in freight_rpa_source_admin_service.get_source_activation_status(source_model)['checks']
}
@@ -594,7 +594,7 @@ def test_rpa_profile_change_does_not_block_activation_hard_gates(app, tmp_path):
db.session.commit()
rpa_profile = db.session.get(FreightRpaProfile, source['rpa_profile_id'])
shipping_onhand_admin_service.save_profile({
freight_rpa_source_admin_service.save_profile({
'profile_code': rpa_profile.profile_code, 'display_name': rpa_profile.display_name,
'connector_type': rpa_profile.connector_type, 'login_url': rpa_profile.login_url,
'login_config_json': rpa_profile.login_config_json, 'enabled': True,
@@ -602,11 +602,11 @@ def test_rpa_profile_change_does_not_block_activation_hard_gates(app, tmp_path):
}, actor_id=None, profile_id=rpa_profile.id)
source_model = db.session.get(FreightRpaSource, source['id'])
status = shipping_onhand_admin_service.get_source_activation_status(source_model)
status = freight_rpa_source_admin_service.get_source_activation_status(source_model)
# 关键断言:连接变更不再把测试导出塞进启用门禁;硬门槛齐备即可启用。
assert 'configuration_test' not in {item['code'] for item in status['checks']}
assert status['ready'] is True
assert shipping_onhand_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True
assert freight_rpa_source_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True
def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path):
@@ -620,8 +620,8 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
completed = _complete_test_run(source, tmp_path)
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_STALE')
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
shipping_onhand_admin_service.save_source({**current, 'display_name': 'Changed after test'}, actor_id=None, source_id=source['id'])
current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id'])
freight_rpa_source_admin_service.save_source({**current, 'display_name': 'Changed after test'}, actor_id=None, source_id=source['id'])
with pytest.raises(ConflictError) as stale:
onhand_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
assert stale.value.code == 'SHIPPING.ONHAND_CONFIGURATION_TEST_STALE'
+27 -17
View File
@@ -1,6 +1,6 @@
"""
用途:验证可复用库存解析 Profile 的版本、共享绑定和订单字段匹配键门禁。
依赖:onhand_parsing_profile、shipping_onhand_admin_service、订单 Schema 服务。
依赖:freight_rpa.parsing_profile、freight_rpa_source_admin_service、订单 Schema 服务。
逻辑:发布一个 Profile 后绑定多个 Source;新版本并存且旧绑定稳定,非法字段、退役引用或非发布绑定被拒绝。
"""
@@ -8,8 +8,8 @@ from cryptography.fernet import Fernet
import pytest
from app.core.errors import ValidationError
from app.services.admin import shipping_onhand_admin_service
from app.services.shipping_notice import onhand_parsing_profile
from app.services.admin import freight_rpa_source_admin_service
from app.services.freight_rpa import parsing_profile as 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, FreightRpaOnhandField, FreightRpaOnhandStructureAnalysis
@@ -84,14 +84,21 @@ def _schema_field_config(field_id: str) -> dict:
def _source(profile_id: int, parsing_id: int, code: str) -> dict:
"""构造绑定共享解析 Profile 的 DBS 库存源。"""
"""构造绑定共享解析 Profile 的 DBS 库存源(s18:解析绑定走 onhand_report_config)。"""
return {
'source_code': code, 'display_name': code, 'connector_type': 'dbs',
'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_id,
'rpa_profile_id': profile_id,
'excel_template_id': _excel_template_id(),
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': code,
'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
'query_parameters_json': [], 'snapshot_ttl_seconds': 3600, 'enabled': True,
'snapshot_ttl_seconds': 3600, 'enabled': True,
'onhand_report_config': {
'parsing_profile_id': parsing_id,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand',
},
'query_parameters_json': [],
},
}
@@ -117,16 +124,16 @@ def test_published_parsing_profile_can_be_shared_by_sources(app):
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
parsing = _published_profile()
login = shipping_onhand_admin_service.save_profile({
login = freight_rpa_source_admin_service.save_profile({
'profile_code': 'DBS_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs',
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
'username': 'u', 'password': 'p', 'enabled': True,
}, actor_id=None)
first = shipping_onhand_admin_service.save_source(_source(login['id'], parsing['id'], 'DUB'), actor_id=None)
second = shipping_onhand_admin_service.save_source(_source(login['id'], parsing['id'], 'RTM'), actor_id=None)
first = freight_rpa_source_admin_service.save_source(_source(login['id'], parsing['id'], 'DUB'), actor_id=None)
second = freight_rpa_source_admin_service.save_source(_source(login['id'], parsing['id'], 'RTM'), actor_id=None)
assert first['parsing_profile_id'] == parsing['id']
assert second['parsing_profile_id'] == parsing['id']
assert first['onhand_report_config']['parsing_profile_id'] == parsing['id']
assert second['onhand_report_config']['parsing_profile_id'] == parsing['id']
assert onhand_parsing_profile.list_profiles()[0]['source_count'] == 2
@@ -144,13 +151,13 @@ def test_source_rejects_draft_parsing_profile(app):
},
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
}, actor_id=None)
login = shipping_onhand_admin_service.save_profile({
login = freight_rpa_source_admin_service.save_profile({
'profile_code': 'LOGIN', 'display_name': 'Login', 'connector_type': 'dbs',
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
'username': 'u', 'password': 'p', 'enabled': True,
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_onhand_admin_service.save_source(_source(login['id'], draft['id'], 'DUB'), actor_id=None)
freight_rpa_source_admin_service.save_source(_source(login['id'], draft['id'], 'DUB'), actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'
@@ -178,7 +185,10 @@ def test_new_published_version_does_not_retire_bound_version(app):
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
first = _published_profile()
field_id = order_schema_service.get_state()['fields'][0]['id']
field_id = next(
item['field_id'] for item in order_schema_service.get_published_contract()['fields']
if item.get('field_code') == 'part_number' and item.get('scope') == 'line'
)
second_draft = onhand_parsing_profile.save_draft({
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx',
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
@@ -198,12 +208,12 @@ def test_referenced_published_profile_cannot_be_retired(app):
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
parsing = _published_profile()
login = shipping_onhand_admin_service.save_profile({
login = freight_rpa_source_admin_service.save_profile({
'profile_code': 'RETIRE_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs',
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
'username': 'u', 'password': 'p', 'enabled': True,
}, actor_id=None)
shipping_onhand_admin_service.save_source(_source(login['id'], parsing['id'], 'RETIRE'), actor_id=None)
freight_rpa_source_admin_service.save_source(_source(login['id'], parsing['id'], 'RETIRE'), actor_id=None)
with pytest.raises(Exception) as exc_info:
onhand_parsing_profile.retire(parsing['id'])
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED'
@@ -13,7 +13,8 @@ from io import BytesIO
from openpyxl import Workbook
from werkzeug.datastructures import FileStorage
from app.services.shipping_notice import onhand_parsing_profile, onhand_structure_analysis
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
from app.services.shipping_notice import onhand_structure_analysis
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.models import FreightRpaOnhandField
@@ -260,7 +260,7 @@ def test_profile_draft_requires_persisted_sample_evidence(app):
"""绕过样本分析直接保存草稿时必须被拒绝,避免来源表头脱离审计依据。"""
with app.app_context():
field_id = _published_part_number()
from app.services.shipping_notice import onhand_parsing_profile
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
with pytest.raises(ValidationError) as exc_info:
onhand_parsing_profile.save_draft({
@@ -303,7 +303,7 @@ def test_profile_draft_purpose_passthrough_creates_inbound_profile(app, tmp_path
def test_publish_inbound_profile_skips_order_match_key_contract(app, tmp_path):
"""发布 inbound 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。"""
from app.services.shipping_notice import onhand_parsing_profile
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
+39 -19
View File
@@ -1,9 +1,9 @@
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验 + 迁移往返)。
用途:验证 onhand_parsing_profile._validate_definition(purpose=...) 分支——
inbound 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
不查库存字段目录、无 match_keys);onhand/outbound 维持既有库存字段目录 + match_keys
校验(outbound 出站文件结构就位,暂无运行时消费方)。并用 app fixture 校验模型
inbound/outbound 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
不查库存字段目录、无 match_keys);onhand 维持库存字段目录 + match_keys 校验。
并用 app fixture 校验模型
purpose 列默认 'onhand'、CHECK 约束三元枚举,以及 tt15 迁移 SQLite 真实往返。
依赖:onhand_parsing_profile._validate_definition / save_draft(纯 + app SQLite)、
migrations/versions/tt15(batch_alter_table 改枚举)、app_ctx(根 conftest app
@@ -23,7 +23,7 @@ from alembic.migration import MigrationContext
from alembic.operations import Operations
from app.core.errors import ValidationError
from app.services.shipping_notice.onhand_parsing_profile import _validate_definition, save_draft
from app.services.freight_rpa.parsing_profile import _validate_definition, save_draft
pytestmark = pytest.mark.pure_unit
@@ -81,6 +81,36 @@ def test_inbound_definition_rejects_unknown_field():
_validate_definition(raw, purpose='inbound')
def test_outbound_definition_uses_movement_fields():
"""outbound 定义完整 → 走异动字段路径,match_keys 空。"""
definition = _validate_definition(_inbound_definition(), purpose='outbound')
assert definition['match_keys'] == []
assert definition['field_mapping']['doc_no'] == '单据编号'
def test_outbound_onhand_shaped_definition_rejected(app_ctx):
"""库存目录形态(含 match_keys)在 outbound 下应失败。"""
from app.models import FreightRpaOnhandField, ShippingOrderField
from app import db
rows = {item.field_code: item for item in FreightRpaOnhandField.query.filter_by(status='active').all()}
field_mapping = {
str(rows['part_number'].id): 'Supplier Sku',
str(rows['reservation_id'].id): 'Reservation ID',
str(rows['available_qty'].id): 'Qty Available',
}
order_field = ShippingOrderField(field_code='part_number', scope='line', value_type='string')
db.session.add(order_field)
db.session.flush()
raw = {
'header_row_index': 1,
'field_mapping': field_mapping,
'match_keys': [{'order_field_id': order_field.id, 'inventory_field_id': next(iter(field_mapping))}],
}
with pytest.raises(ValidationError):
_validate_definition(raw, purpose='outbound')
def test_purpose_enum_values():
"""模型 purpose 列:default/server_default 均为 'onhand',CHECK 名为批次 S 新约束,枚举恰为三元。"""
from app.models.freight_rpa_config import FreightRpaParsingProfile
@@ -128,25 +158,15 @@ def _catalog_mapping() -> dict[str, str]:
def test_draft_accepts_outbound_and_rejects_legacy(app_ctx):
"""save_draft purpose='outbound' 通过校验;purpose='movement' 报 SHIPPING.ONHAND_PARSING_PROFILE_INVALID。"""
from app import db
from app.models import ShippingOrderField
# 出站文件结构就位:outbound 走库存字段目录分支(与 onhand 同构),需行级订单匹配键。
order_field = ShippingOrderField(field_code='part_number', scope='line', value_type='string')
db.session.add(order_field)
db.session.flush()
headers = ['Supplier Sku', 'Reservation ID', 'Qty Available']
headers = [value for value in _inbound_definition()['field_mapping'].values()]
outbound = save_draft({
'profile_code': 'OUT_STD', 'display_name': '出站结构就位', 'purpose': 'outbound',
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers),
'definition': {
'header_row_index': 1,
'field_mapping': _catalog_mapping(),
'match_keys': [{'order_field_id': order_field.id, 'inventory_field_id': next(iter(_catalog_mapping()))}],
},
'profile_code': 'OUT_STD', 'display_name': '出站异动解析', 'purpose': 'outbound',
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers, sheet_name='Inbound'),
'definition': _inbound_definition(),
}, actor_id=None)
assert outbound['purpose'] == 'outbound'
assert outbound['definition']['match_keys'] == []
with pytest.raises(ValidationError) as exc_info:
save_draft({
+4 -4
View File
@@ -68,12 +68,12 @@ def test_title_row_must_not_count_as_detail(tmp_path: Path):
"""
标题含 receipt 时旧逻辑会把真表头当成明细 → 误 success。
[断言意图] 仅标题+表头必须判定为无明细(False),enforce 抛 no_receipt_data。
[断言意图] 仅标题+表头必须判定为无明细(False),enforce 抛 no_inbound_data。
"""
path = tmp_path / 'header_only.xlsx'
_write_dsv_title_header_only(path)
assert inbound_excel_has_detail_rows(path) is False
with pytest.raises(NoInboundDataError, match='no_receipt_data'):
with pytest.raises(NoInboundDataError, match='no_inbound_data'):
enforce_inbound_excel_not_empty(path)
@@ -97,10 +97,10 @@ def test_production_header_only_sample_is_empty(tmp_path: Path):
"""
生产样例 receipt_RUN202609290016193A2E_*_BYAWSPRD01_* 仅表头却曾 success。
[断言意图] 复制该文件后必须判 empty / no_receipt_data。
[断言意图] 复制该文件后必须判 empty / no_inbound_data。
"""
target = tmp_path / _DROP_SAMPLE.name
shutil.copy2(_DROP_SAMPLE, target)
assert inbound_excel_has_detail_rows(target) is False
with pytest.raises(NoInboundDataError, match='no_receipt_data'):
with pytest.raises(NoInboundDataError, match='no_inbound_data'):
enforce_inbound_excel_not_empty(target)
@@ -27,12 +27,12 @@ from app.models import (
User,
)
from app.services.schedule.freight_rpa_inbound_archive import (
get_receipt_archive_dir,
persist_receipt_rpa_raw_zip_archive,
receipt_raw_zip_available_from_summary,
receipt_raw_zip_download_name,
receipt_rpa_attachment_stem,
resolve_receipt_raw_zip_download,
get_inbound_archive_dir,
persist_inbound_rpa_raw_zip_archive,
inbound_raw_zip_available_from_summary,
inbound_raw_zip_download_name,
inbound_rpa_attachment_stem,
resolve_inbound_raw_zip_download,
_build_zip_entry_name,
)
from tests.conftest import parse_api_error
@@ -125,14 +125,14 @@ def _make_receipt_run_with_file(
return run, report_file
def test_receipt_raw_zip_available_from_summary_reads_persisted_flag():
"""列表可见性应只依赖 summary.raw_receipt_zip_available。"""
assert receipt_raw_zip_available_from_summary({'raw_receipt_zip_available': True}) is True
assert receipt_raw_zip_available_from_summary({'raw_receipt_zip_available': False}) is False
assert receipt_raw_zip_available_from_summary(None) is False
def test_inbound_raw_zip_available_from_summary_reads_persisted_flag():
"""列表可见性应只依赖 summary.raw_inbound_zip_available。"""
assert inbound_raw_zip_available_from_summary({'raw_inbound_zip_available': True}) is True
assert inbound_raw_zip_available_from_summary({'raw_inbound_zip_available': False}) is False
assert inbound_raw_zip_available_from_summary(None) is False
def test_get_receipt_archive_dir_falls_back_when_config_none(app, tmp_path, monkeypatch):
def test_get_inbound_archive_dir_falls_back_when_config_none(app, tmp_path, monkeypatch):
"""
Config 缺项时 Flask config 可能为 None;不得 Path(None) 导致 finalize ZIP 全空。
@@ -147,7 +147,7 @@ def test_get_receipt_archive_dir_falls_back_when_config_none(app, tmp_path, monk
)
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = None
archive_dir = Path(get_receipt_archive_dir())
archive_dir = Path(get_inbound_archive_dir())
assert archive_dir.is_dir()
assert archive_dir == (tmp_path / 'receipt_archives_fallback').resolve()
@@ -160,8 +160,8 @@ def test_config_exposes_freight_rpa_receipt_archive_dir(app):
assert str(value).strip() != ''
def test_serialize_run_reads_receipt_raw_zip_available_from_summary(app):
"""serialize_run 应暴露 receipt_raw_zip_available 供管理端深链/按钮。"""
def test_serialize_run_reads_inbound_raw_zip_available_from_summary(app):
"""serialize_run 应暴露 inbound_raw_zip_available 供管理端深链/按钮。"""
from app.services.schedule.query_service import serialize_run
with app.app_context():
@@ -182,12 +182,12 @@ def test_serialize_run_reads_receipt_raw_zip_available_from_summary(app):
run_no='RUN-RCP-SER',
schedule_task_id=task.id,
status='success',
response_summary_json={'raw_receipt_zip_available': True},
response_summary_json={'raw_inbound_zip_available': True},
)
db.session.add(run)
db.session.commit()
payload = serialize_run(run)
assert payload['receipt_raw_zip_available'] is True
assert payload['inbound_raw_zip_available'] is True
assert payload['inventory_raw_zip_available'] is False
@@ -201,7 +201,7 @@ def test_build_zip_entry_name_prefers_source_code():
) == '001_DSV360_AWSBI.xlsx'
def test_persist_receipt_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path, monkeypatch):
def test_persist_inbound_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path, monkeypatch):
"""finalize 预生成应落盘 ZIP(含 manifest)并返回 summary 字段。"""
archive_dir = tmp_path / 'receipt_archives'
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(archive_dir)
@@ -217,13 +217,13 @@ def test_persist_receipt_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_pat
callback_id='receipt-arch-1',
original_filename='receipt_RUN_DSV360_AWSDU_NA.xlsx',
)
summary = persist_receipt_rpa_raw_zip_archive(run)
summary = persist_inbound_rpa_raw_zip_archive(run)
# [断言意图] summary 标记可用且路径落在配置归档目录。
assert summary['raw_receipt_zip_available'] is True
assert summary['raw_receipt_file_count'] == 1
assert summary['raw_receipt_file_ids'] == [report_file.id]
zip_path = Path(summary['raw_receipt_zip_path'])
assert summary['raw_inbound_zip_available'] is True
assert summary['raw_inbound_file_count'] == 1
assert summary['raw_inbound_file_ids'] == [report_file.id]
zip_path = Path(summary['raw_inbound_zip_path'])
assert zip_path.is_file()
assert zip_path.parent.resolve() == archive_dir.resolve()
@@ -237,7 +237,7 @@ def test_persist_receipt_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_pat
assert manifest['files'][0]['file_id'] == report_file.id
def test_resolve_receipt_raw_zip_download_rejects_missing_summary(app, tmp_path):
def test_resolve_inbound_raw_zip_download_rejects_missing_summary(app, tmp_path):
"""summary 未标记可用时应 404。"""
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt_archives')
with app.app_context():
@@ -246,27 +246,27 @@ def test_resolve_receipt_raw_zip_download_rejects_missing_summary(app, tmp_path)
run_no='RUNRCPARCHMISS',
callback_id='receipt-arch-miss',
)
run.response_summary_json = {'raw_receipt_zip_available': False}
run.response_summary_json = {'raw_inbound_zip_available': False}
db.session.commit()
with pytest.raises(NotFoundError):
resolve_receipt_raw_zip_download(run)
resolve_inbound_raw_zip_download(run)
def test_receipt_attachment_stem_uses_local_timezone(app):
"""展示名前缀为收料RPA-日期-时刻(业务时区)。"""
"""展示名前缀为入站RPA-日期-时刻(业务时区)。"""
with app.app_context():
run, _ = _make_receipt_run_with_file(
schedule_no='SCH-RCP-STEM',
run_no='RUN202609281530001234',
callback_id='receipt-stem',
)
stem = receipt_rpa_attachment_stem(run)
assert stem.startswith('收料RPA-')
assert receipt_raw_zip_download_name(run) == f'{stem}-收料.zip'
stem = inbound_rpa_attachment_stem(run)
assert stem.startswith('入站RPA-')
assert inbound_raw_zip_download_name(run) == f'{stem}-入站.zip'
def test_admin_can_download_receipt_raw_zip(app, client, admin_jwt_headers, tmp_path, monkeypatch):
"""管理端 receipt-raw-zip 应返回 ZIP 与展示名。"""
def test_admin_can_download_inbound_raw_zip(app, client, admin_jwt_headers, tmp_path, monkeypatch):
"""管理端 inbound-raw-zip 应返回 ZIP 与展示名。"""
archive_dir = tmp_path / 'receipt_archives'
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(archive_dir)
monkeypatch.setattr(
@@ -280,14 +280,14 @@ def test_admin_can_download_receipt_raw_zip(app, client, admin_jwt_headers, tmp_
run_no='RUNRCPDL1',
callback_id='receipt-dl-1',
)
summary = persist_receipt_rpa_raw_zip_archive(run)
summary = persist_inbound_rpa_raw_zip_archive(run)
run.response_summary_json = summary
db.session.commit()
run_id = run.id
expected_name = receipt_raw_zip_download_name(run)
expected_name = inbound_raw_zip_download_name(run)
response = client.get(
f'/api/admin/schedule-runs/{run_id}/receipt-raw-zip',
f'/api/admin/schedule-runs/{run_id}/inbound-raw-zip',
headers=admin_jwt_headers,
)
assert response.status_code == 200