Files
syops/backend/tests/test_freight_receipt_rpa_access.py
T
hugoandCursor 39fe3c05f2 feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 10:46:06 +08:00

188 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""收料文件下载和人工补偿的权限/审计契约测试。"""
from __future__ import annotations
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
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, User
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
admin = User(username='receipt-retry-admin', email='receipt-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-RECEIPT-RETRY', name='Receipt retry', 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-RECEIPT-RETRY', schedule_task_id=task.id, status='failed')
db.session.add(run); db.session.flush()
failed = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-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_inbound_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json')
response = client.post(f'/api/admin/inbound-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin'))
assert response.status_code == 200
with app.app_context():
retry = FreightRpaInboundUnitRun.query.filter_by(retry_of_id=failed_id).one()
assert retry.status == 'awaiting_rpa'
assert retry.callback_id != 'receipt-failed'
assert captured and captured[0][1][0]['callback_id'] == retry.callback_id
def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client):
"""管理员可见失败单元用于人工补偿;该接口会记录管理员查看审计。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun, User
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
admin = User(username='receipt-units-admin', email='receipt-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-RECEIPT-UNITS', name='Receipt units', 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-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={})
db.session.add(unit); db.session.commit()
unit_id = unit.id
response = client.get('/api/admin/inbound-rpa-units?status=failed', headers=_headers('receipt-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_inbound_rpa_units_listed').count() == 1