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>
This commit is contained in:
hugoandCursor committed 2026-10-19 10:46:06 +08:00
1 parent ffc0d4a430
commit 39fe3c05f2
453 files changed
+17945 -8646

No files matched your search

@@ -129,8 +129,9 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
"""建「启用来源 + 已发布 inbound 解析规则 + 收料配置绑定」全套种子(幂等)。
用途:清空并重新解析(spec §6)服务/端点用例的来源侧种子;来源自身
parsing_profile(在手口径)按约束置最小占位行,真实重建规则挂
ShippingReceiptReportConfig.parsing_profile_id(与运行期口径一致)。
在手解析绑定(在手口径)按约束置最小占位配置行(s18 起归
FreightRpaOnhandReportConfig),真实重建规则挂
FreightRpaInboundReportConfig.parsing_profile_id(与运行期口径一致)。
Args:
source_code: 来源实例编码。
@@ -140,29 +141,30 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
sheet_name / header_row_index: definition_json 结构参数。
status: 入站规则状态(缺省 published;用例可注入 draft 验证 abort)。
Returns:
(ShippingInventorySource, ShippingInventoryParsingProfile) 元组。
(FreightRpaSource, FreightRpaParsingProfile) 元组。
"""
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingRpaProfile,
ShippingReceiptReportConfig,
FreightRpaOnhandReportConfig,
FreightRpaParsingProfile,
FreightRpaSource,
FreightRpaProfile,
FreightRpaInboundReportConfig,
)
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
source = FreightRpaSource.query.filter_by(source_code=source_code).first()
if source is not None:
config = source.receipt_report_config
config = source.inbound_report_config
return source, (config.parsing_profile if config else None)
resolved_code = profile_code or f"MV_{source_code}"
onhand = ShippingInventoryParsingProfile(
onhand = FreightRpaParsingProfile(
purpose="onhand", profile_code=f"ONHAND_{source_code}", display_name=source_code,
version=1, status="published", file_format="xlsx",
definition_json={}, structure_definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile = FreightRpaParsingProfile(
purpose="inbound", profile_code=resolved_code, display_name=resolved_code,
version=version, status=status, file_format="xlsx",
definition_json={
@@ -172,7 +174,7 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
},
structure_definition_json={},
)
rpa = ShippingRpaProfile(
rpa = FreightRpaProfile(
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="dbs",
login_url="https://test.invalid/dbs", login_config_json={"auth_mode": "password"},
)
@@ -182,15 +184,20 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
storage_key=f"test/{source_code}/template.xlsx", original_filename="template.xlsx",
file_checksum="0" * 64, definition_json={}, definition_checksum="0" * 64,
)
source = ShippingInventorySource(
source = FreightRpaSource(
source_code=source_code, display_name=source_code, connector_type="dbs",
rpa_profile=rpa, parsing_profile=onhand, excel_template=template,
rpa_profile=rpa, excel_template=template,
warehouse_resolution_mode="fixed", fixed_warehouse_id="AWSDU", enabled=True,
)
db.session.add_all([onhand, profile, rpa, template, source])
db.session.flush()
db.session.add(ShippingReceiptReportConfig(
inventory_source_id=source.id, parsing_profile_id=profile.id))
# s18 起在手解析方案绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载。
db.session.add(FreightRpaOnhandReportConfig(
source_id=source.id, parsing_profile_id=onhand.id,
report_path_json={}, query_parameters_json=[],
))
db.session.add(FreightRpaInboundReportConfig(
source_id=source.id, parsing_profile_id=profile.id))
db.session.commit()
return source, profile
@@ -213,20 +220,20 @@ def seed_reparse_archive_file(source, *, sha: str, storage_key: str, created_at:
archive_deleted_at: 清理时间;None=未清理。
callback_id: 收料执行单元回调键(缺省按 sha 派生保证唯一)。
Returns:
已入库的 ShippingReceiptReportFile。
已入库的 FreightRpaInboundReportFile。
"""
from app import db
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code,
unit = FreightRpaInboundUnitRun(
source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type,
callback_id=callback_id or f"cb-{sha[:12]}",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = ShippingReceiptReportFile(
report = FreightRpaInboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=storage_key, original_filename=f"{callback_id or 'cb'}.xlsx",
file_size=16, sha256=sha, created_at=created_at,
@@ -57,24 +57,24 @@ def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str):
sha: 归档文件 sha256(与 Fake 仓库 checksum 保持同值,模拟同一份文件)。
callback_id: 收料执行单元回调键(唯一约束,用例间取不同值)。
Returns:
已入库的 ShippingReceiptReportFile。
已入库的 FreightRpaInboundReportFile。
"""
from app import db
from app.models import (
ShippingInventorySource,
ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
FreightRpaSource,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
source = ShippingInventorySource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source_code,
source = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = FreightRpaInboundUnitRun(
source_id=source.id, source_code=source_code,
connector_type="dbs", callback_id=callback_id,
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = ShippingReceiptReportFile(
report = FreightRpaInboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=f"shipping/receipt/{callback_id}.xlsx",
original_filename=f"{callback_id}.xlsx", file_size=16, sha256=sha,
@@ -262,7 +262,7 @@ def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m
# 独立 commit 落到当前可用文件(parse_failed 三列),来源投影转 parse_failed;
# 同步数据已回滚(桥隔离保持)。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
from app.services.in_transit_transfer import evidence_sync
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
@@ -282,7 +282,7 @@ def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m
assert ok is False # [断言意图] 同步失败被吞(桥隔离)
assert TransferMovementLedger.query.count() == 0 # [断言意图] 坏行未落档(同步数据已回滚)
db.session.expire_all() # 标记经桥内独立 commit:失效缓存重读
row = db.session.query(ShippingReceiptReportFile).filter_by(id=report.id).one()
row = db.session.query(FreightRpaInboundReportFile).filter_by(id=report.id).one()
assert row.parse_failed_at is not None # [断言意图] 失败事实已落库
assert row.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID"
assert row.parse_error_message
@@ -0,0 +1,320 @@
"""tests/services/in_transit_transfer/test_inbound_report_handler.py
用途:阶段 B Task 7——inbound 报表事实处理函数(handle_inbound_report)的契约测试:
未注册不推进、处理函数先失败后成功只推进一次且文件只留一行、无等待任务时回调成功、
同来源两单元分属两排程 run 时收口只打「本次回调收尾的单元」的 run(修复轮)。
依赖:app(SQLite)fixture、freight_rpa.reports.dispatch(注册表)、
freight_rpa.inbound.report_archive.ingest_inbound_callback(归档+投递入口)、
in_transit_transfer.inbound_callback_bridge / TransferSourceJob(调拨侧事实)。
逻辑:复刻 test_report_fact_dispatch 的注册表隔离与归档 IO 替身——组合根
(create_app→register_inbound_sinks)启动即注册 handle_inbound_report,
未注册用例必须先清空注册表,否则 404 断言假绿;success 归档走替身 IO
(drop 根读取返回注入字节、MinIO 上传 no-op),不依赖真实文件系统;
收口定位用例构造两个 awaiting 排程 run(各挂一个同来源单元),
对旧单元回调后断言只有旧 run 被收口、新 run 保持等待。
"""
from __future__ import annotations
import hashlib
import pytest
@pytest.fixture
def db_session(app):
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
@pytest.fixture(autouse=True)
def _reset_report_handlers():
"""每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。
[断言意图] 未注册用例必须跑在"干净注册表"上——组合根启动已注册
handle_inbound_report,不清空会让 FREIGHT_RPA.SINK_NOT_REGISTERED 断言假绿。
"""
from app.services.freight_rpa.reports import dispatch as dispatch_module
saved = dict(dispatch_module._REPORT_HANDLERS)
dispatch_module._REPORT_HANDLERS.clear()
yield
dispatch_module._REPORT_HANDLERS.clear()
dispatch_module._REPORT_HANDLERS.update(saved)
@pytest.fixture(autouse=True)
def _fake_archive_io(monkeypatch):
"""替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。
核心逻辑:与 test_report_fact_dispatch 同一 monkeypatch 姿态(patch
report_archive 模块属性),使 success 归档分支脱离真实文件系统与对象存储。
"""
from app.services.freight_rpa.inbound import report_archive
monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: b"handler-bytes")
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。
_CALLBACK_SEQ: dict[str, int] = {"n": 0}
def _next_callback_id() -> str:
"""生成跨用例唯一的 callback_id(unit run 唯一约束)。"""
_CALLBACK_SEQ["n"] += 1
return f"inbound-handler-{_CALLBACK_SEQ['n']}"
def _waiting_job(source_code: str):
"""构造一个未落库的 waiting_rpa_callback 来源任务(先建 TransferRun 满足外键)。
核心逻辑:TransferRun 只 add+flush(拿 run_id);TransferSourceJob 由调用方
add+commit——与用例体里的 db_session.add(job) 契约一致。
"""
from app import db
from app.models import TransferRun, TransferSourceJob
run = TransferRun(
run_no=f"RUN-HANDLER-{_next_callback_id()}",
business_date="2026-09-17",
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 _success_payload_for(source_code: str) -> dict:
"""构造一个挂种子站点的 awaiting 单元及其 success 回调载荷(可通过 schema 校验)。
核心逻辑:source_code 列允许测试值(如 "DSV",与调拨任务匹配),source_id
外键挂 conftest 种子站点 DSV360_AWSDU;替身 IO 注入字节与 sha256 对齐。
"""
from app import db
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = FreightRpaInboundUnitRun(
source_id=anchor.id,
source_code=source_code,
connector_type="dbs",
callback_id=_next_callback_id(),
status="awaiting_rpa",
config_snapshot_json={},
)
db.session.add(unit)
db.session.commit()
data = b"handler-bytes"
return {
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": f"receipt_{unit.id}.xlsx",
"original_filename": "receipt.xlsx",
"sha256": hashlib.sha256(data).hexdigest(),
}
def test_unregistered_transfer_handler_leaves_job_waiting(app, db_session):
"""未注册处理函数:归档 404 后调拨任务必须原地保持 waiting_rpa_callback。"""
from app.core.errors import AppError
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
job = _waiting_job(source_code="DSV")
db_session.add(job)
db_session.commit()
# 不注册 handle_inbound_report
with pytest.raises(AppError) as exc:
ingest_inbound_callback(_success_payload_for("DSV"))
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
db_session.refresh(job)
assert job.status == "waiting_rpa_callback"
def test_handler_fail_then_success_advances_once(app, db_session, monkeypatch):
"""处理函数先失败后成功:文件只留一行,调拨任务只推进一次到 file_ready。"""
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
job = _waiting_job(source_code="DSV")
db_session.add(job)
db_session.commit()
calls = {"n": 0}
def flaky(fact: ReportFact) -> None:
calls["n"] += 1
if calls["n"] == 1:
raise RuntimeError("once")
handle_inbound_report(fact)
register_report_handler("inbound", flaky)
payload = _success_payload_for("DSV")
with pytest.raises(RuntimeError):
ingest_inbound_callback(payload)
ingest_inbound_callback(payload)
db_session.refresh(job)
assert job.status == "file_ready"
assert FreightRpaInboundReportFile.query.count() == 1
def test_no_waiting_job_is_success(app, db_session):
"""无等待中的调拨任务:处理函数照常成功返回,且不产生任何调拨来源任务行。"""
from app.models import TransferSourceJob
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
register_report_handler("inbound", handle_inbound_report)
ingest_inbound_callback(_success_payload_for("DSV"))
assert TransferSourceJob.query.filter_by(source_code="DSV").count() == 0
def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaiting: bool = True):
"""构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_receipt_rpa 等待态。"""
from app.models import ScheduleRun, ScheduleTask
task = ScheduleTask(
schedule_no=schedule_no, name=f'Receipt {schedule_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', total_count=1,
success_count=0, failed_count=0, skipped_count=0,
response_summary_json={'awaiting_receipt_rpa': awaiting},
)
db_session.add(run)
db_session.commit()
return run
def _unit_on_run(db_session, run, *, callback_id: str):
"""在指定排程 run 下造一个挂种子站点的 awaiting 收料单元(source_code=DSV)。"""
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id, source_id=anchor.id, source_code="DSV",
connector_type="dbs", callback_id=callback_id,
status="awaiting_rpa", config_snapshot_json={},
)
db_session.add(unit)
db_session.commit()
return unit
def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch):
"""同来源两个单元分属两个排程 run:本回调收尾的单元(按文件反查)只收口它自己的 run。
[断言意图] 修复「按来源取最新单元」的错位:旧逻辑会把收口打到更新单元的 run,
本回调刚完成的 run 永久滞留 awaiting_receipt_rpa。
"""
from app.models import ScheduleRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file",
lambda _path: b"handler-bytes",
)
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
register_report_handler("inbound", handle_inbound_report)
run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-OLD", run_no="RUN-ONHAND-OLD")
run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-NEW", run_no="RUN-ONHAND-NEW")
unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-old")
_unit_on_run(db_session, run_new, callback_id="inbound-handler-new")
ingest_inbound_callback({
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit_old.callback_id,
"status": "success",
"file_path": "receipt_old.xlsx",
"original_filename": "receipt.xlsx",
"sha256": hashlib.sha256(b"handler-bytes").hexdigest(),
})
db_session.rollback()
db_session.expire_all()
# [断言意图] 本回调收尾的是旧单元:只有旧 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")
# 新单元的 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
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。
"""
from datetime import datetime
from app.models import ScheduleRun, FreightRpaInboundUnitRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file",
lambda _path: b"handler-bytes",
)
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
register_report_handler("inbound", handle_inbound_report)
run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-OLD", run_no="RUN-FAIL-OLD")
run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-NEW", run_no="RUN-FAIL-NEW")
unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-fail-old")
unit_new = _unit_on_run(db_session, run_new, callback_id="inbound-handler-fail-new")
# [RED 场景] 新单元已先以同错误文本终态失败落库——旧逻辑按 (来源, 终态, 错误文本)
# 取最新单元会命中新单元,把收口打到新 run。
unit_new.status = "failed"
unit_new.error_code = "RPA_TEST_FAIL"
unit_new.error_message = "boom"
unit_new.finished_at = datetime.utcnow()
db_session.commit()
result = ingest_inbound_callback({
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit_old.callback_id,
"status": "failed",
"error_code": "RPA_TEST_FAIL",
"error_message": "boom",
})
assert result["status"] == "failed"
db_session.rollback()
db_session.expire_all()
# [断言意图] 只有旧单元的 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")
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
@@ -0,0 +1,36 @@
"""tests/services/in_transit_transfer/test_inbound_report_read_boundary.py
用途:锁定阶段 B Task 4——in_transit_transfer 包不得引用 freight_rpa 报表模型
(站点与报表文件/配置的读取一律改走 app.services.freight_rpa.reports
只读入口,业务方只按 source_code / file_id 消费)。
依赖:pathlib(纯文本扫描;无 app/DB fixture,秒级运行)。
逻辑:对包内全部 .py 逐文件做 banned 字符串扫描(含注释/docstring——模型名
出现在任何位置都算引用面),命中即 fail 并按「文件名: 模型名」逐条列出,
防止调拨域绕过只读入口直接 import 报表模型造成域间漂移。
"""
from __future__ import annotations
from pathlib import Path
def test_in_transit_does_not_import_rpa_report_models():
"""in_transit_transfer 包内任何 .py 不得出现 freight_rpa 报表模型名。
banned 集合与计划 Task 4 冻结一致:入站归档文件、入站报表配置、库存站点、
在手报表配置四类模型自本任务起归 freight_rpa 域读写;调拨域(含注释与
docstring)不得再引用其类名——命中即边界破坏,须收敛到
freight_rpa.reports.queries 的只读函数。
"""
root = Path(__file__).resolve().parents[3] / "app" / "services" / "in_transit_transfer"
banned = ("FreightRpaInboundReportFile", "FreightRpaInboundReportConfig",
"FreightRpaSource", "FreightRpaOnhandReportConfig")
hits = []
for path in root.rglob("*.py"):
text = path.read_text(encoding="utf-8")
for name in banned:
if name in text:
hits.append(f"{path.name}: {name}")
# [断言意图] hits 必须为空:任一命中都意味着调拨域仍在直接引用
# freight_rpa 报表模型(import、类型标注或文档残句),边界未闭合。
assert hits == []
@@ -1,10 +1,10 @@
"""真实收料 RPA 触发服务测试。
用途:验证 trigger_inbound_rpa / trigger_inbound_rpa_batch 按来源装配收料 trigger unit
并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
并调用写者;触发先落 FreightRpaInboundUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
依赖:app(SQLite)fixture、inbound_trigger_service.trigger_inbound_rpa(_batch)、
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
既有测试种子(FreightRpaProfile/FreightRpaSource)。
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False;
批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批,
parse_failed 先本地重解析不触发 RPA)。
@@ -14,7 +14,7 @@ from __future__ import annotations
import pytest
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
from app.services.in_transit_transfer.inbound_trigger_service import (
trigger_inbound_rpa,
trigger_inbound_rpa_batch,
@@ -24,10 +24,10 @@ from app.services.in_transit_transfer.inbound_trigger_service import (
@pytest.fixture
def receipt_source():
"""复用种子来源并为其创建收料配置。"""
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
assert source is not None
config = ShippingReceiptReportConfig(
inventory_source_id=source.id,
config = FreightRpaInboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
)
@@ -67,7 +67,7 @@ def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source):
def test_trigger_inbound_rpa_disabled_source_fails_closed(app):
"""来源停用 → ok=False,不写 trigger。"""
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
source.enabled = False
from app import db
@@ -84,9 +84,9 @@ def test_trigger_inbound_rpa_missing_config_fails_closed(app):
def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
"""触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
"""触发必须先落 FreightRpaInboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
captured: dict = {}
@@ -101,22 +101,22 @@ def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receip
reason="transfer_retry_inbound", writer=fake_writer,
)
assert outcome["ok"] is True
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
assert unit.status == "awaiting_rpa"
# [断言意图] 按需触发无排程 run,schedule_run_id 必须为 NULL——
# PostgreSQL 上 FK 禁止 0 占位(SQLite 测试库不强制 FK,需显式守住列可空契约)。
assert unit.schedule_run_id is None
assert ShippingReceiptRpaUnitRun.__table__.columns['schedule_run_id'].nullable is True
assert FreightRpaInboundUnitRun.__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 _bind_published_inbound_profile(config: ShippingReceiptReportConfig) -> None:
def _bind_published_inbound_profile(config: FreightRpaInboundReportConfig) -> None:
"""给收料配置绑定一条已发布 inbound 规则(仅满足守卫校验,不参与解析)。"""
from app import db
from app.models import ShippingInventoryParsingProfile
from app.models import FreightRpaParsingProfile
profile = ShippingInventoryParsingProfile(
profile = FreightRpaParsingProfile(
purpose='inbound', profile_code='MOVE_TRIGGER_STD', display_name='入站解析规则',
version=1, status='published', file_format='xlsx',
definition_json={'sheet_name': None, 'header_row_index': 1,
@@ -135,8 +135,8 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
with app.app_context():
config = ShippingReceiptReportConfig.query.filter_by(
inventory_source_id=receipt_source.id).one()
config = FreightRpaInboundReportConfig.query.filter_by(
source_id=receipt_source.id).one()
_bind_published_inbound_profile(config)
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
@@ -165,15 +165,15 @@ def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_
def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
outcome = trigger_inbound_rpa(
source_code=receipt_source.source_code, business_date="2026-09-17",
reason="transfer_retry_inbound", writer=lambda *a, **k: None,
)
assert outcome["ok"] is False
unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
ShippingReceiptRpaUnitRun.id.desc()).first()
unit = FreightRpaInboundUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
FreightRpaInboundUnitRun.id.desc()).first()
assert unit.status == "failed"
assert unit.error_code == "RPA_INBOUND_TRIGGER_UNAVAILABLE"
@@ -185,28 +185,35 @@ def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, rec
@pytest.fixture
def second_receipt_source(app):
"""再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定
解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。"""
"""再造一个启用来源 + 收料配置(批量用例需要多来源);s18 起启用态要求
Excel 模板绑定(ck_freight_rpa_sources_enabled_template),解析绑定复用种子源配置行。"""
from app import db
from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig
from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaInboundReportConfig
seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
profile = ShippingRpaProfile(
seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
profile = FreightRpaProfile(
profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs',
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
)
source = ShippingInventorySource(
source = FreightRpaSource(
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
rpa_profile=profile,
parsing_profile=seed.parsing_profile, excel_template=seed.excel_template,
excel_template=seed.excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
enabled=True,
)
# s18 起在手解析绑定/报表路径归配置行,复用种子源绑定形态。
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() # 先取 source.id(新建对象 flush 前无主键)
config = ShippingReceiptReportConfig(
inventory_source_id=source.id,
config = FreightRpaInboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[],
)
@@ -217,7 +224,7 @@ def second_receipt_source(app):
def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
calls: list = []
@@ -238,7 +245,7 @@ def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
callback_ids = {u['callback_id'] for u in calls[0]['units']}
assert len(callback_ids) == 2
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.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)
@@ -278,7 +285,7 @@ def test_trigger_inbound_rpa_batch_all_invalid_no_trigger(app):
def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
@@ -286,7 +293,7 @@ def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, rece
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.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_INBOUND_TRIGGER_UNAVAILABLE'}
@@ -4,7 +4,7 @@
拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码;
inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配,
匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。
依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。
依赖:app fixture 种子站点、FreightRpaOnhandExternalMapping、DefaultRouteResolver。
逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。
"""
@@ -13,18 +13,18 @@ from __future__ import annotations
import pytest
from app.extensions import db
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource
from app.services.in_transit_transfer.deps import DefaultRouteResolver
from app.services.in_transit_transfer.matching_service import RouteNotResolvedError
def _seed_mapping(
source: ShippingInventorySource, *, freight_warehouse_id: str | None,
source: FreightRpaSource, *, freight_warehouse_id: str | None,
in_transit_warehouse_code: str = 'TZT-01',
) -> ShippingInventoryExternalMapping:
) -> FreightRpaOnhandExternalMapping:
"""在既有种子来源上挂一条启用映射。"""
mapping = ShippingInventoryExternalMapping(
inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id,
mapping = FreightRpaOnhandExternalMapping(
source_id=source.id, freight_warehouse_id=freight_warehouse_id,
external_system_code='TOPGP', external_organization_code='TGHX',
external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓',
in_transit_warehouse_code=in_transit_warehouse_code, enabled=True,
@@ -34,12 +34,13 @@ def _seed_mapping(
return mapping
def _seed_inventory_match_source() -> ShippingInventorySource:
def _seed_inventory_match_source() -> FreightRpaSource:
"""以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。"""
template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = ShippingInventorySource(
template = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
# s18 起站点行不再承载 parsing_profile_id;路由解析只读外部映射,无需在手配置行。
source = FreightRpaSource(
source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane',
rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id,
rpa_profile_id=template.rpa_profile_id,
excel_template_id=template.excel_template_id,
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True,
)
@@ -51,7 +52,7 @@ def _seed_inventory_match_source() -> ShippingInventorySource:
def test_fixed_source_uses_single_mapping_in_transit_code(app):
"""fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。"""
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
# 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。
_seed_mapping(source, freight_warehouse_id='TZR2')
@@ -118,7 +119,7 @@ def test_inventory_match_fails_closed_without_any_match(app):
def test_route_resolver_fails_closed_without_in_transit_code(app):
"""映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。"""
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='')
with pytest.raises(RouteNotResolvedError):
@@ -46,12 +46,12 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
"""创建可参与收料的最小库存源(rpa_profile_id 非空,须先建 Profile)。"""
from app.models import (
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingRpaProfile,
FreightRpaParsingProfile,
FreightRpaSource,
FreightRpaProfile,
)
profile = ShippingRpaProfile(
profile = FreightRpaProfile(
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="crane",
login_url="https://test.invalid/login", login_config_json={"auth_mode": "password"},
)
@@ -62,7 +62,7 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
"rpa_profile_id": profile.id, "enabled": enabled,
}
if enabled:
parsing = ShippingInventoryParsingProfile(
parsing = FreightRpaParsingProfile(
profile_code=f"PARSE_{source_code}", display_name=source_code, version=1,
status="published", file_format="xlsx",
definition_json={"field_mapping": {}, "match_keys": []},
@@ -79,27 +79,35 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
db.session.add_all([parsing, template])
db.session.flush()
source_kwargs.update(
parsing_profile_id=parsing.id, excel_template_id=template.id,
excel_template_id=template.id,
warehouse_resolution_mode="fixed", fixed_warehouse_id="WH1",
)
else:
source_kwargs.update(warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None)
source = ShippingInventorySource(**source_kwargs)
source = FreightRpaSource(**source_kwargs)
db.session.add(source)
if enabled:
# s18 起解析方案绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行;
# 经关系级联随站点一并入库。
from app.models import FreightRpaOnhandReportConfig
FreightRpaOnhandReportConfig(
source=source, parsing_profile=parsing,
report_path_json={}, query_parameters_json=[],
)
return source
def test_list_inbound_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
"""缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。"""
from app.models import ShippingReceiptReportConfig
from app.models import FreightRpaInboundReportConfig
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True)
_make_receipt_source(transfer_db, "DBS_OFF", enabled=False)
_make_receipt_source(transfer_db, "CRANE_NOCONF", enabled=True)
transfer_db.session.flush()
transfer_db.session.add(ShippingReceiptReportConfig(
inventory_source_id=enabled.id, report_path_json={}, query_parameters_json=[],
transfer_db.session.add(FreightRpaInboundReportConfig(
source_id=enabled.id, report_path_json={}, query_parameters_json=[],
))
transfer_db.session.commit()
@@ -3,7 +3,7 @@
用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile),
按来源投影 ready/fetching/failed/expired/parse_failed/none,并验证解析失败
标记 record/clear 的往返语义。调拨不维护独立抓取状态表。
依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
逻辑:有当天(业务日)抓取且未过期文件→ready(若标记解析失败→parse_failed);
有进行中单元→fetching;最新单元失败终态→failed;
保留期已到或隔日旧文件(未清理)→expired;否则→none。
@@ -25,9 +25,9 @@ SOURCE_CODE = 'DSV360_AWSDU'
def receipt_unit_run():
"""构造一条收料执行单元(含排程/来源上下文)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
task = ScheduleTask(
schedule_no='SCH-SOURCE-STATUS', name='Source status test', schedule_type='platform_job',
owner_user_id=1, cron_expr='0 8 * * *', job_params={},
@@ -37,8 +37,8 @@ def receipt_unit_run():
run = ScheduleRun(run_no='RUN-SOURCE-STATUS', schedule_task_id=task.id, status='awaiting_callback')
db.session.add(run)
db.session.flush()
unit = ShippingReceiptRpaUnitRun(
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
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-status-001',
status='awaiting_rpa', config_snapshot_json={},
)
@@ -64,7 +64,7 @@ def test_running_unit_is_fetching(app, receipt_unit_run):
def test_failed_latest_unit_is_failed(app, receipt_unit_run):
"""最新单元为失败终态且无文件 → failed。"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
receipt_unit_run.status = 'failed'
db.session.commit()
@@ -75,11 +75,11 @@ def test_failed_latest_unit_is_failed(app, receipt_unit_run):
def test_report_file_is_ready(app, receipt_unit_run):
"""有收料归档文件 → ready,且带 file_no/sha256。"""
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'receipt workbook').hexdigest()
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/test.xlsx', original_filename='receipt.xlsx',
file_size=16, sha256=digest,
@@ -96,10 +96,10 @@ def test_expired_report_is_expired(app, receipt_unit_run):
"""保留期已到但清理任务未删 → expired,不得误报 ready。"""
# [断言意图] 过期判定只看 archive_expires_at,不依赖保留期清理任务是否已落位。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
@@ -115,17 +115,17 @@ def test_newer_valid_report_wins_over_expired(app, receipt_unit_run):
"""过期文件之后又抓到未过期文件 → 以最新未过期文件为准(ready)。"""
# [断言意图] ready 查询过滤掉过期记录后仍按 created_at/id 倒序取最新一条。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'fresh workbook').hexdigest()
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
archive_expires_at=datetime.utcnow() - timedelta(days=1),
))
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/fresh.xlsx', original_filename='fresh.xlsx',
file_size=16, sha256=digest,
@@ -143,10 +143,10 @@ def test_stale_report_is_expired(app, receipt_unit_run):
# [断言意图] 新鲜度按 Asia/Shanghai 业务日窗口判定(UTC 库存时间须换算):
# 隔日抓取的文件对 D+1 预检是旧数据,投影 expired 引导重试重抓。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/stale.xlsx', original_filename='stale.xlsx',
file_size=16, sha256=hashlib.sha256(b'stale workbook').hexdigest(),
@@ -161,11 +161,11 @@ def test_stale_report_is_expired(app, receipt_unit_run):
def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_unit_run):
"""可用归档文件若已标记 parse_failed_at → file_status=parse_failed 且不可当 ready。"""
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'bad workbook').hexdigest()
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/bad.xlsx', original_filename='bad.xlsx',
file_size=16, sha256=digest,
@@ -183,7 +183,7 @@ def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_uni
def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
"""record 写入三列;clear 清空后投影回 ready。"""
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
from app.services.in_transit_transfer.source_file_status import (
clear_inbound_parse_failure,
record_inbound_parse_failure,
@@ -192,7 +192,7 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'roundtrip').hexdigest()
report = ShippingReceiptReportFile(
report = FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/ok.xlsx', original_filename='ok.xlsx',
file_size=16, sha256=digest,
@@ -228,14 +228,14 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
门禁)永久锁死;回收后必须翻转 failed 解锁重新触发 RPA。
"""
from app import db
from app.models import ShippingInventorySource, ShippingReceiptRpaUnitRun
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units
from app.models import FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
db.session.add(ShippingReceiptRpaUnitRun(
schedule_run_id=None, inventory_source_id=source.id, source_code=source.source_code,
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
db.session.add(FreightRpaInboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
connector_type='dbs', callback_id='inbound-orphan-status', status='awaiting_rpa',
config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=5),
))
@@ -4,7 +4,7 @@
可空成分 NOT NULL + default ''/transfer_executed 默认 false/
source_file_id FK ON DELETE SET NULL(文件清理后档事实留存)。
依赖:app_ctx(根 conftest app fixture 上下文别名)、transfer_db(SQLite 内存库)、
models/in_transit_transfer、models/shipping_receipt_report。
models/in_transit_transfer、models/shipping_inbound_report。
逻辑:纯元数据断言(不落库)+ 真库往返(默认值/唯一约束/FK SET NULL 行为)。
"""
@@ -15,7 +15,7 @@ from sqlalchemy import inspect, text
from sqlalchemy.exc import IntegrityError
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
from app.models.in_transit_transfer import TransferMovementLedger
# 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维):8 成分全部 NOT NULL,
@@ -106,13 +106,13 @@ def test_scope_indexes_declared(app_ctx):
def test_source_file_fk_on_delete_set_null(app_ctx):
"""source_file_id FK 指向 shipping_receipt_report_files 且 ON DELETE SET NULL(档事实留存)。"""
"""source_file_id FK 指向 freight_rpa_inbound_report_files 且 ON DELETE SET NULL(档事实留存)。"""
cols = _column_map()
fk = next(
fk for fk in TransferMovementLedger.__table__.foreign_keys
if fk.parent.name == 'source_file_id'
)
assert fk.target_fullname == 'shipping_receipt_report_files.id'
assert fk.target_fullname == 'freight_rpa_inbound_report_files.id'
assert fk.ondelete == 'SET NULL'
assert cols['source_file_id'].nullable is True
@@ -164,17 +164,17 @@ def test_duplicate_natural_key_rejected(transfer_db):
def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
"""source_file relationship 可导航;来源文件删除后档记录留存且 source_file_id 置 NULL。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
unit_run = ShippingReceiptRpaUnitRun(
inventory_source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行
unit_run = FreightRpaInboundUnitRun(
source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行
source_code='DBS-AWSBI',
connector_type='rpa',
callback_id='CB-LEDGER-001',
)
db.session.add(unit_run)
db.session.flush()
report_file = ShippingReceiptReportFile(
report_file = FreightRpaInboundReportFile(
unit_run_id=unit_run.id,
storage_provider='minio',
storage_bucket='receipts',
@@ -198,7 +198,7 @@ def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
db.session.commit()
loaded = db.session.get(TransferMovementLedger, ledger.id)
assert loaded.source_file.id == report_file.id # relationship 目标 ShippingReceiptReportFile
assert loaded.source_file.id == report_file.id # relationship 目标 FreightRpaInboundReportFile
# ON DELETE SET NULL 行为:开启 SQLite FK 强制后原样删文件(文件资产保留策略)。
# PRAGMA 是连接级开关且事务内为 no-op:必须走 AUTOCOMMIT 连接执行,归还连接池
@@ -208,7 +208,7 @@ def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
with db.engine.connect().execution_options(isolation_level='AUTOCOMMIT') as conn:
conn.execute(text('PRAGMA foreign_keys=ON'))
conn.execute(
text('DELETE FROM shipping_receipt_report_files WHERE id = :id'),
text('DELETE FROM freight_rpa_inbound_report_files WHERE id = :id'),
{'id': file_id},
)
conn.execute(text('PRAGMA foreign_keys=OFF'))