Files
syops/backend/tests/test_freight_receipt_rpa_notifications.py
T
hugo 911afa0f73 feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
2026-10-19 18:45:16 +08:00

174 lines
11 KiB
Python

"""
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 _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *, awaiting: bool = True):
"""构造一个收料排程任务+run+成功单元+归档文件的最小通知夹具。"""
from app.models import (
ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
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_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()
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'{callback_id}.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='c' * 64)
db.session.add(report_file)
db.session.commit()
return task, run, report_file
def _patch_unified_wecom(monkeypatch, *, enabled_events: bool):
"""拦截通用排程出口的企微调用,返回可断言的捕获列表。"""
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)
if enabled_events:
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},
)
monkeypatch.setattr('app.services.file_assets.storage.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
return textcards, media_uploads, file_sends
def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_path):
"""收料 run 终态后经通用排程出口一次性发 textcard+收料 ZIP;重复归集不重发。"""
from app import db
from app.models import User
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')
recipient = User(username='receipt-one-shot', email='one-shot@example.com', role='user', status='active', wecom_userid='one-shot-user')
db.session.add(recipient); db.session.flush()
task, run, _report_file = _make_receipt_run_fixture(db, 'SCH-RECEIPT-ONESHOT', 'RUN-RECEIPT-ONESHOT', 'receipt-oneshot-callback')
task.notify_enabled = True
task.notify_user_ids_json = [recipient.id]
db.session.commit()
app.config['WECOM_NOTIFY_ENABLED'] = True
app.config['WECOM_PUBLIC_BASE_URL'] = 'https://hxops.example.com'
textcards, media_uploads, file_sends = _patch_unified_wecom(monkeypatch, enabled_events=True)
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 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 file_sends == ['media-1', 'media-2']
assert run.wecom_notified is True
assert run.response_summary_json.get('raw_inbound_zip_available') is True
# [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。
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。"""
from io import BytesIO
from openpyxl import load_workbook
from app import db
from app.models import (
ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
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_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.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_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.response_summary_json['excel_export_status'] == 'ok'
assert run.response_summary_json['excel_failed'] is False
# [断言意图] 行结构对齐库存:中文表头 + empty→skipped / failed 保持 failed,与卡片计数口径一致。
workbook = load_workbook(BytesIO(run.excel_file_data))
sheet = workbook.active
header = [cell.value for cell in sheet[1]]
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'
assert rows['CRANE_WH1'][4] == 'failed' and rows['CRANE_WH1'][6] == 'download timeout'
def test_receipt_run_notification_follows_inventory_gates(app, monkeypatch):
"""收料通知与库存共用门禁:事件未启用或接收人未绑定企微时不发送并记录原因。"""
from app import db
from app.models import User
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
with app.app_context():
app.config['WECOM_NOTIFY_ENABLED'] = True
textcards, _media_uploads, file_sends = _patch_unified_wecom(monkeypatch, enabled_events=False)
bound_user = User(username='receipt-gate-bound', email='gate-bound@example.com', role='user', status='active', wecom_userid='gate-bound-user')
unbound_user = User(username='receipt-gate-unbound', email='gate-unbound@example.com', role='user', status='active')
db.session.add_all([bound_user, unbound_user]); db.session.flush()
task_a, run_a, _f = _make_receipt_run_fixture(db, 'SCH-RECEIPT-GATE-A', 'RUN-RECEIPT-GATE-A', 'receipt-gate-a')
task_a.notify_user_ids_json = [bound_user.id]
task_b, run_b, _g = _make_receipt_run_fixture(db, 'SCH-RECEIPT-GATE-B', 'RUN-RECEIPT-GATE-B', 'receipt-gate-b')
task_b.notify_user_ids_json = [unbound_user.id]
db.session.commit()
# [断言意图] ①schedule_completed 不在 WECOM_NOTIFY_EVENTS 内 → 整体拦截并留因。
app.config['WECOM_NOTIFY_EVENTS'] = ''
_notify_schedule_run_wecom(task_a, run_a)
assert textcards == [] and file_sends == []
assert run_a.wecom_notify_error == 'event schedule_completed disabled'
# [断言意图] ②事件放行但接收人无 wecom_userid → 不发送并留因,与库存口径一致。
app.config['WECOM_NOTIFY_EVENTS'] = 'schedule_completed'
_notify_schedule_run_wecom(task_b, run_b)
assert textcards == [] and file_sends == []
assert run_b.wecom_notify_error == 'no wecom_userid bound users in notify list'