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

@@ -180,7 +180,7 @@ def test_no_waiting_job_is_success(app, db_session):
def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaiting: bool = True):
"""构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_receipt_rpa 等待态。"""
"""构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_inbound_rpa 等待态。"""
from app.models import ScheduleRun, ScheduleTask
task = ScheduleTask(
@@ -192,7 +192,7 @@ def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaitin
run = ScheduleRun(
run_no=run_no, schedule_task_id=task.id, status='running', total_count=1,
success_count=0, failed_count=0, skipped_count=0,
response_summary_json={'awaiting_receipt_rpa': awaiting},
response_summary_json={'awaiting_inbound_rpa': awaiting},
)
db_session.add(run)
db_session.commit()
@@ -218,7 +218,7 @@ def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session,
"""同来源两个单元分属两个排程 run:本回调收尾的单元(按文件反查)只收口它自己的 run。
[断言意图] 修复「按来源取最新单元」的错位:旧逻辑会把收口打到更新单元的 run,
本回调刚完成的 run 永久滞留 awaiting_receipt_rpa。
本回调刚完成的 run 永久滞留 awaiting_inbound_rpa。
"""
from app.models import ScheduleRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
@@ -254,18 +254,18 @@ def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session,
# [断言意图] 本回调收尾的是旧单元:只有旧 run 被收口(全终态 → success)。
refreshed_old = db_session.get(ScheduleRun, run_old.id)
assert refreshed_old.status == "success"
assert not (refreshed_old.response_summary_json or {}).get("awaiting_receipt_rpa")
assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_rpa")
# 新单元的 run 原样保持等待态——未被本次回调误收口。
refreshed_new = db_session.get(ScheduleRun, run_new.id)
assert refreshed_new.status == "running"
assert (refreshed_new.response_summary_json or {}).get("awaiting_receipt_rpa") is True
assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_rpa") is True
def test_finalize_targets_failed_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch):
"""同来源两单元、同失败错误文本、分属两 run:失败回调只收口本单元(unit_run_id)的 run。
[断言意图] 修复「按来源+终态+错误文本取最新单元」的错位:错误文本碰撞时旧回调
会收口新单元的 run,本回调刚失败的 run 永久滞留 awaiting_receipt_rpa。
会收口新单元的 run,本回调刚失败的 run 永久滞留 awaiting_inbound_rpa。
"""
from datetime import datetime
@@ -310,11 +310,11 @@ def test_finalize_targets_failed_unit_of_this_callback_not_newest_unit(app, db_s
# [断言意图] 只有旧单元的 run 被收口(唯一单元终态失败 → failed、awaiting 清除)。
refreshed_old = db_session.get(ScheduleRun, run_old.id)
assert refreshed_old.status == "failed"
assert not (refreshed_old.response_summary_json or {}).get("awaiting_receipt_rpa")
assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_rpa")
refreshed_saved_old = db_session.get(FreightRpaInboundUnitRun, unit_old.id)
assert refreshed_saved_old.status == "failed"
assert refreshed_saved_old.error_code == "RPA_TEST_FAIL"
# 新单元的 run 原样保持等待态——未被本次回调误收口(新单元自身终态由其回调收口)。
refreshed_new = db_session.get(ScheduleRun, run_new.id)
assert refreshed_new.status == "running"
assert (refreshed_new.response_summary_json or {}).get("awaiting_receipt_rpa") is True
assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_rpa") is True
@@ -0,0 +1,316 @@
"""出站 RPA 触发服务与报表处理函数测试。
用途:验证 trigger_outbound_rpa / trigger_outbound_rpa_batch 按来源装配出站
trigger unit 并调用写者;站点停用 / 出站配置缺失 / 登录连接缺失 fail-closed;
handle_outbound_report 把等待中的 TransferSourceJob 从 waiting_rpa_callback
推进到 file_ready(无等待任务 no-op,可重入)。
依赖:app(SQLite)fixture、outbound_trigger_service、outbound_report_handler、
既有测试种子(FreightRpaProfile/FreightRpaSource)。
逻辑:对照 test_inbound_trigger_service;出站配置行挂 FreightRpaOutboundReportConfig;
写者协议与入站一致(payload= 附加字段);handler 只改调拨等待行,不写新状态。
"""
from __future__ import annotations
import pytest
from app.models import FreightRpaSource, FreightRpaOutboundReportConfig
from app.services.in_transit_transfer.outbound_trigger_service import (
trigger_outbound_rpa,
trigger_outbound_rpa_batch,
)
@pytest.fixture
def outbound_source():
"""复用种子来源并为其创建出站配置。"""
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
assert source is not None
config = FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'},
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
)
from app import db
db.session.add(config)
db.session.commit()
return source
def test_trigger_outbound_rpa_disabled_source_fails_closed(app):
"""来源停用 → ok=False,不写 trigger。"""
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
source.enabled = False
from app import db
db.session.commit()
result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_missing_config_fails_closed(app):
"""来源启用但无出站配置 → ok=False。"""
result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_missing_login_fails_closed(app, outbound_source):
"""出站配置存在但登录连接停用 → ok=False,不写 trigger。"""
from app import db
outbound_source.rpa_profile.enabled = False
db.session.commit()
result = trigger_outbound_rpa(
source_code='DSV360_AWSDU', business_date='2026-08-06',
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
)
assert result['ok'] is False
assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_writes_batch_trigger(app, outbound_source):
"""来源有效 → 写入 trigger 并返回 callback_id / trigger_path。"""
calls = {}
def fake_writer(run_no, units, payload=None):
calls['run_no'] = run_no
calls['units'] = units
calls['payload'] = payload or {}
return f'/tmp/trigger/{run_no}.json'
result = trigger_outbound_rpa(
source_code='DSV360_AWSDU', business_date='2026-08-06',
reason='transfer_retry_outbound', writer=fake_writer,
)
assert result['ok'] is True
assert result['callback_id']
assert result['trigger_path'].endswith('.json')
assert calls['units'][0]['source_code'] == 'DSV360_AWSDU'
assert calls['units'][0]['warehouse_id'] is None
assert calls['units'][0]['query_parameters_json'] == [
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
]
assert calls['units'][0]['credential_envelope']
assert calls['payload']['schema_version'] == 'freight_rpa.outbound.v1'
def test_trigger_outbound_rpa_creates_unit_run_before_writing_trigger(app, outbound_source):
"""触发必须先落 FreightRpaOutboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
from app.models import FreightRpaOutboundUnitRun
captured: dict = {}
def fake_writer(run_no, units, payload=None):
captured['units'] = units
return 'trigger.json'
outcome = trigger_outbound_rpa(
source_code=outbound_source.source_code, business_date='2026-10-19',
reason='transfer_retry_outbound', writer=fake_writer,
)
assert outcome['ok'] is True
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=outcome['callback_id']).one()
assert unit.status == 'awaiting_rpa'
assert unit.schedule_run_id is None
assert FreightRpaOutboundUnitRun.__table__.columns['schedule_run_id'].nullable is True
assert captured['units'][0]['unit_run_id'] == unit.id
assert unit.trigger_snapshot_json['callback_id'] == unit.callback_id
def test_trigger_outbound_rpa_marks_unit_failed_when_trigger_unavailable(app, outbound_source):
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
from app.models import FreightRpaOutboundUnitRun
outcome = trigger_outbound_rpa(
source_code=outbound_source.source_code, business_date='2026-10-19',
reason='transfer_retry_outbound', writer=lambda *a, **k: None,
)
assert outcome['ok'] is False
unit = FreightRpaOutboundUnitRun.query.filter_by(source_code=outbound_source.source_code).order_by(
FreightRpaOutboundUnitRun.id.desc()).first()
assert unit.status == 'failed'
assert unit.error_code == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
@pytest.fixture
def second_outbound_source(app):
"""再造一个启用来源 + 出站配置(批量用例需要多来源)。"""
from app import db
from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaOutboundReportConfig
seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
profile = FreightRpaProfile(
profile_code='DBS_SG_OUT_TEST', display_name='DBS SG Out', connector_type='dbs',
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
)
source = FreightRpaSource(
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
rpa_profile=profile,
excel_template=seed.excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
enabled=True,
)
seed_config = seed.onhand_report_config
FreightRpaOnhandReportConfig(
source=source,
parsing_profile=seed_config.parsing_profile if seed_config is not None else None,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[],
)
db.session.add_all([profile, source])
db.session.flush()
config = FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'},
query_parameters_json=[],
)
db.session.add(config)
db.session.commit()
return source
def test_trigger_outbound_rpa_batch_writes_one_trigger_for_all_units(app, outbound_source, second_outbound_source):
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
from app.models import FreightRpaOutboundUnitRun
calls: list = []
def fake_writer(run_no, units, payload=None):
calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}})
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19',
reason='transfer_retry_outbound', writer=fake_writer,
)
assert len(calls) == 1
assert outcome['ok'] is True and outcome['triggered'] is True
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
assert calls[0]['payload']['schema_version'] == 'freight_rpa.outbound.v1'
callback_ids = {u['callback_id'] for u in calls[0]['units']}
assert len(callback_ids) == 2
rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.source_code.in_(
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
assert {row.status for row in rows} == {'awaiting_rpa'}
assert all(row.schedule_run_id is None for row in rows)
assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']}
def test_trigger_outbound_rpa_batch_skips_invalid_source(app, outbound_source):
"""单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。"""
captured: dict = {}
def fake_writer(run_no, units, payload=None):
captured['units'] = units
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-19',
writer=fake_writer,
)
assert outcome['ok'] is True and outcome['triggered'] is True
assert [u['source_code'] for u in captured['units']] == ['DSV360_AWSDU']
by_code = {item['source_code']: item for item in outcome['results']}
assert by_code['DSV360_AWSDU']['ok'] is True
assert by_code['DSV360_NOPE']['ok'] is False
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_batch_all_invalid_no_trigger(app):
"""全部来源无效 → 不写 trigger,ok=False + RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE。"""
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_NOPE'], business_date='2026-10-19',
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE'
def test_trigger_outbound_rpa_batch_writer_unavailable_marks_all_failed(app, outbound_source, second_outbound_source):
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
from app.models import FreightRpaOutboundUnitRun
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19',
writer=lambda *a, **k: None,
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.source_code.in_(
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
assert {row.status for row in rows} == {'failed'}
assert {row.error_code for row in rows} == {'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'}
def _waiting_job(source_code: str):
"""构造一个未落库的 waiting_rpa_callback 来源任务。"""
from app import db
from app.models import TransferRun, TransferSourceJob
run = TransferRun(
run_no=f'RUN-OUT-{source_code}',
business_date='2026-10-19',
status='preparing_files',
trigger_type='manual',
)
db.session.add(run)
db.session.flush()
return TransferSourceJob(run_id=run.id, source_code=source_code, status='waiting_rpa_callback')
def test_handle_outbound_report_advances_waiting_job_to_file_ready(app):
"""ok 事实把等待中的 SourceJob 从 waiting_rpa_callback 推进到 file_ready。"""
from app import db
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
job = _waiting_job('DSV')
db.session.add(job)
db.session.commit()
handle_outbound_report(ReportFact(
report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True,
))
db.session.refresh(job)
assert job.status == 'file_ready'
assert job.file_no == '42'
assert job.file_sha256 == 'abc'
def test_handle_outbound_report_noop_without_waiting_job(app):
"""无等待中的调拨任务:处理函数 no-op,不产生任何调拨来源任务行。"""
from app.models import TransferSourceJob
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
handle_outbound_report(ReportFact(
report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True,
))
assert TransferSourceJob.query.filter_by(source_code='DSV').count() == 0
def test_handle_outbound_report_is_reentrant(app):
"""第二次投递时该行已离开等待态,不再改(可重入)。"""
from app import db
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
job = _waiting_job('DSV')
db.session.add(job)
db.session.commit()
fact = ReportFact(report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True)
handle_outbound_report(fact)
db.session.refresh(job)
first_finished = job.finished_at
handle_outbound_report(ReportFact(
report_kind='outbound', source_code='DSV', file_id=99, sha256='zzz', ok=True,
))
db.session.refresh(job)
assert job.status == 'file_ready'
assert job.file_no == '42'
assert job.file_sha256 == 'abc'
assert job.finished_at == first_finished
@@ -0,0 +1,51 @@
"""
tests/services/in_transit_transfer/test_rpa_sinks_ownership.py
用途:锁定入站/出站 sink 组合根归属——住在 in_transit_transfer,不在 shipping_notice;
inbound-batch-ready 直挂 freight_rpa 归档入口(无 shipping_notice Middle Man)。
"""
from __future__ import annotations
import importlib
import pytest
def test_shipping_notice_rpa_sinks_only_exposes_onhand_registration():
"""发货包只保留 onhand 注册入口,不再导出 inbound/outbound 注册。"""
sinks = importlib.import_module('app.services.shipping_notice.rpa_sinks')
assert hasattr(sinks, 'register_onhand_sinks')
assert not hasattr(sinks, 'register_inbound_sinks')
assert not hasattr(sinks, 'register_outbound_sinks')
def test_shipping_notice_inbound_report_storage_module_removed():
"""入站 Middle Man 模块已删除,生产与测试均直连 freight_rpa / 调拨处理函数。"""
with pytest.raises(ModuleNotFoundError):
importlib.import_module('app.services.shipping_notice.inbound_report_storage')
def test_register_inbound_sinks_binds_archive_and_transfer_handler(app):
"""register_inbound_sinks 把归档入口与调拨 handler 接到 inbound kinds。"""
from app.services.freight_rpa.common import callback_sinks
from app.services.freight_rpa.reports import dispatch as dispatch_module
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
from app.services.in_transit_transfer.rpa_sinks import register_inbound_sinks
dispatch_module._REPORT_HANDLERS.pop('inbound', None)
callback_sinks._SINKS.pop('inbound-batch-ready', None)
register_inbound_sinks()
assert dispatch_module._REPORT_HANDLERS.get('inbound') is handle_inbound_report
assert 'inbound-batch-ready' in callback_sinks._SINKS
def test_register_outbound_sinks_binds_outbound_handler(app):
"""register_outbound_sinks 把 handle_outbound_report 接到 outbound kind。"""
from app.services.freight_rpa.reports import dispatch as dispatch_module
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
from app.services.in_transit_transfer.rpa_sinks import register_outbound_sinks
dispatch_module._REPORT_HANDLERS.pop('outbound', None)
register_outbound_sinks()
assert dispatch_module._REPORT_HANDLERS.get('outbound') is handle_outbound_report
@@ -229,7 +229,7 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
"""
from app import db
from app.models import FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_inbound_units
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
@@ -244,6 +244,6 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'fetching'
# [断言意图] 回收扫描后投影必须翻转为 failed:这是前端重试门禁
# (file_status !== 'fetching')解锁的依据,也是本测试与事故的直接回归点。
assert recover_all_stale_orphan_receipt_units() == 1
assert recover_all_stale_orphan_inbound_units() == 1
db.session.expire_all()
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'failed'