Files
syops/backend/tests/test_freight_receipt_rpa_notifications.py
T
hugo a8d721e793 feat(in-transit-transfer): 自动调拨支持收料日期范围并收归排程通用通知
- 自动调拨任务新增收料日期范围动态参数(receipt_date_from/to):缩小匹配面便于测试与排障,非法范围由匹配层校验拒绝
- 排程动态参数表单支持占位文案 key 与空值归 null,日期筛选直达任务配置
- 执行结果通知统一走排程「启用通知」通用企微通知,任务不再自建领域通知
- 门禁契约澄清 retry_inventory_matching 语义:复用已抓库存重匹配不重抓;STP 多候选无匹配时阶段能力禁用、不隐式触发 RPA
- 同步匹配/自动调拨/排程测试、四语言文案与文档
2026-10-12 21:25:35 +08:00

230 lines
15 KiB
Python

"""收料文件企微投递和授权下载契约测试。"""
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, ShippingInventorySource, ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun, User,
)
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_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 = ShippingInventorySource.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-receipt-rpa', 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 = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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 = ShippingReceiptReportFile(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.shipping_notice.receipt_report_notification.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.upload_wecom_temp_media', lambda *_args: 'media-1')
calls: list[tuple] = []
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0})
assert deliver_receipt_file(report_file.id)['success_count'] == 1
assert deliver_receipt_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, ShippingInventorySource, ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun, User,
)
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_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 = ShippingInventorySource.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-receipt-rpa', 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 = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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 = ShippingReceiptReportFile(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_receipt_file(report_file.id)
assert outcome['failed_count'] == 1
audit = ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_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 (
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
)
source = ShippingInventorySource.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-receipt-rpa', 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)
db.session.add(run); db.session.flush()
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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 = ShippingReceiptReportFile(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_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
with app.app_context():
app.config['FREIGHT_RPA_RECEIPT_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_receipt_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_receipt_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'}
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, ShippingInventorySource, ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
)
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
with app.app_context():
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
source = ShippingInventorySource.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-receipt-rpa', 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})
db.session.add(run); db.session.flush()
unit_ok = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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 = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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 = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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={})
db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush()
db.session.add(ShippingReceiptReportFile(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)
# [断言意图] 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'