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:
1 parent
ffc0d4a430
commit
39fe3c05f2
453 files changed
+17945
-8646
No files matched your search
@@ -0,0 +1,45 @@
|
||||
"""freight_rpa/reports/__init__.py
|
||||
|
||||
用途:报表读域(阶段 B Task 3)——发货(shipping_notice 域)与在途调拨
|
||||
(in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包。
|
||||
依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。
|
||||
逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice)
|
||||
一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。
|
||||
本包不得 import app.services.shipping_notice 或 app.services.in_transit_transfer
|
||||
(import 边界由 tests/services/freight_rpa/test_report_queries.py 与
|
||||
test_import_boundary.py 锁定)。
|
||||
"""
|
||||
|
||||
from app.services.freight_rpa.reports.facts import REPORT_KINDS, ReportFact, require_report_kind
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
InboundConfigView,
|
||||
InboundFileView,
|
||||
OnhandConfigView,
|
||||
SiteView,
|
||||
clear_inbound_parse_failure,
|
||||
get_inbound_config,
|
||||
get_onhand_config,
|
||||
get_site,
|
||||
latest_usable_inbound_file,
|
||||
mark_inbound_parse_failure,
|
||||
read_inbound_file_bytes,
|
||||
usable_inbound_file_condition,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'REPORT_KINDS',
|
||||
'InboundConfigView',
|
||||
'InboundFileView',
|
||||
'OnhandConfigView',
|
||||
'ReportFact',
|
||||
'SiteView',
|
||||
'clear_inbound_parse_failure',
|
||||
'get_inbound_config',
|
||||
'get_onhand_config',
|
||||
'get_site',
|
||||
'latest_usable_inbound_file',
|
||||
'mark_inbound_parse_failure',
|
||||
'read_inbound_file_bytes',
|
||||
'require_report_kind',
|
||||
'usable_inbound_file_condition',
|
||||
]
|
||||
@@ -0,0 +1,78 @@
|
||||
"""freight_rpa/reports/dispatch.py
|
||||
|
||||
用途:报表事实(ReportFact)处理函数注册表与分发缝——RPA 回调「先 commit
|
||||
终态、再投递事实」的第二段分发(批次 B Task 6)。
|
||||
依赖:app.core.errors.AppError、freight_rpa.reports.facts(ReportFact、
|
||||
require_report_kind)。
|
||||
逻辑:组合根(Task 7 的 shipping_notice.rpa_sinks.register_inbound_sinks /
|
||||
register_onhand_sinks 等)在应用启动时调用 register_report_handler 注入各
|
||||
kind 的业务处理函数;归档入口(如 freight_rpa.inbound.report_archive.
|
||||
ingest_inbound_callback)在每个终态 db.session.commit() 之后调用
|
||||
dispatch_report_fact。kind 未注册时显式 404(FREIGHT_RPA.
|
||||
SINK_NOT_REGISTERED,与 common.callback_sinks.dispatch_sink 同码),
|
||||
绝不静默吞事实;处理函数异常原样向外抛(供 Worker/上层重试整笔回调)。
|
||||
本模块不 commit、不 rollback。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
|
||||
|
||||
# 报表事实处理函数契约:接收单个 ReportFact,返回 None;
|
||||
# 异常由调用方外抛重试,处理函数内部禁止自行吞异常。
|
||||
Handler = Callable[[ReportFact], None]
|
||||
|
||||
# kind → 处理函数注册表(模块级单例;同 kind 重复注册为覆盖)。
|
||||
_REPORT_HANDLERS: dict[str, Handler] = {}
|
||||
|
||||
|
||||
def register_report_handler(report_kind: str, handler: Handler) -> None:
|
||||
"""
|
||||
注册一个报表事实处理函数(由组合根在应用启动时调用)。
|
||||
|
||||
【AI 触发时机】:组合根装配(Task 7 的 register_inbound_sinks /
|
||||
register_onhand_sinks)时调用;测试直接调用注入临时处理函数。
|
||||
核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound /
|
||||
outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。
|
||||
Args:
|
||||
report_kind: 报表种类字符串(必须在 REPORT_KINDS 白名单内)。
|
||||
handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用,
|
||||
不校验其内部行为。
|
||||
Raises:
|
||||
ValidationError: report_kind 不在白名单(code=SHIPPING.RECEIPT_CALLBACK_INVALID)。
|
||||
"""
|
||||
kind = require_report_kind(report_kind)
|
||||
_REPORT_HANDLERS[kind] = handler
|
||||
|
||||
|
||||
def dispatch_report_fact(fact: ReportFact) -> None:
|
||||
"""
|
||||
把已随终态 commit 的报表事实投递给对应 kind 的处理函数。
|
||||
|
||||
【AI 触发时机】:归档入口(如 ingest_inbound_callback)在每个终态
|
||||
db.session.commit() 之后调用;禁止用于 commit 之前的路径(非法载荷 /
|
||||
单元不存在 / 落库失败均不得投递)。
|
||||
核心逻辑:kind 经 require_report_kind 校验后查注册表;命中即调用处理函数,
|
||||
其异常原样向外抛(不包日志、不吞);未注册抛
|
||||
AppError(code='FREIGHT_RPA.SINK_NOT_REGISTERED', http_status=404)。
|
||||
本函数不 commit、不 rollback。
|
||||
Args:
|
||||
fact: 终态已落库后构造好的报表事实(report_kind/source_code/file_id/
|
||||
sha256/ok/error_code/error_message)。
|
||||
Raises:
|
||||
ValidationError: fact.report_kind 不在白名单。
|
||||
AppError: kind 未注册处理函数(404;归档终态已提交不回滚,
|
||||
Worker 重试整笔回调即可补投递)。
|
||||
"""
|
||||
kind = require_report_kind(fact.report_kind)
|
||||
handler = _REPORT_HANDLERS.get(kind)
|
||||
if handler is None:
|
||||
raise AppError(
|
||||
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
|
||||
message=f'No report handler registered for kind: {kind}',
|
||||
http_status=404,
|
||||
)
|
||||
handler(fact)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""freight_rpa/reports/facts.py
|
||||
|
||||
用途:定义跨域报表「事实」的传输契约——report kind 白名单与 ReportFact。
|
||||
依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。
|
||||
逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作;
|
||||
report kind 只认 onhand / inbound / outbound,非法值抛
|
||||
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),
|
||||
与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。
|
||||
本模块不 import shipping_notice / in_transit_transfer。
|
||||
【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递
|
||||
必从单元行回填,供消费方处理函数精确定位本次回调收尾的执行单元。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 【AI 触发时机】AI 或调用方在构造 ReportFact / 分发报表回调前必须先用
|
||||
# require_report_kind 归一化校验 kind;白名单之外的取值一律拒绝。
|
||||
REPORT_KINDS = ('onhand', 'inbound', 'outbound')
|
||||
|
||||
# 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码,
|
||||
# 避免为同一类入参错误分裂出多个近义 code。
|
||||
_INVALID_KIND_ERROR_CODE = 'SHIPPING.RECEIPT_CALLBACK_INVALID'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReportFact:
|
||||
"""一份回报表的事实行(跨域只读传输对象)。
|
||||
|
||||
用途:RPA 回调归档后,由 freight_rpa 域产生、发货/调拨域消费的最小事实快照;
|
||||
ok=False 时 error_code/error_message 描述失败原因。
|
||||
约束:frozen 不可变;file_id/sha256 允许 None(抓取失败时无产物可指);
|
||||
unit_run_id 为归档入口回填的执行单元主键(Task 7 修复轮 2 起每次投递
|
||||
必带——处理函数据此精确定位「本次回调收尾的单元」,禁止按来源猜最新),
|
||||
允许 None 仅为兼容手工构造事实的旧调用方,dispatch 产线恒非空。
|
||||
"""
|
||||
|
||||
report_kind: str
|
||||
source_code: str
|
||||
file_id: int | None
|
||||
sha256: str | None
|
||||
ok: bool
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
unit_run_id: int | None = None
|
||||
|
||||
|
||||
def require_report_kind(value: str) -> str:
|
||||
"""校验并原样返回合法的 report kind。
|
||||
|
||||
用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。
|
||||
核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛
|
||||
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),fail-closed。
|
||||
|
||||
Args:
|
||||
value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。
|
||||
Returns:
|
||||
原样返回通过校验的 value(不含默认值/归一化,调用方以返回值为准)。
|
||||
Raises:
|
||||
ValidationError: value 不在白名单内(HTTP 400,不可重试)。
|
||||
"""
|
||||
if value not in REPORT_KINDS:
|
||||
raise ValidationError(
|
||||
f"Unsupported report kind: {value!r}",
|
||||
code=_INVALID_KIND_ERROR_CODE,
|
||||
details={'report_kind': value, 'allowed': list(REPORT_KINDS)},
|
||||
)
|
||||
return value
|
||||
@@ -0,0 +1,599 @@
|
||||
"""freight_rpa/reports/queries.py
|
||||
|
||||
用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+
|
||||
解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露
|
||||
freight_rpa 报表事实(站点、登录连接、在手/入站报表配置、入站解析方案、
|
||||
入站归档文件),使消费方不再直接 import freight_rpa 模型表。
|
||||
依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig /
|
||||
FreightRpaInboundReportConfig / FreightRpaInboundReportFile;登录连接
|
||||
(RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、
|
||||
app.core.errors(NotFoundError)、
|
||||
file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。
|
||||
逻辑:【禁止】import app.services.shipping_notice 或 app.services.in_transit_transfer
|
||||
——方向只能反过来(门禁模块阶段 B Task 4 起引用本模块的过滤表达式)。
|
||||
usable / expired_inbound_file_condition 是入站归档文件「可用/失效」过滤
|
||||
表达式的唯一权威(自 in_transit_transfer/inbound_file_gate.py 迁移,
|
||||
两条件同核 _fresh_and_retention_valid 推导,规则文本只此一份):可用 =
|
||||
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 +
|
||||
未过期(archive_expires_at 为空视为长期有效或晚于当前时刻);失效 =
|
||||
未删除 且 核心不成立。业务日窗口换算(date_policy.business_date_utc_window
|
||||
的数学)以私有 helper 内联在本文件,就是为了不 import in_transit_transfer
|
||||
(import 禁令)而保持口径逐位一致。
|
||||
【阶段 B Task 4】站点视图补主键/连接绑定/仓库识别方式与入站配置视图补
|
||||
config_id/config_version;新增登录连接(get_rpa_login_profile)、入站解析
|
||||
方案(get_inbound_parsing_profile)、失效文件存在性(has_expired_inbound_
|
||||
file)、重建通道归档清单(list_reparseable_inbound_files)、入站可用站点
|
||||
编码清单(list_inbound_configured_source_codes)——供 in_transit_transfer
|
||||
收敛为「只按 source_code / file_id 读取」的只读函数消费面。
|
||||
mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import ColumnElement, and_, not_, or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaSource,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
# 解析失败分层三列的截断上限,对齐列宽(String(64) / Text≈2000),
|
||||
# 防止上游超长错误信息把写入顶爆。
|
||||
_PARSE_ERROR_CODE_MAX = 64
|
||||
_PARSE_ERROR_MESSAGE_MAX = 2000
|
||||
|
||||
# 业务时区固定 Asia/Shanghai(与 in_transit_transfer.date_policy 同值;本包内
|
||||
# 复制而非 import,见文件头 import 禁令)。
|
||||
_SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
|
||||
_UTC_TZ = ZoneInfo("UTC")
|
||||
|
||||
|
||||
def _business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
|
||||
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
||||
|
||||
自 in_transit_transfer/date_policy.business_date_utc_window 逐位内联(阶段 B
|
||||
Task 3 修复轮 1):数据库统一存 naive UTC,直接取 .date() 与业务日比较会
|
||||
漂移 8 小时,必须先换算窗口再比较;不能 import date_policy,故复制其数学
|
||||
并保持口径一致(此处内联即唯一权威,门禁模块后续引用本包)。
|
||||
|
||||
Args:
|
||||
now: 可选时刻;naive 按 UTC 兼容处理(与 date_policy 口径一致),
|
||||
缺省取当前 Asia/Shanghai 时刻。
|
||||
Returns:
|
||||
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(_SHANGHAI_TZ)
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=_UTC_TZ)
|
||||
sh_now = now.astimezone(_SHANGHAI_TZ)
|
||||
start_utc = (
|
||||
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=_SHANGHAI_TZ)
|
||||
.astimezone(_UTC_TZ)
|
||||
.replace(tzinfo=None)
|
||||
)
|
||||
return start_utc, start_utc + timedelta(hours=24)
|
||||
|
||||
|
||||
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
|
||||
"""新鲜度 + 保留期核心条件(不含删除态;可用/失效两条件同核推导,规则文本只此一份)。"""
|
||||
window_start, window_end = _business_date_utc_window(now)
|
||||
return and_(
|
||||
FreightRpaInboundReportFile.created_at >= window_start,
|
||||
FreightRpaInboundReportFile.created_at < window_end,
|
||||
or_(
|
||||
FreightRpaInboundReportFile.archive_expires_at.is_(None),
|
||||
FreightRpaInboundReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「当前可用的入站归档文件」SQL 条件(唯一权威,供门禁模块引用)。
|
||||
|
||||
判定(与 in_transit_transfer/inbound_file_gate 现行口径逐位一致):
|
||||
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
|
||||
(created_at ∈ 业务日 UTC [窗口起, 窗口止) 窗口,naive UTC 存储)+
|
||||
未过期(archive_expires_at 为空视为长期有效,否则须晚于判定时刻)。
|
||||
本表达式全量自 inbound_file_gate.py 复制(阶段 B Task 3),此后以此为单一
|
||||
事实来源,门禁模块改为引用本函数(禁止反向 import 出现环)。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
|
||||
_fresh_and_retention_valid(now),
|
||||
)
|
||||
|
||||
|
||||
def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
|
||||
|
||||
判定:未删除(archive_deleted_at 为空)且 新鲜度+保留期核心不成立
|
||||
(保留期已到 或 非当天业务日抓取)——与可用条件同核(_fresh_and_retention_valid)
|
||||
推导,口径只存在一处。阶段 B Task 4 自 in_transit_transfer/inbound_file_gate
|
||||
迁移至此(语义逐位一致),此后以本文件为唯一权威;命中即提示重试重抓,
|
||||
不报 ready,也不等待保留期清理任务落位。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
|
||||
not_(_fresh_and_retention_valid(now)),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SiteView:
|
||||
"""库存站点的只读视图:连接与模板绑定、启停状态(不含报表定义,s18 起)。
|
||||
|
||||
阶段 B Task 4 增补三字段(调拨域路由/触发按 source_code 读站点主键与识别
|
||||
方式时不再引用站点模型):source_id(站点主键,供映射查询等 FK 路径)、
|
||||
rpa_profile_id(登录连接绑定)、warehouse_resolution_mode(仓库识别方式)。
|
||||
"""
|
||||
|
||||
source_code: str
|
||||
display_name: str
|
||||
connector_type: str
|
||||
excel_template_id: int | None
|
||||
enabled: bool
|
||||
source_id: int = 0
|
||||
rpa_profile_id: int = 0
|
||||
warehouse_resolution_mode: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RpaLoginProfileView:
|
||||
"""RPA 登录连接只读视图(freight_rpa_profiles 行)。
|
||||
|
||||
凭据密文原样透传(username/password_ciphertext)——仅限投递 RPA Worker
|
||||
trigger,禁止出现在任何日志/接口响应中。
|
||||
"""
|
||||
|
||||
profile_id: int
|
||||
profile_code: str
|
||||
login_url: str
|
||||
login_config: dict
|
||||
username_ciphertext: str | None
|
||||
password_ciphertext: str | None
|
||||
enabled: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OnhandConfigView:
|
||||
"""在手报表配置只读视图(freight_rpa_onhand_report_configs 行)。"""
|
||||
|
||||
report_path_json: dict
|
||||
query_parameters_json: list
|
||||
parsing_profile_id: int | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InboundConfigView:
|
||||
"""入站报表配置只读视图(freight_rpa_inbound_report_configs 行),与在手同构。
|
||||
|
||||
阶段 B Task 4 增补 config_id / config_version(调拨入站触发落可审计单元行
|
||||
快照需要配置行主键与版本,不再引用配置模型)。
|
||||
"""
|
||||
|
||||
report_path_json: dict
|
||||
query_parameters_json: list
|
||||
parsing_profile_id: int | None
|
||||
config_id: int = 0
|
||||
config_version: int = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InboundProfileView:
|
||||
"""入站解析方案只读视图(freight_rpa_parsing_profiles 行)。
|
||||
|
||||
定义(definition_json:field_mapping / sheet_name / header_row_index 等)
|
||||
原样透出;status/purpose 的 published-inbound 门禁决策归调用方按场景
|
||||
自行 fail-closed(运行期取数、重建、触发守卫口径一致,见各自消费方)。
|
||||
"""
|
||||
|
||||
profile_id: int
|
||||
profile_code: str
|
||||
version: int
|
||||
status: str
|
||||
purpose: str
|
||||
definition_json: dict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InboundFileView:
|
||||
"""入站归档文件的只读视图;source_code 取自其所属执行单元行。
|
||||
|
||||
parse_failed_at 为解析失败分层的事实列(None=未失败/已清除)——阶段 B
|
||||
Task 4 增补,供来源状态投影与证据同步判断 parse_failed,免除调用方二次查询。
|
||||
"""
|
||||
|
||||
file_id: int
|
||||
source_code: str
|
||||
sha256: str
|
||||
storage_key: str
|
||||
original_filename: str
|
||||
created_at: datetime
|
||||
parse_failed_at: datetime | None = None
|
||||
|
||||
|
||||
def get_site(source_code: str) -> SiteView | None:
|
||||
"""按 source_code 返回库存站点只读视图。
|
||||
|
||||
用途:调拨/发货域读取站点连接、模板绑定与启停(例如入站触发预检)时调用,
|
||||
替代直接查询 FreightRpaSource。
|
||||
核心逻辑:按 source_code 精确查第一条;命中即映射为 SiteView(frozen),否则 None。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码(大小写敏感,禁止传入模糊值)。
|
||||
Returns:
|
||||
SiteView;站点不存在返回 None(调用方自行 fail-closed)。
|
||||
"""
|
||||
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
|
||||
if site is None:
|
||||
return None
|
||||
return SiteView(
|
||||
source_code=site.source_code,
|
||||
display_name=site.display_name,
|
||||
connector_type=site.connector_type,
|
||||
excel_template_id=site.excel_template_id,
|
||||
enabled=bool(site.enabled),
|
||||
# [阶段 B Task 4] 调拨域(路由解析/入站触发)所需站点主键与识别方式。
|
||||
source_id=site.id,
|
||||
rpa_profile_id=site.rpa_profile_id,
|
||||
warehouse_resolution_mode=str(site.warehouse_resolution_mode or ""),
|
||||
)
|
||||
|
||||
|
||||
def get_onhand_config(source_code: str) -> OnhandConfigView | None:
|
||||
"""按 source_code 返回在手报表配置只读视图。
|
||||
|
||||
用途:RPA 触发读路径取报表路径、查询条件与解析方案绑定(s18 起配置挂在
|
||||
freight_rpa_onhand_report_configs,站点行不再承载这三列)。
|
||||
核心逻辑:join 站点表按 source_code 查配置行,命中即映射视图;站点或配置行
|
||||
缺失一律返回 None(fail-closed,调用方判 None 后阻断触发)。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码。
|
||||
Returns:
|
||||
OnhandConfigView;站点无配置返回 None。
|
||||
"""
|
||||
config = (
|
||||
FreightRpaOnhandReportConfig.query
|
||||
.join(FreightRpaSource, FreightRpaOnhandReportConfig.source_id == FreightRpaSource.id)
|
||||
.filter(FreightRpaSource.source_code == source_code)
|
||||
.first()
|
||||
)
|
||||
if config is None:
|
||||
return None
|
||||
return OnhandConfigView(
|
||||
report_path_json=dict(config.report_path_json or {}),
|
||||
query_parameters_json=list(config.query_parameters_json or []),
|
||||
parsing_profile_id=config.parsing_profile_id,
|
||||
)
|
||||
|
||||
|
||||
def get_inbound_config(source_code: str) -> InboundConfigView | None:
|
||||
"""按 source_code 返回入站报表配置只读视图(与在手配置同构)。
|
||||
|
||||
用途:调拨入站触发读路径取收料报表定义;收料不设独立启停,是否运行由站点
|
||||
enabled 与本配置行是否存在决定。
|
||||
核心逻辑:join 站点表按 source_code 查 freight_rpa_inbound_report_configs 行,
|
||||
命中即映射视图;缺失返回 None。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码。
|
||||
Returns:
|
||||
InboundConfigView;站点或配置不存在返回 None。
|
||||
"""
|
||||
config = (
|
||||
FreightRpaInboundReportConfig.query
|
||||
.join(FreightRpaSource, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id)
|
||||
.filter(FreightRpaSource.source_code == source_code)
|
||||
.first()
|
||||
)
|
||||
if config is None:
|
||||
return None
|
||||
return InboundConfigView(
|
||||
report_path_json=dict(config.report_path_json or {}),
|
||||
query_parameters_json=list(config.query_parameters_json or []),
|
||||
parsing_profile_id=config.parsing_profile_id,
|
||||
# [阶段 B Task 4] 触发快照(config_snapshot)所需的配置行主键与版本。
|
||||
config_id=config.id,
|
||||
config_version=int(config.config_version or 1),
|
||||
)
|
||||
|
||||
|
||||
def get_rpa_login_profile(source_code: str) -> RpaLoginProfileView | None:
|
||||
"""按 source_code 返回站点绑定的 RPA 登录连接只读视图。
|
||||
|
||||
用途:调拨入站 RPA 触发装配 trigger unit(登录页、凭据密文信封、连接编码)
|
||||
时调用,替代直接查询站点与其登录连接模型。
|
||||
核心逻辑:按 source_code 取站点行再走 rpa_profile 关系;站点或连接缺失一律
|
||||
返回 None(fail-closed,调用方判 None 后阻断触发)。凭据密文
|
||||
原样透出(仅限投递 Worker trigger,调用方禁止落日志/响应)。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码(大小写敏感)。
|
||||
Returns:
|
||||
RpaLoginProfileView;站点或连接不存在返回 None。
|
||||
"""
|
||||
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
|
||||
profile = site.rpa_profile if site is not None else None
|
||||
if profile is None:
|
||||
return None
|
||||
return RpaLoginProfileView(
|
||||
profile_id=profile.id,
|
||||
profile_code=profile.profile_code,
|
||||
login_url=profile.login_url,
|
||||
login_config=dict(profile.login_config_json or {}),
|
||||
username_ciphertext=profile.username_ciphertext,
|
||||
password_ciphertext=profile.password_ciphertext,
|
||||
enabled=bool(profile.enabled),
|
||||
)
|
||||
|
||||
|
||||
def get_inbound_parsing_profile(source_code: str) -> InboundProfileView | None:
|
||||
"""按 source_code 返回入站配置绑定的解析方案只读视图。
|
||||
|
||||
用途:调拨运行期取数(movement_file_repository)、清空重建
|
||||
(backlog_reparse_service)与 RPA 触发守卫(deps)读取入站文件解析
|
||||
规则定义时调用,替代直接持有配置模型关系。
|
||||
核心逻辑:站点 → 入站配置 → 配置绑定的解析方案,任一环节缺失返回 None;
|
||||
不校验 status/purpose(调用方按场景自行 fail-closed,见
|
||||
InboundProfileView docstring)。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码。
|
||||
Returns:
|
||||
InboundProfileView;无配置、未绑定或方案行缺失返回 None。
|
||||
"""
|
||||
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
|
||||
config = site.inbound_report_config if site is not None else None
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if profile is None:
|
||||
return None
|
||||
return InboundProfileView(
|
||||
profile_id=profile.id,
|
||||
profile_code=profile.profile_code,
|
||||
version=int(profile.version or 1),
|
||||
status=profile.status,
|
||||
purpose=profile.purpose,
|
||||
definition_json=dict(profile.definition_json or {}),
|
||||
)
|
||||
|
||||
|
||||
def _inbound_file_view(report: FreightRpaInboundReportFile) -> InboundFileView:
|
||||
"""把归档文件 ORM 行映射为冻结只读视图(本模块内唯一映射点,字段增补只改此处)。"""
|
||||
return InboundFileView(
|
||||
file_id=report.id,
|
||||
source_code=report.unit_run.source_code,
|
||||
sha256=report.sha256,
|
||||
storage_key=report.storage_key,
|
||||
original_filename=report.original_filename,
|
||||
created_at=report.created_at,
|
||||
parse_failed_at=report.parse_failed_at,
|
||||
)
|
||||
|
||||
|
||||
def has_expired_inbound_file(source_code: str, *, now: datetime | None = None) -> bool:
|
||||
"""返回某来源是否存在「未删除但已失效」的入站归档文件(expired 投影依据)。
|
||||
|
||||
用途:调拨来源状态投影(source_file_status.resolve_source_file_status)判断
|
||||
该来源是否需要因文件失效(隔日旧文件 / 保留期已到但清理未落位)提示
|
||||
重抓时调用;只读不写,判定与 usable/expired 条件同核不漂移。
|
||||
|
||||
核心逻辑:经执行单元行的 source_code 过滤 + expired_inbound_file_condition,
|
||||
存在任一命中即 True(纯存在性判断,不取列数据不排序)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(写在执行单元行上)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
bool:存在失效但未清理的归档文件 → True;否则 False。
|
||||
"""
|
||||
expired = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return expired is not None
|
||||
|
||||
|
||||
def list_reparseable_inbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]:
|
||||
"""维护通道:列出某来源全部可重建入站归档(未删除 + 未过保留期),不设当日门禁。
|
||||
|
||||
用途:调拨待匹配桶「清空并重新解析」(movement_file_repository →
|
||||
backlog_reparse_service,spec §6)按来源取重建清单时调用。
|
||||
运行期取数(latest_usable_inbound_file)的当日 fail-closed 门禁是
|
||||
运行期语义;本方法是显式的历史重建通道(spec §6),两者不得混用。
|
||||
|
||||
核心逻辑:join 路径与 latest_usable_inbound_file 同款(经执行单元行
|
||||
source_code 过滤),但【刻意无当日门禁】——重建对象正是历史
|
||||
归档;保留期口径一致(archive_expires_at 为空视为长期有效)、
|
||||
未删除(archive_deleted_at 为空)。按 created_at/id 升序返回
|
||||
(重建必须按归档时间序重落,保证幂等重放顺序确定)。只读查询,
|
||||
不触碰对象存储字节(字节由调用方按需经 read_inbound_file_bytes 取)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(经执行单元行 source_code 关联)。
|
||||
now: 保留期判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
InboundFileView 列表(created_at 升序;无可重建归档为空表)。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
reports = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
|
||||
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
|
||||
or_(
|
||||
FreightRpaInboundReportFile.archive_expires_at.is_(None),
|
||||
FreightRpaInboundReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
.order_by(FreightRpaInboundReportFile.created_at.asc(), FreightRpaInboundReportFile.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [_inbound_file_view(report) for report in reports]
|
||||
|
||||
|
||||
def list_inbound_configured_source_codes() -> list[str]:
|
||||
"""列出已配置入站报表的启用站点编码(调拨排程缺省执行范围)。
|
||||
|
||||
用途:在途自动调拨排程 source_codes 留空时的缺省范围
|
||||
(inbound_trigger_service.list_inbound_capable_source_codes 委托本函数)
|
||||
——入站文件只能来自已配置入站报表的启用站点。
|
||||
核心逻辑:站点 join 入站配置行、仅启用站点、按 source_code 排序;只读查询。
|
||||
|
||||
Returns:
|
||||
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
|
||||
"""
|
||||
rows = db.session.query(FreightRpaSource.source_code).join(
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaInboundReportConfig.source_id == FreightRpaSource.id,
|
||||
).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all()
|
||||
return [str(code) for (code,) in rows]
|
||||
|
||||
|
||||
def latest_usable_inbound_file(
|
||||
source_code: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> InboundFileView | None:
|
||||
"""返回某来源当前「可用」的入站归档文件只读视图,最新优先。
|
||||
|
||||
用途:调拨匹配取文件、证据下载等读路径调用;口径与匹配链路原有
|
||||
_latest_usable_report_file 相同——经执行单元行的 source_code 过滤,
|
||||
可用门禁(未删除 + 当天业务日抓取 + 未过期,见
|
||||
usable_inbound_file_condition),按 created_at/id 倒序取第一条。
|
||||
只读不写、不 flush 不 commit。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(写在 FreightRpaInboundUnitRun.source_code 上)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
仅供测试冻结窗口或调用方显式指定业务时刻,生产调用缺省即可。
|
||||
Returns:
|
||||
InboundFileView;来源无可用文件(未抓取/已失效/已清理)返回 None。
|
||||
"""
|
||||
report = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
if report is None:
|
||||
return None
|
||||
return _inbound_file_view(report)
|
||||
|
||||
|
||||
def read_inbound_file_bytes(file_id: int) -> bytes:
|
||||
"""按 file_id 读取入站归档文件的对象字节。
|
||||
|
||||
用途:调拨/发货域需要文件原文(匹配重解析、证据下载)时调用,替代各自
|
||||
持有模型 + file_asset_storage 的双跳查询。
|
||||
核心逻辑:[STEP 1] 按主键取 FreightRpaInboundReportFile,缺失抛 NotFoundError
|
||||
(fail-closed);[STEP 2] 以文件的 storage_key 调
|
||||
file_asset_storage.get_bytes 读取并返回字节(不含元数据)。
|
||||
|
||||
Args:
|
||||
file_id: 归档文件主键(int;禁止传入非整数 ID)。
|
||||
Returns:
|
||||
文件完整字节内容。
|
||||
Raises:
|
||||
NotFoundError: file_id 对应的归档文件不存在(HTTP 404)。
|
||||
"""
|
||||
report = db.session.get(FreightRpaInboundReportFile, file_id)
|
||||
if report is None:
|
||||
raise NotFoundError(
|
||||
f"Inbound report file not found: {file_id}",
|
||||
details={'file_id': file_id},
|
||||
)
|
||||
return file_asset_storage.get_bytes(report.storage_key)
|
||||
|
||||
|
||||
def mark_inbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None:
|
||||
"""标记一份入站归档文件解析失败(写入解析失败三分层列)。
|
||||
|
||||
用途:入站归档文件解析(schema/字段校验)失败时把失败事实落到文件上,
|
||||
使来源状态投影为 parse_failed、阻止下游当作 ready 使用。
|
||||
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError;[STEP 2] 只更新
|
||||
parse_failed_at(当前 UTC)/ parse_error_code(截断 64)/
|
||||
parse_error_message(截断 2000)三列;[STEP 3] db.session.flush()
|
||||
使同事务内投影立即可见。【不 commit】——调用方处于自己的事务,
|
||||
提交/回滚归属调用方,service 层禁止越权提交。
|
||||
|
||||
Args:
|
||||
file_id: 归档文件主键(须已入库)。
|
||||
error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。
|
||||
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
|
||||
Returns:
|
||||
None。失败标记随调用方事务落库。
|
||||
Raises:
|
||||
NotFoundError: file_id 对应的归档文件不存在。
|
||||
"""
|
||||
report = db.session.get(FreightRpaInboundReportFile, file_id)
|
||||
if report is None:
|
||||
raise NotFoundError(
|
||||
f"Inbound report file not found: {file_id}",
|
||||
details={'file_id': file_id},
|
||||
)
|
||||
report.parse_failed_at = datetime.utcnow()
|
||||
report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX]
|
||||
report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX]
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def clear_inbound_parse_failure(file_id: int) -> None:
|
||||
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
|
||||
|
||||
用途:同一文件重新解析成功、或确认可恢复后调用;不要在文件已被
|
||||
清理/过期后调用(无业务意义)。
|
||||
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError(与其他按 id 操作
|
||||
同口径,避免静默吞掉错配);[STEP 2] 将 parse_failed_at /
|
||||
parse_error_code / parse_error_message 置 None(三者全空即未失败的
|
||||
约定态);[STEP 3] flush。【不 commit】——事务归属调用方。
|
||||
|
||||
Args:
|
||||
file_id: 归档文件主键(须已入库)。
|
||||
Returns:
|
||||
None。清除随调用方事务落库。
|
||||
Raises:
|
||||
NotFoundError: file_id 对应的归档文件不存在。
|
||||
"""
|
||||
report = db.session.get(FreightRpaInboundReportFile, file_id)
|
||||
if report is None:
|
||||
raise NotFoundError(
|
||||
f"Inbound report file not found: {file_id}",
|
||||
details={'file_id': file_id},
|
||||
)
|
||||
report.parse_failed_at = None
|
||||
report.parse_error_code = None
|
||||
report.parse_error_message = None
|
||||
db.session.flush()
|
||||
Reference in new issue
Block a user