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

+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'