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

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