feat(freight-rpa): 系统连接只保留上传开关并增加 Crane 一次回查

上传页、按钮和成功判断改由连接器固定。Crane 分配中只排一次 10 分钟状态回查,手动刷新不改到期时间。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-23 12:20:29 +08:00
1 parent 95e7db0831
commit 3bb9938c05
33 files changed
+878 -374

No files matched your search

@@ -3,7 +3,7 @@ tests/services/admin/test_shipping_inventory_service.py
用途:验证库存主数据管理服务的安全性和关键业务约束。
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
逻辑:管理后台写配置前锁定用户名可回显、密码与密文不回传、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
"""
from __future__ import annotations
@@ -22,6 +22,7 @@ from app.models import (
FreightRpaSource,
FreightRpaSourceParsingBindingAudit,
FreightRpaOnhandStructureAnalysis,
FreightRpaProfile,
)
@@ -160,15 +161,50 @@ def _published_route_field_id() -> str:
)
def test_profile_credentials_are_not_returned(app):
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
def test_profile_returns_username_and_keeps_password_secret(app):
"""Profile 回执返回用户名明文,密码与密文不得出现。相同用户名再次保存不轮换密文。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
# 用户名是账号标识,管理端需要明文辨认;密码只报告已配置。
assert payload['username'] == 'test-user'
assert payload['password_configured'] is True
assert payload['username_masked'] == 'configured'
assert 'password' not in payload
assert 'ciphertext' not in payload
stored = db.session.get(FreightRpaProfile, payload['id'])
original_username = stored.username_ciphertext
original_password = stored.password_ciphertext
original_updated_at = stored.credential_updated_at
unchanged = _profile_data()
unchanged.pop('password')
unchanged['display_name'] = 'DBS EU renamed'
again = freight_rpa_source_admin_service.save_profile(unchanged, actor_id=None, profile_id=payload['id'])
# 回显后的原用户名随表单提交时,不得重加密或刷新凭据时间。
assert again['username'] == 'test-user'
db.session.refresh(stored)
assert stored.username_ciphertext == original_username
assert stored.password_ciphertext == original_password
assert stored.credential_updated_at == original_updated_at
assert stored.display_name == 'DBS EU renamed'
def test_profile_username_change_reencrypts_without_touching_password(app):
"""只改用户名时重写用户名密文,密码密文保持不变。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
stored = db.session.get(FreightRpaProfile, payload['id'])
original_username = stored.username_ciphertext
original_password = stored.password_ciphertext
changed = _profile_data()
changed.pop('password')
changed['username'] = 'other-user'
updated = freight_rpa_source_admin_service.save_profile(changed, actor_id=None, profile_id=payload['id'])
assert updated['username'] == 'other-user'
db.session.refresh(stored)
assert stored.username_ciphertext != original_username
assert stored.password_ciphertext == original_password
def test_profile_rejects_page_operation_configuration(app):
@@ -620,29 +656,23 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
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,
'enabled': True, 'entry_url': 'https://evil.example/steal',
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file',
}
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
assert updated['upload_config_json'] == {'enabled': True}
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
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):
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):
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}},
{**_profile_data(), 'upload_config_json': 'not-an-object'},
actor_id=None, profile_id=profile['id'],
)
@@ -0,0 +1,100 @@
"""
backend/tests/services/freight_rpa/test_crane_upload_recheck.py
用途:验证上传配置只保留开关,以及 Crane 分配中只排一次定时回查。
依赖:page_contract、upload_attempt_service、crane_recheck、Flask 测试库。
逻辑:先断言入口 URL 和行分类,再走 complete_attempt、定时回查和手动刷新。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app import db
from app.core.errors import ConflictError
from app.services.freight_rpa.upload.crane_recheck import (
fire_scheduled_crane_recheck,
request_manual_crane_refresh,
)
from app.services.freight_rpa.upload.page_contract import (
build_upload_entry_url,
classify_crane_order_row,
)
from app.services.shipping_notice.upload_attempt_service import (
complete_attempt,
project_notice_upload_status,
start_rpa_attempt,
)
from tests.test_shipping_upload_attempt import _ready_artifact
def test_upload_entry_url_comes_from_login_host_and_crane_row_is_classified():
"""DBS/Crane 上传页由登录主机拼接;只有两句固定文案分别表示已分配和分配中。"""
assert build_upload_entry_url('dbs', 'https://s360.dbschenker.com/login') == (
'https://s360.dbschenker.com/main/portal/frame/WMSUpload2'
)
assert build_upload_entry_url('crane', 'https://wms-portal.craneww.com/') == (
'https://wms-portal.craneww.com/#/shipping-order-upload'
)
assert classify_crane_order_row('Processing', 'Shipping Order Allocated') == 'allocated'
assert classify_crane_order_row('Processing', 'Allocating the Shipping Order') == 'allocating'
assert classify_crane_order_row('Completed', 'Shipping Order Allocated') == 'other'
def test_allocating_schedules_one_recheck_and_blocks_another_upload(app):
"""首次分配中写下 10 分钟回查;第二次回调不改到期时间,也不能重新上传。"""
with app.app_context():
notice, artifact, _reservation = _ready_artifact()
artifact.file_name = 'MXI26082801.xlsx'
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key')
started = datetime(2026, 10, 23, 3, 0, 0)
complete_attempt(attempt, success=False, callback_id='upload-1', result='allocating')
# remember 使用 utcnow;这里只断言间隔为 10 分钟,不绑定测试开始时刻。
due_at = datetime.fromisoformat(attempt.success_evidence_json['crane_recheck']['due_at'])
assert timedelta(minutes=9) < due_at - datetime.utcnow() <= timedelta(minutes=10)
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
assert project_notice_upload_status(notice) == 'allocating'
complete_attempt(attempt, success=False, callback_id='recheck-1', result='allocating')
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at.isoformat(timespec='seconds')
with pytest.raises(ConflictError) as blocked:
start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key-2')
assert blocked.value.code == 'SHIPPING.UPLOAD_CRANE_ALLOCATING'
assert started < due_at
def test_manual_refresh_does_not_move_the_one_scheduled_recheck(app):
"""手动刷新另写一条状态回查,不改定时到期时间,也不把定时标记成已触发。"""
with app.app_context():
notice, artifact, _reservation = _ready_artifact()
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-manual')
complete_attempt(attempt, success=False, callback_id='upload-manual', result='allocating')
due_at = attempt.success_evidence_json['crane_recheck']['due_at']
source = {'login_url': 'https://wms-portal.craneww.com/', 'connector_type': 'crane'}
first = request_manual_crane_refresh(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
)
assert first.endswith(f'upload_recheck_{notice.task_no}_manual.json')
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
with pytest.raises(ConflictError) as inflight:
request_manual_crane_refresh(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
)
assert inflight.value.code == 'SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT'
future = datetime.fromisoformat(due_at) + timedelta(seconds=1)
assert fire_scheduled_crane_recheck(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
) is True
assert fire_scheduled_crane_recheck(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
) is False
db.session.refresh(attempt)
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
assert attempt.success_evidence_json['crane_recheck']['fired'] is True