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

@@ -8,7 +8,8 @@
(解析+组装单一口径)与 _detect_natural_key_collapses/_natural_key_collapse_event
(档自然键坍缩守卫与运行期同口径复用)、ledger_sync(sync_ledger_rows /
RECORD_KIND_INBOUND / FileMeta)、matching_service._effective_occupancy_filter
(占用排除口径,只读引用)、file_asset_storage、audit。
(占用排除口径,只读引用)、freight_rpa.reports.queries(站点与入站解析方案
只读入口——阶段 B Task 4 收敛)、file_asset_storage、audit。
逻辑:桶数据 100% 可由 MinIO 归档重建(原件长期保留 + 档行 sheet/row_no 溯源),
清空不是破坏性操作而是「从证据重建」。安全不变量:先全量预解析入内存,
任一归档解析失败 → 整体中止 AppError(TRANSFER.REPARSE_PARSE_FAILED),
@@ -42,8 +43,12 @@ from sqlalchemy import func
from app import db
from app.core.errors import AppError
from app.models import ShippingInventorySource, TransferInvoiceItem, TransferMovementLedger
from app.models import TransferInvoiceItem, TransferMovementLedger
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.reports.queries import (
get_inbound_parsing_profile,
get_site,
)
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.evidence_sync import (
_detect_natural_key_collapses,
@@ -100,24 +105,23 @@ class ReparseOutcome:
def _load_published_inbound_profile(source_code: str):
"""加载来源当前绑定的「已发布 inbound」解析规则(与运行期取数同口径)。
核心逻辑:来源(enabled)→ 收料配置 → parsing_profile,须 published 且
核心逻辑:来源(enabled)→ 入站配置 → parsing_profile,须 published 且
purpose='inbound'——与 latest_ready_file 的规则门禁一致,防止重建用了
运行期不会使用的规则口径。只读查询。
【阶段 B Task 4】读取改经 freight_rpa.reports.queries 只读入口
(get_site / get_inbound_parsing_profile),不再引用站点/报表模型;返回
InboundProfileView(code/version/definition 消费面不变)。
Args:
source_code: 来源实例编码。
Returns:
ShippingInventoryParsingProfile;无启用来源/无收料配置/规则缺失或
InboundProfileView;无启用来源/无入站配置/规则缺失或
非 published inbound 时返回 None(=无重建通道)。
"""
source = ShippingInventorySource.query.filter_by(
source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
return None
config = source.receipt_report_config
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != "published" or profile.purpose != "inbound":
return None
return profile
@@ -3,7 +3,7 @@
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:movement_file_repository / capability_client / matching_service / models / Flask config。
逻辑:默认实现直接接线真实链路 —— 入站文件行读取走 movement_file_repository
(复用 ShippingReceiptReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由
(复用 ShippingInboundReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed);
策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_
@@ -18,7 +18,12 @@ from typing import Any
from flask import current_app
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.models import FreightRpaOnhandExternalMapping
from app.services.freight_rpa.reports.queries import (
get_inbound_config,
get_inbound_parsing_profile,
get_site,
)
from app.services.in_transit_transfer.capability_client import CapabilityClient
from app.services.in_transit_transfer.movement_file_repository import ShippingInboundFileRepository
from app.services.in_transit_transfer.matching_service import (
@@ -47,6 +52,11 @@ class DefaultRouteResolver:
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
【阶段 B Task 4】站点行(主键/启停/识别方式)读取改经
freight_rpa.reports.queries.get_site 只读视图,不再引用站点模型;
外部仓库映射仍为调拨域自有表(freight_rpa_onhand_external_mappings
不改归属,见计划 Global Constraints),按站点主键直查。
Args:
source_code: 来源实例编码(须启用)。
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
@@ -56,14 +66,14 @@ class DefaultRouteResolver:
Raises:
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
"""
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
raise RouteNotResolvedError(source_code=source_code)
mappings = ShippingInventoryExternalMapping.query.filter_by(
inventory_source_id=source.id, enabled=True,
mappings = FreightRpaOnhandExternalMapping.query.filter_by(
source_id=site.source_id, enabled=True,
).all()
selected = None
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
if site.warehouse_resolution_mode == 'inventory_match':
# [匹配] 入站仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
key = str(warehouse_code or '').strip().upper()
@@ -158,24 +168,24 @@ def get_transfer_dependencies() -> TransferDeps:
class _DefaultRpaTrigger:
"""默认入站 RPA 触发器:委托真实触发服务(trigger_inbound_rpa)。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/ShippingReceiptReportConfig 缺失或 trigger
真实链路 = 落单元行 + 原子写 trigger 文件;站点/入站配置缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
另在本类前置守卫: ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时
另在本类前置守卫:入站配置存在但未绑定已发布 inbound 解析规则时
直接返回 RPA_INBOUND_PROFILE_MISSING,不触发徒劳抓取。
【阶段 B Task 4】守卫读取改经 freight_rpa.reports.queries 只读入口
(get_site / get_inbound_config / get_inbound_parsing_profile)。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa
# [守卫] ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳:
# [守卫] 入站配置存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳:
# 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is not None:
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
site = get_site(source_code)
if site is not None and site.enabled:
config = get_inbound_config(source_code)
if config is not None:
profile = config.parsing_profile
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
return {'ok': False, 'error_code': 'RPA_INBOUND_PROFILE_MISSING'}
@@ -1,9 +1,13 @@
"""services/in_transit_transfer/evidence_sync.py
用途:入站证据同步——把来源最新可用入站文件(ShippingReceiptReport RPA 产物)解析并镜像落档(库存异动档
用途:入站证据同步——把来源最新可用入站文件(freight_rpa 入站 RPA 产物)解析并镜像落档(库存异动档
transfer_movement_ledger,主链路),一次解析、写档不写明细。
依赖:file_parser / ledger_sync / source_file_status / matching_service
(_latest_usable_report_file 复用)/ contracts / models / audit。
依赖:file_parser / ledger_sync / freight_rpa.reports.queries(最新可用归档视图
latest_usable_inbound_file 与解析失败标记 mark/clear——只读只写入口唯一权威)/
source_file_status(状态投影)/ contracts / audit。
【阶段 B Task 4】文件取数不再经 matching_service._latest_usable_report_file
(该函数已删除),改按 source_code 直调 freight_rpa.reports.queries;解析失败
标记改按 file_id 调 mark_inbound_parse_failure / clear_inbound_parse_failure。
逻辑:【2026-10-14 出生翻转(ADR 0001/D3/D4)】本模块不再写 transfer_invoice_items
——items 改为匹配创建时从档圈定(见 matching_service);落地产物=档行:
①按自然键查档不存在 → 插入(record_kind/溯源五列随行);
@@ -45,6 +49,11 @@ from decimal import Decimal
from typing import Any, Mapping
from app import db
from app.services.freight_rpa.reports.queries import (
clear_inbound_parse_failure,
latest_usable_inbound_file,
mark_inbound_parse_failure,
)
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.file_parser import (
@@ -57,11 +66,6 @@ from app.services.in_transit_transfer.ledger_sync import (
FileMeta,
sync_ledger_rows,
)
from app.services.in_transit_transfer.matching_service import _latest_usable_report_file
from app.services.in_transit_transfer.source_file_status import (
clear_inbound_parse_failure,
record_inbound_parse_failure,
)
# 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码),
# 表示「已出生/已重置、库存侧尚未核对」;禁用新状态值。出生翻转后该态出现在
@@ -318,13 +322,14 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
# [STEP 2] 幂等落档;ledger_sync 只 flush 不 commit(提交归调用方:桥自行
# commit,匹配/重查随主事务)。溯源文件 id:当前可用归档文件(Fake 仓库
# 测试场景/文件已清理时为 None,档事实留存不依赖文件存在)。
report = _latest_usable_report_file(source_code)
# 【阶段 B Task 4】文件身份改取 freight_rpa.reports.queries 只读视图(主键 file_id)。
file_view = latest_usable_inbound_file(source_code)
outcome = sync_ledger_rows(
source_code=source_code,
record_kind=RECORD_KIND_INBOUND,
parsed_rows=assembled,
file_meta=FileMeta(
source_file_id=report.id if report is not None else None,
source_file_id=file_view.file_id if file_view is not None else None,
file_version=ready.file_version,
file_sha256=ready.checksum,
),
@@ -365,9 +370,9 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
))
# [解析失败分层 2026-09-29] 同步成功 = 当前可用文件已成功解析:清除其解析
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。只 flush 不 commit,
# 提交归调用方。无可用 ORM 文件时为 no-op。
if report is not None and report.parse_failed_at is not None:
clear_inbound_parse_failure(report=report)
# 提交归调用方。无可用归档时为 no-op。
if file_view is not None and file_view.parse_failed_at is not None:
clear_inbound_parse_failure(file_view.file_id)
return result
@@ -375,8 +380,8 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
"""入站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
【AI 触发时机】:入站 RPA 回调 success 终态落文件后由
shipping_notice 域 ShippingReceiptReport 归档存储的桥函数调用——桥是记账
不是入站链路的正确性依赖,任何异常不得向 ShippingReceiptReport 归档主链路传播(B3:必须自行 commit)。
shipping_notice 域 ShippingInboundReport 归档存储的桥函数调用——桥是记账
不是入站链路的正确性依赖,任何异常不得向 ShippingInboundReport 归档主链路传播(B3:必须自行 commit)。
【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上;
丢失的落档由回调重试/来源「重试 RPA」入口(本地重解析)兜底
@@ -407,7 +412,7 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
return True
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
# [桥隔离] 为什么吞异常:桥是记账不是入站链路的正确性依赖,落档崩溃
# 绝不允许波及 ShippingReceiptReport 归档终态;丢失的落档由回调重试/人工重取兜底。
# 绝不允许波及 ShippingInboundReport 归档终态;丢失的落档由回调重试/人工重取兜底。
current_app.logger.warning(
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
db.session.rollback()
@@ -419,15 +424,15 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
# [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows
# 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。
# 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉,
# B3(任何异常不得向 ShippingReceiptReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。
# B3(任何异常不得向 ShippingInboundReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。
try:
code = getattr(exc, "code", None) or ""
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, MovementFileSchemaError):
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
report = _latest_usable_report_file(source_code)
if report is not None:
record_inbound_parse_failure(
report=report,
file_view = latest_usable_inbound_file(source_code)
if file_view is not None:
mark_inbound_parse_failure(
file_view.file_id,
error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID),
error_message=str(detail)[:2000],
)
@@ -1,7 +1,7 @@
"""在途调拨入站文件 Ready 复用与来源级 RPA 触发。
用途:按 (source_code, business_date, 入站解析规则绑定) 检查最新 ready 文件;
存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingReceiptReport RPA
存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingInboundReport RPA
产物,shipping_notice 域术语保留);存在活动 Source Job
时绑定已有任务,保证并发请求只触发一次抓取。
依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。
@@ -1,11 +1,15 @@
"""在途调拨入站回调桥。
用途:货代入站 RPA(入站证据 = ShippingReceiptReport RPA 产物,shipping_notice 域,术语保留)
用途:货代入站 RPA(入站证据 = ShippingInboundReport RPA 产物,shipping_notice 域,术语保留)
回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。
依赖:models(TransferSourceJob)、datetime。
逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作,
避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。
避免回调迟到误推进其他阶段任务。生产调用方为调拨侧报表事实处理函数
handle_inbound_report(Task 7,inbound_report_handler.py——归档终态 commit 后
经 dispatch_report_fact 调入;返回 None 时调用方跳过提交分支);回归测试桥
(inbound_report_storage._advance_transfer_source_job)仍走本函数。
SourceJob 状态为字符串常量(见 models)。
"""
from __future__ import annotations
@@ -1,70 +1,20 @@
"""在途调拨入站归档文件的可用性门禁(单一事实来源)。
"""在途调拨入站归档文件的可用性门禁(口径唯一,语义归 freight_rpa.reports 维护)。
用途:把「一份 ShippingReceiptReportFile(入站证据 = ShippingReceiptReport RPA 产物,
shipping_notice 域,术语保留)是否可用于调拨链路」的判定收敛为本模块,
供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、
入站文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
两函数同核推导,规则文本只存在一处。
用途:把「一份入站归档文件是否可用于调拨链路」的判定收敛为
freight_rpa/reports/queries 的权威实现,并向调拨域既有 import 路径
(api 下载、历史消费方)透传,防止口径漂移。
依赖:freight_rpa.reports.queries(usable / expired 过滤表达式的唯一权威)。
逻辑:【阶段 B Task 4】本模块不再自带表达式实现,自身不 import 任何
freight_rpa 报表模型;可用 = 未删除 + 当天(Asia/Shanghai 业务日)抓取
+ 未过保留期;已失效(expired)= 未删除 且 该核心不成立——两条件同核
推导,规则文本与业务日窗口换算见 queries.py(禁止反向 import 出现环)。
"""
from __future__ import annotations
from datetime import datetime
from app.services.freight_rpa.reports.queries import (
expired_inbound_file_condition,
usable_inbound_file_condition,
)
from sqlalchemy import ColumnElement, and_, not_, or_
from app.models import ShippingReceiptReportFile
from app.services.in_transit_transfer.date_policy import business_date_utc_window
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
"""新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。"""
window_start, window_end = business_date_utc_window(now)
return and_(
ShippingReceiptReportFile.created_at >= window_start,
ShippingReceiptReportFile.created_at < window_end,
or_(
ShippingReceiptReportFile.archive_expires_at.is_(None),
ShippingReceiptReportFile.archive_expires_at > now,
),
)
def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「当前可用的入站归档文件」SQL 条件。
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
+ 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
ShippingReceiptReportFile.archive_deleted_at.is_(None),
_fresh_and_retention_valid(now),
)
def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
ShippingReceiptReportFile.archive_deleted_at.is_(None),
not_(_fresh_and_retention_valid(now)),
)
__all__ = ["expired_inbound_file_condition", "usable_inbound_file_condition"]
@@ -0,0 +1,134 @@
"""
services/in_transit_transfer/inbound_report_handler.py
用途:inbound 报表事实的调拨侧业务处理函数(阶段 B Task 7)——收料归档
终态 commit 后由 dispatch_report_fact 投递的 ReportFact 只在此推进
调拨自己的任务:TransferSourceJob 终态推进、调拨证据同步、收料排程收口。
依赖:app.db、app.models(FreightRpaInboundUnitRun——执行单元读取;报表文件/
配置模型禁止在本包引用,边界由 test_inbound_report_read_boundary 锁定)、
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)
注册为 'inbound' kind 处理函数;freight_rpa.inbound.report_archive.
ingest_inbound_callback 在每个终态 db.session.commit() 之后经
dispatch_report_fact 调入本函数。处理函数只改调拨自己的行;
【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚,
Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.core.errors import ValidationError
from app.models import FreightRpaInboundUnitRun
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
from app.services.in_transit_transfer.inbound_callback_bridge import (
advance_source_job_from_inbound_callback,
)
def handle_inbound_report(fact: ReportFact) -> None:
"""report_kind 必须是 inbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready;
ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。
(Task 7 契约 docstring 逐字保留如上;以下为补充说明。)
核心逻辑:
[STEP 1] kind 门禁(fail-closed);[STEP 2] 经桥推进等待中的来源任务(桥只改
status='waiting_rpa_callback' 的行,无等待行返回 None——「没有等待行则 return」
指调拨侧无任务行可改,第二次投递时该行已离开等待态,桥天然不重复推进);
[STEP 3] 桥只 flush 不 commit,推进结果必须在此提交(B3 持久性);[STEP 4]
success 事实触发调拨证据同步(与拆分前终态收尾同口径:按 ok 触发、不依赖
等待任务存在——独立收料批次无调拨任务也须把最新可用文件镜像落档;
桥内自吞异常并自行 commit,本处不包 try);[STEP 5] 精确定位「本次回调收尾的
执行单元」并回写收料排程进度、归集终态(finalize 函数住在 schedule 包——
freight_rpa 禁止 import 它,只能由本处理函数调用;「仍由该处理函数调用」= 拆分
前每笔终态回调后的收口行为保持不变;Task 7 修复轮 2 起定位依据为 fact.unit_run_id
——归档入口每次投递(含 failure/empty 与幂等重放)自单元行回填,success 与
failure 同一机制,绝不按来源/错误文本猜「最新单元」)。
【不捕获异常】任何一步失败原样外抛供 Worker 重试。
Args:
fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/
file_id/sha256/ok/error_code/error_message)。
Returns:
None(推进/同步/收口结果全部写库,不返回业务值)。
Raises:
ValidationError: report_kind 非 inbound(误注册/误分发,fail-closed)。
"""
# [STEP 1] kind 门禁:本函数只消费 inbound 事实(dispatch 已按 kind 路由,
# 此处防御性复核,防止误注册成其他 kind 的处理函数后静默错写调拨行)。
kind = require_report_kind(fact.report_kind)
if kind != 'inbound':
raise ValidationError(
f"handle_inbound_report only accepts inbound facts, got: {kind!r}",
code='SHIPPING.RECEIPT_CALLBACK_INVALID',
details={'report_kind': fact.report_kind},
)
# [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready(绑定
# 文件号/指纹);否则 → failed(带错误码/描述)。桥只改 waiting_rpa_callback 行;
# 无等待行返回 None(调拨侧无行可改,直接结束推进分支)。
if fact.ok and fact.file_id is not None:
advanced = advance_source_job_from_inbound_callback(
source_code=fact.source_code,
file_no=str(fact.file_id),
file_sha256=fact.sha256,
callback_ok=True,
)
else:
advanced = advance_source_job_from_inbound_callback(
source_code=fact.source_code,
callback_ok=False,
error_code=fact.error_code,
error_message=fact.error_message,
)
# [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交,否则请求结束回滚会
# 丢掉已推进的任务(B3 持久性——empty/failed 且后续收口提前返回时无人提交)。
if advanced is not None:
db.session.commit()
# [STEP 4] 证据同步:success 事实(ok 且 file_id 有值)后把该来源最新可用
# 入站文件镜像落档。与拆分前终态收尾同口径(按 ok 触发、不依赖等待任务
# 存在——独立收料批次没有调拨任务,但其文件仍是运行期取数的证据源)。
# sync_and_commit_for_callback 桥内自吞异常并自行 commit;本处不包 try,
# 若有异常原样外抛(文件已提交,Worker 重试即可补齐落档)。
if fact.ok and fact.file_id is not None:
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
now = datetime.utcnow()
sync_and_commit_for_callback(
source_code=fact.source_code,
business_date=str(now.date()),
now=now,
)
# [STEP 5] 收料排程收口:精确定位「本次回调收尾的执行单元」的排程 run(Task 7
# 修复轮 2——事实自带 unit_run_id(归档入口每次投递自单元行回填),不再按来源/
# 错误文本猜单元:同来源、同错误文本的新单元存在时旧回调不得收口错误的 run)。
schedule_run_id: int | None = None
if fact.unit_run_id is not None:
# 归档入口产线恒回填 unit_run_id;None 仅为兼容手工构造事实的旧调用方——
# 无单元标识时不猜(跳过收口,不做任何「最新单元」式近似)。
unit = db.session.get(FreightRpaInboundUnitRun, int(fact.unit_run_id))
if unit is None:
# 分发紧跟终态 commit:单元行缺失属硬性不一致,fail-closed 而非静默跳过。
from app.core.errors import NotFoundError
raise NotFoundError(
f"Inbound 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_inbound_finalize import (
finalize_receipt_schedule_run_if_complete,
refresh_receipt_schedule_run_progress,
)
refresh_receipt_schedule_run_progress(schedule_run_id)
finalize_receipt_schedule_run_if_complete(schedule_run_id)
@@ -1,16 +1,20 @@
"""在途调拨入站 RPA 触发服务。
用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = ShippingReceiptReport RPA 产物,
复用货代 ShippingReceiptReport trigger 链路,shipping_notice 域术语保留),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
先落 RPA 单元运行行(awaiting_rpa,回调按 callback_id 查库可达),
再装配入站 trigger unit 并调用 write_inbound_export_batch_trigger 原子写 trigger。
依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、models、db。
用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = freight_rpa 入站 RPA 产物,
复用货代入站 trigger 链路),不创建排程。按来源取站点、入站配置与登录连接
(全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行
(awaiting_rpa,回调按 callback_id 查库可达),再装配入站 trigger unit 并
调用 write_inbound_export_batch_trigger 原子写 trigger。
依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、
freight_rpa.reports.queries(get_site / get_inbound_config / get_rpa_login_profile /
list_inbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。
逻辑:list_inbound_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/ShippingReceiptReportConfig 缺失/rpa_profile 缺失时
一源一单元,query_parameters 原样下发;来源停用/入站配置缺失/登录连接缺失时
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
trigger_inbound_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
【阶段 B Task 4】trigger unit 载荷键集与 Worker 契约(freight_rpa.inbound.v1)
逐键不变;读取改走只读函数后不再引用 freight_rpa 报表模型。
"""
from __future__ import annotations
@@ -24,6 +28,12 @@ from app.services.freight_rpa.inbound.trigger_io import (
SCHEMA,
write_inbound_export_batch_trigger,
)
from app.services.freight_rpa.reports.queries import (
get_inbound_config,
get_rpa_login_profile,
get_site,
list_inbound_configured_source_codes,
)
RouteTriggerWriter = Callable[..., str | None]
@@ -34,38 +44,39 @@ def _build_trigger_unit(
"""装配单来源入站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
【阶段 B Task 4】站点(get_site)/ 入站配置(get_inbound_config)/ 登录连接
(get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的
unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
config = get_inbound_config(source_code)
if config is None:
raise RuntimeError(f'inbound config missing: {source_code}')
profile = source.rpa_profile
profile = get_rpa_login_profile(source_code)
if profile is None or not profile.enabled:
raise RuntimeError(f'inbound 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.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'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': source.rpa_profile_id,
'warehouse_id': None, 'rpa_profile_id': profile.profile_id,
}
return {
'inventory_source_id': source.id,
'source_id': site.source_id,
'callback_id': f'inbound:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
'source_code': site.source_code,
'connector_type': site.connector_type,
'warehouse_id': None,
'rpa_profile_id': profile.id,
'rpa_profile_id': profile.profile_id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'login_config': dict(profile.login_config or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
@@ -79,21 +90,17 @@ def _build_trigger_unit(
def list_inbound_capable_source_codes() -> list[str]:
"""列出可产出入站文件的启用来源实例(enabled 库存源 + 已配置 ShippingReceiptReport)。
"""列出可产出入站文件的启用来源实例(已配置入站报表的启用站点)。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件(ShippingReceiptReport
RPA 产物)只能来自已配置 ShippingReceiptReport 的站点,与货代 ShippingReceiptReport RPA 排程的站点口径一致。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件
只能来自已配置入站报表的站点,与货代入站 RPA 排程的站点口径一致。
【阶段 B Task 4】站点×入站配置 join 查询改委托
freight_rpa.reports.queries.list_inbound_configured_source_codes;本函数
保留为调拨域语义出口(既有调用方 import 路径不变)。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
from app import db
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
rows = db.session.query(ShippingInventorySource.source_code).join(
ShippingReceiptReportConfig,
ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all()
return [str(code) for (code,) in rows]
return list_inbound_configured_source_codes()
def trigger_inbound_rpa(
@@ -122,11 +129,11 @@ def trigger_inbound_rpa(
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
# 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。
from app import db
from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
unit = ShippingInboundRpaUnitRun(
unit = FreightRpaInboundUnitRun(
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
inventory_source_id=unit_payload['inventory_source_id'],
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'),
@@ -192,13 +199,13 @@ def trigger_inbound_rpa_batch(
跳过:{source_code, ok: false, error_code, error_message})。
"""
from app import db
from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
results: list[dict[str, Any]] = []
units: list[ShippingInboundRpaUnitRun] = []
units: list[FreightRpaInboundUnitRun] = []
unit_payloads: list[dict[str, Any]] = []
# [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。
@@ -234,8 +241,8 @@ def trigger_inbound_rpa_batch(
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
for payload in unit_payloads:
unit = ShippingInboundRpaUnitRun(
inventory_source_id=payload['inventory_source_id'],
unit = FreightRpaInboundUnitRun(
source_id=payload['source_id'],
source_code=payload['source_code'],
connector_type=payload['connector_type'],
warehouse_id=payload.get('warehouse_id'),
@@ -45,7 +45,7 @@ assert set(_MOVEMENT_CODES) <= {c.name for c in TransferMovementLedger.__table__
# record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。
INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"})
# 记录种类字面量:inbound=入站(ShippingReceiptReport RPA 产物,shipping_notice 域术语保留);
# 记录种类字面量:inbound=入站(ShippingInboundReport RPA 产物,shipping_notice 域术语保留);
# outbound=出站(出货侧结构就位)。
RECORD_KIND_INBOUND = "inbound"
RECORD_KIND_OUTBOUND = "outbound"
@@ -58,7 +58,7 @@ class FileMeta:
"""一次落地的来源文件证据三元组(溯源的文件级成分;Task 11 从归档文件组装)。
Args:
source_file_id: 入站原样归档文件 id(shipping_receipt_report_files.id;
source_file_id: 入站原样归档文件 id(freight_rpa_inbound_report_files.id;
测试/极端场景可为 None——档事实留存不依赖文件存在)。
file_version: 文件版本号(Task 13 执行门禁 file_current 比对依据)。
file_sha256: 文件 SHA-256(幂等跳过判定的唯一证据指纹)。
@@ -158,7 +158,7 @@ def sync_ledger_rows(
Args:
source_code: 来源实例编码(自然键成分,整批一致)。
record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingReceiptReport
record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingInboundReport
RPA 产物);'outbound' 出货侧(预留合法值,校验放行,不特判)。
parsed_rows: 领域行 dict 列表,每行键=movement 契约 field code
(movement_contract.MOVEMENT_FIELDS:既有 11 + 扩展 7,与
@@ -6,7 +6,9 @@
依赖:transfer_type(配置门禁)/ transfer_type_config_service(resolve_warehouse)/
scope_rules(圈档编译器)/ field_transforms(批号派生)/ ledger(档模型)/
source_file_status / capability_client / date_policy / quantity / contracts /
audit / models。
audit / models。【阶段 B Task 4】取可用入站归档文件的查询已删除并收口到
freight_rpa.reports.queries.latest_usable_inbound_file(匹配不再引用
freight_rpa 报表模型;证据链消费方见 evidence_sync)。
逻辑:【2026-10-14 出生翻转(ADR 0001/D4/D17)】文件落地不再写 items——行由
本服务在匹配创建时从档圈定生成并「创建即绑定」匹配:固定条件(record_kind=
'inbound' + 来源 IN + movement_date 范围 + transfer_executed=false +
@@ -40,7 +42,6 @@ from sqlalchemy import and_, or_
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import (
ShippingReceiptReportFile,
TransferInvoiceItem,
TransferMatching,
TransferMovementLedger,
@@ -70,7 +71,6 @@ from app.services.in_transit_transfer.file_preparation import (
)
from app.services.in_transit_transfer.ledger_sync import RECORD_KIND_INBOUND
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition
from app.services.in_transit_transfer.scope_rules import (
ScopeRule,
apply_scope_filters,
@@ -201,37 +201,6 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCoun
return "success"
def _latest_usable_report_file(source_code: str) -> ShippingReceiptReportFile | None:
"""返回某来源当前「可用」(当天抓取且未清理未过期)的入站归档文件,最新优先。
【AI 触发时机】解析失败分层(2026-09-29)需要把失败事实写到来源当前可用
文件上(parse_failed 三列)、或落档成功后清除其标记、或档落地回填
source_file_id 时调用——查询口径与
source_file_status.resolve_source_file_status 的可用文件判定一致
(inbound_file_gate.usable_inbound_file_condition),防止两处口径漂移。
核心逻辑:[STEP 1] 按 source_code(经 ShippingReceiptReportFile.unit_run
关联单元运行行的 source_code)+ 可用门禁过滤;[STEP 2] 按
created_at/id 倒序取最新一份。只读不写、不 flush 不 commit。
Args:
source_code: 来源实例编码(入站执行单元行上的 source_code)。
Returns:
最新的可用 ShippingReceiptReportFile;来源无可用文件(未抓取/已失效/
已清理)返回 None。
"""
return (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
def _validate_movement_date_range(
business_date: str, movement_date_from: str | None, movement_date_to: str | None,
) -> tuple[date | None, date | None]:
@@ -41,7 +41,7 @@ class MovementField:
# 定死的通用异动字段(领域契约,不配置化):11 个核心字段 + 扩展可选维度字段。
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingReceiptReport External ASN #);
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingInboundReport External ASN #);
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生曾收敛为 external_lot_no() 唯一实现。
# [PROMPT_UPDATE] 2026-10-14(Task 11 切换):external_lot_no() 硬编码退役——批号
@@ -1,18 +1,23 @@
"""在途调拨真实异动(入站/出站)文件仓库。
用途:读取货代入站链路已落库的 ShippingReceiptReportFile(入站证据 = ShippingReceiptReport RPA
产物,shipping_notice 域术语保留;对象存储原始 xlsx),
用该来源 ShippingReceiptReportConfig 绑定的 inbound 解析规则(purpose='inbound',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyInboundFile。
依赖: ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、inbound_file_gate(可用性门禁)、openpyxl。
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
用途:读取货代入站链路已落库的入站归档文件(入站证据 = freight_rpa 入站
RPA 产物,对象存储原始 xlsx),用该来源入站报表配置绑定的 inbound
解析规则(purpose='inbound',端点=定死领域字段 MOVEMENT_FIELDS)的
field_mapping 把列映射为领域行,产出 ReadyInboundFile。
依赖:【阶段 B Task 4】freight_rpa.reports.queries(站点 get_site / 入站配置
get_inbound_config / 入站解析方案 get_inbound_parsing_profile / 最新可用
归档 latest_usable_inbound_file / 归档字节 read_inbound_file_bytes /
维护通道清单 list_reparseable_inbound_files——只读入口唯一权威)、
file_preparation(ReadyInboundFile 契约)、openpyxl。
逻辑:按来源取站点(enabled)与配置 → 解析方案须 published inbound → 最新
【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、文件缺失
或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内
折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。
另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道):同一 join
路径但显式去掉当日门禁,仅供 backlog_reparse_service 使用,运行期禁用。
另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道):
委托 queries 维护通道查询(同一 join 路径但显式去掉当日门禁),仅供
backlog_reparse_service 使用,运行期禁用。
"""
from __future__ import annotations
@@ -23,11 +28,15 @@ from datetime import datetime
from io import BytesIO
from typing import Any, Mapping
from sqlalchemy import or_
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.reports.queries import (
get_inbound_config,
get_inbound_parsing_profile,
get_site,
latest_usable_inbound_file,
list_reparseable_inbound_files,
read_inbound_file_bytes,
)
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition
# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。
_HEADER_WS_RE = re.compile(r"\s+")
@@ -38,7 +47,7 @@ class ReparseableArchiveFile:
"""一份「可重建」归档文件的维护视图(清空重建专用记录,非运行期取数契约)。
Args:
file_id: 归档文件 id(shipping_receipt_report_files.id,档行溯源列同源)。
file_id: 归档文件 id(入站归档文件表主键,档行溯源列同源)。
storage_key: 对象存储键(重建时按此取归档字节)。
sha256: 文件 SHA-256(重落幂等指纹 / FileMeta.file_sha256)。
file_version: 文件版本戳(sha256: 前缀派生,与 latest_ready_file 同口径)。
@@ -66,14 +75,24 @@ def _normalize_header_label(value: Any) -> str:
class ShippingInboundFileRepository:
"""真实入站/异动 ready 文件仓库(复用 ShippingReceiptReport 归档 + inbound 解析规则)。"""
"""真实入站/异动 ready 文件仓库(复用 freight_rpa 入站归档 + inbound 解析规则)。
def __init__(self) -> None:
self._storage = file_asset_storage
【阶段 B Task 4】模型/存储读取全部收敛到 freight_rpa.reports.queries 只读
入口,本类不再 import freight_rpa 报表模型或对象存储客户端;对调用方
(file_preparation / deps / backlog_reparse_service)的类名与方法签名不变。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
"""返回该来源最新且当天(业务日)抓取的未过期入站文件;否则返回 None。
核心逻辑:[STEP 1] 站点须启用(get_site)+ 入站配置须存在
(get_inbound_config)+ 绑定解析方案须 published inbound
(get_inbound_parsing_profile,与运行期规则门禁同一口径);
[STEP 2] 取最新可用归档视图(latest_usable_inbound_file,当天
fail-closed 门禁见 queries.usable_inbound_file_condition)并按
file_id 读归档字节(read_inbound_file_bytes);[STEP 3] 按方案
field_mapping 提取领域行。
Args:
source_code: 来源实例编码。
business_date: 业务日期(用于展示,不强制匹配文件日期)。
@@ -81,45 +100,34 @@ class ShippingInboundFileRepository:
ReadyInboundFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
config = get_inbound_config(source_code)
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
return None
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 inbound_file_gate。
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is None:
view = latest_usable_inbound_file(source_code)
if view is None:
return None
data = self._storage.get_bytes(report.storage_key)
definition = profile.definition_json or {}
data = read_inbound_file_bytes(view.file_id)
rows = _extract_movement_rows(
data,
field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}),
sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None,
header_row_index=(profile.definition_json or {}).get('header_row_index'),
field_mapping=dict(definition.get('field_mapping') or {}),
sheet_name=str(definition.get('sheet_name') or '').strip() or None,
header_row_index=definition.get('header_row_index'),
)
return ReadyInboundFile(
source_code=source_code,
business_date=business_date,
file_no=report.original_filename or str(report.id),
file_version=f"sha256:{report.sha256}"[:64],
checksum=report.sha256,
file_no=view.original_filename or str(view.file_id),
file_version=f"sha256:{view.sha256}"[:64],
checksum=view.sha256,
rows=tuple(rows),
)
@@ -130,13 +138,11 @@ class ShippingInboundFileRepository:
(evidence_sync)禁止改用本方法——当日 fail-closed 门禁是运行期语义,
本方法是显式的历史重建通道(spec §6),两者不得混用。
核心逻辑:join 路径与 latest_ready_file 的归档文件查询同款
(ShippingReceiptReportFile → unit_run.has(source_code=...)),但显式去掉
「当天业务日抓取」新鲜度门禁——重建对象正是历史归档;保留期口径与
inbound_file_gate 一致(archive_expires_at 为空视为长期有效),未清理
(archive_deleted_at 空)且未过保留期(expires > now)才可重建。按归档
时间升序返回(重建必须按归档时间序重落,保证幂等重放顺序确定)。
只读查询,不触碰对象存储字节(字节由调用方按需经 file_asset_storage 取)。
核心逻辑:委托 freight_rpa.reports.queries.list_reparseable_inbound_files
维护通道查询(同一 join 路径,显式去掉「当天业务日抓取」新鲜度门禁——
重建对象正是历史归档;保留期口径一致),并把只读视图映射为本仓库的
维护契约 ReparseableArchiveFile。只读查询,不触碰对象存储字节(字节
由调用方按需经 file_asset_storage 取)。
Args:
source_code: 来源实例编码(经收料执行单元行 source_code 关联)。
@@ -144,34 +150,16 @@ class ShippingInboundFileRepository:
Returns:
ReparseableArchiveFile 列表(archived_at 升序;无可重建归档为空表)。
"""
from app.models import ShippingReceiptReportFile
reports = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
# 维护通道可用性 = 未清理 + 未过保留期(NULL=长期有效,与
# inbound_file_gate 保留期口径一致);【刻意无当日门禁】。
ShippingReceiptReportFile.archive_deleted_at.is_(None),
or_(
ShippingReceiptReportFile.archive_expires_at.is_(None),
ShippingReceiptReportFile.archive_expires_at > now,
),
)
.order_by(ShippingReceiptReportFile.created_at.asc(), ShippingReceiptReportFile.id.asc())
.all()
)
return [
ReparseableArchiveFile(
file_id=report.id,
storage_key=report.storage_key,
sha256=report.sha256,
file_version=f"sha256:{report.sha256}"[:64],
archived_at=report.created_at,
original_filename=report.original_filename,
file_id=view.file_id,
storage_key=view.storage_key,
sha256=view.sha256,
file_version=f"sha256:{view.sha256}"[:64],
archived_at=view.created_at,
original_filename=view.original_filename,
)
for report in reports
for view in list_reparseable_inbound_files(source_code, now=now)
]
@@ -196,7 +184,7 @@ def _extract_movement_rows(
header_row_index: 1-based 表头行;空则自动探测。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index
wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True)
try:
@@ -251,4 +239,4 @@ def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str
if codes and index < len(row):
for code in codes:
output[code] = row[index]
return output
return output
@@ -1,30 +1,31 @@
"""在途调拨来源入站文件状态投影服务。
用途:只读货代入站链路(入站证据 = ShippingReceiptReport RPA 产物,shipping_notice 域,术语保留)
已有事实(ShippingInboundRpaUnitRun 别名 + ShippingReceiptReportFile),
用途:只读货代入站链路已有事实(入站执行单元行 + freight_rpa 入站归档文件),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 /
无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile ,前者经域内别名引用)、
inbound_file_gate(可用/失效判定单一事实来源)。
逻辑:按来源取该来源最新入站执行单元;命中可用门禁(当天业务日抓取且未过期,
见 inbound_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→
parse_failed(不可当 ready,仍带 file_no/file_sha256 便于诊断);
有进行中单元 → fetching;最新单元为失败终态 → failed;
文件仍在但已失效 → expired;否则 → none。
record_inbound_parse_failure / clear_inbound_parse_failure 维护解析失败三列
(写入与清除均只 flush 不 commit,事务归属调用方)。
依赖:freight_rpa.reports.queries(最新可用入站归档 / 失效文件存在性 / 解析失败
标记的只读写入口——口径唯一权威);入站执行单元行模型(经域内别名引用)。
逻辑:【阶段 B Task 4】模型查询全部改走 freight_rpa.reports.queries 只读入口——
可用文件命中(当天业务日抓取且未过期未清理,口径见
queries.usable_inbound_file_condition)→ ready,但文件已标记解析失败
(parse_failed_at 非空)→ parse_failed(不可当 ready,仍带 file_no/
file_sha256 便于诊断);有进行中单元 → fetching;最新单元为失败终态 →
failed;空数据单元 → no_data;文件仍在但已失效 → expired;否则 → none。
record/clear_inbound_parse_failure 保留为兼容薄壳(既有调用方按 ORM 文件
对象传参),内部按主键委托 queries.mark/clear 同一实现(写入与清除均只
flush 不 commit,事务归属调用方)。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import ShippingReceiptReportFile
from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun
from app.services.in_transit_transfer.inbound_file_gate import (
expired_inbound_file_condition,
usable_inbound_file_condition,
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
from app.services.freight_rpa.reports.queries import (
clear_inbound_parse_failure as _clear_parse_failure_by_id,
has_expired_inbound_file,
latest_usable_inbound_file,
mark_inbound_parse_failure as _mark_parse_failure_by_id,
)
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
@@ -38,7 +39,8 @@ def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的入站文件状态投影。
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
inbound_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
freight_rpa.reports.queries 的可用/失效条件):保留期已到 或 非当前业务日
(Asia/Shanghai)抓取。
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
@@ -46,47 +48,41 @@ def resolve_source_file_status(*, source_code: str) -> dict:
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
仍带 file_no/file_sha256 便于诊断与前端提示。
"""
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is not None:
# 【阶段 B Task 4】可用文件读取经 freight_rpa.reports.queries 只读视图
# (file_no/failure 事实列随视图一次取得,不再引用归档文件模型)。
file_view = latest_usable_inbound_file(source_code)
if file_view is not None:
file_no = file_view.original_filename or str(file_view.file_id)
# 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败,
# 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。
if report.parse_failed_at is not None:
if file_view.parse_failed_at is not None:
return {
'file_status': 'parse_failed',
'has_ready_file': False,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
'file_no': file_no,
'file_sha256': file_view.sha256,
}
return {
'file_status': 'ready',
'has_ready_file': True,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
'file_no': file_no,
'file_sha256': file_view.sha256,
}
active_unit = (
ShippingInboundRpaUnitRun.query
FreightRpaInboundUnitRun.query
.filter_by(source_code=source_code)
.filter(ShippingInboundRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(ShippingInboundRpaUnitRun.id.desc())
.filter(FreightRpaInboundUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(FreightRpaInboundUnitRun.id.desc())
.first()
)
if active_unit is not None:
return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
latest_unit = (
ShippingInboundRpaUnitRun.query
FreightRpaInboundUnitRun.query
.filter_by(source_code=source_code)
.order_by(ShippingInboundRpaUnitRun.id.desc())
.order_by(FreightRpaInboundUnitRun.id.desc())
.first()
)
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
@@ -96,16 +92,8 @@ def resolve_source_file_status(*, source_code: str) -> dict:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
expired_report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
expired_inbound_file_condition(),
)
.first()
)
if expired_report is not None:
# 【阶段 B Task 4】失效存在性经 queries.has_expired_inbound_file(与可用条件同核)。
if has_expired_inbound_file(source_code):
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
@@ -113,10 +101,9 @@ def resolve_source_file_status(*, source_code: str) -> dict:
def record_inbound_parse_failure(
*,
report: ShippingReceiptReportFile,
report: Any,
error_code: str,
error_message: str,
now: datetime | None = None,
) -> None:
"""标记一份入站归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
@@ -124,40 +111,34 @@ def record_inbound_parse_failure(
让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后
改调 clear_inbound_parse_failure。
核心逻辑:[STEP 1] 写入失败时间(now 或当前 UTC)与截断后的错误码/错误信息;
[STEP 2] db.session.flush() 使投影同事务内立即可见。只 flush 不 commit,
事务提交时机归调用方(与解析流程共用同一事务,禁止在 service 层越权提交)。
【阶段 B Task 4 兼容薄壳】全量语义(失败时刻取当前 UTC、错误码按 64 字符/
错误信息按 2000 字符截断、只 flush 不 commit——事务提交时机归属调用方)已
收口 freight_rpa.reports.queries.mark_inbound_parse_failure(唯一实现);
本壳只为既有调用方按归档文件对象传参的签名而保留——取对象主键委托真实现。
Args:
report: 待标记的 ShippingReceiptReportFile(须已入库,主键可用)。
error_code: 机器可读错误码,超 64 字符截断(对齐列宽 String(64))。
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
now: 可选失败时刻;缺省取当前 UTC(与全链路 utcnow 口径一致)。
report: 入站归档文件对象(仅取主键 .id;须已入库)。
error_code: 机器可读错误码(真实现内按列宽截断)。
error_message: 人类可读错误信息(真实现内做防御性截断)。
Returns:
None。失败标记写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
None。失败标记随调用方事务落库。
"""
report.parse_failed_at = now or datetime.utcnow()
report.parse_error_code = (error_code or '')[:64]
report.parse_error_message = (error_message or '')[:2000]
db.session.flush()
_mark_parse_failure_by_id(report.id, error_code=error_code, error_message=error_message)
def clear_inbound_parse_failure(*, report: ShippingReceiptReportFile) -> None:
def clear_inbound_parse_failure(*, report: Any) -> None:
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态
投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。
核心逻辑:[STEP 1] 将 parse_failed_at / parse_error_code / parse_error_message
三列置 None(三者全空即未失败/已清除的约定态);[STEP 2] flush 使同事务内
投影立即可见。只 flush 不 commit,事务提交时机归调用方。
【阶段 B Task 4 兼容薄壳】语义收口同 record_inbound_parse_failure:取对象
主键委托 freight_rpa.reports.queries.clear_inbound_parse_failure(置空三列
后 flush,不 commit,事务归属调用方)。
Args:
report: 待清除标记的 ShippingReceiptReportFile(须已入库,主键可用)。
report: 入站归档文件对象(仅取主键 .id;须已入库)。
Returns:
None。清除写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
None。清除随调用方事务落库。
"""
report.parse_failed_at = None
report.parse_error_code = None
report.parse_error_message = None
db.session.flush()
_clear_parse_failure_by_id(report.id)