feat(in-transit-transfer): 落地证据流重解析并纳入货代与排程配套改动
外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
911afa0f73
commit
4c2a7e2a23
145 files changed
+11695
-4214
No files matched your search
@@ -1,15 +1,25 @@
|
||||
"""backend/app/api/in_transit_transfer/__init__.py
|
||||
|
||||
用途:在途仓自动调拨用户态 API(仓库管理人员)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps、
|
||||
source_file_status、inbound/outbound trigger、scope_rules、transfer_type。
|
||||
逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id);
|
||||
POST /sources/<code>/reparse 重解析当前最新可用归档(不触发 RPA);
|
||||
单源重试读 record_kind(缺省 inbound,出站另走 outbound trigger);
|
||||
批量重试带 transfer_type 时按 record_kinds_of 分组,跳过 ready/fetching/
|
||||
unconfigured 后再各写最多一个 batch;
|
||||
证据下载(POST /sources/inbound-files)按同一函数打包各来源最新可用
|
||||
入站/出站文件;当天清单(GET /sources/<code>/evidence-files)复用可用
|
||||
条件返回当天全部文件并签发预签地址;
|
||||
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
|
||||
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
|
||||
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
||||
retrigger → 202,D11 唯一出口);首页「已执行」区块:已执行单分页查询
|
||||
(GET /documents,只读)与人工关闭失败单(POST /documents/{doc_no}/close,
|
||||
D18 废单不废行);调拨类型选择数据源(GET /transfer-types,仅启用、
|
||||
最小暴露,读 Task 4 transfer_type_config_service);待匹配桶维护(spec §6):
|
||||
D18 废单不废行); 调拨类型选择数据源(GET /transfer-types,仅启用、
|
||||
最小暴露,另附 record_kinds_of(scope_rules) 推导的 record_kinds,不回传
|
||||
scope_rules / warehouse_config / description);来源列表(GET /sources)
|
||||
一次批量投影全部启用来源的入站/出站文件状态;待匹配桶维护(spec §6):
|
||||
「清空并重新解析」预检(GET /backlog/pending-match/reparse-preview,只读)
|
||||
与执行(POST /backlog/pending-match/reparse,单事务由 service 提交并落审计)。
|
||||
"""
|
||||
@@ -183,58 +193,65 @@ def requery_items_api(matching_no: str):
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/inbound-files", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def download_source_inbound_files_api():
|
||||
"""按选中来源打包下载各自最新归档入站文件(ShippingInboundReport RPA 产物,zip);记录访问审计。"""
|
||||
import io
|
||||
import zipfile
|
||||
from pathlib import Path as _Path
|
||||
def _usable_archive_files(source_code: str, record_kind: str) -> list:
|
||||
"""返回某来源当天全部可用归档,最新在前。
|
||||
|
||||
from app import db
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
用途:证据压缩包与当天清单共用同一可用条件。压缩包只取第一条,清单返回全部。
|
||||
核心逻辑:入站过滤用 usable_inbound_file_condition;出站过滤与
|
||||
latest_usable_outbound_file 相同(未清理 + 当天业务日 + 未过保留期)。
|
||||
不读取、不解析文件字节。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
record_kind: inbound 或 outbound。
|
||||
Returns:
|
||||
归档 ORM 行列表,按 created_at、id 倒序。未知记录类型返回空列表。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import FreightRpaInboundReportFile, FreightRpaOutboundReportFile
|
||||
from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
_outbound_fresh_and_retention_valid,
|
||||
)
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
source_codes = body.get("source_codes")
|
||||
if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]:
|
||||
raise ValidationError("source_codes is required")
|
||||
if record_kind == "outbound":
|
||||
model = FreightRpaOutboundReportFile
|
||||
usable = (
|
||||
model.archive_deleted_at.is_(None),
|
||||
_outbound_fresh_and_retention_valid(datetime.utcnow()),
|
||||
)
|
||||
elif record_kind == "inbound":
|
||||
model = FreightRpaInboundReportFile
|
||||
usable = (usable_inbound_file_condition(),)
|
||||
else:
|
||||
return []
|
||||
return (
|
||||
model.query
|
||||
.join(model.unit_run)
|
||||
.filter(model.unit_run.has(source_code=source_code), *usable)
|
||||
.order_by(model.created_at.desc(), model.id.desc())
|
||||
.all()
|
||||
)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
included: list[str] = []
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
for code in source_codes:
|
||||
code = str(code or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
report = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundReportFile.unit_run.has(source_code=code),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/匹配取文件同口径,
|
||||
# 单一事实来源见 inbound_file_gate。
|
||||
usable_inbound_file_condition(),
|
||||
)
|
||||
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
if report is None:
|
||||
continue
|
||||
data = file_asset_storage.get_bytes(report.storage_key)
|
||||
safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name
|
||||
archive.writestr(f"{code}-{safe_name}", data)
|
||||
included.append(code)
|
||||
if not included:
|
||||
raise NotFoundError("no archived inbound files", code="SHIPPING.INBOUND_FILE_NOT_FOUND")
|
||||
|
||||
def _record_evidence_download_audit(*, aggregate_id: str) -> None:
|
||||
"""写入证据文件访问审计,事件类型保持 TRANSFER_INBOUND_FILES_DOWNLOADED。
|
||||
|
||||
核心逻辑:下载与清单共用这一事件。aggregate_id 由调用方决定
|
||||
(下载为打进包的来源编码,清单为当前 source_code)。
|
||||
|
||||
Args:
|
||||
aggregate_id: 审计聚合标识。
|
||||
"""
|
||||
from app import db
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
|
||||
aggregate_type="in_transit_source",
|
||||
aggregate_id=",".join(included),
|
||||
aggregate_id=aggregate_id,
|
||||
actor_type="user",
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
actor_display=str(getattr(user, "name", "") or ""),
|
||||
@@ -242,15 +259,106 @@ def download_source_inbound_files_api():
|
||||
result="success",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/inbound-files", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def download_source_inbound_files_api():
|
||||
"""按调拨类型的证据流打包各来源最新可用归档。
|
||||
|
||||
请求体:{"source_codes": [...], "transfer_type": 类型编码}。
|
||||
证据流来自 record_kinds_of(该类型已有范围规则),没有 record_kinds 列。
|
||||
没有 record_kind 规则时入站和出站都打包;规则等于 inbound 时只打包入站。
|
||||
每种记录类型只取该来源最新一份可用文件。压缩包路径为
|
||||
inbound/<source_code>/<filename> 或 outbound/<source_code>/<filename>。
|
||||
下载名 evidence-files-<n>.zip,n 为打进包的文件数。两种都没有文件时
|
||||
404,错误码 SHIPPING.INBOUND_FILE_NOT_FOUND。审计事件类型仍是
|
||||
TRANSFER_INBOUND_FILES_DOWNLOADED。
|
||||
"""
|
||||
import io
|
||||
import zipfile
|
||||
from pathlib import Path as _Path
|
||||
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.scope_rules import record_kinds_of
|
||||
from app.services.in_transit_transfer.transfer_type import resolve_transfer_type
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
source_codes = body.get("source_codes")
|
||||
if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]:
|
||||
raise ValidationError("source_codes is required")
|
||||
config = resolve_transfer_type(str(body.get("transfer_type") or ""))
|
||||
kinds = record_kinds_of(config.scope_rules)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
packed_sources: list[str] = []
|
||||
packed = 0
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
for raw_code in source_codes:
|
||||
code = str(raw_code or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
wrote = False
|
||||
for kind in kinds:
|
||||
files = _usable_archive_files(code, kind)
|
||||
report = files[0] if files else None
|
||||
if report is None:
|
||||
continue
|
||||
data = file_asset_storage.get_bytes(report.storage_key)
|
||||
safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name
|
||||
archive.writestr(f"{kind}/{code}/{safe_name}", data)
|
||||
packed += 1
|
||||
wrote = True
|
||||
if wrote and code not in packed_sources:
|
||||
packed_sources.append(code)
|
||||
if packed == 0:
|
||||
raise NotFoundError("no archived inbound files", code="SHIPPING.INBOUND_FILE_NOT_FOUND")
|
||||
|
||||
_record_evidence_download_audit(aggregate_id=",".join(packed_sources))
|
||||
buffer.seek(0)
|
||||
return send_file(
|
||||
buffer,
|
||||
mimetype="application/zip",
|
||||
as_attachment=True,
|
||||
download_name=f"inbound-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip",
|
||||
download_name=f"evidence-files-{packed}.zip",
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/<source_code>/evidence-files", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def list_source_evidence_files_api(source_code: str):
|
||||
"""返回某来源当天全部可用证据文件,并签发短期下载地址。
|
||||
|
||||
查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。
|
||||
可用条件与证据压缩包相同,但返回当天全部可用文件,不只最新一份。
|
||||
每项含 file_id、original_filename、created_at、sha256、file_size、
|
||||
presigned_url。不解析 Excel,不含行数。预签调用
|
||||
presigned_get_url(storage_key, expires_seconds=300)。签发时写
|
||||
TRANSFER_INBOUND_FILES_DOWNLOADED,aggregate_id 为 source_code。
|
||||
"""
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
kind = str(request.args.get("record_kind") or "inbound").strip()
|
||||
if kind not in {"inbound", "outbound"}:
|
||||
raise ValidationError("record_kind must be inbound or outbound")
|
||||
code = str(source_code or "").strip()
|
||||
payload = []
|
||||
for report in _usable_archive_files(code, kind):
|
||||
created = report.created_at.isoformat() if report.created_at is not None else None
|
||||
payload.append({
|
||||
"file_id": report.id,
|
||||
"original_filename": report.original_filename,
|
||||
"created_at": created,
|
||||
"sha256": report.sha256,
|
||||
"file_size": report.file_size,
|
||||
"presigned_url": file_asset_storage.presigned_get_url(
|
||||
report.storage_key, expires_seconds=300,
|
||||
),
|
||||
})
|
||||
_record_evidence_download_audit(aggregate_id=code)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_run_api(run_no: str):
|
||||
@@ -733,11 +841,13 @@ def transfer_metrics_api():
|
||||
def transfer_types_api():
|
||||
"""调拨类型配置列表(启用中,最小暴露)——匹配创建的类型选择数据源。
|
||||
|
||||
仅返回 {code, names, sort_order, transform_rules} 四键:范围规则/仓库定义/
|
||||
描述属管理端配置资产,禁止对用户态暴露(最小暴露硬契约,见 Task 5 测试);
|
||||
enabled 由查询限定(get_enabled)、sort_order 升序。配置缺失返回空列表,
|
||||
不抛 NOT_CONFIGURED(该码留给匹配创建链路)。
|
||||
返回 code、names、sort_order、transform_rules,以及 record_kinds。
|
||||
record_kinds 只由 record_kinds_of(dto.scope_rules) 现算,不读存储列。
|
||||
范围规则原文、仓库定义、描述仍不暴露。enabled 由查询限定(get_enabled)、
|
||||
sort_order 升序。配置缺失返回空列表,不抛 NOT_CONFIGURED。
|
||||
"""
|
||||
from app.services.in_transit_transfer.scope_rules import record_kinds_of
|
||||
|
||||
return _ok([
|
||||
{
|
||||
"code": dto.code,
|
||||
@@ -747,6 +857,7 @@ def transfer_types_api():
|
||||
{"field": rule.field, "op": rule.op, "source": rule.source, "target": rule.target}
|
||||
for rule in dto.transform_rules
|
||||
],
|
||||
"record_kinds": list(record_kinds_of(dto.scope_rules)),
|
||||
}
|
||||
for dto in list_enabled_transfer_types()
|
||||
])
|
||||
@@ -757,59 +868,114 @@ def transfer_types_api():
|
||||
def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附入站文件状态(ready/parse_failed/fetching/failed/expired/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天
|
||||
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
|
||||
每来源附入站与出站两条证据流 streams。每条含 record_kind、file_status、
|
||||
has_ready_file、file_no、file_sha256。扁平 file_status / has_ready_file /
|
||||
file_no / file_sha256 仍等于入站流,供尚未改完的前端;出站无配置时该条
|
||||
file_status=unconfigured。保留期已到或非当天(业务日)抓取且未清理均投影
|
||||
expired。文件状态由 resolve_source_file_statuses 一次投影全部来源,
|
||||
查询次数不随来源个数增长。只读复用已启用库存来源。
|
||||
"""
|
||||
from app.models import FreightRpaSource
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses
|
||||
|
||||
rows = FreightRpaSource.query.filter_by(enabled=True).order_by(
|
||||
FreightRpaSource.connector_type, FreightRpaSource.source_code,
|
||||
).all()
|
||||
return _ok([
|
||||
{
|
||||
statuses = resolve_source_file_statuses(rows)
|
||||
items = []
|
||||
for source in rows:
|
||||
pair = statuses[source.source_code]
|
||||
inbound = pair["inbound"]
|
||||
outbound = pair["outbound"]
|
||||
items.append({
|
||||
"source_code": source.source_code,
|
||||
"display_name": source.display_name,
|
||||
"platform": source.connector_type,
|
||||
"enabled": bool(source.enabled),
|
||||
**resolve_source_file_status(source_code=source.source_code),
|
||||
}
|
||||
for source in rows
|
||||
])
|
||||
**inbound,
|
||||
"streams": [
|
||||
{"record_kind": "inbound", **inbound},
|
||||
{"record_kind": "outbound", **outbound},
|
||||
],
|
||||
})
|
||||
return _ok(items)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/<source_code>/reparse", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def reparse_current_file_api(source_code: str):
|
||||
"""重解析该来源当前最新可用归档,不触发 RPA。
|
||||
|
||||
body 只读 record_kind,缺省 inbound。不接受 file_id。
|
||||
"""
|
||||
from app.services.in_transit_transfer.current_file_reparse import reparse_current_file
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError("request body must be a JSON object")
|
||||
record_kind = str(payload.get("record_kind") or "inbound").strip() or "inbound"
|
||||
result = reparse_current_file(
|
||||
source_code=str(source_code).strip(),
|
||||
record_kind=record_kind,
|
||||
now=datetime.utcnow(),
|
||||
)
|
||||
return _ok({
|
||||
"source_code": result.source_code,
|
||||
"record_kind": result.record_kind,
|
||||
"ok": result.ok,
|
||||
"file_status": result.file_status,
|
||||
"file_id": result.file_id,
|
||||
"inserted": result.inserted,
|
||||
"updated": result.updated,
|
||||
"skipped": result.skipped,
|
||||
"sealed_skipped": result.sealed_skipped,
|
||||
"error_code": result.error_code,
|
||||
"error_message": result.error_message,
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/<source_code>/retry-rpa", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_source_rpa_api(source_code: str):
|
||||
"""对指定来源重新触发一次入站 RPA 抓取(复用货代 ShippingInboundReport trigger 链路,shipping_notice 域术语保留)。
|
||||
"""按证据流重试一个来源:缺省入站,请求体 record_kind=outbound 走出站触发。
|
||||
|
||||
【AI 触发时机】来源入站文件不可用需要恢复时调用:解析失败(parse_failed)先
|
||||
本地重解析已归档文件;文件缺失/失效(none/expired/failed)才重新触发 RPA 抓取。
|
||||
【AI 触发时机】来源某一条证据流需要恢复时调用。入站解析失败(parse_failed)
|
||||
先本地重解析已归档文件;出站解析失败重新触发出站 RPA。行上重试不跳过 ready。
|
||||
|
||||
解析失败优先本地重解析(解析失败分层 2026-09-29):当日文件可用但解析失败时,
|
||||
先走 sync_and_commit_for_callback 重解析归档文件——成功且投影回 ready →
|
||||
入站解析失败分层(2026-09-29):当日文件可用但解析失败时,先走
|
||||
sync_and_commit_for_callback——成功且投影回 ready →
|
||||
200 {"source_code", "ok": true, "file_status": "ready", "reparsed": true}
|
||||
(不触发 RPA、不返回 202/fetching);仍失败 → 同结构 ok=false
|
||||
(file_status=parse_failed)。其余状态沿用原路径:重新触发一次入站 RPA,
|
||||
成功 202+fetching;配置缺失时 fail-closed(ok=False)。
|
||||
(file_status=parse_failed)。其余状态按 record_kind 选择
|
||||
trigger_inbound_rpa 或 trigger_outbound_rpa,成功 202+fetching;
|
||||
配置缺失时 fail-closed(ok=False,沿用触发服务的配置缺失码)。
|
||||
"""
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa
|
||||
from app.services.in_transit_transfer.outbound_trigger_service import trigger_outbound_rpa
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError("request body must be a JSON object")
|
||||
record_kind = str(payload.get("record_kind") or "inbound").strip() or "inbound"
|
||||
source_code = str(source_code).strip()
|
||||
business_date = str(business_date_now())
|
||||
|
||||
# [STEP 1] 解析失败分层:文件可用但解析失败 → 先本地重解析归档文件,不触发 RPA。
|
||||
status = resolve_source_file_status(source_code=source_code)
|
||||
if status.get("file_status") == "parse_failed" and status.get("file_sha256"):
|
||||
# [STEP 1] 只有入站 parse_failed 本地重解析。出站 parse_failed 落到 STEP 2 重抓。
|
||||
status = resolve_source_file_status(source_code=source_code, record_kind=record_kind)
|
||||
if (
|
||||
record_kind == "inbound"
|
||||
and status.get("file_status") == "parse_failed"
|
||||
and status.get("file_sha256")
|
||||
):
|
||||
synced = sync_and_commit_for_callback(
|
||||
source_code=source_code,
|
||||
business_date=str(business_date_now()),
|
||||
business_date=business_date,
|
||||
now=datetime.utcnow(),
|
||||
)
|
||||
# 重解析后再取投影:以真实落库事实(而非 sync 返回值)决定 ok。
|
||||
status = resolve_source_file_status(source_code=source_code)
|
||||
status = resolve_source_file_status(source_code=source_code, record_kind="inbound")
|
||||
ready = bool(synced) and status.get("file_status") == "ready"
|
||||
return _ok({
|
||||
"source_code": source_code,
|
||||
@@ -818,13 +984,20 @@ def retry_source_rpa_api(source_code: str):
|
||||
"reparsed": True,
|
||||
})
|
||||
|
||||
# [STEP 2] 其余状态沿用原路径:重新触发一次入站 RPA 抓取(202 + fetching)。
|
||||
outcome = trigger_inbound_rpa(
|
||||
source_code=source_code,
|
||||
business_date=str(business_date_now()),
|
||||
reason="transfer_retry_inbound",
|
||||
)
|
||||
status = resolve_source_file_status(source_code=source_code)
|
||||
# [STEP 2] 按证据流选择已有触发器,不合并两套实现。
|
||||
if record_kind == "outbound":
|
||||
outcome = trigger_outbound_rpa(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
reason="transfer_retry_outbound",
|
||||
)
|
||||
else:
|
||||
outcome = trigger_inbound_rpa(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
reason="transfer_retry_inbound",
|
||||
)
|
||||
status = resolve_source_file_status(source_code=source_code, record_kind=record_kind)
|
||||
if not outcome.get("ok"):
|
||||
return _ok({
|
||||
"source_code": source_code,
|
||||
@@ -840,30 +1013,194 @@ def retry_source_rpa_api(source_code: str):
|
||||
}, status=202)
|
||||
|
||||
|
||||
def resolve_source_file_status(*, source_code: str, record_kind: str = "inbound") -> dict:
|
||||
"""按证据流投影来源文件状态(路由层入口,测试可替换本函数)。
|
||||
|
||||
核心逻辑:调用时再导入投影服务,因此服务模块上的测试替身仍然生效;
|
||||
批量重试按流入参 record_kind,缺省 inbound。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
record_kind: inbound 或 outbound。
|
||||
Returns:
|
||||
file_status / has_ready_file / file_no / file_sha256。
|
||||
"""
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
resolve_source_file_status as impl,
|
||||
)
|
||||
|
||||
return impl(source_code=source_code, record_kind=record_kind)
|
||||
|
||||
|
||||
def trigger_inbound_rpa_batch(*, source_codes, business_date, reason="transfer_retry_inbound"):
|
||||
"""转发入站批量触发(不合并出站实现;测试可替换本函数)。
|
||||
|
||||
Args:
|
||||
source_codes: 需要入站重试的来源编码。
|
||||
business_date: 业务日。
|
||||
reason: 写入 trigger 的原因。
|
||||
Returns:
|
||||
inbound_trigger_service.trigger_inbound_rpa_batch 的返回值。
|
||||
"""
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import (
|
||||
trigger_inbound_rpa_batch as impl,
|
||||
)
|
||||
|
||||
return impl(source_codes=source_codes, business_date=business_date, reason=reason)
|
||||
|
||||
|
||||
def trigger_outbound_rpa_batch(*, source_codes, business_date, reason="transfer_retry_outbound"):
|
||||
"""转发出站批量触发(与入站触发分开;测试可替换本函数)。
|
||||
|
||||
Args:
|
||||
source_codes: 需要出站重试的来源编码。
|
||||
business_date: 业务日。
|
||||
reason: 写入 trigger 的原因。
|
||||
Returns:
|
||||
outbound_trigger_service.trigger_outbound_rpa_batch 的返回值。
|
||||
"""
|
||||
from app.services.in_transit_transfer.outbound_trigger_service import (
|
||||
trigger_outbound_rpa_batch as impl,
|
||||
)
|
||||
|
||||
return impl(source_codes=source_codes, business_date=business_date, reason=reason)
|
||||
|
||||
|
||||
# 批量重试:已就绪或抓取中不写 trigger;未配置只记结果。可重试状态进入对应流。
|
||||
_STREAM_SKIP_STATUSES = frozenset({"ready", "fetching"})
|
||||
_STREAM_RETRY_STATUSES = frozenset({"no_data", "failed", "expired", "none", "parse_failed"})
|
||||
_STREAM_CONFIG_MISSING = {
|
||||
"inbound": "RPA_INBOUND_CONFIG_MISSING",
|
||||
"outbound": "RPA_OUTBOUND_CONFIG_MISSING",
|
||||
}
|
||||
|
||||
|
||||
def _annotate_stream_results(outcome: dict, record_kind: str, source_codes: list[str]) -> list[dict]:
|
||||
"""给一条证据流的批量触发结果补上 record_kind。
|
||||
|
||||
核心逻辑:触发器已带回 results 时逐项加上记录类型;没有 results 时按本次
|
||||
提交的来源补一行,避免这条流在响应里消失。
|
||||
|
||||
Args:
|
||||
outcome: trigger_*_rpa_batch 的返回值。
|
||||
record_kind: inbound 或 outbound。
|
||||
source_codes: 本次交给该触发器的来源编码。
|
||||
Returns:
|
||||
每项都含 record_kind 的结果列表。
|
||||
"""
|
||||
raw = outcome.get("results")
|
||||
if not raw:
|
||||
error_code = outcome.get("error_code")
|
||||
raw = []
|
||||
for code in source_codes:
|
||||
item: dict[str, Any] = {"source_code": code, "ok": bool(outcome.get("ok"))}
|
||||
if error_code and not outcome.get("ok"):
|
||||
item["error_code"] = error_code
|
||||
raw.append(item)
|
||||
annotated = []
|
||||
for item in raw:
|
||||
row = dict(item)
|
||||
row["record_kind"] = record_kind
|
||||
annotated.append(row)
|
||||
return annotated
|
||||
|
||||
|
||||
def _append_unique(bucket: list[str], code: str) -> None:
|
||||
"""保序去重追加来源编码(同一流只进一次 batch)。"""
|
||||
if code not in bucket:
|
||||
bucket.append(code)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/retry-rpa-batch", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_sources_rpa_batch_api():
|
||||
"""批量重试多来源入站 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。
|
||||
"""批量重试:无 transfer_type 时整批入站;有类型时按证据流各写最多一个 batch。
|
||||
|
||||
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
|
||||
逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器;
|
||||
合并单文件后 Worker 单次登录串行导出全部来源(与 ShippingInboundReport RPA 排程路径同效率)。
|
||||
【AI 触发时机】聊天侧「批量重试 RPA」提交多个来源时调用。带 transfer_type
|
||||
时只重试该类型范围规则推导出的、尚未就绪、不是抓取中、且已配置的流。
|
||||
|
||||
请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与
|
||||
fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。
|
||||
请求体:{"source_codes": [...], "transfer_type": "hub_to_hub"}。
|
||||
transfer_type 缺省时保持旧契约:source_codes 原样交给入站 batch,HTTP 200。
|
||||
有类型时 ready/fetching 不写入结果;unconfigured 记 ok=false 与既有配置缺失码
|
||||
且不写 trigger;no_data/failed/expired/none/parse_failed 进入对应流。
|
||||
入站 parse_failed 仍由入站 batch 本地重解析;出站 parse_failed 重新触发出站 RPA。
|
||||
结果每项带 record_kind。写出 trigger 时返回 202。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError("request body must be a JSON object")
|
||||
source_codes = [str(code).strip() for code in (payload.get("source_codes") or []) if str(code).strip()]
|
||||
if not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa_batch
|
||||
|
||||
outcome = trigger_inbound_rpa_batch(
|
||||
source_codes=source_codes,
|
||||
business_date=str(business_date_now()),
|
||||
reason="transfer_retry_inbound",
|
||||
transfer_type = str(payload.get("transfer_type") or "").strip()
|
||||
business_date = str(business_date_now())
|
||||
# [STEP 1] 旧调用不带类型:整批入站,回传触发服务 envelope。
|
||||
if not transfer_type:
|
||||
outcome = trigger_inbound_rpa_batch(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
reason="transfer_retry_inbound",
|
||||
)
|
||||
return _ok(outcome)
|
||||
|
||||
from app.services.in_transit_transfer.scope_rules import record_kinds_of
|
||||
from app.services.in_transit_transfer.transfer_type import resolve_transfer_type
|
||||
|
||||
# [STEP 2] 类型门禁后按范围规则推导证据流,再按流分组。不在这里合并两个触发实现。
|
||||
config = resolve_transfer_type(transfer_type)
|
||||
kinds = record_kinds_of(config.scope_rules)
|
||||
inbound_codes: list[str] = []
|
||||
outbound_codes: list[str] = []
|
||||
results: list[dict[str, Any]] = []
|
||||
for code in dict.fromkeys(source_codes):
|
||||
for kind in kinds:
|
||||
status = resolve_source_file_status(source_code=code, record_kind=kind)
|
||||
file_status = status.get("file_status")
|
||||
if file_status == "unconfigured":
|
||||
results.append({
|
||||
"source_code": code,
|
||||
"record_kind": kind,
|
||||
"ok": False,
|
||||
"error_code": _STREAM_CONFIG_MISSING[kind],
|
||||
})
|
||||
continue
|
||||
if file_status in _STREAM_SKIP_STATUSES or file_status not in _STREAM_RETRY_STATUSES:
|
||||
continue
|
||||
if kind == "outbound":
|
||||
_append_unique(outbound_codes, code)
|
||||
else:
|
||||
_append_unique(inbound_codes, code)
|
||||
|
||||
# [STEP 3] 每条流最多一次 batch。没有任何 trigger 时保持 200。
|
||||
triggered = False
|
||||
overall_ok = True
|
||||
if inbound_codes:
|
||||
outcome = trigger_inbound_rpa_batch(
|
||||
source_codes=inbound_codes,
|
||||
business_date=business_date,
|
||||
reason="transfer_retry_inbound",
|
||||
)
|
||||
triggered = triggered or bool(outcome.get("triggered"))
|
||||
if not outcome.get("ok"):
|
||||
overall_ok = False
|
||||
results.extend(_annotate_stream_results(outcome, "inbound", inbound_codes))
|
||||
if outbound_codes:
|
||||
outcome = trigger_outbound_rpa_batch(
|
||||
source_codes=outbound_codes,
|
||||
business_date=business_date,
|
||||
reason="transfer_retry_outbound",
|
||||
)
|
||||
triggered = triggered or bool(outcome.get("triggered"))
|
||||
if not outcome.get("ok"):
|
||||
overall_ok = False
|
||||
results.extend(_annotate_stream_results(outcome, "outbound", outbound_codes))
|
||||
if any(item.get("ok") is False for item in results):
|
||||
overall_ok = False
|
||||
return _ok(
|
||||
{"ok": overall_ok, "triggered": triggered, "results": results},
|
||||
status=202 if triggered else 200,
|
||||
)
|
||||
return _ok(outcome)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
|
||||
@@ -948,6 +1285,8 @@ def backlog_summary_api():
|
||||
'unknown': summary.unknown_count,
|
||||
# 首页待办看板第 4 张数字卡(D16):已落档尚未匹配的外部入站记录数。
|
||||
'pending_match': summary.pending_match_count,
|
||||
# 库存匹配卡:启用类型现在圈得住的行数。待匹配卡用上面的全量。
|
||||
'matchable_count': summary.matchable_count,
|
||||
'aging': {
|
||||
'warn_3d': summary.warn_3d,
|
||||
'escalate_5d': summary.escalate_5d,
|
||||
@@ -959,14 +1298,14 @@ def backlog_summary_api():
|
||||
@in_transit_transfer_bp.route("/backlog/pending-match", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_pending_match_api():
|
||||
"""首页待办看板「待匹配」桶清单(D16 只读:启用类型范围并集内已落档、
|
||||
尚未被任何匹配圈定的外部入站记录;无 item_id——不可勾选执行,
|
||||
前端仅提供只读清单与「去匹配」引导)。
|
||||
"""首页待办看板「待匹配」桶清单(只读:已落档、尚未被匹配圈定的成熟出入站
|
||||
记录,不按调拨类型范围过滤;无 item_id——不可勾选执行)。
|
||||
|
||||
Query(可选;不带 page/page_size 时保持历史行为返回全量数组——向后兼容):
|
||||
page(默认 1);page_size(默认 20,上限 100)——任一提供即切换为
|
||||
分页 envelope {records, total, page, page_size}(2026-10-16 服务端分页:
|
||||
桶为 951 行级大池,全量序列化/传输从 O(桶) 降到 O(页))。
|
||||
分页 envelope {records, total, page, page_size}。
|
||||
segment:all(默认,全量)/ matchable(启用类型现在圈得住)/
|
||||
outside(其余已落档)。每行带 matchable。
|
||||
"""
|
||||
from app.services.in_transit_transfer.backlog_service import (
|
||||
BACKLOG_PAGE_DEFAULT,
|
||||
@@ -976,11 +1315,15 @@ def backlog_pending_match_api():
|
||||
list_pending_match_records_page,
|
||||
)
|
||||
|
||||
segment = (request.args.get("segment") or "all").strip()
|
||||
if segment not in ("all", "matchable", "outside"):
|
||||
raise ValidationError("segment must be all, matchable, or outside")
|
||||
paginated = bool((request.args.get("page") or "").strip() or (request.args.get("page_size") or "").strip())
|
||||
if paginated:
|
||||
page_data = list_pending_match_records_page(
|
||||
page=_parse_int_arg("page", BACKLOG_PAGE_DEFAULT, minimum=1),
|
||||
page_size=_parse_int_arg("page_size", BACKLOG_PAGE_SIZE_DEFAULT, minimum=1, maximum=BACKLOG_PAGE_SIZE_MAX),
|
||||
segment=segment,
|
||||
)
|
||||
return _ok({
|
||||
'records': [_serialize_pending_match_record(record) for record in page_data.records],
|
||||
@@ -991,12 +1334,12 @@ def backlog_pending_match_api():
|
||||
|
||||
return _ok([
|
||||
_serialize_pending_match_record(record)
|
||||
for record in list_pending_match_records()
|
||||
for record in list_pending_match_records(segment=segment)
|
||||
])
|
||||
|
||||
|
||||
def _serialize_pending_match_record(record) -> dict[str, Any]:
|
||||
"""「待匹配」桶项序列化(档记录只读投影七键;无 item_id)。"""
|
||||
"""「待匹配」桶项序列化(档记录只读投影;含 record_kind;无 item_id)。"""
|
||||
return {
|
||||
'ledger_record_id': record.ledger_record_id,
|
||||
'doc_no': record.doc_no,
|
||||
@@ -1004,7 +1347,9 @@ def _serialize_pending_match_record(record) -> dict[str, Any]:
|
||||
'material_name': record.material_name,
|
||||
'movement_date': record.movement_date,
|
||||
'source_code': record.source_code,
|
||||
'record_kind': record.record_kind,
|
||||
'quantity': record.quantity,
|
||||
'matchable': record.matchable,
|
||||
}
|
||||
|
||||
|
||||
@@ -1015,15 +1360,18 @@ def pending_match_reparse_preview_api():
|
||||
|
||||
【AI 触发时机】仅待匹配面板「清空并重新解析」确认弹窗加载预检结果时调用;
|
||||
禁止在运行期收料落地链路调用(运行期走 evidence_sync,当日 fail-closed 语义)。
|
||||
响应 data:{files:[{archived_at,sha256,rows}], profile:{code,version}|None,
|
||||
clearable_rows, kept_rows}——语义见 backlog_reparse_service.preview_pending_match_reparse。
|
||||
Query:source_code(必填)、record_kind(缺省 inbound;outbound=出站流)。
|
||||
响应 data:{record_kind, files, profile, clearable_rows, kept_rows}。
|
||||
"""
|
||||
from app.services.in_transit_transfer.backlog_reparse_service import preview_pending_match_reparse
|
||||
|
||||
source_code = str(request.args.get("source_code") or "").strip()
|
||||
if not source_code:
|
||||
raise ValidationError("source_code is required")
|
||||
return _ok(preview_pending_match_reparse(source_code=source_code, now=datetime.utcnow()))
|
||||
record_kind = str(request.args.get("record_kind") or "inbound").strip() or "inbound"
|
||||
return _ok(preview_pending_match_reparse(
|
||||
source_code=source_code, now=datetime.utcnow(), record_kind=record_kind,
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog/pending-match/reparse", methods=["POST"])
|
||||
@@ -1033,10 +1381,9 @@ def pending_match_reparse_api():
|
||||
|
||||
【AI 触发时机】仅待匹配面板「清空并重新解析」确认提交时调用;
|
||||
禁止在运行期收料落地链路调用(运行期走 evidence_sync,当日 fail-closed 语义)。
|
||||
请求体 {"source_code"};任一归档解析失败整体中止(TRANSFER.REPARSE_PARSE_FAILED,
|
||||
一行不删)。审计 TRANSFER_PENDING_MATCH_REPARSED 由 service 落库(含操作人)。
|
||||
响应 data:{source_code, cleared, reinserted, date_skipped, kept_unrebuildable,
|
||||
unlinked_items(R9 废弃引用解绑数), collapses(重落坍缩键数), files}。
|
||||
请求体 {"source_code", "record_kind"?};record_kind 缺省 inbound。
|
||||
任一归档解析失败整体中止(TRANSFER.REPARSE_PARSE_FAILED,一行不删)。
|
||||
响应 data:含 record_kind 与 cleared/reinserted 等计数。
|
||||
"""
|
||||
from app.services.in_transit_transfer.backlog_reparse_service import reparse_pending_match
|
||||
|
||||
@@ -1044,14 +1391,17 @@ def pending_match_reparse_api():
|
||||
source_code = str(payload.get("source_code") or "").strip()
|
||||
if not source_code:
|
||||
raise ValidationError("source_code is required")
|
||||
record_kind = str(payload.get("record_kind") or "inbound").strip() or "inbound"
|
||||
user = _require_user()
|
||||
outcome = reparse_pending_match(
|
||||
source_code=source_code,
|
||||
operator=str(getattr(user, "username", "") or user.id),
|
||||
now=datetime.utcnow(),
|
||||
record_kind=record_kind,
|
||||
)
|
||||
return _ok({
|
||||
"source_code": outcome.source_code,
|
||||
"record_kind": outcome.record_kind,
|
||||
"cleared": outcome.cleared,
|
||||
"reinserted": outcome.reinserted,
|
||||
"date_skipped": outcome.date_skipped,
|
||||
|
||||
@@ -47,7 +47,11 @@ def run_schedule(task_id: int):
|
||||
triggered_by_user_id=getattr(user, 'id', None),
|
||||
)
|
||||
if not created:
|
||||
raise ConflictError('该排程正在等待或执行中,请等待完成后再试', details={'run_id': run.id})
|
||||
raise ConflictError(
|
||||
'该排程正在等待或执行中,请等待完成后再试',
|
||||
code='SCHEDULE.RUN_ALREADY_ACTIVE',
|
||||
details={'run_id': run.id},
|
||||
)
|
||||
fresh = db.session.get(ScheduleRun, run.id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
|
||||
Reference in new issue
Block a user