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

@@ -8,7 +8,7 @@
避免回调迟到误推进其他阶段任务。生产调用方为调拨侧报表事实处理函数
handle_inbound_report(Task 7,inbound_report_handler.py——归档终态 commit 后
经 dispatch_report_fact 调入;返回 None 时调用方跳过提交分支);回归测试桥
(inbound_report_storage._advance_transfer_source_job)仍走本函数。
(handle_inbound_report / 历史测试桥)仍走本函数。
SourceJob 状态为字符串常量(见 models)。
"""
@@ -9,7 +9,7 @@ services/in_transit_transfer/inbound_report_handler.py
app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact /
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、
in_transit_transfer.inbound_callback_bridge / evidence_sync(同包)。
逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_inbound_sinks)
逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_inbound_sinks)
注册为 'inbound' kind 处理函数;freight_rpa.inbound.report_archive.
ingest_inbound_callback 在每个终态 db.session.commit() 之后经
dispatch_report_fact 调入本函数。处理函数只改调拨自己的行;
@@ -65,7 +65,7 @@ def handle_inbound_report(fact: ReportFact) -> None:
if kind != 'inbound':
raise ValidationError(
f"handle_inbound_report only accepts inbound facts, got: {kind!r}",
code='SHIPPING.RECEIPT_CALLBACK_INVALID',
code='SHIPPING.INBOUND_CALLBACK_INVALID',
details={'report_kind': fact.report_kind},
)
@@ -126,9 +126,9 @@ def handle_inbound_report(fact: ReportFact) -> None:
schedule_run_id = unit.schedule_run_id
if schedule_run_id:
from app.services.schedule.freight_rpa_inbound_finalize import (
finalize_receipt_schedule_run_if_complete,
refresh_receipt_schedule_run_progress,
finalize_inbound_schedule_run_if_complete,
refresh_inbound_schedule_run_progress,
)
refresh_receipt_schedule_run_progress(schedule_run_id)
finalize_receipt_schedule_run_if_complete(schedule_run_id)
refresh_inbound_schedule_run_progress(schedule_run_id)
finalize_inbound_schedule_run_if_complete(schedule_run_id)
@@ -0,0 +1,144 @@
"""
services/in_transit_transfer/outbound_report_handler.py
用途:outbound 报表事实的调拨侧业务处理函数——出站归档终态 commit 后由
dispatch_report_fact 投递的 ReportFact 只在此推进调拨自己的任务:
TransferSourceJob 等待态推进、出站排程收口。
依赖:app.db、app.models(FreightRpaOutboundUnitRun——执行单元读取)、
app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact /
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)。
逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_outbound_sinks)
注册为 'outbound' kind 处理函数;freight_rpa.outbound.report_archive.
ingest_outbound_callback 在每个终态 db.session.commit() 之后经
dispatch_report_fact 调入本函数。处理函数只改调拨自己的行;
【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚,
Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。
状态机字段与入站同一套:waiting_rpa_callback → file_ready / failed;
无等待任务则 no-op;第二次调用该行已离开等待态,不再改(可重入)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.core.errors import ValidationError
from app.models import FreightRpaOutboundUnitRun, TransferSourceJob
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
_FILE_READY = 'file_ready'
_WAITING_RPA_CALLBACK = 'waiting_rpa_callback'
_FAILED = 'failed'
def _advance_waiting_source_job(
*, source_code: str, file_no: str | None = None, file_sha256: str | None = None,
callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None,
) -> TransferSourceJob | None:
"""按来源推进最新等待回调的调拨来源任务(与入站桥同一等待态字段)。
核心逻辑:只改 status='waiting_rpa_callback' 的行;无匹配则不动作,
避免回调迟到误推进其他阶段任务。success/有文件 → file_ready;否则 → failed。
本函数只 flush 不 commit,提交归属 handle_outbound_report。
Args:
source_code: 回调所属来源实例。
file_no: 出站文件号(success 时)。
file_sha256: 出站文件 sha256(success 时)。
callback_ok / error_code / error_message: 回调终态。
Returns:
被推进的任务;无等待任务或已终态时返回 None。
"""
job = (
TransferSourceJob.query
.filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK)
.order_by(TransferSourceJob.id.desc())
.first()
)
if job is None:
return None
if callback_ok and file_no:
job.status = _FILE_READY
job.file_no = file_no
job.file_sha256 = file_sha256
job.error_code = None
job.error_message = None
job.finished_at = datetime.utcnow()
else:
job.status = _FAILED
job.error_code = error_code or 'RPA_OUTBOUND_CALLBACK_FAILED'
job.error_message = error_message or 'outbound rpa callback failed'
job.finished_at = datetime.utcnow()
db.session.flush()
return job
def handle_outbound_report(fact: ReportFact) -> None:
"""report_kind 必须是 outbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready;
ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。
核心逻辑:
[STEP 1] kind 门禁(fail-closed);[STEP 2] 推进等待中的来源任务(只改
status='waiting_rpa_callback' 的行,无等待行返回 None);[STEP 3]
推进结果必须在此提交;[STEP 4] 精确定位本次回调收尾的执行单元并回写出站
排程进度、归集终态。不调用入站 evidence_sync(record_kind=inbound 专用)。
【不捕获异常】任何一步失败原样外抛供 Worker 重试。
Args:
fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/
file_id/sha256/ok/error_code/error_message/unit_run_id)。
Returns:
None(推进/收口结果全部写库,不返回业务值)。
Raises:
ValidationError: report_kind 非 outbound(误注册/误分发,fail-closed)。
"""
# [STEP 1] kind 门禁:本函数只消费 outbound 事实。
kind = require_report_kind(fact.report_kind)
if kind != 'outbound':
raise ValidationError(
f"handle_outbound_report only accepts outbound facts, got: {kind!r}",
code='SHIPPING.OUTBOUND_CALLBACK_INVALID',
details={'report_kind': fact.report_kind},
)
# [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready;
# 否则 → failed。无等待行返回 None(调拨侧无行可改,直接结束推进分支)。
if fact.ok and fact.file_id is not None:
advanced = _advance_waiting_source_job(
source_code=fact.source_code,
file_no=str(fact.file_id),
file_sha256=fact.sha256,
callback_ok=True,
)
else:
advanced = _advance_waiting_source_job(
source_code=fact.source_code,
callback_ok=False,
error_code=fact.error_code,
error_message=fact.error_message,
)
# [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交。
if advanced is not None:
db.session.commit()
# [STEP 4] 出站排程收口:按 fact.unit_run_id 精确定位本次回调收尾的执行单元。
schedule_run_id: int | None = None
if fact.unit_run_id is not None:
unit = db.session.get(FreightRpaOutboundUnitRun, int(fact.unit_run_id))
if unit is None:
from app.core.errors import NotFoundError
raise NotFoundError(
f"Outbound RPA unit not found: {fact.unit_run_id}",
details={'unit_run_id': fact.unit_run_id},
)
schedule_run_id = unit.schedule_run_id
if schedule_run_id:
from app.services.schedule.freight_rpa_outbound_finalize import (
finalize_outbound_schedule_run_if_complete,
refresh_outbound_schedule_run_progress,
)
refresh_outbound_schedule_run_progress(schedule_run_id)
finalize_outbound_schedule_run_if_complete(schedule_run_id)
@@ -0,0 +1,261 @@
"""在途调拨出站 RPA 触发服务。
用途:为单个或多个来源触发出站 RPA 抓取(出站证据 = freight_rpa 出站 RPA 产物,
复用货代出站 trigger 链路),不创建排程。按来源取站点、出站配置与登录连接
(全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行
(awaiting_rpa,回调按 callback_id 查库可达),再装配出站 trigger unit 并
调用 write_outbound_export_batch_trigger 原子写 trigger。
依赖:write_outbound_export_batch_trigger(默认 writer,freight_rpa.outbound.trigger_io)、
freight_rpa.reports.queries(get_site / get_outbound_config / get_rpa_login_profile /
list_outbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。
逻辑:list_outbound_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/出站配置缺失/登录连接缺失时
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
trigger_outbound_rpa_batch 把多来源合并为一个 batch trigger 文件:
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
trigger unit 载荷键集与 Worker 契约(freight_rpa.outbound.v1)逐键对齐入站。
"""
from __future__ import annotations
import uuid
from typing import Any, Callable
from app.services.freight_rpa.outbound.trigger_io import (
ACTION_OUTBOUND_EXPORT_BATCH,
SCHEMA,
write_outbound_export_batch_trigger,
)
from app.services.freight_rpa.reports.queries import (
get_outbound_config,
get_rpa_login_profile,
get_site,
list_outbound_configured_source_codes,
)
RouteTriggerWriter = Callable[..., str | None]
def _write_outbound_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
"""适配出站 IO 的 meta 形参,对外保持与入站 writer 相同的 payload= 协议。"""
return write_outbound_export_batch_trigger(run_no, units, meta=payload)
def _build_trigger_unit(
*, source_code: str, business_date: str, reason: str,
) -> dict[str, Any]:
"""装配单来源出站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
站点(get_site)/ 出站配置(get_outbound_config)/ 登录连接
(get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的
unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。
"""
site = get_site(source_code)
if site is None or not site.enabled:
raise RuntimeError(f'source not enabled: {source_code}')
config = get_outbound_config(source_code)
if config is None:
raise RuntimeError(f'outbound config missing: {source_code}')
profile = get_rpa_login_profile(source_code)
if profile is None or not profile.enabled:
raise RuntimeError(f'outbound source profile unavailable: {source_code}')
query_parameters = [
dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict)
]
snapshot = {
'config_id': config.config_id, 'config_version': config.config_version,
'connector_type': site.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': query_parameters,
'warehouse_id': None, 'rpa_profile_id': profile.profile_id,
}
return {
'source_id': site.source_id,
'callback_id': f'outbound:{uuid.uuid4().hex}',
'source_code': site.source_code,
'connector_type': site.connector_type,
'warehouse_id': None,
'rpa_profile_id': profile.profile_id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(query_parameters),
'config_snapshot': snapshot,
'business_date': business_date,
'reason': reason,
}
def list_outbound_capable_source_codes() -> list[str]:
"""列出可产出出站文件的启用来源实例(已配置出站报表的启用站点)。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——出站文件
只能来自已配置出站报表的站点,与货代出站 RPA 排程的站点口径一致。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
return list_outbound_configured_source_codes()
def trigger_outbound_rpa(
*,
source_code: str,
business_date: str,
reason: str = 'transfer_retry_outbound',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源出站 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
Args:
source_code: 来源实例编码。
business_date: 业务日期。
reason: 触发原因(写入 trigger)。
writer: 触发写者;缺省复用 write_outbound_export_batch_trigger(payload= 协议)。
Returns:
{"ok": True, "callback_id": ..., "trigger_path": ...} 或
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
"""
try:
unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
except RuntimeError as exc:
return {"ok": False, "error_code": "RPA_OUTBOUND_CONFIG_MISSING", "error_message": str(exc)}
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
# 不落行则回调必然 404(与排程路径 / 入站按需触发同一模式)。
from app import db
from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun
unit = FreightRpaOutboundUnitRun(
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
source_id=unit_payload['source_id'],
source_code=unit_payload['source_code'],
connector_type=unit_payload['connector_type'],
warehouse_id=unit_payload.get('warehouse_id'),
callback_id=unit_payload['callback_id'],
status='awaiting_rpa',
config_snapshot_json=dict(unit_payload['config_snapshot']),
)
db.session.add(unit)
db.session.flush()
unit_payload['unit_run_id'] = unit.id
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or _write_outbound_trigger
path = writer_fn(run_no, [unit_payload], payload={
'schema_version': SCHEMA,
'action': ACTION_OUTBOUND_EXPORT_BATCH,
'source_code': source_code,
'business_date': business_date,
'reason': reason,
})
if not path:
unit.status = 'failed'
unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
unit.error_message = 'outbound trigger directory unavailable'
db.session.commit()
return {"ok": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE"}
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
unit.trigger_snapshot_json = unit_payload
db.session.commit()
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
def trigger_outbound_rpa_batch(
*,
source_codes: list[str],
business_date: str,
reason: str = 'transfer_retry_outbound',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""批量触发多来源出站 RPA:全部有效来源合并写**一个** batch trigger 文件。
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个出站来源编码时调用;
行级单来源重试仍走 trigger_outbound_rpa(一源一文件语义不变)。
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批);
有效 units 先各落一行 RPA 单元运行行再一次性 write_outbound_export_batch_trigger
原子落盘。Worker 对单文件按 profile 分组共享一次浏览器会话串行导出。
入站 batch 的 parse_failed 本地重解析不在此复用——来源文件状态投影仅覆盖入站归档。
Args:
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
business_date: 业务日期。
reason: 触发原因(写入 trigger payload)。
writer: 触发写者;缺省复用 write_outbound_export_batch_trigger。
Returns:
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
ok=本次请求产生了主效果(写盘成功);triggered=是否写了 batch trigger;
results 逐来源携带真实结果。
"""
from app import db
from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
results: list[dict[str, Any]] = []
units: list[FreightRpaOutboundUnitRun] = []
unit_payloads: list[dict[str, Any]] = []
# [STEP 1] 逐来源装配 unit;单源失败跳过不阻断整批。
for code in codes:
try:
unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason))
except RuntimeError as exc:
results.append({
'source_code': code, 'ok': False,
'error_code': 'RPA_OUTBOUND_CONFIG_MISSING', 'error_message': str(exc),
})
if not unit_payloads:
db.session.commit()
return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE", "results": results}
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
for payload in unit_payloads:
unit = FreightRpaOutboundUnitRun(
source_id=payload['source_id'],
source_code=payload['source_code'],
connector_type=payload['connector_type'],
warehouse_id=payload.get('warehouse_id'),
callback_id=payload['callback_id'],
status='awaiting_rpa',
config_snapshot_json=dict(payload['config_snapshot']),
)
db.session.add(unit)
units.append(unit)
db.session.flush()
for unit, payload in zip(units, unit_payloads):
payload['unit_run_id'] = unit.id
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or _write_outbound_trigger
path = writer_fn(run_no, unit_payloads, payload={
'schema_version': SCHEMA,
'action': ACTION_OUTBOUND_EXPORT_BATCH,
'business_date': business_date,
'reason': reason,
'source_codes': [payload['source_code'] for payload in unit_payloads],
})
if not path:
for unit in units:
unit.status = 'failed'
unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
unit.error_message = 'outbound trigger directory unavailable'
db.session.commit()
return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE", "results": results}
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
for unit, payload in zip(units, unit_payloads):
unit.trigger_snapshot_json = payload
results.append({'source_code': unit.source_code, 'ok': True})
db.session.commit()
return {"ok": True, "triggered": True, "trigger_path": path, "results": results}
@@ -0,0 +1,63 @@
"""
services/in_transit_transfer/rpa_sinks.py
用途:入站 / 出站 RPA 回调与报表事实的组合根注册——把 /api/freight-rpa/inbound-*、
outbound-* 接到 freight_rpa 归档入口与本包事实处理函数(调拨是唯一业务消费方)。
依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、
freight_rpa.inbound/outbound.report_archive、schedule.freight_rpa_*_finalize、
inbound_report_handler / outbound_report_handler。
逻辑:由 app.create_app 调用 register_inbound_sinks / register_outbound_sinks(幂等)。
进度类 sink 复刻 {'success':True,'data':...} envelope;文件事实经
register_report_handler 注册。不 import shipping_notice。
"""
from __future__ import annotations
from typing import Any, Callable
def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
"""旧 inbound/outbound 进度端点 envelope:{'success':True,'data':业务结果}。"""
def _sink(**payload: Any) -> dict[str, Any]:
return {'success': True, 'data': handler(payload)}
return _sink
def register_inbound_sinks() -> None:
"""注册全部 inbound 进度 sink 与 inbound 事实处理函数(幂等)。
核心逻辑:inbound-batch-ready 直挂 freight_rpa.inbound.report_archive.ingest_inbound_callback
(与 outbound 对称,无 shipping_notice 薄壳);unit/batch-progress 挂
schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report。
"""
from app.services.freight_rpa.common.callback_sinks import register_sink
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
from app.services.schedule import freight_rpa_inbound_finalize
register_sink('inbound-batch-ready', _success_data_envelope(ingest_inbound_callback))
register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_inbound_unit_processing))
register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_inbound_batch_progress))
register_report_handler('inbound', handle_inbound_report)
def register_outbound_sinks() -> None:
"""注册全部 outbound 进度 sink 与 outbound 事实处理函数(幂等)。
核心逻辑:outbound-batch-ready 直挂 freight_rpa.outbound.report_archive.ingest_outbound_callback;
unit/batch-progress 挂 schedule.freight_rpa_outbound_finalize;事实处理函数挂
handle_outbound_report。
"""
from app.services.freight_rpa.common.callback_sinks import register_sink
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
from app.services.schedule import freight_rpa_outbound_finalize
register_sink('outbound-batch-ready', _success_data_envelope(ingest_outbound_callback))
register_sink('outbound-unit-progress', _success_data_envelope(freight_rpa_outbound_finalize.mark_outbound_unit_processing))
register_sink('outbound-batch-progress', _success_data_envelope(freight_rpa_outbound_finalize.report_outbound_batch_progress))
register_report_handler('outbound', handle_outbound_report)