feat(in-transit-transfer): 落地证据流重解析并纳入货代与排程配套改动

外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-22 00:48:37 +08:00
1 parent 911afa0f73
commit 4c2a7e2a23
145 files changed
+11695 -4214

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
DEBUG_SERVER_URL=http://127.0.0.1:7778/event
DEBUG_SESSION_ID=login-401
@@ -1,2 +0,0 @@
{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "A", "location": "src/main.ts:8", "msg": "[DEBUG] Frontend bootstrap started", "data": {"href": "http://192.168.100.192:8910/config"}, "ts": 1788828493927}
{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "C", "location": "src/main.ts:16", "msg": "[DEBUG] Vue app mounted", "data": {"appChildren": 1}, "ts": 1788828493938}
+456 -106
View File
@@ -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,
+5 -1
View File
@@ -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))
+15 -6
View File
@@ -529,11 +529,12 @@ class TransferMovementLedger(Base):
用途:外部系统入站(一期)/出站(结构就位,record_kind='outbound')记录统一落档;
匹配明细(items)由匹配创建时从档圈定生成(落地不再写 items,出生翻转)。
幂等增量落地:自然键 (source_code, record_kind, doc_no, line_no, line_seq,
in_out_flag, carton_id, lot_no) 唯一约束去重——不存在则插入、证据变化则原行
更新、文件缺席不删(tt14 扩维:真实 WMS 行身份=单据+行+箱/批,carton_id/
lot_no 加入键防同箱/批塌缩丢行;R7 终审:两列同步 NOT NULL + default '',
nullable 成分的 NULL 不参与 PG/SQLite 唯一比对会逃逸约束,空值成分一律以
空串入库保证唯一约束可比);
in_out_flag, carton_id, lot_no, external_doc_no, external_line_no) 唯一约束
去重——不存在则插入、证据变化则原行更新、文件缺席不删(tt14 扩维:真实 WMS
行身份=单据+行+箱/批,carton_id/lot_no 加入键防同箱/批塌缩丢行;R7 终审:
两列同步 NOT NULL + default '',nullable 成分的 NULL 不参与 PG/SQLite 唯一
比对会逃逸约束,空值成分一律以空串入库保证唯一约束可比;2026-10-21 再扩维:
外部单号/外部项次=WMS Order #/Line # 入键,外部单据身份作为档幂等主键管控);
已执行记录 transfer_executed=true 封存(executed_doc_no 回写),永不更新、
永不复活、永不再次被圈定(防二次调拨,档级封存兜底)。
刻意双字段:record_kind(文件种类声明,权威)与 in_out_flag(数据列原值),
@@ -555,9 +556,13 @@ class TransferMovementLedger(Base):
# 自然键唯一(幂等增量落地兜底;应用层按自然键查档先行)。tt14 扩维 8 成分:
# carton_id/lot_no 进键(真实 WMS 行身份=单据+行+箱/批),R7 终审同步
# NOT NULL + default ''(可空成分以空串入库,防 PG NULL 逃逸唯一比对)。
# 2026-10-21 扩维 10 成分:external_doc_no/external_line_no(外部单号/
# 外部项次,WMS Order #/Line #)进键——外部单据身份作为档幂等主键管控,
# 同一外部单号+项次的重复落档/证据更新收敛到同一档行(存量行以空串参与
# 键;配置外部映射后重放同文件即按新键收敛,必要时走清空并重解析重建)。
UniqueConstraint(
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
'carton_id', 'lot_no',
'carton_id', 'lot_no', 'external_doc_no', 'external_line_no',
name='uq_transfer_movement_ledger_natural_key',
),
# 匹配创建圈档主路径:来源 + 记录种类 + 异动日期范围扫描。
@@ -573,6 +578,10 @@ class TransferMovementLedger(Base):
line_seq: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
# 数据列原值(入站=收发标记),与 record_kind 交叉校验用,不参与权威判定。
in_out_flag: Mapped[str] = mapped_column(String(8), nullable=False, default='', server_default='')
# --- A+ 外部单据身份(2026-10-21 起入自然键:外部单号/外部项次 = WMS Order #/
# --- 行号;NOT NULL + default '' 与 line_seq 同口径,防 NULL 逃逸唯一比对)---
external_doc_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
external_line_no: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
# --- B 物料与数量(数量 Decimal 文本,与 items.movement_quantity 同约定)---
material_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
material_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
@@ -141,9 +141,20 @@ def validate_rpa_callback_not_replayed(task: Any, run_no: str) -> str | None:
return None
def validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callback_run_no: str) -> str | None:
def validate_schedule_batch_callback_run_no(
schedule_run_id: int | None,
callback_run_no: str,
*,
require_awaiting: bool = True,
) -> str | None:
"""校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。
Args:
schedule_run_id: 排程 run 主键;None 表示非排程回调,直接通过。
callback_run_no: Worker 上报的 batch_run_no / run_no。
require_awaiting: True(进度/收件终态)要求仍处于 awaiting_rpa;
False(解析 Job)只校验身份,允许排程已按「文件返回」终态化。
Returns:
None 校验通过;否则返回拒绝原因码(schedule_run_not_found / schedule_run_no_missing /
schedule_run_no_mismatch / schedule_run_not_awaiting)。
@@ -159,6 +170,8 @@ def validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callbac
return "schedule_run_no_missing"
if provided != expected:
return "schedule_run_no_mismatch"
if not require_awaiting:
return None
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != "running" or not summary.get("awaiting_rpa"):
return "schedule_run_not_awaiting"
@@ -22,10 +22,12 @@
(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 / list_outbound_configured_source_codes)
——供 in_transit_transfer 收敛为「只按 source_code / file_id 读取」的只读函数消费面。
方案(get_inbound_parsing_profile / get_outbound_parsing_profile)、失效文件
存在性(has_expired_inbound_file)、重建通道归档清单
(list_reparseable_inbound_files / list_reparseable_outbound_files)、入站/
出站可用站点编码清单(list_inbound_configured_source_codes /
list_outbound_configured_source_codes)——供 in_transit_transfer 收敛为
「只按 source_code / file_id 读取」的只读函数消费面。
mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。
"""
@@ -44,6 +46,7 @@ from app.models import (
FreightRpaInboundReportFile,
FreightRpaOnhandReportConfig,
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaSource,
)
from app.services.file_assets.storage import file_asset_storage
@@ -427,6 +430,34 @@ def get_inbound_parsing_profile(source_code: str) -> InboundProfileView | None:
)
def get_outbound_parsing_profile(source_code: str) -> InboundProfileView | None:
"""按 source_code 返回出站配置绑定的解析方案只读视图(与入站同形)。
用途:调拨出站运行期落档(outbound_evidence_sync)与清空重建
(backlog_reparse_service record_kind=outbound)读取出站文件解析规则。
核心逻辑:站点 → 出站配置 → 配置绑定的解析方案,任一环节缺失返回 None;
不校验 status/purpose(调用方按场景自行 fail-closed)。
Args:
source_code: 站点实例编码。
Returns:
InboundProfileView(字段同入站方案视图);无配置/未绑定/方案缺失返回 None。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
config = site.outbound_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(
@@ -507,6 +538,56 @@ def list_reparseable_inbound_files(source_code: str, *, now: datetime | None = N
return [_inbound_file_view(report) for report in reports]
def _outbound_file_view(report: FreightRpaOutboundReportFile) -> InboundFileView:
"""出站归档 → 与入站同形的只读视图(重建/投影消费面字段对齐)。"""
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 list_reparseable_outbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]:
"""维护通道:列出某来源全部可重建出站归档(未删除 + 未过保留期),不设当日门禁。
用途:调拨待匹配桶「清空并重新解析」出站流(backlog_reparse_service
record_kind=outbound)按来源取重建清单;与 list_reparseable_inbound_files
同口径,禁止与运行期 latest_usable_outbound_file 混用。
核心逻辑:经出站执行单元行 source_code 过滤;【无当日门禁】;保留期口径
archive_expires_at 为空视为长期有效;按 created_at/id 升序。
Args:
source_code: 来源实例编码。
now: 保留期判定时刻;缺省当前 UTC。
Returns:
InboundFileView 列表(created_at 升序;无可重建归档为空表)。
"""
now = now or datetime.utcnow()
reports = (
FreightRpaOutboundReportFile.query
.join(FreightRpaOutboundReportFile.unit_run)
.filter(
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
or_(
FreightRpaOutboundReportFile.archive_expires_at.is_(None),
FreightRpaOutboundReportFile.archive_expires_at > now,
),
)
.order_by(
FreightRpaOutboundReportFile.created_at.asc(),
FreightRpaOutboundReportFile.id.asc(),
)
.all()
)
return [_outbound_file_view(report) for report in reports]
def list_inbound_configured_source_codes() -> list[str]:
"""列出已配置入站报表的启用站点编码(调拨排程缺省执行范围)。
@@ -661,4 +742,61 @@ def clear_inbound_parse_failure(file_id: int) -> None:
report.parse_failed_at = None
report.parse_error_code = None
report.parse_error_message = None
db.session.flush()
db.session.flush()
def mark_outbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None:
"""标记一份出站归档文件解析失败(写入解析失败三分层列;与入站同名函数对称)。
用途:出站归档文件解析(schema/字段校验)失败时把失败事实落到文件上,
使来源出站流状态投影为 parse_failed、阻止下游当作 ready 使用
(resolve_source_file_status(record_kind='outbound') 同一投影顺序)。
核心逻辑:与 mark_inbound_parse_failure 同款(错误码截 64/错误信息截
2000/flush 不 commit——事务归属调用方),仅目标表为
FreightRpaOutboundReportFile。
Args:
file_id: 出站归档文件主键(须已入库)。
error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
Returns:
None。失败标记随调用方事务落库。
Raises:
NotFoundError: file_id 对应的出站归档文件不存在。
"""
report = db.session.get(FreightRpaOutboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Outbound 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_outbound_parse_failure(file_id: int) -> None:
"""清除一份出站归档文件的解析失败标记(三列置空),投影恢复 ready。
用途:同一出站文件重新解析成功后调用;不要在文件已被清理/过期后调用
(无业务意义)。与 clear_inbound_parse_failure 同款,仅目标表为
FreightRpaOutboundReportFile。
Args:
file_id: 出站归档文件主键(须已入库)。
Returns:
None。清除随调用方事务落库。
Raises:
NotFoundError: file_id 对应的出站归档文件不存在。
"""
report = db.session.get(FreightRpaOutboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Outbound 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()
@@ -1,36 +1,22 @@
"""services/in_transit_transfer/backlog_reparse_service.py
用途:待匹配桶「清空并重新解析」(spec §6/D7,维护链路)——解析规则修改后,
按来源把旧映射档行清空、以当前绑定入站解析规则重解析全部可重建归档、
走常规 sync_ledger_rows 幂等重落;另提供只读预检供确认弹窗展示。
依赖:movement_file_repository(list_reparseable_archived_files 维护通道 +
_extract_movement_rows 归档字节提取)、evidence_sync.parse_archive_to_ledger_rows
(解析+组装单一口径)与 _detect_natural_key_collapses/_natural_key_collapse_event
(档自然键坍缩守卫与运行期同口径复用)、ledger_sync(sync_ledger_rows /
RECORD_KIND_INBOUND / FileMeta)、matching_service._effective_occupancy_filter
(占用排除口径,只读引用)、freight_rpa.reports.queries(站点与入站解析方案
只读入口——阶段 B Task 4 收敛)、file_asset_storage、audit。
逻辑:桶数据 100% 可由 MinIO 归档重建(原件长期保留 + 档行 sheet/row_no 溯源),
清空不是破坏性操作而是「从证据重建」。安全不变量:先全量预解析入内存,
按来源 + 记录类型(inbound/outbound)把旧映射档行清空、以当前绑定解析规则
重解析全部可重建归档、走常规 sync_ledger_rows 幂等重落;另提供只读预检供
确认弹窗展示。
依赖:movement_file_repository(ReparseableArchiveFile + _extract_movement_rows)、
evidence_sync.parse_archive_to_ledger_rows(解析+组装单一口径)与
_detect_natural_key_collapses/_natural_key_collapse_event、ledger_sync
(sync_ledger_rows / RECORD_KIND_* / FileMeta / movement_file_version)、
matching_service.
_effective_occupancy_filter、freight_rpa.reports.queries(站点与入站/出站
解析方案、可重建归档清单)、file_asset_storage、audit。
逻辑:桶数据 100% 可由 MinIO 归档重建。安全不变量:先全量预解析入内存,
任一归档解析失败 → 整体中止 AppError(TRANSFER.REPARSE_PARSE_FAILED),
一行不删——解析阶段只读,删除永远发生在全部文件解析成功之后。
删除范围三重过滤(分辨率裁决 #2):source_code + record_kind=inbound +
transfer_executed=false + 未被有效 items 占用 + source_file_id ∈ 可重建
归档;证据缺失行(归档已清理/过保留期/无溯源)保留并计入
kept_unrebuildable。删除前同事务把指向待删集合的 items 的 ledger_record_id
置 NULL(R9/方案 D:该列是普通 FK 无 ondelete,已取消匹配/已隔离 items 的
陈旧引用会让 PG flush 撞 IntegrityError 且此后每次重建复发;置空范围严格
限于待删集合——有效占用行的 items 不受影响,仅损失已废弃行的溯源装饰),
计数入审计 payload unlinked_items。重落按归档时间升序逐文件
sync_ledger_rows(FileMeta 带真实 source_file_id/file_version/sha256),
commit 在本服务内做一次(提交归属模式同
evidence_sync.sync_and_commit_for_callback)。审计事件
TRANSFER_PENDING_MATCH_REPARSED:operator/source_code/files 概要/profile
code+version/cleared/reinserted/date_skipped/kept/unlinked_items/collapses;
坍缩键另逐条落 ledger_natural_key_collapse(与运行期 evidence_sync 同构造)。
与运行期(evidence_sync)的边界:运行期取数带「当日 fail-closed」门禁且
缺席不删;本服务是显式的历史重建通道,仅管理端「清空并重新解析」动作
触发,禁止在运行期收料落地链路调用。
一行不删。删除范围:source_code + record_kind + transfer_executed=false +
未被有效 items 占用 + source_file_id ∈ 可重建归档。入站/出站分流仅体现在
规则门禁(published purpose)、归档清单表与落档 record_kind;其余步骤同源。
commit 在本服务内做一次。审计 TRANSFER_PENDING_MATCH_REPARSED 含 record_kind。
"""
from __future__ import annotations
@@ -42,12 +28,15 @@ from typing import Any
from sqlalchemy import func
from app import db
from app.core.errors import AppError
from app.core.errors import AppError, ValidationError
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_outbound_parsing_profile,
get_site,
list_reparseable_inbound_files,
list_reparseable_outbound_files,
)
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.evidence_sync import (
@@ -57,23 +46,20 @@ from app.services.in_transit_transfer.evidence_sync import (
)
from app.services.in_transit_transfer.ledger_sync import (
RECORD_KIND_INBOUND,
RECORD_KIND_OUTBOUND,
FileMeta,
movement_file_version,
sync_ledger_rows,
)
from app.services.in_transit_transfer.matching_service import _effective_occupancy_filter
from app.services.in_transit_transfer.movement_file_repository import (
ReparseableArchiveFile,
ShippingInboundFileRepository,
_extract_movement_rows,
)
# 审计事件 kind(任务简报冻结字面量;仓库事件 kind 无集中常量表,行内常量惯例
# ——ledger_sync.LEDGER_CROSS_CHECK_EVENT 同款)。
REPARSE_EVENT = "TRANSFER_PENDING_MATCH_REPARSED"
# 重建中止错误码(走通用兜底文案,不新增四语言 errors.json 键——参照
# TRANSFER.MOVEMENT_DATE_RANGE_INVALID 先例):覆盖「任一归档解析失败」与
# 「无已发布入站解析规则(无重建通道)」两类中止。
REPARSE_PARSE_FAILED = "TRANSFER.REPARSE_PARSE_FAILED"
_RECORD_KINDS = frozenset({RECORD_KIND_INBOUND, RECORD_KIND_OUTBOUND})
@dataclass(frozen=True)
@@ -82,17 +68,13 @@ class ReparseOutcome:
Args:
source_code: 来源实例编码。
cleared: 删除的旧映射档行数(三重过滤口径)。
reinserted: 重落新插入档行数(各文件 sync_ledger_rows inserted 之和)。
date_skipped: 重落时异动日期空值被滤行数(六分类透传,常规为 0)。
kept_unrebuildable: 证据缺失保留行数(不可重建,原样留存)。
unlinked_items: 删除前被置空 ledger_record_id 的废弃 items 数(R9)。
collapses: 重落批内档自然键坍缩键数(同键异料号,第二料号行被吞——
与运行期 evidence_sync 同一守卫口径,改模板重建恰是坍缩易发时刻)。
files: 逐文件概要(file_id/sha256/archived_at/inserted,归档时间升序)。
record_kind: inbound 或 outbound。
cleared / reinserted / date_skipped / kept_unrebuildable / unlinked_items /
collapses / files: 同入站重建语义。
"""
source_code: str
record_kind: str = RECORD_KIND_INBOUND
cleared: int = 0
reinserted: int = 0
date_skipped: int = 0
@@ -102,55 +84,73 @@ class ReparseOutcome:
files: tuple[dict, ...] = field(default_factory=tuple)
def _load_published_inbound_profile(source_code: str):
"""加载来源当前绑定的「已发布 inbound」解析规则(与运行期取数同口径)。
def _normalize_record_kind(record_kind: str | None) -> str:
"""规范化记录类型;非法值 fail-closed。"""
kind = str(record_kind or RECORD_KIND_INBOUND).strip() or RECORD_KIND_INBOUND
if kind not in _RECORD_KINDS:
raise ValidationError(
"record_kind must be inbound or outbound",
details={"record_kind": kind},
)
return kind
核心逻辑:来源(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 消费面不变)。
def _load_published_profile(source_code: str, record_kind: str):
"""加载来源当前绑定的「已发布」解析规则(与运行期取数同口径)。
核心逻辑:来源 enabled → 入站/出站配置绑定方案;须 published 且
purpose 等于 record_kind。
Args:
source_code: 来源实例编码。
record_kind: inbound 或 outbound。
Returns:
InboundProfileView;无启用来源/无入站配置/规则缺失或
非 published inbound 时返回 None(=无重建通道)。
解析方案视图;无通道时 None。
"""
site = get_site(source_code)
if site is None or not site.enabled:
return None
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != "published" or profile.purpose != "inbound":
if record_kind == RECORD_KIND_OUTBOUND:
profile = get_outbound_parsing_profile(source_code)
else:
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != "published" or profile.purpose != record_kind:
return None
return profile
def _list_reparseable_files(
source_code: str, now: datetime, record_kind: str,
) -> list[ReparseableArchiveFile]:
"""按记录类型列出可重建归档,映射为维护契约 ReparseableArchiveFile。"""
if record_kind == RECORD_KIND_OUTBOUND:
views = list_reparseable_outbound_files(source_code, now=now)
else:
views = list_reparseable_inbound_files(source_code, now=now)
return [
ReparseableArchiveFile(
file_id=view.file_id,
storage_key=view.storage_key,
sha256=view.sha256,
file_version=movement_file_version(view.sha256),
archived_at=view.created_at,
original_filename=view.original_filename,
)
for view in views
]
def _partition_deletable(
source_code: str, files: list[ReparseableArchiveFile],
source_code: str,
files: list[ReparseableArchiveFile],
record_kind: str,
) -> tuple[list[TransferMovementLedger], list[TransferMovementLedger]]:
"""把「未封存且未被占用」的 inbound 档行按证据可得性分成 可删/证据缺失 两组。
删除候选三重过滤(分辨率裁决 #2):source_code + record_kind=inbound +
transfer_executed=false + 未被有效 items 占用(复用
matching_service._effective_occupancy_filter 的 NOT EXISTS 口径,只读引用);
其中 source_file_id ∈ 可重建归档者为「可删可重建」,其余(归档已清理/
过保留期/无溯源)为「证据缺失保留」。preview 与执行共用本口径,保证
clearable_rows/kept_rows 与 cleared/kept_unrebuildable 1:1。
Args:
source_code: 来源实例编码。
files: list_reparseable_archived_files 产物(可重建归档清单)。
Returns:
(candidates, deletable)——candidates=全部未封存未占用行,deletable=其中
证据可得(可删可重建)子集。
"""
"""把「未封存且未被占用」的指定 record_kind 档行按证据可得性分成两组。"""
available_ids = {record.file_id for record in files}
candidates = (
TransferMovementLedger.query.filter(
TransferMovementLedger.source_code == source_code,
TransferMovementLedger.record_kind == RECORD_KIND_INBOUND,
TransferMovementLedger.record_kind == record_kind,
TransferMovementLedger.transfer_executed.is_(False),
_effective_occupancy_filter(),
)
@@ -160,29 +160,25 @@ def _partition_deletable(
return candidates, deletable
def preview_pending_match_reparse(*, source_code: str, now: datetime) -> dict:
"""清空并重新解析预检(只读,确认弹窗数据源,spec §6 入口)。
def preview_pending_match_reparse(
*, source_code: str, now: datetime, record_kind: str = RECORD_KIND_INBOUND,
) -> dict:
"""清空并重新解析预检(只读;按 record_kind 分流入站/出站归档与档行)。
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」确认弹窗展示预检结果
时调用;不要在运行期收料落地链路调用(运行期走 evidence_sync,当日语义)。
files[].rows 预估口径(分辨率裁决 #5,取实现简单者):现有档行按
source_file_id 计数近似(含封存/占用行),不在预检里解析归档字节——预检
只读零副作用,行数仅供弹窗展示,精确值以执行结果为准。
时调用;不要在运行期落地链路调用。
Args:
source_code: 来源实例编码。
now: 保留期判定时刻(与执行时刻口径一致)。
now: 保留期判定时刻。
record_kind: inbound(默认,兼容旧调用)或 outbound。
Returns:
{files: [{archived_at, sha256, rows}(归档时间升序)],
profile: {code, version} | None,
clearable_rows: 可删可重建行数,
kept_rows: 证据缺失保留行数}
{record_kind, files, profile, clearable_rows, kept_rows}
"""
files = ShippingInboundFileRepository().list_reparseable_archived_files(source_code, now)
profile = _load_published_inbound_profile(source_code)
_candidates, deletable = _partition_deletable(source_code, files)
# 预估行数:现有档行按溯源文件计数(单查询分组;档行与归档文件多对一)。
kind = _normalize_record_kind(record_kind)
files = _list_reparseable_files(source_code, now, kind)
profile = _load_published_profile(source_code, kind)
_candidates, deletable = _partition_deletable(source_code, files, kind)
file_ids = [record.file_id for record in files]
counts: dict[int, int] = {}
if file_ids:
@@ -194,13 +190,14 @@ def preview_pending_match_reparse(*, source_code: str, now: datetime) -> dict:
)
.filter(
TransferMovementLedger.source_code == source_code,
TransferMovementLedger.record_kind == RECORD_KIND_INBOUND,
TransferMovementLedger.record_kind == kind,
TransferMovementLedger.source_file_id.in_(file_ids),
)
.group_by(TransferMovementLedger.source_file_id)
.all()
}
return {
"record_kind": kind,
"files": [
{
"archived_at": record.archived_at.isoformat(),
@@ -218,40 +215,44 @@ def preview_pending_match_reparse(*, source_code: str, now: datetime) -> dict:
}
def reparse_pending_match(*, source_code: str, operator: str, now: datetime) -> ReparseOutcome:
"""清空并重新解析一个来源的待匹配桶(spec §6;单事务,本函数提交)。
def reparse_pending_match(
*,
source_code: str,
operator: str,
now: datetime,
record_kind: str = RECORD_KIND_INBOUND,
) -> ReparseOutcome:
"""清空并重新解析一个来源指定记录类型的待匹配桶(单事务,本函数提交)。
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」动作调用;
禁止在运行期收料落地链路调用(运行期走 evidence_sync,当日语义)。
删除前置动作(R9/方案 D):指向待删集合的 items(已取消匹配/已隔离的废弃
行)先同事务置空 ledger_record_id 再删行——普通 FK 无 ondelete,不置空则
PG flush 撞 IntegrityError 且每次重建复发;有效占用行的 items 不受影响。
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」动作调用。
record_kind=outbound 时清出站档、用 purpose=outbound 规则与出站归档重建。
Raises:
AppError: TRANSFER.REPARSE_PARSE_FAILED——①无已发布入站解析规则
(无重建通道,删了装不回去故拒绝执行);②任一归档文件解析
失败。两种情况整体中止且未删除任何行(先解析后删除是本函数
的安全不变量;解析阶段只读,中止时不 rollback 不触碰调用方
事务状态)。
ValidationError: record_kind 非法。
AppError: TRANSFER.REPARSE_PARSE_FAILED——无已发布对应流解析规则,或
任一归档解析失败(整体中止且未删除任何行)。
"""
# [STEP 1] 重建通道与可重建文件清单(维护路径,无当日门禁;规则门禁与
# 运行期同口径——published inbound)。无规则=无重建通道,拒绝执行。
profile = _load_published_inbound_profile(source_code)
kind = _normalize_record_kind(record_kind)
# [STEP 1] 重建通道与可重建文件清单。
profile = _load_published_profile(source_code, kind)
if profile is None:
raise AppError(
code=REPARSE_PARSE_FAILED,
message=f"reparse aborted: no published inbound parsing profile (source={source_code})",
message=(
f"reparse aborted: no published {kind} parsing profile "
f"(source={source_code})"
),
http_status=422,
details={"source_code": source_code, "reason": "no_published_inbound_profile"},
details={
"source_code": source_code,
"record_kind": kind,
"reason": f"no_published_{kind}_profile",
},
)
repository = ShippingInboundFileRepository()
files = repository.list_reparseable_archived_files(source_code, now)
files = _list_reparseable_files(source_code, now, kind)
definition = profile.definition_json or {}
# [STEP 2] 全量预解析入内存(归档字节→原始行经仓库 _extract_movement_rows,
# 原始行→档行经 evidence_sync.parse_archive_to_ledger_rows 单一口径);
# 任一失败 → AppError 整体中止(此时未执行任何删除,一行未删)。
# [STEP 2] 全量预解析入内存;任一失败整体中止。
prepared: list[tuple[ReparseableArchiveFile, list[dict]]] = []
for record in files:
try:
@@ -263,13 +264,14 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
header_row_index=definition.get("header_row_index"),
)
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows)
except Exception as exc: # noqa: BLE001 —— 安全不变量:任何预解析异常都不得进入删除阶段
except Exception as exc: # noqa: BLE001 —— 安全不变量
raise AppError(
code=REPARSE_PARSE_FAILED,
message=f"reparse aborted: archive file failed to parse (source={source_code})",
http_status=422,
details={
"source_code": source_code,
"record_kind": kind,
"file_id": record.file_id,
"storage_key": record.storage_key,
"sha256": record.sha256,
@@ -278,17 +280,8 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
) from exc
prepared.append((record, assembled))
# [STEP 3] 删除可重建且未封存、未被有效 items 占用的 inbound 行;证据缺失
# 行保留(kept_unrebuildable 只计数,不动行)。
# [R9 解引用前置] 待删行的 items 解引用必须先于删除、同事务完成:
# transfer_movement_ledger.source_file_id 有 ondelete,但
# transfer_invoice_items.ledger_record_id 是普通 FK(无 ondelete)——已取消
# 匹配的 items 与 blocked_file_removed 隔离 items 仍持有该引用,直接删除会
# 在 PG flush 撞 IntegrityError,且该来源此后每次重建都撞同一堵墙。置空范围
# 严格限于待删集合:能指向待删行的 items 必然是已取消/已隔离的废弃行
#(被有效占用排除的行不在删除集,其 items 不受影响)——陈旧可匹配行是数据
# 正确性风险,置空仅损失已废弃行的溯源装饰(处置见审计 unlinked_items)。
candidates, deletable = _partition_deletable(source_code, files)
# [STEP 3] 删除可重建未占用行(先解引用废弃 items)。
candidates, deletable = _partition_deletable(source_code, files, kind)
kept_unrebuildable = len(candidates) - len(deletable)
deletable_ids = [row.id for row in deletable]
unlinked_items = 0
@@ -302,12 +295,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
db.session.delete(row)
db.session.flush()
# [STEP 4] 按归档时间升序逐文件 sync_ledger_rows 重落(FileMeta 带真实
# source_file_id/file_version/sha256;date_skipped 等六分类随 outcome 汇总)。
# [档自然键坍缩守卫·重建路径] 每文件批内复检与运行期 evidence_sync 同一口径:
# 同六成分键异料号(项次全空)→ 第二料号行必被幂等吞掉,行处理不变(首见为准)
# 但每个坍缩键写一条 ledger_natural_key_collapse 审计事件——静默吞行变显式
# 可观测;仅在该文件实际落档(inserted/updated)时记,防重放刷事件。
# [STEP 4] 按归档时间升序逐文件重落。
reinserted = 0
date_skipped = 0
collapses = 0
@@ -315,7 +303,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
for record, assembled in prepared:
outcome = sync_ledger_rows(
source_code=source_code,
record_kind=RECORD_KIND_INBOUND,
record_kind=kind,
parsed_rows=assembled,
file_meta=FileMeta(
source_file_id=record.file_id,
@@ -326,11 +314,12 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
)
reinserted += outcome.inserted
date_skipped += outcome.date_skipped
if (outcome.inserted or outcome.updated):
if outcome.inserted or outcome.updated:
file_collapses = _detect_natural_key_collapses(assembled)
for collapse in file_collapses:
db.session.add(_natural_key_collapse_event(
source_code=source_code, collapse=collapse))
source_code=source_code, collapse=collapse, record_kind=kind,
))
collapses += len(file_collapses)
file_summaries.append({
"file_id": record.file_id,
@@ -339,8 +328,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
"inserted": outcome.inserted,
})
# [STEP 5] 审计事件 + 单次 commit(提交归属模式同 evidence_sync 桥:调用方
# 不感知事务时机;payload=操作人/来源/文件概要/规则 code+version/前后计数)。
# [STEP 5] 审计 + commit。
db.session.add(build_transfer_audit_event(
event_type=REPARSE_EVENT,
aggregate_type="transfer_source",
@@ -352,6 +340,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
after={
"operator": operator,
"source_code": source_code,
"record_kind": kind,
"files": [
{"file_id": record.file_id, "sha256": record.sha256}
for record, _assembled in prepared
@@ -369,6 +358,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
db.session.commit()
return ReparseOutcome(
source_code=source_code,
record_kind=kind,
cleared=len(deletable),
reinserted=reinserted,
date_skipped=date_skipped,
@@ -4,14 +4,15 @@
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘;
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部入站记录,
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部出入站记录,
规格 §10/D16:只读清单 + 计数,不可勾选执行)。
依赖:models、status、matching_service(启用类型范围并集圈档)。
依赖:models、status、matching_service(待匹配全量圈档 + 启用类型范围并集)。
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
manually_closed / success / duplicate_success 永久排除。
待匹配桶=启用类型范围并集圈档(复用匹配创建的固定条件底座:inbound/
未封存/有异动日期/未被有效 items 占用——D17 占用判定一致),无 item_id
不可执行;匹配圈定后记录离开本桶,取消匹配释放后回归。
待匹配桶=成熟未占用的出入站全量(pending_ledger_query:未封存/有异动日期/
未被有效 items 占用/T−2,不按调拨类型范围过滤)。可匹配=启用类型范围并集,
供库存匹配卡计数,并给清单行打 matchable。无 item_id 不可执行;
匹配圈定后记录离开本桶,取消匹配释放后回归。
"""
from __future__ import annotations
@@ -26,6 +27,7 @@ from app import db
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer.matching_service import (
circle_ledger_records_scope_union,
pending_ledger_query,
)
from app.services.in_transit_transfer.status import TransferStatus
@@ -100,7 +102,11 @@ class PendingMatchRecordDTO:
material_name: Optional[str] = None
movement_date: Optional[str] = None
source_code: str = ""
# 档记录类型(inbound/outbound);前端「清空重解析」按行传入,避免出站行误清入站档。
record_kind: str = "inbound"
quantity: Optional[str] = None
# 当前启用类型范围并集罩得住。首页待匹配清单据此分出「当前可匹配」。
matchable: bool = False
@dataclass
@@ -113,8 +119,10 @@ class BacklogSummaryDTO:
warn_3d: int = 0
escalate_5d: int = 0
critical_7d: int = 0
# 首页第 4 张数字卡(D16):已落档尚未匹配的外部入站记录数。
# 首页「待匹配」卡:已落档、尚未匹配的成熟出入站记录数(不含类型范围)。
pending_match_count: int = 0
# 首页「匹配可调拨库存」卡:启用类型范围并集现在圈得住的记录数。
matchable_count: int = 0
@dataclass(frozen=True)
@@ -129,10 +137,13 @@ class BacklogPageDTO:
page_size: int
_PENDING_SEGMENTS = ("all", "matchable", "outside")
@dataclass(frozen=True)
class PendingMatchPageDTO:
"""「待匹配」桶分页结果(951 行级大池;圈档并集无法合成单查询,
计数在 Python 侧取 len,但序列化/传输只出当前页)。"""
"""「待匹配」桶分页结果。all/outside 走 SQL 计数与切片;
matchable 与 all 使用同一排序,只是 id 集合不同。"""
records: list[PendingMatchRecordDTO]
total: int
@@ -320,67 +331,93 @@ def list_backlog_page(
return BacklogPageDTO(items=_backlog_dtos(rows, current), total=total, page=page, page_size=page_size)
def list_pending_match_records() -> list[PendingMatchRecordDTO]:
"""首页待办看板「待匹配」桶清单(D16:已抓取尚未匹配的外部入站记录,只读)。
def _pending_match_dto(record, *, matchable_ids: set[int]) -> PendingMatchRecordDTO:
"""把档行投影成待匹配清单项,并标出是否落在启用类型范围并集内。
数据源=启用类型范围并集圈档(matching_service.circle_ledger_records_scope_union:
固定条件 inbound/未封存/有异动日期/未被有效 items 占用,与匹配创建圈档和 D17
占用判定同一实现)。数字变化口径:文件落地→涨;被匹配圈定→离开(占用);
取消匹配→回归(释放占用);执行成功→封存恒排除。
Args:
record: TransferMovementLedger 或带同名字段的行。
matchable_ids: circle_ledger_records_scope_union 的 id 集合。
Returns:
只读 PendingMatchRecordDTO。无 item_id。
"""
return PendingMatchRecordDTO(
ledger_record_id=record.id,
doc_no=record.doc_no,
material_code=record.material_code,
material_name=record.material_name,
movement_date=record.movement_date,
source_code=record.source_code,
record_kind=str(getattr(record, "record_kind", None) or "inbound"),
quantity=record.quantity,
matchable=record.id in matchable_ids,
)
def _matchable_ids() -> set[int]:
"""启用类型现在圈得住的档 id。无启用类型时为空集。"""
return {record.id for record in circle_ledger_records_scope_union()}
def list_pending_match_records(*, segment: str = "all") -> list[PendingMatchRecordDTO]:
"""首页待办看板「待匹配」桶清单(已抓取尚未匹配的外部异动记录,只读)。
数据源=pending_ledger_query:未封存、有异动日期、未被有效 items 占用、
movement_date ≤ T−2 的出入站记录,不按调拨类型范围过滤。
segment=matchable 只留启用类型范围并集;segment=outside 是其余已落档。
每行 matchable 标记并集成员,供清单把「当前可匹配」和其余行分开。
数字变化口径:文件落地→涨;被匹配圈定→离开(占用);取消匹配→回归;
执行成功→封存恒排除。停用类型只减少可匹配行,不把其余行移出本桶。
不可执行:记录尚未经匹配/库存核对(无 items),本桶仅提供只读清单与
「去匹配」引导,禁止任何勾选执行入口。
Args:
segment: all、matchable 或 outside。
Returns:
PendingMatchRecordDTO 列表(圈档稳定排序:异动日期 → 来源 → 单号 → id)。
Raises:
ValidationError: segment 不是上述三值。
"""
return [
PendingMatchRecordDTO(
ledger_record_id=record.id,
doc_no=record.doc_no,
material_code=record.material_code,
material_name=record.material_name,
movement_date=record.movement_date,
source_code=record.source_code,
quantity=record.quantity,
)
for record in circle_ledger_records_scope_union()
]
from app.core.errors import ValidationError
if segment not in _PENDING_SEGMENTS:
raise ValidationError("segment must be all, matchable, or outside")
matchable_ids = _matchable_ids()
rows = pending_ledger_query(matchable_ids=matchable_ids, segment=segment).all()
return [_pending_match_dto(record, matchable_ids=matchable_ids) for record in rows]
def list_pending_match_records_page(
*,
page: int = BACKLOG_PAGE_DEFAULT,
page_size: int = BACKLOG_PAGE_SIZE_DEFAULT,
segment: str = "all",
) -> PendingMatchPageDTO:
"""「待匹配」桶分页清单(2026-10-16 服务端分页;只读语义与全量版一致)。
"""「待匹配」桶分页清单(服务端分页;只读语义与全量版一致)。
圈档=启用类型范围并集(多类型逐范围圈取后按 id 去重,无法合成单查询),
故 total 在 Python 侧取 len;切片后仅当前页做 DTO 投影/序列化,
951 行级大池的响应规模从 O(桶) 降到 O(页)。
all 与 outside 按 SQL count/limit 切片,避免把整桶载入内存后再切页。
matchable 使用同一查询,只保留启用类型范围并集的 id。
Args:
page: 页码(1 起)。
page_size: 每页行数(1..100)。
segment: all、matchable 或 outside。
Returns:
PendingMatchPageDTO(records=当前页切片,total=桶全量计数)。
PendingMatchPageDTO(records=当前页切片,total=该段全量计数)。
Raises:
ValidationError: segment 不是上述三值。
"""
rows = circle_ledger_records_scope_union()
start = (page - 1) * page_size
from app.core.errors import ValidationError
if segment not in _PENDING_SEGMENTS:
raise ValidationError("segment must be all, matchable, or outside")
matchable_ids = _matchable_ids()
query = pending_ledger_query(matchable_ids=matchable_ids, segment=segment)
total = query.count()
rows = query.offset((page - 1) * page_size).limit(page_size).all()
return PendingMatchPageDTO(
records=[
PendingMatchRecordDTO(
ledger_record_id=record.id,
doc_no=record.doc_no,
material_code=record.material_code,
material_name=record.material_name,
movement_date=record.movement_date,
source_code=record.source_code,
quantity=record.quantity,
)
for record in rows[start:start + page_size]
],
total=len(rows),
records=[_pending_match_dto(record, matchable_ids=matchable_ids) for record in rows],
total=total,
page=page,
page_size=page_size,
)
@@ -403,7 +440,8 @@ def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
summary.escalate_5d += 1
elif item.aging_level == AGING_CRITICAL_7D:
summary.critical_7d += 1
# [待匹配桶计数(D16)] 与行桶相互独立:档记录尚无 items 不进任何行桶,
# 只有本计数可见(出生翻转后「抓到了没匹配」的唯一可见位)。
summary.pending_match_count = len(list_pending_match_records())
# [待匹配桶计数] 与行桶相互独立:成熟未占用的出入站全量。
# 可匹配计数是其中启用类型现在圈得住的子集,供库存匹配卡单独展示。
summary.pending_match_count = pending_ledger_query().count()
summary.matchable_count = len(_matchable_ids())
return summary
@@ -0,0 +1,171 @@
"""services/in_transit_transfer/current_file_reparse.py
用途:对当前最新可用入站/出站归档做一次本地重解析并落档(不触发 RPA)。
依赖:evidence_sync.sync_source_rows、outbound_evidence_sync.sync_outbound_source_rows、
source_file_status(latest_usable_outbound_file、resolve_source_file_status)、
freight_rpa.reports.queries(latest_usable_inbound_file、mark_inbound_parse_failure、
mark_outbound_parse_failure)、date_policy.business_date_now、deps.get_transfer_dependencies、
file_parser.MovementFileSchemaError、core.errors、flask.current_app(非 schema 失败记日志)。
逻辑:先确认可用归档与已发布规则门禁,再委托既有 sync_*_source_rows 落档并 commit;
schema 失败 rollback 后 mark 解析失败并单独 commit;无规则/无文件 fail-closed;
其他异常(含非 NO_PROFILE 的 AppError)rollback、记日志、不标 parse_failed,返回 ok=False。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from flask import current_app
from app import db
from app.core.errors import AppError, ValidationError
from app.services.freight_rpa.reports.queries import (
latest_usable_inbound_file,
mark_inbound_parse_failure,
mark_outbound_parse_failure,
)
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.deps import get_transfer_dependencies
from app.services.in_transit_transfer.evidence_sync import sync_source_rows
from app.services.in_transit_transfer.file_parser import MovementFileSchemaError
from app.services.in_transit_transfer.outbound_evidence_sync import sync_outbound_source_rows
from app.services.in_transit_transfer.source_file_status import (
latest_usable_outbound_file,
resolve_source_file_status,
)
_RECORD_KINDS = frozenset({"inbound", "outbound"})
@dataclass(frozen=True)
class CurrentReparseResult:
"""一次当前归档重解析的返回。"""
source_code: str
record_kind: str
ok: bool
file_status: str
file_id: int | None
inserted: int = 0
updated: int = 0
skipped: int = 0
sealed_skipped: int = 0
error_code: str | None = None
error_message: str | None = None
def reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult:
"""重解析该来源当前最新可用归档并提交。
核心逻辑:先取 latest usable 文件。没有文件抛 CURRENT_REPARSE_NO_FILE。
有文件则调用既有 sync_*_source_rows。返回 None 表示没有已发布规则,抛
CURRENT_REPARSE_NO_PROFILE,不写 parse_failed。结构错误回滚后 mark_*_parse_failure
并单独提交。其他异常(含非 NO_PROFILE 的 AppError,如存储不可用)只回滚、
记 TRANSFER_CURRENT_REPARSE_FAILED 日志,不标解析失败,返回 ok=False。
error_message 取异常 message,为空再退回 str(exc)。成功路径由 sync 函数里的
movement_file_version 写版本戳,本函数不拼 sha256: 前缀。
Args:
source_code: 来源实例编码。
record_kind: inbound 或 outbound。
now: 落档与新鲜度判定时刻。
Returns:
CurrentReparseResult。结构错误和其他落档异常(含非 NO_PROFILE 的 AppError)时 ok 为 False。
Raises:
ValidationError: record_kind 不是 inbound 或 outbound。
AppError: 仅 TRANSFER.CURRENT_REPARSE_NO_FILE 或 TRANSFER.CURRENT_REPARSE_NO_PROFILE,HTTP 422。
"""
kind = record_kind.strip()
if kind not in _RECORD_KINDS:
raise ValidationError("record_kind must be inbound or outbound")
if kind == "outbound":
file_view = latest_usable_outbound_file(source_code, now=now)
else:
file_view = latest_usable_inbound_file(source_code, now=now)
if file_view is None:
raise AppError(
code="TRANSFER.CURRENT_REPARSE_NO_FILE",
message="no usable archive file",
http_status=422,
details={"source_code": source_code, "record_kind": kind},
)
file_id = file_view.file_id
try:
if kind == "outbound":
outcome = sync_outbound_source_rows(source_code=source_code, now=now)
else:
outcome = sync_source_rows(
source_code=source_code,
deps=get_transfer_dependencies(),
business_date=business_date_now(),
now=now,
)
if outcome is None:
raise AppError(
code="TRANSFER.CURRENT_REPARSE_NO_PROFILE",
message="no published parsing profile",
http_status=422,
details={"source_code": source_code, "record_kind": kind},
)
db.session.commit()
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
return CurrentReparseResult(
source_code=source_code,
record_kind=kind,
ok=True,
file_status=str(status["file_status"]),
file_id=file_id,
inserted=outcome.inserted,
updated=outcome.updated,
skipped=outcome.skipped,
sealed_skipped=outcome.sealed_skipped,
)
except MovementFileSchemaError as exc:
db.session.rollback()
error_message = (getattr(exc, "message", "") or str(exc))[:2000]
error_code = exc.code
if kind == "outbound":
mark_outbound_parse_failure(
file_id, error_code=error_code, error_message=error_message)
else:
mark_inbound_parse_failure(
file_id, error_code=error_code, error_message=error_message)
db.session.commit()
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
return CurrentReparseResult(
source_code=source_code,
record_kind=kind,
ok=False,
file_status=str(status["file_status"]),
file_id=file_id,
error_code=error_code,
error_message=error_message,
)
except Exception as exc:
# 无已发布规则仍是 422;其余 AppError(存储不可用等)与普通异常同一失败分支。
if isinstance(exc, AppError) and exc.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE":
raise
db.session.rollback()
current_app.logger.exception(
"TRANSFER_CURRENT_REPARSE_FAILED source=%s kind=%s",
source_code,
kind,
)
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
error_message = (getattr(exc, "message", "") or str(exc))[:500]
return CurrentReparseResult(
source_code=source_code,
record_kind=kind,
ok=False,
file_status=str(status["file_status"]),
file_id=file_id,
error_code="TRANSFER.CURRENT_REPARSE_FAILED",
error_message=error_message,
)
@@ -1,13 +1,15 @@
"""在途调拨业务日期与日期解析。
用途:固定业务时区 Asia/Shanghai,统一 parse_date 归一化异动日期(ISO + DSV SSRS
美式 MM/DD/YYYY[ HH:MM:SS]);提供业务日换算与 UTC 存储窗口换算。
美式 MM/DD/YYYY[ HH:MM:SS]);提供业务日换算、UTC 存储窗口换算与可匹配
截止日(T−2)换算。
依赖:标准库 zoneinfo / datetime。
逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync
复用,避免各服务各自计算导致口径漂移。
【成熟度规则已退役 2026-10-16】数据无成熟属性——日期边界由调用方入参严格
给定(交互匹配=用户选择的范围;自动排程=任务 T−N 偏移参数);引擎只保留
「截止 ≤ 业务日期」的入参合法性与未来日期阻断(数据错误)。
【T−2 管控恢复 2026-10-21】T−2 之前的数据全部成熟,T−2 之后(T−1/当天/
未来)无成熟数据不可进入异动日期范围——matching_service 以
eligible_movement_date_to 卡控范围截止;未来日期阻断(数据错误)保留。
(2026-10-16 曾随成熟规则退役放开到「截止 ≤ 业务日期」,本次按业务口径收回。)
"""
from __future__ import annotations
@@ -17,6 +19,10 @@ from zoneinfo import ZoneInfo
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
# 可匹配截止滞后天数:T−2 之前数据全部成熟(与前端 transferDate.ts
# DEFAULT_LOOKBACK_DAYS 同口径,两侧须同步调整)。
MOVEMENT_DATE_MAX_LAG_DAYS = 2
# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。
_US_DATE_FORMATS = (
"%m/%d/%Y %H:%M:%S",
@@ -77,6 +83,22 @@ def business_date_now(moment: datetime | None = None) -> date:
return moment.astimezone(SHANGHAI_TZ).date()
def eligible_movement_date_to(business_date: date | str,
lag_days: int = MOVEMENT_DATE_MAX_LAG_DAYS) -> date:
"""返回可进入异动日期范围的截止日(业务日期 T − lag 天,默认 T−2)。
【AI 触发时机】matching_service 校验异动日期范围、或任何需要「最远可选到
哪天」的场景;与前端 transferDate.ts defaultMovementDate 同口径。
Args:
business_date: 当前业务日期 T。
lag_days: 截止滞后天数;缺省 MOVEMENT_DATE_MAX_LAG_DAYS。
Returns:
T − lag 天。
"""
return parse_date(business_date) - timedelta(days=lag_days)
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
@@ -101,10 +101,13 @@ def _assemble_ledger_rows(
核心逻辑:[STEP 1] 原始行按 (sheet, row_no) 建索引——ParsedMovementRow 无扩展
字段槽位(Task 8 事实),扩展 7 字段(line_no/line_seq/in_out_flag/order_type/
odm_*/carton_id/pallet_id 及 🔖预留)从原始领域行 dict 取。[STEP 2] 按调拨明细
粒度 (doc_no, material_code, movement_date) 聚合:数量 Decimal 相加,其余字段
取组内首行,sheet_name/row_no 取首行——与旧 aggregate_invoices 汇总键一致,
保证翻转后严格数量比对(ASN 合计 vs ERP 账面)语义不变。
odm_*/carton_id/pallet_id 及 🔖预留)与外部单据身份(external_doc_no/
external_line_no,2026-10-21 扩展)从原始领域行 dict 取。[STEP 2] 按调拨明细
粒度 (doc_no, material_code, movement_date, 外部单号, 外部项次) 聚合:数量
Decimal 相加,其余字段取组内首行,sheet_name/row_no 取首行——与旧 aggregate_
invoices 汇总键一致,保证翻转后严格数量比对(ASN 合计 vs ERP 账面)语义不变;
外部单据身份入聚合键(2026-10-21):不同 WMS 单号/项次的行不得数量相加折叠
(外部身份是档自然键成分,折叠即丢行)。
注意:原始行无「项次」且同单号多料号时,自然键 (doc_no, line_no='', ...,
carton_id 等值, lot_no 等值) 会折叠多料号行为一条档记录(档自然键不含料号,
规格 §4.2;carton_id/lot_no 为键成分,批内等值才折叠)——真实 WMS 导出
@@ -124,11 +127,14 @@ def _assemble_ledger_rows(
continue
raw_by_key[(str(raw.get("sheet") or "").strip(), raw.get("row_no"))] = raw
groups: dict[tuple[str, str, str], dict] = {}
groups: dict[tuple[str, str, str, str, str], dict] = {}
ordered: list[dict] = []
for row in parsed:
raw = raw_by_key.get((row.sheet, row.row_no)) or {}
key = (row.invoice_no, row.material_no, row.movement_date.isoformat())
# 聚合键含外部单据身份(2026-10-21):不同外部单号/项次不折叠、不数量相加。
key = (row.invoice_no, row.material_no, row.movement_date.isoformat(),
_natural_key_text(raw.get("external_doc_no")),
_natural_key_text(raw.get("external_line_no")))
group = groups.get(key)
if group is None:
group = {
@@ -151,6 +157,10 @@ def _assemble_ledger_rows(
"odm_name": str(raw.get("odm_name") or "").strip(),
"carton_id": str(raw.get("carton_id") or "").strip(),
"pallet_id": str(raw.get("pallet_id") or "").strip(),
# 外部单据身份(2026-10-21 扩展:外部单号/外部项次=WMS Order #/
# 行号)——异动档自然键成分(档幂等主键管控),缺列按空串落键。
"external_doc_no": str(raw.get("external_doc_no") or "").strip(),
"external_line_no": str(raw.get("external_line_no") or "").strip(),
# 🔖预留列(出货报告确认后直接映射):入站侧照常透传原值。
"doc_nature": str(raw.get("doc_nature") or "").strip(),
"movement_type": str(raw.get("movement_type") or "").strip(),
@@ -190,9 +200,10 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
"""检测批内档自然键坍缩(终审 I3,纯函数不改行)。
【AI 触发时机】sync_source_rows 组装落档前调用;不要在匹配/执行链路调用。
判定:档自然键行级六成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
lot_no)(source_code/record_kind 整批恒定不入键;carton_id/lot_no 随 tt14
键扩维入检——两列批内等值才可能与既有档行同键)批内出现 ≥2 行且 material_code
判定:档自然键行级八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
lot_no, external_doc_no, external_line_no)(source_code/record_kind 整批恒定
不入键;carton_id/lot_no 随 tt14 键扩维入检;外部单据身份随 2026-10-21 键
扩维入检——批内等值才可能与既有档行同键)批内出现 ≥2 行且 material_code
不同 → 该键坍缩(落地侧第二料号行必被幂等吞掉)。同料号多行不算坍缩(数量
聚合合法形态,且规格 §4.2 判据即料号不同)。首见序返回,保证审计内容确定。
@@ -200,10 +211,10 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
rows: _assemble_ledger_rows 产物(成分已归一化)。
Returns:
坍缩键信息列表(仅含坍缩键):doc_no/line_no/line_seq/in_out_flag/
carton_id/lot_no + material_codes(首见序全量料号)+ dropped_material_codes
(首见后被吞料号)。
carton_id/lot_no/external_doc_no/external_line_no + material_codes
(首见序全量料号)+ dropped_material_codes(首见后被吞料号)。
"""
seen: dict[tuple[str, str, str, str, str, str], dict] = {}
seen: dict[tuple[str, ...], dict] = {}
for row in rows:
key = (
_natural_key_text(row.get("doc_no")),
@@ -212,6 +223,8 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
_natural_key_text(row.get("in_out_flag")),
_natural_key_text(row.get("carton_id")),
_natural_key_text(row.get("lot_no")),
_natural_key_text(row.get("external_doc_no")),
_natural_key_text(row.get("external_line_no")),
)
material = _natural_key_text(row.get("material_code"))
entry = seen.get(key)
@@ -225,6 +238,7 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
"doc_no": entry["key"][0], "line_no": entry["key"][1],
"line_seq": entry["key"][2], "in_out_flag": entry["key"][3],
"carton_id": entry["key"][4], "lot_no": entry["key"][5],
"external_doc_no": entry["key"][6], "external_line_no": entry["key"][7],
"material_codes": entry["materials"],
"dropped_material_codes": entry["dropped"],
}
@@ -232,20 +246,23 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
]
def _natural_key_collapse_event(*, source_code: str, collapse: dict):
def _natural_key_collapse_event(*, source_code: str, collapse: dict,
record_kind: str = RECORD_KIND_INBOUND):
"""构造档自然键坍缩审计事件(未落库,由调用方 add——build 契约同 ledger_sync)。
Args:
source_code: 来源实例编码(自然键成分,整批一致)。
collapse: _detect_natural_key_collapses 的单条坍缩键信息。
record_kind: 记录类型(入站/出站共用检测口径;聚合键与快照随流声明)。
Returns:
已计算 Hash 的 TransferAuditEvent(event_type=ledger_natural_key_collapse,
result='failure':数据质量降级——行被吞是既成事实,须运维介入核导出模板)。
"""
natural_key = "/".join((
source_code, RECORD_KIND_INBOUND,
source_code, record_kind,
collapse["doc_no"], collapse["line_no"], collapse["line_seq"], collapse["in_out_flag"],
collapse["carton_id"], collapse["lot_no"],
collapse["external_doc_no"], collapse["external_line_no"],
))
return build_transfer_audit_event(
event_type=LEDGER_NATURAL_KEY_COLLAPSE_EVENT,
@@ -256,10 +273,12 @@ def _natural_key_collapse_event(*, source_code: str, collapse: dict):
actor_type="system",
result="failure",
after={
"source_code": source_code, "record_kind": RECORD_KIND_INBOUND,
"source_code": source_code, "record_kind": record_kind,
"doc_no": collapse["doc_no"], "line_no": collapse["line_no"],
"line_seq": collapse["line_seq"], "in_out_flag": collapse["in_out_flag"],
"carton_id": collapse["carton_id"], "lot_no": collapse["lot_no"],
"external_doc_no": collapse["external_doc_no"],
"external_line_no": collapse["external_line_no"],
"material_codes": collapse["material_codes"],
"dropped_material_codes": collapse["dropped_material_codes"],
"resolution": "first_seen_wins",
@@ -10,7 +10,8 @@
(classify_quantity_match)、document_id、contracts、audit、status、
source_file_status、matching_service(门禁/scope/路由契约)、
jobs.queue(TRANSFER_RUN 入队)、models。
逻辑:防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按
逻辑:执行门禁与 worker 复核按档记录 record_kind 对证据文件 sha(无档回落入站)。
防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按
五元组建单,同组存在失败单则复用其单号/时间戳全量重跑(doc.run_id 改指新
Run,现任归属语义),存在 result_unknown/executing 单则阻断新行
(group_order_unresolved);部分唯一索引竞态以 SAVEPOINT + 复用重查重试
@@ -58,6 +59,8 @@ from app.services.in_transit_transfer.matching_service import (
RouteMapping,
TransferDeps,
_item_evaluated_sha,
_item_evidence_kind,
_latest_evidence_files,
item_external_lot_no,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
@@ -127,8 +130,9 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv
门禁:
① 存在且可执行:id 存在且 status == ready_to_execute,否则
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID")。
② 文件版本对账:行评估版本戳(_item_evaluated_sha)≠ 来源最新可用文件
sha(含来源无可用文件/行无版本戳)→ ValidationError(code="TRANSFER.FILE_CHANGED")。
② 文件版本对账:行评估版本戳(_item_evaluated_sha)≠ 该行证据流最新可用
文件 sha。证据流取档记录 record_kind,无档关联回落入站。来源无可用文件
或行无版本戳 → ValidationError(code="TRANSFER.FILE_CHANGED")。
[2026-09-25 TTL 退役] 原门禁②「行级新鲜度(updated_at 距 now 超过
confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」已删除:匹配 10 分钟后必被拒
@@ -178,20 +182,17 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv
)
items = [by_id[i] for i in ordered_ids]
# [门禁②] 文件版本对账(按去重来源投影最新可用文件,行评估 sha 必须一致)。
latest_files: dict[str, dict] = {
source_code: resolve_source_file_status(source_code=source_code)
for source_code in sorted({item.source_code for item in items})
}
# [门禁②] 文件版本对账:按 (来源, 档 record_kind) 投影最新证据文件,行评估 sha 必须一致。
latest_files = _latest_evidence_files(items, resolve=resolve_source_file_status)
changed = []
for item in items:
evaluated_sha = _item_evaluated_sha(item)
latest = latest_files.get(item.source_code) or {}
latest = latest_files.get((item.source_code, _item_evidence_kind(item))) or {}
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
changed.append(item.id)
if changed:
raise ValidationError(
"source inbound file changed since evaluation", code="TRANSFER.FILE_CHANGED",
"source evidence file changed since evaluation", code="TRANSFER.FILE_CHANGED",
details={"changed_item_ids": changed},
)
return items
@@ -551,15 +552,12 @@ def _recheck_gates(run: TransferRun, deps: TransferDeps) -> tuple[str, str] | No
status_machine.TransferStatus.READY_TO_EXECUTE.value,
)
]
latest_files: dict[str, dict] = {
source_code: resolve_source_file_status(source_code=source_code)
for source_code in sorted({item.source_code for item in items})
}
latest_files = _latest_evidence_files(items, resolve=resolve_source_file_status)
for item in items:
evaluated_sha = _item_evaluated_sha(item)
latest = latest_files.get(item.source_code) or {}
latest = latest_files.get((item.source_code, _item_evidence_kind(item))) or {}
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
return ("file_changed", "source inbound file changed since evaluation")
return ("file_changed", "source evidence file changed since evaluation")
return None
@@ -1,9 +1,10 @@
"""在途调拨异动文件字段/结构校验。
用途:校验异动文件必填列(单号/料号/异动日期/异动数量)、数量与日期合法性、
来源身份一致性,输出 ParsedMovementRow 供 Invoice 汇总。
用途:校验异动文件必填列(单号/异动日期/异动数量;料号为空的行静默跳过)、
数量与日期合法性、来源身份一致性,输出 ParsedMovementRow 供 Invoice 汇总。
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_inbound_quantity。
逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。
逻辑:必填缺失或非法值整行阻断并携带行号细节;料号空行跳过不管控不落档
(2026-10-21 CRANE/Lognet 出站报告实测);本模块不接触文件存储。
tt14 入站化后统一走 movement 契约字段(parse_movement_rows 单一入口,
旧字段投影链路已并入,无兼容层)。
"""
@@ -92,6 +93,9 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
warehouse_code 透传至 ParsedMovementRow.warehouse_code(inventory_match 源路由匹配键);
unit 原值透传至 ParsedMovementRow.unit(movement 契约第 11 字段,仅 trim,
空值不阻断解析——行级 missing_unit 阻断在匹配阶段);
external_doc_no/external_line_no(2026-10-21 扩展:外部单号/外部项次)经原始行
透传至落档组装(_assemble_ledger_rows 从原始行取扩展字段,解析行不设槽位),
作为异动档自然键成分承担档幂等主键管控;
storage_code 仍仅展示保留。旧字段名投影链路(tt14 前的直连列名解析)已并入
本函数(入站化,无兼容层),校验逻辑一致。
@@ -152,12 +156,15 @@ def _parse_rows(
if not sheet or not row_no:
_fail(errors, row_no=row_no, reason="missing_sheet_or_row_no")
continue
if not material_no:
# [料号空行跳过 2026-10-21] 料号为空=非可用异动行(CRANE/Lognet 出站
# 报告的说明行/占位行实测):不做必填管控、不进异动表,静默跳过——
# 与 _is_unusable_movement_row 同家族(跳过不阻断整文件)。其余必填
#(单号)管控不变,仅对有料号的行生效。
continue
if not invoice_no:
_fail(errors, row_no=row_no, reason="missing_invoice_no")
continue
if not material_no:
_fail(errors, row_no=row_no, reason="missing_material_no")
continue
row_source = str(row.get("source_code") or "").strip()
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
@@ -7,11 +7,15 @@
依赖:models/in_transit_transfer.TransferMovementLedger、audit.build_transfer_audit_event、
movement_contract.MOVEMENT_FIELDS(档列镜像取值的唯一字段来源)。不解析文件
(parsed_rows 由调用方/Task 11 接线从解析产物组装)、不查外部系统、零外部调用。
逻辑:落档前先滤 movement_date 空值行——空=未发生异动(未收 ASN/未发货订单行),
逻辑:file_version 戳由 movement_file_version 统一生成(sha256: 前缀按档列宽度截断),
入站仓库、出站落档、清空重建、匹配进度快照都调用它,禁止各处自行拼接。
落档前先滤 movement_date 空值行——空=未发生异动(未收 ASN/未发货订单行),
落档即幽灵行,计入 date_skipped(解析层已滤一轮,此处为映射无关第二道防线)。
规格 §5 五条幂等语义——①自然键 (doc_no, line_no, line_seq, in_out_flag,
carton_id, lot_no)(source_code/record_kind 整批恒定不入行内键;tt14 扩维
箱号/批号)查档不存在 → 插入(record_kind/溯源五列随行写入);②行
carton_id, lot_no, external_doc_no, external_line_no)(source_code/
record_kind 整批恒定不入行内键;tt14 扩维箱号/批号;2026-10-21 扩维外部
单据身份=外部单号+外部项次,作档幂等主键管控)查档不存在 → 插入
(record_kind/溯源五列随行写入);②行
file_sha256 与来件一致 → 跳过(完全不动行,不续 updated_at——档无 TTL,
无新鲜度概念);③证据变化 → 原行更新业务镜像列 + 换溯源(source_file_id/
file_version/file_sha256/sheet_name/row_no/updated_at);④文件缺席的档行
@@ -45,6 +49,12 @@ assert set(_MOVEMENT_CODES) <= {c.name for c in TransferMovementLedger.__table__
# record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。
INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"})
# 自然键 NOT NULL 成分(行级 8 成分;source_code/record_kind 整批恒定不入行内键):
# 镜像取值时缺值以空串落库(防 NULL 违反非空约束/逃逸唯一比对,与模型 default '' 同口径)。
_NOT_NULL_KEY_CODES: tuple[str, ...] = (
"doc_no", "line_no", "line_seq", "in_out_flag",
"carton_id", "lot_no", "external_doc_no", "external_line_no",
)
# 记录种类字面量:inbound=入站(ShippingInboundReport RPA 产物,shipping_notice 域术语保留);
# outbound=出站(出货侧结构就位)。
RECORD_KIND_INBOUND = "inbound"
@@ -69,6 +79,23 @@ class FileMeta:
file_sha256: str | None = None
def movement_file_version(sha256: str) -> str:
"""把文件 SHA-256 摘要打成异动档 file_version 戳。
核心逻辑:前缀 sha256: 加摘要后,按 TransferMovementLedger.file_version 列宽截断。
64 位摘要加前缀共 71 字符,超出 varchar(64) 时 PostgreSQL 会整批拒绝插入。
列宽取自模型,避免戳长和列定义各写一个 64。
Args:
sha256: 文件 SHA-256 十六进制摘要,不含前缀。
Returns:
以 sha256: 开头、长度不超过档列宽度的版本戳。
"""
limit = TransferMovementLedger.__table__.c.file_version.type.length
return f"sha256:{sha256}"[:limit]
@dataclass(frozen=True)
class LedgerSyncOutcome:
"""一次落档的结果计数(审计与兜底日志的数据源;字段名为冻结契约,顺序自 date_skipped 引入后不再承诺)。"""
@@ -105,7 +132,7 @@ def _cross_check_event(
*,
source_code: str,
record_kind: str,
key: tuple[str, str, str, str, str, str],
key: tuple[str, str, str, str, str, str, str, str],
sheet_name: str | None,
row_no: int | None,
file_meta: FileMeta,
@@ -114,16 +141,20 @@ def _cross_check_event(
Args:
source_code / record_kind: 来源实例编码与记录种类。
key: 自然键六成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
lot_no)(已归一化;箱号/批号随 tt14 键扩维入事件,保证矛盾行可唯一定位)。
key: 自然键八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
lot_no, external_doc_no, external_line_no)(已归一化;箱号/批号随
tt14 键扩维入事件,外部单据身份随 2026-10-21 键扩维入事件,保证
矛盾行可唯一定位)。
sheet_name / row_no: 行级溯源(入事件快照辅助定位来源行)。
file_meta: 来源文件证据三元组。
Returns:
已计算 Hash 的 TransferAuditEvent(event_type=ledger_cross_check_failed)。
"""
doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no = key
(doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
external_doc_no, external_line_no) = key
natural_key = "/".join((
source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
external_doc_no, external_line_no,
))
return build_transfer_audit_event(
event_type=LEDGER_CROSS_CHECK_EVENT,
@@ -136,6 +167,7 @@ def _cross_check_event(
"source_code": source_code, "record_kind": record_kind,
"doc_no": doc_no, "line_no": line_no, "line_seq": line_seq,
"in_out_flag": in_out_flag, "carton_id": carton_id, "lot_no": lot_no,
"external_doc_no": external_doc_no, "external_line_no": external_line_no,
"file_version": file_meta.file_version, "file_sha256": file_meta.file_sha256,
"sheet_name": sheet_name, "row_no": row_no,
},
@@ -189,12 +221,13 @@ def sync_ledger_rows(
counters["date_skipped"] = total_in - len(parsed_rows)
# [STEP 1] 只圈定批内 doc_no 的既有档行(含封存行——封存命中必须可见),按自然键
# 建索引;source_code/record_kind 整批恒定,键只留行级六成分(tt14 扩维:
# carton_id/lot_no——真实 WMS 行身份=单据+行+箱/批)。档「缺席不删、永不
# 删除」行数单调增长(评审 Important 修复):按 source+kind 全量水化会使每次
# 落地成本随历史线性膨胀(Task 11 接生产落地热路径),故追加 doc_no IN 批内
# 过滤——批外键本就查不到、不参与任何分支,语义与全量查询 100% 等价;
# in_([]) 空批由 SQLAlchemy 渲染恒假子句,安全。
# 建索引;source_code/record_kind 整批恒定,键只留行级八成分(tt14 扩维:
# carton_id/lot_no——真实 WMS 行身份=单据+行+箱/批;2026-10-21 扩维:
# external_doc_no/external_line_no——外部单据身份作档幂等主键管控)。档「缺席
# 不删、永不删除」行数单调增长(评审 Important 修复):按 source+kind 全量
# 水化会使每次落地成本随历史线性膨胀(Task 11 接生产落地热路径),故追加
# doc_no IN 批内过滤——批外键本就查不到、不参与任何分支,语义与全量查询 100%
# 等价;in_([]) 空批由 SQLAlchemy 渲染恒假子句,安全。
doc_nos = sorted({_key_text(raw.get("doc_no")) for raw in parsed_rows})
existing = (
TransferMovementLedger.query.filter_by(
@@ -204,12 +237,13 @@ def sync_ledger_rows(
.all()
)
by_key = {
(r.doc_no, r.line_no, r.line_seq, r.in_out_flag, r.carton_id, r.lot_no): r
(r.doc_no, r.line_no, r.line_seq, r.in_out_flag, r.carton_id, r.lot_no,
r.external_doc_no, r.external_line_no): r
for r in existing
}
# 同批自然键去重索引(首见为准):批内重复若不拦截,二次插入会撞
# uq_transfer_movement_ledger_natural_key 唯一约束炸 flush。
landed: dict[tuple[str, str, str, str, str, str], TransferMovementLedger] = {}
landed: dict[tuple[str, str, str, str, str, str, str, str], TransferMovementLedger] = {}
# [STEP 2] 逐行六分类:日期空 → 封存 → 跳过 → 插入/更新(矛盾标记随落档动作判定)。
for raw in parsed_rows:
@@ -219,7 +253,10 @@ def sync_ledger_rows(
in_out_flag = _key_text(raw.get("in_out_flag"))
carton_id = _key_text(raw.get("carton_id"))
lot_no = _key_text(raw.get("lot_no"))
key = (doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no)
external_doc_no = _key_text(raw.get("external_doc_no"))
external_line_no = _key_text(raw.get("external_line_no"))
key = (doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
external_doc_no, external_line_no)
sheet_name = _mirror_text(raw.get("sheet_name"))
row_no = _opt_int(raw.get("row_no"))
@@ -250,9 +287,16 @@ def sync_ledger_rows(
))
# [镜像取值] 业务值一律从领域行 dict 按契约 code 取(扩展字段无独立槽位);
# 自然键成分同源同值,插入/更新统一按全字段镜像写入(更新时键成分等值重写
# 为无操作,SQLAlchemy 等值列不入 UPDATE)。
mirror = {code: _mirror_text(raw.get(code)) for code in _MOVEMENT_CODES}
# 自然键 NOT NULL 成分缺值以空串落库(_key_text,防 NULL 违反非空约束/
# 逃逸唯一比对——2026-10-21 外部身份扩维时修复的潜在缺陷:此前镜像缺值
# 即 None,仅因各组装方恒给空串而未暴露)。自然键成分同源同值,插入/更新
# 统一按全字段镜像写入(更新时键成分等值重写为无操作,SQLAlchemy 等值列
# 不入 UPDATE)。
mirror = {
code: (_key_text(raw.get(code)) if code in _NOT_NULL_KEY_CODES
else _mirror_text(raw.get(code)))
for code in _MOVEMENT_CODES
}
if row is None:
# [插入] 自然键不存在:新档行,record_kind + 溯源五列随行写入。
row = TransferMovementLedger(
@@ -6,27 +6,26 @@
依赖:transfer_type(配置门禁)/ transfer_type_config_service(resolve_warehouse)/
scope_rules(圈档编译器)/ field_transforms(批号派生)/ ledger(档模型)/
source_file_status / capability_client / date_policy / quantity / contracts /
audit / models。【阶段 B Task 4】取可用入站归档文件的查询已删除并收口到
freight_rpa.reports.queries.latest_usable_inbound_file(匹配不再引用
freight_rpa 报表模型;证据链消费方见 evidence_sync)。
audit / models / evidence_sync(入站 ready 补落档)/
outbound_evidence_sync(出站 ready 补落档)/
ledger_sync.movement_file_version(进度快照的 file_version 戳)。【阶段 B Task 4】取可用入站
归档文件的查询已删除并收口到 freight_rpa.reports.queries;匹配不再引用
freight_rpa 报表模型。
逻辑:【2026-10-14 出生翻转(ADR 0001/D4/D17)】文件落地不再写 items——行由
本服务在匹配创建时从档圈定生成并「创建即绑定」匹配:固定条件(record_kind=
'inbound' + 来源 IN + movement_date 范围 + transfer_executed=false +
本服务在匹配创建时从档圈定生成并「创建即绑定」匹配:固定条件(record_kind
∈ record_kinds_of(类型.scope_rules);无类型对象的调用点显式 inbound +
来源 IN + movement_date 范围 + transfer_executed=false +
movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+
未被有效 items 占用(D17:不存在所属匹配未取消且未被失效隔离的 item 引用;
取消匹配即释放占用)。逐记录建 item(ledger_record_id 外键、业务字段=档
原值、movement_quantity=record.quantity、raw_lines 单行溯源);仓库经
resolve_warehouse 按类型定义(mapped/fixed)落 from/to;既有库存评估链
不变(继续以 items 为工作单元)。来源实例独立处理,任一来源失败不阻断
其他来源;【失败分层 2026-09-29】路由不可解析只落行级 blocked_route_not_
resolved;当天入站不查询 外部系统;匹配 Hash 从 scope_json 快照内容 +
business_date + file_snapshot 计算(无环境变量/全局态,2026-09-22 陷阱
根因防御);create_matching 先落 Run + Matching 再驱动管道(行出生即绑定
matching_id),末尾统一提交;restore 与可调拨明细按匹配自有 items 圈行
(行归属=匹配绑定,scope_item_query 已随翻转退役);
行交易单位(movement 契约第 11 字段 unit)只取 ERP 库存查询返回的
stock_unit(img09,单据字段以 ERP 为唯一来源,禁用货代文件单位列):
命中库存但 ERP 未给单位 → 行级 blocked_missing_unit;unit 不参与匹配 Hash。
未被有效 items 占用(D17:ledger_record_id 引用或同匹配 grain
(source, invoice/doc_no, material, movement_date) 已被有效 item 占用;
取消匹配即释放)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
空→有值的重解析双行);出生前按 grain 择一建 item(不累加数量,防翻倍),
占用亦按 grain 互斥。业务字段=档原值;仓库经 resolve_warehouse;库存评估
链以 items 为工作单元。create_matching 先落 Run + Matching 再驱动管道。
【确认匹配落档补齐 2026-10-20】UI ready≠档已写入:圈档前对所需流为 ready
的来源做幂等落档(入站 sync_source_rows / 出站 sync_outbound_source_rows,
只 flush 随主事务),补齐「回调落档桥未跑或部署前已就绪」的空档窗口;
parse_failed(入站/出站)均记 failed 进度,不阻断其他来源圈档。
"""
from __future__ import annotations
@@ -37,7 +36,7 @@ from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import Any, Protocol
from sqlalchemy import and_, or_
from sqlalchemy import and_, false, func, or_
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
@@ -57,6 +56,8 @@ from app.services.in_transit_transfer.contracts import (
RawLineRefDTO,
)
from app.services.in_transit_transfer.date_policy import (
business_date_now,
eligible_movement_date_to,
parse_date,
)
from app.services.in_transit_transfer.field_transforms import (
@@ -69,12 +70,13 @@ from app.services.in_transit_transfer.file_preparation import (
RpaTrigger,
ensure_inbound_file_ready,
)
from app.services.in_transit_transfer.ledger_sync import RECORD_KIND_INBOUND
from app.services.in_transit_transfer.ledger_sync import movement_file_version
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.scope_rules import (
ScopeRule,
apply_scope_filters,
parse_scope_rules,
record_kinds_of,
scope_rules_note,
)
from app.services.in_transit_transfer.source_file_status import (
@@ -91,6 +93,8 @@ from app.services.in_transit_transfer.transfer_type_config_service import (
)
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
# ready 流在圈档前补落档:与回调桥共用解析/落档实现,匹配路径只 flush 不 commit。
_CONFIRMABLE_SYNC_STATUSES = frozenset({"ready"})
# 明细结果值(对应 Invoice 项状态)
# 【RESULT_NOT_MATURED 已退役 2026-10-16】成熟概念删除(未上线不设兼容层)。
@@ -206,16 +210,18 @@ def _validate_movement_date_range(
) -> tuple[date | None, date | None]:
"""校验可选异动日期范围(纯校验无副作用;run_matching / create_matching 共用)。
【成熟规则已退役 2026-10-16】日期边界由调用方入参严格给定(交互=用户选择;
排程=任务 T−N 偏移参数),引擎只做入参合法性校验。
【T−2 成熟封顶 2026-10-21】T−2 之前的数据全部成熟(简化成熟边界,不回退
2026-10-16 退役决策——无成熟行级状态):范围截止不得晚于 T−2 可匹配截止日
(eligible_movement_date_to),T−1/当天/未来无成熟数据不可选;与前端选择器
上限(transferDate.ts defaultMovementDate)同口径。
Args:
business_date: 业务日期 T(未来日期阻断的基准)。
business_date: 业务日期 T(截止上限换算基准)。
movement_date_from / movement_date_to: 可选异动日期范围(约束明细 movement_date)。
Returns:
(range_from, range_to) 解析后的日期(未提供为 None)。
Raises:
ValidationError: 起始晚于截止,或截止晚于业务日期(未来日期无账可核)。
ValidationError: 起始晚于截止,或截止晚于 T−2 可匹配截止日。
"""
range_from = parse_date(movement_date_from) if movement_date_from else None
range_to = parse_date(movement_date_to) if movement_date_to else None
@@ -223,19 +229,76 @@ def _validate_movement_date_range(
raise ValidationError(
"movement date range is invalid", code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID",
)
if range_to and range_to > parse_date(business_date):
matured_date_to = eligible_movement_date_to(business_date)
if range_to and range_to > matured_date_to:
raise ValidationError(
"movement date range end is later than business date", code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID",
f"movement date range end is later than matured boundary {matured_date_to.isoformat()}",
code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID",
)
return range_from, range_to
def _item_grain_of_ledger(record: TransferMovementLedger) -> tuple[str, str, str, str]:
"""档记录对应的匹配明细 grain(与 uq_transfer_invoice_items_matching_grain 对齐)。
Args:
record: 库存异动档行。
Returns:
(source_code, doc_no/invoice_no, material_no, movement_date) 四元组。
"""
return (
str(record.source_code or ""),
str(record.doc_no or ""),
str(record.material_code or ""),
str(record.movement_date or ""),
)
def _prefer_ledger_for_item_grain(
current: TransferMovementLedger, candidate: TransferMovementLedger,
) -> TransferMovementLedger:
"""同 grain 多档择一:优先非空 carton_id(更完整自然键),再取更大 id(更新解析)。
不累加数量——同 grain 双行常见于重解析扩键(空 carton → 有 carton)的镜像分叉,
相加会翻倍;合法同文件多箱数量已在 evidence_sync 组装期按 grain 汇总。
"""
cur_carton = str(getattr(current, "carton_id", None) or "").strip()
cand_carton = str(getattr(candidate, "carton_id", None) or "").strip()
if bool(cand_carton) != bool(cur_carton):
return candidate if cand_carton else current
return candidate if int(candidate.id or 0) >= int(current.id or 0) else current
def _dedupe_ledger_records_for_item_birth(
records: list[TransferMovementLedger],
) -> list[TransferMovementLedger]:
"""出生前按 item grain 去重,避免撞 uq_transfer_invoice_items_matching_grain。
Args:
records: 圈档结果(可含同 grain 多档)。
Returns:
每 grain 一条档(稳定顺序:首次出现序,值已按 _prefer_ledger_for_item_grain 择优)。
"""
chosen: dict[tuple[str, str, str, str], TransferMovementLedger] = {}
order: list[tuple[str, str, str, str]] = []
for record in records:
grain = _item_grain_of_ledger(record)
if grain not in chosen:
chosen[grain] = record
order.append(grain)
continue
chosen[grain] = _prefer_ledger_for_item_grain(chosen[grain], record)
return [chosen[grain] for grain in order]
def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
"""构造「未被有效 items 占用」(D17)的 NOT EXISTS 过滤(圈档互斥单一口径)。
占用定义(规格 §9):存在任一 item 引用该档记录,且其所属匹配未取消、行未被
失效隔离(blocked_file_removed)。取消匹配(items→cancelled / 匹配→cancelled)
即释放占用;人工关闭/成功终态不释放(前者=业务裁定不拨;后者=档级封存)。
占用定义(规格 §9 + grain 互斥):存在有效 item(所属匹配未取消、行非
blocked_file_removed)且满足其一——(a) ledger_record_id 直指本档;
(b) 与本档同匹配 grain(source/invoice=doc_no/material/movement_date)。
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档,避免待匹配桶与二次
匹配仍圈到兄弟档。取消匹配即释放;人工关闭/成功终态不释放。
Args:
exclude_matching_id: 重查对账场景传入本匹配 id——本匹配自有 items 不构成
@@ -243,8 +306,22 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
Returns:
SQLAlchemy NOT EXISTS 子句(作用于 TransferMovementLedger 查询)。
"""
# material_code 可空:COALESCE 与出生侧 ``material_code or ""`` 对齐。
# grain 互斥只认「已绑定未取消匹配」的行——出生翻转前 matching_id=NULL 的
# 历史孤儿行不得按 grain 封死整票待匹配(本地曾因此从 ~2k 掉到 5)。
# ledger_record_id 直指占用仍含 NULL 归属行(保持 D17 原口径)。
grain_match = and_(
TransferInvoiceItem.matching_id.isnot(None),
TransferInvoiceItem.source_code == TransferMovementLedger.source_code,
TransferInvoiceItem.invoice_no == TransferMovementLedger.doc_no,
TransferInvoiceItem.material_no == func.coalesce(TransferMovementLedger.material_code, ""),
TransferInvoiceItem.movement_date == TransferMovementLedger.movement_date,
)
item_conditions = [
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
or_(
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
grain_match,
),
# 失效隔离行不占用(消失证据不可用,记录可被重新圈定修复)。
or_(TransferInvoiceItem.result_code.is_(None),
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
@@ -271,22 +348,40 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
return ~occupancy
def _circle_ledger_base_query(*, exclude_occupied_by_matching_id: int | None = None):
def _circle_ledger_base_query(
*,
record_kinds: tuple[str, ...],
exclude_occupied_by_matching_id: int | None = None,
matured_date_to: date | None = None,
):
"""圈档固定条件底座(匹配创建圈档/重查对账/首页待匹配桶共享的唯一实现)。
固定条件(规格 §6/§9):record_kind='inbound'(一期入站)、transfer_executed=false
(档级封存防二次执行——已执行记录永不再次被圈定)、movement_date 非空(可空
记录照常落档但不进异动日期圈定)、未被有效 items 占用(D17,见
_effective_occupancy_filter;取消匹配即释放占用)。
固定条件(规格 §6/§9):record_kind ∈ record_kinds(由调用方按类型范围规则
经 record_kinds_of 推导;没有类型对象时显式传入,禁止再把入站当隐式默认)、
transfer_executed=false(档级封存防二次执行——已执行记录永不再次被圈定)、
movement_date 非空(可空记录照常落档但不进异动日期圈定)、未被有效 items
占用(D17,见 _effective_occupancy_filter;取消匹配即释放占用)。
【T−2 成熟封顶 2026-10-21】matured_date_to 传入时只圈 movement_date ≤ T−2
的成熟记录(T−2 之前数据全部成熟;T−1/当天未成熟不匹配,留在档内待成熟后
自然进圈)。匹配创建圈档与首页待匹配桶传值;重查对账不传——对账只对既有
items 与档证据对齐,新增封顶会把存量未成熟行误判「档消失」走失效隔离。
【单一口径纪律】任何新的圈档消费方必须经本底座组合查询,禁止第三处手写
固定条件(双份维护=谓词漂移温床)。
Args:
record_kinds: 允许圈入的记录类型(inbound/outbound)。必传。
exclude_occupied_by_matching_id: 重查对账时排除本匹配占用;创建圈档不传。
matured_date_to: 可匹配截止日(eligible_movement_date_to 产物);None=不封顶。
"""
return TransferMovementLedger.query.filter(
TransferMovementLedger.record_kind == RECORD_KIND_INBOUND,
query = TransferMovementLedger.query.filter(
TransferMovementLedger.record_kind.in_(record_kinds),
TransferMovementLedger.transfer_executed.is_(False),
TransferMovementLedger.movement_date.isnot(None),
_effective_occupancy_filter(exclude_matching_id=exclude_occupied_by_matching_id),
)
if matured_date_to is not None:
query = query.filter(TransferMovementLedger.movement_date <= str(matured_date_to))
return query
def _order_circled_ledger(query):
@@ -302,14 +397,19 @@ def _order_circled_ledger(query):
def circle_ledger_records_scope_union() -> list[TransferMovementLedger]:
"""启用类型范围并集圈档(首页待办看板「待匹配」桶数据源,D16/规格 §10)。
【AI 触发时机】首页待办看板需要「已抓取尚未匹配的外部入站记录」清单/计数时
【AI 触发时机】首页待办看板需要「已抓取尚未匹配的出入站记录」清单/计数时
调用(backlog_service.list_pending_match_records);匹配创建圈档不要用本函数
(匹配按所选类型单范围圈定,不经并集)。
范围并集=对每个启用类型分别按其现行规则圈取后按 id 去重并集(等价实现):
每类型查询复用 _circle_ledger_base_query 固定条件(inbound/未封存/有异动日期/
未被有效 items 占用)+ apply_scope_filters 单一编译器——与匹配创建圈档同口径,
杜绝谓词漂移。无启用类型 → 空集(fail-closed:无类型即无范围,与匹配创建
每类型查询复用 _circle_ledger_base_query 固定条件(record_kinds_of(该类型
范围规则)/未封存/有异动日期/未被有效 items 占用/T−2 成熟封顶)+
apply_scope_filters 单一编译器——与匹配创建圈档同口径,杜绝谓词漂移。
【2026-10-21 桶口径放开】待匹配桶随类型规则推导记录类型(未钉 record_kind
的类型=出入站双轨):出入站未匹配记录都在桶里可见(一期"只收收料记录"
旧契约随类型配置化退役;桶=待办可见性清单,不影响各类型实际圈定匹配)。
【T−2 成熟封顶 2026-10-21】待匹配=可匹配:未成熟行(>T−2)不进桶,待成熟后
自然出现。无启用类型 → 空集(fail-closed:无类型即无范围,与匹配创建
NOT_CONFIGURED 语义一致)。已封存记录恒不在结果中(固定条件)。
Returns:
@@ -317,9 +417,17 @@ def circle_ledger_records_scope_union() -> list[TransferMovementLedger]:
"""
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
matured_date_to = eligible_movement_date_to(business_date_now())
by_id: dict[int, TransferMovementLedger] = {}
for config in get_enabled():
query = apply_scope_filters(_circle_ledger_base_query(), TransferMovementLedger, config.scope_rules)
query = apply_scope_filters(
_circle_ledger_base_query(
record_kinds=record_kinds_of(config.scope_rules),
matured_date_to=matured_date_to,
),
TransferMovementLedger,
config.scope_rules,
)
for record in query.all():
by_id.setdefault(record.id, record)
if not by_id:
@@ -330,35 +438,75 @@ def circle_ledger_records_scope_union() -> list[TransferMovementLedger]:
).all()
def pending_ledger_query(*, matchable_ids: set[int] | None = None, segment: str = "all"):
"""待匹配圈档查询:固定条件与 T−2,出入站都收,不按调拨类型范围过滤。
【AI 触发时机】首页「待匹配」计数和清单需要「已落档、尚未匹配」的全量时调用。
库存匹配卡上的「当前可匹配」不要用本查询的 all 段,那是启用类型范围并集。
核心逻辑:复用 _circle_ledger_base_query(未封存、异动日期非空、未被占用、
movement_date ≤ T−2),record_kinds 固定为 inbound 与 outbound。
segment=matchable 只留 matchable_ids;segment=outside 排除这些 id;
并集为空时 matchable 段为空查询,outside 段等于 all。
Args:
matchable_ids: 启用类型范围并集的档 id。all 段忽略。
segment: all、matchable 或 outside。
Returns:
已按异动日期、来源、单号、id 排序的 Query。
"""
matured_date_to = eligible_movement_date_to(business_date_now())
query = _circle_ledger_base_query(
record_kinds=("inbound", "outbound"),
matured_date_to=matured_date_to,
)
# [STEP 1] 类型范围只用于把全量拆成「现在可匹配」和「其余已落档」。
ids = matchable_ids or set()
if segment == "matchable":
query = query.filter(TransferMovementLedger.id.in_(ids) if ids else false())
elif segment == "outside" and ids:
query = query.filter(~TransferMovementLedger.id.in_(ids))
return _order_circled_ledger(query)
def _circle_ledger_records(
*,
source_codes: list[str],
rules: tuple[ScopeRule, ...],
movement_date_from: str | None,
movement_date_to: str | None,
record_kinds: tuple[str, ...],
exclude_occupied_by_matching_id: int | None = None,
doc_nos: list[str] | None = None,
matured_date_to: date | None = None,
) -> list[TransferMovementLedger]:
"""按快照规则+固定条件圈定档记录(匹配创建圈档与重查对账的共享底座/唯一实现)。
固定条件(规格 §6/§9)见 _circle_ledger_base_query(本函数叠加:来源 IN
(所选来源)、movement_date 范围、快照范围规则(apply_scope_filters 单一
编译器)、可选单号过滤)——两个调用方必须复用本函数,禁止各自手写固定条件
(双份维护=谓词漂移温床)。
(双份维护=谓词漂移温床)。record_kinds 原样传给底座,本函数不另给默认。
Args:
source_codes: 来源实例编码列表。
rules: 范围规则元组(parse_scope_rules 产物)。
movement_date_from / movement_date_to: 可选异动日期范围(ISO 字符串)。
record_kinds: 允许圈入的记录类型。有类型对象的调用方传
record_kinds_of(config.scope_rules);没有类型对象时显式传入。必传。
exclude_occupied_by_matching_id: 重查对账场景传入本匹配 id——本匹配自有
items 不构成占用(允许刷新/补建);匹配创建圈档不传(任何有效占用
都排除)。
doc_nos: 可选单号过滤(重查 invoice_nos 限定范围时约束补圈)。
matured_date_to: 可匹配截止日(T−2 成熟封顶,见底座);匹配创建圈档传值,
重查对账不传(对账不做成熟裁剪,避免存量未成熟行误判档消失)。
Returns:
档记录列表(异动日期 → 来源 → 单号 → id 稳定排序,与明细视图同口径)。
"""
query = _circle_ledger_base_query(
record_kinds=record_kinds,
exclude_occupied_by_matching_id=exclude_occupied_by_matching_id,
matured_date_to=matured_date_to,
).filter(TransferMovementLedger.source_code.in_([str(code) for code in source_codes]))
if movement_date_from:
query = query.filter(TransferMovementLedger.movement_date >= str(movement_date_from))
@@ -468,6 +616,61 @@ def item_external_lot_no(item: TransferInvoiceItem) -> str:
return apply_field_transforms("lot_no", item.lot_no, rules) or ""
def _sync_ready_evidence_before_circle(
*,
source_code: str,
required_kinds: tuple[str, ...],
kind_status: dict[str, dict],
deps: TransferDeps,
business_date: str,
now: datetime,
) -> None:
"""确认匹配前:对所需流为 ready 的证据做幂等落档(只 flush,提交归调用方)。
【AI 触发时机】run_matching STEP 0 在圈档前调用——UI「就绪」只表示归档文件
可用,不等于 transfer_movement_ledger 已有行(出站落档桥后部署、或回调桥
失败时会出现空档);此处补一次与回调同口径的落档,sha 未变则幂等跳过。
核心逻辑:按 required_kinds 逐流;仅 file_status==ready 触发。入站走
evidence_sync.sync_source_rows(deps + business_date);出站走
outbound_evidence_sync.sync_outbound_source_rows。异常只打 warning,不抛——
匹配主链路不得被单源落档失败整单炸掉(圈档仍按现有档事实进行;parse_failed
由落档桥尽力标记后由下方状态分支反映)。
Args:
source_code: 来源实例编码。
required_kinds: 本类型所需记录类型(inbound/outbound)。
kind_status: 该来源各流的 resolve_source_file_status 投影。
deps: 入站落档用的 TransferDeps(file_repository)。
business_date: 业务日(入站新鲜度口径)。
now: 落档时间基准。
"""
from flask import current_app
from app.services.in_transit_transfer.evidence_sync import sync_source_rows
from app.services.in_transit_transfer.outbound_evidence_sync import (
sync_outbound_source_rows,
)
for kind in required_kinds:
status = kind_status.get(kind) or {}
if status.get("file_status") not in _CONFIRMABLE_SYNC_STATUSES:
continue
try:
if kind == "inbound":
sync_source_rows(
source_code=source_code, deps=deps,
business_date=business_date, now=now,
)
elif kind == "outbound":
sync_outbound_source_rows(source_code=source_code, now=now)
except Exception as exc: # noqa: BLE001 —— 单源落档失败不阻断匹配
current_app.logger.warning(
"TRANSFER_MATCH_EVIDENCE_SYNC_FAILED source=%s kind=%s error=%s",
source_code, kind, exc,
)
def run_matching(
*,
source_codes: list[str],
@@ -488,10 +691,14 @@ def run_matching(
【出生翻转 2026-10-14】本函数不再做证据兜底对齐(align 已退役):STEP 0 改为
「从档圈行建 items」——按类型快照范围规则+固定条件圈定档记录并逐记录创建
item(创建即绑定 matching_id);随后既有库存评估链不变(以 items 为工作单元)。
来源无可用文件时保留既有 UX:触发 RPA 抓取并按准备结果标来源阶段(来源阶段
只影响进度展示,不阻断档圈定——档是镜像事实,不随当日文件可用性消失)。
落库写入不在此 commit(随调用方事务:create_matching 末尾统一提交 / 异步
Job handler 回写后提交)。
来源阶段只影响进度展示,不阻断档圈定——档是镜像事实,不随当日文件可用性消失。
入站 RPA 只在类型要求入站、且入站投影不是 ready / no_data / unconfigured /
parse_failed 时触发;入站已确认无数据,或类型不要求入站,不得触发入站抓取。
【确认匹配落档补齐】所需流为 ready 时先幂等落档再圈档(见
_sync_ready_evidence_before_circle);所需流出站/入站 parse_failed 均记
failed 进度。落库写入不在此 commit(随调用方事务:create_matching 末尾统一
提交 / 异步 Job handler 回写后提交)。圈档记录类型取 record_kinds_of(本次
已加载的 scope_rules):创建路径=类型现行规则,存量重跑=快照规则。
Args:
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
@@ -528,23 +735,78 @@ def run_matching(
)
now = datetime.utcnow()
# [STEP 0] 来源文件状态快照(进度展示与缺文件 RPA 触发;不阻断档圈定):
# resolve 命中(含 sha)→ file_ready 留痕;未命中 → ensure_inbound_file_ready
#(缺文件触发 RPA,既有 UX 保留);parse_failed 文件如实标 failed(解析失败
# 分层:失败事实由落档桥落库,匹配不再解析)。
# [STEP 0] 来源文件状态快照(进度展示;不阻断档圈定)。
# 按类型所需证据流逐条投影。ensure_inbound_file_ready(reason=
# matching_missing_ready_file)只在「inbound ∈ required_kinds」且入站投影
# 不是 ready / no_data / unconfigured 时调用。所需流 parse_failed(入/出站)
# 标 failed 并跳过该来源文件留痕。ready 流先幂等落档再圈档(补齐空档窗口)。
# 入站 no_data、或不要求入站:不触发入站 RPA,进度记 file_ready(有 sha 则
# 留痕,否则空 checksum),圈档照常进行。出站缺文件保持非阻断,这里不做出站 ensure。
required_kinds = record_kinds_of(scope_rules)
# ready=已有文件;no_data=确认当日无记录;unconfigured=该流未配置。三者都可确认,不抓取。
skip_inbound_ensure = {"ready", "no_data", "unconfigured"}
sources: list[SourceProgressDTO] = []
file_snapshot: dict[str, Any] = {}
def _remember_ready(
source_code: str, *, file_no: str | None, file_version: str | None, checksum: str,
) -> None:
"""把已有 checksum 的来源记入进度与 file_snapshot(不触发 RPA)。
Args:
source_code: 来源实例编码。
file_no / file_version / checksum: 当前证据文件身份。
"""
file_snapshot[source_code] = {
"file_no": file_no,
"file_version": file_version,
"checksum": checksum,
}
sources.append(SourceProgressDTO(
source_code=source_code, stage="file_ready",
file_no=file_no, file_version=file_version, checksum=checksum,
))
for source_code in source_codes:
file_status = resolve_source_file_status(source_code=source_code) or {}
checksum = file_status.get("file_sha256")
if file_status.get("file_status") == "parse_failed":
kind_status = {
kind: resolve_source_file_status(source_code=source_code, record_kind=kind) or {}
for kind in required_kinds
}
# [确认匹配落档补齐] ready → 幂等写入异动档(flush);失败仅日志,下方再投影。
_sync_ready_evidence_before_circle(
source_code=source_code,
required_kinds=required_kinds,
kind_status=kind_status,
deps=deps,
business_date=business_date,
now=now,
)
# 落档可能把 ready 标成 parse_failed:补投影后再做门禁。
kind_status = {
kind: resolve_source_file_status(source_code=source_code, record_kind=kind) or {}
for kind in required_kinds
}
inbound_required = "inbound" in required_kinds
outbound_required = "outbound" in required_kinds
inbound_status = kind_status.get("inbound") or {}
outbound_status = kind_status.get("outbound") or {}
inbound_state = inbound_status.get("file_status")
outbound_state = outbound_status.get("file_status")
if inbound_required and inbound_state == "parse_failed":
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code="TRANSFER_FILE_SCHEMA_INVALID",
error_message="inbound file parse failed; see source file status",
))
continue
if not checksum:
if outbound_required and outbound_state == "parse_failed":
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code="TRANSFER_FILE_SCHEMA_INVALID",
error_message="outbound file parse failed; see source file status",
))
continue
if inbound_required and inbound_state not in skip_inbound_ensure:
prepared = ensure_inbound_file_ready(
source_code=source_code, business_date=business_date,
repository=deps.file_repository, rpa_trigger=deps.rpa_trigger,
@@ -552,18 +814,10 @@ def run_matching(
)
if prepared.stage == "file_ready" and prepared.file is not None:
ready_file = prepared.file
checksum = ready_file.checksum
file_snapshot[source_code] = {
"file_no": ready_file.file_no,
"file_version": ready_file.file_version,
"checksum": ready_file.checksum,
}
sources.append(SourceProgressDTO(
source_code=source_code, stage="file_ready",
file_no=ready_file.file_no,
file_version=ready_file.file_version,
checksum=ready_file.checksum,
))
_remember_ready(
source_code, file_no=ready_file.file_no,
file_version=ready_file.file_version, checksum=ready_file.checksum,
)
else:
# 等待 RPA 回调 / 触发失败:该来源本轮不阻断(档照常圈定)。
sources.append(SourceProgressDTO(
@@ -573,22 +827,36 @@ def run_matching(
))
continue
else:
file_snapshot[source_code] = {
"file_no": file_status.get("file_no"),
"file_version": f"sha256:{checksum}"[:64],
"checksum": checksum,
}
sources.append(SourceProgressDTO(
source_code=source_code, stage="file_ready",
file_no=file_status.get("file_no"),
file_version=f"sha256:{checksum}"[:64],
checksum=checksum,
))
# 不调用 ensure_inbound_file_ready。入站 ready 留入站 sha;仅出站且
# 出站 ready 留出站 sha。no_data / 出站缺文件:空 checksum 的 file_ready。
chosen: dict | None = None
if inbound_required and inbound_state == "ready":
chosen = inbound_status
elif not inbound_required and outbound_state == "ready":
chosen = outbound_status
checksum = (chosen or {}).get("file_sha256")
if checksum:
_remember_ready(
source_code,
file_no=(chosen or {}).get("file_no"),
file_version=movement_file_version(checksum),
checksum=checksum,
)
else:
sources.append(SourceProgressDTO(source_code=source_code, stage="file_ready"))
# [STEP 0b 圈档建 items(出生翻转核心)] 圈定未占用档记录并逐记录建 item。
ledger_records = _circle_ledger_records(
source_codes=list(source_codes), rules=scope_rules,
movement_date_from=movement_date_from, movement_date_to=movement_date_to,
# [STEP 0b 圈档建 items(出生翻转核心)] 圈定未占用档记录;同 grain 多档择一
# 再建 item(uq_transfer_invoice_items_matching_grain;不累加防重解析翻倍)。
# 【T−2 成熟封顶 2026-10-21】只圈 movement_date ≤ T−2 的成熟记录——T−1/当天
# 未成熟不匹配,留在档内待成熟后自然进圈(「不回退退役决策,仅落简化成熟
# 边界」:无成熟行级状态,不做逐行标记)。
ledger_records = _dedupe_ledger_records_for_item_birth(
_circle_ledger_records(
source_codes=list(source_codes), rules=scope_rules,
movement_date_from=movement_date_from, movement_date_to=movement_date_to,
record_kinds=required_kinds,
matured_date_to=eligible_movement_date_to(business_date),
)
)
born: list[TransferInvoiceItem] = []
for record in ledger_records:
@@ -878,6 +1146,51 @@ def _generate_no(prefix: str, business_date: str) -> str:
return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}"
def _item_evidence_kind(item: TransferInvoiceItem) -> str:
"""行文件对账使用的证据流。
核心逻辑:有档关联时取档记录 record_kind(出站行对出站文件);无档关联回落
入站,与 resolve_source_file_status 的缺省一致。
Args:
item: 匹配明细行(ledger_record 可空)。
Returns:
inbound 或 outbound。
"""
record = item.ledger_record
kind = record.record_kind if record is not None else None
if kind in ("inbound", "outbound"):
return kind
return "inbound"
def _latest_evidence_files(
items: list[TransferInvoiceItem],
*,
resolve=None,
) -> dict[tuple[str, str], dict]:
"""按 (source_code, record_kind) 缓存当前可用证据文件投影。
核心逻辑:同一来源的入站与出站文件分开投影。resolve 缺省用本模块的
resolve_source_file_status;执行门禁传入自己命名空间里的同名函数,这样
测试替身打在调用方模块上仍然生效。
Args:
items: 待装饰或待门禁的明细行。
resolve: 状态投影函数,签名 (source_code, record_kind) → dict。
Returns:
(source_code, record_kind) → 文件状态投影。
"""
lookup = resolve or resolve_source_file_status
keys = sorted({
(item.source_code, _item_evidence_kind(item)) for item in items
})
return {
(source_code, kind): lookup(source_code=source_code, record_kind=kind) or {}
for source_code, kind in keys
}
def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
"""读取行的文件版本戳(行当前性判定锚点,规格 §10 改锚)。
@@ -931,7 +1244,8 @@ def create_matching(
【出生翻转 2026-10-14】先落 Run + Matching(flush 取 id)再驱动 run_matching:
圈档建行时 matching_id/run_id 出生即绑定(D17 占用互斥与取消释放的归属基础),
管道回写 status/counts/estimated/hash 后随主事务统一提交。类型必填且配置
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。圈档记录类型由
run_matching 对已加载的 scope_rules 调用 record_kinds_of,不再写死入站。
Args:
source_codes / business_date / deps: 同 run_matching。
@@ -1094,12 +1408,9 @@ def restore_matching(
invalid_rows = [row for row in rows_all if row.result_code == RESULT_FILE_REMOVED]
rows = [row for row in rows_all if row.result_code != RESULT_FILE_REMOVED]
# [STEP 2] 文件对账映射:自有行去重来源逐个投影当前可用文件版本,
# 行评估版本戳与之比对得 file_current(来源无可用文件 → False)。
latest_files: dict[str, dict] = {
source_code: resolve_source_file_status(source_code=source_code)
for source_code in sorted({row.source_code for row in rows})
}
# [STEP 2] 文件对账映射:按 (来源, 档记录 record_kind) 投影当前可用文件。
# 无档关联回落入站。行评估版本戳与之比对得 file_current(无可用文件 → False)。
latest_files = _latest_evidence_files(rows)
# [STEP 3] counts 按自有行实时聚合。
# pending/invalid 两桶为 2026-09-25 counts 契约扩展(同口径内存计算)。
@@ -1131,7 +1442,11 @@ def restore_matching(
items = []
for item in rows:
items.append(
_item_dto(item, latest_files.get(item.source_code) or {}, moment, ttl_seconds)
_item_dto(
item,
latest_files.get((item.source_code, _item_evidence_kind(item))) or {},
moment, ttl_seconds,
)
)
sources = [
SourceProgressDTO(
@@ -1167,7 +1482,7 @@ def _item_dto(
Args:
item: 明细行。
latest: 该行来源当前可用文件状态投影(resolve_source_file_status 结果)。
latest: 该行证据流的当前文件状态投影(按档 record_kind 解析;无档为入站)。
moment: 新鲜度判定基准时间。
inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds;
仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
@@ -1215,8 +1530,8 @@ def _item_dto(
# (库存查得时刻,仅匹配评估/重查/写前复查写入)——原 updated_at 时钟
# 被证据同步换戳每日续期,徽标对老行永不触发;stale=距库存取数超过
# 展示阈值(inventory_stale_ttl_seconds),无库存数据(NULL)不判定;
# file_current=行评估版本戳仍是该来源当前可用文件 sha
# (无版本戳或无可用文件均视为不一致 → False)。
# file_current=行评估版本戳仍是该行证据流(档 record_kind,无档则入站)
# 当前可用文件 sha(无版本戳或无可用文件均视为不一致 → False)。
item_id=item.id,
checked_at=inventory_checked_at.isoformat() if inventory_checked_at else None,
stale=bool(inventory_checked_at)
@@ -1272,12 +1587,13 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
)
.all()
)
latest_files: dict[str, dict] = {
source_code: resolve_source_file_status(source_code=source_code)
for source_code in sorted({row.source_code for row in rows})
}
latest_files = _latest_evidence_files(rows)
items = [
_item_dto(row, latest_files.get(row.source_code) or {}, moment, ttl_seconds)
_item_dto(
row,
latest_files.get((row.source_code, _item_evidence_kind(row))) or {},
moment, ttl_seconds,
)
for row in rows
]
return {"items": items, "counts": {"executable_count": len(rows)}}
@@ -76,6 +76,14 @@ MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("odm_name", "ODM名称", MovementFieldValueType.TEXT),
MovementField("carton_id", "箱号", MovementFieldValueType.TEXT),
MovementField("pallet_id", "栈板号", MovementFieldValueType.TEXT),
# ---- 2026-10-21 扩展:外部单据身份(外部单号/外部项次;CRANE/Lognet 出站
# 报告的 WMS Order #/行号)——解析放行空值(required=False),不进匹配身份
#(is_identity=False:匹配 grain 仍=单号/料号/异动日期,契约测试钉死不受扰);
# 但两字段自 2026-10-21 起作为库存异动档自然键成分(模型
# uq_transfer_movement_ledger_natural_key + ledger_sync 行级键)承担档幂等
# 主键管控:同一外部单号+项次的重复落档/证据更新收敛到同一档行。
MovementField("external_doc_no", "外部单号", MovementFieldValueType.TEXT),
MovementField("external_line_no", "外部项次", MovementFieldValueType.TEXT),
)
@@ -8,7 +8,8 @@
get_inbound_config / 入站解析方案 get_inbound_parsing_profile / 最新可用
归档 latest_usable_inbound_file / 归档字节 read_inbound_file_bytes /
维护通道清单 list_reparseable_inbound_files——只读入口唯一权威)、
file_preparation(ReadyInboundFile 契约)、openpyxl。
file_preparation(ReadyInboundFile 契约)、ledger_sync.movement_file_version
(file_version 戳的唯一生成处)、openpyxl。
逻辑:按来源取站点(enabled)与配置 → 解析方案须 published inbound → 最新
【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、文件缺失
或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
@@ -37,6 +38,7 @@ from app.services.freight_rpa.reports.queries import (
read_inbound_file_bytes,
)
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
from app.services.in_transit_transfer.ledger_sync import movement_file_version
# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。
_HEADER_WS_RE = re.compile(r"\s+")
@@ -126,7 +128,7 @@ class ShippingInboundFileRepository:
source_code=source_code,
business_date=business_date,
file_no=view.original_filename or str(view.file_id),
file_version=f"sha256:{view.sha256}"[:64],
file_version=movement_file_version(view.sha256),
checksum=view.sha256,
rows=tuple(rows),
)
@@ -155,7 +157,7 @@ class ShippingInboundFileRepository:
file_id=view.file_id,
storage_key=view.storage_key,
sha256=view.sha256,
file_version=f"sha256:{view.sha256}"[:64],
file_version=movement_file_version(view.sha256),
archived_at=view.created_at,
original_filename=view.original_filename,
)
@@ -0,0 +1,223 @@
"""services/in_transit_transfer/outbound_evidence_sync.py
用途:出站证据同步——出站回调 success 后把该来源最新可用出站归档按
purpose='outbound' 已发布解析规则解析、以 record_kind='outbound' 幂等落档
(transfer_movement_ledger),与 evidence_sync(入站专用,record_kind='inbound')
完全对称;解析失败把 parse_failed 三列独立落到出站归档文件上(2026-10-16
出站落档桥补齐——此前出站链路止步于归档+状态投影,异动档恒无 outbound 行)。
依赖:ledger_sync(sync_ledger_rows / RECORD_KIND_OUTBOUND / FileMeta /
movement_file_version)、
evidence_sync(parse_archive_to_ledger_rows 解析组装单一口径 +
_detect_natural_key_collapses/_natural_key_collapse_event 坍缩守卫 + SyncOutcome)、
movement_file_repository._extract_movement_rows(归档字节提取)、
source_file_status.latest_usable_outbound_file(出站可用文件视图,当天新鲜度
口径)、freight_rpa.reports.queries(get_outbound_config /
mark_outbound_parse_failure / clear_outbound_parse_failure)、file_asset_storage、
models、audit、db。
逻辑:sync_outbound_source_rows 只 flush 不 commit(提交归属调用方,契约同入站
sync_source_rows);sync_and_commit_for_outbound_callback 桥自行 commit +
异常全吞(B3 桥隔离——出站归档主链路不得被落档失败波及),schema 类失败
rollback 后把失败事实独立 commit 到当前可用文件(入站同款解析失败分层)。
规则门禁 fail-closed:无配置 / 未绑定规则 / 规则未发布 / purpose≠outbound
→ no-op(None)——规则缺失不是文件错误,不落解析失败标记(与入站仓库
latest_ready_file 门禁同口径)。cross_flag 交叉校验沿用 ledger_sync 既有
口径(当前仅 inbound 定义矛盾标志,outbound 行不计数)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import FreightRpaParsingProfile
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.reports.queries import (
clear_outbound_parse_failure,
get_outbound_config,
mark_outbound_parse_failure,
)
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.evidence_sync import (
SyncOutcome,
_detect_natural_key_collapses,
_natural_key_collapse_event,
parse_archive_to_ledger_rows,
)
from app.services.in_transit_transfer.file_parser import MovementFileSchemaError
from app.services.in_transit_transfer.ledger_sync import (
RECORD_KIND_OUTBOUND,
FileMeta,
movement_file_version,
sync_ledger_rows,
)
from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows
from app.services.in_transit_transfer.source_file_status import latest_usable_outbound_file
_TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
# schema 类解析失败判据与入站桥同一口径(code 或异常类型)。
_SCHEMA_FAILURE_CODES = (_TRANSFER_FILE_SCHEMA_INVALID,)
def _load_published_outbound_profile(source_code: str) -> FreightRpaParsingProfile | None:
"""加载来源出站配置绑定的「已发布 purpose='outbound'」解析规则(fail-closed 门禁)。
核心逻辑:出站配置(get_outbound_config,缺失=None)→ parsing_profile_id →
规则行须 published 且 purpose='outbound'——与运行期入站取数门禁
(movement_file_repository.latest_ready_file 的 published inbound 校验)同构。
Args:
source_code: 来源实例编码。
Returns:
FreightRpaParsingProfile;任一环节缺失或门禁不符返回 None。
"""
config = get_outbound_config(source_code)
if config is None or config.parsing_profile_id is None:
return None
profile = db.session.get(FreightRpaParsingProfile, config.parsing_profile_id)
if profile is None or profile.status != "published" or profile.purpose != "outbound":
return None
return profile
def sync_outbound_source_rows(*, source_code: str, now: datetime) -> SyncOutcome | None:
"""解析来源最新可用出站归档并幂等落档(零外部调用,flush 不 commit)。
【AI 触发时机】出站 RPA 回调桥(sync_and_commit_for_outbound_callback)调用;
不要在匹配/重查链路调用(匹配从档圈定,不写档)。
Args:
source_code: 来源实例编码。
now: 落档时间基准(插入/更新显式续 updated_at;文件新鲜度判定时刻)。
Returns:
SyncOutcome;无可用出站文件或无 published outbound 规则返回 None
(该分支不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。
Raises:
MovementFileSchemaError: 行必填缺失/非法(schema 类失败原样上抛——桥内
rollback + 落解析失败标记)。
"""
file_view = latest_usable_outbound_file(source_code, now=now)
if file_view is None:
return None
profile = _load_published_outbound_profile(source_code)
if profile is None:
return None
definition = profile.definition_json or {}
# [STEP 1] 归档字节 → 原始行(提取口径与运行期入站/清空重建同源)→ 档行
# (parse_archive_to_ledger_rows 解析组装单一口径;schema 类失败原样上抛)。
data = file_asset_storage.get_bytes(file_view.storage_key)
raw_rows = _extract_movement_rows(
data,
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"),
)
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows)
# [STEP 2] 幂等落档(record_kind='outbound');溯源文件三元组取当前可用归档。
# file_version 走 movement_file_version:出站归档无独立版本列,戳与入站仓库、
# 清空重建、匹配进度快照同一函数,避免再在此处自行拼接超长。
outcome = sync_ledger_rows(
source_code=source_code,
record_kind=RECORD_KIND_OUTBOUND,
parsed_rows=assembled,
file_meta=FileMeta(
source_file_id=file_view.file_id,
file_version=movement_file_version(file_view.sha256),
file_sha256=file_view.sha256,
),
now=now,
)
# [档自然键坍缩守卫] 与入站同口径复检(检测按行级六成分、record_kind 声明进
# 审计聚合键);仅实际落档时打事件,幂等重落不刷审计。
collapses = _detect_natural_key_collapses(assembled)
if collapses and (outcome.inserted or outcome.updated):
for collapse in collapses:
db.session.add(_natural_key_collapse_event(
source_code=source_code, collapse=collapse, record_kind=RECORD_KIND_OUTBOUND))
result = SyncOutcome(
source_code=source_code,
file_sha256=file_view.sha256 or "",
inserted=outcome.inserted,
updated=outcome.updated,
skipped=outcome.skipped,
sealed_skipped=outcome.sealed_skipped,
cross_flagged=outcome.cross_flagged,
)
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_EVIDENCE_SYNCED",
aggregate_type="transfer_source",
aggregate_id=source_code,
actor_type="system",
result="success",
after={
"file_sha256": result.file_sha256,
"record_kind": RECORD_KIND_OUTBOUND,
"inserted": result.inserted, "updated": result.updated,
"skipped": result.skipped, "sealed_skipped": result.sealed_skipped,
"cross_flagged": result.cross_flagged,
},
))
# [解析失败分层] 同步成功 = 当前可用文件已成功解析:清除失败标记(若此前
# 失败过),出站流状态投影随之恢复 ready。只 flush 不 commit。
if file_view.parse_failed_at is not None:
clear_outbound_parse_failure(file_view.file_id)
return result
def sync_and_commit_for_outbound_callback(*, source_code: str, now: datetime) -> bool:
"""出站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
【AI 触发时机】出站 RPA 回调 success 终态落文件后由
handle_outbound_report(outbound_report_handler)调用——桥是记账不是出站
链路的正确性依赖,任何异常不得向出站归档主链路传播(B3:必须自行 commit)。
【解析失败分层】失败路径先 rollback(桥隔离),仅 schema 类解析失败把失败
事实(parse_failed 三列)独立 commit 落到当前可用出站文件上;丢失的落档由
回调重试/出站重抓兜底。
Args:
source_code: 来源实例编码(出站单元行上的 source_code)。
now: 落档时间基准。
Returns:
True=落档成功或无事可做(无可用文件/无可用规则);False=落档失败
(已记日志;schema 类失败尽力把解析失败标记落库并独立提交,标记失败
仅告警不影响返回)。
"""
from flask import current_app
try:
outcome = sync_outbound_source_rows(source_code=source_code, now=now)
# [桥隔离] sync_outbound_source_rows 只 flush 不 commit;桥由回调事实
# 处理在归档 commit 之后独立调用,必须在此自行提交(B3 持久性教训)。
db.session.commit()
if outcome is not None:
current_app.logger.info(
"TRANSFER_OUTBOUND_EVIDENCE_SYNC source=%s inserted=%s updated=%s skipped=%s sealed=%s cross=%s",
source_code, outcome.inserted, outcome.updated,
outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged)
return True
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志
# [桥隔离] 落档崩溃绝不波及出站归档终态;丢失的落档由回调重试/重抓兜底。
current_app.logger.warning(
"TRANSFER_OUTBOUND_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
db.session.rollback()
# [解析失败分层] rollback 之后再写标记;仅 schema 类失败落库——通用异常
# (网络/DB 故障等)不是文件解析问题,不落标记。标记写入后独立 commit
# (落档数据已回滚,本次 commit 只持久化失败事实),仍返回 False。
# 标记写入是尽力而为:再抛异常也必须吞掉(B3 优先),丢失标记由下次重试补。
try:
code = getattr(exc, "code", None) or ""
if code in _SCHEMA_FAILURE_CODES or isinstance(exc, MovementFileSchemaError):
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
file_view = latest_usable_outbound_file(source_code, now=now)
if file_view is not None:
mark_outbound_parse_failure(
file_view.file_id,
error_code=str(code or _TRANSFER_FILE_SCHEMA_INVALID),
error_message=str(detail)[:2000],
)
db.session.commit()
except Exception as mark_exc: # noqa: BLE001 —— 桥隔离:标记失败仅日志
current_app.logger.warning(
"TRANSFER_OUTBOUND_PARSE_MARK_FAILED source=%s error=%s", source_code, mark_exc)
return False
@@ -15,6 +15,9 @@ services/in_transit_transfer/outbound_report_handler.py
Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。
状态机字段与入站同一套:waiting_rpa_callback → file_ready / failed;
无等待任务则 no-op;第二次调用该行已离开等待态,不再改(可重入)。
【STEP 4 出站证据同步 2026-10-16】success 事实把最新可用出站归档按
purpose=outbound 规则解析、record_kind='outbound' 落异动档(与入站
handle_inbound_report STEP 4 对称;桥内自吞异常并自行 commit)。
"""
from __future__ import annotations
@@ -80,9 +83,10 @@ def handle_outbound_report(fact: ReportFact) -> None:
核心逻辑:
[STEP 1] kind 门禁(fail-closed);[STEP 2] 推进等待中的来源任务(只改
status='waiting_rpa_callback' 的行,无等待行返回 None);[STEP 3]
推进结果必须在此提交;[STEP 4] 精确定位本次回调收尾的执行单元并回写出站
排程进度、归集终态。不调用入站 evidence_sync(record_kind=inbound 专用)。
【不捕获异常】任何一步失败原样外抛供 Worker 重试。
推进结果必须在此提交;[STEP 4] success 事实触发出站证据同步
(outbound_evidence_sync,record_kind='outbound',与入站 STEP 4 对称);
[STEP 5] 精确定位本次回调收尾的执行单元并回写出站排程进度、归集终态。
【不捕获异常】任何一步失败原样外抛供 Worker 重试(STEP 4 桥内自吞)。
Args:
fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/
@@ -122,7 +126,20 @@ def handle_outbound_report(fact: ReportFact) -> None:
if advanced is not None:
db.session.commit()
# [STEP 4] 出站排程收口:按 fact.unit_run_id 精确定位本次回调收尾的执行单元。
# [STEP 4] 出站证据同步:success 事实(ok 且 file_id 有值)后把该来源最新
# 可用出站归档按 purpose=outbound 规则解析、record_kind='outbound' 落异动档
# (与入站 handle_inbound_report STEP 4 对称:按 ok 触发、不依赖等待任务存在;
# 桥内自吞异常并自行 commit,本处不包 try——文件已提交,Worker 重试即可补齐)。
if fact.ok and fact.file_id is not None:
from app.services.in_transit_transfer.outbound_evidence_sync import (
sync_and_commit_for_outbound_callback,
)
sync_and_commit_for_outbound_callback(
source_code=fact.source_code, now=datetime.utcnow(),
)
# [STEP 5] 出站排程收口:按 fact.unit_run_id 精确定位本次回调收尾的执行单元。
schedule_run_id: int | None = None
if fact.unit_run_id is not None:
unit = db.session.get(FreightRpaOutboundUnitRun, int(fact.unit_run_id))
@@ -2,14 +2,16 @@
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps、
scope_rules.parse_scope_rules、scope_rules.record_kinds_of。
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断;
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制);
【2026-10-14 对档对账(ADR 0001/规格 §9)】requery_items(匹配号入口)前置
「对档重圈 → 与本匹配自有 items 对账」:档新增记录 → 补建 item(绑同一
匹配);档证据变 → 刷新 item 证据并重置待查;档记录消失 → item 失效隔离
(沿用 blocked_file_removed 语义退出主视图)。圈档复用匹配创建的同一函数
(_circle_ledger_records:固定条件单点实现)+ 同一快照规则(scope_json),
(_circle_ledger_records:固定条件单点实现;记录类型取
record_kinds_of(快照 scope_rules))+ 同一快照规则(scope_json),
D17 占用互斥排除「其他匹配」的有效占用(本匹配自有 items 不构成占用);
终态行(已执行/人工关闭/取消/在流)绝不触碰——已执行行不得被证据刷新
复活(防同批档证据更新促成二次写 ERP)。
@@ -53,12 +55,14 @@ from app.services.in_transit_transfer.matching_service import (
TransferDeps,
_born_item_from_record,
_circle_ledger_records,
_dedupe_ledger_records_for_item_birth,
_item_grain_of_ledger,
_resolve_route_with_config,
_SYNC_TERMINAL_STATUSES,
item_external_lot_no,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.scope_rules import parse_scope_rules
from app.services.in_transit_transfer.scope_rules import parse_scope_rules, record_kinds_of
from app.services.in_transit_transfer.serializers import DOCUMENT_STATUS_GROUPS
from app.services.in_transit_transfer.transfer_type import resolve_transfer_type
@@ -450,7 +454,9 @@ def _reconcile_items_with_ledger(
核心逻辑:[STEP 1] 按匹配快照规则(scope_rules + 来源 + 异动日期范围)圈定
档记录——复用匹配创建的同一圈档函数 _circle_ledger_records(固定条件单点
实现,杜绝谓词漂移),排除已执行封存、其他匹配的有效占用(D17;本匹配自有
实现,杜绝谓词漂移)。记录类型取 record_kinds_of(已解析的快照 rules)
(仅没有范围规则、也没有类型对象的调用点才显式只圈 inbound)。
排除已执行封存、其他匹配的有效占用(D17;本匹配自有
items 不构成占用)。[STEP 2] 三分类对账(**终态守卫:SUCCESS/DUPLICATE_
SUCCESS/MANUALLY_CLOSED/CANCELLED/EXECUTING/RESULT_UNKNOWN 行绝不触碰——
已执行行不得被证据刷新复活,否则同批档证据更新会促成二次写 ERP**):
@@ -483,13 +489,16 @@ def _reconcile_items_with_ledger(
sources = [str(code) for code in (scope.get("source_codes") or [])]
records: list = []
if sources:
records = _circle_ledger_records(
source_codes=sources,
rules=rules,
movement_date_from=scope.get("movement_date_from"),
movement_date_to=scope.get("movement_date_to"),
exclude_occupied_by_matching_id=matching.id,
doc_nos=wanted_doc_nos,
records = _dedupe_ledger_records_for_item_birth(
_circle_ledger_records(
source_codes=sources,
rules=rules,
movement_date_from=scope.get("movement_date_from"),
movement_date_to=scope.get("movement_date_to"),
record_kinds=record_kinds_of(rules),
exclude_occupied_by_matching_id=matching.id,
doc_nos=wanted_doc_nos,
)
)
# 类型配置(仓库定义):从快照类型码读现行配置(存量不要求启用)。
@@ -505,15 +514,24 @@ def _reconcile_items_with_ledger(
# [终态守卫·占用面] own_by_record 收全部自有行(含终态):档记录已被本匹配
# 任一行(含已执行行)绑定时按「档有行有」处理——终态绑定永不补建第二个 item
#(否则已执行记录将以新待查行复活 → 二次写 ERP)。
#(否则已执行记录将以新待查行复活 → 二次写 ERP)。同 grain 兄弟档亦视为已绑。
own_by_record = {
item.ledger_record_id: item
for item in matching.items
if item.ledger_record_id is not None
}
own_grains = {
(str(item.source_code or ""), str(item.invoice_no or ""),
str(item.material_no or ""), str(item.movement_date or ""))
for item in matching.items
}
for record in records:
item = own_by_record.get(record.id)
if item is None:
grain = _item_grain_of_ledger(record)
if grain in own_grains:
# 同 grain 已有自有 item(兄弟档 / 择优后的另一 ledger_record_id)。
continue
# [①补建] 档新增记录:绑同一匹配(D17:本匹配占用即成立)。
route = None
route_failed = False
@@ -541,6 +559,7 @@ def _reconcile_items_with_ledger(
else f"route not resolved for source {record.source_code}"
)
db.session.add(born)
own_grains.add(grain)
continue
# [②证据对账] 只比对异动事实(数量/批号/仓库);名称/规格为展示字段。
# [终态守卫·刷新面] 终态行(已执行/人工关闭/取消/在流)绝不触碰(含
@@ -5,16 +5,22 @@ services/in_transit_transfer/rpa_sinks.py
outbound-* 接到 freight_rpa 归档入口与本包事实处理函数(调拨是唯一业务消费方)。
依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、
freight_rpa.inbound/outbound.report_archive、schedule.freight_rpa_*_finalize、
inbound_report_handler / outbound_report_handler。
inbound_report_handler / outbound_report_handler、models。
逻辑:由 app.create_app 调用 register_inbound_sinks / register_outbound_sinks(幂等)。
进度类 sink 复刻 {'success':True,'data':...} envelope;文件事实经
register_report_handler 注册。不 import shipping_notice。
batch-ready:归档单元终态后立即尝试排程 finalize(文件返回= RPA/排程结束),
再投递事实;事实处理(证据同步等)失败不得挡排程收口。不 import shipping_notice。
"""
from __future__ import annotations
import logging
from typing import Any, Callable
_LOG = logging.getLogger(__name__)
_INBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'})
_OUTBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'})
def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
"""旧 inbound/outbound 进度端点 envelope:{'success':True,'data':业务结果}。"""
@@ -25,20 +31,102 @@ def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]])
return _sink
def _try_finalize_inbound_schedule_after_unit(payload: dict[str, Any]) -> None:
"""单元已落终态后按文件返回收口入站排程;解析/证据失败不得阻塞。
核心逻辑:用 callback_id 定位单元;仅当 status 已终态且挂了 schedule_run_id
时 refresh + finalize_if_complete(幂等)。异常只记日志,不回滚已提交单元。
"""
callback_id = str(payload.get('callback_id') or '').strip()
if not callback_id:
return
try:
from app.models import FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import (
finalize_inbound_schedule_run_if_complete,
refresh_inbound_schedule_run_progress,
)
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None or unit.schedule_run_id is None:
return
if str(unit.status or '') not in _INBOUND_UNIT_TERMINAL:
return
refresh_inbound_schedule_run_progress(int(unit.schedule_run_id))
finalize_inbound_schedule_run_if_complete(int(unit.schedule_run_id))
except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果
_LOG.warning(
'inbound schedule finalize after unit terminal failed callback_id=%s: %s',
callback_id,
exc,
exc_info=True,
)
def _try_finalize_outbound_schedule_after_unit(payload: dict[str, Any]) -> None:
"""单元已落终态后按文件返回收口出站排程;解析/证据失败不得阻塞。"""
callback_id = str(payload.get('callback_id') or '').strip()
if not callback_id:
return
try:
from app.models import FreightRpaOutboundUnitRun
from app.services.schedule.freight_rpa_outbound_finalize import (
finalize_outbound_schedule_run_if_complete,
refresh_outbound_schedule_run_progress,
)
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None or unit.schedule_run_id is None:
return
if str(unit.status or '') not in _OUTBOUND_UNIT_TERMINAL:
return
refresh_outbound_schedule_run_progress(int(unit.schedule_run_id))
finalize_outbound_schedule_run_if_complete(int(unit.schedule_run_id))
except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果
_LOG.warning(
'outbound schedule finalize after unit terminal failed callback_id=%s: %s',
callback_id,
exc,
exc_info=True,
)
def _inbound_batch_ready_sink(**payload: Any) -> dict[str, Any]:
"""入站 batch-ready:归档 →(单元终态后)排程收口 → 返回;事实投递异常仍尽量收口排程。"""
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
try:
data = ingest_inbound_callback(payload)
return {'success': True, 'data': data}
finally:
# 单元终态已 commit 后,无论事实处理是否抛错,都按文件返回尝试排程 finalize。
_try_finalize_inbound_schedule_after_unit(payload)
def _outbound_batch_ready_sink(**payload: Any) -> dict[str, Any]:
"""出站 batch-ready:归档 →(单元终态后)排程收口 → 返回。"""
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
try:
data = ingest_outbound_callback(payload)
return {'success': True, 'data': data}
finally:
_try_finalize_outbound_schedule_after_unit(payload)
def register_inbound_sinks() -> None:
"""注册全部 inbound 进度 sink 与 inbound 事实处理函数(幂等)。
核心逻辑:inbound-batch-ready 直挂 freight_rpa.inbound.report_archive.ingest_inbound_callback
(与 outbound 对称,无 shipping_notice 薄壳);unit/batch-progress 挂
schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report。
核心逻辑:inbound-batch-ready 走归档+文件返回即排程 finalize;unit/batch-progress 挂
schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report(证据/
调拨推进;排程收口已在 batch-ready 侧完成,handler 内 finalize 仍幂等兜底)。
"""
from app.services.freight_rpa.common.callback_sinks import register_sink
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
from app.services.schedule import freight_rpa_inbound_finalize
register_sink('inbound-batch-ready', _success_data_envelope(ingest_inbound_callback))
register_sink('inbound-batch-ready', _inbound_batch_ready_sink)
register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_inbound_unit_processing))
register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_inbound_batch_progress))
register_report_handler('inbound', handle_inbound_report)
@@ -47,17 +135,15 @@ def register_inbound_sinks() -> None:
def register_outbound_sinks() -> None:
"""注册全部 outbound 进度 sink 与 outbound 事实处理函数(幂等)。
核心逻辑:outbound-batch-ready 直挂 freight_rpa.outbound.report_archive.ingest_outbound_callback;
unit/batch-progress 挂 schedule.freight_rpa_outbound_finalize;事实处理函数挂
handle_outbound_report。
核心逻辑:outbound-batch-ready 走归档+文件返回即排程 finalize;unit/batch-progress 挂
schedule.freight_rpa_outbound_finalize;事实处理函数挂 handle_outbound_report。
"""
from app.services.freight_rpa.common.callback_sinks import register_sink
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
from app.services.schedule import freight_rpa_outbound_finalize
register_sink('outbound-batch-ready', _success_data_envelope(ingest_outbound_callback))
register_sink('outbound-batch-ready', _outbound_batch_ready_sink)
register_sink('outbound-unit-progress', _success_data_envelope(freight_rpa_outbound_finalize.mark_outbound_unit_processing))
register_sink('outbound-batch-progress', _success_data_envelope(freight_rpa_outbound_finalize.report_outbound_batch_progress))
register_report_handler('outbound', handle_outbound_report)
@@ -5,7 +5,8 @@
供匹配创建圈档、重查对账、管理页校验三处单一口径。
依赖:app.core.errors.ValidationError;SQLAlchemy Select(编译形态)。
逻辑:parse 校验词表/匹配方式/值非空 → ScopeRule 元组;evaluate 逐规则 AND、
逐值 OR(prefix/contains 大小写不敏感);apply_scope_filters 生成等价 SQL。
逐值 OR(prefix/contains 大小写不敏感);apply_scope_filters 生成等价 SQL;
record_kinds_of 从 record_kind 范围规则推导证据流(入站/出站)。
"""
from __future__ import annotations
@@ -25,6 +26,7 @@ SCOPE_FIELDS: frozenset[str] = frozenset({
})
_MATCHES = ("prefix", "equals", "contains", "in")
_RECORD_KINDS = ("inbound", "outbound")
@dataclass(frozen=True)
@@ -71,6 +73,30 @@ def _hit(value: str | None, rule: ScopeRule) -> bool:
return text in {v.upper() for v in rule.values} # in
def record_kinds_of(rules: tuple[ScopeRule, ...]) -> tuple[str, ...]:
"""从范围规则推导调拨类型需要的证据流(入站/出站)。
核心逻辑:筛 field=record_kind 的规则;无则默认双轨。多条规则时,各规则
允许的 inbound/outbound 集合(与 evaluate 同口径 _hit)逐条取交集;结果按
inbound→outbound 顺序输出,交集为空则返回空元组。
Args:
rules: parse_scope_rules 产出的 ScopeRule 元组。
Returns:
仅含 inbound/outbound 的去重元组。
"""
kind_rules = [rule for rule in rules if rule.field == "record_kind"]
if not kind_rules:
return _RECORD_KINDS
allowed: set[str] | None = None
for rule in kind_rules:
rule_allowed = {kind for kind in _RECORD_KINDS if _hit(kind, rule)}
allowed = rule_allowed if allowed is None else allowed & rule_allowed
if not allowed:
return ()
return tuple(kind for kind in _RECORD_KINDS if kind in allowed)
def evaluate_scope(record: Mapping[str, Any], rules: Sequence[ScopeRule]) -> bool:
"""内存求值:规则间 AND、规则内多值 OR(匹配/测试/小数据场景)。"""
return all(_hit(record.get(rule.field), rule) for rule in rules)
@@ -1,60 +1,214 @@
"""在途调拨来源入站文件状态投影服务。
"""在途调拨来源证据文件状态投影服务。
用途:只读货代入站链路已有事实(入站执行单元行 + freight_rpa 入站归档文件),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 /
无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖: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,事务归属调用方)。
用途:只读货代入站/出站链路已有事实(执行单元行 + freight_rpa 归档文件),
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
调拨不维护独立抓取状态表(低耦合)。
依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 /
get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、
出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与
入站可用条件同口径)。
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
最新单元失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
出站先查 get_outbound_config,缺失 → unconfigured;有配置则对出站文件表与
FreightRpaOutboundUnitRun 走同一顺序。列表接口走
resolve_source_file_statuses:同一顺序一次性投影全部来源,查询次数不随
来源个数增长。record/clear_inbound_parse_failure 仍是入站解析失败标记的
兼容薄壳(按主键委托 queries.mark/clear,只 flush 不 commit,事务归属调用方)。
"""
from __future__ import annotations
from typing import Any
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Callable
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
from sqlalchemy import and_, not_, or_
from app.core.errors import ValidationError
from app.models.freight_rpa_inbound_report import (
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
from app.models.freight_rpa_outbound_report import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
)
from app.services.freight_rpa.reports.queries import (
clear_inbound_parse_failure as _clear_parse_failure_by_id,
expired_inbound_file_condition,
get_outbound_config,
has_expired_inbound_file,
latest_usable_inbound_file,
mark_inbound_parse_failure as _mark_parse_failure_by_id,
usable_inbound_file_condition,
)
from app.services.in_transit_transfer.date_policy import business_date_utc_window
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
FAILED_UNIT_STATUSES = ('failed', 'cancelled')
# 空数据(RPA empty 回调契约值,shipping_notice 域术语保留):抓取成功但当日无入站记录,
# 空数据(RPA empty 回调契约值,shipping_notice 域术语保留):抓取成功但当日无记录,
# 属业务结果而非故障,独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
NO_DATA_UNIT_STATUSES = ('empty',)
_RECORD_KINDS = ('inbound', 'outbound')
def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的入站文件状态投影。
@dataclass(frozen=True)
class _FileFact:
"""批量投影用的文件身份,字段与单来源文件视图中参与状态判断的部分一致。"""
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
freight_rpa.reports.queries 的可用/失效条件):保留期已到 或 非当前业务日
(Asia/Shanghai)抓取。
file_id: int
original_filename: str
sha256: str
parse_failed_at: datetime | None
@dataclass(frozen=True)
class _UnitFact:
"""批量投影用的执行单元,只保留状态判断需要的 status。"""
status: str
@dataclass(frozen=True)
class _OutboundFileView:
"""出站归档文件只读视图,字段与入站 InboundFileView 对齐,供同一投影顺序读取。"""
file_id: int
source_code: str
sha256: str
storage_key: str
original_filename: str
created_at: datetime
parse_failed_at: datetime | None = None
def _outbound_fresh_and_retention_valid(now: datetime):
"""出站归档的新鲜度 + 保留期条件,列与入站 _fresh_and_retention_valid 同口径。
核心逻辑:业务日窗口用 date_policy.business_date_utc_window(与 queries 内联
数学一致);archive_expires_at 为空视为长期有效。
"""
window_start, window_end = business_date_utc_window(now)
return and_(
FreightRpaOutboundReportFile.created_at >= window_start,
FreightRpaOutboundReportFile.created_at < window_end,
or_(
FreightRpaOutboundReportFile.archive_expires_at.is_(None),
FreightRpaOutboundReportFile.archive_expires_at > now,
),
)
def _outbound_file_view(report: FreightRpaOutboundReportFile) -> _OutboundFileView:
"""把出站归档 ORM 行映射为冻结只读视图。"""
return _OutboundFileView(
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 latest_usable_outbound_file(
source_code: str,
*,
now: datetime | None = None,
) -> _OutboundFileView | None:
"""返回某来源当前可用的出站归档只读视图,最新优先。
用途:出站证据流状态投影取文件身份;口径与 latest_usable_inbound_file 相同
(未删除 + 当天业务日抓取 + 未过期),不读取对象存储字节。
核心逻辑:经出站执行单元行的 source_code 过滤,按 created_at/id 倒序取第一条。
Args:
source_code: 来源实例编码(写在 FreightRpaOutboundUnitRun.source_code 上)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'};
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
仍带 file_no/file_sha256 便于诊断与前端提示。
_OutboundFileView;无可用文件返回 None。
"""
now = now or datetime.utcnow()
report = (
FreightRpaOutboundReportFile.query
.join(FreightRpaOutboundReportFile.unit_run)
.filter(
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
_outbound_fresh_and_retention_valid(now),
)
.order_by(FreightRpaOutboundReportFile.created_at.desc(), FreightRpaOutboundReportFile.id.desc())
.first()
)
if report is None:
return None
return _outbound_file_view(report)
def has_expired_outbound_file(source_code: str, *, now: datetime | None = None) -> bool:
"""返回某来源是否存在未删除但已失效的出站归档(expired 投影依据)。
用途:出站状态投影在无可用文件、无进行中/终态单元之后,判断是否因隔日旧文件
或保留期已到而提示重抓。只读不写。
核心逻辑:未删除且新鲜度+保留期不成立,与 has_expired_inbound_file 同核。
Args:
source_code: 来源实例编码。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
存在失效但未清理的出站归档 → True;否则 False。
"""
now = now or datetime.utcnow()
expired = (
FreightRpaOutboundReportFile.query
.join(FreightRpaOutboundReportFile.unit_run)
.filter(
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
not_(_outbound_fresh_and_retention_valid(now)),
)
.first()
)
return expired is not None
def _empty_status(file_status: str) -> dict:
"""没有可用文件身份时的投影字典。"""
return {'file_status': file_status, 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
def _status_from_facts(
*,
file_view: Any | None,
active_unit: Any | None,
latest_unit: Any | None,
expired: bool,
) -> dict:
"""按既定优先级把已取到的文件与单元事实收成状态字典。
核心逻辑:可用文件(解析失败优先于 ready)→ 进行中单元 → 最新单元空数据 →
最新单元失败终态 → 失效文件 → none。单来源与批量投影共用,避免两条路径
各写一套优先级。
Args:
file_view: 可用文件视图;须有 original_filename、file_id、parse_failed_at、sha256。
没有可用文件时为 None。
active_unit: 仍在进行的执行单元;没有时为 None。只要求对象存在。
latest_unit: id 最大的执行单元;没有时为 None。须有 status。
expired: 是否仍有未清理的失效归档。
Returns:
file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。
"""
# 【阶段 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 并保留文件身份供诊断。
# 解析失败分层:文件本身可用但解析失败,不得当 ready,保留文件身份供诊断。
if file_view.parse_failed_at is not None:
return {
'file_status': 'parse_failed',
@@ -68,35 +222,288 @@ def resolve_source_file_status(*, source_code: str) -> dict:
'file_no': file_no,
'file_sha256': file_view.sha256,
}
active_unit = (
FreightRpaInboundUnitRun.query
.filter_by(source_code=source_code)
.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 = (
FreightRpaInboundUnitRun.query
.filter_by(source_code=source_code)
.order_by(FreightRpaInboundUnitRun.id.desc())
.first()
)
return _empty_status('fetching')
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
# 空数据:抓取成功但当日无入站记录——如实投影 no_data,不得与抓取失败混淆。
return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
# 空数据:抓取成功但当日无记录——如实投影 no_data,不得与抓取失败混淆。
return _empty_status('no_data')
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return _empty_status('failed')
if expired:
return _empty_status('expired')
return _empty_status('none')
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
# 【阶段 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}
def _project_file_status(
source_code: str,
*,
latest_file: Callable[..., Any],
unit_model: type,
has_expired: Callable[..., bool],
) -> dict:
"""按入站既有顺序把文件视图与执行单元投影成文件状态。
核心逻辑:有可用文件就不再查单元;没有进行中单元才看最新单元;最新单元
已是空数据或失败终态就不再查失效文件。入站与出站共用,差异只在三个协作参数。
Args:
source_code: 来源实例编码。
latest_file: 返回可用文件视图或 None;视图须有 original_filename、file_id、
parse_failed_at、sha256。
unit_model: 带 query/status/id/source_code 的执行单元模型。
has_expired: 该来源是否仍有失效未清理文件。
Returns:
file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。
"""
file_view = latest_file(source_code)
active_unit = None
latest_unit = None
expired = False
if file_view is None:
active_unit = (
unit_model.query
.filter_by(source_code=source_code)
.filter(unit_model.status.in_(RUNNING_UNIT_STATUSES))
.order_by(unit_model.id.desc())
.first()
)
if active_unit is None:
latest_unit = (
unit_model.query
.filter_by(source_code=source_code)
.order_by(unit_model.id.desc())
.first()
)
terminal = latest_unit is not None and latest_unit.status in (
*NO_DATA_UNIT_STATUSES, *FAILED_UNIT_STATUSES,
)
if not terminal:
expired = has_expired(source_code)
return _status_from_facts(
file_view=file_view,
active_unit=active_unit,
latest_unit=latest_unit,
expired=expired,
)
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
"""一次取出这批来源各自最新的可用归档。
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
Args:
file_model: 入站或出站归档文件模型。
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
source_ids: 要投影的来源主键。
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
Returns:
source_code 到文件事实的映射;没有可用文件的来源不出现。
"""
rows = (
file_model.query
.join(unit_model, file_model.unit_run_id == unit_model.id)
.filter(unit_model.source_id.in_(source_ids), *filters)
.with_entities(
unit_model.source_code,
file_model.id,
file_model.original_filename,
file_model.sha256,
file_model.parse_failed_at,
)
.order_by(file_model.created_at.desc(), file_model.id.desc())
.all()
)
picked: dict[str, _FileFact] = {}
for source_code, file_id, filename, sha256, parse_failed_at in rows:
if source_code in picked:
continue
picked[str(source_code)] = _FileFact(
file_id=file_id,
original_filename=filename,
sha256=sha256,
parse_failed_at=parse_failed_at,
)
return picked
def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str, _UnitFact], dict[str, _UnitFact]]:
"""一次取出这批来源的最新单元,以及仍在进行的最新单元。
核心逻辑:按 id 倒序扫描,每个来源遇到的第一行就是最新单元;状态属于进行中
的第一行就是该来源仍在抓取的单元。较新的失败单元因此盖不住更早仍在进行的单元。
Args:
unit_model: 入站或出站执行单元模型。
source_ids: 要投影的来源主键。
Returns:
(最新单元, 进行中单元),键都是 source_code。没有单元时对应字典为空。
"""
rows = (
unit_model.query
.filter(unit_model.source_id.in_(source_ids))
.with_entities(unit_model.source_code, unit_model.id, unit_model.status)
.order_by(unit_model.id.desc())
.all()
)
latest: dict[str, _UnitFact] = {}
active: dict[str, _UnitFact] = {}
for source_code, _unit_id, status in rows:
code = str(source_code)
if code not in latest:
latest[code] = _UnitFact(status=status)
if status in RUNNING_UNIT_STATUSES and code not in active:
active[code] = _UnitFact(status=status)
return latest, active
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
"""一次找出仍有失效未清理归档的来源编码。
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
Args:
file_model: 入站或出站归档文件模型。
unit_model: 对应的执行单元模型。
source_ids: 要投影的来源主键。
filters: 失效文件条件。
Returns:
至少有一份失效未清理归档的 source_code 集合。
"""
rows = (
file_model.query
.join(unit_model, file_model.unit_run_id == unit_model.id)
.filter(unit_model.source_id.in_(source_ids), *filters)
.with_entities(unit_model.source_code)
.distinct()
.all()
)
return {str(row[0]) for row in rows}
def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict]]:
"""批量投影一组来源的入站与出站证据文件状态。
用途:GET /sources 渲染来源选择卡。来源个数增加时仍只做固定几条查询,
供页面同时展示调拨类型和数据源时不必按来源等待。
核心逻辑:出站配置、入站/出站的可用文件、执行单元、失效文件各查一次,
再按与 resolve_source_file_status 相同的优先级收口。没有出站配置的来源
直接记 unconfigured,不把入站状态抄到出站。
Args:
sources: 已加载的来源行,须有 id 与 source_code。空列表不查库。
Returns:
{source_code: {"inbound": 状态字典, "outbound": 状态字典}}。
状态字典键与 resolve_source_file_status 相同。
"""
if not sources:
return {}
now = datetime.utcnow()
source_ids = [int(source.id) for source in sources]
configured_outbound = {
int(row[0])
for row in (
FreightRpaOutboundReportConfig.query
.filter(FreightRpaOutboundReportConfig.source_id.in_(source_ids))
.with_entities(FreightRpaOutboundReportConfig.source_id)
.all()
)
}
inbound_files = _latest_files_by_source(
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
source_ids,
usable_inbound_file_condition(now=now),
)
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
inbound_expired = _expired_source_codes(
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
source_ids,
expired_inbound_file_condition(now=now),
)
outbound_files = _latest_files_by_source(
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
source_ids,
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
_outbound_fresh_and_retention_valid(now),
)
outbound_latest, outbound_active = _units_by_source(FreightRpaOutboundUnitRun, source_ids)
outbound_expired = _expired_source_codes(
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
source_ids,
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
not_(_outbound_fresh_and_retention_valid(now)),
)
projected: dict[str, dict[str, dict]] = {}
for source in sources:
code = str(source.source_code)
inbound = _status_from_facts(
file_view=inbound_files.get(code),
active_unit=inbound_active.get(code),
latest_unit=inbound_latest.get(code),
expired=code in inbound_expired,
)
if int(source.id) not in configured_outbound:
outbound = _empty_status('unconfigured')
else:
outbound = _status_from_facts(
file_view=outbound_files.get(code),
active_unit=outbound_active.get(code),
latest_unit=outbound_latest.get(code),
expired=code in outbound_expired,
)
projected[code] = {'inbound': inbound, 'outbound': outbound}
return projected
def resolve_source_file_status(*, source_code: str, record_kind: str = 'inbound') -> dict:
"""返回某来源在指定记录类型上的证据文件状态投影。
用途:来源列表与重试门禁按流入站或出站询问文件是否就绪。缺省 record_kind
为 inbound,既有只传来源的调用返回值与改造前相同。
核心逻辑:record_kind 不是 inbound/outbound 时抛 ValidationError。出站先查
get_outbound_config,没有配置行则 unconfigured,不再往下看文件或单元。
有配置(以及全部入站)再按同一顺序投影。失效判定不依赖保留期清理任务:
保留期已到,或非当前业务日(Asia/Shanghai)抓取。
Args:
source_code: 来源实例编码。
record_kind: inbound 或 outbound,默认 inbound。
Returns:
{"file_status", "has_ready_file", "file_no", "file_sha256"}。
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data',
'expired', 'none', 'unconfigured'}。parse_failed 时 has_ready_file=False,
仍带 file_no/file_sha256。unconfigured 仅出站且无出站报表配置时出现。
Raises:
ValidationError: record_kind 不是 inbound 或 outbound。
"""
if record_kind not in _RECORD_KINDS:
raise ValidationError(
f'unsupported record_kind: {record_kind}',
details={'record_kind': record_kind},
)
if record_kind == 'outbound':
if get_outbound_config(source_code) is None:
return _empty_status('unconfigured')
return _project_file_status(
source_code,
latest_file=latest_usable_outbound_file,
unit_model=FreightRpaOutboundUnitRun,
has_expired=has_expired_outbound_file,
)
return _project_file_status(
source_code,
latest_file=latest_usable_inbound_file,
unit_model=FreightRpaInboundUnitRun,
has_expired=has_expired_inbound_file,
)
def record_inbound_parse_failure(
@@ -98,7 +98,7 @@ def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
def inventory_rpa_result_excel_name(run: ScheduleRun) -> str:
"""库存 RPA 结果 Excel 的企微/下载展示名。"""
return f"{onhand_rpa_attachment_stem(run)}-结果.xlsx"
return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx"
def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
@@ -107,7 +107,7 @@ def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f"{onhand_rpa_attachment_stem(run)}-库存.zip"
return f"{inventory_rpa_attachment_stem(run)}-库存.zip"
def _inventory_raw_zip_archive_path(run_no: str) -> Path:
@@ -137,12 +137,13 @@ def _iter_packable_inventory_files(
created: list[dict[str, Any]] | None = None,
):
"""
遍历可实际打包的库存快照。
遍历可实际打包的库存文件。
核心逻辑:需存在 FreightRpaOnhandReportFile 且 storage_path 指向可读文件。
核心逻辑:优先 FreightRpaOnhandReportFile(解析入库后);若无 inventory_file_no
则回退 created.file_path(HTTP 文件返回即终态时的收件副本)。
Yields:
tuple[dict, FreightRpaOnhandReportFile, Path]: created 项、快照记录、可读路径。
tuple[dict, FreightRpaOnhandReportFile | None, Path]: created 项、快照记录(可空)、可读路径。
"""
if not is_shipping_inventory_rpa_task(getattr(run, "task", None)):
return
@@ -150,22 +151,28 @@ def _iter_packable_inventory_files(
items = _normalize_created_items(created) if created is not None else _api_response_created(run)
for item in items:
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
if not inventory_file_no:
if inventory_file_no:
inv_file = (
db.session.query(FreightRpaOnhandReportFile)
.filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no)
.first()
)
if not inv_file:
continue
storage_path = Path(str(inv_file.storage_path or "").strip())
if not storage_path.is_file():
continue
yield item, inv_file, storage_path
continue
inv_file = (
db.session.query(FreightRpaOnhandReportFile)
.filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no)
.first()
)
if not inv_file:
# RPA 文件返回即终态:尚无快照号时用回调/收件副本路径打包。
file_path = str(item.get("file_path") or "").strip()
if not file_path:
continue
storage_path = Path(str(inv_file.storage_path or "").strip())
storage_path = Path(file_path)
if not storage_path.is_file():
continue
yield item, inv_file, storage_path
yield item, None, storage_path
def inventory_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
@@ -208,8 +215,12 @@ def persist_inventory_rpa_raw_zip_archive(
with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for zip_index, (item, inv_file, storage_path) in enumerate(packable_files, start=1):
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
source_code = str(item.get("source_code") or inv_file.source_code or "").strip()
warehouse_id = str(item.get("warehouse_id") or inv_file.warehouse_id or "").strip()
source_code = str(
item.get("source_code") or (getattr(inv_file, "source_code", None) or "")
).strip()
warehouse_id = str(
item.get("warehouse_id") or (getattr(inv_file, "warehouse_id", None) or "")
).strip()
entry_name = _build_zip_entry_name(
index=zip_index,
source_code=source_code,
@@ -217,12 +228,16 @@ def persist_inventory_rpa_raw_zip_archive(
original_suffix=storage_path.suffix or ".xlsx",
)
archive.write(storage_path, arcname=entry_name)
original_name = (
str(getattr(inv_file, "source_file_name", None) or "").strip()
or storage_path.name
)
files_manifest.append({
"inventory_file_no": inventory_file_no,
"source_code": source_code,
"warehouse_id": warehouse_id,
"file_name": entry_name,
"original_file_name": inv_file.source_file_name or storage_path.name,
"original_file_name": original_name,
})
manifest = {
@@ -2,9 +2,11 @@
backend/app/services/schedule/freight_rpa_onhand_finalize.py
用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。
逻辑:freight_rpa_onhand_job 写 trigger 后 defer;onhand_rpa_workflow 回调后 finalize;
run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common、
freight_rpa.onhand.workflow_protocol(结果状态归一)。
逻辑:freight_rpa_onhand_job 写 trigger 后 defer;HTTP batch-ready 按 RPA 导出结果 finalize
(文件返回即 RPA/排程结束);解析 Job 可后置且不得重新打开 awaiting;
run_task_now / cron 启动前回收超时 awaiting run。
"""
from __future__ import annotations
@@ -111,6 +113,82 @@ def _compute_run_status(*, total_count: int, success_count: int, failed_count: i
return "partial_failed"
def map_rpa_batch_results_for_schedule_finalize(
results: list[Any] | None,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
"""把 Worker batch results 映射为排程 finalize 的 created/failed/skipped。
【AI 触发时机】:HTTP onhand-batch-ready 收件后、入队解析 Job 前调用;
只认 RPA 导出成败(含 file_path),不依赖解析入库后的 inventory_file_no。
Args:
results: Worker 回调 results 列表。
Returns:
(created, failed, skipped):供 finalize_shipping_inventory_schedule_run 使用。
"""
from app.services.freight_rpa.onhand.workflow_protocol import normalize_inventory_batch_item_status
created: list[dict[str, Any]] = []
failed: list[dict[str, Any]] = []
skipped: list[dict[str, Any]] = []
for raw in results or []:
if not isinstance(raw, dict):
continue
source_code = str(raw.get("source_code") or "").strip().upper()
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
status = normalize_inventory_batch_item_status(raw)
if status == "success":
created.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"inventory_file_no": str(raw.get("inventory_file_no") or "").strip(),
"file_path": str(raw.get("file_path") or "").strip(),
})
continue
if status == "skipped":
skipped.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"skip_reason": str(raw.get("skip_reason") or raw.get("reason") or "skipped")[:200],
"message": str(raw.get("message") or raw.get("error_message") or "")[:500],
})
continue
failed.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"error": str(
raw.get("error") or raw.get("error_message") or raw.get("message") or "rpa_export_failed"
)[:500],
})
return created, failed, skipped
def finalize_shipping_inventory_schedule_run_from_rpa_results(
schedule_run_id: int,
payload: dict[str, Any],
) -> FinalizeScheduleRunResult:
"""按 RPA 导出结果终态化排程(文件返回即结束,不等解析)。
核心逻辑:map Worker results → finalize;解析 Job 稍后仍可入库,但不得重新 awaiting。
Args:
schedule_run_id: ScheduleRun 主键。
payload: 已收件的 batch-ready 载荷(含 results)。
Returns:
FinalizeScheduleRunResult: 与 finalize_shipping_inventory_schedule_run 同形。
"""
created, failed, skipped = map_rpa_batch_results_for_schedule_finalize(payload.get("results"))
return finalize_shipping_inventory_schedule_run(
schedule_run_id,
created=created,
failed=failed,
skipped=skipped,
payload=payload,
)
def _build_finalize_details(
pending_details: list[dict[str, Any]],
*,
@@ -8,9 +8,12 @@
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
该偏移参数是自动处理面的唯一日期边界(成熟规则已退役 2026-10-16,
未配置即处理全部圈中数据);空数据日(无 run_no 且无 errors)置
domain_notification_managed 保持静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎
只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置
偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(无
run_no 且无 errors)置 domain_notification_managed 保持静默(C5),有
Run 或硬失败交由框架完成卡按排程「启用通知」发送。
"""
from __future__ import annotations
@@ -81,9 +84,10 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面
(成熟规则已退役:未配置偏移即处理全部圈中数据);偏移非法(负数/小数/
非数字)快速失败不执行;范围越界由匹配层 ValidationError 落 errors 走硬失败路径。
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
成熟积压,偏移终点 0/1(T−1/当天)由匹配层 ValidationError 落 errors 走
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
Args:
task: 排程任务(job_params: source_codes/recover_history/
+14 -2
View File
@@ -4,6 +4,7 @@ backend/app/services/schedule/query_service.py
用途:排程任务与运行记录的查询/序列化。
依赖:ScheduleRun / ScheduleTask、库存/入站/出站 raw-zip 可用性判定。
逻辑:list_tasks / get_run / serialize_run 供管理端排程工作台与下载按钮读取。
执行记录日期窗用 coalesce(started_at, created_at),排队中尚未开始的 run 仍落在创建日。
"""
from __future__ import annotations
@@ -159,6 +160,15 @@ def list_runs(
started_before: Optional[datetime] = None,
limit: int = 100,
) -> list[dict]:
"""
按任务、状态与时间窗列出执行记录。
核心逻辑:时间窗比较 coalesce(started_at, created_at)。手动入队时 started_at 仍为空,
若只比 started_at,工作台默认「今天」会把排队中的 run 滤掉,再次点击则因活动 run 冲突。
Returns:
序列化后的运行记录,按 created_at 倒序,最多 500 条。
"""
query = db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
if task_id is not None:
query = query.filter(ScheduleRun.schedule_task_id == task_id)
@@ -166,10 +176,12 @@ def list_runs(
query = query.filter(ScheduleTask.name.ilike(f'%{schedule_name}%'))
if status:
query = query.filter(ScheduleRun.status == status)
# 排队 run 还没有 started_at,用创建时间落入同一日期窗,避免工作台看起来像没触发。
activity_at = func.coalesce(ScheduleRun.started_at, ScheduleRun.created_at)
if started_after is not None:
query = query.filter(ScheduleRun.started_at >= _as_naive_utc(started_after))
query = query.filter(activity_at >= _as_naive_utc(started_after))
if started_before is not None:
query = query.filter(ScheduleRun.started_at < _as_naive_utc(started_before))
query = query.filter(activity_at < _as_naive_utc(started_before))
if owner_user_id is not None:
query = query.filter(ScheduleTask.owner_user_id == owner_user_id)
if notify_user_id is not None:
+13 -10
View File
@@ -676,9 +676,9 @@ def _adjudicate_notice_odm(
"""
整单(Notice)级 ODM 收敛裁决;模板不消费 odm 字段时直接跳过。
逻辑:客户 ODM ID 范围非空先过滤;用户选择(OT.chosen_odm_id)次之;
无范围且无选择时,各导出行命中 odm 交集唯一则自动收敛(唯一可行解,无需人工)。
多值并存时不过滤,由逐行折叠按现有契约阻断,并由工作台下发候选供用户选择。
逻辑:各行命中 odm 交集恰一个值(唯一可行解)时直接收敛并跳过客户 odm_ids
白名单(2026-10-20 白名单降级);多值时客户 ODM ID 范围非空先过滤,用户选择
(OT.chosen_odm_id)次之;范围排除全部命中或选择已失效时抛 ValueError。
Returns:
{'inventory_lines': 收敛后的库存行, 'feasible_odm_ids': 排序候选,
@@ -711,8 +711,13 @@ def _adjudicate_notice_odm(
result['chosen_odm_id'] = odm_display.get(chosen_odm, str(chosen_odm_raw).strip()) if chosen_odm else None
normalized_keys = _normalize_match_keys(match_keys)
pre_odm_sets = _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
# [STEP] 唯一命中优先(2026-10-20 白名单降级):各行命中的 ODM 交集恰一个值时
# 直接取用,不再套客户 odm_ids 白名单——客户主数据与库存文件的口径漂移不应
# 拦下「Excel 里只有一个 ODM」的确定事实(回归 OT-20261017-184D440D)。
unique_feasible = _intersect_odm_sets(pre_odm_sets)
unique_hit = len(unique_feasible) == 1
if customer_odm_ids:
if customer_odm_ids and not unique_hit:
result['whitelist_applied'] = True
scope = set(customer_odm_ids)
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in scope]
@@ -720,20 +725,18 @@ def _adjudicate_notice_odm(
# 避免回落成误导性的「没有匹配的库存记录」。
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
raise ValueError('订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内,请检查客户数据或库存文件')
elif unique_hit:
# 唯一命中即唯一可行解:绕过白名单直接收敛,多值时白名单才参与收敛。
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in unique_feasible]
# 逐行候选取「客户范围过滤后、选择收敛前」的集合:用户在任何一行改选,候选都来自同一口径。
scoped_sets = (
_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
if customer_odm_ids else pre_odm_sets
if (customer_odm_ids and not unique_hit) else pre_odm_sets
)
if chosen_odm:
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) == chosen_odm]
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
raise ValueError('发货通知已选择的 ODM ID 在当前库存中不存在,请重新选择')
elif not customer_odm_ids:
# 无范围、无选择:交集唯一即唯一可行解,自动收敛;多值留给折叠阻断 + 人工选择。
feasible = _intersect_odm_sets(pre_odm_sets)
if len(feasible) == 1:
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in feasible]
result['inventory_lines'] = inventory_lines
result['per_line_odm_ids'] = [
sorted(odm_display.get(value, value) for value in line_set)
@@ -684,15 +684,33 @@ def _sync_workflow_stage(
)
def _facts_order_task(task: ShippingNotice) -> ShippingOrderTask | None:
"""返回匹配/放行/结案事实归属的 OT:正式 Notice 经 order_task_id 回链,OT 原样返回。
核心逻辑:行级匹配事实与复核 Case 的 confirmed_task_id 都按 OT 主键落库;
Excel 生成链物化正式 Notice 后会以 Notice 对象复评满足性门禁,读取端必须统一
回链 OT,否则已放行/已满足事实不可见(回归 2026-10-17 OT-20261017-364C7BF2:
已自动放行的短缺单在 Excel 生成时被误判「尚未完成库存匹配」)。
"""
if task is None or getattr(task, 'id', None) is None:
return None
linked_id = getattr(task, 'order_task_id', None)
if linked_id is None:
return task if isinstance(task, ShippingOrderTask) else None
return db.session.get(ShippingOrderTask, int(linked_id))
def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
"""读取当前任务已审计的短缺放行冻结行 ID,供满足性与聚合重算共用。
核心逻辑:只认活动 ``release_onhand_shortage`` 决定;无放行事实时返回空集,
保证聚合重算与 ``match_completed`` 读到的放行语义完全一致,避免两处分裂。
读取身份经 :func:`_facts_order_task` 回链 OT,OT/Notice 两态结果一致。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
if task.id is None:
task = _facts_order_task(task)
if task is None:
return set()
if not getattr(task, 'order_snapshot_id', None):
return set()
@@ -723,10 +741,12 @@ def _closed_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
核心逻辑:与 ``_released_snapshot_line_ids_for_task`` 同源同口径——只认活动决定,
经 line_index 映射快照行;结案行不再是履约要求,在满足性/建单/导出各处按豁免处理。
读取身份同样经 :func:`_facts_order_task` 回链 OT。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
if task.id is None:
task = _facts_order_task(task)
if task is None:
return set()
if not getattr(task, 'order_snapshot_id', None):
return set()
@@ -759,10 +779,12 @@ def match_completed(task: ShippingNotice) -> bool:
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求,
从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。
事实读取身份经 :func:`_facts_order_task` 回链 OT,OT/Notice 两态结果一致。
"""
from app.models import ShippingNoticeLineOnhandMatch
if task.id is None:
task = _facts_order_task(task)
if task is None:
return False
rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
if not rows:
@@ -804,7 +826,8 @@ def inventory_match_facts_complete(task: ShippingNotice) -> bool:
"""判断当前行级匹配是否覆盖冻结订单全部项次且不再处于准备中。"""
from app.models import ShippingNoticeLineOnhandMatch, ShippingOrderSnapshot
if task.id is None or not getattr(task, 'order_snapshot_id', None):
task = _facts_order_task(task)
if task is None or not getattr(task, 'order_snapshot_id', None):
return False
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if snapshot is None or not snapshot.lines:
@@ -822,22 +845,27 @@ def inventory_match_facts_complete(task: ShippingNotice) -> bool:
def _released_snapshot_line_ids_for_export(task: ShippingNotice) -> set[int]:
"""读取当前任务已审计的短缺放行行,供滚动 Excel 资格筛选使用。"""
"""读取当前任务已审计的短缺放行行,供滚动 Excel 资格筛选使用。
核心逻辑:决定 join 必须用 OT 主键(owner.id)——复核 Case 的 confirmed_task_id
按 OT 落库,而 source_notice 在 Notice 物化后是 Notice 对象,用它 join 会永远
读不到放行(回归 2026-10-17 OT-20261017-364C7BF2);快照同样取自 owner。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderSnapshot
from app.services.shipping_notice.export import _source_notice_for_order_facts
source_notice = _source_notice_for_order_facts(task)
from app.models import ShippingOrderTask
owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot_id = getattr(owner, 'order_snapshot_id', None) if owner is not None else None
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None or source_notice.id is None:
if snapshot is None or owner is None or getattr(owner, 'id', None) is None:
return set()
decisions = (
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewCase.confirmed_task_id == int(owner.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
)
@@ -916,14 +944,16 @@ def excel_gate_error(task: ShippingNotice) -> str | None:
"""校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。"""
# 库存准备失败是硬门禁:即使任务上残留旧的 match/export 投影,也不得继续生成
# 发货 Excel。恢复只能由显式库存准备重试或人工上传重新建立成功事实。
# 准备轮次按 OT 主键落库;Notice 身份进入本门禁时须回链 OT,防止漏检硬失败。
from app.models import ShippingOnhandPreparationAttempt
facts_task = _facts_order_task(task)
latest_preparation = (
ShippingOnhandPreparationAttempt.query
.filter_by(task_id=int(task.id))
.filter_by(task_id=int(facts_task.id))
.order_by(ShippingOnhandPreparationAttempt.attempt_no.desc())
.first()
)
) if facts_task is not None else None
if latest_preparation is not None and str(latest_preparation.status or '').strip().lower() == 'failed':
return 'workflow.fulfillment.inventory_preparation_failed'
if _upload_status(task) == 'uploaded' and _export_file_path(task):
@@ -3,7 +3,8 @@ services/shipping_notice/notice_odm_choice_service.py
用途:发货通知整单(Notice)级 ODM ID 的逐行候选投影与用户选择持久化。
依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineOnhandMatch、AppError。
逻辑:候选 = 各导出行命中 odm(先经客户 odm_ids 范围过滤)的交集,与导出收敛共用同一
逻辑:候选 = 各导出行命中 odm 的交集(多值时先经客户 odm_ids 范围过滤,唯一命中
免白名单,与导出降级口径一致),与导出收敛共用同一
事实源(prepare_export_match_inputs);选择写在当前行级匹配事实行
(shipping_notice_line_onhand_matches.chosen_odm_id)上,按「同一库存快照文件」
圈同步范围——改任一行,同文件全部 is_current 行统一变更(Header 契约是整单一个值);
@@ -1965,10 +1965,11 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
"""快速收件库存 RPA batch 回调,并将业务处理交给 shipping worker。
"""快速收件库存 RPA batch 回调:排程按文件返回终态化,解析交给 shipping worker。
【AI 触发时机】:freight_rpa_worker 已完成库存文件导出、需要确认 HXOPS 已接收回调时调用。
本函数只验证回调信封并持久化 Job;禁止在 HTTP 请求内解析 Excel、关联任务或推进 Gate。
核心逻辑:校验收件信封 → 复制到受控区 → 若含 schedule_run_id 则按 RPA 导出结果
finalize 排程(文件返回= RPA/排程结束)→ 再入队解析 Job;禁止在 HTTP 内解析 Excel。
"""
if payload.get('schema_version') != SCHEMA:
return tool_response(status='failed', message='callback_schema_invalid', data={
@@ -2018,6 +2019,36 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_file_receipt_failed',
})
# [STEP] 排程:文件成功返回即按 RPA 导出结果终态化,解析成败不阻塞排程收口。
finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"}
schedule_run_id = receipt_payload.get("schedule_run_id")
try:
schedule_run_id = int(schedule_run_id) if schedule_run_id is not None else None
except (TypeError, ValueError):
schedule_run_id = None
if schedule_run_id is not None:
schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, batch_run_no)
if schedule_run_error:
return tool_response(
status="failed",
message="排程 RPA 回调 run_no 无效或与当前等待轮次不一致",
data={
"schedule_run_error": schedule_run_error,
"batch_run_no": batch_run_no,
"transport_status": "invalid",
"business_status": "rejected",
"error_code": schedule_run_error,
},
)
from app.services.schedule.freight_rpa_onhand_finalize import (
finalize_shipping_inventory_schedule_run_from_rpa_results,
)
finalize_result = finalize_shipping_inventory_schedule_run_from_rpa_results(
schedule_run_id,
receipt_payload,
)
from app.jobs.queue import enqueue
from app.jobs.types import JobType
@@ -2026,19 +2057,27 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
receipt_payload,
domain='shipping_notice',
business_ref=f'inventory-callback:{callback_id}',
message='库存 RPA 回调已收件,等待异步处理',
message='库存 RPA 回调已收件,等待异步解析处理',
max_attempts=3,
commit=True,
)
response_data: dict[str, Any] = {
'job_id': int(job_id),
'batch_run_no': batch_run_no,
'result_status': 'accepted',
'callback_result_status': 'accepted',
'schedule_finalize_status': finalize_result.get('schedule_finalize_status'),
}
if finalize_result.get('error'):
response_data['schedule_finalize_error'] = finalize_result.get('error')
if finalize_result.get('manual_retryable'):
response_data['schedule_finalize_manual_retryable'] = True
if finalize_result.get('run_status'):
response_data['run_status'] = finalize_result.get('run_status')
return tool_response(
status='ok',
message='库存 RPA 回调已收件,正在异步处理库存文件。',
data={
'job_id': int(job_id),
'batch_run_no': batch_run_no,
'result_status': 'accepted',
'callback_result_status': 'accepted',
},
message='库存 RPA 回调已收件;排程已按导出结果收口(若适用),解析异步处理中。',
data=response_data,
extra={'result_status': 'accepted'},
)
@@ -2234,7 +2273,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
【AI 触发时机】:freight_rpa_worker 完成 inventory_export_batch 后 POST 本接口。
核心逻辑:遍历 results;定时任务只入库;带 task_no 的成功项关联对应任务;
含 schedule_run_id 时委托 finalize 终态化排程 run。
含 schedule_run_id 时:若 HTTP 已按文件返回终态化则幂等跳过 finalize,
仍 awaiting 时才委托 finalize(兼容旧同步路径/终态失败重试)。
响应:tool_response.status 恒为 ok(payload 合法且处理完成);业务成败看 result_status。
"""
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
@@ -2267,7 +2307,10 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
except (TypeError, ValueError):
schedule_run_id = None
schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, run_no)
# 解析 Job:只校验 run 身份;排程可能已在 HTTP 收件时按 RPA 文件返回终态化。
schedule_run_error = _validate_schedule_batch_callback_run_no(
schedule_run_id, run_no, require_awaiting=False,
)
if schedule_run_error:
return tool_response(
status="failed",
@@ -314,6 +314,61 @@ def _has_terminal_inventory_rpa_failure(
)
def _line_hit_odm_multiple(
*,
onhand_snapshot_id: Any,
reservation_id: Any,
part_number: Any,
) -> bool:
"""判断预约+料号命中库存行(0 命中时回退料号命中行)的 ODM ID 是否多值。
核心逻辑:自动放行以「放行后 Excel 可生成」为前提;导出侧 ODM 裁决只在命中
ODM 唯一时免白名单收敛(2026-10-20 降级规则),多值时放行必然导致生成失败,
因此多值行保持人工路径。ODM 字段目录未启用、快照不可读或命中行无 ODM 值时
不设前置(返回 False,维持既有放行行为,避免误伤无 ODM 语义的客户/模板)。
"""
from app.models import FreightRpaOnhandField, FreightRpaOnhandReportFile
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
odm_field = FreightRpaOnhandField.query.filter_by(field_code='odm_id', status='active').first()
if odm_field is None:
return False
snapshot = (
db.session.get(FreightRpaOnhandReportFile, int(onhand_snapshot_id))
if onhand_snapshot_id else None
)
if snapshot is None:
return False
try:
lines, _meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError, AppError):
return False
part_field = FreightRpaOnhandField.query.filter_by(field_code='part_number').first()
reservation_field = FreightRpaOnhandField.query.filter_by(field_code='reservation_id').first()
part = str(part_number or '').strip().upper()
reservation = str(reservation_id or '').strip()
part_key = str(part_field.id) if part_field is not None else 'part_number'
reservation_key = str(reservation_field.id) if reservation_field is not None else 'reservation_id'
odm_key = str(odm_field.id)
def _hits(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [
row for row in rows
if part and str(row.get(part_key) or '').strip().upper() == part
and (not reservation or str(row.get(reservation_key) or '').strip() == reservation)
]
hits = _hits(lines) or [
row for row in lines
if part and str(row.get(part_key) or '').strip().upper() == part
]
odm_values = {str(row.get(odm_key) or '').strip() for row in hits} - {''}
import os as _os
if _os.environ.get('ODM_DEBUG'):
print('ODM_DEBUG hits=%d values=%r part=%r resv=%r snap=%r' % (len(hits), odm_values, part, reservation, onhand_snapshot_id))
return len(odm_values) > 1
def _shortage_release_required_fields(
*,
task: ShippingNotice,
@@ -1557,11 +1612,13 @@ def auto_release_part_fallback_shortages(
"""
匹配落库后按料号兜底自动放行缺口行(用户确认语义:满足即自动放行,非仅可放行)。
核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 无活动决定 + 证据字段全部可
自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律跳过并保持人工
路径,fail-closed 不变。复用 _apply_shortage_line_release,审计/门禁同步/自动
履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证,不自动撤销
既有放行。注意:行匹配事实以 snapshot_line_id 为键,行号取自 fact['line_index']。
核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 命中行 ODM 唯一 + 无活动决定
+ 证据字段全部可自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律
跳过并保持人工路径,fail-closed 不变。ODM 唯一前置保证放行后导出可收敛(唯一
ODM 免白名单,2026-10-20 需求)。复用 _apply_shortage_line_release,审计/门禁
同步/自动履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证,不
自动撤销既有放行。注意:行匹配事实以 snapshot_line_id 为键,行号取自
fact['line_index']。
Args:
task: 正式任务聚合根(OT 或正式 Notice,须含 id 与 order_snapshot_id)。
@@ -1598,6 +1655,14 @@ def auto_release_part_fallback_shortages(
if required is None or part_total is None or part_total < required:
# 料号兜底量缺失或不足 → 维持人工待处置(不得任取部分数量放行)。
continue
if _line_hit_odm_multiple(
onhand_snapshot_id=fact.get('inventory_snapshot_id'),
reservation_id=fact.get('reservation_id'),
part_number=fact.get('part_number'),
):
# 命中行 ODM 多值:导出侧无法唯一收敛(多值时白名单未必可救),
# 放行后 Excel 仍会失败,保持人工路径(2026-10-20 需求)。
continue
fields, evidence_scope = _shortage_release_required_fields(
task=task,
line_index=line_index,
-648
View File
@@ -1,648 +0,0 @@
# backend/config/freight_rpa_sources.yaml
# 历史库存源配置:仅用于期初数据导入和人工核对,不能恢复为运行时真相源。
# 新增或修改库存源、报表路径、查询参数和别名必须维护在数据库后台。
# 本文件保留 site_id、selector 等旧字段,导入时需显式映射或丢弃;新运行时不得读取。
version: 2
sources:
- source_code: DSV360_AWSBI_BYAWSATL01
display_name: DSV 360 / Bison / AWSBI / BYAWSATL01
enabled: true
connector_type: dsv360
site_id: AWSBI
warehouse_id: BYAWSATL01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSATL01
required: true
match_aliases:
- BYAWSATL01
- ATL01
- source_code: DSV360_AWSBI_BYAWSAVP01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSAVP01
warehouse_id: BYAWSAVP01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSAVP01
required: true
match_aliases:
- BYAWSAVP01
- source_code: DSV360_AWSBI_BYAWSAZA01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSAZA01
warehouse_id: BYAWSAZA01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSAZA01
required: true
match_aliases:
- BYAWSAZA01
- source_code: DSV360_AWSBI_BYAWSCMH01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSCMH01
warehouse_id: BYAWSCMH01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSCMH01
required: true
match_aliases:
- BYAWSCMH01
- CMH
- source_code: DSV360_AWSBI_BYAWSCMN01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSCMN01
warehouse_id: BYAWSCMN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSCMN01
required: true
match_aliases:
- BYAWSCMN01
- CMN
- source_code: DSV360_AWSBI_BYAWSEZE01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSEZE01
warehouse_id: BYAWSEZE01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSEZE01
required: true
match_aliases:
- BYAWSEZE01
- EZE
- source_code: DSV360_AWSBI_BYAWSFRA01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSFRA01
warehouse_id: BYAWSFRA01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSFRA01
required: true
match_aliases:
- BYAWSFRA01
- source_code: DSV360_AWSBI_BYAWSGRU01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSGRU01
warehouse_id: BYAWSGRU01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSGRU01
required: true
match_aliases:
- BYAWSGRU01
- source_code: DSV360_AWSBI_BYAWSIAD01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSIAD01
warehouse_id: BYAWSIAD01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSIAD01
required: true
match_aliases:
- BYAWSIAD01
- source_code: DSV360_AWSBI_BYAWSJAN01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSJAN01
warehouse_id: BYAWSJAN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSJAN01
required: true
match_aliases:
- BYAWSJAN01
- source_code: DSV360_AWSBI_BYAWSLTN01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSLTN01
warehouse_id: BYAWSLTN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSLTN01
required: true
match_aliases:
- BYAWSLTN01
- source_code: DSV360_AWSBI_BYAWSMEL01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSMEL01
warehouse_id: BYAWSMEL01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSMEL01
required: true
match_aliases:
- BYAWSMEL01
- source_code: DSV360_AWSBI_BYAWSNRT01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSNRT01
warehouse_id: BYAWSNRT01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSNRT01
required: true
match_aliases:
- BYAWSNRT01
- source_code: DSV360_AWSBI_BYAWSPHX01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSPHX01
warehouse_id: BYAWSPHX01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPHX01
required: true
match_aliases:
- BYAWSPHX01
- source_code: DSV360_AWSBI_BYAWSPNE01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSPNE01
warehouse_id: BYAWSPNE01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPNE01
required: true
match_aliases:
- BYAWSPNE01
- source_code: DSV360_AWSBI_BYAWSPRD01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSPRD01
warehouse_id: BYAWSPRD01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPRD01
required: true
match_aliases:
- BYAWSPRD01
- source_code: DSV360_AWSBI_BYAWSPSC01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSPSC01
warehouse_id: BYAWSPSC01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPSC01
required: true
match_aliases:
- BYAWSPSC01
- source_code: DSV360_AWSBI_BYAWSQRO01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSQRO01
warehouse_id: BYAWSQRO01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSQRO01
required: true
match_aliases:
- BYAWSQRO01
- source_code: DSV360_AWSBI_BYAWSRIC01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSRIC01
warehouse_id: BYAWSRIC01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSRIC01
required: true
match_aliases:
- BYAWSRIC01
- source_code: DSV360_AWSBI_BYAWSRNO01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSRNO01
warehouse_id: BYAWSRNO01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSRNO01
required: true
match_aliases:
- BYAWSRNO01
- source_code: DSV360_AWSBI_BYAWSRUH01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSRUH01
warehouse_id: BYAWSRUH01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSRUH01
required: true
match_aliases:
- BYAWSRUH01
- source_code: DSV360_AWSBI_BYAWSSBN01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSSBN01
warehouse_id: BYAWSSBN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSSBN01
required: true
match_aliases:
- BYAWSSBN01
- source_code: DSV360_AWSBI_BYAWSSCL01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSSCL01
warehouse_id: BYAWSSCL01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSSCL01
required: true
match_aliases:
- BYAWSSCL01
- source_code: DSV360_AWSBI_BYAWSYYZ01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSYYZ01
warehouse_id: BYAWSYYZ01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSYYZ01
required: true
match_aliases:
- BYAWSYYZ01
- source_code: DSV360_AWSBI_BYAWSZAZ01
enabled: true
connector_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSZAZ01
warehouse_id: BYAWSZAZ01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSZAZ01
required: true
match_aliases:
- BYAWSZAZ01
- source_code: DSV360_AWSCV
enabled: true
connector_type: dsv360
site_id: AWSCV
warehouse_id: AWSCV
display_name: DSV 360 / Cincinnati / AWSCV
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Cincinnati
program_label: AWSCV
report_group: Inventory
report_name: On Hand Inventory by Location
match_aliases:
- CINCINNATI
- CVG
- AWSCV
- source_code: DSV360_AWSDU
enabled: true
connector_type: dsv360
site_id: AWSDU
warehouse_id: AWSDU
display_name: DSV 360 / Dublin / AWSDU - Prod (JDA)
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Dublin
program_label: AWSDU - Prod (JDA)
report_group: Inventory
report_name: On Hand Inventory by Location
match_aliases:
- DBS DUB
- DUB
- DUBLIN
- source_code: DSV360_AWSAMS
enabled: true
connector_type: dsv360
site_id: AWSAMS
warehouse_id: RTM
display_name: DSV 360 / Moerdijk / AWSAMS
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Moerdijk
program_label: AWSAMS
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: multi_select
select_all: true
selectors:
text: '#ReportViewerMain_ctl08_ctl17_txtValue'
toggle: '#ReportViewerMain_ctl08_ctl17_ctl01'
dropdown: '#ReportViewerMain_ctl08_ctl17_divDropDown'
values:
- RTM
required: true
match_aliases:
- MOERDIJK
- AMS
- AWSAMS
- source_code: DSV360_AWSSL
enabled: true
connector_type: dsv360
site_id: AWSSL
warehouse_id: AWSSL
display_name: DSV 360 / Salt Lake City / AWSSL
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Salt Lake City
program_label: AWSSL
report_group: Inventory
report_name: On Hand Inventory by Location
match_aliases:
- USLCK
- SALT LAKE CITY
- SALTLAKECITY
- source_code: DSV360_AWSSG
enabled: true
connector_type: dsv360
site_id: AWSSG
warehouse_id: AWSSG
display_name: DSV 360 / Singapore / AWSSG - Prod (JDA)
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Singapore
program_label: AWSSG - Prod (JDA)
report_group: Inventory
report_name: On Hand Inventory by Location
match_aliases:
- SINGAPORE HUB
- SINGAPORE
- SG
- VMI-SIN
- source_code: CRANE
enabled: true
connector_type: crane_footprint
site_id: CRANE
warehouse_resolution: alias_match
display_name: Crane FootPrint
entry_url: https://wms-portal.craneww.com/#/on-hand-details-query
navigation:
report_name: On Hand Details Query
download_mode: scheduled_report
parameters: []
match_aliases:
- TZR
- TZR2
- TZR3
allowed_warehouse_ids:
- TZR
- TZR2
- TZR3
@@ -0,0 +1,52 @@
"""transfer_movement_ledger 增加外部单号/外部项次并扩自然键唯一约束(2026-10-21)
Revision ID: tt21c8d9e0f1a2
Revises: s19a0b1c2d3e4
Create Date: 2026-10-21
用途:库存异动档新增外部单据身份两列(external_doc_no/external_line_no,对应
CRANE/Lognet 出站报告的 WMS Order #/行号),并把两列加入自然键唯一约束
uq_transfer_movement_ledger_natural_key(8→10 成分)——外部单号+项次作为
档幂等主键管控:同一外部单号+项次的重复落档/证据更新收敛到同一档行。
依赖:movement_contract.MOVEMENT_FIELDS 追加同名契约字段(模型列 1:1 镜像断言
在 ledger_sync 导入期 fail-fast)。
逻辑:两列 NOT NULL + server_default ''(自然键可空成分以空串参与唯一比对,
防 PG NULL 逃逸);约束先删后建(PG/SQLite 通用)。存量行两列填默认空串
参与键;来源配置外部映射后重放同文件即按新键收敛,必要时走「清空并重解析」
重建(backlog_reparse_service)。
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "tt21c8d9e0f1a2"
down_revision = "s19a0b1c2d3e4"
branch_labels = None
depends_on = None
_TABLE = "transfer_movement_ledger"
_NATURAL_KEY = "uq_transfer_movement_ledger_natural_key"
_NATURAL_KEY_COLUMNS = (
"source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
"carton_id", "lot_no", "external_doc_no", "external_line_no",
)
def upgrade() -> None:
"""加两列(NOT NULL + server_default '',存量行回填空串)并扩自然键唯一约束。"""
op.add_column(_TABLE, sa.Column("external_doc_no", sa.String(64), nullable=False, server_default=""))
op.add_column(_TABLE, sa.Column("external_line_no", sa.String(32), nullable=False, server_default=""))
op.drop_constraint(_NATURAL_KEY, _TABLE, type_="unique")
op.create_unique_constraint(_NATURAL_KEY, _TABLE, list(_NATURAL_KEY_COLUMNS))
def downgrade() -> None:
"""回退:恢复 8 成分唯一约束并删两列(外部身份列数据随列删除,不留残档)。"""
op.drop_constraint(_NATURAL_KEY, _TABLE, type_="unique")
op.create_unique_constraint(
_NATURAL_KEY, _TABLE,
["source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
"carton_id", "lot_no"],
)
op.drop_column(_TABLE, "external_line_no")
op.drop_column(_TABLE, "external_doc_no")
@@ -1,175 +0,0 @@
"""
scripts/import_freight_rpa_sources.py
用途:把期初 YAML 库存源导入 freight_rpa_sources / freight_rpa_profiles 主数据。
依赖:Flask app、SQLAlchemy、PyYAML、models.FreightRpaSource、models.FreightRpaProfile、
models.FreightRpaOnhandReportConfig(s18 起报表路径/查询条件归配置行)。
逻辑:由运维手工执行;读取 config/freight_rpa_sources.yaml,按平台与登录地址复用连接,
导入行一律保持停用,不导入 selector 与凭据;YAML 的报表路径与查询条件写入
FreightRpaOnhandReportConfig 配置行,解析方案绑定留空。运行时不再读这份 YAML。
"""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Any
import yaml
from app import create_app
from app.extensions import db
from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile
CONNECTOR_TYPES = {"dsv360": "dbs", "crane_footprint": "crane"}
def _source_payload(raw: dict[str, Any]) -> dict[str, Any]:
"""Convert one legacy source while excluding worker-only selector configuration.
Args:
raw: A source item from the legacy YAML document.
Returns:
Normalized source fields for ``FreightRpaSource`` plus the
``report_path_json`` / ``query_parameters_json`` carried by
``FreightRpaOnhandReportConfig`` since s18.
"""
connector_type = CONNECTOR_TYPES.get(str(raw.get("connector_type") or "").strip().lower())
if connector_type is None:
raise ValueError(f"Unsupported connector_type: {raw.get('connector_type')!r}")
navigation = raw.get("navigation") if isinstance(raw.get("navigation"), dict) else {}
parameters: list[dict[str, Any]] = []
for parameter in raw.get("parameters") or []:
if not isinstance(parameter, dict):
continue
parameters.append({
"name": str(parameter.get("name") or "").strip(),
"mode": str(parameter.get("mode") or "single").strip(),
"values": [str(value).strip() for value in parameter.get("values") or [] if str(value).strip()],
"required": bool(parameter.get("required", False)),
"select_all": bool(parameter.get("select_all", False)),
**({"joiner": str(parameter.get("joiner") or ",")} if str(parameter.get("mode") or "") == "multi_text" else {}),
})
dynamic = str(raw.get("warehouse_resolution") or "").strip() == "alias_match"
return {
"source_code": str(raw["source_code"]).strip().upper(),
"display_name": str(raw.get("display_name") or raw["source_code"]).strip(),
"connector_type": connector_type,
"login_url": str(raw.get("entry_url") or "").strip(),
"warehouse_resolution_mode": "inventory_match" if dynamic else "fixed",
"fixed_warehouse_id": None if dynamic else str(raw.get("warehouse_id") or "").strip() or None,
"report_path_json": ({
key: str(navigation.get(key) or "").strip()
for key in ("program_group", "program_label", "report_group", "report_name")
} if connector_type == "dbs" else {}),
"query_parameters_json": parameters,
}
def _connection_for(source: dict[str, Any]) -> FreightRpaProfile:
"""Return a compatible connection, reusing configured credentials whenever possible."""
profile = FreightRpaProfile.query.filter_by(
connector_type=source["connector_type"], login_url=source["login_url"],
).order_by(FreightRpaProfile.id).first()
if profile is not None and (profile.username_ciphertext or profile.password_ciphertext):
return profile
# Legacy YAML stores the portal root while a configured DBS connection can use a portal path.
# Prefer an existing credential-bearing platform connection instead of creating an unusable duplicate.
if source["connector_type"] == "dbs":
profile = FreightRpaProfile.query.filter_by(connector_type="dbs").filter(
(FreightRpaProfile.username_ciphertext.is_not(None)) | (FreightRpaProfile.password_ciphertext.is_not(None))
).order_by(FreightRpaProfile.credential_updated_at.desc(), FreightRpaProfile.id).first()
if profile is not None:
return profile
if profile is not None:
return profile
# The historical Crane connection was initially stored as DBS before source master data existed.
if source["connector_type"] == "crane":
profile = FreightRpaProfile.query.filter_by(profile_code="CRANE").first()
if profile is not None:
profile.connector_type = "crane"
profile.login_url = source["login_url"]
return profile
code = "DBS_S360" if source["connector_type"] == "dbs" else "CRANE"
profile = FreightRpaProfile(
profile_code=code,
display_name="DBS 平台" if source["connector_type"] == "dbs" else "Crane 平台",
connector_type=source["connector_type"],
login_url=source["login_url"],
login_config_json={"auth_mode": "password"},
enabled=True,
)
db.session.add(profile)
db.session.flush()
return profile
def import_sources(path: Path) -> tuple[int, int]:
"""Idempotently insert/update YAML source master data with imported rows disabled.
Returns:
A pair of ``(created, updated)`` counts.
"""
document = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
rows = document.get("sources") if isinstance(document, dict) else None
if not isinstance(rows, list):
raise ValueError("YAML must contain a sources list")
created = updated = 0
for raw in rows:
if not isinstance(raw, dict):
continue
data = _source_payload(raw)
profile = _connection_for(data)
source = FreightRpaSource.query.filter_by(source_code=data["source_code"]).first()
if source is None:
source = FreightRpaSource(
source_code=data["source_code"], display_name=data["display_name"],
connector_type=data["connector_type"], rpa_profile=profile,
warehouse_resolution_mode=data["warehouse_resolution_mode"], enabled=False,
)
db.session.add(source)
created += 1
else:
updated += 1
source.display_name = data["display_name"]
source.connector_type = data["connector_type"]
source.rpa_profile = profile
source.excel_template_id = None
source.warehouse_resolution_mode = data["warehouse_resolution_mode"]
source.fixed_warehouse_id = data["fixed_warehouse_id"]
# s18 起报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行(无则插入);
# 解析方案绑定保持 None,与今日导入语义一致(启用前由管理员绑定)。
config = source.onhand_report_config
if config is None:
config = FreightRpaOnhandReportConfig(source=source)
db.session.add(config)
config.parsing_profile_id = None
config.report_path_json = data["report_path_json"]
config.query_parameters_json = data["query_parameters_json"]
source.snapshot_ttl_seconds = 86400
# Templates are not present in legacy YAML; activation requires published bindings.
source.enabled = False
db.session.commit()
# A previous run may have created this deterministic placeholder before a configured DBS connection was found.
placeholder = FreightRpaProfile.query.filter_by(profile_code="DBS_S360").first()
if placeholder and not placeholder.sources and not placeholder.username_ciphertext and not placeholder.password_ciphertext:
db.session.delete(placeholder)
db.session.commit()
return created, updated
def main() -> None:
"""Run the controlled YAML import and print counts without exposing credentials."""
parser = argparse.ArgumentParser(description="Import legacy freight RPA sources")
parser.add_argument("--file", type=Path, default=Path("config/freight_rpa_sources.yaml"))
args = parser.parse_args()
app = create_app()
with app.app_context():
created, updated = import_sources(args.file)
print(f"Imported freight RPA sources: created={created}, updated={updated}")
if __name__ == "__main__":
main()
@@ -2,10 +2,12 @@
用途:验证 POST /matchings 创建(含 envelope/权限/参数校验)与
GET /matchings/{id} 进度恢复;无权限 403、未认证 401;
待匹配桶「清空并重新解析」预检/执行端点(spec §6,Task 7)。
待匹配桶「清空并重新解析」预检/执行端点(spec §6,Task 7);
证据压缩包路径与当天清单(Task 5)。
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes、factories。
逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或
in_transit_transfer Agent 授权校验。
in_transit_transfer Agent 授权校验。证据下载用内存字节替换
file_asset_storage.get_bytes,清单用 presigned_get_url 替身。
"""
from __future__ import annotations
@@ -49,8 +51,9 @@ def transfer_deps(app, monkeypatch, dbs_ready_file):
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
def _resolve(*, source_code: str) -> dict:
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
# 执行门禁②(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。
del record_kind
return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64}
monkeypatch.setattr(
@@ -233,7 +236,7 @@ def test_executable_items_lists_ready_rows_with_decoration(
# 行装饰的文件对账在 matching_service 命名空间——与执行门禁②同口径替身。
monkeypatch.setattr(
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
lambda *, source_code: {"file_status": "ready", "has_ready_file": True,
lambda *, source_code, record_kind="inbound": {"file_status": "ready", "has_ready_file": True,
"file_no": "REC-TEST", "file_sha256": "d" * 64},
)
_create_matching(client, admin_headers)
@@ -605,9 +608,36 @@ def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client,
)
for i in range(25)
]
class _Rows:
"""分页测试用的查询替身:count/offset/limit/all 与 Query 同形。"""
def __init__(self, items):
self._items = items
self._offset = 0
self._limit = None
def count(self):
return len(self._items)
def offset(self, start):
self._offset = start
return self
def limit(self, size):
self._limit = size
return self
def all(self):
end = None if self._limit is None else self._offset + self._limit
return self._items[self._offset:end]
monkeypatch.setattr(
"app.services.in_transit_transfer.backlog_service.circle_ledger_records_scope_union",
lambda: rows,
lambda: [],
)
monkeypatch.setattr(
"app.services.in_transit_transfer.backlog_service.pending_ledger_query",
lambda **_kwargs: _Rows(rows),
)
legacy = client.get(f"{API_PREFIX}/backlog/pending-match", headers=admin_headers)
@@ -628,13 +658,33 @@ def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client,
def test_list_transfer_sources(app, client, admin_headers):
"""来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。"""
"""来源实例列表:返回启用来源,并附入站/出站两条证据流。
扁平 file_status / has_ready_file 必须等于入站那条,供尚未改完的前端。
生产侧漏掉 streams、把两条合成一条、或扁平字段改读出站,本用例都会失败。
"""
response = client.get(f"{API_PREFIX}/sources", headers=admin_headers)
assert response.status_code == 200
sources = response.get_json()["data"]
assert isinstance(sources, list)
# 测试种子来源 DSV360_AWSDU(dbs)应在列表中
assert any(item["source_code"] == "DSV360_AWSDU" for item in sources)
dsv = next(item for item in sources if item["source_code"] == "DSV360_AWSDU")
# 两条都返回且入站在前:前端按 record_kind 过滤,扁平字段仍跟入站。
# 种子来源没有出站报表配置,出站必须是 unconfigured,不能抄入站投影。
assert len(dsv["streams"]) == 2
assert dsv["streams"][0]["record_kind"] == "inbound"
assert set(dsv["streams"][0]) == {
"record_kind", "file_status", "has_ready_file", "file_no", "file_sha256",
}
assert dsv["streams"][1] == {
"record_kind": "outbound",
"file_status": "unconfigured",
"has_ready_file": False,
"file_no": None,
"file_sha256": None,
}
assert dsv["file_status"] == dsv["streams"][0]["file_status"]
assert dsv["has_ready_file"] == dsv["streams"][0]["has_ready_file"]
for item in sources:
assert item["source_code"]
assert item["platform"] in {"dbs", "crane"}
@@ -647,6 +697,27 @@ def test_list_transfer_sources_forbidden(app, client, unauthorized_headers):
assert response.status_code == 403
def test_reparse_current_without_file_returns_422(client, admin_headers):
# [断言意图] 没有出站归档时重解析是 422,不是 202 抓取中。
response = client.post(
f"{API_PREFIX}/sources/DSV360_AWSDU/reparse",
headers=admin_headers,
json={"record_kind": "outbound"},
)
assert response.status_code == 422
assert response.get_json()["error"]["code"] == "TRANSFER.CURRENT_REPARSE_NO_FILE"
def test_reparse_current_forbidden(client, unauthorized_headers):
# [断言意图] 无调拨权限不能重解析。
response = client.post(
f"{API_PREFIX}/sources/DSV360_AWSDU/reparse",
headers=unauthorized_headers,
json={"record_kind": "inbound"},
)
assert response.status_code == 403
# ---------------------------------------------------------------------------
# Task 4:retry-rpa 对 parse_failed 先本地重解析(成功 200+ready / 仍失败 ok=False;
# 两条路径均不触发 RPA、不返回 202/fetching)
@@ -801,6 +872,310 @@ def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_h
assert [item["source_code"] for item in body["results"]] == ["DSV360_AWSDU", "DSV360_AWSSG"]
def _ensure_hub_to_hub_both_streams():
"""启用 hub_to_hub,范围规则显式包含入站与出站两条证据流。
核心逻辑:类型表没有 record_kinds 列。record_kinds_of 从 record_kind
规则推导;不写该规则时也会得到双流。这里用 match=in 写明两个值,
批量重试才能同时看到入站与出站。已存在则直接复用。
"""
from app.core.errors import ValidationError
from app.services.in_transit_transfer.transfer_type_config_service import (
create_config,
get_by_code,
)
try:
return get_by_code("hub_to_hub")
except ValidationError:
return create_config({
"code": "hub_to_hub",
"names": {"zh-CN": "仓间调拨"},
"enabled": True,
"scope_rules": [
{"field": "record_kind", "match": "in", "values": ["inbound", "outbound"]},
],
})
def _stream_status(file_status: str) -> dict:
"""投影替身的最小状态字典(与 resolve_source_file_status 四键一致)。"""
ready = file_status == "ready"
return {
"file_status": file_status,
"has_ready_file": ready,
"file_no": "a.xlsx" if ready else None,
"file_sha256": "abc" if ready or file_status == "parse_failed" else None,
}
def test_batch_retry_skips_ready_inbound_and_triggers_outbound(app, client, admin_headers, monkeypatch):
"""HUB 仓间调拨:入站已就绪不重抓,出站未就绪才触发。"""
import app.api.in_transit_transfer as api_module
_ensure_hub_to_hub_both_streams()
def fail_inbound(**kwargs):
raise AssertionError("inbound batch")
called = {}
def record_outbound(**kwargs):
called["codes"] = kwargs["source_codes"]
return {"ok": True, "triggered": True}
def status(*, source_code, record_kind="inbound"):
if record_kind == "outbound":
return {"file_status": "none", "has_ready_file": False, "file_no": None, "file_sha256": None}
return {"file_status": "ready", "has_ready_file": True, "file_no": "a.xlsx", "file_sha256": "abc"}
monkeypatch.setattr(api_module, "trigger_inbound_rpa_batch", fail_inbound)
monkeypatch.setattr(api_module, "trigger_outbound_rpa_batch", record_outbound)
monkeypatch.setattr(api_module, "resolve_source_file_status", status)
response = client.post("/api/in-transit-transfer/sources/retry-rpa-batch", json={
"source_codes": ["DSV360_AWSBI"],
"transfer_type": "hub_to_hub",
}, headers=admin_headers)
# 断言意图:入站 ready 不进 trigger;出站 none 只写出站 batch,并回 202。
assert response.status_code == 202
assert called["codes"] == ["DSV360_AWSBI"]
def test_retry_rpa_outbound_triggers_outbound_rpa(app, client, admin_headers, monkeypatch):
"""单源重试带 record_kind=outbound 时走出站触发,不碰入站。"""
called = {}
def fail_inbound(**kwargs):
raise AssertionError("inbound")
def record_outbound(**kwargs):
called["source_code"] = kwargs["source_code"]
called["reason"] = kwargs["reason"]
return {"ok": True, "callback_id": "cb-out"}
monkeypatch.setattr(
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa",
fail_inbound,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa",
record_outbound,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
lambda *, source_code, record_kind="inbound": _stream_status("none"),
)
response = client.post(
f"{API_PREFIX}/sources/DSV360_AWSBI/retry-rpa",
headers=admin_headers,
json={"record_kind": "outbound"},
)
# 断言意图:缺省才是入站;显式 outbound 必须 202 且 reason 为出站重试。
assert response.status_code == 202
assert called["source_code"] == "DSV360_AWSBI"
assert called["reason"] == "transfer_retry_outbound"
assert response.get_json()["data"]["file_status"] == "fetching"
def test_retry_rpa_outbound_parse_failed_retriggers_outbound_rpa(app, client, admin_headers, monkeypatch):
"""出站 parse_failed 重新触发出站 RPA,不走入站本地重解析。"""
called = {"sync": 0, "outbound": 0}
def status(*, source_code, record_kind="inbound"):
if record_kind == "outbound":
return _stream_status("parse_failed")
return _stream_status("ready")
def fake_sync(**kwargs):
called["sync"] += 1
return True
def fail_inbound(**kwargs):
raise AssertionError("inbound")
def record_outbound(**kwargs):
called["outbound"] += 1
return {"ok": True, "callback_id": "cb-out"}
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
status,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback",
fake_sync,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa",
fail_inbound,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa",
record_outbound,
)
response = client.post(
f"{API_PREFIX}/sources/DSV360_AWSBI/retry-rpa",
headers=admin_headers,
json={"record_kind": "outbound"},
)
# 断言意图:本地重解析只留给入站;出站解析失败仍是一次 RPA 重抓。
assert response.status_code == 202
assert called["sync"] == 0
assert called["outbound"] == 1
def test_batch_retry_records_unconfigured_without_trigger(app, client, admin_headers, monkeypatch):
"""未配置的流不写 trigger,结果 ok=false 且沿用既有配置缺失码。"""
_ensure_hub_to_hub_both_streams()
called = {}
def record_inbound(**kwargs):
called["inbound"] = list(kwargs["source_codes"])
return {"ok": True, "triggered": True, "results": []}
def record_outbound(**kwargs):
called["outbound"] = list(kwargs["source_codes"])
return {"ok": True, "triggered": True, "results": []}
monkeypatch.setattr(
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch",
record_inbound,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa_batch",
record_outbound,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
lambda *, source_code, record_kind="inbound": _stream_status("unconfigured"),
)
response = client.post(
f"{API_PREFIX}/sources/retry-rpa-batch",
headers=admin_headers,
json={"source_codes": ["DSV360_AWSBI"], "transfer_type": "hub_to_hub"},
)
# 断言意图:两条流都是 unconfigured 时两个 batch 都不写,并各记配置缺失码。
assert response.status_code == 200
assert "inbound" not in called and "outbound" not in called
body = response.get_json()["data"]
assert body["ok"] is False
assert body["triggered"] is False
assert body["results"] == [
{
"source_code": "DSV360_AWSBI",
"record_kind": "inbound",
"ok": False,
"error_code": "RPA_INBOUND_CONFIG_MISSING",
},
{
"source_code": "DSV360_AWSBI",
"record_kind": "outbound",
"ok": False,
"error_code": "RPA_OUTBOUND_CONFIG_MISSING",
},
]
def test_batch_retry_skips_fetching_stream(app, client, admin_headers, monkeypatch):
"""抓取中的流不写入 trigger。"""
_ensure_hub_to_hub_both_streams()
called = {}
def record(**kwargs):
called["codes"] = list(kwargs["source_codes"])
return {"ok": True, "triggered": True, "results": []}
monkeypatch.setattr(
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch",
record,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa_batch",
record,
)
def status(*, source_code, record_kind="inbound"):
if record_kind == "outbound":
return _stream_status("fetching")
return _stream_status("ready")
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
status,
)
response = client.post(
f"{API_PREFIX}/sources/retry-rpa-batch",
headers=admin_headers,
json={"source_codes": ["DSV360_AWSBI"], "transfer_type": "hub_to_hub"},
)
# 断言意图:ready 与 fetching 都跳过,不回 202,结果为空。
assert response.status_code == 200
assert called == {}
body = response.get_json()["data"]
assert body["ok"] is True
assert body["triggered"] is False
assert body["results"] == []
def test_batch_retry_groups_one_batch_per_stream(app, client, admin_headers, monkeypatch):
"""同一请求最多一个入站 batch 和一个出站 batch,结果带 record_kind。"""
_ensure_hub_to_hub_both_streams()
calls = []
def record_inbound(**kwargs):
calls.append(("inbound", list(kwargs["source_codes"]), kwargs["reason"]))
return {
"ok": True,
"triggered": True,
"results": [{"source_code": code, "ok": True} for code in kwargs["source_codes"]],
}
def record_outbound(**kwargs):
calls.append(("outbound", list(kwargs["source_codes"]), kwargs["reason"]))
return {
"ok": True,
"triggered": True,
"results": [{"source_code": code, "ok": True} for code in kwargs["source_codes"]],
}
monkeypatch.setattr(
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch",
record_inbound,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa_batch",
record_outbound,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
lambda *, source_code, record_kind="inbound": _stream_status("none"),
)
response = client.post(
f"{API_PREFIX}/sources/retry-rpa-batch",
headers=admin_headers,
json={
"source_codes": ["DSV360_AWSBI", "DSV360_AWSDU"],
"transfer_type": "hub_to_hub",
},
)
# 断言意图:两个来源按流合并成各一次 batch,而不是逐来源各写一个文件。
assert response.status_code == 202
assert calls == [
("inbound", ["DSV360_AWSBI", "DSV360_AWSDU"], "transfer_retry_inbound"),
("outbound", ["DSV360_AWSBI", "DSV360_AWSDU"], "transfer_retry_outbound"),
]
pairs = {
(item["source_code"], item["record_kind"])
for item in response.get_json()["data"]["results"]
}
assert pairs == {
("DSV360_AWSBI", "inbound"),
("DSV360_AWSBI", "outbound"),
("DSV360_AWSDU", "inbound"),
("DSV360_AWSDU", "outbound"),
}
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
@@ -978,8 +1353,9 @@ def _custom_transfer_deps(monkeypatch, rows: list[dict], stocks: list[tuple[str,
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
def _resolve(*, source_code: str) -> dict:
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
# 执行门禁②(文件版本对账)替身:与 transfer_deps 夹具同语义。
del record_kind
return {"file_status": "ready", "has_ready_file": True,
"file_no": "REC-TEST", "file_sha256": "d" * 64}
@@ -1679,3 +2055,282 @@ def test_pending_match_reparse_forbidden_without_permission(app, client, unautho
json={"source_code": "X"})
assert preview.status_code == 403
assert execute.status_code == 403
# ---------------------------------------------------------------------------
# Task 5:证据压缩包按记录类型分目录;当天清单只列可用文件的大小与预签地址
# ---------------------------------------------------------------------------
EVIDENCE_SOURCE = "DSV360_AWSBI"
_INBOUND_ONLY_TYPE = "evidence_inbound_only"
def _ensure_inbound_only_type():
"""启用一个范围规则把记录类型收成只要 inbound 的调拨类型。
核心逻辑:没有 record_kinds 列。equals inbound 的 record_kind 规则经
record_kinds_of 只得到入站。已存在则复用。
"""
from app.core.errors import ValidationError
from app.services.in_transit_transfer.transfer_type_config_service import (
create_config,
get_by_code,
)
try:
return get_by_code(_INBOUND_ONLY_TYPE)
except ValidationError:
return create_config({
"code": _INBOUND_ONLY_TYPE,
"names": {"zh-CN": "仅入站证据"},
"enabled": True,
"scope_rules": [
{"field": "record_kind", "match": "equals", "values": ["inbound"]},
],
})
def _ensure_evidence_source():
"""保证 DSV360_AWSBI 来源存在(压缩包路径用这个编码)。"""
from tests.services.in_transit_transfer.factories import seed_inbound_reparse_source
source, _profile = seed_inbound_reparse_source(EVIDENCE_SOURCE)
return source
def _seed_evidence_file(
source,
*,
kind: str,
filename: str,
storage_key: str,
sha: str,
file_size: int,
created_at: datetime,
deleted: bool = False,
):
"""写入一条入站或出站归档。created_at 决定是否落在当天可用窗口。"""
from app.models import (
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
)
if kind == "outbound":
unit_model, file_model = FreightRpaOutboundUnitRun, FreightRpaOutboundReportFile
else:
unit_model, file_model = FreightRpaInboundUnitRun, FreightRpaInboundReportFile
unit = unit_model(
source_id=source.id,
source_code=source.source_code,
connector_type=source.connector_type,
warehouse_id=source.fixed_warehouse_id,
callback_id=f"{kind}-{sha[:16]}",
status="success",
config_snapshot_json={},
trigger_snapshot_json={},
result_json={},
)
db.session.add(unit)
db.session.flush()
report = file_model(
unit_run_id=unit.id,
storage_provider="minio",
storage_bucket="test",
storage_key=storage_key,
original_filename=filename,
file_size=file_size,
sha256=sha,
created_at=created_at,
archive_deleted_at=created_at if deleted else None,
)
db.session.add(report)
db.session.commit()
return report
def _patch_archive_bytes(monkeypatch, objects: dict[str, bytes]) -> None:
"""用内存字节替换对象存储读取,避免下载测试连接 MinIO。"""
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes",
lambda storage_key: objects[storage_key],
)
def _zip_entries(response) -> dict[str, bytes]:
"""用 zipfile 读响应体,返回归档路径到原始字节。"""
import io
import zipfile
with zipfile.ZipFile(io.BytesIO(response.data)) as archive:
return {name: archive.read(name) for name in archive.namelist()}
def test_evidence_zip_packs_inbound_only_when_scope_rule_equals_inbound(
app, client, admin_headers, monkeypatch,
):
"""范围规则 record_kind equals inbound 时,压缩包只有入站最新文件。"""
from datetime import timedelta
now = datetime.utcnow().replace(microsecond=0)
source = _ensure_evidence_source()
_ensure_inbound_only_type()
_seed_evidence_file(
source, kind="inbound", filename="OldInbound.xlsx",
storage_key="evidence/old-inbound", sha="31" * 32, file_size=10,
created_at=now - timedelta(minutes=10),
)
_seed_evidence_file(
source, kind="inbound", filename="Inbound.xlsx",
storage_key="evidence/inbound", sha="11" * 32, file_size=12,
created_at=now,
)
_seed_evidence_file(
source, kind="outbound", filename="Outbound.xlsx",
storage_key="evidence/outbound", sha="22" * 32, file_size=13,
created_at=now,
)
_patch_archive_bytes(monkeypatch, {
"evidence/old-inbound": b"OLD-INBOUND",
"evidence/inbound": b"INBOUND-RAW",
"evidence/outbound": b"OUTBOUND-RAW",
})
response = client.post(
f"{API_PREFIX}/sources/inbound-files",
headers=admin_headers,
json={"source_codes": [EVIDENCE_SOURCE], "transfer_type": _INBOUND_ONLY_TYPE},
)
assert response.status_code == 200
entries = _zip_entries(response)
# 断言意图:目录是记录类型/来源/文件名,且只打最新一份入站,不打出站。
assert entries == {f"inbound/{EVIDENCE_SOURCE}/Inbound.xlsx": b"INBOUND-RAW"}
assert not any(name.startswith("outbound/") for name in entries)
assert "evidence-files-1.zip" in response.headers.get("Content-Disposition", "")
with app.app_context():
from app.models import TransferAuditEvent
audit = TransferAuditEvent.query.filter_by(
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
).one()
assert audit.aggregate_id == EVIDENCE_SOURCE
def test_evidence_zip_packs_both_kinds_without_record_kind_rule(
app, client, admin_headers, monkeypatch,
):
"""没有 record_kind 范围规则时,入站和出站就绪文件都打进包。"""
now = datetime.utcnow().replace(microsecond=0)
source = _ensure_evidence_source()
_seed_evidence_file(
source, kind="inbound", filename="Inbound.xlsx",
storage_key="evidence/both-inbound", sha="41" * 32, file_size=12,
created_at=now,
)
_seed_evidence_file(
source, kind="outbound", filename="Outbound.xlsx",
storage_key="evidence/both-outbound", sha="42" * 32, file_size=13,
created_at=now,
)
_patch_archive_bytes(monkeypatch, {
"evidence/both-inbound": b"INBOUND-RAW",
"evidence/both-outbound": b"OUTBOUND-RAW",
})
response = client.post(
f"{API_PREFIX}/sources/inbound-files",
headers=admin_headers,
json={"source_codes": [EVIDENCE_SOURCE], "transfer_type": "in_transit_to_hub"},
)
assert response.status_code == 200
entries = _zip_entries(response)
# 断言意图:默认类型只有单号前缀规则,两种就绪文件都按记录类型分目录。
assert entries == {
f"inbound/{EVIDENCE_SOURCE}/Inbound.xlsx": b"INBOUND-RAW",
f"outbound/{EVIDENCE_SOURCE}/Outbound.xlsx": b"OUTBOUND-RAW",
}
assert "evidence-files-2.zip" in response.headers.get("Content-Disposition", "")
with app.app_context():
from app.models import TransferAuditEvent
audit = TransferAuditEvent.query.filter_by(
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
).one()
assert audit.event_type == "TRANSFER_INBOUND_FILES_DOWNLOADED"
def test_evidence_files_list_returns_today_size_and_presigned_url(
app, client, admin_headers, monkeypatch,
):
"""当天清单返回全部可用入站文件的大小与预签地址,不解析行数。"""
from datetime import timedelta
now = datetime.utcnow().replace(microsecond=0)
source = _ensure_evidence_source()
newer = _seed_evidence_file(
source, kind="inbound", filename="Inbound.xlsx",
storage_key="evidence/list-new", sha="51" * 32, file_size=111,
created_at=now,
)
older = _seed_evidence_file(
source, kind="inbound", filename="Older.xlsx",
storage_key="evidence/list-old", sha="52" * 32, file_size=222,
created_at=now - timedelta(minutes=20),
)
_seed_evidence_file(
source, kind="inbound", filename="Yesterday.xlsx",
storage_key="evidence/list-yesterday", sha="53" * 32, file_size=333,
created_at=now - timedelta(days=2),
)
_seed_evidence_file(
source, kind="inbound", filename="Deleted.xlsx",
storage_key="evidence/list-deleted", sha="54" * 32, file_size=444,
created_at=now, deleted=True,
)
signed = []
def _presign(storage_key, *, expires_seconds):
signed.append((storage_key, expires_seconds))
return f"https://files.test/{storage_key}"
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.presigned_get_url",
_presign,
)
response = client.get(
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files?record_kind=inbound",
headers=admin_headers,
)
assert response.status_code == 200
rows = response.get_json()["data"]
# 断言意图:当天两份都在,隔日与已清理不在;字段是文件大小和预签地址,没有行数。
assert [row["original_filename"] for row in rows] == ["Inbound.xlsx", "Older.xlsx"]
assert rows[0]["file_id"] == newer.id
assert rows[1]["file_id"] == older.id
assert rows[0]["file_size"] == 111
assert rows[1]["file_size"] == 222
assert rows[0]["sha256"] == "51" * 32
assert rows[0]["created_at"] == now.isoformat()
assert rows[0]["presigned_url"] == "https://files.test/evidence/list-new"
assert rows[1]["presigned_url"] == "https://files.test/evidence/list-old"
for row in rows:
assert set(row) == {
"file_id", "original_filename", "created_at", "sha256", "file_size", "presigned_url",
}
assert "rows" not in row and "row_count" not in row
assert signed == [
("evidence/list-new", 300),
("evidence/list-old", 300),
]
with app.app_context():
from app.models import TransferAuditEvent
audit = TransferAuditEvent.query.filter_by(
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
).one()
assert audit.aggregate_id == EVIDENCE_SOURCE
+15 -5
View File
@@ -267,9 +267,13 @@ def test_admin_create_rejects_non_object_body(app, client, admin_headers):
def test_chat_transfer_types_returns_enabled_only_with_minimal_fields(
app, client, warehouse_headers,
):
"""chat 列表:仅启用项、sort_order 升序、最小暴露(不含范围规则/仓库定义等)。"""
"""chat 列表:仅启用项、sort_order 升序、最小暴露,并附推导出的 record_kinds。"""
_seed_type(sort_order=20)
_seed_type(code="hub_to_line", sort_order=10)
_seed_type(
code="hub_to_line",
sort_order=10,
scope_rules=[{"field": "record_kind", "match": "equals", "values": ["inbound"]}],
)
_seed_type(code="disabled_type", enabled=False, sort_order=1)
response = client.get(CHAT_PREFIX, headers=warehouse_headers)
assert response.status_code == 200
@@ -279,9 +283,15 @@ def test_chat_transfer_types_returns_enabled_only_with_minimal_fields(
# [断言意图] 仅 enabled 限定 + sort_order 升序是前端类型选择器的顺序契约。
assert [item["code"] for item in data] == ["hub_to_line", "in_transit_to_hub"]
for item in data:
# [断言意图] 最小暴露硬契约:响应 key 集合恰为四键——scope_rules/
# warehouse_config/description 属管理端配置资产,禁止泄露。
assert set(item.keys()) == {"code", "names", "sort_order", "transform_rules"}
# [断言意图] 最小暴露:在原四键上只增加 record_kinds。scope_rules /
# warehouse_config / description 仍不回传。record_kinds 由
# record_kinds_of 现算:hub_to_line 只写 inbound,另一条没有
# 记录类型规则所以入站和出站都要。
assert set(item.keys()) == {
"code", "names", "sort_order", "transform_rules", "record_kinds",
}
assert data[0]["record_kinds"] == ["inbound"]
assert data[1]["record_kinds"] == ["inbound", "outbound"]
assert data[0]["transform_rules"] == [
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
]
+8 -5
View File
@@ -700,6 +700,8 @@ def dbs_ready_file() -> dict:
rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date),
与真实仓库 movement_file_repository 产出一致(B5 接线后 run_matching 按
parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。
【T−2 成熟封顶 2026-10-21】rows 异动日期取 2026-08-04(= 业务日 08-06 的
T−2 恰好成熟边界);更晚日期(T−1/当天)已被圈档封顶排除,不得再作夹具日期。
"""
return {
"source_code": "DBS-AWSBI",
@@ -712,13 +714,13 @@ def dbs_ready_file() -> dict:
"rows": [
{"sheet": "Receipt", "row_no": 10, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "500", "unit": "个", "source_code": "DBS-AWSBI"},
"movement_date": "2026-08-04", "quantity": "500", "unit": "个", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 11, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "700", "unit": "个", "source_code": "DBS-AWSBI"},
"movement_date": "2026-08-04", "quantity": "700", "unit": "个", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 20, "doc_no": "HOX-002", "lot_no": "LOT-20", "material_code": "MAT-002",
"material_name": "控制器组件", "specification": "标准型 / 48V",
"movement_date": "2026-08-05", "quantity": "1200", "unit": "PCS", "source_code": "DBS-AWSBI"},
"movement_date": "2026-08-04", "quantity": "1200", "unit": "PCS", "source_code": "DBS-AWSBI"},
],
}
@@ -728,6 +730,7 @@ def crane_ready_file() -> dict:
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
异动日期=T−2 成熟边界(见 dbs_ready_file 注释)。
"""
return {
"source_code": "CRANE-SZ",
@@ -740,14 +743,14 @@ def crane_ready_file() -> dict:
"rows": [
{"sheet": "Inbound", "row_no": 5, "doc_no": "WTP-008", "lot_no": "LOT-8", "material_code": "MAT-200",
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
"movement_date": "2026-08-05", "quantity": "600", "unit": "PCS", "source_code": "CRANE-SZ"},
"movement_date": "2026-08-04", "quantity": "600", "unit": "PCS", "source_code": "CRANE-SZ"},
],
}
@pytest.fixture
def same_day_inbound_file() -> dict:
"""含业务日期当天异动数据的文件(成熟规则已退役:当天数据正常进匹配)。
"""含业务日期当天异动数据的文件(T−2 成熟封顶 2026-10-21:当天未成熟不匹配)。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
"""
@@ -40,8 +40,9 @@ def transfer_deps(app, monkeypatch, dbs_ready_file):
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
def _resolve(*, source_code: str) -> dict:
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
# 执行门禁②(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。
del record_kind
return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64}
monkeypatch.setattr(
@@ -48,7 +48,7 @@ def test_bulk_matching_300_invoices(transfer_db):
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
started = time.perf_counter()
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
elapsed = time.perf_counter() - started
assert summary.counts.executable_count == 300
assert summary.counts.file_invoice_count == 300
@@ -79,9 +79,10 @@ def wecom_fake() -> FakeWeCom:
def patch_source_file_status(monkeypatch):
"""执行文件对账门禁替身工厂:替换 execution_service 的来源文件状态投影。
用途:execute_items 门禁②按去重来源调 resolve_source_file_status(真实查询
收料文件表);单元测试注入替身避免触碰表数据。缺省全部来源投影为
ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file 行版本戳同源)。
用途:execute_items 门禁②按 (来源, record_kind) 调 resolve_source_file_status
(真实查询收料/出站文件表);单元测试注入替身避免触碰表数据。缺省全部
来源投影为 ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file
行版本戳同源)。record_kind 入参接受但不区分,存量用例仍按来源给 sha。
Args:
mapping: source_code → sha 映射;值为 None 表示该来源无可用文件
@@ -92,7 +93,8 @@ def patch_source_file_status(monkeypatch):
def _patch(mapping: dict[str, str | None] | None = None) -> None:
table = mapping or {}
def _resolve(*, source_code: str) -> dict:
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
del record_kind # 本替身按来源给 sha;出站分流用例自行覆盖本函数。
if source_code in table:
sha = table[source_code]
if sha is None:
@@ -252,7 +252,8 @@ def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1"
movement_date: str = "2026-08-05",
transfer_executed: bool = False,
executed_doc_no: str | None = None,
updated_at: datetime | None = None):
updated_at: datetime | None = None,
record_kind: str = "inbound"):
"""插一条旧映射库存异动档行(清空重建用例种子;业务值=旧映射形态)。
Args:
@@ -263,6 +264,7 @@ def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1"
quantity / material_code / material_name / movement_date: 旧业务值。
transfer_executed / executed_doc_no: 封存形态注入。
updated_at: 显式更新时间(封存不动行断言用)。
record_kind: inbound(默认)或 outbound。
Returns:
已入库的 TransferMovementLedger。
"""
@@ -270,7 +272,7 @@ def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1"
from app.models import TransferMovementLedger
row = TransferMovementLedger(
source_code=source_code, record_kind="inbound",
source_code=source_code, record_kind=record_kind,
doc_no=doc_no, line_no=line_no, line_seq="", in_out_flag=in_out_flag,
carton_id="", lot_no=lot_no,
material_code=material_code, material_name=material_name,
@@ -282,3 +284,79 @@ def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1"
db.session.add(row)
db.session.commit()
return row
def seed_outbound_reparse_source(source_code: str, *, profile_code: str | None = None,
version: int = 1, status: str = "published"):
"""建「启用来源 + 已发布 outbound 解析规则 + 出站配置绑定」种子(幂等)。
用途:清空并重新解析出站流用例。若来源已存在则只补出站配置/规则。
Returns:
(FreightRpaSource, FreightRpaParsingProfile) 元组。
"""
from app import db
from app.models import (
FreightRpaOutboundReportConfig,
FreightRpaParsingProfile,
FreightRpaSource,
)
source, _inbound = seed_inbound_reparse_source(source_code)
existing = source.outbound_report_config
if existing is not None and existing.parsing_profile is not None:
return source, existing.parsing_profile
resolved_code = profile_code or f"OUT_{source_code}"
profile = FreightRpaParsingProfile(
purpose="outbound", profile_code=resolved_code, display_name=resolved_code,
version=version, status=status, file_format="xlsx",
definition_json={
"sheet_name": "Receipt", "header_row_index": 1,
"field_mapping": dict(INBOUND_MOVEMENT_FIELD_MAPPING),
},
structure_definition_json={},
)
db.session.add(profile)
db.session.flush()
if existing is None:
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id, parsing_profile_id=profile.id,
report_path_json={"report_name": "Outbound"},
query_parameters_json=[],
))
else:
existing.parsing_profile_id = profile.id
db.session.commit()
return source, profile
def seed_reparse_outbound_archive_file(source, *, sha: str, storage_key: str,
created_at: datetime,
archive_expires_at: datetime | None = None,
callback_id: str | None = None):
"""建一条出站执行单元 + 归档文件行(清空重建出站用例种子)。
Returns:
已入库的 FreightRpaOutboundReportFile。
"""
from app import db
from app.models import FreightRpaOutboundReportFile, FreightRpaOutboundUnitRun
unit = FreightRpaOutboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type, warehouse_id="AWSDU",
callback_id=callback_id or f"out-cb-{sha[:12]}",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = FreightRpaOutboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=storage_key, original_filename=f"{callback_id or 'out'}.xlsx",
file_size=16, sha256=sha, created_at=created_at,
archive_expires_at=archive_expires_at,
)
db.session.add(report)
db.session.commit()
return report
@@ -6,7 +6,7 @@
占用行幸存;④证据缺失(归档已清理/过保留期/无溯源)的行保留并计入
kept_unrebuildable;⑤预检形状(files/profile/clearable_rows/kept_rows)。
依赖:factories(来源/归档/档行种子 + FakeArchiveStorage + build_movement_xlsx)、
app fixture。
ledger_sync.movement_file_version、app fixture。
逻辑:归档文件字节经假存储注入(monkeypatch file_asset_storage.get_bytes);
归档文件 created_at 均早于 NOW 数日——若 repository 仍带运行期「当日抓取」
门禁则清单为空,本套件即红(锁定维护路径无当日门禁)。
@@ -27,6 +27,7 @@ from app.models import (
TransferMovementLedger,
)
from app.services.in_transit_transfer import evidence_sync
from app.services.in_transit_transfer.ledger_sync import movement_file_version
from app.services.in_transit_transfer.backlog_reparse_service import (
preview_pending_match_reparse,
reparse_pending_match,
@@ -107,7 +108,8 @@ def test_reparse_clears_and_relands(app, archive_storage):
# (真实 source_file_id / sha256: 版本戳),不再是旧映射值。
assert a1.quantity == "500" and a1.material_code == "MAT-1"
assert a1.file_sha256 == SHA_A and a1.source_file_id == file_a.id
assert str(a1.file_version).startswith("sha256:a")
# [断言意图] 重建写入的版本戳走 movement_file_version,与运行期落档同一串。
assert a1.file_version == movement_file_version(SHA_A)
assert a1.movement_date == "2026-08-05"
# [断言意图] 文件顺序:按归档时间升序逐文件重落(files 概要 A 在前)。
assert [f["sha256"] for f in outcome.files] == [SHA_A, SHA_B]
@@ -118,6 +120,7 @@ def test_reparse_clears_and_relands(app, archive_storage):
assert event.aggregate_id == SOURCE
payload = event.after_json
assert payload["operator"] == "admin" and payload["source_code"] == SOURCE
assert payload["record_kind"] == "inbound"
assert payload["cleared"] == 3 and payload["reinserted"] == 3
assert payload["date_skipped"] == 0 and payload["kept"] == 0
assert payload["profile_code"] == profile.profile_code
@@ -244,7 +247,10 @@ def test_preview_shape(app, archive_storage):
preview = preview_pending_match_reparse(source_code=SOURCE, now=NOW)
assert set(preview.keys()) == {"files", "profile", "clearable_rows", "kept_rows"}
assert set(preview.keys()) == {
"record_kind", "files", "profile", "clearable_rows", "kept_rows",
}
assert preview["record_kind"] == "inbound"
assert preview["profile"] == {"code": profile.profile_code, "version": 1}
assert [f["sha256"] for f in preview["files"]] == [SHA_A, SHA_B] # 归档时间升序
assert preview["files"][0]["archived_at"] == datetime(2026, 10, 10, 8, 0, 0).isoformat()
@@ -370,3 +376,66 @@ def test_reparse_writes_collapse_audit_for_multi_material_same_key(app, archive_
# [断言意图] 重建概要事件携带坍缩计数(运维一眼判断本次重建是否有数据质量降级)。
reparse_event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert reparse_event.after_json["collapses"] == 1
def test_outbound_reparse_clears_and_relands_without_touching_inbound(app, archive_storage):
"""出站流清空重建:只动 record_kind=outbound,入站档行幸存。"""
source, profile = factories.seed_outbound_reparse_source(SOURCE)
out_file = factories.seed_reparse_outbound_archive_file(
source, sha=SHA_A, storage_key=f"archive/{SOURCE}/out-a.xlsx",
created_at=datetime(2026, 10, 10, 8, 0, 0),
)
archive_storage.objects[f"archive/{SOURCE}/out-a.xlsx"] = factories.build_movement_xlsx([
["HOX-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-08-05"],
])
# 入站旧行 + 出站旧行并存:出站重建不得误删入站。
factories.seed_reparse_ledger_row(
SOURCE, "ASN-IN1", source_file_id=None, sha=OLD_SHA, record_kind="inbound",
)
factories.seed_reparse_ledger_row(
SOURCE, "HOX-O1", source_file_id=out_file.id, sha=OLD_SHA,
quantity="1", record_kind="outbound", in_out_flag="O",
)
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="inbound").count() == 1
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 1
outcome = reparse_pending_match(
source_code=SOURCE, operator="admin", now=NOW, record_kind="outbound",
)
assert outcome.record_kind == "outbound"
assert (outcome.cleared, outcome.reinserted) == (1, 1)
db.session.expire_all()
# [断言意图] 入站行未动;出站行按新映射重落。
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="inbound", doc_no="ASN-IN1").count() == 1
out_row = TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound", doc_no="HOX-O1").one()
assert out_row.quantity == "120" and out_row.material_code == "MAT-O1"
assert out_row.source_file_id == out_file.id and out_row.file_sha256 == SHA_A
# [断言意图] 出站重建的版本戳同样走共享函数。
assert out_row.file_version == movement_file_version(SHA_A)
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert event.after_json["record_kind"] == "outbound"
assert event.after_json["profile_code"] == profile.profile_code
def test_outbound_preview_uses_outbound_archives(app, archive_storage):
"""出站预检只统计 outbound 归档与档行。"""
source, profile = factories.seed_outbound_reparse_source(SOURCE)
out_file = factories.seed_reparse_outbound_archive_file(
source, sha=SHA_A, storage_key=f"archive/{SOURCE}/out-preview.xlsx",
created_at=datetime(2026, 10, 10, 8, 0, 0),
)
factories.seed_reparse_ledger_row(
SOURCE, "HOX-P1", source_file_id=out_file.id, sha=SHA_A, record_kind="outbound",
)
preview = preview_pending_match_reparse(
source_code=SOURCE, now=NOW, record_kind="outbound",
)
assert preview["record_kind"] == "outbound"
assert preview["profile"] == {"code": profile.profile_code, "version": 1}
assert preview["clearable_rows"] == 1
assert len(preview["files"]) == 1 and preview["files"][0]["sha256"] == SHA_A
@@ -59,7 +59,7 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file):
updated_at 会让正在处理的行跳位(用户实测:恢复后被处理的行跳到列表末尾)。
业务稳定键下,触碰前后列表顺序完全一致。
"""
_blocked_matching(dbs_ready_file) # HOM-001(inbound 2026-08-05)与 HOX-002 不进池,构造两笔 blocked
_blocked_matching(dbs_ready_file) # HOM-001(inbound 2026-08-04)与 HOX-002 不进池,构造两笔 blocked
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
# 手工造第二笔 blocked:不同收料日期、更晚创建
second = TransferInvoiceItem(
@@ -75,7 +75,7 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file):
db.session.commit()
invoices = [dto.invoice_no for dto in list_backlog()]
# 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-05),尽管它刚被触碰过
# 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-04),尽管它刚被触碰过
# (两行同来源,数据源键不改变先后)。
assert invoices == ["HOM-002", "HOM-001"]
@@ -142,4 +142,5 @@ def test_backlog_summary_includes_pending_match_count(transfer_db, dbs_ready_fil
summary = backlog_summary()
assert summary.pending_match_count == 1 # [断言意图] 待匹配桶计数独立于行桶
assert summary.matchable_count == 1 # [断言意图] 范围内未匹配行同时计入可匹配
assert summary.recoverable_count == 1 # [断言意图] 原行桶语义保持
@@ -0,0 +1,277 @@
"""current_file_reparse:当前归档重解析(不触发 RPA)守卫矩阵。
用途:锁定「当前最新可用入站/出站归档本地重解析落档」——成功落档、幂等跳过、
入站/出站 schema 失败标 parse_failed、无规则/无文件 fail-closed、
非 schema 异常与存储 AppError 回 ok=false 且不回标。
依赖:factories、movement_file_version、app fixture、core.errors.ServiceUnavailableError;
出站种子 DSV360_AWSDU,入站种子 seed_inbound_reparse_source。
逻辑:归档字节经假存储注入;不新增 RPA 执行单元。
"""
from __future__ import annotations
import logging
from datetime import datetime
import pytest
from app import db
from app.core.errors import AppError, ServiceUnavailableError
from app.models import (
FreightRpaInboundReportFile,
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
FreightRpaParsingProfile,
TransferAuditEvent,
TransferMovementLedger,
)
from app.services.in_transit_transfer.current_file_reparse import reparse_current_file
from app.services.in_transit_transfer.ledger_sync import movement_file_version
from tests.services.in_transit_transfer import factories
pytestmark = [pytest.mark.usefixtures("app")]
SOURCE = "DSV360_AWSDU"
STORAGE_KEY = "shipping/outbound/evidence-sync.xlsx"
@pytest.fixture
def outbound_storage(monkeypatch):
"""归档假存储:替换单例 get_bytes(所有引用方同源)。"""
fake = factories.FakeArchiveStorage()
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
return fake
@pytest.fixture
def archive_storage(monkeypatch):
"""归档假存储:注入 FakeArchiveStorage 并替换单例 get_bytes(所有引用方同源)。"""
fake = factories.FakeArchiveStorage()
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
return fake
def _seed_outbound_world(*, profile_status: str = "published") -> FreightRpaOutboundReportFile:
"""出站世界种子:出站配置(绑定解析规则)+ 执行单元 + 当天可用归档文件行。
Returns:
已入库的 FreightRpaOutboundReportFile(字节由用例注入假存储)。
"""
from app.models import FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SOURCE).one()
profile = FreightRpaParsingProfile(
purpose="outbound", profile_code=f"OUT_{SOURCE}", display_name=SOURCE,
version=1, status=profile_status, file_format="xlsx",
definition_json={
"field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING,
"sheet_name": "Receipt", "header_row_index": 1,
},
structure_definition_json={},
)
db.session.add(profile)
db.session.flush()
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={"report_name": "Outbound"},
query_parameters_json=[],
parsing_profile_id=profile.id,
))
unit = FreightRpaOutboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=SOURCE,
connector_type="dbs", warehouse_id="AWSDU", callback_id="outbound-sync-001",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
import hashlib
digest = hashlib.sha256(b"outbound evidence workbook").hexdigest()
report = FreightRpaOutboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=STORAGE_KEY, original_filename="outbound-sync.xlsx",
file_size=16, sha256=digest,
created_at=datetime.utcnow(),
)
db.session.add(report)
db.session.commit()
return report
def test_reparse_outbound_inserts_ledger_without_new_rpa_run(outbound_storage):
# [断言意图] 已落地出站文件重解析后出现 outbound 档行,且不新增出站执行单元。
report = _seed_outbound_world()
runs_before = FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is True
assert result.file_id == report.id
assert result.inserted == 1
assert result.file_status == "ready"
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound", doc_no="ASN-O1").count() == 1
assert FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count() == runs_before
assert TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").count() == 1
def test_reparse_same_outbound_file_skips_existing_row(outbound_storage):
# [断言意图] 同一份摘要再解析一次不插入第二行。
_seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
again = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert again.ok is True
assert again.inserted == 0
assert again.skipped == 1
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 1
def test_reparse_schema_failure_marks_file_and_lands_nothing(outbound_storage):
# [断言意图] 单号缺失是结构失败:零档行,文件变为 parse_failed,响应带原因。
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx(
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is False
assert result.file_status == "parse_failed"
assert result.inserted == 0
assert "missing_invoice_no" in (result.error_message or "")
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is not None
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 0
def test_reparse_without_published_profile_does_not_mark_parse_failed(outbound_storage):
# [断言意图] 规则未发布不是文件错误,不写 parse_failed。
report = _seed_outbound_world(profile_status="draft")
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
with pytest.raises(AppError) as exc_info:
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE"
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is None
def test_reparse_without_file_raises():
# [断言意图] 没有可用归档时拒绝,而不是去触发 RPA。
with pytest.raises(AppError) as exc_info:
reparse_current_file(
source_code="DSV360_AWSDU", record_kind="outbound", now=datetime.utcnow())
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_FILE"
assert exc_info.value.http_status == 422
def test_reparse_non_schema_error_does_not_mark_parse_failed(outbound_storage, monkeypatch, caplog):
# [断言意图] 数据库一类异常回滚后不把文件标成解析失败,并把异常文本带回。
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
def _boom(**_kwargs):
raise RuntimeError("value too long for varchar(64)")
monkeypatch.setattr(
"app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows",
_boom,
)
with caplog.at_level(logging.ERROR):
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is False
assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED"
assert "varchar(64)" in (result.error_message or "")
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is None
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 0
assert any(
"TRANSFER_CURRENT_REPARSE_FAILED" in record.message and "kind=outbound" in record.message
for record in caplog.records
)
def test_reparse_storage_unavailable_returns_ok_false(outbound_storage, monkeypatch):
# [断言意图] 存储读抛 ServiceUnavailableError 时走 ok=false,不把文件标成解析失败。
report = _seed_outbound_world()
def _unavailable(_storage_key: str) -> bytes:
raise ServiceUnavailableError("object storage unreachable")
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes",
_unavailable,
)
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is False
assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED"
assert "object storage unreachable" in (result.error_message or "")
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is None
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 0
def test_reparse_inbound_inserts_ledger(archive_storage):
# [断言意图] 入站当前文件走 sync_source_rows,record_kind 为 inbound。
source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_NOW")
storage_key = "archive/CRANE_REPARSE_NOW/current.xlsx"
report = factories.seed_reparse_archive_file(
source, sha="c" * 64, storage_key=storage_key, created_at=datetime.utcnow())
archive_storage.objects[storage_key] = factories.build_movement_xlsx([
["ASN-I1", "1", "I", "MAT-I1", "连接器", "LOT-I1", 10, "2026-08-05"],
])
result = reparse_current_file(
source_code="CRANE_REPARSE_NOW", record_kind="inbound", now=datetime.utcnow())
assert result.ok is True
assert result.file_id == report.id
assert result.inserted == 1
row = TransferMovementLedger.query.filter_by(
source_code="CRANE_REPARSE_NOW", record_kind="inbound").one()
assert row.doc_no == "ASN-I1"
assert row.file_version == movement_file_version("c" * 64)
def test_reparse_inbound_schema_failure_marks_file_and_lands_nothing(archive_storage):
# [断言意图] 入站单号缺失是结构失败:零档行,入站文件变为 parse_failed。
source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_SCHEMA")
storage_key = "archive/CRANE_REPARSE_SCHEMA/current.xlsx"
report = factories.seed_reparse_archive_file(
source, sha="d" * 64, storage_key=storage_key, created_at=datetime.utcnow())
archive_storage.objects[storage_key] = factories.build_movement_xlsx(
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
result = reparse_current_file(
source_code="CRANE_REPARSE_SCHEMA", record_kind="inbound", now=datetime.utcnow())
assert result.ok is False
assert result.file_status == "parse_failed"
assert result.inserted == 0
assert "missing_invoice_no" in (result.error_message or "")
marked = FreightRpaInboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is not None
assert TransferMovementLedger.query.filter_by(
source_code="CRANE_REPARSE_SCHEMA", record_kind="inbound").count() == 0
@@ -102,7 +102,7 @@ def test_sync_inserts_ledger_rows_without_erp(app, dbs_ready_file):
# 数量真相源,与旧 items movement_quantity 等值)。
assert hom.quantity == "1200"
assert hom.material_code == "MAT-001" and hom.lot_no == "LOT-10"
assert hom.movement_date == "2026-08-05"
assert hom.movement_date == "2026-08-04"
assert hom.file_version == "v3" and hom.file_sha256 == "d" * 64
assert hom.sheet_name == "Receipt" and hom.row_no == 10 # 组内首行溯源
assert TransferInvoiceItem.query.count() == 0 # [断言意图] 停写 items
@@ -342,6 +342,38 @@ def test_sync_writes_cross_flag_for_contradictory_in_out_flag(app):
assert row.in_out_flag == "-1" # [断言意图] 原值落档不拒收
def test_sync_lands_external_doc_line_and_expands_natural_key(app):
# [断言意图] 外部单据身份(外部单号/外部项次=WMS Order #/行号)经落档链路
# 写入档列并参与自然键:同单号同行不同外部单号 = 两行独立落档(2026-10-21
# 档幂等主键管控扩维),外部身份列原值随行留存。
deps, _, _ = make_transfer_deps({
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "inbound",
"file_no": "REC-EXT",
"file_version": "v1",
"checksum": "e" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-E1", "line_no": "1",
"external_doc_no": "WMS-001", "external_line_no": "10",
"lot_no": "LOT-E", "material_code": "MAT-E", "material_name": "外部身份料号",
"movement_date": "2026-08-05", "quantity": "10", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-E1", "line_no": "1",
"external_doc_no": "WMS-002", "external_line_no": "10",
"lot_no": "LOT-E", "material_code": "MAT-E", "material_name": "外部身份料号",
"movement_date": "2026-08-05", "quantity": "20", "source_code": "DBS-AWSBI"},
],
})
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert outcome is not None and outcome.inserted == 2 # [断言意图] 不同外部单号各自成行
rows = TransferMovementLedger.query.filter_by(
source_code="DBS-AWSBI", doc_no="HOM-E1").order_by(TransferMovementLedger.id).all()
assert [(r.external_doc_no, r.external_line_no) for r in rows] == [
("WMS-001", "10"), ("WMS-002", "10")] # [断言意图] 外部身份列原值落档
def _collapsed_multi_material_file() -> dict:
"""同单号双料号、行级 line_no/line_seq/in_out_flag 全空且 carton/lot 等值的坍缩形态文件。
@@ -47,7 +47,7 @@ def _ready_items(dbs_ready_file, *seeds) -> tuple:
erp.seed_stock(*_INVOICE_TUPLES[invoice_no], quantity)
deps, erp, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = (
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
.order_by(TransferInvoiceItem.id)
@@ -76,7 +76,7 @@ def test_execute_items_writes_one_order_and_aggregates(transfer_db, dbs_ready_fi
deps, erp, items = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first()
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-07").first()
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
# Run 终态与单据聚合:同组两 Invoice 合并一张 ERP 单(D1 五元组一组一单),无异常。
@@ -145,7 +145,7 @@ def _two_group_deps(dbs_ready_file, patch_source_file_status):
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
deps, erp, _ = make_transfer_deps(file, capabilities=erp)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = (
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
.order_by(TransferInvoiceItem.id)
@@ -289,7 +289,7 @@ def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_read
deps, erp, _ = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first()
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-07").first()
outcome = execute_matching_items(
matching_id=matching.matching_no, deps=deps, invoice_nos=["HOM-001"],
@@ -10,7 +10,10 @@
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service、jobs.queue。
逻辑:场景编号对应计划 Task 10 Step 1 场景①-⑪;SQLite 无 PG 序列,单号序列经
monkeypatch execution_service._sequence_loader 注入替身;文件对账门禁经
patch_source_file_status 夹具注入 ready 投影。
patch_source_file_status 夹具注入 ready 投影。出站档行用例把入站/出站
投影分成两个 sha,确认门禁与 file_current 读档上的 record_kind。
【T−2 成熟封顶 2026-10-21】匹配 business_date 用 2026-08-07(行日期
2026-08-04/08-05 均 ≤T−2 成熟可圈;文件/种子新鲜度仍用 2026-08-06)。
"""
from __future__ import annotations
@@ -32,6 +35,7 @@ from app.models import (
TransferDocument,
TransferInvoiceItem,
TransferMatching,
TransferMovementLedger,
TransferRun,
)
from app.services.in_transit_transfer.execution_service import (
@@ -41,7 +45,7 @@ from app.services.in_transit_transfer.execution_service import (
retrigger_document,
)
from app.services.in_transit_transfer.serializers import serialize_order
from app.services.in_transit_transfer.matching_service import create_matching
from app.services.in_transit_transfer.matching_service import create_matching, restore_matching
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
READY_SHA = "d" * 64
@@ -154,7 +158,7 @@ def test_two_movement_dates_create_two_documents(
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-04", "700"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
assert outcome.status == "queued"
@@ -185,7 +189,7 @@ def test_same_order_same_material_lot_across_invoices_aggregates_line(
])
# 严格数量匹配逐 Invoice 核对:库存须等于单 Invoice 数量(聚合发生在执行组建单时)。
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "500.5")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -212,7 +216,7 @@ def test_order_doc_date_equals_group_movement_date(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -237,7 +241,7 @@ def test_order_success_propagates_to_all_items(
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-05", "700"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -274,7 +278,7 @@ def test_order_failure_isolates_to_its_items(
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-04", "700"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = _ready_items()
outcome = prepare_execution(item_ids=[i.id for i in items], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
@@ -310,7 +314,7 @@ def test_worker_reclaim_executing_stage_confirmed_runs_final_only(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -342,7 +346,7 @@ def test_failed_order_reused_with_new_row_full_rerun(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run1 = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run1)
@@ -366,7 +370,7 @@ def test_failed_order_reused_with_new_row_full_rerun(
erp2.seed_stock("MAT-003", "DBS-TRANSIT", "LOT-30", "300")
patch_source_file_status()
seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06") # 新行 HOM-C 落地;HOM-A 幂等跳过
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps2, transfer_type="in_transit_to_hub")
second = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps2)
run2 = TransferRun.query.filter_by(run_no=second.run_no).first()
@@ -402,7 +406,7 @@ def test_result_unknown_order_blocks_new_rows(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run1 = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run1)
@@ -461,7 +465,7 @@ def test_retrigger_document_full_chain(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run)
@@ -531,7 +535,7 @@ def test_partial_unique_index_race_falls_back_to_reuse(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = _ready_items()
original_insert = execution_service._insert_document
@@ -583,7 +587,7 @@ def test_prepare_enqueues_single_transfer_run_job(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
ids = [i.id for i in _ready_items()]
outcome = prepare_execution(item_ids=ids, deps=deps)
@@ -618,7 +622,7 @@ def test_execute_run_rechecks_file_hash_fail_closed(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -646,7 +650,7 @@ def test_full_run_passes_stage_callback_and_marks_stage_confirmed(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -672,7 +676,7 @@ def test_retrigger_final_only_does_not_pass_stage_callback(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run)
@@ -706,7 +710,7 @@ def test_requeried_rows_reuse_order_without_new_rows(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run1 = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run1)
@@ -799,7 +803,7 @@ def test_recheck_failure_marks_executing_order_technical_failed(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -832,7 +836,7 @@ def test_serialize_run_orders_projects_multi_status_order_list(
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_row("Receipt", 2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
docs = _docs_of(run)
@@ -888,7 +892,7 @@ def test_order_lines_group_by_external_lot_form():
# [出生翻转] 批号派生按行所属匹配快照的转换规则(scope_json.transform_rules):
# 构造携带 WTP→HOW 规则的匹配对象并挂到两行(transient 赋值,不触库)。
matching = TransferMatching(
matching_no="MTG-LOT", business_date="2026-08-06", status="success",
matching_no="MTG-LOT", business_date="2026-08-07", status="success",
scope_json={"transform_rules": [
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
]},
@@ -921,7 +925,7 @@ def test_serialize_order_reason_join_uses_external_lot_form():
WTP 前缀行投影出空品名/空原因。
"""
matching = TransferMatching(
matching_no="MTG-LOT-2", business_date="2026-08-06", status="success",
matching_no="MTG-LOT-2", business_date="2026-08-07", status="success",
scope_json={"transform_rules": [
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
]},
@@ -956,7 +960,7 @@ def test_order_success_seals_ledger_records(
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-05", "700"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -988,7 +992,7 @@ def test_order_success_seal_is_idempotent_and_stays_sealed_on_duplicate(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -1026,7 +1030,7 @@ def test_order_failure_does_not_seal_ledger_records(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = _ready_items()
outcome = prepare_execution(item_ids=[i.id for i in items], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
@@ -1053,7 +1057,7 @@ def test_gate_anchors_to_ledger_record_version(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
item = _ready_items()[0]
from app.models import TransferMovementLedger
@@ -1082,3 +1086,61 @@ def test_gate_anchors_to_ledger_record_version(
prepare_execution(item_ids=[item.id], deps=deps)
assert exc.value.code == "TRANSFER.FILE_CHANGED" # [断言意图] 记录落后 → 拒绝执行
db.session.expire_all()
def test_execute_gate_compares_outbound_evidence_not_inbound(
transfer_db, monkeypatch, seq_loader,
):
"""出站档行的 file_current 与执行门禁对出站文件 sha,不拿入站投影比较。
核心逻辑:同一来源入站投影 sha 与出站不同。出站档 file_sha256 等于出站投影。
若门禁仍解析入站,file_current 为假且 prepare_execution 抛 FILE_CHANGED。
"""
del seq_loader # 夹具注入单号序列;本用例只确认门禁放行。
out_sha = "o" * 64
in_sha = "i" * 64
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
"""入站与出站返回不同 sha,用来区分门禁读了哪一条流。"""
del source_code
sha = out_sha if record_kind == "outbound" else in_sha
return {
"file_status": "ready", "has_ready_file": True,
"file_no": f"{record_kind}-file", "file_sha256": sha,
}
monkeypatch.setattr(
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
_resolve,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.execution_service.resolve_source_file_status",
_resolve,
)
deps, erp, _rpa = make_transfer_deps()
erp.seed_stock("MAT-OUT", "DBS-TRANSIT", "LOT-OUT", "100")
db.session.add(TransferMovementLedger(
source_code="DBS-AWSBI", record_kind="outbound",
doc_no="HOX-OUT", line_no="1", line_seq="", in_out_flag="",
material_code="MAT-OUT", material_name="出站物料", specification="",
lot_no="LOT-OUT", quantity="100", unit="PCS",
warehouse_code="", storage_code="", movement_date="2026-08-05",
source_file_id=None, file_version="v1", file_sha256=out_sha,
sheet_name="Shipment", row_no=1, updated_at=datetime.utcnow(),
transfer_executed=False,
))
db.session.commit()
summary = create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps,
transfer_type="in_transit_to_hub",
)
restored = restore_matching(summary.matching_id, deps=deps)
row = next(item for item in restored["items"] if item.invoice_no == "HOX-OUT")
# [断言意图] 入站 sha 与档不同;file_current 仍为真,说明比的是出站证据文件。
assert row.file_current is True
item = TransferInvoiceItem.query.filter_by(invoice_no="HOX-OUT").one()
assert item.ledger_record.record_kind == "outbound"
assert item.status == "ready_to_execute"
outcome = prepare_execution(item_ids=[item.id], deps=deps)
# [断言意图] 执行门禁放行。误用入站 sha 会以 FILE_CHANGED 拒绝。
assert outcome.run_no
@@ -61,15 +61,36 @@ def test_valid_rows_parse():
def test_missing_invoice_no_rejected():
"""单号(doc_no)缺失必须整行阻断。"""
"""单号(doc_no)缺失必须整行阻断(管控保留:配置错列由解析失败暴露)。"""
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no=""))
def test_missing_material_no_rejected():
"""料号缺失必须整行阻断。"""
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(material_code=""))
def test_missing_material_no_row_skipped_not_blocked():
"""料号空行=非可用异动行:静默跳过——不管控、不进异动表(2026-10-21 实测反转)。
Why: CRANE/Lognet 出站报告携带说明行/占位行(料号为空),旧逻辑按
missing_material_no 整文件阻断致出站解析失败;此类行不是可用异动事实,
跳过语义与零数量行同家族(_is_unusable_movement_row)。
"""
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(material_code=""))
assert parsed == []
def test_empty_material_rows_mixed_with_valid_rows_only_valid_parsed():
"""料号空行与合法行混排:只放行有料号的行,空料号行不阻断整文件。"""
rows = [
dict(VALID_ROW, row_no=2, material_code=""), # 说明/占位行:跳过
dict(VALID_ROW, row_no=3, material_code="MAT-002", doc_no="INV-002"),
]
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
assert [row.row_no for row in parsed] == [3]
def test_material_and_invoice_both_empty_row_skipped():
"""料号与单号双空行按料号空行处理:静默跳过而非 missing_invoice_no 阻断。"""
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no="", material_code=""))
assert parsed == []
def test_invalid_quantity_rejected():
@@ -6,7 +6,7 @@
(inbound 行出库语义 '-1')计 cross_flagged 并写 ledger_cross_check_failed
审计事件且记录照常落档;shipment 预留合法值放行、同批自然键重复首见为准。
依赖:app fixture(pytestmark)、models.TransferMovementLedger / TransferAuditEvent、
ledger_sync.sync_ledger_rows / FileMeta。
ledger_sync.sync_ledger_rows / FileMeta / movement_file_version。
逻辑:parsed_rows 以「movement 契约 field code → 值」的领域行 dict 直接构造
(扩展字段值从 dict 取,非 ParsedMovementRow 属性——Task 11 接线同形态);
直连 SQLite 内存库断言行级状态与审计事件,全程零外部调用。
@@ -22,6 +22,7 @@ from app import db
from app.models import TransferAuditEvent, TransferMovementLedger
from app.services.in_transit_transfer.ledger_sync import (
FileMeta,
movement_file_version,
sync_ledger_rows,
)
@@ -211,6 +212,31 @@ def test_lot_no_expands_natural_key():
assert outcome.inserted == 2
def test_external_doc_line_expands_natural_key():
# [断言意图] 外部单据身份(外部单号/外部项次)入自然键:同单号同行但外部单号
# 不同 = 两行独立落档(2026-10-21 档幂等主键管控扩维,防外部身份塌缩丢行)。
outcome = _sync([
_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001", quantity="1"),
_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-002", quantity="2"),
], record_kind="inbound")
assert outcome.inserted == 2
assert outcome.skipped == 0
def test_external_doc_line_same_identity_converges_to_one_row():
# [断言意图] 主键管控收敛面:同外部单号+项次的重复落档收敛同一档行——
# 证据变化走原行更新(不是插入第二行),与 tt14 箱号/批号扩维同语义。
outcome = _sync([_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001",
external_line_no="5", quantity="1")])
assert outcome.inserted == 1
outcome2 = _sync([_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001",
external_line_no="5", quantity="3")], meta=_meta(sha=SHA_V2), now=NOW2)
assert (outcome2.inserted, outcome2.updated, outcome2.skipped) == (0, 1, 0)
row = TransferMovementLedger.query.one()
assert row.quantity == "3"
assert row.external_doc_no == "WMS-001" and row.external_line_no == "5"
def test_empty_movement_date_rows_skipped():
# [断言意图] movement_date 空 = 未发生异动:不落档、不计入其他分类(date_skipped 单列)。
outcome = _sync([
@@ -246,3 +272,12 @@ def test_batch_external_doc_no_row_untouched_by_landing():
assert external.quantity == "7" and external.file_sha256 == SHA_V1 # 内容不变
assert external.updated_at == external_at # 零触碰
assert TransferMovementLedger.query.count() == 2 # 缺席不删:批外行留存
def test_movement_file_version_fits_varchar64_column():
# [断言意图] 64 位摘要加 sha256: 前缀共 71 字符;档列 file_version 是 varchar(64),
# 戳必须是这一条已知截断值(2026-10-21 DSV 出站整批插入失败的摘要)。
digest = "7bbca0adaef3d550e0db47955a9b59609313be3b1335c1b498381db3b7a11715"
stamp = movement_file_version(digest)
assert stamp == "sha256:7bbca0adaef3d550e0db47955a9b59609313be3b1335c1b498381db3b"
assert len(stamp) == 64
@@ -67,7 +67,7 @@ def test_items_are_born_bound_to_matching(transfer_db, dbs_ready_file):
hom = next(row for row in rows if row.invoice_no == "HOM-001")
# [断言意图] 业务字段=档原值:数量=档聚合值(500+700),批号/仓库/日期同档。
assert hom.movement_quantity == "1200"
assert hom.lot_no == "LOT-10" and hom.movement_date == "2026-08-05"
assert hom.lot_no == "LOT-10" and hom.movement_date == "2026-08-04"
assert hom.movement_warehouse_code == "" # 夹具行无仓库列 → 档原值为空串
@@ -4,7 +4,9 @@
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
外部依赖注入 Fake 替身。
外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行,
经 create_matching 断言 doc_no。入站 no_data / 仅出站类型断言不触发入站 RPA。
确认匹配对 ready 出站归档幂等补落档后再圈行(空档窗口回归)。
"""
from __future__ import annotations
@@ -38,6 +40,21 @@ def _deps(*files: dict, erp: FakeCapabilityClient | None = None, rpa: FakeRPA |
return make_transfer_deps(*files, capabilities=erp, rpa=rpa)
@pytest.fixture
def deps(app):
"""圈档记录类型用例的匹配依赖(空文件仓库,DSV360_AWSBI 路由可解析)。
核心逻辑:请求 app 以建表并触发默认类型种子;路由只为评估链不中断,
断言不看仓库。
Returns:
TransferDeps。
"""
built, _erp, _rpa = make_transfer_deps(
routes={"DSV360_AWSBI": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
)
return built
def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file):
"""两个来源全部严格匹配 → executable_count 正确,无阻断。"""
deps, erp, _ = _deps(dbs_ready_file, crane_ready_file)
@@ -88,7 +105,7 @@ def test_estimated_document_count_merges_same_group(dbs_ready_file):
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
)
assert result.summary.counts.executable_count == 2
# HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-05, DBS-TRANSIT, HUB-CN01)。
# HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-04, DBS-TRANSIT, HUB-CN01)。
assert result.summary.estimated_external_write_count == 1
items = {item.invoice_no: item for item in result.items}
assert items["HOM-001"].external_org == "HX-CN01"
@@ -100,6 +117,8 @@ def test_estimated_document_count_splits_by_movement_date():
锁定分组的日期维度:execution_service.prepare_execution 以 movement_date 入键,
跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。
【T−2 成熟封顶 2026-10-21】两行均取 ≤ T−2(08-03/08-04)成熟日期,
隔天分组语义不变。
"""
deps, erp, _ = _deps({
"source_code": "DBS-AWSBI",
@@ -112,10 +131,10 @@ def test_estimated_document_count_splits_by_movement_date():
"rows": [
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-A", "lot_no": "LOT-A",
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
"movement_date": "2026-08-03", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-B", "lot_no": "LOT-B",
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
"movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
],
})
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-A", "600")
@@ -128,11 +147,13 @@ def test_estimated_document_count_splits_by_movement_date():
assert result.summary.estimated_external_write_count == 2
def test_same_day_data_reaches_erp_query(same_day_inbound_file):
"""【成熟退役 2026-10-16】当天异动数据不再被成熟门禁跳过:正常进 ERP 查询。
def test_same_day_data_not_matched_before_maturity(same_day_inbound_file):
"""【T−2 成熟封顶 2026-10-21】当天(T)异动未成熟:不进匹配、不发起外部查询。
[断言意图] 夹具未种库存 → 行落 blocked_inventory_not_found;关键契约是
网关调用必须发生(=1),证明日期不再构成评估前置过滤。
[断言意图] 圈档封顶 movement_date ≤ T−2(T−2 之前数据全部成熟):当天行留在
档内待成熟,不出生 item、不查外部系统(=0);成熟(≤T−2)数据的正常匹配由
happy path 用例锁定。此前「成熟规则已退役 2026-10-16」放开的当天进匹配语义
随 T−2 管控恢复一并收回。
"""
deps, erp, _ = _deps(same_day_inbound_file)
seed_rows_from_file("DBS-AWSSG", deps, "2026-08-06")
@@ -140,8 +161,8 @@ def test_same_day_data_reaches_erp_query(same_day_inbound_file):
source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
)
assert result.summary.counts.executable_count == 0
assert result.summary.counts.blocked_count == 1
assert_erp_calls(erp, 1)
assert result.summary.counts.blocked_count == 0
assert_erp_calls(erp, 0)
def test_quantity_mismatch_blocked_no_write(dbs_ready_file):
@@ -173,7 +194,7 @@ def test_erp_inventory_not_found_blocked(dbs_ready_file):
def _wtp_lot_file() -> dict:
"""构造 WTP 前缀批号的单行收料文件(WMS 原形态落库口径)。"""
"""构造 WTP 前缀批号的单行收料文件(WMS 原形态落库口径;异动日期=T−2 成熟边界)。"""
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
@@ -185,7 +206,7 @@ def _wtp_lot_file() -> dict:
"rows": [
{"sheet": "Receipt", "row_no": 10, "doc_no": "HOX-900", "lot_no": "WTP26060612",
"material_code": "MAT-900", "material_name": "汇流排", "specification": "48V",
"movement_date": "2026-08-05", "quantity": "200", "unit": "PCS",
"movement_date": "2026-08-04", "quantity": "200", "unit": "PCS",
"source_code": "DBS-AWSBI"},
],
}
@@ -284,7 +305,7 @@ def test_create_and_restore_matching(transfer_db, dbs_ready_file):
# 落库数量与 DTO 一致(Decimal 文本持久化)
assert str(restored_items["HOM-001"].to_quantity) == "1200"
# [断言意图] 收料日期与批号必须随明细恢复——聊天卡片收料日期/拨出批号/拨入批号列的数据来源。
assert restored_items["HOM-001"].movement_date == "2026-08-05"
assert restored_items["HOM-001"].movement_date == "2026-08-04"
assert restored_items["HOM-001"].lot_no == "LOT-10"
assert restored_items["HOX-002"].lot_no == "LOT-20"
@@ -304,7 +325,7 @@ def test_parse_failed_file_reports_source_failure_on_restore(transfer_db, monkey
# 来源阶段转 failed、错误码随 SourceProgress 透出;档照常圈定(无档行=全 0)。
monkeypatch.setattr(
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
lambda *, source_code: {"file_status": "parse_failed", "has_ready_file": False,
lambda *, source_code, record_kind="inbound": {"file_status": "parse_failed", "has_ready_file": False,
"file_no": "F1", "file_sha256": "sha:x"},
)
summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
@@ -352,10 +373,10 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
"rows": [
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-1", "lot_no": "ASN-1",
"material_code": "M1", "material_name": "物料1",
"quantity": 5, "movement_date": "2026-09-16"},
"quantity": 5, "movement_date": "2026-09-15"},
{"sheet": "Movement", "row_no": 2, "doc_no": "HOX-2", "lot_no": "ASN-1",
"material_code": "M2", "material_name": "物料2",
"quantity": 7, "movement_date": "2026-09-16"},
"quantity": 7, "movement_date": "2026-09-15"},
],
},
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
@@ -368,46 +389,84 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
def test_movement_date_range_filters_invoices(transfer_db, dbs_ready_file):
"""收料日期范围作为匹配查询范围:范围外发票不进入明细。"""
"""收料日期范围作为匹配查询范围:范围外发票不进入明细(行日期=T−2 成熟边界)。"""
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
movement_date_from="2026-08-05", movement_date_to="2026-08-05", transfer_type="in_transit_to_hub"
movement_date_from="2026-08-04", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub"
)
assert summary.counts.file_invoice_count == 2
empty = create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
movement_date_from="2026-08-01", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub"
movement_date_from="2026-08-01", movement_date_to="2026-08-03", transfer_type="in_transit_to_hub"
)
assert empty.counts.file_invoice_count == 0
def test_movement_date_range_end_beyond_business_date_rejected(transfer_db, dbs_ready_file):
"""卡控(成熟退役后唯一日期校验):截止晚于业务日期(未来日期)必须拒绝。
def test_movement_date_range_end_beyond_matured_boundary_rejected(transfer_db, dbs_ready_file):
"""卡控(T−2 成熟封顶 2026-10-21):截止晚于 T−2 可匹配截止日必须拒绝。
[断言意图] 截止=业务日期当天(2026-08-06)现在合法(旧成熟规则会拒绝 T-1/
当天);只有严格晚于业务日期才拒——未来日期无账可核。
[断言意图] T−2 之前数据全部成熟(简化成熟边界,不回退退役决策)——范围
截止 ≤ T−2(2026-08-04)合法,T−1/当天/未来(>T−2)无成熟数据不可选;
与前端选择器上限(transferDate.ts defaultMovementDate)同口径,越界统一
TRANSFER.MOVEMENT_DATE_RANGE_INVALID。
"""
from app.core.errors import ValidationError
deps, erp, _ = _deps(dbs_ready_file)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
with pytest.raises(ValidationError) as exc_info:
create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
movement_date_from="2026-08-04", movement_date_to="2026-08-07", transfer_type="in_transit_to_hub"
movement_date_from="2026-08-04", movement_date_to="2026-08-05", transfer_type="in_transit_to_hub"
)
assert exc_info.value.code == "TRANSFER.MOVEMENT_DATE_RANGE_INVALID"
# [边界反转] 截止=业务日期当天合法(旧行为 lag=1 下会被拒)。
empty = create_matching(
# [边界] 截止=T−2(2026-08-04)恰好合法:成熟行正常进匹配。
bounded = create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
movement_date_from="2026-08-06", movement_date_to="2026-08-06", transfer_type="in_transit_to_hub"
movement_date_from="2026-08-04", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub"
)
assert empty.counts.file_invoice_count == 0
assert bounded.counts.file_invoice_count == 2
def test_circle_excludes_immature_rows_beyond_t_minus_2(transfer_db):
"""圈档 T−2 成熟封顶:T−1/当天行不进匹配(留在档内待成熟),≤T−2 正常圈定。
[断言意图] 未传范围(积压模式)时 T−1(08-05)/当天(08-06)行也不被圈定
——成熟封顶是圈档固定条件,不依赖调用方传范围;两行在次日(业务日前移)
自然跨过 T−2 后即可进圈。
"""
deps, _erp, _rpa = make_transfer_deps(
{
"source_code": "DSV360_AWSDU", "business_date": "2026-08-06",
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
"rows": [
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-M", "lot_no": "LOT-M",
"material_code": "M1", "material_name": "物料1",
"quantity": 5, "movement_date": "2026-08-04"},
{"sheet": "Movement", "row_no": 2, "doc_no": "HOM-Y", "lot_no": "LOT-Y",
"material_code": "M2", "material_name": "物料2",
"quantity": 6, "movement_date": "2026-08-05"},
{"sheet": "Movement", "row_no": 3, "doc_no": "HOM-T", "lot_no": "LOT-T",
"material_code": "M3", "material_name": "物料3",
"quantity": 7, "movement_date": "2026-08-06"},
],
},
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
)
seed_rows_from_file("DSV360_AWSDU", deps, "2026-08-06")
result = run_matching(
source_codes=["DSV360_AWSDU"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
)
invoices = {item.invoice_no for item in result.items}
# [断言意图] 只有 ≤T−2(08-04)的行出生 item;T−1/当天行被圈档封顶排除。
assert invoices == {"HOM-M"}
assert result.summary.counts.file_invoice_count == 1
def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file):
@@ -451,7 +510,7 @@ def test_run_matching_consumes_movement_field_rows(app):
"rows": [{
"sheet": "Movement", "row_no": 1,
"doc_no": "WTP-1", "lot_no": "LOT-1", "material_code": "M1", "material_name": "物料1",
"quantity": 5, "movement_date": "2026-09-16", "unit": "PCS",
"quantity": 5, "movement_date": "2026-09-15", "unit": "PCS",
}],
},
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
@@ -476,13 +535,13 @@ def test_type1_filters_invoices_by_prefix(app):
"rows": [
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-100", "lot_no": "LOT-1",
"material_code": "M1", "material_name": "物料1",
"quantity": 5, "movement_date": "2026-09-16", "unit": "PCS"},
"quantity": 5, "movement_date": "2026-09-15", "unit": "PCS"},
{"sheet": "Movement", "row_no": 2, "doc_no": "INV-9", "lot_no": "LOT-2",
"material_code": "M2", "material_name": "物料2",
"quantity": 6, "movement_date": "2026-09-16", "unit": "PCS"},
"quantity": 6, "movement_date": "2026-09-15", "unit": "PCS"},
{"sheet": "Movement", "row_no": 3, "doc_no": "WTP-300", "lot_no": "LOT-3",
"material_code": "M3", "material_name": "物料3",
"quantity": 7, "movement_date": "2026-09-16", "unit": "PCS"},
"quantity": 7, "movement_date": "2026-09-15", "unit": "PCS"},
],
},
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
@@ -506,7 +565,7 @@ def test_create_matching_persists_transfer_type_on_run_and_scope(transfer_db):
"rows": [{
"sheet": "Movement", "row_no": 1, "doc_no": "HOX-1", "lot_no": "LOT-1",
"material_code": "M1", "material_name": "物料1",
"quantity": 5, "movement_date": "2026-09-16",
"quantity": 5, "movement_date": "2026-09-15",
}],
},
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
@@ -677,17 +736,28 @@ def test_executable_list_stale_clock_is_inventory_checked_at(app, dbs_ready_file
def _seed_ledger_record(doc_no: str, *, material: str = "MAT-LED", quantity: str = "100",
movement_date: str = "2026-08-05", sealed: bool = False,
source_code: str = "DSV360_AWSDU", row_no: int = 1):
"""直接 ORM 种子一条收料档记录(单元测试圈档口径;不依赖文件落地链路)。"""
source_code: str = "DSV360_AWSDU", row_no: int = 1,
record_kind: str = "inbound", carton_id: str = "",
lot_no: str | None = None, file_sha256: str | None = None):
"""直接 ORM 种子一条异动档记录(单元测试圈档口径;不依赖文件落地链路)。
Args:
record_kind: 档记录类型,缺省 inbound(存量圈档用例)。
carton_id: 自然键成分(tt14);同 grain 不同 carton 可并存两条档。
lot_no / file_sha256: 可选覆盖,便于构造 grain 分叉夹具。
"""
from app.models import TransferMovementLedger
record = TransferMovementLedger(
source_code=source_code, record_kind="inbound",
source_code=source_code, record_kind=record_kind,
doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="",
carton_id=carton_id,
material_code=material, material_name="档物料", specification="",
lot_no=f"LOT-{doc_no}", quantity=quantity, unit="PCS",
lot_no=lot_no if lot_no is not None else f"LOT-{doc_no}",
quantity=quantity, unit="PCS",
warehouse_code="", storage_code="", movement_date=movement_date,
source_file_id=None, file_version="v1", file_sha256="a" * 64,
source_file_id=None, file_version="v1",
file_sha256=file_sha256 or ("a" * 64),
sheet_name="Receipt", row_no=row_no, updated_at=datetime.utcnow(),
transfer_executed=sealed,
executed_doc_no="TRF-SEALED" if sealed else None,
@@ -697,6 +767,252 @@ def _seed_ledger_record(doc_no: str, *, material: str = "MAT-LED", quantity: str
return record
def _insert_ledger(*, source_code: str, record_kind: str, doc_no: str, movement_date: str):
"""直接 ORM 落一条异动档(圈档记录类型用例;不走文件落地)。
核心逻辑:复用 _seed_ledger_record 的列口径,只放开 record_kind / 来源 / 单号 / 日期。
Returns:
TransferMovementLedger 行。
"""
return _seed_ledger_record(
doc_no, movement_date=movement_date, source_code=source_code, record_kind=record_kind,
)
def _prepare_record_kind_circle_types() -> None:
"""启用 hub_to_hub(范围规则不含 record_kind),并给 in_transit_to_hub 写上只要 inbound。
核心逻辑:hub_to_hub 用默认前缀规则(无记录类型 → 入站+出站)。
in_transit_to_hub 在既有前缀规则上追加 record_kind equals inbound,
否则同一出站行也会被圈入。
"""
from app.models import TransferTypeConfig
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
seed_transfer_type_config()
seed_transfer_type_config("hub_to_hub")
row = db.session.query(TransferTypeConfig).filter_by(code="in_transit_to_hub").one()
rules = [dict(item) for item in (row.scope_rules_json or [])]
if not any(item.get("field") == "record_kind" for item in rules):
rules.append({"field": "record_kind", "match": "equals", "values": ["inbound"]})
row.scope_rules_json = rules
db.session.commit()
def items_of(summary):
"""读取本次匹配已圈明细,只暴露 doc_no(行 invoice_no = 档单号)。
Args:
summary: create_matching 返回的匹配摘要(matching_id 为匹配编号)。
Returns:
带 doc_no 属性的明细列表。
"""
from types import SimpleNamespace
from app.models import TransferMatching
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
rows = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
return [SimpleNamespace(doc_no=row.invoice_no) for row in rows]
def test_hub_to_hub_circles_outbound_ledger_rows(deps):
"""没有记录类型规则的类型圈入出站档;范围规则写明只要 inbound 的类型不圈。"""
_prepare_record_kind_circle_types()
_insert_ledger(source_code="DSV360_AWSBI", record_kind="outbound", doc_no="HOX1", movement_date="2026-10-14")
inbound_only = create_matching(
source_codes=["DSV360_AWSBI"],
business_date="2026-10-16",
movement_date_from="2026-10-14",
movement_date_to="2026-10-14",
transfer_type="in_transit_to_hub",
deps=deps,
)
# [断言意图] 先圈只要 inbound 的类型:行尚未被占用,HOX1 因记录类型被排除。
assert "HOX1" not in {item.doc_no for item in items_of(inbound_only)}
circled = create_matching(
source_codes=["DSV360_AWSBI"],
business_date="2026-10-16",
movement_date_from="2026-10-14",
movement_date_to="2026-10-14",
transfer_type="hub_to_hub",
deps=deps,
)
# [断言意图] 无 record_kind 规则的启用类型应圈入出站档 HOX1。
assert "HOX1" in {item.doc_no for item in items_of(circled)}
def test_no_data_or_outbound_only_does_not_trigger_inbound_rpa(deps, monkeypatch):
"""入站 no_data、或类型不要求入站时,create_matching 不触发入站 RPA。
核心逻辑:投影替身按 record_kind 返回状态。先跑只要 inbound 且入站为
no_data;再把 hub_to_hub 收成只要 outbound,入站投影改为 none(若入站仍被
当作必需,none 会走 ensure 并写入 matching_missing_ready_file)。
"""
projection = {"inbound": "no_data", "outbound": "ready"}
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
"""按当前 projection 返回该证据流的文件状态。"""
del source_code
state = projection.get(record_kind, "none")
if state == "ready":
return {
"file_status": "ready", "has_ready_file": True,
"file_no": f"{record_kind}-file", "file_sha256": "b" * 64,
}
if state == "no_data":
return {
"file_status": "no_data", "has_ready_file": False,
"file_no": None, "file_sha256": None,
}
return {
"file_status": "none", "has_ready_file": False,
"file_no": None, "file_sha256": None,
}
monkeypatch.setattr(
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
_resolve,
)
_prepare_record_kind_circle_types()
_insert_ledger(
source_code="DSV360_AWSBI", record_kind="inbound",
doc_no="HOM-ND", movement_date="2026-10-14",
)
inbound_only = create_matching(
source_codes=["DSV360_AWSBI"],
business_date="2026-10-16",
movement_date_from="2026-10-14",
movement_date_to="2026-10-14",
transfer_type="in_transit_to_hub",
deps=deps,
)
# [断言意图] 入站已确认 no_data:不得写 matching_missing_ready_file,档仍圈入。
assert deps.rpa_trigger.triggered == []
assert "HOM-ND" in {item.doc_no for item in items_of(inbound_only)}
from app.models import TransferTypeConfig
hub = db.session.query(TransferTypeConfig).filter_by(code="hub_to_hub").one()
rules = [dict(item) for item in (hub.scope_rules_json or [])]
rules.append({"field": "record_kind", "match": "equals", "values": ["outbound"]})
hub.scope_rules_json = rules
db.session.commit()
projection["inbound"] = "none"
projection["outbound"] = "no_data"
deps.rpa_trigger.triggered.clear()
_insert_ledger(
source_code="DSV360_AWSBI", record_kind="outbound",
doc_no="HOX-OD", movement_date="2026-10-14",
)
outbound_only = create_matching(
source_codes=["DSV360_AWSBI"],
business_date="2026-10-16",
movement_date_from="2026-10-14",
movement_date_to="2026-10-14",
transfer_type="hub_to_hub",
deps=deps,
)
# [断言意图] 只要出站、入站缺文件(none)时仍不触发入站 RPA,出站档照常圈入。
assert deps.rpa_trigger.triggered == []
assert "HOX-OD" in {item.doc_no for item in items_of(outbound_only)}
def test_confirm_matching_syncs_ready_outbound_into_ledger_before_circle(deps, monkeypatch):
"""确认匹配时:出站 ready 但档空 → 先幂等落档再圈行(补齐回调未落档窗口)。
[断言意图] 不再依赖「仅回调 success 才写档」;create_matching 对 ready 出站
流调用 sync_outbound_source_rows,圈出 HOX-MATCH-O1(前缀落在类型范围规则内)。
"""
import hashlib
from app.models import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
FreightRpaParsingProfile,
FreightRpaSource,
TransferMovementLedger,
TransferTypeConfig,
)
from tests.services.in_transit_transfer import factories
source_code = "DSV360_AWSDU"
storage_key = "shipping/outbound/match-sync.xlsx"
now = datetime.utcnow()
fake_storage = factories.FakeArchiveStorage()
fake_storage.objects[storage_key] = factories.build_movement_xlsx([
["HOX-MATCH-O1", "1", "O", "MAT-LED", "成品", "LOT-O1", 80, "2026-10-14"],
])
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes",
fake_storage.get_bytes,
)
# outbound_evidence_sync 直接 import 了 file_asset_storage 单例方法,需同补丁。
monkeypatch.setattr(
"app.services.in_transit_transfer.outbound_evidence_sync.file_asset_storage.get_bytes",
fake_storage.get_bytes,
)
source = FreightRpaSource.query.filter_by(source_code=source_code).one()
profile = FreightRpaParsingProfile(
purpose="outbound", profile_code="OUT_MATCH_SYNC", display_name=source_code,
version=1, status="published", file_format="xlsx",
definition_json={
"field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING,
"sheet_name": "Receipt", "header_row_index": 1,
},
structure_definition_json={},
)
db.session.add(profile)
db.session.flush()
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={"report_name": "Outbound"},
query_parameters_json=[],
parsing_profile_id=profile.id,
))
unit = FreightRpaOutboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=source_code,
connector_type="dbs", warehouse_id="AWSDU", callback_id="match-sync-out-1",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
digest = hashlib.sha256(b"match sync outbound workbook").hexdigest()
db.session.add(FreightRpaOutboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=storage_key, original_filename="match-sync.xlsx",
file_size=16, sha256=digest, created_at=now,
))
_prepare_record_kind_circle_types()
hub = db.session.query(TransferTypeConfig).filter_by(code="hub_to_hub").one()
# 保留默认前缀规则,只追加「只要 outbound」,避免 ASN 类单号被前缀滤掉。
rules = [dict(item) for item in (hub.scope_rules_json or [])]
rules = [item for item in rules if item.get("field") != "record_kind"]
rules.append({"field": "record_kind", "match": "equals", "values": ["outbound"]})
hub.scope_rules_json = rules
db.session.commit()
assert TransferMovementLedger.query.filter_by(
source_code=source_code, record_kind="outbound").count() == 0
summary = create_matching(
source_codes=[source_code],
business_date="2026-10-16",
movement_date_from="2026-10-14",
movement_date_to="2026-10-14",
transfer_type="hub_to_hub",
deps=deps,
)
# [断言意图] 匹配前落档:异动档出现 outbound 行,并被圈入本次匹配。
assert TransferMovementLedger.query.filter_by(
source_code=source_code, record_kind="outbound", doc_no="HOX-MATCH-O1",
).count() == 1
assert "HOX-MATCH-O1" in {item.doc_no for item in items_of(summary)}
def test_matching_circles_ledger_records_within_scope(transfer_db):
"""圈档口径:范围外单(前缀不匹配)与已封存记录不入 items;圈内记录出生绑定档。"""
from app.models import TransferMovementLedger
@@ -730,6 +1046,53 @@ def test_matching_circles_ledger_records_within_scope(transfer_db):
]
def test_matching_birth_dedupes_same_grain_ledger_forks(transfer_db):
"""同 grain 多档(空 carton + 有 carton 重解析分叉)只出生一行,不撞唯一约束、不翻倍数量。"""
from app.models import TransferMatching
deps, erp, _rpa = make_transfer_deps(
{
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
"rows": [],
},
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
)
erp.seed_stock("D4-A08AR12000002", "WH1", "HOX26021903", "30")
older = _seed_ledger_record(
"HOX26021903", material="D4-A08AR12000002", quantity="30",
movement_date="2026-08-05", lot_no="HOX26021903", carton_id="",
row_no=1, file_sha256="b" * 64,
)
newer = _seed_ledger_record(
"HOX26021903", material="D4-A08AR12000002", quantity="30",
movement_date="2026-08-05", lot_no="HOX26021903", carton_id="C260219121",
row_no=2, file_sha256="c" * 64,
)
assert newer.id > older.id
summary = create_matching(
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
transfer_type="in_transit_to_hub",
)
# [断言意图] grain 择优有 carton 的较新档;数量仍为 30(不把分叉双行相加)。
# summary.matching_id 是 matching_no(MTG-…),行上 FK 是整数 matching.id。
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
items = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
assert len(items) == 1, (summary.counts, TransferInvoiceItem.query.count())
assert items[0].ledger_record_id == newer.id
assert items[0].movement_quantity == "30"
assert items[0].invoice_no == "HOX26021903"
# [断言意图] grain 占用互斥:二次匹配圈不到兄弟档,不累加行。
create_matching(
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
transfer_type="in_transit_to_hub",
)
assert TransferInvoiceItem.query.filter_by(invoice_no="HOX26021903").count() == 1
assert TransferMatching.query.count() == 2
def test_matching_routes_fixed_warehouse_from_type_config(transfer_db):
"""仓库定义(规格 §7):fixed 角色按类型配置覆盖映射档仓库(from 仍走映射档)。"""
from app import db as _db
@@ -61,12 +61,12 @@ def test_model_inbound_columns_and_ledger_key(app_ctx):
)
assert [col.name for col in ledger_uq.columns] == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq",
"in_out_flag", "carton_id", "lot_no",
"in_out_flag", "carton_id", "lot_no", "external_doc_no", "external_line_no",
]
# R7 终审:进键维度列必须 NOT NULL + default ''(nullable 成分的 NULL 不参与
# PG/SQLite 唯一比对,会逃逸唯一约束)。
# R7 终审 + 2026-10-21 外部身份扩维:进键维度列必须 NOT NULL + default ''
#(nullable 成分的 NULL 不参与 PG/SQLite 唯一比对,会逃逸唯一约束)。
ledger_cols = {c.name: c for c in TransferMovementLedger.__table__.columns}
for name in ("carton_id", "lot_no"):
for name in ("carton_id", "lot_no", "external_doc_no", "external_line_no"):
assert ledger_cols[name].nullable is False, f"{name} 进键即 NOT NULL"
assert ledger_cols[name].default.arg == ''
assert ledger_cols[name].server_default.arg == ''
@@ -33,16 +33,22 @@ pytestmark = pytest.mark.pure_unit
EXTENSION_FIELD_CODES = (
"line_seq", "specification", "order_type", "odm_id", "odm_name", "carton_id", "pallet_id",
)
# 2026-10-21 扩展追加的外部单据身份字段(外部单号/外部项次=WMS Order #/行号):
# required=False, is_identity=False(不进匹配身份);但作为异动档自然键成分承担
# 档幂等主键管控(模型 uq_transfer_movement_ledger_natural_key 10 成分)。
EXTERNAL_IDENTITY_FIELD_CODES = ("external_doc_no", "external_line_no")
def test_movement_fields_contract_is_frozen_and_complete():
"""领域字段契约定死:既有 11 字段 + 2026-10-14 扩展 7 可选字段、名称唯一、不可变。"""
assert len(MOVEMENT_FIELDS) == 18
"""领域字段契约定死:既有 11 字段 + 2026-10-14 扩展 7 可选字段 + 2026-10-21
外部单据身份 2 字段、名称唯一、不可变。"""
assert len(MOVEMENT_FIELDS) == 20
codes = {field.code for field in MOVEMENT_FIELDS}
assert codes == {
"doc_no", "line_no", "in_out_flag", "material_code", "material_name",
"warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", "unit",
*EXTENSION_FIELD_CODES,
*EXTERNAL_IDENTITY_FIELD_CODES,
}
@@ -69,6 +75,7 @@ def test_movement_field_extension_codes_appended_optional_non_identity():
"doc_no", "line_no", "in_out_flag", "material_code", "material_name",
"warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", "unit",
*EXTENSION_FIELD_CODES,
*EXTERNAL_IDENTITY_FIELD_CODES,
]
by_code = {field.code: field for field in MOVEMENT_FIELDS}
expected_labels = {
@@ -84,6 +91,27 @@ def test_movement_field_extension_codes_appended_optional_non_identity():
assert field.is_identity is False, code
def test_external_identity_fields_appended_optional_non_matching_identity():
"""2026-10-21 外部单据身份 2 字段(外部单号/外部项次):追加尾部、可选、非匹配身份。
Why: CRANE/Lognet 出站报告携带 WMS 自己的单据+行身份,需要与调拨单号
(doc_no)分开留存并作为异动档自然键成分(档幂等主键管控);匹配 grain
仍=单号/料号/异动日期,不受外部身份扩维扰动(契约由
test_identity_and_match_key_unchanged_by_extension 锁定)。
"""
by_code = {field.code: field for field in MOVEMENT_FIELDS}
expected_labels = {"external_doc_no": "外部单号", "external_line_no": "外部项次"}
# [断言意图] 只追加不重排:外部身份字段排在既有全部字段之后(文件列顺序契约)。
assert [field.code for field in MOVEMENT_FIELDS][-2:] == list(EXTERNAL_IDENTITY_FIELD_CODES)
for code in EXTERNAL_IDENTITY_FIELD_CODES:
field = by_code[code]
assert field.label == expected_labels[code], code
assert field.value_type == "text", code
# 解析放行空值(存量入站 Profile 未映射时不阻断);不进匹配身份集合。
assert field.required is False, code
assert field.is_identity is False, code
def test_movement_field_codes_include_extension_codes():
"""movement_field_codes() 自动包含全部扩展字段码(管理端字段目录/映射白名单数据源)。"""
codes = movement_field_codes()
@@ -0,0 +1,235 @@
"""outbound_evidence_sync:出站证据同步(落档桥)守卫矩阵。
用途:锁定出站回调 success 后的解析落档链——①正常路径按 purpose=outbound 已发布
规则解析归档、record_kind='outbound' 幂等落档 + 审计事件;②schema 类解析
失败把 parse_failed 三列独立落到出站归档文件上(状态投影随之 parse_failed)、
一行不落;③无配置/规则未发布或 purpose 不符 → no-op(fail-closed,不落失败
标记——规则缺失不是文件错误);④handler 接线:success 事实触发同步。
依赖:factories(build_movement_xlsx/INBOUND_MOVEMENT_FIELD_MAPPING + FakeArchiveStorage)、
ledger_sync.movement_file_version、app fixture(全局种子含 DSV360_AWSDU 站点)。
逻辑:归档字节经假存储注入(monkeypatch file_asset_storage.get_bytes);解析组装
与落档口径全部复用入站同一实现(parse_archive_to_ledger_rows / sync_ledger_rows),
差异仅 record_kind 与规则门禁 purpose='outbound'。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
FreightRpaParsingProfile,
TransferAuditEvent,
TransferMovementLedger,
)
from app.services.in_transit_transfer.ledger_sync import movement_file_version
from app.services.in_transit_transfer.outbound_evidence_sync import (
sync_and_commit_for_outbound_callback,
)
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
from tests.services.in_transit_transfer import factories
pytestmark = [pytest.mark.usefixtures("app")]
SOURCE = "DSV360_AWSDU"
# 真实时钟基准:handler/状态投影内部固定取 utcnow(),种子必须同窗口。
NOW = datetime.utcnow()
STORAGE_KEY = "shipping/outbound/evidence-sync.xlsx"
@pytest.fixture
def outbound_storage(monkeypatch):
"""归档假存储:替换单例 get_bytes(所有引用方同源)。"""
fake = factories.FakeArchiveStorage()
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
return fake
def _seed_outbound_world(*, profile_status: str = "published",
profile_purpose: str = "outbound",
bind_profile: bool = True) -> FreightRpaOutboundReportFile:
"""出站世界种子:出站配置(绑定解析规则)+ 执行单元 + 当天可用归档文件行。
Returns:
已入库的 FreightRpaOutboundReportFile(字节由用例注入假存储)。
"""
from app.models import FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SOURCE).one()
profile = None
if bind_profile:
profile = FreightRpaParsingProfile(
purpose=profile_purpose, profile_code=f"OUT_{SOURCE}", display_name=SOURCE,
version=1, status=profile_status, file_format="xlsx",
definition_json={
"field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING,
"sheet_name": "Receipt", "header_row_index": 1,
},
structure_definition_json={},
)
db.session.add(profile)
db.session.flush()
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={"report_name": "Outbound"},
query_parameters_json=[],
parsing_profile_id=profile.id if profile is not None else None,
))
unit = FreightRpaOutboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=SOURCE,
connector_type="dbs", warehouse_id="AWSDU", callback_id="outbound-sync-001",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
import hashlib
digest = hashlib.sha256(b"outbound evidence workbook").hexdigest()
report = FreightRpaOutboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=STORAGE_KEY, original_filename="outbound-sync.xlsx",
file_size=16, sha256=digest,
# 与 NOW 同刻:保证落在真实业务日新鲜度窗口内(handler/投影同窗口)。
created_at=NOW,
)
db.session.add(report)
db.session.commit()
return report
def _count_outbound_ledger(source_code: str = SOURCE) -> int:
"""该来源 outbound 档行总数。"""
return TransferMovementLedger.query.filter_by(
source_code=source_code, record_kind="outbound").count()
def test_outbound_callback_syncs_ledger_rows(outbound_storage):
# [断言意图] 正常路径:success 回调桥把出站归档按 purpose=outbound 规则解析、
# record_kind='outbound' 幂等落档;溯源(source_file_id/sha)与审计事件齐全。
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
assert ok is True # [断言意图] 落档成功
assert _count_outbound_ledger() == 1 # [断言意图] 出站行落异动档
db.session.expire_all()
row = TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").one()
assert row.doc_no == "ASN-O1" and row.material_code == "MAT-O1"
assert row.quantity == "120" and row.movement_date == "2026-10-16"
assert row.source_file_id == report.id and row.file_sha256 == report.sha256
# [断言意图] 审计事件带 record_kind=outbound(与入站同 kind、payload 区分流)。
event = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").one()
assert event.after_json["record_kind"] == "outbound"
assert event.after_json["inserted"] == 1
def test_outbound_file_version_uses_shared_stamp(outbound_storage):
"""出站落档的 file_version 必须是 movement_file_version,不能在本路径另拼。
Why: 2026-10-21 DSV AWSFRA01/AWSBICMH01 实测——本路径自行拼接 sha256: 前缀
且未按列宽截断,71 字符整批 INSERT 失败,文件仍显示就绪但档里零记录。
"""
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
assert ok is True # [断言意图] 落档成功(不再超长炸批)
db.session.expire_all()
row = TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").one()
# [断言意图] 落库版本戳等于共享函数对这份摘要的结果,且不超过列宽。
assert row.file_version == movement_file_version(report.sha256)
assert len(row.file_version) <= 64
def test_outbound_parse_failure_marks_file_and_lands_nothing(outbound_storage):
# [断言意图] 解析失败分层(出站补齐):schema 类失败 → parse_failed 三列独立
# 落到出站归档文件、零档行;状态投影随之 parse_failed(文件仍可用、供诊断)。
report = _seed_outbound_world()
# 有料号但单号为空 → missing_invoice_no → 解析必失败(料号空行 2026-10-21
# 起静默跳过放行,schema 失败路径改由仍受管控的单号缺失触发)。
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx(
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
assert ok is False # [断言意图] 落档失败如实返回
assert _count_outbound_ledger() == 0 # [断言意图] 一行不落
db.session.expire_all()
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is not None # [断言意图] 失败事实落到文件
assert marked.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID"
status = resolve_source_file_status(source_code=SOURCE, record_kind="outbound")
assert status["file_status"] == "parse_failed" # [断言意图] 投影不再当 ready
assert status["file_sha256"] == report.sha256
def test_outbound_without_published_outbound_profile_is_noop(outbound_storage):
# [断言意图] 规则门禁(fail-closed):无绑定规则 / 规则未发布 / purpose 不符
# → 桥 no-op(True=无事可做),零档行且不落解析失败标记——规则缺失不是文件错误。
for kwargs in (
{"bind_profile": False}, # 未绑定规则
{"profile_status": "draft"}, # 规则未发布
{"profile_purpose": "inbound"}, # purpose 不符(误绑入站规则)
):
report = _seed_outbound_world(**kwargs)
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O2", "1", "O", "MAT-O2", "成品", "LOT-O2", 30, "2026-10-16"],
])
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
assert ok is True, kwargs # [断言意图] 无事可做≠失败
assert _count_outbound_ledger() == 0, kwargs
db.session.expire_all()
assert FreightRpaOutboundReportFile.query.filter_by(
id=report.id).one().parse_failed_at is None, kwargs
# 清场(三门支共用全局种子,互不污染)。
FreightRpaOutboundReportConfig.query.delete()
FreightRpaOutboundReportFile.query.delete()
FreightRpaOutboundUnitRun.query.delete()
if kwargs.get("bind_profile", True):
FreightRpaParsingProfile.query.filter(
FreightRpaParsingProfile.profile_code == f"OUT_{SOURCE}").delete()
db.session.commit()
def test_outbound_handler_success_fact_triggers_sync(outbound_storage):
# [断言意图] handler 接线:outbound success 事实(ok 且 file_id)在任务推进/
# 提交之后触发证据同步(与入站 handle_inbound_report STEP 4 对称);失败事实
# 不触发(无文件可解析,桥不得误读他源文件)。
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O3", "1", "O", "MAT-O3", "成品", "LOT-O3", 55, "2026-10-16"],
])
handle_outbound_report(ReportFact(
report_kind="outbound", source_code=SOURCE, file_id=report.id,
sha256=report.sha256, ok=True, error_code=None, error_message=None,
unit_run_id=report.unit_run_id,
))
assert _count_outbound_ledger() == 1 # [断言意图] 事实驱动落档
# [断言意图] 失败事实(同一世界、新归档无字节解析路径不触发):行数不增。
handle_outbound_report(ReportFact(
report_kind="outbound", source_code=SOURCE, file_id=None,
sha256=None, ok=False, error_code="RPA_OUTBOUND_CALLBACK_FAILED",
error_message="export failed", unit_run_id=report.unit_run_id,
))
assert _count_outbound_ledger() == 1
@@ -70,11 +70,11 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
assert item.from_quantity == Decimal("1200")
def test_same_day_data_queried_through_gateway(app, same_day_inbound_file):
"""【成熟退役 2026-10-16】当天异动数据照常经网关查询(无免查日期)。
def test_same_day_data_not_queried_before_maturity(app, same_day_inbound_file):
"""【T−2 成熟封顶 2026-10-21】当天(T)异动未成熟:不进圈档、不经网关查询。
[断言意图] 夹具未种库存 → 行落 blocked_inventory_not_found;关键契约是
网关调用必须发生——日期不再构成评估前置过滤。
[断言意图] 圈档封顶 movement_date ≤ T−2:当天行不出生 item,网关零调用——
日期在圈档入口即构成过滤(此前「成熟退役 2026-10-16」的免查语义随之收回)。
"""
gw = FakeGateway(inventory={})
deps = _cap_deps(same_day_inbound_file, gw)
@@ -83,8 +83,8 @@ def test_same_day_data_queried_through_gateway(app, same_day_inbound_file):
source_codes=["DBS-AWSSG"], business_date="2026-08-06",
deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub"
)
assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls)
assert result.items[0].result == "blocked_inventory_not_found"
assert gw.calls == []
assert result.items == ()
def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file):
@@ -1,9 +1,10 @@
"""首页队列「待匹配」桶与执行门禁改锚测试(Task 12,规格 §10,D16/D17)。
用途:锁定两块契约——
①「待匹配」桶口径(D16):档记录 ∈ 启用类型范围并集、record_kind='inbound'、
未封存(transfer_executed=false)、无有效 items(D17 占用判定一致);
匹配圈定后离开、取消匹配释放后回归;无 item_id 不可勾选执行;
①「待匹配」桶口径:成熟未占用的出入站全量(不按类型范围过滤);
可匹配=启用类型范围并集(matchable / matchable_count)。
未封存(transfer_executed=false)、无有效 items(D17 占用判定一致)、
movement_date ≤ T−2;匹配圈定后离开、取消匹配释放后回归;无 item_id。
②file_current 门禁改锚(规格 §10):行当前性 = item → 档记录 file_sha256 ==
该来源最新可用文件 sha(档记录无变化即当前——档换版原行更新后行不再因
出生戳陈旧误判);行无档关联回退 raw_lines 出生戳(存量兼容)。
@@ -68,6 +69,11 @@ def _pending_doc_nos() -> set[str]:
return {record.doc_no for record in list_pending_match_records()}
def _matchable_doc_nos() -> set[str]:
"""待匹配桶里启用类型现在圈得住的单号。"""
return {record.doc_no for record in list_pending_match_records() if record.matchable}
# ---------------------------------------------------------------------------
# ①「待匹配」桶口径(D16)
# ---------------------------------------------------------------------------
@@ -104,12 +110,30 @@ def test_pending_match_bucket_summary_count():
assert summary.pending_match_count == 2
def test_pending_match_includes_mature_rows_outside_enabled_types():
"""待匹配收全部成熟未占用记录;可匹配只计启用类型范围并集。"""
_seed_ledger("HOM-1")
_seed_ledger("QQQ-1", row_no=2)
pending = list_pending_match_records()
summary = backlog_summary()
# [断言意图] 首页待匹配不再按类型范围收窄:范围外的成熟行仍在桶里。
assert {record.doc_no for record in pending} == {"HOM-1", "QQQ-1"}
# [断言意图] 库存匹配卡的可匹配数只含启用类型罩得住的行。
assert {record.doc_no for record in pending if record.matchable} == {"HOM-1"}
assert {record.doc_no for record in list_pending_match_records(segment="outside")} == {"QQQ-1"}
assert {record.doc_no for record in list_pending_match_records(segment="matchable")} == {"HOM-1"}
assert summary.pending_match_count == 2
assert summary.matchable_count == 1
def test_pending_match_bucket_leaves_once_matched():
"""匹配圈定 → 记录被 items 占用,离开待匹配桶(数字卡回落)。"""
_seed_ledger("HOM-1")
deps = _match_defaults()
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-14",
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-15",
deps=deps, transfer_type="in_transit_to_hub")
# [断言意图] 记录被匹配 items 占用(D17)→ 离开待匹配桶。
@@ -120,7 +144,7 @@ def test_pending_match_bucket_returns_after_matching_cancelled():
"""取消匹配释放占用(D17)→ 记录回归待匹配桶。"""
_seed_ledger("HOM-1")
deps = _match_defaults()
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-14",
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-15",
deps=deps, transfer_type="in_transit_to_hub")
assert _pending_doc_nos() == set()
@@ -135,21 +159,22 @@ def test_pending_match_bucket_returns_after_matching_cancelled():
assert _pending_doc_nos() == {"HOM-1"}
def test_pending_match_bucket_excludes_sealed_shipment_and_out_of_scope():
"""恒排除:已封存(transfer_executed)/ 出货记录 / 范围外 / movement_date 空值。"""
_seed_ledger("HOM-1") # 在桶
def test_pending_match_bucket_excludes_sealed_and_out_of_scope():
"""恒排除已封存与空异动日期;范围外仍留在待匹配,但不算可匹配。"""
_seed_ledger("HOM-1") # 在桶且可匹配
_seed_ledger("HOM-SEALED", row_no=2, transfer_executed=True,
executed_doc_no="ERP-1") # 已执行封存
_seed_ledger("HOM-SHIP", row_no=3, record_kind="outbound") # 出货记录(一期不进桶)
_seed_ledger("QQQ-1", row_no=4) # 范围外(无启用类型命中)
_seed_ledger("HOM-NODATE", row_no=5, movement_date=None) # 收料日期空值(不进圈定)
_seed_ledger("HOM-SHIP", row_no=3, record_kind="outbound") # 出站,默认类型未钉记录类型
_seed_ledger("QQQ-1", row_no=4) # 范围外,仍在待匹配
_seed_ledger("HOM-NODATE", row_no=5, movement_date=None) # 异动日期空值
# [断言意图] 桶只收「启用类型范围并集内、inbound、未封存、有异动日期、无 items」的档记录。
assert _pending_doc_nos() == {"HOM-1"}
# [断言意图] 待匹配收成熟未占用的出入站;可匹配才按启用类型范围并集收窄。
assert _pending_doc_nos() == {"HOM-1", "HOM-SHIP", "QQQ-1"}
assert _matchable_doc_nos() == {"HOM-1", "HOM-SHIP"}
def test_pending_match_bucket_is_union_of_enabled_type_scopes():
"""范围并集=对每个启用类型分别圈取后并集;停用类型即退出并集。"""
"""可匹配=启用类型范围并集;停用类型不把已落档行移出待匹配。"""
_seed_ledger("HOM-1") # 默认类型(HOM/HOX/WTP 前缀)
_seed_ledger("ZZZ-1", row_no=2) # 第二类型范围
_seed_ledger("QQQ-1", row_no=3) # 无类型覆盖
@@ -157,19 +182,24 @@ def test_pending_match_bucket_is_union_of_enabled_type_scopes():
{"field": "doc_no", "match": "prefix", "values": ["ZZZ"]},
])
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1"}
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"}
assert _matchable_doc_nos() == {"HOM-1", "ZZZ-1"}
# [断言意图] 停用类型即刻退出并集(停用后新匹配不可选,队列口径同步收窄)。
# [断言意图] 停用类型即刻退出可匹配并集,待匹配全量保持不变。
row = db.session.query(TransferTypeConfig).filter_by(code="hub_repair_out").one()
row.enabled = False
db.session.commit()
assert _pending_doc_nos() == {"HOM-1"}
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"}
assert _matchable_doc_nos() == {"HOM-1"}
# [断言意图] 无启用类型 → 空桶(fail-closed:无类型即无范围,与匹配创建一致)。
# [断言意图] 无启用类型 → 可匹配为空;待匹配仍可见已落档行。
for cfg in db.session.query(TransferTypeConfig).all():
cfg.enabled = False
db.session.commit()
assert _pending_doc_nos() == set()
assert _matchable_doc_nos() == set()
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"}
# [断言意图] 可匹配段在没有启用类型时走空查询,而不是把全量当成可匹配。
assert list_pending_match_records(segment="matchable") == []
# ---------------------------------------------------------------------------
@@ -177,9 +207,13 @@ def test_pending_match_bucket_is_union_of_enabled_type_scopes():
# ---------------------------------------------------------------------------
def _patch_latest_file(monkeypatch, sha_by_source: dict[str, str]):
"""注入 matching_service 的来源文件状态投影(source_code → 最新可用文件 sha)。"""
"""注入 matching_service 的来源文件状态投影(source_code → 最新可用文件 sha)。
def _resolve(*, source_code: str) -> dict:
record_kind 入参接受但不区分,存量断言仍按来源比对。
"""
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
del record_kind
sha = sha_by_source.get(source_code)
return {"file_status": "ready" if sha else "none", "has_ready_file": bool(sha),
"file_no": "REC-TEST", "file_sha256": sha}
@@ -28,7 +28,7 @@ def _file_ready(monkeypatch, dbs_ready_file: dict) -> None:
"""让来源文件状态投影返回 ready(sha 与 fixture 文件一致,不触碰真实文件表)。"""
monkeypatch.setattr(
matching_service, "resolve_source_file_status",
lambda *, source_code: {"file_status": "ready", "has_ready_file": True,
lambda *, source_code, record_kind="inbound": {"file_status": "ready", "has_ready_file": True,
"file_no": dbs_ready_file["file_no"],
"file_sha256": dbs_ready_file["checksum"]},
)
@@ -114,7 +114,7 @@ def test_restore_marks_file_current_false_without_ready_file(transfer_db, dbs_re
"""来源当前无可用文件 → 行 file_current=False(fail-safe,不得当作新鲜)。"""
monkeypatch.setattr(
matching_service, "resolve_source_file_status",
lambda *, source_code: {"file_status": "none", "has_ready_file": False,
lambda *, source_code, record_kind="inbound": {"file_status": "none", "has_ready_file": False,
"file_no": None, "file_sha256": None},
)
deps, erp, _ = make_transfer_deps(dbs_ready_file)
@@ -25,7 +25,7 @@ def _mismatch_matching(dbs_ready_file):
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
return deps, erp, summary
@@ -213,7 +213,7 @@ def test_requery_reaches_only_own_matching_rows(transfer_db, dbs_ready_file):
assert row.matching_id == first_matching.id
# 第二次同 scope 匹配:圈档互斥 → 空壳(无自有行)。
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
assert second.matching_id != first.matching_id
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
assert row.matching_id != second_matching.id
@@ -285,7 +285,7 @@ def _wtp_lot_matching(transfer_db):
}
deps, erp, _ = make_transfer_deps(file_dict)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
return deps, erp
@@ -1,8 +1,8 @@
"""范围规则引擎契约:规则间 AND、规则内多值 OR、受控词表、SQL 编译与内存求值同口径。
用途:锁定 scope_rules 引擎对外契约——受控字段白名单校验、evaluate/apply 双形态
同口径(防谓词漂移)、审计说明文本格式;Task 11(圈档/重查)与 Task 5
(API 校验)消费本契约。
同口径(防谓词漂移)、record_kinds_of 证据流推导、审计说明文本格式;
Task 11(圈档/重查)与 Task 5(API 校验)及证据流 UI 后续任务消费本契约。
依赖:app.core.errors.ValidationError、scope_rules 引擎、SQLAlchemy、
models/in_transit_transfer.TransferMovementLedger(SQL 编译断言与真库
行集交叉验证均以真档表为对象,2026-10-14 Task 9 回补,探针模型退役)。
@@ -19,7 +19,7 @@ from app import db
from app.core.errors import ValidationError
from app.models.in_transit_transfer import TransferMovementLedger
from app.services.in_transit_transfer.scope_rules import (
apply_scope_filters, evaluate_scope, parse_scope_rules, scope_rules_note,
apply_scope_filters, evaluate_scope, parse_scope_rules, record_kinds_of, scope_rules_note,
)
pytestmark = pytest.mark.pure_unit
@@ -31,6 +31,19 @@ RULES = parse_scope_rules([
])
def test_record_kinds_of_reads_existing_scope_rule():
"""没有记录类型规则时入站和出站都要;只写 outbound 时只要出站。"""
assert record_kinds_of(parse_scope_rules([
{"field": "doc_no", "match": "prefix", "values": ["HOM"]},
])) == ("inbound", "outbound")
assert record_kinds_of(parse_scope_rules([
{"field": "record_kind", "match": "equals", "values": ["outbound"]},
])) == ("outbound",)
assert record_kinds_of(parse_scope_rules([
{"field": "record_kind", "match": "in", "values": ["outbound", "inbound"]},
])) == ("inbound", "outbound")
def test_rules_are_and_values_are_or():
"""两条规则须同时满足;同一规则内任一前缀命中即可。"""
assert evaluate_scope({"doc_no": "HOM-1", "source_code": "SRC-A"}, RULES)
@@ -1,12 +1,15 @@
"""来源收料文件状态投影服务测试。
"""来源证据文件状态投影服务测试。
用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile),
按来源投影 ready/fetching/failed/expired/parse_failed/none,并验证解析失败
标记 record/clear 的往返语义。调拨不维护独立抓取状态表。
依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
逻辑:有当天(业务日)抓取且未过期文件→ready(若标记解析失败→parse_failed);
有进行中单元→fetching;最新单元失败终态→failed;
保留期已到或隔日旧文件(未清理)→expired;否则→none。
用途:验证 resolve_source_file_status / resolve_source_file_statuses 只读货代入站/出站事实(UnitRun/ReportFile),
按来源与 record_kind 投影 ready/fetching/failed/expired/parse_failed/none/
unconfigured,并验证入站解析失败标记 record/clear 的往返语义。
调拨不维护独立抓取状态表。
依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile;
出站用例用 monkeypatch 注入配置与可用文件视图,不连对象存储。
逻辑:入站既有用例保持:当天业务日且未过期文件→ready(解析失败→parse_failed);
进行中单元→fetching;最新单元失败终态→failed;空数据→no_data;
保留期已到或隔日旧文件→expired;否则→none。
出站无配置→unconfigured;出站有可用文件视图→ready。
"""
from __future__ import annotations
@@ -247,3 +250,170 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
assert recover_all_stale_orphan_inbound_units() == 1
db.session.expire_all()
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'failed'
def test_outbound_without_config_is_unconfigured(monkeypatch):
"""没有出站报表配置时,出站流是未配置,入站投影函数签名仍可只传来源。"""
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.get_outbound_config",
lambda source_code: None,
)
status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound")
assert status["file_status"] == "unconfigured"
assert status["has_ready_file"] is False
def test_outbound_usable_file_is_ready(monkeypatch):
"""出站已配置且存在可用归档时投影 ready;文件视图按入站可用文件形状注入,不读对象存储。"""
from types import SimpleNamespace
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.get_outbound_config",
lambda source_code: object(),
)
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.latest_usable_outbound_file",
lambda source_code: SimpleNamespace(
file_id=7,
original_filename="outbound.xlsx",
sha256="ab" * 32,
parse_failed_at=None,
),
)
status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound")
# [断言意图] ready 必须读入站同形视图的文件名与摘要,而不是另查对象存储。
assert status["file_status"] == "ready"
assert status["has_ready_file"] is True
assert status["file_no"] == "outbound.xlsx"
assert status["file_sha256"] == "ab" * 32
def test_unknown_record_kind_is_rejected():
"""record_kind 只接受 inbound / outbound。"""
from app.core.errors import ValidationError
with pytest.raises(ValidationError):
resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="onhand")
def test_outbound_report_file_projects_ready(app):
"""出站配置与当天可用归档都在库时,按出站文件表投影 ready,不读对象存储。"""
from app import db
from app.models import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
FreightRpaSource,
)
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={'report_name': 'Outbound'},
query_parameters_json=[],
))
unit = FreightRpaOutboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
connector_type='dbs', warehouse_id='AWSDU', callback_id='outbound-status-ready',
status='success', config_snapshot_json={}, trigger_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
digest = hashlib.sha256(b'outbound workbook').hexdigest()
db.session.add(FreightRpaOutboundReportFile(
unit_run_id=unit.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/outbound/test.xlsx', original_filename='outbound-real.xlsx',
file_size=16, sha256=digest,
))
db.session.commit()
status = resolve_source_file_status(source_code=SOURCE_CODE, record_kind='outbound')
# [断言意图] 出站 ready 走真实归档表与单元行,文件名/摘要来自行数据而非对象存储。
assert status['file_status'] == 'ready'
assert status['has_ready_file'] is True
assert status['file_no'] == 'outbound-real.xlsx'
assert status['file_sha256'] == digest
def _clone_enabled_source(source_code: str):
"""再造一个启用来源,复用种子站点的登录连接与模板,避免把查询次数测试绑在单来源上。"""
from app import db
from app.models import FreightRpaSource
existing = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
source = FreightRpaSource(
source_code=source_code,
display_name=source_code,
connector_type=existing.connector_type,
rpa_profile_id=existing.rpa_profile_id,
excel_template_id=existing.excel_template_id,
warehouse_resolution_mode=existing.warehouse_resolution_mode,
fixed_warehouse_id=existing.fixed_warehouse_id,
enabled=True,
)
db.session.add(source)
db.session.commit()
return source
def test_batch_status_matches_per_source_and_prefers_running_unit(app, receipt_unit_run):
"""列表批量投影与逐来源投影一致;较新的失败单元不能盖住仍在进行的单元。"""
from app import db
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses
db.session.add(FreightRpaInboundUnitRun(
schedule_run_id=None,
source_id=receipt_unit_run.source_id,
source_code=SOURCE_CODE,
connector_type='dbs',
callback_id='inbound-newer-failed',
status='failed',
config_snapshot_json={},
trigger_snapshot_json={},
))
extra = _clone_enabled_source('DSV360_BATCH_EXTRA')
db.session.commit()
sources = FreightRpaSource.query.filter(
FreightRpaSource.source_code.in_([SOURCE_CODE, extra.source_code]),
).all()
batched = resolve_source_file_statuses(sources)
# [断言意图] 进行中单元优先于更新的失败单元,批量结果必须与逐条投影相同。
assert batched[SOURCE_CODE]['inbound']['file_status'] == 'fetching'
assert batched[SOURCE_CODE]['outbound']['file_status'] == 'unconfigured'
assert batched[extra.source_code]['inbound']['file_status'] == 'none'
for source in sources:
assert batched[source.source_code]['inbound'] == resolve_source_file_status(
source_code=source.source_code, record_kind='inbound',
)
assert batched[source.source_code]['outbound'] == resolve_source_file_status(
source_code=source.source_code, record_kind='outbound',
)
def test_batch_status_query_count_stays_flat_for_two_sources(app, receipt_unit_run):
"""两个来源的列表投影查询次数保持常数,不能按来源乘开。"""
from sqlalchemy import event
from app import db
from app.models import FreightRpaSource
from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses
extra = _clone_enabled_source('DSV360_BATCH_COUNT')
sources = FreightRpaSource.query.filter(
FreightRpaSource.source_code.in_([SOURCE_CODE, extra.source_code]),
).all()
assert len(sources) == 2
count = {'n': 0}
def _count_query(*_args, **_kwargs):
count['n'] += 1
event.listen(db.engine, 'before_cursor_execute', _count_query)
try:
resolve_source_file_statuses(sources)
finally:
event.remove(db.engine, 'before_cursor_execute', _count_query)
# [断言意图] 逐来源投影约 7 次/来源;两个来源仍必须落在固定的几次批量查询里。
assert count['n'] <= 8
@@ -18,13 +18,14 @@ from app import db
from app.models import FreightRpaInboundReportFile
from app.models.in_transit_transfer import TransferMovementLedger
# 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维):8 成分全部 NOT NULL,
# 可空语义成分(line_seq/in_out_flag/carton_id/lot_no)default ''(R7 终审:
# carton_id/lot_no NOT NULL + default '',防 PG NULL 逃逸唯一比对)。
# 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维 + 2026-10-21 外部身份
# 扩维):10 成分全部 NOT NULL,可空语义成分(line_seq/in_out_flag/carton_id/
# lot_no/external_doc_no/external_line_no)default ''(R7 终审:carton_id/lot_no
# NOT NULL + default '',防 PG NULL 逃逸唯一比对;外部身份两列同口径)。
NATURAL_KEY_COLUMNS = (
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
)
NATURAL_KEY_DIMENSION_COLUMNS = ('carton_id', 'lot_no')
NATURAL_KEY_DIMENSION_COLUMNS = ('carton_id', 'lot_no', 'external_doc_no', 'external_line_no')
NATURAL_KEY_CONSTRAINT = 'uq_transfer_movement_ledger_natural_key'
# 规格 §4.2 全部业务/证据列(除自然键成分与回写布尔外一律 nullable)。
@@ -49,7 +50,7 @@ def _column_map() -> dict:
def test_table_name_and_natural_key_constraint(app_ctx):
"""表名固定;自然键八成分(tt14 扩维 carton_id/lot_no)构成唯一约束。"""
"""表名固定;自然键十成分(tt14 扩维 carton_id/lot_no + 2026-10-21 外部单据身份)构成唯一约束。"""
assert TransferMovementLedger.__tablename__ == 'transfer_movement_ledger'
constraints = {
c.name: [col.name for col in c.columns]
@@ -62,12 +63,13 @@ def test_table_name_and_natural_key_constraint(app_ctx):
def test_natural_key_columns_not_null_with_empty_default(app_ctx):
"""自然键 8 成分全部 NOT NULL;可空语义成分 default ''(R7:carton_id/lot_no 同口径)。"""
"""自然键 10 成分全部 NOT NULL;可空语义成分 default ''(R7:carton_id/lot_no 同口径)。"""
cols = _column_map()
for name in NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS:
assert cols[name].nullable is False, f"{name} 必须参与自然键即 NOT NULL"
# 与落档链路同口径:可空语义成分以空串入库(唯一约束可比,防 PG NULL 逃逸)。
for name in ('line_seq', 'in_out_flag', 'carton_id', 'lot_no'):
for name in ('line_seq', 'in_out_flag', 'carton_id', 'lot_no',
'external_doc_no', 'external_line_no'):
assert cols[name].default.arg == ''
assert cols[name].server_default.arg == ''
@@ -43,8 +43,12 @@ def _file(*rows: dict) -> dict:
}
def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: str = "2026-08-05") -> dict:
"""构造单条 movement 行;unit=None 表示文件中该列缺失(而非空串)。"""
def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: str = "2026-08-04") -> dict:
"""构造单条 movement 行;unit=None 表示文件中该列缺失(而非空串)。
movement_date 缺省取 2026-08-04(= 业务日 08-06 的 T−2 成熟边界;更晚日期
会被圈档 T−2 封顶排除)。
"""
row = {
"sheet": "Movement", "row_no": row_no, "doc_no": doc_no,
"lot_no": f"LOT-{row_no}", "material_code": f"MAT-{row_no}",
@@ -62,9 +66,10 @@ def test_movement_fields_contract_contains_unit_as_11th_field():
"""契约定死且第 11 个为 unit:可选文本字段(空值由匹配阶段行级阻断,不产生解析失败)。
2026-10-14 扩展在 unit 之后追加 7 个可选维度字段(Task 8)——只追加、不重排,
unit 的第 11 位契约不变。
unit 的第 11 位契约不变;2026-10-21 再追加外部单据身份 2 字段(外部单号/
外部项次),总数 11+7+2=20。
"""
assert len(MOVEMENT_FIELDS) == 18
assert len(MOVEMENT_FIELDS) == 20
unit = MOVEMENT_FIELDS[10]
# [断言意图] unit 定死在第 11 位——movement 文件列顺序契约,解析/展示/ERP 写入共用。
assert unit.code == "unit"
@@ -73,7 +78,7 @@ def test_movement_fields_contract_contains_unit_as_11th_field():
# unit 不是幂等/匹配身份,也不是必填(解析层放行空值,阻断留给匹配层)。
assert unit.is_identity is False
assert unit.required is False
assert len({field.code for field in MOVEMENT_FIELDS}) == 18
assert len({field.code for field in MOVEMENT_FIELDS}) == 20
# ---- ② 解析:带出 unit 原值(仅 trim,不换算/不清洗) -----------------------
@@ -189,10 +194,10 @@ def test_matching_hash_freezes_unit_value_out_of_snapshot(app):
def test_matching_hash_unchanged_when_unit_backfilled(app):
"""行补 unit 前后 Hash 不变:unit 是展示/写入列而非 Hash 入参(口径冻结)。"""
deps_before, _erp_a, _rpa = make_transfer_deps(_file(
_row(1, "HOM-901", movement_date="2026-08-06"),
_row(1, "HOM-901", movement_date="2026-08-04"),
))
deps_after, _erp_b, _rpa = make_transfer_deps(_file(
_row(1, "HOM-901", unit="KG", movement_date="2026-08-06"),
_row(1, "HOM-901", unit="KG", movement_date="2026-08-04"),
))
seed_rows_from_file("DBS-AWSBI", deps_before, "2026-08-06") # 行落地一次
hash_before = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_before, transfer_type="in_transit_to_hub").summary.matching_hash
+145 -24
View File
@@ -39,30 +39,48 @@ class _FakeLocator:
class _FakePage:
def __init__(self, *, url: str = "https://wms-portal.craneww.com/#/") -> None:
def __init__(
self,
*,
url: str = "https://wms-portal.craneww.com/#/",
visible_tokens: tuple[str, ...] = ("on-hand-details-query", "On Hand Details", "Queries", "navbar"),
visible_role_names: tuple[str, ...] = ("On Hand Details", "Queries"),
) -> None:
self.url = url
self.frames: list[_FakePage] = []
self.goto_calls: list[str] = []
self.evaluate_calls: list[tuple[str, object]] = []
self.reload_calls: list[int] = []
self.locator_selectors: list[str] = []
self._visible_tokens = visible_tokens
self._visible_role_names = visible_role_names
def locator(self, selector: str) -> _FakeLocator:
if "on-hand-details-query" in selector or "On Hand Details" in selector:
return _FakeLocator(visible=True)
if "Queries" in selector or "navbar" in selector:
return _FakeLocator(visible=True)
return _FakeLocator(visible=False)
self.locator_selectors.append(selector)
visible = any(token in selector for token in self._visible_tokens)
return _FakeLocator(visible=visible)
def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator:
if role == "link" and name in {"On Hand Details", "Queries"}:
return _FakeLocator(visible=True)
return _FakeLocator(visible=False)
return _FakeLocator(visible=name in self._visible_role_names)
def goto(self, url: str, wait_until: str = "", timeout: int = 0) -> None:
self.goto_calls.append(url)
self.url = url
def reload(self, wait_until: str = "", timeout: int = 0) -> None:
self.reload_calls.append(1)
def evaluate(self, script: str, arg: object = None) -> None:
self.evaluate_calls.append((script, arg))
if isinstance(arg, str):
self.url = f"https://wms-portal.craneww.com/#/{arg.lstrip('/')}"
def wait_for_load_state(self, state: str = "", timeout: int = 0) -> None:
return None
def test_navigate_prefers_dashboard_tile(monkeypatch):
"""应优先尝试首页 On Hand Details 卡片。"""
"""应优先尝试首页目标报表卡片。"""
module = _load_navigation()
page = _FakePage()
calls: list[str] = []
@@ -70,10 +88,10 @@ def test_navigate_prefers_dashboard_tile(monkeypatch):
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
monkeypatch.setattr(
module,
"_click_dashboard_on_hand_details",
"_click_dashboard_report_tile",
lambda *args, **kwargs: calls.append("dashboard") or True,
)
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: calls.append("navbar") or True)
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: calls.append("navbar") or True)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
mode = module.navigate_to_crane_report(
@@ -95,8 +113,8 @@ def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch):
wait_calls = {"n": 0}
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: True)
def _wait(page_arg, entry_url, *, browser_timeout_ms):
wait_calls["n"] += 1
@@ -115,22 +133,59 @@ def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch):
assert wait_calls["n"] == 2
def test_navigate_uses_direct_goto_as_last_resort(monkeypatch):
"""卡片与菜单均失败时应 goto entry_url。"""
def test_direct_goto_last_resort_assigns_hash_in_place(monkeypatch):
"""卡片与菜单均失败后:goto entry_url 未就绪时只允许就地赋 hash,禁止回根地址。"""
module = _load_navigation()
page = _FakePage()
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
entry = "https://wms-portal.craneww.com/#/outbound-details-query"
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: False)
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: False)
def _wait(page_arg, entry_url_arg, *, browser_timeout_ms):
# [断言意图] 就地赋 hash 之后表单才视为就绪;此前一律未就绪
return len(page.evaluate_calls) > 0
monkeypatch.setattr(module, "_wait_for_report_navigation", _wait)
mode = module.navigate_to_crane_report(
page,
entry,
env=lambda name, default="": default,
browser_timeout_ms=5_000,
)
assert mode == "direct_goto"
assert page.goto_calls == [entry]
assert page.reload_calls == []
assert not any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
assert page.evaluate_calls and "outbound-details-query" in str(page.evaluate_calls[0][1])
def test_navigation_never_lands_on_origin_when_form_never_ready(monkeypatch):
"""表单始终未就绪也应抛 RuntimeError,且全程不得 goto 根地址或 reload(会强制登出)。"""
module = _load_navigation()
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
entry = "https://wms-portal.craneww.com/#/outbound-details-query"
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: False)
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: False)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: False)
with pytest.raises(RuntimeError, match="navigation failed"):
module.navigate_to_crane_report(page, entry, env=lambda n, d="": d, browser_timeout_ms=5_000)
module.navigate_to_crane_report(
page,
entry,
env=lambda name, default="": default,
browser_timeout_ms=5_000,
)
assert page.goto_calls[0] == entry
assert any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
# [断言意图] 失败收场也只允许一次 goto(entry):根地址/reload 一旦发生即登出
assert page.goto_calls == [entry]
assert page.reload_calls == []
assert not any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
def test_is_crane_on_report_route_reads_entry_hash():
@@ -157,3 +212,69 @@ def test_report_route_without_controls_is_not_ready(monkeypatch):
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
monkeypatch.setattr(module, "_has_report_form_controls", lambda page_arg: False)
assert module.is_crane_report_form_ready(page, entry) is False
@pytest.mark.parametrize(
("route", "label"),
(
("on-hand-details-query", "On Hand Details"),
("inbound-details-query", "Inbound Details"),
("outbound-details-query", "Outbound Details"),
),
)
def test_navigate_targets_tile_by_entry_route(route, label, monkeypatch):
"""首页卡片/菜单选择器必须由 entry 路由推导,禁止硬编码 On Hand Details。"""
module = _load_navigation()
# [构造] 门户对授权用户渲染目标报表卡片:当前路由/标签的选择器可见
page = _FakePage(
url="https://wms-portal.craneww.com/#/",
visible_tokens=(route, label, "Queries"),
)
entry = f"https://wms-portal.craneww.com/#/{route}"
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
mode = module.navigate_to_crane_report(
page,
entry,
env=lambda name, default="": default,
browser_timeout_ms=5_000,
)
assert mode == "dashboard_tile"
joined = "\n".join(page.locator_selectors)
assert label in joined
# [断言意图] 出站/入站导航不得再查询 On Hand Details 选择器(2026-10-20 死循环根因之一);
# 路由推导由 test_direct_goto_last_resort(evaluate 参数)单独覆盖
for other in {"On Hand Details", "Inbound Details", "Outbound Details"} - {label}:
assert other not in joined
def test_navbar_fallback_uses_entry_route_label(monkeypatch):
"""首页卡片不可见时,经 Queries 菜单点击的路由项也须由 entry 推导。"""
module = _load_navigation()
# [构造] 卡片全部不可见(token 只含 navbar),仅 Queries 下拉项可见;
# 首页等待用短超时避免 shell 未就绪时白等 5s
page = _FakePage(
url="https://wms-portal.craneww.com/#/",
visible_tokens=("navbar",),
visible_role_names=("Queries",),
)
entry = "https://wms-portal.craneww.com/#/outbound-details-query"
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
mode = module.navigate_to_crane_report(
page,
entry,
env=lambda name, default="": default,
browser_timeout_ms=1_000,
)
assert mode == "navbar_menu"
joined = "\n".join(page.locator_selectors)
# [断言意图] 菜单回退路径同样按 entry 推导标签,禁止再查询 On Hand Details 选择器
assert '.navbar-dropdown a.navbar-item:has-text("Outbound Details")' in joined
assert "On Hand Details" not in joined
+23
View File
@@ -599,6 +599,29 @@ def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_p
assert fallback_called["value"] is False
def test_refresh_scheduled_reports_list_never_reloads_page(monkeypatch):
"""列表 goto 刷新失败时就地重赋 hash;登录态下禁止 page.reload(Crane 门户刷新即登出)。"""
module = _load_export()
page = MagicMock()
page.url = "https://wms-portal.craneww.com/#/scheduled-reports"
page.goto.side_effect = RuntimeError("net::ERR_ABORTED")
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
monkeypatch.setattr(module, "_scheduled_reports_table_visible", lambda *_a, **_k: True)
monkeypatch.setattr(module, "_wait_for_scheduled_reports_list_ready", lambda *_a, **_k: True)
module._refresh_scheduled_reports_list(
page,
env=lambda name, default="": default,
browser_timeout_ms=5_000,
entry_url="https://wms-portal.craneww.com/#/outbound-details-query",
)
# [断言意图] goto 失败的兜底是就地 hash 重赋;reload 一次都不允许发生
page.reload.assert_not_called()
assert page.evaluate.called
def test_row_matches_scheduled_report_normalizes_name_form(monkeypatch):
"""行名 InboundDetails.xlsx 与期望名 Inbound Details 应规范化后相等(收料轮询 not found 根因)。"""
module = _load_export()
+143 -5
View File
@@ -217,6 +217,26 @@ def test_resolve_parameter_controls_receipt_detail_awsrtm_warehouse_multi_value(
assert module.resolve_parameter_controls("Receipt Detail", "Warehouse")["control"] == "select"
def test_resolve_parameter_controls_shipment_order_detail_owner_and_warehouse():
"""出站 Shipment Order Detail 的 Owner/Warehouse 应按实机 DOM 使用 multi_value,而不是库存默认 select。"""
module = _load_module()
owner = module.resolve_parameter_controls("Shipment Order Detail", "Owner")
warehouse = module.resolve_parameter_controls("Shipment Order Detail", "Warehouse")
# 关键断言:2026-10-19 AWS/Bison/AWSBI 实机——Owner ctl15、Warehouse ctl31,均为 txtValue 下拉。
assert owner == {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
}
assert warehouse == {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl31_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl31_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl31_divDropDown",
}
def test_resolve_parameter_controls_unknown_report_empty():
"""未登记报表名应返回空配置,由调用方回退参数名默认值(保持旧行为)。"""
module = _load_module()
@@ -326,10 +346,12 @@ def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value():
report_name="On Hand Inventory by Location",
)
assert payloads, "应进入多选框下拉填充路径而不是无痕失败"
# payloads 会混入结构性解析传入的 label 字符串("Warehouse"),只断言 dict 载荷。
dict_payloads = [p for p in payloads if isinstance(p, dict)]
assert dict_payloads, "应进入多选框下拉填充路径而不是无痕失败"
assert any(
payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl17_divDropDown"
for payload in payloads
for payload in dict_payloads
), f"应命中 JDA ctl17 multi_value dropdown,实际 payloads={payloads!r}"
@@ -431,10 +453,12 @@ def test_fill_dsv_filter_if_needed_receipt_awsrtm_uses_ctl29_multi_value():
program_label="AWSRTM",
)
assert payloads, "应进入 AWSRTM multi_value 填充路径"
# payloads 会混入结构性解析传入的 label 字符串,只断言 dict 载荷。
dict_payloads = [p for p in payloads if isinstance(p, dict)]
assert dict_payloads, "应进入 AWSRTM multi_value 填充路径"
assert any(
payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl29_divDropDown"
for payload in payloads
for payload in dict_payloads
), f"应命中 ctl29 multi_value dropdown,实际 payloads={payloads!r}"
@@ -471,14 +495,20 @@ class _RecordingPage:
_STRUCTURAL_CONTROLS = {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
}
_STRUCTURAL_SELECT = {
"control": "select",
"selector": "#ReportViewerMain_ctl08_ctl19_ddValue",
}
def test_structural_resolver_hit_returns_controls_and_trims_label():
"""命中 frame 返回三件套;label 先 trim 再传入页面脚本。"""
"""命中 frame 返回 multi_value 三件套(含 control);label 先 trim 再传入页面脚本。"""
module = _load_module()
early = _RecordingFrame(result=None)
hit = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
@@ -490,6 +520,22 @@ def test_structural_resolver_hit_returns_controls_and_trims_label():
assert hit.calls == ["Owner"]
def test_structural_resolver_select_via_label_for_returns_ddvalue():
"""Cincinnati CVG611 形态:label[for]=ctl19_ddValue 时返回 select,禁止再当 multi_value。
[断言意图] 2026-10-20 事故回归——Warehouse 是原生 select,不得落到 ctl17_txtValue
(已漂移为 Project ID)文本兜底。
"""
module = _load_module()
hit = _RecordingFrame(result=dict(_STRUCTURAL_SELECT))
page = _RecordingPage([hit])
got = module.resolve_parameter_controls_structural(page, "Warehouse")
assert got == _STRUCTURAL_SELECT
assert hit.calls == ["Warehouse"]
def test_structural_resolver_all_frames_miss_or_error_returns_none():
"""全部 frame 未命中或探测异常(跨域/销毁帧):返回 None 交调用方回退。"""
module = _load_module()
@@ -596,6 +642,98 @@ def test_fill_multi_select_structural_preferred_registry_is_fallback(monkeypatch
assert probed.calls == ["Warehouse"]
def test_fill_warehouse_uses_structural_select_not_stale_txtvalue(monkeypatch, capsys):
"""Warehouse 结构性命中 select 时走 ddValue,禁止 JDA 模板 ctl17_txtValue 文本兜底。
[断言意图] 复现 2026-10-20 Cincinnati:模板仍写 multi_value@ctl17,但页面 Warehouse
是 ctl19_ddValue;不得把 BYAWSCV611 写进漂移后的 Project ID。
"""
module = _load_module()
page = _RecordingPage([_RecordingFrame(result=dict(_STRUCTURAL_SELECT))])
selected: dict[str, str] = {}
class _FakeText:
first = None
def __init__(self) -> None:
self.first = self
def is_visible(self, timeout: int | None = None) -> bool:
return False
page.get_by_text = lambda text, exact=False: _FakeText() # type: ignore[attr-defined]
def _fake_select(page_obj, label, value, selector, *, timeout_ms):
selected["selector"] = selector
selected["value"] = value
return True
def _fake_multi(*_a, **_k):
raise AssertionError("select 形态不得走 multi_value")
monkeypatch.setattr(module, "_fill_select_parameter", _fake_select)
monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_multi)
ok = module.fill_dsv_filter_if_needed(
page,
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse",
"BYAWSCV611",
env=lambda name, default="": default,
browser_timeout_ms=lambda: 3_000,
report_name="On Hand Inventory By Location",
program_label="CVG611",
)
assert ok is True
assert selected == {
"selector": "#ReportViewerMain_ctl08_ctl19_ddValue",
"value": "BYAWSCV611",
}
captured = capsys.readouterr()
assert "ctl17_txtValue" not in captured.out + captured.err
def test_fill_warehouse_refuses_stale_txtvalue_when_structural_miss(monkeypatch, capsys):
"""结构性未命中且模板 multi_value 失败时:Warehouse 拒绝 txtValue 文本兜底并返回 False。"""
module = _load_module()
page = _RecordingPage([_RecordingFrame(result=None)])
class _FakeText:
first = None
def __init__(self) -> None:
self.first = self
def is_visible(self, timeout: int | None = None) -> bool:
return False
page.get_by_text = lambda text, exact=False: _FakeText() # type: ignore[attr-defined]
monkeypatch.setattr(module, "_fill_multi_value_parameter", lambda *_a, **_k: False)
monkeypatch.setattr(module, "_probe_report_parameter_controls", lambda *_a, **_k: {"controls": []})
filled_via_script: list[str] = []
monkeypatch.setattr(
module,
"_fill_input_via_script",
lambda root, selector, text: filled_via_script.append(selector) or True,
)
ok = module.fill_dsv_filter_if_needed(
page,
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse",
"BYAWSCV611",
env=lambda name, default="": default,
browser_timeout_ms=lambda: 3_000,
report_name="On Hand Inventory By Location",
)
assert ok is False
assert filled_via_script == []
captured = capsys.readouterr()
assert "refusing stale txtValue fallback" in captured.err
def test_multi_value_already_set_set_equality_not_substring():
"""2026-10-08 Owner@AWSRTM 事故根因回归:SSRS 多选框默认全选,txtValue 恒为全量 CSV,
目标值必为该 CSV 的子串——必须用集合相等判定,子串包含会恒误判"已设置"并跳过下拉勾选。"""
@@ -76,6 +76,87 @@ def test_receipt_unit_processing_and_batch_progress(app):
assert refreshed.response_summary_json['progress']['success_count'] == 1
def test_inbound_batch_ready_sink_finalizes_schedule_even_if_fact_handler_raises(
app, monkeypatch,
):
"""文件归档单元终态后,事实/证据处理失败仍须收口排程(文件返回= RPA 结束)。
[断言意图] batch-ready sink 在 finally 中 finalize;不得依赖 handle_inbound_report 成功。
"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.rpa_sinks import _inbound_batch_ready_sink
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(
schedule_no='SCH-INBOUND-FILE-FINAL',
name='Inbound file finalize',
schedule_type='platform_job',
platform_api_path='freight-rpa-inbound',
owner_user_id=1,
cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no='RUN-INBOUND-FILE-FINAL',
schedule_task_id=task.id,
status='running',
total_count=1,
success_count=0,
failed_count=0,
skipped_count=0,
response_summary_json={'awaiting_inbound_rpa': True},
)
db.session.add(run)
db.session.flush()
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id,
source_id=source.id,
source_code=source.source_code,
connector_type='dbs',
warehouse_id='AWSDU',
callback_id='inbound-file-final-cb',
status='awaiting_rpa',
config_snapshot_json={},
)
db.session.add(unit)
db.session.commit()
monkeypatch.setattr(
'app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file',
lambda _path: b'receipt-bytes',
)
monkeypatch.setattr(
'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes',
lambda **_kwargs: None,
)
def _boom(_fact):
raise RuntimeError('evidence sync exploded')
register_report_handler('inbound', _boom)
payload = {
'schema_version': 'freight_rpa.inbound.v1',
'callback_id': unit.callback_id,
'status': 'success',
'file_path': 'Z:/receipt.xlsx',
'original_filename': 'receipt.xlsx',
'sha256': hashlib.sha256(b'receipt-bytes').hexdigest(),
}
with pytest.raises(RuntimeError, match='evidence sync exploded'):
_inbound_batch_ready_sink(**payload)
db.session.expire_all()
refreshed = db.session.get(ScheduleRun, run.id)
assert refreshed.status == 'success'
assert (refreshed.response_summary_json or {}).get('awaiting_inbound_rpa') is False
assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'success'
def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
"""success 回调在 finalize 前须回写 ScheduleRun 进度计数(对齐 empty/failed)。"""
from app import db
@@ -214,3 +214,20 @@ def test_receipt_worker_defaults_session_reuse_with_scoped_profiles():
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'start_inbound_worker.ps1').read_text(encoding='utf-8')
assert '[switch]$NoSessionReuse' in ps1
assert "FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse" in ps1
def test_receipt_worker_reports_remaining_units_on_batch_open_failure():
"""批级浏览器打开失败须给剩余单元补 failed 回调,禁止只归档 trigger。
[断言意图] 2026-10-20 事故:launch_persistent_context TargetClosed 后 trigger 进
failed/ 但单元无终态回调 → awaiting_rpa/抓取中永挂。契约要求
`_report_group_open_failure` + `reported_callback_ids` 剩余补发。
"""
text = (
Path(__file__).resolve().parents[2]
/ 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py'
).read_text(encoding='utf-8')
assert 'def _report_group_open_failure(' in text
assert 'reported_callback_ids' in text
assert '_report_group_open_failure(remaining, exc)' in text
assert 'open/group failed' in text
@@ -101,6 +101,80 @@ def _awaiting_outbound_unit(*, callback_id: str):
)
def test_outbound_batch_ready_sink_finalizes_schedule_even_if_fact_handler_raises(
tmp_path, app, monkeypatch,
):
"""文件归档单元终态后,事实/证据处理失败仍须收口排程(文件返回= RPA 结束)。
[断言意图] batch-ready sink 在 finally 中 finalize;不得依赖 handle_outbound_report 成功。
"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaOutboundUnitRun
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.rpa_sinks import _outbound_batch_ready_sink
drop = tmp_path / "outbound_drop"
drop.mkdir()
payload_bytes = b"PK\x03\x04fake"
(drop / "foo.xlsx").write_bytes(payload_bytes)
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
task = ScheduleTask(
schedule_no="SCH-OUTBOUND-FILE-FINAL",
name="Outbound file finalize",
schedule_type="platform_job",
platform_api_path="freight-rpa-outbound",
owner_user_id=1,
cron_expr="0 8 * * *",
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no="RUN-OUTBOUND-FILE-FINAL",
schedule_task_id=task.id,
status="running",
total_count=1,
success_count=0,
failed_count=0,
skipped_count=0,
response_summary_json={"awaiting_outbound_rpa": True},
)
db.session.add(run)
db.session.flush()
unit = _awaiting_outbound_unit(callback_id="outbound-file-final-cb")
unit.schedule_run_id = run.id
db.session.add(unit)
db.session.commit()
monkeypatch.setattr(
"app.services.freight_rpa.outbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
def _boom(_fact):
raise RuntimeError("evidence sync exploded")
register_report_handler("outbound", _boom)
payload = {
"schema_version": "freight_rpa.outbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx",
"original_filename": "foo.xlsx",
"sha256": hashlib.sha256(payload_bytes).hexdigest(),
}
with pytest.raises(RuntimeError, match="evidence sync exploded"):
_outbound_batch_ready_sink(**payload)
db.session.expire_all()
refreshed = db.session.get(ScheduleRun, run.id)
assert refreshed.status == "success"
assert (refreshed.response_summary_json or {}).get("awaiting_outbound_rpa") is False
assert db.session.get(FreightRpaOutboundUnitRun, unit.id).status == "success"
def test_ingest_outbound_callback_archives_and_dispatches_fact(tmp_path, app, monkeypatch):
"""success 回调按 Windows 绝对路径只认文件名归档,并投递 report_kind=outbound 事实。"""
from app import db
@@ -146,3 +146,16 @@ def test_outbound_worker_ready_callback_outside_export_retry():
progress_at = text.find("progress_counts['success'] += 1")
ready_at = text.find("_post_unit_ready(unit, output)")
assert progress_at > 0 and ready_at > progress_at
def test_outbound_worker_reports_remaining_units_on_batch_open_failure():
"""批级浏览器打开失败须给剩余单元补 failed 回调——与 inbound/onhand 同契约。
[断言意图] 禁止只归档 trigger 到 failed/ 而不收口单元;须有
`_report_group_open_failure` + `reported_callback_ids` 剩余补发。
"""
text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8")
assert "def _report_group_open_failure(" in text
assert "reported_callback_ids" in text
assert "_report_group_open_failure(remaining, exc)" in text
assert "open/group failed" in text
+77
View File
@@ -187,6 +187,83 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
}
def test_batch_open_browser_failure_records_remaining_sources_as_profile_failed(monkeypatch, tmp_path):
"""批级 launch_persistent_context 失败须为组内全部源记 rpa_profile_failed 并批末回调。
[断言意图] 与 inbound/outbound「剩余单元补 failed」同契约:浏览器未开时不得
静默丢源;须进 results + ONHAND_BATCH_READY,error_code=rpa_profile_failed。
"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
trigger_dir.mkdir()
drop_dir.mkdir()
trigger_path = trigger_dir / "inventory_export_batch_open_fail.json"
sources = [
{
"source_code": code,
"connector_type": "dbs",
"warehouse_id": wh,
"expected_warehouse_id": wh,
"rpa_profile_code": "DBS_AR",
"entry_url": "https://s360.dbschenker.com/",
"task_no": "SN-OPEN-FAIL",
"callback_id": f"PSR-OPEN-FAIL-{wh}:C1",
"source_run_no": f"PSR-OPEN-FAIL-{wh}",
"attempt_no": 1,
"lease_token": f"lease-{wh}",
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
}
for code, wh in (("DSV360_AWSDU", "AWSDU"), ("DSV360_AWSRTM", "AWSRTM"))
]
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": "BATCH-OPEN-FAIL:batch:C1",
"batch_run_no": "BATCH-OPEN-FAIL",
"task_no": "SN-OPEN-FAIL",
"inventory_sources": sources,
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
def _boom(*_args, **_kwargs):
raise RuntimeError("BrowserType.launch_persistent_context: Target page, context or browser has been closed")
monkeypatch.setattr(worker, "_open_browser", _boom)
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
monkeypatch.setattr(worker, "_close_batch_browser_resources", lambda *_a, **_k: None)
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
assert completed["failed_count"] == 2
assert completed["success_count"] == 0
assert len(completed["results"]) == 2
assert {row["source_code"] for row in completed["results"]} == {"DSV360_AWSDU", "DSV360_AWSRTM"}
assert all(row["error_code"] == "rpa_profile_failed" for row in completed["results"])
assert all(row["status"] == "failed" for row in completed["results"])
assert (processed_dir / trigger_path.name).is_file()
def test_onhand_batch_profile_failure_skips_already_recorded_sources_contract():
"""组级补 failed 必须按 recorded_keys 跳过已入 results 的源(禁止二次追加)。
[断言意图] onhand 与 inbound/outbound 同契约:批级失败只收口「剩余」源;
源码须含 recorded_keys / remaining / rpa_profile_failed 门禁。
"""
text = (
_repo_root() / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
).read_text(encoding="utf-8")
assert "recorded_keys" in text
assert "remaining" in text
assert "rpa_profile_failed" in text
assert "open/group failed" in text
assert "尚未写入 results" in text or "not in recorded_keys" in text
def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_path):
"""Crane 动态 Warehouse 在导出前未知时,v2 trigger 不应被身份校验拒绝。"""
worker = _load_freight_rpa_worker()
@@ -0,0 +1,58 @@
"""
backend/tests/test_schedule_run_list_filter.py
用途:断言排程执行记录日期窗包含尚未开始的排队 run。
依赖:query_service.list_runs、ScheduleTask / ScheduleRun、User。
逻辑:工作台默认按今天过滤;started_at 为空时必须以 created_at 落入同一窗口。
"""
from __future__ import annotations
from datetime import datetime, timedelta
def test_list_runs_includes_queued_run_without_started_at(app):
"""排队 run 的 started_at 为空时,仍按 created_at 出现在当天窗口。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.query_service import list_runs
with app.app_context():
owner = User(username='sched-filter', email='sched-filter@example.com', role='admin')
db.session.add(owner)
db.session.flush()
task = ScheduleTask(
schedule_no='SCH-FILTER-QUEUED',
name='filter queued',
owner_user_id=owner.id,
cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
now = datetime.utcnow()
queued = ScheduleRun(
run_no='RUN-FILTER-QUEUED',
schedule_task_id=task.id,
trigger_type='manual',
status='queued',
started_at=None,
created_at=now,
)
stale = ScheduleRun(
run_no='RUN-FILTER-STALE',
schedule_task_id=task.id,
trigger_type='manual',
status='success',
started_at=now - timedelta(days=2),
created_at=now - timedelta(days=2),
)
db.session.add_all([queued, stale])
db.session.commit()
rows = list_runs(
task_id=task.id,
started_after=now - timedelta(hours=1),
started_before=now + timedelta(hours=1),
)
# 断言:当天窗口只含排队中的本轮,不含两天前已开始的记录。
assert [row['run_no'] for row in rows] == ['RUN-FILTER-QUEUED']
@@ -1051,6 +1051,23 @@ def test_export_odm_range_excluding_all_raises_specific_error(app, tmp_path):
generate_shipment_excel(task)
def test_export_unique_hit_odm_bypasses_customer_range(app, tmp_path):
"""唯一命中 ODM 免白名单:Excel 里只有一个 ODM 时直接取用,不拦客户口径漂移。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1'], customer_odm_ids=['ODM-9'],
)
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-1'
finally:
workbook.close()
def test_export_applies_notice_odm_choice(app, tmp_path):
"""整单用户选择优先于多值冲突;选择经 casefold 归一后命中库存行。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
@@ -3,7 +3,7 @@ backend/tests/test_shipping_notice_inventory_schedule.py
用途:货代库存 RPA 排程 executor、defer/finalize 契约与 source 过滤单测。
依赖:ScheduleTask/ScheduleRun、freight_rpa_onhand_job、freight_rpa_onhand_finalize。
逻辑:覆盖 trigger 写入、awaiting 终态、回调 finalize、超时回收。
逻辑:覆盖 trigger 写入、awaiting、HTTP 文件返回即终态、解析 Job 后置入库、超时回收。
"""
from datetime import datetime, timedelta
@@ -30,13 +30,15 @@ from tests.conftest import v2_inventory_batch_payload
@pytest.fixture(autouse=True)
def _freeze_schedule_batch_callback_contract(monkeypatch):
def _freeze_schedule_batch_callback_contract(request, monkeypatch):
"""旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。
排程终态化逻辑已从 HTTP 快速收件(rpa_report_inventory_batch,只入队异步 job)
解耦到同步 process_rpa_report_inventory_batch(由异步 worker job 调用);单测保持
同步断言,因此把旧入口重新指向同步处理函数。
多数旧测把 HTTP 入口同步指到 process 以便断言终态;标注
``real_http_batch_ready`` 的用例要验真实 HTTP「文件返回即终态」,跳过该包装。
"""
if request.node.get_closest_marker("real_http_batch_ready"):
return
from app.services.shipping_notice import onhand_rpa_workflow
import sys
@@ -1013,3 +1015,147 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon
rpa_run_no=run.run_no,
snapshot_status="ready",
).count() == 1
@pytest.mark.real_http_batch_ready
def test_http_batch_ready_finalizes_schedule_on_rpa_file_return(app, tmp_path, monkeypatch):
"""排程点执行:HTTP batch-ready 在文件成功返回时即终态化,不等解析 Job。
[断言意图] RPA 解耦阶段 B 契约——文件返回= RPA/排程结束;解析成败另算。
本测绕过 autouse 同步 process 包装,直接打真实 HTTP 收件入口。
"""
from app.models import FreightRpaOnhandReportFile
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory_batch as http_batch_ready
from tests.conftest import v2_inventory_batch_payload
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "rpa_file_return.xlsx"
_write_sample_inventory(sample, "AWSDU")
enqueued: list[dict] = []
def _fake_enqueue(job_type, payload, **kwargs):
enqueued.append({"job_type": job_type, "payload": payload, **kwargs})
return 99001
monkeypatch.setattr("app.jobs.queue.enqueue", _fake_enqueue)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-HTTP-FINALIZE",
username="schedule_inv_http_finalize_user",
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
run = ScheduleRun(
run_no="RUN20261020110500",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
"display_name": "CVG611",
}],
},
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
before_files = FreightRpaOnhandReportFile.query.count()
result = http_batch_ready(v2_inventory_batch_payload({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"status": "success",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSDU",
success=True,
file_path=str(sample),
warehouse_id="AWSDU",
)],
}))
db.session.refresh(run)
assert result["status"] == "ok"
assert result["data"]["callback_result_status"] == "accepted"
assert result["data"]["job_id"] == 99001
assert result["data"]["schedule_finalize_status"] == "ok"
assert run.status == "success"
assert run.finished_at is not None
assert run.success_count == 1
assert run.failed_count == 0
assert (run.response_summary_json or {}).get("awaiting_rpa") is False
# 解析尚未跑:不得要求已有 onhand 快照行
assert FreightRpaOnhandReportFile.query.count() == before_files
assert len(enqueued) == 1
def test_process_after_rpa_finalize_still_ingests_without_reopening_awaiting(app, tmp_path, monkeypatch):
"""排程已按 RPA 文件返回终态后,解析 Job 仍可入库,且不得把 awaiting_rpa 重新打开。"""
from app.models import FreightRpaOnhandReportFile
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
from tests.conftest import v2_inventory_batch_payload
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "parse_after_finalize.xlsx"
_write_sample_inventory(sample, "AWSDU")
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-PARSE-AFTER",
username="schedule_inv_parse_after_user",
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
)
run = ScheduleRun(
run_no="RUN20261020110501",
schedule_task_id=task.id,
status="success",
started_at=datetime.utcnow(),
finished_at=datetime.utcnow(),
total_count=1,
success_count=1,
failed_count=0,
skipped_count=0,
response_summary_json={
"awaiting_rpa": False,
"schedule_finalize_status": "ok",
"pending_details": [{
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
"display_name": "CVG611",
}],
},
)
db.session.add(run)
db.session.commit()
finished_at = run.finished_at
before = FreightRpaOnhandReportFile.query.filter_by(snapshot_status="ready").count()
result = process_rpa_report_inventory_batch(v2_inventory_batch_payload({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSDU",
success=True,
file_path=str(sample),
warehouse_id="AWSDU",
)],
}))
db.session.refresh(run)
assert result["status"] == "ok"
assert FreightRpaOnhandReportFile.query.filter_by(snapshot_status="ready").count() == before + 1
assert run.status == "success"
assert (run.response_summary_json or {}).get("awaiting_rpa") is False
assert run.finished_at == finished_at
@@ -1136,6 +1136,63 @@ def test_auto_release_runs_after_match_when_part_total_satisfies(app, monkeypatc
assert decision.snapshot_json['release_required_fields'] == []
def test_auto_release_skips_when_hit_odm_multi_valued(app, monkeypatch):
"""命中行 ODM 多值时不得自动放行:放行后导出无法唯一收敛,保持人工路径。"""
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
auto_release_part_fallback_shortages,
)
with app.app_context():
# 同料号两行库存携带不同 ODM 值 → 命中行 ODM 非唯一。
task, case, _odm_field = _seed_auto_release_fixture(app, inventory_rows=[
{'part': 'ODM-001', 'reservation': 'R-INV', 'odm': 'ODM-A'},
{'part': 'ODM-001', 'reservation': 'R-INV', 'odm': 'ODM-B'},
])
_patch_auto_release_side_effects(monkeypatch)
released = auto_release_part_fallback_shortages(task)
# 断言意图:料号总量满足也不放行(多值 ODM 放行后 Excel 必失败)。
assert released == []
assert _active_auto_release_decisions(case) == []
def test_release_and_sufficiency_readers_resolve_via_notice_identity(app):
"""放行/满足性读取按 OT 回链:Notice 对象复评必须与 OT 同判(键位断裂回归)。"""
from app import db
from app.models import ShippingNotice, ShippingOrderReviewLineDecision
from app.services.shipping_notice.fulfillment_workflow import (
_closed_snapshot_line_ids_for_task,
_released_snapshot_line_ids_for_task,
match_completed,
)
with app.app_context():
task, case, _odm_field = _seed_auto_release_fixture(app)
db.session.add(ShippingOrderReviewLineDecision(
review_case_id=int(case.id), draft_line_id='line-1', line_index=0,
decision_code=DECISION_RELEASE_SHORTAGE, decision_source='system',
required_qty='8.0', available_qty='6.0', reservation_id='3000112934',
part_number='ODM-001', snapshot_json={'auto_release': True},
))
db.session.flush()
notice = ShippingNotice(
task_no='SN-KEYSPLIT', source_type='manual',
order_task_id=int(task.id), user_id=int(task.user_id),
)
db.session.add(notice)
db.session.flush()
# 断言意图:以 Notice 身份读取放行/满足性事实与 OT 完全同判,
# Excel 生成链换绑 Notice 后不再丢放行事实(回归 OT-20261017-364C7BF2)。
assert _released_snapshot_line_ids_for_task(notice) == _released_snapshot_line_ids_for_task(task)
assert _released_snapshot_line_ids_for_task(notice)
assert _closed_snapshot_line_ids_for_task(notice) == set()
assert match_completed(task) is True
assert match_completed(notice) is True
def test_auto_release_skips_when_part_total_below_required(app, monkeypatch):
"""料号兜底量不足时不得自动放行,行保持人工待处置。"""
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
+1 -1
View File
@@ -252,7 +252,7 @@
### 3.x 货代发货通知库存源补充需求
- **核心目标**:在订单解析阶段即确定库存查询来源(`source_code`),避免 RPA 抓错库存池;用户仅需确认来源编码,站点与仓库由系统配置生成。
- **自动匹配**:根据发货通知目的地/港口/仓库线索与 `freight_rpa_sources.yaml` 规则自动 adjudicate;唯一命中则 `resolved` 并继续流程。
- **自动匹配**:根据发货通知目的地/港口/仓库线索与数据库库存源配置(`freight_rpa_sources` 表,管理端维护)自动 adjudicate;唯一命中则 `resolved` 并继续流程。
- **人工确认**:无法唯一命中时进入 `inventory_source_review` 检查点,用户在聊天区选择或输入线索确认 `source_code`。
- **硬阻断**:库存源未稳定(`resolved` / `user_confirmed`)时,RPA、库存匹配、Excel 生成、货代上传均不得执行。
- **身份校验**:关联库存快照时校验 `source_code`、`site_id`、`warehouse_id` 与任务一致。
@@ -21,7 +21,7 @@ _Avoid_: 海外仓
_Avoid_: 入库单、ASN
**出站登记 (Outbound Registration)**:
外部系统记录货物从 HUB 仓出库的登记记录(维修出、HUB 间调拨出的数据来源;出站 RPA 尚未建设)。
外部系统记录货物从 HUB 仓出库的登记记录;维修出、HUB 间调拨出的数据来源。
_Avoid_: 出库单、出货登记
**库存异动档 (Movement Ledger)**:
@@ -67,9 +67,13 @@ _Avoid_: 单据类型
已发布解析规则的适用文件种类枚举:`onhand`=库存文件、`inbound`=入站文件、`outbound`=出站文件;收料配置(入站证据绑定)只能绑定 `inbound` 规则。
_Avoid_: 库存/异动两值旧枚举(inventory/movement)
**出入站来源实例 (Inbound Source Instance)**:
一个外部系统的入站数据抓取通道(如 DSV360_AWSBI_BYAWSCMH01),调拨按来源实例为执行边界;本身也是范围规则可用的字段之一。入站证据=收料报表产物(shipping_notice 域收料 RPA 抓取,该域术语保留)。
_Avoid_: 数据源、站点
**出入站来源实例 (Source Instance)**:
一个外部系统站点通道(如 DSV360_AWSBI_BYAWSCMH01),调拨按它划分执行边界;同一通道可挂多条证据流。本身也是范围规则可用的字段之一。
_Avoid_: 数据源、站点、Inbound Source Instance
**证据流 (Evidence Stream)**:
一个出入站来源实例上、按记录类型分开的一条抓取与文件状态。同一来源实例可同时有入站证据流和出站证据流。
_Avoid_: 来源状态、部分就绪
**收料 RPA (Receipt RPA · 旧名保留)**:
入站证据抓取链路的**实现载体**:在途调拨的入站抓取复用货代 shipping_notice 域的 ShippingReceiptReport RPA,故该域内的数据表名(`shipping_receipt_report_*`)、RPA 契约(`shipping_receipt_rpa.v1` / `receipt_export_batch`)、目录(`freight_rpa/receipt/`)与环境变量(`FREIGHT_RPA_RECEIPT_*`)保留「收料/receipt」旧名,默认不改(与运行期收敛口径一致;如后续确需更名须单独立项评估)。它与在途调拨域所说的「入站(链路/文件/抓取)」是**同一条物理链路**——域内业务说辞(代码、API、前端文案)一律用「入站」,读代码遇到 receipt 旧名时按本条映射理解。
@@ -37,7 +37,7 @@
以下任一前置条件失败,测试必须证明 ERP 写入调用次数为 `0`:
- 异动日期晚于业务日期(未来日期无账可核;【成熟规则已退役 2026-10-16】当天/昨天数据正常进匹配,日期边界由调用方入参给定)。
- 异动日期晚于 T−2 可匹配截止日(【T−2 成熟封顶 2026-10-21】T−2 之前数据全部成熟:T−1/当天/未来不进圈档、范围入参截止 >T−2 拒绝;2026-10-16 的「当天/昨天正常进匹配」语义随之收回)。
- 入站文件缺失、过期、checksum变化或结构漂移。
- Invoice字段冲突或一张Invoice跨多个料号/日期。
- ERP账面库存与入站数量不完全相等。
@@ -85,7 +85,7 @@ backend/tests/services/in_transit_transfer/assertions.py
| `fixed_clock` | 默认 `2026-08-06 09:00:00+08:00`,可推进到下一业务日 |
| `dbs_ready_file` | 当日ready入站全量文件,含重复Invoice多行 |
| `crane_ready_file` | 当日ready入站全量文件,支持HTTP Callback完成 |
| `same_day_inbound_file` | 含业务日期当天异动文件(成熟规则已退役:当天数据正常进匹配) |
| `same_day_inbound_file` | 含业务日期当天异动文件(T−2 成熟封顶 2026-10-21:当天未成熟不进匹配,用于锁定圈档封顶) |
| `erp_fake` | 查询账面库存;写接口原子新建/审核/过账;重复Invoice返回原单号 |
| `erp_timeout_fake` | 查询或写入超时,分别可配置已落单/未落单 |
| `rpa_fake` | 领取、Callback、失败、重复Callback、错误来源Callback |
@@ -162,12 +162,14 @@ timeout(after_commit=true, replay_query_unsupported=true)
测试文件:`backend/tests/services/in_transit_transfer/test_date_policy.py`
【成熟规则已退役 2026-10-16】T+lag 策略用例删除;保留日期解析/时区纯单元用例,
范围校验(截止≤业务日期)由 matching_service 用例覆盖:
【T−2 成熟封顶 2026-10-21】T+lag 成熟策略不恢复(无行级成熟状态),但圈档/
范围按 T−2 简化边界卡控;日期解析/时区纯单元用例保留,范围校验(截止≤T−2)
与圈档封顶由 matching_service 用例覆盖:
1. 当天/昨天异动正常进入匹配(无日期前置过滤)。
2. 未来日期返回结构化阻断错误。
3. “今天可调拨”过滤成功项和`manually_closed`项。
1. ≤T−2 异动正常进入匹配(成熟边界内无日期过滤)。
2. T−1/当天异动不进圈档(留在档内待成熟,不出生 item、不查外部系统)。
3. 范围截止晚于 T−2 返回结构化阻断错误(`MOVEMENT_DATE_RANGE_INVALID`)。
4. “今天可调拨”过滤成功项和`manually_closed`项。
5. Asia/Shanghai跨UTC午夜时业务日期不漂移。
### 5.2 文件字段和Invoice汇总
@@ -323,7 +325,7 @@ frontend/src/features/chat/composables/useChatTransfer.spec.ts
必须验证:
- 文件准备卡逐来源显示DBS/Crane阶段,不伪造总百分比。
- 当天异动正常展示匹配结果(成熟规则已退役,无未成熟态)。
- 成熟(≤T−2)异动正常展示匹配结果;未成熟行不进圈档(T−2 成熟封顶 2026-10-21,无行级未成熟态)。
- 预检卡展示可执行数、阻断数、预计调拨总数量和预计ERP写入数。
- 阻断项checkbox禁用,用户不能编辑数量、仓库或ERP组织。
- 确认卡显示10分钟倒计时和失效原因。
@@ -420,7 +422,7 @@ frontend/src/features/admin/modules/in-transit-transfer/TransferAuditPage.spec.t
```text
成功ERP单据数 <= 可执行Invoice数
ERP写入数量 = success数量 + duplicate_success数量
blocked / result_unknown 不得产生ERP写调用(not_matured 已随成熟规则退役)
blocked / result_unknown 不得产生ERP写调用(无行级 not_matured 状态;未成熟行在圈档入口已被 T−2 封顶排除)
manual_close后不得再次生成Attempt
每次Attempt只能有一个终态
每个Invoice在同一ERP组织内最多一个成功单号
@@ -62,10 +62,10 @@
- 按来源实例分组、路由或指定 Invoice 查询;DBS、Crane 仅为当前已配置的来源分组示例。
- 检查当前业务日期的最新 `ready` 入站文件。
- 文件缺失时实时触发 RPA,并在对话中持续展示进度。
- 【已退役 2026-10-16】T+lag 成熟规则不再实施(用户裁定:数据无成熟属性);日期边界由调用方入参严格给定(交互=用户选择范围;自动排程=任务 T−N 偏移参数),引擎只校验截止≤业务日期与未来日期阻断。
- 【T−2 成熟封顶 2026-10-21 修订】T+lag 成熟规则不恢复(无行级成熟状态),但按业务口径落简化成熟边界:T−2 之前的数据全部成熟,匹配圈档只圈 `movement_date ≤ T−2`(`date_policy.eligible_movement_date_to`),未成熟行(T−1/当天)留档待成熟;异动日期范围入参截止 ≤T−2(`MOVEMENT_DATE_RANGE_INVALID`),前端选择器默认=上限=T−2。(2026-10-16 曾整体退役成熟规则并放开到截止≤业务日期,本次按「不成熟数据不匹配」收回边界。)
- 相同 Invoice 多行汇总入站数量。
- 按 Invoice No 查询 ERP 账面库存。
- 生成可执行、阻断和预计调拨数量(未成熟态已随成熟规则退役)。
- 生成可执行、阻断和预计调拨数量(无行级未成熟态;未成熟行在圈档入口被 T−2 封顶排除)。
- 用户选择全部或部分可执行 Invoice。
- 10 分钟确认卡。
- 后台逐张调用 ERP 原子新建、审核、过账接口。
@@ -97,7 +97,9 @@
> 【2026-10-16 修订】本节 T+lag 成熟规则已整体退役(概念删除,`TRANSFER_INBOUND_NOT_MATURED`/
> `not_matured` 状态/`IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS` 一并退役,未上线不设兼容层)。
> 日期边界改为完全由调用方入参给定;以下原文仅作历史设计记录。
> 【2026-10-21 再修订】按「T−2 之前数据全部成熟」落简化成熟边界:圈档只圈
> `movement_date ≤ T−2`、范围截止 ≤T−2、选择器默认=上限=T−2(无行级成熟状态,
> 不恢复本节 T+lag 逐行标记语义);以下原文仅作历史设计记录。
- 业务时区固定为 `Asia/Shanghai`。
- 当前业务日期为 `T`。
@@ -16,7 +16,7 @@
## 2. 数据库
- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`);后续 `it2c3d4e5f6a7_add_in_transit_warehouse_code.py` 为 `transfer_invoice_items` 追加 `movement_warehouse_code`(入站仓库匹配键,2026-10-15 随明细列更名);`tt3d4e5f6a7b_add_transfer_runs_transfer_type.py` 为 `transfer_runs` 追加 `transfer_type`(调拨业务类型,带检查约束);`rn1a2b3c4d5e6_rename_transfer_precheck_to_match.py`(down_revision=`43a8179cdd88`)为术语重构迁移——表 `transfer_prechecks`→`transfer_matchings`、列 `precheck_no/precheck_hash/precheck_id`→`matching_no/matching_hash/matching_id`、状态值 `prechecking`→`matching`(13 状态中仅此一个更名)、约束/索引同步改名,未上线直改无兼容层;2026-10-15 改版迁移 `tt14a5f6a7b8c9_inbound_rename_and_ledger_key.py`(明细/单据列更名 `movement_*`、`record_kind` 值迁移 inbound/outbound、异动档自然键扩为 8 成分)与 `tt15b6a7b8c9d0_parsing_purpose_onhand_inbound_outbound.py`(解析规则 purpose CHECK 重建为 onhand/inbound/outbound + 值迁移),均带 downgrade(见 §12)。
- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`);后续 `it2c3d4e5f6a7_add_in_transit_warehouse_code.py` 为 `transfer_invoice_items` 追加 `movement_warehouse_code`(入站仓库匹配键,2026-10-15 随明细列更名);`tt3d4e5f6a7b_add_transfer_runs_transfer_type.py` 为 `transfer_runs` 追加 `transfer_type`(调拨业务类型,带检查约束);`rn1a2b3c4d5e6_rename_transfer_precheck_to_match.py`(down_revision=`43a8179cdd88`)为术语重构迁移——表 `transfer_prechecks`→`transfer_matchings`、列 `precheck_no/precheck_hash/precheck_id`→`matching_no/matching_hash/matching_id`、状态值 `prechecking`→`matching`(13 状态中仅此一个更名)、约束/索引同步改名,未上线直改无兼容层;2026-10-15 改版迁移 `tt14a5f6a7b8c9_inbound_rename_and_ledger_key.py`(明细/单据列更名 `movement_*`、`record_kind` 值迁移 inbound/outbound、异动档自然键扩为 8 成分)与 `tt15b6a7b8c9d0_parsing_purpose_onhand_inbound_outbound.py`(解析规则 purpose CHECK 重建为 onhand/inbound/outbound + 值迁移);2026-10-21 迁移 `tt21c8d9e0f1a2_ledger_external_doc_line_natural_key.py`(异动档新增外部单号/外部项次两列并入自然键,约束 8→10 成分),均带 downgrade(见 §12)。
- 部署:`cd backend && flask db upgrade`(PostgreSQL)。回滚:`flask db downgrade <上一revision>`。
- 表:transfer_runs / transfer_source_jobs / transfer_matchings / transfer_invoice_items / transfer_attempts / transfer_audit_events / transfer_archives。
- 审计表只追加(ORM 门禁 + 前端禁止删除);大对象归档 MinIO(transfer_archives 记录 provider/bucket/key/sha256)。
@@ -68,6 +68,7 @@
| GET | `/metrics` | 调拨运营指标(成功率/失败类型/待处理老化/通知失败) |
| GET | `/sources` | 来源实例列表(附入站文件状态 ready/parse_failed/fetching/failed/expired/none + has_ready_file,供前端门禁;2026-09-29 起 `parse_failed`=当日文件在但 movement 解析失败(`has_ready_file=false`),路由失败仅行内 `blocked_route_not_resolved`、不抬升来源顶栏) |
| POST | `/sources/{source_code}/retry-rpa` | 来源入站重试(2026-09-29 起分层:parse_failed 且有当日可用文件时优先本地重解析——成功 ready / 仍失败 parse_failed,200 `reparsed=true`,不触发 RPA;否则原样重新触发一次收料 RPA 抓取,202+fetching,配置缺失 fail-closed ok=False) |
| POST | `/sources/{source_code}/reparse` | 重解析当前最新可用归档(body `record_kind`,缺省 inbound;不接受 file_id;不触发 RPA)。成功 200,`ok/file_status/file_id/inserted/updated/skipped/sealed_skipped`。无文件 422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。无已发布规则 422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`,不标 parse_failed。结构失败 200 `ok: false` 且文件为 `parse_failed`。其他异常 200 `ok: false`,不标 parse_failed。与待匹配 `POST /backlog/pending-match/reparse` 不是同一条链路。 |
| POST | `/sources/retry-rpa-batch` | 批量来源入站重试(body `source_codes`;2026-10-09 起多来源合并写**一个** batch trigger 文件——Worker 单次浏览器会话按 profile 分组串行导出,替代逐来源 N 个 trigger/N 次开浏览器;逐来源分层与 fail-closed 语义同单来源端点,单源配置缺失跳过并记录不阻断整批,响应 `triggered`+逐源 `results`) |
| GET | `/backlog` | 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级;查看留审计) |
| GET | `/backlog/summary` | 待处理异常汇总(含 3/5/7 天老化分级) |
@@ -149,7 +150,7 @@ cd backend && flask db upgrade
**账面轴(待办行 → ERP 库存核对)**
- 匹配 = 证据对齐 → 未来日期阻断/路由分组 → **按组织批量查库存**(`query_inventory` 能力)→ 严格数量比对落位;文件解析已上移证据轴,匹配不再解析入站文件。(成熟规则已退役 2026-10-16:日期边界由调用方入参给定)
- 匹配 = 证据对齐 → 未来日期阻断/路由分组 → **按组织批量查库存**(`query_inventory` 能力)→ 严格数量比对落位;文件解析已上移证据轴,匹配不再解析入站文件。【T−2 成熟封顶 2026-10-21】T−2 之前的数据全部成熟(简化成熟边界,不回退 2026-10-16 退役决策、无成熟行级状态):匹配圈档只圈 `movement_date ≤ T−2`(`date_policy.eligible_movement_date_to`),T−1/当天未成熟行留在档内待成熟后自然进圈;异动日期范围入参截止同样不得晚于 T−2(`TRANSFER.MOVEMENT_DATE_RANGE_INVALID`),与前端选择器上限(默认=上限=T−2)同口径。
- **worker 写前库存复查 `_recheck_stock_for_document`**(TTL 门禁退役后的写前安全最后防线):`create_transfer` 前按组织批量重查一次账面,按「入站数量 == 账面」严格相等再裁——查无 → `blocked_inventory_not_found`(账面按 0 留痕)、数量不等 → `blocked_quantity_mismatch`,均携带最新账面数量原位落行并移出本单(fail-closed 不写 ERP;全行漂移 → 单 `business_failed/stock_drifted`)。**仅全量重跑路径执行**:final_only/result_unknown 续跑单不复查——单可能已在 ERP 建成、只触发末步,此时任何阻断都是假失败。复查自身查询失败不新造失败模式(行原样放行,交给写路径既有错误语义兜底)。
- **「库存数据已过期」为纯展示提示**:`IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` 降为 stale 徽标判定阈值(默认 600s),超时行仅亮「库存数据已过期,请重查」徽标引导重查,不拦截任何动作。
@@ -361,7 +362,7 @@ cd backend && flask db upgrade
- **规则模型**:`{field, match, values[]}`,`match ∈ {prefix, equals, contains, in}`;**规则间 AND、规则内多值 OR**;空规则=不限(管理页默认要求至少一条,显式确认才可豁免)。
- **字段白名单(18 字段,封闭可扩展)**:`source_code, doc_no, warehouse_code, storage_code, lot_no, movement_date, record_kind, in_out_flag, order_type, odm_id, odm_name, carton_id, pallet_id, material_code, doc_nature, movement_type, reason_code, partner_code`。
- **双形态求值(同一编译器,杜绝谓词漂移)**:内存谓词 `evaluate_scope`(测试/小数据)+ SQL 编译 `apply_scope_filters`(prefix→`UPPER(col) LIKE 'X%'`;equals→集合等值 upper.in_;contains/in 同理)。匹配创建圈档与重查对账共用。
- **圈定固定条件**:`record_kind='inbound'`(一期,2026-10-15 起枚举值为 inbound/outbound)+ `source_code IN (所选来源)` + `movement_date BETWEEN 异动日期范围` + 未封存(`transfer_executed=false`)+ 未被有效 items 占用(D17,§11.6)。
- **圈定固定条件**:`record_kind ∈ record_kinds_of(类型范围规则)`(无 `record_kind` 规则时入站与出站都圈;2026-10-15 起枚举值为 inbound/outbound)+ `source_code IN (所选来源)` + `movement_date BETWEEN 异动日期范围` + 未封存(`transfer_executed=false`)+ 未被有效 items 占用(D17,§11.6)。
- **快照**:范围规则 + 转换规则 + 类型/来源/日期序列化进 `scope_json` 参与匹配 hash;hash 一律从快照内容计算。
### 11.3 仓库定义与路由(`warehouse_config_json`)
@@ -376,7 +377,7 @@ cd backend && flask db upgrade
### 11.5 库存异动档(`transfer_movement_ledger`,迁移 `tt11b2c3d4e5f`)
- **自然键唯一索引**:`(source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no)`——2026-10-15 由 6 成分扩为 **8 成分**(追加箱号 `carton_id`、批号 `lot_no`;迁移 `tt14a5f6a7b8c9` 重建 `uq_transfer_movement_ledger_natural_key`),真实文件行身份「单据+行+箱/批」不再塌缩(三份实测文件扩键后塌缩归零,`ledger_natural_key_collapse` 审计退化为纯保险);可空成分 NOT NULL + default ''(防 PG NULL 逃逸)。字段组:单据标识 / 物料与数量 / 仓储与日期 / 业务属性(D13 新增 `order_type/odm_id/odm_name/carton_id/pallet_id` + 出站预留列 `doc_nature/movement_type/reason_code/source_ref_no/partner_code/remark`)/ 平台溯源(`source_file_id` FK ON DELETE SET NULL——文件清理后档记录必须留存)/ 平台回写。
- **自然键唯一索引**:`(source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no, external_doc_no, external_line_no)`——2026-10-15 由 6 成分扩为 8 成分(追加箱号 `carton_id`、批号 `lot_no`;迁移 `tt14a5f6a7b8c9` 重建 `uq_transfer_movement_ledger_natural_key`),真实文件行身份「单据+行+箱/批」不再塌缩(三份实测文件扩键后塌缩归零,`ledger_natural_key_collapse` 审计退化为纯保险);2026-10-21 再扩为 **10 成分**(追加外部单号 `external_doc_no`、外部项次 `external_line_no`,对应 CRANE/Lognet 出站报告 WMS Order #/行号;迁移 `tt21c8d9e0f1a2` 重建约束)——外部单据身份作为档幂等主键管控,同一外部单号+项次的重复落档/证据更新收敛到同一档行;可空成分 NOT NULL + default ''(防 PG NULL 逃逸)。字段组:单据标识 / 外部单据身份 / 物料与数量 / 仓储与日期 / 业务属性(D13 新增 `order_type/odm_id/odm_name/carton_id/pallet_id` + 出站预留列 `doc_nature/movement_type/reason_code/source_ref_no/partner_code/remark`)/ 平台溯源(`source_file_id` FK ON DELETE SET NULL——文件清理后档记录必须留存)/ 平台回写。配套口径:movement 契约字段目录扩至 20 字段(追加 `external_doc_no/external_line_no`,解析 Profile 可映射、缺列放行空值入键);解析层料号空行静默跳过(不管控、不进异动表,2026-10-21 CRANE/Lognet 出站报告说明行实测)。
- **落地幂等五语义**(`evidence_sync` 一次解析、写档不写明细):①自然键不存在→插入 ②同文件 sha 未变→幂等跳过 ③证据变化→原行更新业务镜像列+换溯源 ④文件缺席→保留不删(收料 RPA 非全量导出,缺席≠删除)⑤已执行封存行(`transfer_executed=true`)永不更新永不复活。
- **record_kind 声明 + 交叉校验(D14)**:`record_kind` 由文件种类声明写入(权威),与数据列 `in_out_flag` 交叉校验,矛盾即解析错位——打审计事件 `ledger_cross_check_failed`,记录照常落档。
- **`movement_date` 非空才落档(2026-10-15 起,D1)**:`ledger_sync` 行级前置过滤——异动日期为空的行计入 `date_skipped` 分类、不落档(无异动日期 = 未发生异动;入站未完成行、出站 Cancelled/Executing 行自动排除);圈档/待匹配桶的日期条件恒排除 NULL(纵深防御)。
@@ -389,7 +390,7 @@ cd backend && flask db upgrade
### 11.7 首页待办看板「待匹配」桶(D16)
- 四队列卡数据源改为**档 + 最近执行状态联查**(启用类型范围并集圈档,左联 items 取最近评估状态)。新增「待匹配」桶:**已落档但尚无有效 items**(从未被匹配圈中)的外部记录在此可见——点击展开只读清单 + 「去匹配」引导;**不可勾选执行**(未做库存核对)。数字时机:入站落地→涨;点匹配→圈中记录离开;匹配后文件新增记录→再涨。
- 四队列卡数据源改为**档 + 最近执行状态联查**。新增「待匹配」桶:**已落档但尚无有效 items**(从未被匹配圈中)的外部记录在此可见——点击展开只读清单;**不可勾选执行**(未做库存核对)。【2026-10-21 首页拆数】待匹配计数与清单不再按调拨类型范围收窄:固定条件仍是未封存、异动日期非空、未被占用、movement_date ≤ T−2,出入站都收。启用类型范围并集改记为 `matchable_count`,显示在「匹配可调拨库存」卡上。清单上段是这段并集,带「去匹配」;下段是其余已落档,只读。选类型建匹配时仍只圈该类型罩得住的行。数字时机:文件落地→待匹配涨;点匹配→圈中记录离开;停用类型只减少可匹配数。
### 11.8 `file_current` 门禁改锚
@@ -35,7 +35,7 @@ query_parameters_json # 参数名、single/multi_text/multi_select、values、
业务管理员维护路径和参数值;订单到库存站点的选择统一在版本化路由规则中维护。RPA Driver 模板维护 `selector_env`、CSS selector、下载模式、控件等待策略等技术细节。上述技术字段和第二套路由别名不得写入库存源。DBS 参数必须支持单选、文本多值和列表多选。Crane 当前导出完整多仓库存文件,不维护 Crane Warehouse 清单。
`backend/config/freight_rpa_sources.yaml` 保留为**期初导入参考**,直到数据库导入、校验和试跑完成前不得删除;它不再是运行时读取源。导入时将旧 `dsv360` / `crane_footprint` 归一为 `dbs` / `crane`,映射报表路径、参数和别名,并丢弃 `site_id`。导入完成后,RPA 运行时只读取数据库。
期初导入参考 `backend/config/freight_rpa_sources.yaml` 及配套导入脚本 `backend/scripts/import_freight_rpa_sources.py` 已于 2026-10-20 删除(数据库导入、校验和试跑早已完成):库存源唯一真相是数据库 `freight_rpa_sources`,新增/修改一律走管理端,运行时只读数据库。历史 YAML 内容可在 Git 历史中查阅(删除前提交 39fe3c05f 附近)。
### 固定 Warehouse
+9 -4
View File
@@ -3156,6 +3156,8 @@ Ubuntu:/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop
Crane 出站固定 **Outbound Details**;DBS 路径/查询与入站同构(日期不得出现在查询条件)。回调 `file_path` **只认 drop 根内文件名**(跨机 Windows 绝对路径须在后端取 `.name` 再拼 `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR`)。
**Crane 导航整页刷新禁令(2026-10-20)**:Crane 门户登录态不随整页加载恢复(人工实测:登录后点浏览器刷新即掉登录),登录态下 `goto` 根地址 / `reload` 等于强制登出。`crane_navigation.navigate_to_crane_report` 的首页卡片/Queries 菜单目标由 `entry_url` 推导(On Hand / Inbound / Outbound Details 通用,禁止再硬编码 On Hand);direct goto 后先轮询表单就绪(SPA 换页有渲染间隙,瞬时判定会误判失败),兜底只允许就地 `window.location.hash` 赋值;`crane_report_export._refresh_scheduled_reports_list` 的 `reload` 兜底已替换为就地重赋 hash。出站死循环(登录→on-hand→整页刷新→登出反复)即由「导航硬编码 On Hand + goto 后瞬时判定失败即 goto 根地址」叠加触发。
#### 1.10.2 Windows:部署出站 Worker
目录初始化(与入站并列,不共用 trigger/drop/logs):
@@ -3946,14 +3948,17 @@ inventory_preparation Gate
## 客户数据 ODM ID 范围与整单 ODM 裁决(2026-09)
- 「客户主数据」页面与文案统一更名为「客户数据」;`ShippingCustomer` 新增可空 `odm_ids`(JSON 字符串清单),由客户数据页维护(每行一个,留空表示不限定)。
- 生成发货 Excel 的整单 ODM 裁决(模板 Header 消费 `odm_id` 字段时生效,`export._adjudicate_notice_odm`):
1. 客户 `odm_ids` 非空 → 先全局过滤库存命中行,仅保留范围内的 ODM;把原有命中全部排除时报「订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内」。
2. 用户选择(`shipping_notice_line_onhand_matches.chosen_odm_id`,task 全部 `is_current` 行统一值)→ 过滤为所选 ODM;在当前库存中不存在时报「已选择的 ODM ID 在当前库存中不存在」。
3. 无范围、无选择且各行命中 ODM 交集唯一 → 自动收敛到唯一可行值;交集多个 → 维持折叠冲突阻断,由工作台下发候选。
- 生成发货 Excel 的整单 ODM 裁决(模板 Header 消费 `odm_id` 字段时生效,`export._adjudicate_notice_odm`;2026-10-20 白名单降级):
1. 各行命中 ODM 交集恰一个值(唯一可行解)→ **直接收敛到该值,跳过客户 `odm_ids` 白名单**——客户主数据与库存文件口径漂移不拦「Excel 里只有一个 ODM」的确定事实(回归 OT-20261017-184D440D)。
2. 交集多个且客户 `odm_ids` 非空 → 先全局过滤库存命中行,仅保留范围内的 ODM;把原有命中全部排除时报「订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内」。
3. 用户选择(`shipping_notice_line_onhand_matches.chosen_odm_id`,task 全部 `is_current` 行统一值)→ 过滤为所选 ODM;在当前库存中不存在时报「已选择的 ODM ID 在当前库存中不存在」。
4. 多值、无范围、无选择 → 维持折叠冲突阻断,由工作台下发候选。
- 工作台「通知准备」面板为**行内 ODM 下拉**(任一行候选多于一个且未生成 Excel 时展示列):候选为该行经客户范围过滤后的命中值(保留原大小写);确认后 `POST /shipping-tasks/<task_no>/odm-choice`(body: `snapshot_line_id` + `odm_id`)落库并自动重试 `regenerate_excel_artifact`。
- **同快照文件同步**:选择按 `onhand_snapshot_id` 圈同步——改任一行,同一快照文件的全部 `is_current` 匹配行写同一 `chosen_odm_id`(前后端同步:后端落库即同步,前端刷新后各行回显同一值);校验取同步范围内各行候选的交集,保证选择不会把其他行变成无匹配。
- 选择不落 Notice/OT:Notice 在生成失败事务中会回滚,行级匹配事实表才是导出读取库存源/文件的既有事实源;重匹配产生新匹配轮次后旧选择自然失效。Header 契约是整单一个值,若业务需要不同行走不同 ODM(跨快照文件),应拆分通知单。
- 迁移:`aa11bb22cc33_customer_odm_scope`(`shipping_customers.odm_ids` + `shipping_notice_line_onhand_matches.chosen_odm_id`,均幂等守卫)。
- **料号兜底自动放行的 ODM 唯一前置(2026-10-20)**:`order_review_fulfillment_decision_service.auto_release_part_fallback_shortages` 在「料号总量≥需求」之外,还要求预约+料号命中行(0 命中时回退料号命中行)的 ODM ID 唯一,否则保持人工路径——保证放行后导出可收敛;ODM 字段目录停用时不设前置。
- **放行/满足性读取按 OT 回链(2026-10-20)**:匹配事实与复核 Case 的 `confirmed_task_id` 都按 OT 主键落库;Excel 生成链物化正式 Notice 后以 Notice 对象复评 `match_completed` / 放行 / 结案 / 库存准备失败读取时,统一经 `fulfillment_workflow._facts_order_task` 回链 OT,导出侧放行读取 join `owner.id`(回归 OT-20261017-364C7BF2:已自动放行的短缺单在 Notice 身份下被误判「尚未完成库存匹配」)。
## 订单队列五态图标与 needs_attention(2026-09)
+7 -5
View File
@@ -193,7 +193,7 @@
| 人工复核与字段证据闭环(阶段 5) | 已实现 | 单头、订单行、冲突解决均要求乐观锁、原因和结构化 `document_cell`/`manual_input` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 |
| 原 PDF 双层重解析 | 已实现 | “重新识别此 PDF”仅为当前原始文件创建后继 Run;“重新解析本批次”逐 PDF 创建独立子 Run、局部成功替换,按完整 Run 谱系选择每个原文件的当前 Case;已确认/履约文件排除;不支持上传替代 PDF。 |
| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 |
| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/freight_rpa_sources.yaml`,新增 Warehouse 只改 YAML |
| 库存 RPA 源配置 | 已实现 | 源、报表路径与查询参数维护在数据库 `freight_rpa_sources`(管理端货代 RPA 页);期初 YAML 已于 2026-10-20 删除,运行时只读数据库 |
| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` |
| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings |
| 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 |
@@ -806,21 +806,23 @@
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | backend/app/models/in_transit_transfer.py(Run/SourceJob/Matching/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e / rn1a2b3c4d5e6(precheck→match 术语改名);13 状态服务端门禁(services/in_transit_transfer/status.py) |
| 入站文件准备与只读匹配(原"预检") | 后端已实现 | 入站文件落地即同步库存异动档(2026-10-14 出生翻转:RPA 回调桥 → evidence_sync 一次解析写档不写明细,自然键幂等五分类——插入/sha 幂等跳过/证据变原行更新/缺席存续/已执行封存);匹配=从档圈定建行 + 按组织批量查库存 + 严格数量比对;缺文件按来源触发收料 RPA/来源隔离/字段校验/未来日期阻断(成熟规则已退役 2026-10-16,日期边界由调用方入参给定)/Invoice 多行汇总+原始行追溯/匹配快照 Hash/进度恢复 |
| 入站文件准备与只读匹配(原"预检") | 后端已实现 | 入站文件落地即同步库存异动档(2026-10-14 出生翻转:RPA 回调桥 → evidence_sync 一次解析写档不写明细,自然键幂等五分类——插入/sha 幂等跳过/证据变原行更新/缺席存续/已执行封存);匹配=从档圈定建行 + 按组织批量查库存 + 严格数量比对;缺文件按来源触发收料 RPA/来源隔离/字段校验/T−2 成熟封顶(2026-10-21:T−2 之前数据全部成熟,圈档只圈 movement_date≤T−2,未成熟行留档待成熟;范围入参截止>T−2 拒绝)/Invoice 多行汇总+原始行追溯/匹配快照 Hash/进度恢复 |
| 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行提交执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按票聚合结果(写路径已接线,见下行「ERP 建单写路径」) |
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 入站文件与 09:00 自动调拨(现注册表单列 `in-transit-transfer` platform job,缺当日入站文件自动触发收料 RPA);任务参数=来源实例/历史可恢复异常复核/可选异动日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部积压;非法偏移快速失败,越界由匹配层卡控截止≤业务日期);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) |
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 入站文件与 09:00 自动调拨(现注册表单列 `in-transit-transfer` platform job,缺当日入站文件自动触发收料 RPA);任务参数=来源实例/历史可恢复异常复核/可选异动日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部成熟积压;非法偏移快速失败,偏移终点落在 T−1/当天或更晚由匹配层卡控截止≤T−2);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) |
| 调拨类型配置化(2026-10-14) | 已实现 | 类型来自平台配置表 `transfer_type_configs`(ADR 0002,代码枚举/CHECK 约束/前端 union/「即将上线」占位全退役):管理端「在途调拨类型」页四块配置(基本信息/范围规则/仓库定义/字段转换),admin CRUD API + chat enabled 最小暴露 API;`transfer_type` 匹配创建必填(未配置/停用 fail-closed),配置为空前端空态;范围规则引擎(18 字段白名单、规则间 AND 值间 OR、内存谓词+SQL 编译双形态)、仓库定义(mapped/fixed+法人覆盖)、字段转换(批号前缀替换,六个系统边界生效,行/档保原值);规则随匹配快照进 scope_json;管理页见 `features/admin/modules/transfer-types/`,运维手册 technical.md §11 |
| 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放) |
| 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放);2026-10-21 外部单据身份扩维:自然键 8→10 成分(+外部单号/外部项次=WMS Order #/行号,迁移 tt21c8d9e0f1a2)作档幂等主键管控,movement 契约字段目录扩至 20 字段(解析 Profile 可映射),解析层料号空行静默跳过(不管控、不进异动表) |
| 入站/出站统一改版与幂等修复(2026-10-15) | 已实现 | record_kind 枚举值改版 inbound/outbound(迁移 tt14 值迁移);明细/单据列异动口径 `movement_*`(异动日期/数量/仓库列与匹配创建参数 `movement_date_from/to`、序列化键、Excel 表头随行更名,无兼容层);异动档自然键扩为 8 成分(+箱号/批号,三份真实 WMS 文件实测塌缩归零)+「异动日期非空才落档」过滤(`date_skipped`,未完成/已取消行不入档);解析规则 purpose 三枚举 onhand/inbound/outbound(迁移 tt15 值迁移);入站配置绑定校验 inbound 专用(`SHIPPING.INBOUND_PROFILE_INVALID`),出站绑定 `SHIPPING.OUTBOUND_PROFILE_INVALID`(2026-10-19 出站全栈);解析规则退役守卫补查入站/出站配置绑定;API 路由 `/sources/inbound-files`、`/runs/{run_no}/inbound-files` 与错误码/审计事件 inbound 化;出站 RPA 与调拨 sink 见 [superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md](superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md);2026-10-15 设计见 [superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md](superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md),运维手册 technical.md §12 |
| 待匹配桶清空并重新解析(2026-10-15) | 已实现 | 解析规则修改后的存量档行重建入口:`GET /backlog/pending-match/reparse-preview` 预检(可重建归档文件清单/份数、将用规则 code+version、将清除行数、证据缺失保留行数)+ `POST /backlog/pending-match/reparse` 执行(单事务:先全量重解析归档文件,任一失败 400 `TRANSFER.REPARSE_PARSE_FAILED` 一行不删;删除可重建/未封存/未被有效 items 占用行后按当前模板幂等重落,8 成分键与异动日期过滤自动生效);审计 `TRANSFER_PENDING_MATCH_REPARSED`(操作人/来源/文件清单/规则版本/前后计数) |
| 首页待匹配桶与 file_current 改锚(2026-10-14) | 已实现 | 待办看板新增「待匹配」桶(已落档但从未匹配的外部记录只读可见+去匹配引导,不可勾选执行),四队列卡数据源改档+最近执行状态联查;file_current 门禁改锚档记录 file_version(==来源最新可用文件 sha 即当前) |
| 首页待匹配与可匹配拆数(2026-10-21) | 已实现 | 「待匹配」改为成熟未占用的出入站全量,不再按调拨类型范围收窄。「匹配可调拨库存」卡显示启用类型现在圈得住的 `matchable_count`。清单上段可去匹配,下段范围外只读。建匹配仍按所选类型圈档。 |
| 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md |
| 可调拨明细与待办看板首页 | 已实现 | 首页上区「库存匹配」动作卡 + 待办看板五桶(2026-10-14 起数据源=档联查):待匹配(已落档未匹配,只读+去匹配引导,不可执行)/可调拨明细(GET /items/executable 全局可执行行,勾选按行生成调拨单)/待恢复异常/已人工关闭/结果未知;「最近匹配」(原"最近预检")已移除(匹配卡=范围实时视图,多份同 scope 匹配属重复窗口) |
| 待处理池批量操作与恢复处理 | 已实现 | 批量重查(恢复处理=行级重查原地刷新+续新鲜度;2026-10-14 起重查对档对账,不再有文件证据对齐兜底)/批量关闭;blocked_file_removed 仅历史残留防御(2026-09-28 起不再新产生,现为档记录被新版本替换的失效隔离语义);行归属=匹配出生即绑定(§「库存异动档与出生翻转」) |
| 按行执行与执行门禁 | 已实现 | execute(item_ids) **202 异步**:API 两道门禁(存在可执行 + 文件版本对账,fail-closed)通过即建 queued Run + 五元组分组建票 + 一次入队,worker 逐票执行(文件对账复核 + 写前路由/库存复查——库存复查仅全量重跑路径,final_only 续跑不复查);Run 留痕不绑匹配;进度/结果无状态回读(GET /runs 轮询票清单);行级新鲜度 TTL 门禁与 ITEMS_STALE 错误码退役,TTL 降为 stale 徽标展示阈值(2026-09-25 定稿,见 features/in-transit-transfer/technical.md §6.3) |
| ERP 建单写路径(票级顺序引擎,2026-09-24) | 已实现 | 写路径经集成连接器统一出口:`database` 连接器(oracle/mysql/sqlserver/postgresql 四库直连,SQL 接口 identifiers 白名单替换)+ `create_transfer` 绑定一对多有序步骤(steps_json:写 ERP 中间表 → 触发 WS);顺序引擎四规则(resume 跳过非末步/非末步失败即中止/末步映射+裁决钩子/末步超时 result_unknown);融合卡「票清单=进度=结果」、result_unknown retrigger(D11 唯一出口,禁关闭重建)、失败票人工关票(D18 行脱离回可执行)、首页「已执行」票维护区块;管理端配置配方/SOP/UAT 确认项/已知限制统一见 [features/in-transit-transfer/technical.md](features/in-transit-transfer/technical.md) §10(含 SOP 红线 §10.8;交付说明:新增依赖 pymysql/pymssql,psycopg2-binary 既有;本期零新增环境变量) |
| 异动日期默认与输入期限制 | 已实现 | 来源选择卡异动日期默认 T−2(产品默认作业点,非强制边界;成熟规则已退役 2026-10-16);日期输入 max=业务日期当天 + 起止非法行内提示禁用确认(后端 MOVEMENT_DATE_RANGE_INVALID 卡控保留双保险);「直接生成调拨单」改名「生成调拨单」 |
| 异动日期默认与输入期限制 | 已实现 | 来源选择卡异动日期默认与上限同为 T−2 可匹配截止日(T−2 成熟封顶 2026-10-21:T−2 之前数据全部成熟,T−2 之后不可选);面板 disabled-date 卡 T−2 之后日期 + 起止非法行内提示禁用确认(后端 MOVEMENT_DATE_RANGE_INVALID 截止≤T−2 双保险);「直接生成调拨单」改名「生成调拨单」 |
| 来源重试合并触发与知情范围确认(2026-10-09) | 已实现 | 批量重试 RPA 合并写**单个** batch trigger(POST `/sources/retry-rpa-batch`,Worker 单次浏览器会话按 profile 分组串行导出,替代逐来源 N 个 trigger/N 次开浏览器;单源失败跳过不阻断整批,parse_failed 仍先本地重解析);来源选择卡混合选择(含非就绪项)确认前先披露范围(可匹配/暂不可匹配计数+按状态分组明细),显式确认后提交 ready-only,全就绪直达(知情部分确认,替代静默剔除;其余来源就绪后可重新匹配增量补入) |
| 当前归档重新解析(2026-10-21) | 已实现 | 来源卡证据清单第一行「重新解析」调用 `POST /sources/{source_code}/reparse`,只重放该流入站或出站的最新可用归档并幂等落档,不触发 RPA,不删除档行。↻ 仍是重新抓取。待匹配「清空并重新解析」仍是整桶重建。 |
| 前端 Chat 卡片/结果页与四语言 | 已实现 | `frontend/src/features/chat/` 卡片(文件进度/匹配/结果/待处理)与 admin 模块已按计划实施(结果=融合卡:202 提交后 4s 轮询票清单至严格终态) |
---
@@ -0,0 +1,463 @@
# 调拨证据流状态、重试与下载 Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 来源选择卡按调拨类型声明的记录类型,分行内括号显示入站/出站状态,并用一个批量按钮和一个下载按钮按流重试、按目录打包。
**Architecture:** 一条调拨类型要哪些证据流,从它已有的范围规则里推导:字段为 `record_kind` 的规则值。没有这种规则时结果是 `("inbound", "outbound")`。状态投影、批量重试、下载打包和匹配圈档都读这个推导结果。不新增表字段,不改调拨类型表单。`resolve_source_file_status` 增加 `record_kind`,默认 `inbound`,这只是单流查询的参数缺省,不是类型没写规则时的业务默认。来源 API 在保留入站扁平字段的同时增加 `streams`。前端只按 `streams` 画括号。
**Tech Stack:** Flask、SQLAlchemy 2.0、Alembic、Vue 3、Vitest、pytest。后端测试在 `backend/`,Python 用 `backend/.venv/Scripts/python.exe`。
**Spec:** `docs/superpowers/specs/2026-10-19-transfer-evidence-stream-ui-design.md`
## Global Constraints
- 状态粒度是来源实例 × 记录类型。不拆来源行,不做「部分就绪」。
- 不新增调拨类型字段,不改调拨类型表单。入站还是出站,读该类型已有的范围规则:字段为 `record_kind`(表单下拉里的「记录类型」)的那几条,值里的 `inbound` / `outbound`。
- 一条类型没有「记录类型」规则时,入站和出站都要。规则里只写了其中一种,就只要那一种。来源卡、批量重试、下载、圈档都读这一结果,不看类型编码。
- 来源行只显示当前调拨类型声明的证据流。缺报表配置时状态为「未配置」。
- 行形态:`DSV360_AWSBI_BYAWSCMH01 [入站 √就绪 ↻] [出站 ⟳抓取中]`。重试是括号内的 `↻`,可读名称「重试入站」或「重试出站」。抓取中不显示 `↻`。行上不出现「重试」「文件」。
- 点状态字展开该流当天清单:文件名、抓取时间、sha256、文件大小、预览、下载。不解析 Excel,不新增行数字段。
- 选择条仍是三个按钮。下载文案为「下载证据文件」。压缩包名 `evidence-files-<n>.zip`,路径 `inbound/<source_code>/<filename>` 与 `outbound/<source_code>/<filename>`,只打包当前类型所需且已就绪的文件。
- 批量重试仍是一个按钮。按当前调拨类型的 `record_kinds`,只重试尚未就绪、且不是抓取中、且已配置的流。行上的 `↻` 可对已就绪的流强制重试。
- 确认匹配:该来源每一条所需流为 `ready` 或 `no_data` 才可提交。混合选择沿用披露条,并写明记录类型。
- 圈档固定条件里的 `record_kind='inbound'` 改为 `record_kinds_of(该类型的范围规则)`。没有类型对象的调用方显式只圈入站。
- 不拆两个下载按钮,不拆两个批量按钮,不为出站复制来源实例行,不改 Worker、排程和回调契约。
- 新增用户可见文案同时写入 `zh-CN` / `zh-TW` / `en` / `th`。
- 每个任务结束于 `git add`。不要在计划步骤里 `git commit`。
## File Structure
- `backend/app/services/in_transit_transfer/scope_rules.py`:从已有范围规则推导 `record_kinds_of`。不改表,不写迁移。
- `backend/app/services/in_transit_transfer/source_file_status.py`:按 `record_kind` 投影,缺配置为 `unconfigured`。
- `backend/app/api/in_transit_transfer/__init__.py`:`/sources` 增加 `streams`;重试与批量重试接受记录类型;下载改目录;新增证据清单。
- `backend/app/services/in_transit_transfer/matching_service.py`:`create_matching` 把 `record_kinds_of(类型.scope_rules)` 传入圈档底座。底座默认仍是入站。
- `frontend/src/features/chat/types/transfer.types.ts`、`api/transfer.api.ts`、`components/messages/TransferSourceSelectCard.vue`:括号行、清单、一个下载按钮、一个批量按钮。
- `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`:来源卡新文案。调拨类型页不改。
## 界面框线
调拨类型页不改。要出站时,仍用现有范围规则,字段选「记录类型」,值写 `outbound` 或同时写 `inbound` 与 `outbound`。
```text
+--------------------------------------------------+
| 范围规则 |
| 字段 [记录类型 v] 匹配 [等于 v] 值 [outbound] |
+--------------------------------------------------+
```
Task 7 只改来源选择卡。当前类型的范围规则里,「记录类型」只写了 inbound:
```text
+----------------------------------------------------------+
| 选择出入站来源实例 |
| 调拨类型 (在途仓至HUB仓) HUB仓维修出 HUB仓维修入 |
| 异动日期 [2026-10-14] ~ [2026-10-14] |
| 已选 10 个来源实例,其中 10 个可重试 |
| [批量重试 RPA] [下载证据文件] [清空选择] |
| CRANE |
| [x] DSV360_AWSBI_BYAWSCMH01 [入站 √就绪 ↻] |
| [确认范围并匹配] |
+----------------------------------------------------------+
```
同一张卡。当前类型没有「记录类型」规则,或规则值里 inbound 和 outbound 都有。点「入站 √就绪」后,清单开在该行下面。抓取中的括号里没有 ↻。
```text
+----------------------------------------------------------+
| 调拨类型 (没有记录类型规则,或两种值都有) |
| [x] DSV360_AWSBI_BYAWSCMH01 |
| [入站 √就绪 ↻] [出站 ⟳抓取中] |
| +----------------------------------------------+ |
| | Inbound_20261014.xlsx | |
| | 2026-10-14 09:12 · 128 KB · a1b2c3d4… | |
| | [预览] [下载] | |
| +----------------------------------------------+ |
| [x] DSV360_AWSBI_BYAWSPRD01 |
| [入站 —无数据 ↻] [出站 —未配置] |
+----------------------------------------------------------+
```
「未配置」的括号里没有 ↻。文件大小来自归档的 `file_size`,框线里的 `128 KB` 只是示意。
---
### Task 1: 从已有范围规则推导证据流
**Files:**
- Modify: `backend/app/services/in_transit_transfer/scope_rules.py`
- Test: `backend/tests/services/in_transit_transfer/test_scope_rules.py`(没有则新建)
**Interfaces:**
- Consumes: `parse_scope_rules` 得到的 `ScopeRule`。字段名已在 `SCOPE_FIELDS` 里,就是 `record_kind`。
- Produces: `record_kinds_of(rules: tuple[ScopeRule, ...]) -> tuple[str, ...]`。只认值 `inbound` 与 `outbound`,按这个顺序去重。没有任何 `field == "record_kind"` 的规则时返回 `("inbound", "outbound")`。多条这种规则取值的交集;交集为空时返回 `()`。
- [ ] **Step 1: Write the failing test**
```python
def test_record_kinds_of_reads_existing_scope_rule():
"""没有记录类型规则时入站和出站都要;只写 outbound 时只要出站。"""
assert record_kinds_of(parse_scope_rules([
{"field": "doc_no", "match": "prefix", "values": ["HOM"]},
])) == ("inbound", "outbound")
assert record_kinds_of(parse_scope_rules([
{"field": "record_kind", "match": "equals", "values": ["outbound"]},
])) == ("outbound",)
assert record_kinds_of(parse_scope_rules([
{"field": "record_kind", "match": "in", "values": ["outbound", "inbound"]},
])) == ("inbound", "outbound")
```
- [ ] **Step 2: Run test to verify it fails**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_scope_rules.py::test_record_kinds_of_reads_existing_scope_rule -v`
Expected: FAIL,`record_kinds_of` 未定义。
- [ ] **Step 3: Write minimal implementation**
在 `scope_rules.py` 实现 `record_kinds_of`。不要加模型列,不要写迁移,不要改调拨类型表单。启用类型 API 若把推导结果放进响应,字段名用 `record_kinds`,值只能来自这个函数。
- [ ] **Step 4: Run test to verify it passes**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_scope_rules.py -v`
Expected: PASS
- [ ] **Step 5: Stage changes**
```bash
git add backend/app/services/in_transit_transfer/scope_rules.py backend/tests/services/in_transit_transfer/test_scope_rules.py
```
---
### Task 2: 按记录类型投影文件状态
**Files:**
- Modify: `backend/app/services/in_transit_transfer/source_file_status.py`
- Test: `backend/tests/services/in_transit_transfer/test_source_file_status.py`(没有则新建;已有入站用例保持)
**Interfaces:**
- Consumes: `queries.get_inbound_config` / `get_outbound_config`,`latest_usable_inbound_file`,出站文件与 `FreightRpaOutboundUnitRun` 的同口径查询。
- Produces: `resolve_source_file_status(*, source_code: str, record_kind: str = "inbound") -> dict`。`record_kind="inbound"` 时返回值与今天相同。`record_kind="outbound"` 且 `get_outbound_config` 为 `None` 时返回 `{"file_status": "unconfigured", "has_ready_file": False, "file_no": None, "file_sha256": None}`。
- [ ] **Step 1: Write the failing test**
```python
def test_outbound_without_config_is_unconfigured(monkeypatch):
"""没有出站报表配置时,出站流是未配置,入站投影函数签名仍可只传来源。"""
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.get_outbound_config",
lambda source_code: None,
)
status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound")
assert status["file_status"] == "unconfigured"
assert status["has_ready_file"] is False
```
再写一条:出站存在可用文件时 `file_status == "ready"`。查询函数按入站 `latest_usable_inbound_file` 的返回形状做 monkeypatch,不连真实 MinIO。
- [ ] **Step 2: Run test to verify it fails**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_source_file_status.py::test_outbound_without_config_is_unconfigured -v`
Expected: FAIL,`record_kind` 意外参数或没有 `unconfigured`。
- [ ] **Step 3: Write minimal implementation**
`record_kind` 不是 `inbound`/`outbound` 时抛 `ValidationError`。入站分支保持现有顺序:可用文件 → 解析失败 → 进行中单元 → 失败 → `no_data` → 过期 → `none`。出站先查配置,没有则 `unconfigured`;有配置则用出站文件表和 `FreightRpaOutboundUnitRun` 走同一顺序。默认参数 `record_kind="inbound"`,不改 `execution_service` 等现有调用。
- [ ] **Step 4: Run test to verify it passes**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_source_file_status.py tests/services/in_transit_transfer/test_evidence_sync.py -v`
Expected: PASS。既有入站用例仍绿。
- [ ] **Step 5: Stage changes**
```bash
git add backend/app/services/in_transit_transfer/source_file_status.py backend/tests/services/in_transit_transfer/test_source_file_status.py
```
---
### Task 3: 来源列表返回 streams
**Files:**
- Modify: `backend/app/api/in_transit_transfer/__init__.py`(`transfer_sources_api`)
- Test: `backend/tests/api/test_in_transit_transfer_api.py`
**Interfaces:**
- Consumes: `resolve_source_file_status(*, source_code, record_kind)`。
- Produces: 每个来源除现有 `file_status` / `has_ready_file`(等于入站流,供尚未改完的前端)外,增加
```python
"streams": [
{"record_kind": "inbound", "file_status": "ready", "has_ready_file": True, "file_no": "...", "file_sha256": "..."},
{"record_kind": "outbound", "file_status": "unconfigured", "has_ready_file": False, "file_no": None, "file_sha256": None},
]
```
两条都返回,前端按类型过滤。
- [ ] **Step 1: Write the failing test**
在来源列表用例中断言响应里 `DSV` 来源的 `streams` 长度为 2,且 `streams[0]["record_kind"] == "inbound"`,`file_status` 仍等于入站那条的 `file_status`。用现有测试夹具里的来源码,不要新造平台。
- [ ] **Step 2: Run test to verify it fails**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k sources -v`
Expected: FAIL,响应没有 `streams`。
- [ ] **Step 3: Write minimal implementation**
`transfer_sources_api` 对每个来源调用两次投影,组装 `streams`。扁平字段继续取 `record_kind="inbound"` 的结果。
- [ ] **Step 4: Run test to verify it passes**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k sources -v`
Expected: PASS
- [ ] **Step 5: Stage changes**
```bash
git add backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_in_transit_transfer_api.py
```
---
### Task 4: 重试按证据流,批量按调拨类型
**Files:**
- Modify: `backend/app/api/in_transit_transfer/__init__.py`(`retry_source_rpa_api`、`retry_sources_rpa_batch_api`)
- Modify: `backend/app/services/in_transit_transfer/inbound_trigger_service.py` 与 `outbound_trigger_service.py`(只在 API 层选择调用哪个,不合并两个 trigger 实现)
- Test: `backend/tests/api/test_in_transit_transfer_api.py`
**Interfaces:**
- Consumes: `trigger_inbound_rpa`、`trigger_outbound_rpa`、`trigger_*_rpa_batch`、`get_by_code(transfer_type).record_kinds`。
- Produces: `POST /sources/<code>/retry-rpa` 请求体 `{"record_kind": "outbound"}`,缺省 `inbound`。`POST /sources/retry-rpa-batch` 请求体 `{"source_codes": [...], "transfer_type": "hub_to_hub"}`。批量结果每项增加 `record_kind`。已 `ready`、`fetching`、`unconfigured` 的流不写入 trigger。`no_data` / `failed` / `expired` / `none` / `parse_failed` 会进入对应流的重试。
- [ ] **Step 1: Write the failing test**
```python
def test_batch_retry_skips_ready_inbound_and_triggers_outbound(client, monkeypatch):
"""HUB 仓间调拨:入站已就绪不重抓,出站未就绪才触发。"""
def fail_inbound(**kwargs):
raise AssertionError("inbound batch")
called = {}
def record_outbound(**kwargs):
called["codes"] = kwargs["source_codes"]
return {"ok": True, "triggered": True}
def status(*, source_code, record_kind="inbound"):
if record_kind == "outbound":
return {"file_status": "none", "has_ready_file": False, "file_no": None, "file_sha256": None}
return {"file_status": "ready", "has_ready_file": True, "file_no": "a.xlsx", "file_sha256": "abc"}
monkeypatch.setattr(api_module, "trigger_inbound_rpa_batch", fail_inbound)
monkeypatch.setattr(api_module, "trigger_outbound_rpa_batch", record_outbound)
monkeypatch.setattr(api_module, "resolve_source_file_status", status)
response = client.post("/api/in-transit-transfer/sources/retry-rpa-batch", json={
"source_codes": ["DSV360_AWSBI"],
"transfer_type": "hub_to_hub",
})
assert response.status_code == 202
assert called["codes"] == ["DSV360_AWSBI"]
```
`api_module` 指 `app.api.in_transit_transfer`。蓝图前缀是 `/api/in-transit-transfer`。夹具若没有启用的 `hub_to_hub`,本测试用 `create_config` 建一个,`record_kinds` 为 `["inbound", "outbound"]`。
- [ ] **Step 2: Run test to verify it fails**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py::test_batch_retry_skips_ready_inbound_and_triggers_outbound -v`
Expected: FAIL,请求体没有 `transfer_type` 或仍只调用入站 batch。
- [ ] **Step 3: Write minimal implementation**
单源端点读取 `record_kind`,出站走 `trigger_outbound_rpa`,`parse_failed` 仍只对入站做本地重解析;出站 `parse_failed` 重新触发出站 RPA。批量端点读取类型的 `record_kinds`,按流分组后最多写一个入站 batch 和一个出站 batch。`unconfigured` 记入结果 `ok: false`,`error_code` 用现有配置缺失码,不新增错误码。
- [ ] **Step 4: Run test to verify it passes**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k retry -v`
Expected: PASS
- [ ] **Step 5: Stage changes**
```bash
git add backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_in_transit_transfer_api.py
```
---
### Task 5: 证据压缩包与当天清单
**Files:**
- Modify: `backend/app/api/in_transit_transfer/__init__.py`(`download_source_inbound_files_api`,并新增清单路由)
- Test: `backend/tests/api/test_in_transit_transfer_api.py`
**Interfaces:**
- Consumes: 可用入站/出站归档文件、`file_asset_storage.get_bytes`、`file_asset_storage.presigned_get_url`。
- Produces:
- `POST /sources/inbound-files` 请求体增加 `transfer_type`。压缩包内路径为 `inbound/<source_code>/<filename>` 或 `outbound/<source_code>/<filename>`。下载名 `evidence-files-<n>.zip`。审计事件类型仍是 `TRANSFER_INBOUND_FILES_DOWNLOADED`。
- `GET /sources/<source_code>/evidence-files?record_kind=inbound` 返回 `[{file_id, original_filename, created_at, sha256, file_size, presigned_url}]`,只含当天可用文件。签发 URL 时写同一审计事件,`aggregate_id` 为 `source_code`。
- [ ] **Step 1: Write the failing test**
用 `zipfile.ZipFile` 读响应体。类型的范围规则把记录类型收成只要 inbound 时,名单包含 `inbound/DSV360_AWSBI/Inbound.xlsx`,且不包含 `outbound/`。没有记录类型规则时,两种就绪文件都打进包。清单用例断言 JSON 含 `file_size` 与 `presigned_url`,不含解析出的行数。
- [ ] **Step 2: Run test to verify it fails**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k "evidence or inbound_files" -v`
Expected: FAIL,路径仍是 `<code>-<filename>` 或清单路由 404。
- [ ] **Step 3: Write minimal implementation**
下载循环按类型的 `record_kinds` 各取该来源最新可用文件,`archive.writestr(f"{kind}/{code}/{safe_name}", data)`。两种都没有文件时仍 `NotFoundError(..., code="SHIPPING.INBOUND_FILE_NOT_FOUND")`。清单查询复用下载用的可用文件条件,但返回当天全部可用文件而不只最新一份。`presigned_get_url(..., expires_seconds=300)`。
- [ ] **Step 4: Run test to verify it passes**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k "evidence or inbound_files" -v`
Expected: PASS
- [ ] **Step 5: Stage changes**
```bash
git add backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_in_transit_transfer_api.py
```
---
### Task 6: 圈档跟随调拨类型的记录类型
**Files:**
- Modify: `backend/app/services/in_transit_transfer/matching_service.py`(`_circle_ledger_base_query` 与 `create_matching` 附近的调用)
- Test: `backend/tests/services/in_transit_transfer/test_matching_service.py`
**Interfaces:**
- Consumes: `record_kinds_of(config.scope_rules)`。
- Produces: `_circle_ledger_base_query(*, record_kinds: tuple[str, ...], exclude_occupied_by_matching_id: int | None = None)`。`record_kinds` 必传,避免再用入站当隐式默认。`_circle_ledger_records` 增加同名参数并传给底座。`create_matching` 与 `circle_ledger_records_scope_union` 传入 `record_kinds_of(...)`。没有类型对象的调用点显式传入 `("inbound",)`。
- [ ] **Step 1: Write the failing test**
```python
def test_hub_to_hub_circles_outbound_ledger_rows(deps):
"""没有记录类型规则的类型圈入出站档;范围规则写明只要 inbound 的类型不圈。"""
_insert_ledger(source_code="DSV360_AWSBI", record_kind="outbound", doc_no="HOX1", movement_date="2026-10-14")
circled = create_matching(
source_codes=["DSV360_AWSBI"],
business_date="2026-10-14",
movement_date_from="2026-10-14",
movement_date_to="2026-10-14",
transfer_type="hub_to_hub",
deps=deps,
)
assert "HOX1" in {item.doc_no for item in items_of(circled)}
inbound_only = create_matching(
source_codes=["DSV360_AWSBI"],
business_date="2026-10-14",
movement_date_from="2026-10-14",
movement_date_to="2026-10-14",
transfer_type="in_transit_to_hub",
deps=deps,
)
assert "HOX1" not in {item.doc_no for item in items_of(inbound_only)}
```
`_insert_ledger` 与 `items_of` 按本文件已有的落档、读明细写法就地写,断言只看 `doc_no`。`hub_to_hub` 的范围规则不写记录类型。`in_transit_to_hub` 的范围规则必须有一条 `record_kind` 等于 `inbound`,否则会把 `HOX1` 也圈进来。
- [ ] **Step 2: Run test to verify it fails**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_matching_service.py::test_hub_to_hub_circles_outbound_ledger_rows -v`
Expected: FAIL,出站行被 `record_kind='inbound'` 滤掉。
- [ ] **Step 3: Write minimal implementation**
底座过滤改为 `TransferMovementLedger.record_kind.in_(record_kinds)`。`_circle_ledger_records` 把 `record_kinds` 传给底座。`create_matching` 传入 `record_kinds_of(当前类型.scope_rules)`。`circle_ledger_records_scope_union` 对每个 `config` 传入 `record_kinds_of(config.scope_rules)`。没有类型对象的调用点不改参数。
- [ ] **Step 4: Run test to verify it passes**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_matching_service.py -v`
Expected: PASS
- [ ] **Step 5: Stage changes**
```bash
git add backend/app/services/in_transit_transfer/matching_service.py backend/tests/services/in_transit_transfer/test_matching_service.py
```
---
### Task 7: 来源选择卡与调拨类型表单
**Files:**
- Modify: `frontend/src/features/chat/types/transfer.types.ts`
- Modify: `frontend/src/features/chat/api/transfer.api.ts`
- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue`
- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`
- Modify: `frontend/src/locales/zh-CN/chat.json`、`zh-TW/chat.json`、`en/chat.json`、`th/chat.json`
**Interfaces:**
- Consumes: `streams[]`、`record_kinds`、`POST retry-rpa` 的 `record_kind`、`POST retry-rpa-batch` 的 `transfer_type`、`GET evidence-files`、`POST inbound-files` 的 `transfer_type`。
- Produces: 卡片只渲染当前类型 `record_kinds` 里的括号。状态字按钮的 `aria-expanded` 控制行下清单。`↻` 的 `aria-label` 为 i18n「重试入站」或「重试出站」。`file_status === 'fetching'` 时不渲染 `↻`。
- [ ] **Step 1: Write the failing test**
在 `TransferSourceSelectCard.spec.ts` 增加来源:
```typescript
const hubSource = {
source_code: 'DSV360_AWSBI_BYAWSCMH01',
display_name: 'CMH01',
platform: 'crane',
enabled: true,
has_ready_file: true,
file_status: 'ready' as const,
streams: [
{ record_kind: 'inbound' as const, file_status: 'ready' as const, has_ready_file: true },
{ record_kind: 'outbound' as const, file_status: 'fetching' as const, has_ready_file: false },
],
};
```
断言类型为 `hub_to_hub`(两种记录类型)时,文本含 `[入站 √就绪]` 与 `[出站 ⟳抓取中]`,出站括号内没有重试按钮,入站括号内的按钮 `aria-label` 为「重试入站」。类型为 `in_transit_to_hub` 时不出现「出站」。组件内不出现按钮文案「文件」。下载按钮文案为「下载证据文件」。
- [ ] **Step 2: Run test to verify it fails**
Run: `npm run test -- src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`
工作目录:`frontend/`。
Expected: FAIL,仍渲染单个「文件已就绪」和「下载入站文件」。
- [ ] **Step 3: Write minimal implementation**
`TransferSourceOption.streams` 为 `{ record_kind: 'inbound' | 'outbound'; file_status: ...; has_ready_file: boolean }[]`。状态字映射:`ready` → `√就绪`,`fetching` → `⟳抓取中`,`failed` → `×失败`,`no_data` → `—无数据`,`expired` → `!已过期`,`parse_failed` → `!解析失败`,`none` → `—无文件`,`unconfigured` → `—未配置`。前缀用 i18n「入站」「出站」。括号用文本,不用额外色块区分记录类型;就绪/失败仍可用现有绿/红字色,文字始终在。
点状态字调用 `listEvidenceFiles(sourceCode, recordKind)`,清单插在该行下方,按钮只有「预览」「下载」,都打开 `presigned_url`。批量重试提交 `{ source_codes, transfer_type }`。单行 `↻` 提交 `{ record_kind }`。确认门禁改为:所选类型的每条流都是 `ready` 或 `no_data`。披露条把未就绪流写成「来源编码 入站 抓取中」。
`downloadFiles` 的 zh-CN 改为「下载证据文件」,zh-TW「下載證據文件」,en「Download evidence files」,th「ดาวน์โหลดไฟล์หลักฐาน」。新增键走 `chat.transfer.streamInbound`、`streamOutbound`、`retryInbound`、`retryOutbound`、`previewEvidence`、`downloadEvidence`,四语言一起补。不改 `TransferTypesPage.vue`。来源卡用启用类型接口带回的 `record_kinds`(由 `record_kinds_of` 算出)决定画几条括号。
卡片上的来源编码、状态括号保持现在的 `text-xs` 密度,不把重试按钮放大到 44px。
- [ ] **Step 4: Run test to verify it passes**
Run: `npm run test -- src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`
Expected: PASS
- [ ] **Step 5: Stage changes**
```bash
git add frontend/src/features/chat/types/transfer.types.ts frontend/src/features/chat/api/transfer.api.ts frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json
```
@@ -0,0 +1,571 @@
# 当前归档重新解析 Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 来源卡展开的当前证据文件可以本地重新解析并幂等落档,不触发 RPA。
**Architecture:** 新服务 `reparse_current_file` 自己找出站或入站的最新可用归档,然后调用已经存在的 `sync_outbound_source_rows` / `sync_source_rows`(它们只 flush)。结构错误沿用现有 `mark_*_parse_failure`。HTTP 层只做鉴权、参数和 envelope。前端按钮只画在清单第一行,请求体不带 `file_id`。
**Tech Stack:** Flask、SQLAlchemy 2.0、Vue 3、Vitest、pytest。后端测试在 `backend/`,Python 用 `backend/.venv/Scripts/python.exe`。前端测试在 `frontend/`,用 `npx vitest run`。
**Spec:** `docs/superpowers/specs/2026-10-21-transfer-current-file-reparse-design.md`
## Global Constraints
- 入站和出站各自有「重新解析」。当天该流已有可用归档时可以点,状态是就绪或解析失败都可以。
- 只解析该流当前最新一份可用归档(`created_at`、`id` 倒序第一条,与 `latest_usable_*_file` 相同),并幂等写入异动档。不写 RPA trigger。
- 请求不接受 `file_id`。服务端自己取最新一份,避免清单过期时重放历史文件。
- 同一份文件再解析一次:摘要未变则跳过已有档行,不另插一行。
- 没有可用归档:422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。
- 有归档但没有已发布的对应 purpose 规则:422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`。不把文件标成解析失败。规则缺失不是文件错误。
- 结构校验失败(`MovementFileSchemaError`):回滚档行,把 `parse_failed` 写到当前文件,HTTP 200,`ok: false`,`file_status: parse_failed`,带 `error_message`。
- 其他异常(数据库截断、连接失败):回滚,不标解析失败,HTTP 200,`ok: false`,`error_message` 为异常文本。文件状态保持原投影。
- 成功:HTTP 200,`ok: true`,返回 `inserted` / `updated` / `skipped` / `sealed_skipped` 和解析后的 `file_status`。审计沿用落档函数已有的 `TRANSFER_EVIDENCE_SYNCED`,不另造事件。
- `file_version` 只经 `movement_file_version`。本入口不自己拼版本戳。
- 展开清单后只有第一行显示「重新解析」。↻ 与 `POST /sources/{source_code}/retry-rpa` 不变。
- 不调用 `POST /backlog/pending-match/reparse`,不删除已有档行。
- 新增用户可见文案同时写入 `zh-CN` / `zh-TW` / `en` / `th`。新增 `error.code` 同步写入四份 `locales/*/errors.json`。
- 每个任务结束于 `git add`。不要在计划步骤里 `git commit`。
## File Structure
- `backend/app/services/in_transit_transfer/current_file_reparse.py`:取当前归档、调用既有落档函数、提交或回滚、返回计数。不触发 RPA,不拼 `file_version`。
- `backend/app/api/in_transit_transfer/__init__.py`:新增 `POST /sources/<source_code>/reparse`。不改 `retry-rpa`。
- `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`:服务行为。
- `backend/tests/api/test_in_transit_transfer_api.py`:无文件 422、无权限 403。
- `frontend/src/features/chat/api/transfer.api.ts` 与 `types/transfer.types.ts`:请求与响应类型。
- `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue`:第一行按钮。
- `frontend/src/features/chat/components/messages/TransferMessageView.vue`:成功后 `loadSources`。
- `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` 与 `errors.json`:按钮文案和两个错误码。
- `docs/features/in-transit-transfer/technical.md`、`docs/funclist.md`:登记入口。
---
### Task 1: 当前文件重解析服务
**Files:**
- Create: `backend/app/services/in_transit_transfer/current_file_reparse.py`
- Create: `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`
- Test: `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`
**Interfaces:**
- Consumes: `sync_outbound_source_rows(*, source_code: str, now: datetime) -> SyncOutcome | None`;`sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None`;`latest_usable_outbound_file` / `latest_usable_inbound_file`;`mark_outbound_parse_failure` / `mark_inbound_parse_failure`;`resolve_source_file_status(*, source_code: str, record_kind: str) -> dict`;`MovementFileSchemaError`。
- Produces: `reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult`。`CurrentReparseResult` 字段:`source_code: str`、`record_kind: str`、`ok: bool`、`file_status: str`、`file_id: int | None`、`inserted: int`、`updated: int`、`skipped: int`、`sealed_skipped: int`、`error_code: str | None`、`error_message: str | None`。
- [ ] **Step 1: Write the failing test**
新建 `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`。文件头写明用途是锁定「当前归档重解析、不触发 RPA」。导入 `pytest`、`datetime`、`AppError`、`TransferAuditEvent`、`TransferMovementLedger`、`FreightRpaOutboundReportFile`、`FreightRpaOutboundUnitRun`、`reparse_current_file`、`movement_file_version`、`factories`。把 `test_outbound_evidence_sync.py` 里的 `outbound_storage` fixture 和 `_seed_outbound_world` 抄进来,来源仍用全局种子 `DSV360_AWSDU`,`created_at` 用 `datetime.utcnow()`,否则当天可用门禁会把文件看成过期。`pytestmark = [pytest.mark.usefixtures("app")]`。
```python
def test_reparse_outbound_inserts_ledger_without_new_rpa_run(outbound_storage):
# [断言意图] 已落地出站文件重解析后出现 outbound 档行,且不新增出站执行单元。
report = _seed_outbound_world()
runs_before = FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is True
assert result.file_id == report.id
assert result.inserted == 1
assert result.file_status == "ready"
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound", doc_no="ASN-O1").count() == 1
assert FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count() == runs_before
assert TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").count() == 1
def test_reparse_same_outbound_file_skips_existing_row(outbound_storage):
# [断言意图] 同一份摘要再解析一次不插入第二行。
_seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
again = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert again.ok is True
assert again.inserted == 0
assert again.skipped == 1
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 1
def test_reparse_schema_failure_marks_file_and_lands_nothing(outbound_storage):
# [断言意图] 单号缺失是结构失败:零档行,文件变为 parse_failed,响应带原因。
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx(
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is False
assert result.file_status == "parse_failed"
assert result.inserted == 0
assert "missing_invoice_no" in (result.error_message or "")
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is not None
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 0
def test_reparse_without_published_profile_does_not_mark_parse_failed(outbound_storage):
# [断言意图] 规则未发布不是文件错误,不写 parse_failed。
report = _seed_outbound_world(profile_status="draft")
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
with pytest.raises(AppError) as exc_info:
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE"
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is None
def test_reparse_without_file_raises():
# [断言意图] 没有可用归档时拒绝,而不是去触发 RPA。
with pytest.raises(AppError) as exc_info:
reparse_current_file(
source_code="DSV360_AWSDU", record_kind="outbound", now=datetime.utcnow())
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_FILE"
assert exc_info.value.http_status == 422
def test_reparse_non_schema_error_does_not_mark_parse_failed(outbound_storage, monkeypatch):
# [断言意图] 数据库一类异常回滚后不把文件标成解析失败,并把异常文本带回。
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
def _boom(**_kwargs):
raise RuntimeError("value too long for varchar(64)")
monkeypatch.setattr(
"app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows",
_boom,
)
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is False
assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED"
assert "varchar(64)" in (result.error_message or "")
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is None
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 0
```
`_seed_outbound_world` 增加可选参数 `profile_status: str = "published"`,传给 `FreightRpaParsingProfile.status`。入站成功路径用下面这个测试,归档时间同样取 `datetime.utcnow()`:
```python
def test_reparse_inbound_inserts_ledger(archive_storage):
# [断言意图] 入站当前文件走 sync_source_rows,record_kind 为 inbound。
source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_NOW")
storage_key = "archive/CRANE_REPARSE_NOW/current.xlsx"
report = factories.seed_reparse_archive_file(
source, sha="c" * 64, storage_key=storage_key, created_at=datetime.utcnow())
archive_storage.objects[storage_key] = factories.build_movement_xlsx([
["ASN-I1", "1", "I", "MAT-I1", "连接器", "LOT-I1", 10, "2026-08-05"],
])
result = reparse_current_file(
source_code="CRANE_REPARSE_NOW", record_kind="inbound", now=datetime.utcnow())
assert result.ok is True
assert result.file_id == report.id
assert result.inserted == 1
row = TransferMovementLedger.query.filter_by(
source_code="CRANE_REPARSE_NOW", record_kind="inbound").one()
assert row.doc_no == "ASN-I1"
assert row.file_version == movement_file_version("c" * 64)
```
`archive_storage` fixture 与 `test_backlog_reparse_service.py` 相同:替换 `file_asset_storage.get_bytes`。
- [ ] **Step 2: Run test to verify it fails**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_current_file_reparse.py -q`
Expected: FAIL,`reparse_current_file` 无法导入。
- [ ] **Step 3: Write minimal implementation**
新建 `backend/app/services/in_transit_transfer/current_file_reparse.py`。文件头写明:用途是对当前可用归档做一次本地重解析;依赖 `evidence_sync.sync_source_rows`、`outbound_evidence_sync.sync_outbound_source_rows`、`source_file_status`、`freight_rpa.reports.queries` 的 mark/latest 函数;逻辑是先确认文件和已发布规则,再落档并提交,失败按规格回滚。
```python
@dataclass(frozen=True)
class CurrentReparseResult:
"""一次当前归档重解析的返回。"""
source_code: str
record_kind: str
ok: bool
file_status: str
file_id: int | None
inserted: int = 0
updated: int = 0
skipped: int = 0
sealed_skipped: int = 0
error_code: str | None = None
error_message: str | None = None
def reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult:
"""重解析该来源当前最新可用归档并提交。
核心逻辑:先取 latest usable 文件。没有文件抛 CURRENT_REPARSE_NO_FILE。
有文件则调用既有 sync_*_source_rows。返回 None 表示没有已发布规则,抛
CURRENT_REPARSE_NO_PROFILE,不写 parse_failed。结构错误回滚后 mark_*_parse_failure
并单独提交。其他异常只回滚,不标解析失败。成功路径由 sync 函数里的
movement_file_version 写版本戳,本函数不拼 sha256: 前缀。
Args:
source_code: 来源实例编码。
record_kind: inbound 或 outbound。
now: 落档与新鲜度判定时刻。
Returns:
CurrentReparseResult。结构错误和其他落档异常时 ok 为 False。
Raises:
ValidationError: record_kind 不是 inbound 或 outbound。
AppError: TRANSFER.CURRENT_REPARSE_NO_FILE 或 TRANSFER.CURRENT_REPARSE_NO_PROFILE,HTTP 422。
"""
```
函数体按这个顺序写:
1. `kind = record_kind.strip()`。不在 `{"inbound", "outbound"}` 时 `raise ValidationError("record_kind must be inbound or outbound")`。
2. 出站用 `latest_usable_outbound_file(source_code, now=now)`,入站用 `latest_usable_inbound_file(source_code, now=now)`。结果是 `None` 时抛 `AppError(code="TRANSFER.CURRENT_REPARSE_NO_FILE", message="no usable archive file", http_status=422, details={"source_code": source_code, "record_kind": kind})`。
3. `try` 里调用落档。出站:`sync_outbound_source_rows(source_code=source_code, now=now)`。入站:`sync_source_rows(source_code=source_code, deps=get_transfer_dependencies(), business_date=business_date_now(), now=now)`。
4. 返回值是 `None`:抛 `AppError(code="TRANSFER.CURRENT_REPARSE_NO_PROFILE", message="no published parsing profile", http_status=422, details={"source_code": source_code, "record_kind": kind})`。此时还没有 commit。
5. `db.session.commit()`。再用 `resolve_source_file_status(source_code=source_code, record_kind=kind)` 填 `file_status`。返回 `ok=True` 和 outcome 的四个计数、`file_id=file_view.file_id`。
6. `except MovementFileSchemaError as exc`:`db.session.rollback()`,然后 `mark_outbound_parse_failure` 或 `mark_inbound_parse_failure`。`error_message` 取 `getattr(exc, "message", "") or str(exc)` 后截到 2000 字符(`AppError` 的 `str()` 可能是空串,行级原因在 `message` 里,例如 `missing_invoice_no`)。`error_code=exc.code`。`db.session.commit()` 只提交失败标记。再投影状态,返回 `ok=False`、同样的 `error_code` / `error_message`、计数全 0。
7. `except AppError`:原样抛出(第 4 步的无规则错误不能被下面的通用分支吃掉)。
8. `except Exception as exc`:`db.session.rollback()`,不调用 mark。投影状态后返回 `ok=False`、`error_code="TRANSFER.CURRENT_REPARSE_FAILED"`、`error_message=str(exc)[:500]`、计数全 0。
`sync_outbound_source_rows` 和 `sync_source_rows` 必须是本模块的顶层 import。非结构异常测试打桩的是 `app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows`。不要 import `trigger_inbound_rpa` 或 `trigger_outbound_rpa`。
- [ ] **Step 4: Run test to verify it passes**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_current_file_reparse.py -q`
Expected: PASS。
- [ ] **Step 5: Stage changes**
```bash
git add backend/app/services/in_transit_transfer/current_file_reparse.py backend/tests/services/in_transit_transfer/test_current_file_reparse.py
```
---
### Task 2: HTTP 入口
**Files:**
- Modify: `backend/app/api/in_transit_transfer/__init__.py`(放在 `retry_source_rpa_api` 前面)
- Modify: `backend/tests/api/test_in_transit_transfer_api.py`
- Test: `backend/tests/api/test_in_transit_transfer_api.py`
**Interfaces:**
- Consumes: `reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult`
- Produces: `POST /api/in-transit-transfer/sources/<source_code>/reparse`。body `{"record_kind": "inbound"|"outbound"}`,缺省 `inbound`。成功 envelope 的 `data` 是 `CurrentReparseResult` 的字段。无文件、无规则由服务抛出的 `AppError` 变成 422。
- [ ] **Step 1: Write the failing test**
在 `test_in_transit_transfer_api.py` 增加:
```python
def test_reparse_current_without_file_returns_422(client, admin_headers):
# [断言意图] 没有出站归档时重解析是 422,不是 202 抓取中。
response = client.post(
f"{API_PREFIX}/sources/DSV360_AWSDU/reparse",
headers=admin_headers,
json={"record_kind": "outbound"},
)
assert response.status_code == 422
assert response.get_json()["error"]["code"] == "TRANSFER.CURRENT_REPARSE_NO_FILE"
def test_reparse_current_forbidden(client, unauthorized_headers):
# [断言意图] 无调拨权限不能重解析。
response = client.post(
f"{API_PREFIX}/sources/DSV360_AWSDU/reparse",
headers=unauthorized_headers,
json={"record_kind": "inbound"},
)
assert response.status_code == 403
```
使用该文件已有的 `admin_headers` 和 `unauthorized_headers`。
- [ ] **Step 2: Run test to verify it fails**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py::test_reparse_current_without_file_returns_422 tests/api/test_in_transit_transfer_api.py::test_reparse_current_forbidden -q`
Expected: FAIL,路由 404。
- [ ] **Step 3: Write minimal implementation**
在 `retry_source_rpa_api` 之前增加路由。不要修改 `retry_source_rpa_api` 的函数体。
```python
@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,
})
```
更新该 API 模块文件头的路由说明,加上这条 POST。`datetime` 若文件顶部未导入,沿用文件里已有的导入方式(`retry_source_rpa_api` 已使用 `datetime.utcnow()`,不要重复导入)。
- [ ] **Step 4: Run test to verify it passes**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py::test_reparse_current_without_file_returns_422 tests/api/test_in_transit_transfer_api.py::test_reparse_current_forbidden tests/services/in_transit_transfer/test_current_file_reparse.py -q`
Expected: PASS。
- [ ] **Step 5: Stage changes**
```bash
git add backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_in_transit_transfer_api.py
```
---
### Task 3: 来源卡按钮与四语文案
**Files:**
- Modify: `frontend/src/features/chat/types/transfer.types.ts`
- Modify: `frontend/src/features/chat/api/transfer.api.ts`
- Modify: `frontend/src/features/chat/api/transfer.api.spec.ts`
- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue`
- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`
- Modify: `frontend/src/features/chat/components/messages/TransferMessageView.vue`
- Modify: `frontend/src/locales/zh-CN/chat.json`
- Modify: `frontend/src/locales/zh-TW/chat.json`
- Modify: `frontend/src/locales/en/chat.json`
- Modify: `frontend/src/locales/th/chat.json`
- Modify: `frontend/src/locales/zh-CN/errors.json`
- Modify: `frontend/src/locales/zh-TW/errors.json`
- Modify: `frontend/src/locales/en/errors.json`
- Modify: `frontend/src/locales/th/errors.json`
- Test: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`、`frontend/src/features/chat/api/transfer.api.spec.ts`
**Interfaces:**
- Consumes: `POST /api/in-transit-transfer/sources/{sourceCode}/reparse`
- Produces: `reparseCurrentFile(sourceCode: string, recordKind: TransferRecordKind): Promise<TransferCurrentReparseResult>`。`TransferCurrentReparseResult` 字段与 Task 2 的 `data` 相同。
- [ ] **Step 1: Write the failing test**
在 `transfer.api.spec.ts` 旁路现有 `retryTransferSourceRpa` 用例增加:
```typescript
it('当前文件重解析 POST reparse,body 只有 record_kind', () => {
reparseCurrentFile('DSV360_AWSDU', 'outbound');
const calls = vi.mocked(requestJson).mock.calls;
expect(calls[0][0]).toBe('/api/in-transit-transfer/sources/DSV360_AWSDU/reparse');
expect(JSON.parse(String((calls[0][1] as RequestInit).body))).toEqual({ record_kind: 'outbound' });
});
```
按该文件已有的 `requestJson` mock 写法调整 `calls` 的取法。断言 body 里没有 `file_id`。
在 `TransferSourceSelectCard.spec.ts` 顶部、组件 import 之前增加 mock:
```typescript
const transferApiMocks = vi.hoisted(() => ({
listEvidenceFiles: vi.fn(),
reparseCurrentFile: vi.fn(),
}));
vi.mock('../../api/transfer.api', () => transferApiMocks);
```
新增用例:
```typescript
it('只在清单第一行显示重新解析,点击不发出 retry', async () => {
transferApiMocks.listEvidenceFiles.mockResolvedValue([
{ file_id: 25, original_filename: 'current.xlsx', created_at: '2026-10-21T10:00:00', sha256: 'abc', file_size: 10, presigned_url: 'https://files.example/current' },
{ file_id: 9, original_filename: 'older.xlsx', created_at: '2026-10-20T10:00:00', sha256: 'def', file_size: 10, presigned_url: 'https://files.example/older' },
]);
transferApiMocks.reparseCurrentFile.mockResolvedValue({
source_code: 'DBS-AWSBI', record_kind: 'inbound', ok: true, file_status: 'ready',
file_id: 25, inserted: 2, updated: 0, skipped: 0, sealed_skipped: 0,
error_code: null, error_message: null,
});
const wrapper = mount(TransferSourceSelectCard, {
props: { sources: readySources, transferTypes: defaultTransferTypes },
global: { plugins: [i18n] },
});
await wrapper.find('[data-testid="transfer-source-status-DBS-AWSBI"]').trigger('click');
await flushPromises();
const buttons = wrapper.findAll('[data-testid="transfer-evidence-reparse-DBS-AWSBI-inbound"]');
expect(buttons).toHaveLength(1);
await buttons[0].trigger('click');
expect(transferApiMocks.reparseCurrentFile).toHaveBeenCalledWith('DBS-AWSBI', 'inbound');
expect(wrapper.emitted('retry')).toBeUndefined();
expect(wrapper.emitted('reparsed')).toBeTruthy();
});
```
`flushPromises` 用 `import { flushPromises } from '@vue/test-utils'`。若现有 mount 助手已经包了 props,沿用那个助手,不要另写一套来源数据。
- [ ] **Step 2: Run test to verify it fails**
Run: `npx vitest run src/features/chat/api/transfer.api.spec.ts src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`
工作目录:`frontend/`。
Expected: FAIL,`reparseCurrentFile` 不存在,按钮找不到。
- [ ] **Step 3: Write minimal implementation**
`transfer.types.ts` 在 `TransferEvidenceFile` 后增加:
```typescript
export interface TransferCurrentReparseResult {
source_code: string;
record_kind: TransferRecordKind;
ok: boolean;
file_status: TransferSourceFileStatus['file_status'];
file_id: number | null;
inserted: number;
updated: number;
skipped: number;
sealed_skipped: number;
error_code: string | null;
error_message: string | null;
}
```
`transfer.api.ts` 在 `listEvidenceFiles` 后增加 `reparseCurrentFile`。JSDoc 写明:只重放当前最新归档;body 只有 `record_kind`;不触发 RPA。
```typescript
export const reparseCurrentFile = (
sourceCode: string,
recordKind: TransferRecordKind,
) =>
requestJson<TransferCurrentReparseResult>(
`${BASE}/sources/${encodeURIComponent(sourceCode)}/reparse`,
{
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ record_kind: recordKind }),
},
);
```
`TransferSourceSelectCard.vue`:
- import 改为 `listEvidenceFiles, reparseCurrentFile`。
- `defineEmits` 增加 `reparsed: []`。
- 增加 `reparsingKey = ref<string | null>(null)`。
- 清单 `v-for` 改成 `(file, index) in evidenceFilesOf(...)`。
- 仅当 `index === 0` 时,在预览链接前放按钮:
```vue
<button
v-if="index === 0"
type="button"
class="font-bold text-brand-700 disabled:opacity-50"
:disabled="reparsingKey === evidenceKey(source.source_code, stream.record_kind)"
:data-testid="`transfer-evidence-reparse-${source.source_code}-${stream.record_kind}`"
@click="reparseEvidence(source.source_code, stream.record_kind)"
>{{ t('chat.transfer.reparseCurrentFile') }}</button>
```
`reparseEvidence` 的 JSDoc 写明:调用 `reparseCurrentFile`,不 emit `retry`。成功且 `ok` 时 `success` 提示新增/更新数,并重新 `listEvidenceFiles` 写回 `evidenceByKey`,然后 `emit('reparsed')`。`ok === false` 时 `notifyError` 显示 `error_message`,同样刷新清单和 `emit('reparsed')`,让解析失败状态回到芯片上。抛错时只 `notifyError`。
`TransferMessageView.vue` 的来源卡增加 `@reparsed="transfer.loadSources()"`。不要改 `onSourceRetry`。
四份 `chat.json` 的 `chat.transfer` 里,紧挨 `previewEvidence` 增加:
| key | zh-CN | zh-TW | en | th |
| --- | --- | --- | --- | --- |
| `reparseCurrentFile` | 重新解析 | 重新解析 | Reparse | แยกวิเคราะห์ซ้ำ |
| `reparseCurrentFileDone` | 已重新解析:新增 {inserted},更新 {updated} | 已重新解析:新增 {inserted},更新 {updated} | Reparsed: {inserted} inserted, {updated} updated | แยกวิเคราะห์ซ้ำแล้ว: เพิ่ม {inserted} อัปเดต {updated} |
四份 `errors.json` 的 `TRANSFER.*` 段增加:
| key | zh-CN | zh-TW | en | th |
| --- | --- | --- | --- | --- |
| `TRANSFER.CURRENT_REPARSE_NO_FILE` | 当前没有可重新解析的归档文件。 | 目前沒有可重新解析的歸檔檔案。 | No archived file is available to reparse. | ไม่มีไฟล์ที่เก็บถาวรให้แยกวิเคราะห์ซ้ำ |
| `TRANSFER.CURRENT_REPARSE_NO_PROFILE` | 当前证据流没有已发布的解析规则。 | 目前證據流沒有已發布的解析規則。 | This evidence stream has no published parsing profile. | สตรีมหลักฐานนี้ไม่มีโปรไฟล์การแยกวิเคราะห์ที่เผยแพร่แล้ว |
更新 `TransferSourceSelectCard.vue` 文件头依赖,写上 `reparseCurrentFile`。函数 `reparseEvidence` 上方按项目 JSDoc 写用途、参数、返回值。
- [ ] **Step 4: Run test to verify it passes**
Run: `npx vitest run src/features/chat/api/transfer.api.spec.ts src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`
工作目录:`frontend/`。
Expected: PASS。既有来源卡用例仍然通过。若 mock 替换了整个 `transfer.api` 导致其他用例缺导出,只补那些用例实际会调用的导出,不要改断言去迁就 mock。
- [ ] **Step 5: Stage changes**
```bash
git add frontend/src/features/chat/types/transfer.types.ts frontend/src/features/chat/api/transfer.api.ts frontend/src/features/chat/api/transfer.api.spec.ts frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts frontend/src/features/chat/components/messages/TransferMessageView.vue frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json frontend/src/locales/zh-CN/errors.json frontend/src/locales/zh-TW/errors.json frontend/src/locales/en/errors.json frontend/src/locales/th/errors.json
```
---
### Task 4: 文档
**Files:**
- Modify: `docs/features/in-transit-transfer/technical.md`(来源 API 表,约第 70 行 `retry-rpa` 那一行之后)
- Modify: `docs/funclist.md`(「来源重试合并触发与知情范围确认」那一行之后)
**Interfaces:**
- Consumes: Task 2 的路由和两个错误码。
- Produces: 文档与代码一致。无新代码。
- [ ] **Step 1: Update the API table**
在 `technical.md` 的来源路由表,`POST /sources/{source_code}/retry-rpa` 下一行增加:
`POST /sources/{source_code}/reparse`:重解析当前最新可用归档(body `record_kind`,缺省 inbound;不接受 file_id;不触发 RPA)。成功 200,`ok/file_status/file_id/inserted/updated/skipped/sealed_skipped`。无文件 422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。无已发布规则 422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`,不标 parse_failed。结构失败 200 `ok: false` 且文件为 `parse_failed`。其他异常 200 `ok: false`,不标 parse_failed。与待匹配 `POST /backlog/pending-match/reparse` 不是同一条链路。
- [ ] **Step 2: Update the feature list**
在 `funclist.md` 来源重试行后增加一行:
「当前归档重新解析(2026-10-21)」已实现。来源卡证据清单第一行「重新解析」调用 `POST /sources/{source_code}/reparse`,只重放该流入站或出站的最新可用归档并幂等落档,不触发 RPA,不删除档行。↻ 仍是重新抓取。待匹配「清空并重新解析」仍是整桶重建。
- [ ] **Step 3: Stage changes**
```bash
git add docs/features/in-transit-transfer/technical.md docs/funclist.md docs/superpowers/specs/2026-10-21-transfer-current-file-reparse-design.md docs/superpowers/plans/2026-10-21-transfer-current-file-reparse.md
```
@@ -0,0 +1,29 @@
# 调拨来源选择:按证据流显示状态、重试与下载
日期:2026-10-19
对话已确认的界面与范围。实施计划:`docs/superpowers/plans/2026-10-19-transfer-evidence-stream-ui.md`。
## 目的
操作员在来源选择卡上能看出每个来源实例的入站、出站是否各自就绪,并只重试当前调拨类型还缺的那条证据流。下载仍是一个按钮,压缩包内按记录类型分目录。
## 已定决策
- 状态粒度是来源实例 × 记录类型。不拆来源行,不做「部分就绪」。
- 不新增调拨类型字段,不改调拨类型表单。入站还是出站,读该类型已有的范围规则:字段为 `record_kind`(表单下拉里的「记录类型」)的那几条,值里的 `inbound` / `outbound`。
- 一条类型没有「记录类型」规则时,入站和出站都要。规则里只写了其中一种,就只要那一种。来源卡、批量重试、下载、圈档都读这一结果,不看类型编码。
- 来源行只显示当前调拨类型声明的证据流。缺报表配置时状态为「未配置」。
- 行形态:`DSV360_AWSBI_BYAWSCMH01 [入站 √就绪 ↻] [出站 ⟳抓取中]`。重试是括号内的 `↻`,可读名称「重试入站」或「重试出站」。抓取中不显示 `↻`。行上不出现「重试」「文件」。
- 点状态字展开该流当天清单:文件名、抓取时间、sha256、文件大小、预览、下载。不解析 Excel,不新增行数字段。
- 选择条仍是三个按钮。下载文案为「下载证据文件」。压缩包名 `evidence-files-<n>.zip`,路径 `inbound/<source_code>/<filename>` 与 `outbound/<source_code>/<filename>`,只打包当前类型所需且已就绪的文件。
- 批量重试仍是一个按钮。按当前调拨类型的 `record_kinds`,只重试尚未就绪、且不是抓取中、且已配置的流。行上的 `↻` 可对已就绪的流强制重试。
- 确认匹配:该来源每一条所需流为 `ready` 或 `no_data` 才可提交。混合选择沿用披露条,并写明记录类型。
- 圈档固定条件里的 `record_kind='inbound'` 改为 `record_kinds_of(该类型的范围规则)`。没有类型对象的调用方显式只圈入站。
## 不做
- 不拆两个下载按钮,不拆两个批量按钮。
- 不为出站复制来源实例行。
- 不把整张卡改成大触控尺寸。
- 不改货代 RPA Worker、排程和回调契约。
@@ -0,0 +1,32 @@
# 当前归档重新解析
日期:2026-10-21
来源选择卡在文件已经落地之后,需要一条不触发 RPA 的重新解析入口。出站回调落档失败(例如 `file_version` 超长)会被桥接吞掉,文件状态仍是就绪,异动档没有行。只在 `parse_failed` 上重试,覆盖不到这种情况。↻ 继续表示重新抓取。
## 行为
- 入站和出站各自有「重新解析」。当天该流已有可用归档时可以点,状态是就绪或解析失败都可以。
- 只解析该流当前最新一份可用归档(`created_at`、`id` 倒序第一条,与 `latest_usable_*_file` 相同),并幂等写入异动档。不写 RPA trigger。
- 请求不接受 `file_id`。服务端自己取最新一份,避免清单过期时重放历史文件。
- 同一份文件再解析一次:摘要未变则跳过已有档行,不另插一行。
- 没有可用归档:422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。
- 有归档但没有已发布的对应 purpose 规则:422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`。不把文件标成解析失败。规则缺失不是文件错误。
- 结构校验失败(`MovementFileSchemaError`):回滚档行,把 `parse_failed` 写到当前文件,HTTP 200,`ok: false`,`file_status: parse_failed`,带 `error_message`。
- 其他异常(数据库截断、连接失败):回滚,不标解析失败,HTTP 200,`ok: false`,`error_message` 为异常文本。文件状态保持原投影。
- 成功:HTTP 200,`ok: true`,返回 `inserted` / `updated` / `skipped` / `sealed_skipped` 和解析后的 `file_status`。审计沿用落档函数已有的 `TRANSFER_EVIDENCE_SYNCED`,不另造事件。
- `file_version` 只经 `movement_file_version`。本入口不自己拼版本戳。
## 界面
展开来源卡某条证据流的当天清单后,只有第一行(当前文件)在预览、下载旁边显示「重新解析」。更旧的归档只有预览和下载。
点下去调用 `POST /api/in-transit-transfer/sources/{source_code}/reparse`,body 只有 `{ "record_kind": "inbound" | "outbound" }`。成功或 `ok: false` 后刷新来源状态和这一条清单。↻ 与 `POST /sources/{source_code}/retry-rpa` 的行为不变。
待匹配「清空并重新解析」(`POST /backlog/pending-match/reparse`)仍是改规则后的整桶重建,本入口不调用它,也不删除已有档行。
## 不做
- 不改 ↻、批量重试、Worker、回调契约。
- 不给历史归档逐份重放。
- 不在部署或进程启动时自动补解析已经落地的文件。
@@ -232,6 +232,7 @@
<label><span>{{ t('admin.freightRpa.reportGroup') }}</span><el-input v-model="outboundConfig.report_path_json.report_group" required /></label>
<label><span>{{ t('admin.freightRpa.reportName') }}</span><el-input v-model="outboundConfig.report_path_json.report_name" required /></label>
<div class="subsection full">{{ t('admin.freightRpa.queryParameters') }}</div>
<p class="section-hint full">{{ t('admin.freightRpa.outboundQueryParametersHint') }}</p>
<div v-for="(parameter, index) in outboundConfig.query_parameters_json" :key="`outbound-${index}-${parameter.name}`" class="parameter-row full">
<el-input v-model="parameter.name" :placeholder="t('admin.freightRpa.parameterName')" />
<el-select v-model="parameter.mode"><el-option value="single" :label="t('admin.freightRpa.single')" /><el-option value="multi_text" :label="t('admin.freightRpa.multiText')" /><el-option value="multi_select" :label="t('admin.freightRpa.multiSelect')" /></el-select>
@@ -20,6 +20,7 @@ const BACKEND_MOVEMENT_FIELD_CODES = [
'doc_no', 'line_no', 'in_out_flag', 'material_code', 'material_name',
'warehouse_code', 'storage_code', 'lot_no', 'quantity', 'movement_date', 'unit',
'line_seq', 'specification', 'order_type', 'odm_id', 'odm_name', 'carton_id', 'pallet_id',
'external_doc_no', 'external_line_no',
] as const;
const LABEL_MAPS: Record<string, Record<string, string>> = {
@@ -1,23 +1,34 @@
/**
* features/admin/modules/schedules/SchedulesPage.vue
* 定时任务管理独立页面壳层。路由:/admin/schedules
* 依赖:useSchedulesAdmin、schedules.context、子 panel/overlays 组件。
* 逻辑:reactive + provide admin 上下文;onMounted 加载列表。
* 用途:定时任务管理独立页面壳层。路由:/admin/schedules
* 依赖:useSchedulesAdmin、schedules.context、Element Plus、子 panel/overlays。
* 逻辑:reactive + provide admin;ElConfigProvider 包裹 admin-table-section;概览/工作台切换。
*/
<script setup lang="ts">
import { onMounted, provide, reactive } from 'vue';
import { ElConfigProvider } from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import { useSchedulesAdmin } from './composables/useSchedulesAdmin';
import { SCHEDULES_ADMIN_KEY, SCHEDULE_CREATE_MODAL_OPEN_KEY, type SchedulesAdminContextProvided } from './composables/schedules.context';
import {
SCHEDULES_ADMIN_KEY,
SCHEDULE_CREATE_MODAL_OPEN_KEY,
type SchedulesAdminContextProvided,
} from './composables/schedules.context';
import SchedulePageHeader from './components/SchedulePageHeader.vue';
import ScheduleOverviewPanel from './components/ScheduleOverviewPanel.vue';
import ScheduleWorkbenchPanel from './components/ScheduleWorkbenchPanel.vue';
import SchedulesPageOverlays from './components/SchedulesPageOverlays.vue';
const { elementLocale } = useElementProvider();
const adminApi = useSchedulesAdmin();
const admin = reactive(adminApi) as SchedulesAdminContextProvided;
provide(SCHEDULES_ADMIN_KEY, admin);
/** 弹窗 v-if 须绑定原始 ref,避免 reactive 属性赋值破坏 ref 链接 */
provide(SCHEDULE_CREATE_MODAL_OPEN_KEY, adminApi.showScheduleCreateModal);
onMounted(async () => {
await admin.loadAll();
await admin.applyFromRouteQuery();
@@ -25,10 +36,12 @@ onMounted(async () => {
</script>
<template>
<section class="section-gap animate-fade-in-up">
<SchedulePageHeader />
<ScheduleOverviewPanel v-if="admin.scheduleViewMode === 'overview'" />
<ScheduleWorkbenchPanel v-else />
</section>
<SchedulesPageOverlays />
<ElConfigProvider :locale="elementLocale">
<section class="admin-table-section animate-fade-in-up">
<SchedulePageHeader />
<ScheduleOverviewPanel v-if="admin.scheduleViewMode === 'overview'" />
<ScheduleWorkbenchPanel v-else />
</section>
<SchedulesPageOverlays />
</ElConfigProvider>
</template>
@@ -3,7 +3,7 @@
* features/admin/modules/schedules/components/DynamicTaskParamsForm.vue
* 用途:平台任务参数通用表单——按注册表 params_schema 渲染控件并输出统一 job_params。
* 依赖:schedule.api(PlatformTaskDefinition/listAdminPlatformTaskOptions)、vue-i18n。
* 逻辑:ScheduleCreateEditModal 传入选中任务的 definition;本组件只认识控件 type 与
* 逻辑:ScheduleCreateEditDrawer 传入选中任务的 definition;本组件只认识控件 type 与
* options_source,不认识具体任务(红框参数区完全由 schema 决定);
* 高级配置折叠 JSON 与 schema type=json 字段均本地校验,非法时 emit valid=false 阻止保存;
* modelValue 异步回填时同步 _advanced / json 文本(用户已编辑时不覆盖)。
@@ -0,0 +1,472 @@
/**
* features/admin/modules/schedules/components/ScheduleCreateEditDrawer.vue
* 用途:排程新增/编辑右侧抽屉(Element Plus ElDrawer + ElForm)。
* 依赖:schedules.context、ScheduleCronDesigner、DynamicTaskParamsForm、Element Plus。
* 逻辑:替换原居中 Modal;平台 Job 与动态参数区行为不变;ElDrawer resizable 支持左缘拖拽调宽。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ArrowDown, ArrowUp, Plus } from '@element-plus/icons-vue';
import {
ElButton,
ElCheckbox,
ElCollapse,
ElCollapseItem,
ElDivider,
ElDrawer,
ElForm,
ElFormItem,
ElInput,
ElInputNumber,
ElOption,
ElSelect,
ElSpace,
} from 'element-plus';
import { useScheduleCreateModalOpen, useSchedulesAdminContext } from '../composables/schedules.context';
import DynamicTaskParamsForm from './DynamicTaskParamsForm.vue';
import ScheduleCronDesigner from './ScheduleCronDesigner.vue';
const { t } = useI18n();
const admin = useSchedulesAdminContext();
const showCreateModal = useScheduleCreateModalOpen();
const drawerTitle = computed(() => (
admin.scheduleEditingId ? t('admin.schedule.form.editTitle') : t('admin.schedule.form.createTitle')
));
const submitDisabled = computed(() => (
admin.scheduleCreateSaving
|| !admin.scheduleCreateForm.name
|| !admin.scheduleCreateForm.owner_user_id
|| !admin.cronDesigner.isValid
));
/**
* 用户下拉展示名。
* @param user - 用户行
*/
function userLabel(user: { real_name?: string | null; username: string; employee_id?: string | null }): string {
const name = user.real_name || user.username;
return user.employee_id ? `${name}(${user.employee_id})` : name;
}
/**
* 关闭抽屉(提交中忽略,由 ElDrawer 的 close-on 控制)。
*/
function handleClose(): void {
if (!admin.scheduleCreateSaving) admin.closeScheduleCreateModal();
}
</script>
<template>
<ElDrawer
:model-value="showCreateModal"
size="min(720px, 96vw)"
direction="rtl"
resizable
append-to-body
destroy-on-close
:close-on-click-modal="!admin.scheduleCreateSaving"
:close-on-press-escape="!admin.scheduleCreateSaving"
:show-close="!admin.scheduleCreateSaving"
class="schedule-create-drawer"
@close="handleClose"
>
<template #header>
<h3 class="text-lg font-semibold text-primary">{{ drawerTitle }}</h3>
</template>
<ElForm label-position="top" class="schedule-create-form" @submit.prevent>
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
<ElFormItem :label="t('admin.schedule.form.name')" required>
<ElInput
v-model="admin.scheduleCreateForm.name"
:placeholder="t('admin.schedule.form.namePlaceholder')"
/>
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.owner')" required>
<ElSelect
v-model="admin.scheduleCreateForm.owner_user_id"
filterable
class="w-full"
:disabled="admin.users.length === 0"
:placeholder="admin.users.length === 0 ? t('admin.schedule.form.noUsers') : t('admin.schedule.form.selectOwner')"
>
<ElOption
v-for="u in admin.users"
:key="u.id"
:label="userLabel(u)"
:value="u.id"
/>
</ElSelect>
</ElFormItem>
</div>
<ElDivider content-position="left">{{ t('admin.schedule.form.dataSourceConfig') }}</ElDivider>
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
<ElFormItem :label="t('admin.schedule.form.scheduleType')">
<ElSelect v-model="admin.scheduleCreateForm.schedule_type" class="w-full">
<ElOption :label="t('admin.schedule.form.scheduleTypeDataPipeline')" value="data_pipeline" />
<ElOption :label="t('admin.schedule.form.scheduleTypePlatformJob')" value="platform_job" />
</ElSelect>
</ElFormItem>
<ElFormItem
v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'"
:label="t('admin.schedule.form.dataSourceType')"
>
<ElSelect v-model="admin.scheduleCreateForm.data_source_type" class="w-full">
<ElOption :label="t('admin.schedule.form.databaseDirect')" value="database" />
<ElOption :label="t('admin.schedule.form.externalApi')" value="external_api" />
</ElSelect>
</ElFormItem>
<ElFormItem
v-else
:label="t('admin.schedule.form.platformJob')"
>
<ElSelect
v-model="admin.scheduleCreateForm.platform_api_path"
class="w-full"
:placeholder="t('admin.schedule.form.selectPlatformJob')"
@change="admin.handlePlatformJobChange"
>
<ElOption
v-for="job in admin.platformJobs"
:key="job.key"
:label="job.label_key ? t(job.label_key) : (job.label || job.key)"
:value="job.key"
/>
</ElSelect>
</ElFormItem>
</div>
<ElSpace v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'" wrap class="mb-3">
<ElButton
:disabled="admin.scheduleTestLoading || !admin.scheduleEditingId"
:loading="admin.scheduleTestLoading"
@click="admin.handleTestScheduleSql"
>
{{ admin.scheduleTestLoading ? t('admin.schedule.form.querying') : t('admin.schedule.form.testQuery') }}
</ElButton>
<ElButton
:icon="admin.scheduleConfigCollapsed ? ArrowDown : ArrowUp"
@click="admin.scheduleConfigCollapsed = !admin.scheduleConfigCollapsed"
>
{{ admin.scheduleConfigCollapsed ? t('admin.schedule.form.expandConfig') : t('admin.schedule.form.collapseConfig') }}
</ElButton>
</ElSpace>
<div
v-show="admin.scheduleCreateForm.schedule_type === 'data_pipeline' && !admin.scheduleConfigCollapsed"
class="space-y-3"
>
<template v-if="admin.scheduleCreateForm.data_source_type === 'database'">
<ElCollapse model-value="ds">
<ElCollapseItem :title="t('admin.schedule.form.dataSourceSection')" name="ds">
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
<ElFormItem :label="t('admin.schedule.form.dsDbType')">
<ElSelect v-model="admin.scheduleSqlEditForm.ds_db_type" class="w-full">
<ElOption label="SQL Server" value="sqlserver" />
<ElOption label="PostgreSQL" value="postgresql" />
<ElOption label="MySQL" value="mysql" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.dsHost')">
<ElInput v-model="admin.scheduleSqlEditForm.ds_host" :placeholder="t('admin.schedule.form.dsHostPlaceholder')" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.dsPort')">
<ElInput v-model="admin.scheduleSqlEditForm.ds_port" placeholder="1433" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.dsDatabase')">
<ElInput v-model="admin.scheduleSqlEditForm.ds_database" :placeholder="t('admin.schedule.form.dsDatabasePlaceholder')" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.dsUsername')">
<ElInput v-model="admin.scheduleSqlEditForm.ds_username" placeholder="sa" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.dsPassword')">
<ElInput v-model="admin.scheduleSqlEditForm.ds_password" type="password" show-password :placeholder="t('admin.schedule.form.dsPasswordPlaceholder')" />
</ElFormItem>
</div>
<div v-if="admin.scheduleSqlEditForm.ds_db_type === 'sqlserver'" class="grid grid-cols-1 gap-2 sm:grid-cols-3">
<ElFormItem :label="t('admin.schedule.form.dsDriver')">
<ElInput v-model="admin.scheduleSqlEditForm.ds_driver" placeholder="SQL Server" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.dsEncrypt')">
<ElSelect v-model="admin.scheduleSqlEditForm.ds_encrypt" class="w-full" clearable>
<ElOption :label="t('admin.schedule.form.defaultNo')" value="" />
<ElOption label="yes" value="yes" />
<ElOption label="no" value="no" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.dsTrustCert')">
<ElSelect v-model="admin.scheduleSqlEditForm.ds_trust_cert" class="w-full" clearable>
<ElOption :label="t('admin.schedule.form.defaultYes')" value="" />
<ElOption label="yes" value="yes" />
<ElOption label="no" value="no" />
</ElSelect>
</ElFormItem>
</div>
<p class="text-xs text-muted">{{ t('admin.schedule.form.envVarHint', { token: t('admin.schedule.form.envVarToken') }) }}</p>
</ElCollapseItem>
</ElCollapse>
<ElFormItem :label="t('admin.schedule.form.baseFetchSql')">
<ElInput v-model="admin.scheduleSqlEditForm.base_fetch_sql" type="textarea" :rows="6" class="font-mono text-xs" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.fetchWhereConditions')">
<ElInput v-model="admin.scheduleSqlEditForm.fetch_where_conditions" type="textarea" :rows="3" class="font-mono text-xs" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.fetchOrderBy')">
<ElInput v-model="admin.scheduleSqlEditForm.fetch_order_by" class="font-mono text-xs" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.detailSql')">
<ElInput v-model="admin.scheduleSqlEditForm.detail_sql" type="textarea" :rows="4" class="font-mono text-xs" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.writebackSql')">
<ElInput v-model="admin.scheduleSqlEditForm.writeback_sql" type="textarea" :rows="2" class="font-mono text-xs" />
</ElFormItem>
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
<ElFormItem :label="t('admin.schedule.form.rowIdKey')">
<ElInput v-model="admin.scheduleSqlEditForm.row_id_key" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.logPrefix')">
<ElInput v-model="admin.scheduleSqlEditForm.log_prefix" />
</ElFormItem>
</div>
<ElFormItem :label="t('admin.schedule.form.aliasOrder')">
<ElInput v-model="admin.scheduleSqlEditForm.alias_order_str" class="font-mono text-xs" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.detailAliasOrder')">
<ElInput v-model="admin.scheduleSqlEditForm.detail_alias_order_str" class="font-mono text-xs" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.headerLabels')">
<ElInput v-model="admin.scheduleSqlEditForm.header_labels_str" type="textarea" :rows="3" class="font-mono text-xs" />
</ElFormItem>
</template>
<template v-if="admin.scheduleCreateForm.data_source_type === 'external_api'">
<ElFormItem :label="t('admin.schedule.form.apiUrl')">
<ElInput v-model="admin.scheduleSqlEditForm.api_url" placeholder="https://api.example.com/endpoint" />
</ElFormItem>
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
<ElFormItem :label="t('admin.schedule.form.apiMethod')">
<ElSelect v-model="admin.scheduleSqlEditForm.api_method" class="w-full">
<ElOption label="POST" value="POST" />
<ElOption label="GET" value="GET" />
<ElOption label="PUT" value="PUT" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.apiTimeoutSeconds')">
<ElInputNumber :model-value="120" disabled class="w-full" />
</ElFormItem>
</div>
<ElFormItem :label="t('admin.schedule.form.apiHeaders')">
<ElInput v-model="admin.scheduleSqlEditForm.api_headers_str" type="textarea" :rows="2" class="font-mono text-xs" />
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.apiBodyTemplate')">
<ElInput v-model="admin.scheduleSqlEditForm.api_body_template" type="textarea" :rows="3" class="font-mono text-xs" />
</ElFormItem>
</template>
</div>
<div v-if="admin.scheduleCreateForm.schedule_type === 'platform_job'" class="mt-2">
<DynamicTaskParamsForm
v-if="admin.selectedPlatformTaskDefinition"
:definition="admin.selectedPlatformTaskDefinition"
:model-value="admin.scheduleCreateForm.job_params"
:valid="admin.platformJobParamsValid"
@update:model-value="admin.scheduleCreateForm.job_params = $event"
@update:valid="admin.platformJobParamsValid = $event"
/>
<div
v-else-if="admin.platformTaskDefinitionsLoading || admin.platformTaskDefinitionsError"
class="space-y-2 rounded-lg border border-default px-4 py-3 text-sm text-muted"
>
<p>
{{ admin.platformTaskDefinitionsLoading
? t('admin.schedule.form.dynamicParamsLoading')
: t('admin.schedule.form.dynamicParamsLoadFailed') }}
</p>
<ElButton
v-if="admin.platformTaskDefinitionsError && !admin.platformTaskDefinitionsLoading"
size="small"
@click="admin.loadPlatformTaskDefinitions"
>
{{ t('admin.schedule.form.dynamicParamsRetry') }}
</ElButton>
</div>
</div>
<div v-if="admin.scheduleTestResult" class="mt-3 rounded-lg border border-emerald-200 bg-emerald-50/40 p-3">
<div class="mb-2 flex items-center justify-between">
<h4 class="text-sm font-bold text-emerald-900">{{ t('admin.schedule.testRun.queryResult') }}</h4>
<ElButton link type="primary" @click="admin.scheduleTestResult = null">✕</ElButton>
</div>
<p class="mb-2 text-xs text-emerald-600">
{{ t('admin.schedule.testRun.resultSummary', { total: admin.scheduleTestResult.total, showing: admin.scheduleTestResult.showing }) }}
</p>
<div class="mb-2 overflow-x-auto rounded border border-emerald-200 bg-surface">
<table class="w-full text-xs">
<thead class="bg-emerald-50">
<tr>
<th
v-for="col in admin.scheduleTestResult.columns"
:key="col"
class="whitespace-nowrap px-3 py-2 text-left font-semibold text-emerald-800"
>{{ col }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="(row, ri) in admin.scheduleTestResult.rows"
:key="ri"
class="border-t border-emerald-100"
>
<td
v-for="col in admin.scheduleTestResult.columns"
:key="col"
class="whitespace-nowrap px-3 py-1.5 text-secondary"
>{{ row[col] }}</td>
</tr>
</tbody>
</table>
</div>
<details>
<summary class="cursor-pointer text-xs font-semibold text-emerald-700">{{ t('admin.schedule.testRun.viewGeneratedSql') }}</summary>
<pre class="admin-pre-block admin-pre-block--sql">{{ admin.scheduleTestResult.sql }}</pre>
</details>
</div>
<template v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'">
<ElDivider />
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
<ElFormItem :label="t('admin.schedule.form.agentLabel')">
<ElSelect
v-model="admin.scheduleCreateForm.dify_agent_id"
class="w-full"
clearable
:disabled="admin.agents.length === 0"
:placeholder="admin.agents.length === 0 ? t('admin.schedule.form.noAgents') : t('admin.schedule.form.agentDisabled')"
>
<ElOption
v-for="a in admin.agents"
:key="a.id"
:label="`${a.name}${t('admin.schedule.form.agentOptionId', { id: a.dify_app_id?.slice(0, 8) || a.id })}`"
:value="a.id"
/>
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('admin.schedule.form.waitSeconds')">
<ElInputNumber v-model="admin.scheduleCreateForm.wait_seconds" :min="0" class="w-full" />
</ElFormItem>
</div>
<ElFormItem>
<ElCheckbox v-model="admin.scheduleCreateForm.kb_sync_enabled">
{{ t('admin.schedule.form.kbSyncEnabled') }}
</ElCheckbox>
<p class="mt-1 text-xs text-muted">{{ t('admin.schedule.form.kbSyncHint') }}</p>
</ElFormItem>
<ElFormItem
v-if="admin.scheduleCreateForm.kb_sync_enabled"
:label="t('admin.schedule.form.kbGroup')"
>
<ElSelect
v-model="admin.scheduleCreateForm.kb_group_id"
class="w-full"
:disabled="admin.kbGroups.length === 0"
:placeholder="admin.kbGroups.length === 0 ? t('admin.schedule.form.noKbGroups') : t('admin.schedule.form.selectKbGroup')"
>
<ElOption
v-for="group in admin.kbGroups"
:key="group.id"
:label="group.name"
:value="group.id"
/>
</ElSelect>
</ElFormItem>
<ElFormItem
v-if="admin.scheduleCreateForm.dify_agent_id"
:label="t('admin.schedule.form.difySystemPrompt')"
>
<p class="mb-2 text-xs text-muted">{{ t('admin.schedule.form.difySystemPromptHint') }}</p>
<ElInput
v-model="admin.scheduleSqlEditForm.dify_system_prompt"
type="textarea"
:rows="5"
class="font-mono text-sm"
:placeholder="t('admin.schedule.form.difySystemPromptPlaceholder')"
/>
</ElFormItem>
</template>
<ElDivider content-position="left">{{ t('admin.schedule.form.cronTitle') }}</ElDivider>
<p class="mb-3 text-xs text-muted">{{ t('admin.schedule.form.cronHint') }}</p>
<ScheduleCronDesigner
:designer="admin.cronDesigner"
:format-date-time="admin.formatDateTime"
/>
<ElFormItem class="mt-4">
<ElCheckbox v-model="admin.scheduleCreateForm.notify_enabled">
{{ t('admin.schedule.form.notifyEnabled') }}
</ElCheckbox>
</ElFormItem>
<ElFormItem v-if="admin.scheduleCreateForm.notify_enabled" :label="t('admin.schedule.form.selectNotifyUsers')">
<ElSelect
v-model="admin.scheduleCreateForm.notify_user_ids_json"
multiple
filterable
class="w-full"
:placeholder="t('admin.schedule.form.selectNotifyUsers')"
>
<ElOption
v-for="u in admin.users"
:key="u.id"
:label="userLabel(u)"
:value="u.id"
/>
</ElSelect>
</ElFormItem>
<ElFormItem>
<ElCheckbox v-model="admin.scheduleCreateForm.enabled">
{{ t('admin.schedule.form.enableOnCreate') }}
</ElCheckbox>
</ElFormItem>
</ElForm>
<template #footer>
<div class="flex justify-end gap-3">
<ElButton :disabled="admin.scheduleCreateSaving" @click="admin.closeScheduleCreateModal">
{{ t('admin.schedule.form.cancel') }}
</ElButton>
<ElButton
type="primary"
:icon="Plus"
:loading="admin.scheduleCreateSaving"
:disabled="submitDisabled"
@click="admin.createSchedule"
>
{{ admin.scheduleCreateSaving
? t('admin.schedule.form.saving')
: (admin.scheduleEditingId
? t('admin.schedule.form.saveChanges')
: t('admin.schedule.form.createSchedule')) }}
</ElButton>
</div>
</template>
</ElDrawer>
</template>
<style scoped>
.schedule-create-form :deep(.el-form-item) {
margin-bottom: 14px;
}
.schedule-create-form :deep(.el-divider) {
margin: 12px 0 16px;
}
</style>
@@ -1,500 +0,0 @@
<script setup lang="ts">
/**
* features/admin/modules/schedules/components/ScheduleCreateEditModal.vue
* 用途:定时任务创建/编辑弹窗。
* 依赖:schedules.context、ScheduleCronDesigner、DynamicTaskParamsForm。
* 逻辑:平台 Job 下拉展示由 registry 返回的 label_key 经 $t() 渲染;平台任务参数区由
* DynamicTaskParamsForm 按 params_schema 通用渲染,本组件不再按任务硬编码 v-if。
*/
import { ChevronDown, ChevronUp, Plus } from 'lucide-vue-next';
import { useScheduleCreateModalOpen, useSchedulesAdminContext } from '../composables/schedules.context';
import DynamicTaskParamsForm from './DynamicTaskParamsForm.vue';
import ScheduleCronDesigner from './ScheduleCronDesigner.vue';
const admin = useSchedulesAdminContext();
const showCreateModal = useScheduleCreateModalOpen();
</script>
<template>
<Teleport to="body">
<div v-if="showCreateModal" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-h-[92vh] max-w-3xl min-h-0">
<div class="flex shrink-0 items-center justify-between border-b border-subtle px-8 py-6">
<h3 class="text-2xl font-bold tracking-tight text-primary">{{ admin.scheduleEditingId ? $t('admin.schedule.form.editTitle') : $t('admin.schedule.form.createTitle') }}</h3>
<button
class="rounded-full p-2 text-muted transition hover-surface-soft hover:text-secondary"
@click="admin.closeScheduleCreateModal"
>
✕
</button>
</div>
<div class="min-h-0 flex-1 space-y-5 overflow-y-auto px-8 py-6">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.name') }}</label>
<input v-model="admin.scheduleCreateForm.name" class="input-field !text-sm !leading-5" :placeholder="$t('admin.schedule.form.namePlaceholder')" />
</div>
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.owner') }}</label>
<div class="relative">
<input
v-model="admin.scheduleOwnerQuery"
type="text"
class="input-field !text-sm !leading-5"
:placeholder="admin.users.length === 0 ? $t('admin.schedule.form.noUsers') : $t('admin.schedule.form.selectOwner')"
:disabled="admin.users.length === 0"
@focus="admin.scheduleOwnerDropdownOpen = true"
@input="admin.handleScheduleOwnerInput"
@blur="admin.scheduleCloseOwnerDropdown"
/>
<div
v-if="admin.scheduleOwnerDropdownOpen && admin.users.length > 0"
class="admin-dropdown max-h-60 w-full overflow-y-auto"
>
<button
v-for="u in admin.filteredOwnerUsers"
:key="u.id"
type="button"
class="flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition hover:bg-surface-soft"
:class="admin.scheduleCreateForm.owner_user_id === u.id ? 'bg-blue-50/50' : ''"
@mousedown.prevent="admin.selectScheduleOwner(u.id)"
>
<span class="text-secondary">{{ u.real_name || u.username }}{{ u.employee_id ? '(' + u.employee_id + ')' : '' }}</span>
</button>
<div v-if="admin.filteredOwnerUsers.length === 0" class="px-3 py-2 text-sm text-muted">
{{ $t('admin.wecom.noData') }}
</div>
</div>
</div>
</div>
</div>
<!-- SQL Config Panel -->
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4">
<div class="mb-3 space-y-3">
<h4 class="text-base font-bold text-primary">{{ $t('admin.schedule.form.dataSourceConfig') }}</h4>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div>
<label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-muted">
{{ $t('admin.schedule.form.scheduleType') }}
</label>
<select
v-model="admin.scheduleCreateForm.schedule_type"
class="input-field w-full !text-sm !leading-5"
>
<option value="data_pipeline">{{ $t('admin.schedule.form.scheduleTypeDataPipeline') }}</option>
<option value="platform_job">{{ $t('admin.schedule.form.scheduleTypePlatformJob') }}</option>
</select>
</div>
<div v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'">
<label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-muted">
{{ $t('admin.schedule.form.dataSourceType') }}
</label>
<select
v-model="admin.scheduleCreateForm.data_source_type"
class="input-field w-full !text-sm !leading-5"
>
<option value="database">{{ $t('admin.schedule.form.databaseDirect') }}</option>
<option value="external_api">{{ $t('admin.schedule.form.externalApi') }}</option>
</select>
</div>
<div v-else>
<label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-muted">
{{ $t('admin.schedule.form.platformJob') }}
</label>
<select
v-model="admin.scheduleCreateForm.platform_api_path"
class="input-field w-full !text-sm !leading-5"
@change="admin.handlePlatformJobChange"
>
<option :value="null">{{ $t('admin.schedule.form.selectPlatformJob') }}</option>
<option v-for="job in admin.platformJobs" :key="job.key" :value="job.key">
{{ job.label_key ? $t(job.label_key) : job.label || job.key }}
</option>
</select>
</div>
</div>
<div
v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'"
class="flex flex-wrap items-center gap-2 sm:shrink-0"
>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap disabled:cursor-not-allowed disabled:opacity-60"
:disabled="admin.scheduleTestLoading || !admin.scheduleEditingId"
@click="admin.handleTestScheduleSql"
>
{{ admin.scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
</button>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap"
@click="admin.scheduleConfigCollapsed = !admin.scheduleConfigCollapsed"
>
<ChevronDown v-if="admin.scheduleConfigCollapsed" class="h-3.5 w-3.5 shrink-0" />
<ChevronUp v-else class="h-3.5 w-3.5 shrink-0" />
{{ admin.scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
</button>
</div>
</div>
<div
v-show="admin.scheduleCreateForm.schedule_type === 'data_pipeline' && !admin.scheduleConfigCollapsed"
class="space-y-3"
>
<template v-if="admin.scheduleCreateForm.data_source_type === 'database'">
<!-- 数据源配置 -->
<details class="rounded-xl border border-default bg-surface" open>
<summary class="cursor-pointer px-4 py-2.5 text-sm font-semibold text-secondary hover:bg-surface-soft rounded-xl">{{ $t('admin.schedule.form.dataSourceSection') }}</summary>
<div class="space-y-3 px-4 pb-4 pt-2">
<div class="grid grid-cols-2 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.dsDbType') }}</label>
<select v-model="admin.scheduleSqlEditForm.ds_db_type" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200">
<option value="sqlserver">SQL Server</option>
<option value="postgresql">PostgreSQL</option>
<option value="mysql">MySQL</option>
</select>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.dsHost') }}</label>
<input v-model="admin.scheduleSqlEditForm.ds_host" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" :placeholder="$t('admin.schedule.form.dsHostPlaceholder')" />
</div>
</div>
<div class="grid grid-cols-4 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.dsPort') }}</label>
<input v-model="admin.scheduleSqlEditForm.ds_port" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="1433" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.dsDatabase') }}</label>
<input v-model="admin.scheduleSqlEditForm.ds_database" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" :placeholder="$t('admin.schedule.form.dsDatabasePlaceholder')" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.dsUsername') }}</label>
<input v-model="admin.scheduleSqlEditForm.ds_username" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="sa" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.dsPassword') }}</label>
<input v-model="admin.scheduleSqlEditForm.ds_password" type="password" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" :placeholder="$t('admin.schedule.form.dsPasswordPlaceholder')" />
</div>
</div>
<div v-if="admin.scheduleSqlEditForm.ds_db_type === 'sqlserver'" class="grid grid-cols-3 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.dsDriver') }}</label>
<input v-model="admin.scheduleSqlEditForm.ds_driver" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="SQL Server" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.dsEncrypt') }}</label>
<select v-model="admin.scheduleSqlEditForm.ds_encrypt" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200">
<option value="">{{ $t('admin.schedule.form.defaultNo') }}</option>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.dsTrustCert') }}</label>
<select v-model="admin.scheduleSqlEditForm.ds_trust_cert" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200">
<option value="">{{ $t('admin.schedule.form.defaultYes') }}</option>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
</div>
</div>
<p class="text-xs text-muted">{{ $t('admin.schedule.form.envVarHint', { token: $t('admin.schedule.form.envVarToken') }) }}</p>
</div>
</details>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.baseFetchSql') }}</label>
<textarea
v-model="admin.scheduleSqlEditForm.base_fetch_sql"
class="w-full min-h-[160px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.fetchWhereConditions') }}</label>
<textarea
v-model="admin.scheduleSqlEditForm.fetch_where_conditions"
class="w-full min-h-[80px] rounded-xl border border-amber-200 bg-amber-50/30 p-3 text-xs leading-relaxed text-secondary font-mono focus:border-amber-300 focus:outline-none focus:ring-1 focus:ring-amber-200 resize-y"
></textarea>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.fetchOrderBy') }}</label>
<input v-model="admin.scheduleSqlEditForm.fetch_order_by" class="w-full input-field px-3 py-2 text-xs font-mono text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.detailSql') }}</label>
<textarea
v-model="admin.scheduleSqlEditForm.detail_sql"
class="w-full min-h-[120px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.writebackSql') }}</label>
<textarea
v-model="admin.scheduleSqlEditForm.writeback_sql"
class="w-full min-h-[48px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.rowIdKey') }}</label>
<input v-model="admin.scheduleSqlEditForm.row_id_key" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.logPrefix') }}</label>
<input v-model="admin.scheduleSqlEditForm.log_prefix" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
</div>
<div class="hidden">
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.aliasOrder') }}</label>
<input v-model="admin.scheduleSqlEditForm.alias_order_str" class="w-full input-field px-3 py-2 text-xs font-mono text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.detailAliasOrder') }}</label>
<input v-model="admin.scheduleSqlEditForm.detail_alias_order_str" class="w-full input-field px-3 py-2 text-xs font-mono text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.headerLabels') }}</label>
<textarea
v-model="admin.scheduleSqlEditForm.header_labels_str"
class="w-full min-h-[100px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
</template>
<!-- 外部API模式 -->
<template v-if="admin.scheduleCreateForm.data_source_type === 'external_api'">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.apiUrl') }}</label>
<input v-model="admin.scheduleSqlEditForm.api_url" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" placeholder="https://api.example.com/endpoint" />
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.apiMethod') }}</label>
<select v-model="admin.scheduleSqlEditForm.api_method" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200">
<option value="POST">POST</option>
<option value="GET">GET</option>
<option value="PUT">PUT</option>
</select>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.apiTimeoutSeconds') }}</label>
<input type="number" :value="120" class="w-full input-field px-3 py-2 text-sm text-secondary focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200" disabled />
</div>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.apiHeaders') }}</label>
<textarea
v-model="admin.scheduleSqlEditForm.api_headers_str"
class="w-full min-h-[60px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.apiBodyTemplate') }}</label>
<textarea
v-model="admin.scheduleSqlEditForm.api_body_template"
class="w-full min-h-[80px] input-field p-3 text-xs leading-relaxed text-secondary font-mono focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-200 resize-y"
></textarea>
</div>
</template>
</div>
<!-- 平台任务参数区:完全由注册表 params_schema 决定,无任务级 v-if。
外层仅按 schedule_type 判定(同步、必然为真),不依赖异步 definitions;
定义解析完成前显示加载提示,完成后立即渲染 DynamicTaskParamsForm(含库存源)。 -->
<div v-if="admin.scheduleCreateForm.schedule_type === 'platform_job'" class="mt-3">
<DynamicTaskParamsForm
v-if="admin.selectedPlatformTaskDefinition"
:definition="admin.selectedPlatformTaskDefinition"
:model-value="admin.scheduleCreateForm.job_params"
:valid="admin.platformJobParamsValid"
@update:model-value="admin.scheduleCreateForm.job_params = $event"
@update:valid="admin.platformJobParamsValid = $event"
/>
<div v-else-if="admin.platformTaskDefinitionsLoading || admin.platformTaskDefinitionsError" class="space-y-2 rounded-xl border border-blue-200 bg-blue-50/40 px-4 py-3 text-sm text-muted">
<p>{{ admin.platformTaskDefinitionsLoading
? $t('admin.schedule.form.dynamicParamsLoading')
: $t('admin.schedule.form.dynamicParamsLoadFailed') }}</p>
<button
v-if="admin.platformTaskDefinitionsError && !admin.platformTaskDefinitionsLoading"
type="button"
class="btn-secondary btn-sm"
@click="admin.loadPlatformTaskDefinitions"
>
{{ $t('admin.schedule.form.dynamicParamsRetry') }}
</button>
</div>
</div>
<div v-if="admin.scheduleTestResult" class="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
<div class="mb-3 flex items-center justify-between">
<h4 class="text-sm font-bold text-emerald-900">{{ $t('admin.schedule.testRun.queryResult') }}</h4>
<div class="flex items-center gap-3">
<span class="text-xs text-emerald-600">{{ $t('admin.schedule.testRun.resultSummary', { total: admin.scheduleTestResult.total, showing: admin.scheduleTestResult.showing }) }}</span>
<button class="rounded-full p-1 text-emerald-400 transition hover:bg-emerald-100 hover:text-emerald-600" @click="admin.scheduleTestResult = null">✕</button>
</div>
</div>
<div class="mb-2 overflow-x-auto rounded-xl border border-emerald-200 bg-surface">
<table class="w-full text-xs">
<thead class="bg-emerald-50">
<tr>
<th v-for="col in admin.scheduleTestResult.columns" :key="col" class="whitespace-nowrap px-3 py-2 text-left font-semibold text-emerald-800">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in admin.scheduleTestResult.rows" :key="ri" class="border-t border-emerald-100">
<td v-for="col in admin.scheduleTestResult.columns" :key="col" class="whitespace-nowrap px-3 py-1.5 text-secondary">{{ row[col] }}</td>
</tr>
</tbody>
</table>
</div>
<details class="mt-2">
<summary class="cursor-pointer text-xs font-semibold text-emerald-700 hover:text-emerald-900">{{ $t('admin.schedule.testRun.viewGeneratedSql') }}</summary>
<pre class="admin-pre-block admin-pre-block--sql">{{ admin.scheduleTestResult.sql }}</pre>
</details>
</div>
</div>
<div v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'" class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.agentLabel') }}</label>
<div class="relative">
<select v-model="admin.scheduleCreateForm.dify_agent_id" class="input-field appearance-none pr-10 !text-sm !leading-5" :disabled="admin.agents.length === 0">
<option :value="null">{{ admin.agents.length === 0 ? $t('admin.schedule.form.noAgents') : $t('admin.schedule.form.agentDisabled') }}</option>
<option v-for="a in admin.agents" :key="a.id" :value="a.id">{{ a.name }}{{ $t('admin.schedule.form.agentOptionId', { id: a.dify_app_id?.slice(0, 8) || a.id }) }}</option>
</select>
<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
<svg class="h-4 w-4 text-muted" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clip-rule="evenodd"/></svg>
</div>
</div>
</div>
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.waitSeconds') }}</label>
<input v-model.number="admin.scheduleCreateForm.wait_seconds" type="number" min="0" class="input-field !text-sm !leading-5" placeholder="300" />
</div>
</div>
<div v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'" class="rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
<label class="flex items-center gap-2 text-sm font-semibold text-secondary">
<input v-model="admin.scheduleCreateForm.kb_sync_enabled" type="checkbox" class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-300" />
{{ $t('admin.schedule.form.kbSyncEnabled') }}
</label>
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.kbSyncHint') }}</p>
<div v-if="admin.scheduleCreateForm.kb_sync_enabled" class="mt-3">
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.kbGroup') }}</label>
<select v-model="admin.scheduleCreateForm.kb_group_id" class="input-field !text-sm !leading-5" :disabled="admin.kbGroups.length === 0">
<option :value="null">{{ admin.kbGroups.length === 0 ? $t('admin.schedule.form.noKbGroups') : $t('admin.schedule.form.selectKbGroup') }}</option>
<option v-for="group in admin.kbGroups" :key="group.id" :value="group.id">{{ group.name }}</option>
</select>
</div>
</div>
<div v-if="admin.scheduleCreateForm.dify_agent_id" class="rounded-2xl border border-indigo-200 bg-indigo-50/40 p-4">
<div class="mb-2">
<label class="block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.difySystemPrompt') }}</label>
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.difySystemPromptHint') }}</p>
</div>
<textarea
v-model="admin.scheduleSqlEditForm.dify_system_prompt"
class="input-field min-h-[140px] p-3 text-sm font-mono resize-y border-indigo-200"
:placeholder="$t('admin.schedule.form.difySystemPromptPlaceholder')"
></textarea>
</div>
<ScheduleCronDesigner
:designer="admin.cronDesigner"
:format-date-time="admin.formatDateTime"
/>
<div class="input-field px-3 py-2.5">
<div class="flex flex-col gap-2 md:flex-row md:items-center">
<label class="inline-flex shrink-0 items-center gap-2 text-sm text-secondary">
<input v-model="admin.scheduleCreateForm.notify_enabled" type="checkbox" class="h-4 w-4 rounded text-blue-600" />
{{ $t('admin.schedule.form.notifyEnabled') }}
</label>
<div v-if="admin.scheduleCreateForm.notify_enabled" class="relative flex-1">
<div
class="min-h-[38px] input-field px-3 py-2 text-sm flex flex-wrap gap-1.5 items-center focus-within:border-blue-300 focus-within:ring-1 focus-within:ring-blue-200"
>
<span
v-for="uid in admin.scheduleCreateForm.notify_user_ids_json"
:key="uid"
class="inline-flex items-center gap-1 rounded-lg bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700"
>
{{ admin.getUserName(uid) }}
<button
type="button"
class="ml-0.5 text-blue-400 hover:text-blue-600"
@click.stop="admin.removeNotifyUser(uid)"
>✕</button>
</span>
<input
v-model="admin.scheduleNotifyUserQuery"
type="text"
class="min-w-[120px] flex-1 border-0 bg-transparent p-0 text-sm text-secondary outline-none focus:ring-0"
:placeholder="$t('admin.schedule.form.selectNotifyUsers')"
@focus="admin.scheduleNotifyDropdownOpen = true"
@input="admin.scheduleNotifyDropdownOpen = true"
@blur="admin.scheduleCloseNotifyDropdown"
/>
</div>
<div
v-if="admin.scheduleNotifyDropdownOpen"
class="admin-dropdown max-h-60 w-full overflow-y-auto"
>
<button
v-for="u in admin.filteredNotifyUsers"
:key="u.id"
type="button"
class="flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left text-sm transition hover:bg-surface-soft"
:class="admin.scheduleCreateForm.notify_user_ids_json.includes(u.id) ? 'bg-blue-50/50' : ''"
@mousedown.prevent="admin.toggleNotifyUser(u.id)"
>
<input
type="checkbox"
class="pointer-events-none h-3.5 w-3.5 rounded text-blue-600"
:checked="admin.scheduleCreateForm.notify_user_ids_json.includes(u.id)"
tabindex="-1"
readonly
/>
<span class="text-secondary">{{ u.real_name || u.username }}{{ u.employee_id ? '(' + u.employee_id + ')' : '' }}</span>
</button>
<div v-if="admin.filteredNotifyUsers.length === 0" class="px-3 py-2 text-sm text-muted">
{{ $t('admin.wecom.noData') }}
</div>
</div>
</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-surface-soft/40 px-4 py-3">
<label class="inline-flex cursor-pointer items-center gap-2 text-sm text-secondary">
<input v-model="admin.scheduleCreateForm.enabled" type="checkbox" class="admin-checkbox" />
{{ $t('admin.schedule.form.enableOnCreate') }}
</label>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted relative z-10 pointer-events-auto justify-end gap-3 px-8 py-5">
<button
type="button"
class="btn-secondary"
@click="admin.closeScheduleCreateModal"
>
{{ $t('admin.schedule.form.cancel') }}
</button>
<button
type="button"
class="btn-primary inline-flex items-center gap-2 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="admin.scheduleCreateSaving || !admin.scheduleCreateForm.name || !admin.scheduleCreateForm.owner_user_id || !admin.cronDesigner.isValid"
@click="admin.createSchedule"
>
<Plus class="h-4 w-4 shrink-0" />
{{ admin.scheduleCreateSaving ? $t('admin.schedule.form.saving') : (admin.scheduleEditingId ? $t('admin.schedule.form.saveChanges') : $t('admin.schedule.form.createSchedule')) }}
</button>
</div>
</div>
</div>
</Teleport>
</template>
@@ -1,153 +1,350 @@
/**
* features/admin/modules/schedules/components/ScheduleOverviewPanel.vue
* 定时任务概览模式:统计卡片与任务卡片网格。
* 依赖:schedules.context、lucide-vue-next。
* 逻辑:inject admin;展示 schedules 列表与快捷操作。
* 用途:排程管理概览——紧凑统计条 + 筛选 + ElTable + 前端分页 + 批量启停。
* 依赖:schedules.context、Element Plus、ScheduleTask。
* 逻辑:全量 schedules 前端过滤/排序/分页;行点击进工作台;操作列 stop 冒泡。
*/
<script setup lang="ts">
import { Edit3, FlaskConical, Plus, Power, PowerOff, Rocket, Settings2, Trash2 } from 'lucide-vue-next';
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Search } from '@element-plus/icons-vue';
import {
ElButton,
ElInput,
ElLoading,
ElOption,
ElPagination,
ElSelect,
ElSpace,
ElTable,
ElTableColumn,
ElTag,
} from 'element-plus';
import type { ScheduleTask } from '@/shared/types/schedule.types';
import { useSchedulesAdminContext } from '../composables/schedules.context';
const vLoading = ElLoading.directive;
const { t } = useI18n();
const admin = useSchedulesAdminContext();
type StatusFilter = 'all' | 'enabled' | 'disabled';
type TypeFilter = 'all' | 'data_pipeline' | 'platform_job';
type SortKey = 'name' | 'last_run_at' | 'next_run_at' | '';
const searchKeyword = ref('');
const statusFilter = ref<StatusFilter>('all');
const typeFilter = ref<TypeFilter>('all');
const sortKey = ref<SortKey>('name');
const sortDir = ref<'asc' | 'desc'>('asc');
const currentPage = ref(1);
const pageSize = ref(20);
const pageSizeOptions = [10, 20, 50, 100];
const selectedRows = ref<ScheduleTask[]>([]);
const bulkBusy = ref(false);
/**
* 按关键词/状态/类型过滤后的排程列表,再按当前排序键排序。
*/
const filteredSchedules = computed(() => {
const keyword = searchKeyword.value.trim().toLowerCase();
const matched = admin.schedules.filter((item) => {
const haystack = `${item.name} ${item.schedule_no} ${item.cron_expr} ${item.owner_username || ''}`.toLowerCase();
const matchesKeyword = !keyword || haystack.includes(keyword);
const matchesStatus = statusFilter.value === 'all'
|| (statusFilter.value === 'enabled' && item.enabled)
|| (statusFilter.value === 'disabled' && !item.enabled);
const matchesType = typeFilter.value === 'all' || item.schedule_type === typeFilter.value;
return matchesKeyword && matchesStatus && matchesType;
});
if (!sortKey.value) return matched;
return [...matched].sort((a, b) => {
let result = 0;
if (sortKey.value === 'name') {
result = a.name.localeCompare(b.name, undefined, { numeric: true });
} else if (sortKey.value === 'last_run_at') {
result = (Date.parse(a.last_run_at || '') || 0) - (Date.parse(b.last_run_at || '') || 0);
} else {
result = (Date.parse(a.next_run_at || '') || 0) - (Date.parse(b.next_run_at || '') || 0);
}
return sortDir.value === 'asc' ? result : -result;
});
});
const pagedSchedules = computed(() => {
const start = (currentPage.value - 1) * pageSize.value;
return filteredSchedules.value.slice(start, start + pageSize.value);
});
const tableEmptyText = computed(() => (
admin.schedules.length === 0 ? t('admin.schedule.emptyList') : t('admin.schedule.filters.emptyResult')
));
watch([searchKeyword, statusFilter, typeFilter], () => {
currentPage.value = 1;
});
/**
* 同步表格勾选行,供批量启停使用。
* @param rows - 当前选中的排程行
*/
function onSelectionChange(rows: ScheduleTask[]): void {
selectedRows.value = rows;
}
/**
* 表头自定义排序写回本地 sortKey/sortDir。
* @param payload - Element sort-change 载荷
*/
function onSortChange(payload: { prop: string | null; order: string | null }): void {
const prop = payload.prop;
if (prop === 'name' || prop === 'last_run_at' || prop === 'next_run_at') {
sortKey.value = payload.order ? prop : '';
sortDir.value = payload.order === 'ascending' ? 'asc' : 'desc';
}
}
/**
* 行点击进入工作台(操作列需 stop 冒泡)。
* @param row - 被点击的排程
*/
function onRowClick(row: ScheduleTask): void {
void admin.openScheduleRunSubmenu(row.id);
}
/**
* 批量将选中排程设为启用或停用。
* @param enabled - true 启用,false 停用
*/
async function bulkSetEnabled(enabled: boolean): Promise<void> {
if (selectedRows.value.length === 0 || bulkBusy.value) return;
bulkBusy.value = true;
try {
for (const row of selectedRows.value) {
if (row.enabled !== enabled) {
await admin.setScheduleEnabled(row.id, enabled);
}
}
selectedRows.value = [];
} finally {
bulkBusy.value = false;
}
}
</script>
<template>
<div class="admin-panel-lg p-6 shadow-sm">
<div class="mb-5 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
<div class="admin-stat-tile px-4 py-3">
<div class="text-xl font-bold text-primary">{{ admin.schedules.length }}</div>
<div class="text-sm text-muted">{{ $t('admin.schedule.stats.total') }}</div>
<div>
<div class="schedule-stats-bar">
<div class="schedule-stat">
<span class="schedule-stat__value">{{ admin.schedules.length }}</span>
<span class="schedule-stat__label">{{ t('admin.schedule.stats.total') }}</span>
</div>
<div class="admin-stat-tile px-4 py-3">
<div class="text-xl font-bold text-primary">{{ admin.scheduleEnabledCount }}</div>
<div class="text-sm text-muted">{{ $t('admin.schedule.stats.enabled') }}</div>
<div class="schedule-stat">
<span class="schedule-stat__value">{{ admin.scheduleEnabledCount }}</span>
<span class="schedule-stat__label">{{ t('admin.schedule.stats.enabled') }}</span>
</div>
<div class="admin-stat-tile px-4 py-3">
<div class="text-xl font-bold text-primary">{{ admin.scheduleDisabledCount }}</div>
<div class="text-sm text-muted">{{ $t('admin.schedule.stats.disabled') }}</div>
<div class="schedule-stat">
<span class="schedule-stat__value">{{ admin.scheduleDisabledCount }}</span>
<span class="schedule-stat__label">{{ t('admin.schedule.stats.disabled') }}</span>
</div>
<div class="admin-stat-tile px-4 py-3">
<div class="text-xl font-bold text-primary">{{ admin.scheduleRunningCount }}</div>
<div class="text-sm text-muted">{{ $t('admin.schedule.stats.running') }}</div>
<div class="schedule-stat">
<span class="schedule-stat__value">{{ admin.scheduleRunningCount }}</span>
<span class="schedule-stat__label">{{ t('admin.schedule.stats.running') }}</span>
</div>
</div>
<div class="admin-panel p-4">
<div class="mb-3 flex items-center justify-between">
<h4 class="text-lg font-bold text-primary">{{ $t('admin.schedule.sectionOverview') }}</h4>
<span class="text-xs text-muted">{{ $t('admin.schedule.switchByCard') }}</span>
</div>
<div v-if="admin.scheduleLoading" class="py-8 text-center text-sm text-muted">{{ $t('admin.schedule.loading') }}</div>
<div v-else class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3 auto-rows-fr">
<div class="admin-panel p-4 transition-colors hover:border-brand-300 h-full min-h-[260px] flex flex-col">
<div class="mb-3 flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-xl bg-brand-50 text-brand-600">
<Settings2 class="h-4 w-4" />
</div>
<div class="font-semibold text-primary">{{ $t('admin.schedule.addTitle') }}</div>
</div>
<div class="text-sm text-muted">
{{ $t('admin.schedule.addHint') }}
</div>
<div class="mt-auto pt-3">
<button
@click="admin.openScheduleCreateModal"
class="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-brand-600 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
>
<Plus class="h-4 w-4" />
{{ $t('admin.schedule.addButton') }}
</button>
</div>
</div>
<div
v-for="s in admin.schedules"
:key="s.id"
class="flex h-full min-h-[260px] flex-col admin-panel p-4 transition hover:border-blue-200 hover:bg-surface-soft"
>
<div
class="w-full shrink-0 cursor-pointer rounded-lg text-left outline-none focus-visible:ring-2 focus-visible:ring-brand-400"
role="button"
tabindex="0"
@click="admin.openScheduleRunSubmenu(s.id)"
@keydown.enter.prevent="admin.openScheduleRunSubmenu(s.id)"
@keydown.space.prevent="admin.openScheduleRunSubmenu(s.id)"
>
<div class="min-h-[96px]">
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="truncate text-base font-semibold text-primary">{{ s.name }}</div>
<div class="mt-0.5 truncate text-xs text-muted" :title="s.schedule_no">{{ s.schedule_no }}</div>
</div>
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="s.enabled ? 'bg-emerald-100 text-emerald-700' : 'bg-surface-strong text-secondary'">
{{ s.enabled ? $t('admin.schedule.enabled') : $t('admin.schedule.disabled') }}
</span>
</div>
<div class="mt-2 text-sm text-muted">Cron:{{ s.cron_expr }}</div>
<div class="mt-1 text-sm text-muted">{{ $t('admin.schedule.owner') }}:{{ s.owner_username || s.owner_user_id }}</div>
</div>
<div class="schedule-filters">
<ElInput
v-model="searchKeyword"
clearable
:prefix-icon="Search"
class="schedule-filter-search"
:placeholder="t('admin.schedule.filters.searchPlaceholder')"
/>
<ElSelect v-model="statusFilter" class="schedule-filter-select" :placeholder="t('admin.schedule.filters.statusAll')">
<ElOption :label="t('admin.schedule.filters.statusAll')" value="all" />
<ElOption :label="t('admin.schedule.enabled')" value="enabled" />
<ElOption :label="t('admin.schedule.disabled')" value="disabled" />
</ElSelect>
<ElSelect v-model="typeFilter" class="schedule-filter-select" :placeholder="t('admin.schedule.filters.typeAll')">
<ElOption :label="t('admin.schedule.filters.typeAll')" value="all" />
<ElOption :label="t('admin.schedule.form.scheduleTypeDataPipeline')" value="data_pipeline" />
<ElOption :label="t('admin.schedule.form.scheduleTypePlatformJob')" value="platform_job" />
</ElSelect>
<ElSpace v-if="selectedRows.length > 0" wrap>
<ElButton :loading="bulkBusy" @click="() => void bulkSetEnabled(true)">
{{ t('admin.schedule.bulk.enable') }} ({{ selectedRows.length }})
</ElButton>
<ElButton :loading="bulkBusy" @click="() => void bulkSetEnabled(false)">
{{ t('admin.schedule.bulk.disable') }} ({{ selectedRows.length }})
</ElButton>
</ElSpace>
</div>
<ElTable
v-loading="admin.scheduleLoading"
class="hx-admin-table"
:data="pagedSchedules"
row-key="id"
:default-sort="{ prop: 'name', order: 'ascending' }"
:empty-text="tableEmptyText"
highlight-current-row
@selection-change="onSelectionChange"
@sort-change="onSortChange"
@row-click="onRowClick"
>
<ElTableColumn type="selection" width="48" reserve-selection />
<ElTableColumn prop="name" :label="t('admin.schedule.table.name')" min-width="160" sortable="custom">
<template #default="{ row }">
<div class="truncate font-medium text-primary" :title="(row as ScheduleTask).name">
{{ (row as ScheduleTask).name }}
</div>
<div class="relative z-10 mt-auto shrink-0 pt-3" @click.stop>
<div class="mb-1 text-sm text-muted">
{{ $t('admin.schedule.lastRun') }}:{{ admin.formatDateTime(s.last_run_at) }}
</div>
<div class="mb-3 text-sm text-muted">
{{ $t('admin.schedule.nextRun') }}:{{ admin.formatDateTime(s.next_run_at) }}
</div>
<div class="flex flex-wrap items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-2 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="admin.openScheduleEditModal(s)"
>
<Edit3 class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.edit') }}
</button>
<button
v-if="!s.enabled"
class="inline-flex items-center gap-1 rounded-xl border border-emerald-200 px-3 py-2 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-50"
@click.stop="admin.setScheduleEnabled(s.id, true)"
>
<Power class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.start') }}
</button>
<button
v-else
class="inline-flex items-center gap-1 rounded-xl border border-amber-200 px-3 py-2 text-xs font-medium text-amber-700 transition-colors hover:bg-amber-50"
@click.stop="admin.setScheduleEnabled(s.id, false)"
>
<PowerOff class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.pause') }}
</button>
<button
class="inline-flex items-center gap-1 rounded-xl border border-blue-200 px-3 py-2 text-xs font-medium text-blue-700 transition-colors hover:bg-blue-50"
@click.stop="admin.runScheduleNow(s.id)"
>
<Rocket class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.run') }}
</button>
<button
v-if="s.schedule_type === 'data_pipeline' && s.data_source_type === 'database'"
class="inline-flex items-center gap-1 rounded-xl border border-violet-200 px-3 py-2 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
@click.stop="admin.openTestRunDialog(s)"
>
<FlaskConical class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.test') }}
</button>
<button
class="inline-flex items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50"
@click.stop="admin.deleteSchedule(s)"
>
<Trash2 class="h-3.5 w-3.5" />
{{ $t('admin.schedule.actions.delete') }}
</button>
</div>
</template>
</ElTableColumn>
<ElTableColumn prop="schedule_no" :label="t('admin.schedule.scheduleNo')" min-width="140">
<template #default="{ row }">
<span class="truncate text-muted" :title="(row as ScheduleTask).schedule_no">
{{ (row as ScheduleTask).schedule_no }}
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.schedule.table.status')" width="100">
<template #default="{ row }">
<ElTag :type="(row as ScheduleTask).enabled ? 'success' : 'info'" effect="light" size="small">
{{ (row as ScheduleTask).enabled ? t('admin.schedule.enabled') : t('admin.schedule.disabled') }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn prop="cron_expr" :label="t('admin.schedule.table.cron')" min-width="120">
<template #default="{ row }">
<code class="schedule-cron">{{ (row as ScheduleTask).cron_expr }}</code>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.schedule.owner')" min-width="100">
<template #default="{ row }">
{{ (row as ScheduleTask).owner_username || (row as ScheduleTask).owner_user_id }}
</template>
</ElTableColumn>
<ElTableColumn prop="last_run_at" :label="t('admin.schedule.lastRun')" min-width="160" sortable="custom">
<template #default="{ row }">{{ admin.formatDateTime((row as ScheduleTask).last_run_at) }}</template>
</ElTableColumn>
<ElTableColumn prop="next_run_at" :label="t('admin.schedule.nextRun')" min-width="160" sortable="custom">
<template #default="{ row }">{{ admin.formatDateTime((row as ScheduleTask).next_run_at) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.schedule.table.actions')" width="280" align="right" fixed="right">
<template #default="{ row }">
<div class="schedule-row-actions" @click.stop>
<ElButton link type="primary" @click="admin.openScheduleEditModal(row as ScheduleTask)">
{{ t('admin.schedule.actions.edit') }}
</ElButton>
<ElButton
v-if="!(row as ScheduleTask).enabled"
link
type="success"
@click="() => void admin.setScheduleEnabled((row as ScheduleTask).id, true)"
>
{{ t('admin.schedule.actions.start') }}
</ElButton>
<ElButton
v-else
link
type="warning"
@click="() => void admin.setScheduleEnabled((row as ScheduleTask).id, false)"
>
{{ t('admin.schedule.actions.pause') }}
</ElButton>
<ElButton link type="primary" @click="() => void admin.runScheduleNow((row as ScheduleTask).id)">
{{ t('admin.schedule.actions.run') }}
</ElButton>
<ElButton
v-if="(row as ScheduleTask).schedule_type === 'data_pipeline' && (row as ScheduleTask).data_source_type === 'database'"
link
type="primary"
@click="admin.openTestRunDialog(row as ScheduleTask)"
>
{{ t('admin.schedule.actions.test') }}
</ElButton>
<ElButton link type="danger" @click="() => void admin.deleteSchedule(row as ScheduleTask)">
{{ t('admin.schedule.actions.delete') }}
</ElButton>
</div>
</div>
<div v-if="admin.schedules.length === 0" class="rounded-xl border border-dashed border-default px-4 py-6 text-center text-sm text-muted">
{{ $t('admin.schedule.emptyList') }}
</div>
</div>
</template>
</ElTableColumn>
</ElTable>
<div v-if="filteredSchedules.length > 0" class="hx-admin-pager">
<ElPagination
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:total="filteredSchedules.length"
:page-sizes="pageSizeOptions"
layout="total, sizes, prev, pager, next"
background
/>
</div>
</div>
</template>
<style scoped>
.schedule-stats-bar {
display: flex;
flex-wrap: wrap;
gap: 16px 32px;
padding: 12px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.schedule-stat {
display: inline-flex;
align-items: baseline;
gap: 8px;
}
.schedule-stat__value {
font-size: 1.125rem;
font-weight: 700;
color: var(--el-text-color-primary);
}
.schedule-stat__label {
font-size: 0.8125rem;
color: var(--el-text-color-secondary);
}
.schedule-filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
padding: 16px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.schedule-filter-search {
width: 16rem;
}
.schedule-filter-select {
width: 10rem;
}
.schedule-cron {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 0.75rem;
}
.schedule-row-actions {
display: inline-flex;
flex-wrap: nowrap;
align-items: center;
justify-content: flex-end;
gap: 0;
white-space: nowrap;
}
.schedule-row-actions :deep(.el-button) {
margin-left: 0;
padding: 0 6px;
}
</style>
@@ -1,46 +1,57 @@
/**
* features/admin/modules/schedules/components/SchedulePageHeader.vue
* 定时任务页顶栏:返回、标题、刷新。
* 依赖:schedules.context、lucide-vue-next。
* 逻辑:inject admin 上下文;概览/工作台模式切换标题与返回按钮。
* 用途:排程管理页表头(KB 式 admin-table-header)。
* 依赖:schedules.context、Element Plus、@element-plus/icons-vue。
* 逻辑:概览显示刷新/新增;工作台显示返回/刷新;由 SchedulesPage 包在 admin-table-section 内。
*/
<script setup lang="ts">
import { ArrowLeft, RefreshCw, Settings2 } from 'lucide-vue-next';
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ArrowLeft, Plus, Refresh } from '@element-plus/icons-vue';
import { ElButton, ElSpace } from 'element-plus';
import { useSchedulesAdminContext } from '../composables/schedules.context';
const { t } = useI18n();
const admin = useSchedulesAdminContext();
const isWorkbench = computed(() => admin.scheduleViewMode === 'workbench');
const title = computed(() => (
isWorkbench.value ? t('admin.schedule.workbenchTitle') : t('admin.schedule.overviewTitle')
));
const subtitle = computed(() => (
isWorkbench.value ? t('admin.schedule.workbenchSubtitle') : t('admin.schedule.overviewSubtitle')
));
</script>
<template>
<div class="admin-panel-lg px-7 py-6 shadow-sm">
<div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div class="flex items-start gap-4">
<button
v-if="admin.scheduleViewMode === 'workbench'"
class="inline-flex h-14 w-14 items-center justify-center admin-panel text-muted transition hover:bg-surface-soft hover:text-secondary"
<div class="admin-table-header admin-table-header--stacked">
<div class="min-w-0 flex-1">
<div class="flex items-start gap-3">
<ElButton
v-if="isWorkbench"
:icon="ArrowLeft"
circle
:aria-label="t('admin.schedule.backToOverview')"
@click="admin.backToScheduleOverview"
>
<ArrowLeft class="h-7 w-7" />
</button>
<div class="flex h-14 w-14 items-center justify-center rounded-2xl bg-blue-50 text-blue-600">
<Settings2 class="h-7 w-7" />
</div>
<div>
<h2 class="text-2xl font-bold tracking-tight text-primary">
{{ admin.scheduleViewMode === 'overview' ? $t('admin.schedule.overviewTitle') : $t('admin.schedule.workbenchTitle') }}
</h2>
<p class="mt-1.5 text-sm text-muted">
{{ admin.scheduleViewMode === 'overview' ? $t('admin.schedule.overviewSubtitle') : $t('admin.schedule.workbenchSubtitle') }}
</p>
/>
<div class="min-w-0">
<h2 class="section-title">{{ title }}</h2>
<p class="section-desc mt-1">{{ subtitle }}</p>
</div>
</div>
<button
class="inline-flex items-center gap-2 admin-panel px-5 py-2.5 text-sm font-semibold text-secondary transition hover:bg-surface-soft"
@click="() => void admin.loadSchedules()"
>
<RefreshCw class="h-5 w-5" />
{{ $t('admin.schedule.refresh') }}
</button>
</div>
<ElSpace wrap>
<ElButton :icon="Refresh" @click="() => void admin.loadSchedules()">
{{ t('admin.schedule.refresh') }}
</ElButton>
<ElButton
v-if="!isWorkbench"
type="primary"
:icon="Plus"
@click="admin.openScheduleCreateModal"
>
{{ t('admin.schedule.addButton') }}
</ElButton>
</ElSpace>
</div>
</template>
@@ -1,23 +1,23 @@
/**
* features/admin/modules/schedules/components/ScheduleWorkbenchPanel.spec.ts
* 用途:断言执行记录页不默认展示原始库存/收料下载;仅企微深链 raw_zip=1 时突出下载入口。
* 用途:断言执行记录页不默认展示原始库存/收料下载;仅企微深链 raw_zip=1 时突出下载入口;
* 方案 C 无左侧排程列表,使用 ElSelect 切换任务。
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
describe('ScheduleWorkbenchPanel run table actions', () => {
const panelPath = resolve(__dirname, 'ScheduleWorkbenchPanel.vue');
const content = readFileSync(panelPath, 'utf8');
it('does not render raw inventory zip download in the run table column', () => {
const panelPath = resolve(__dirname, 'ScheduleWorkbenchPanel.vue');
const content = readFileSync(panelPath, 'utf8');
expect(content).not.toMatch(/downloadScheduleInventoryRawZip\(r\.id\)/);
expect(content).not.toMatch(/downloadScheduleInboundRawZip\(r\.id\)/);
expect(content).not.toMatch(/downloadScheduleOutboundRawZip\(r\.id\)/);
});
it('only shows raw inventory/inbound/outbound download when wecom deep link prompt is active', () => {
const panelPath = resolve(__dirname, 'ScheduleWorkbenchPanel.vue');
const content = readFileSync(panelPath, 'utf8');
expect(content).toMatch(/wecomRawZipPromptRunId/);
expect(content).not.toMatch(/v-if="admin\.expandedScheduleRun\.inventory_raw_zip_available"/);
expect(content).not.toMatch(/v-if="admin\.expandedScheduleRun\.inbound_raw_zip_available"/);
@@ -26,4 +26,14 @@ describe('ScheduleWorkbenchPanel run table actions', () => {
expect(content).toMatch(/downloadScheduleInboundRawZip/);
expect(content).toMatch(/downloadScheduleOutboundRawZip/);
});
it('uses scheme C full-width layout without left schedule card list', () => {
// 无左侧卡片式排程列表(旧 workbench-* 卡片循环)
expect(content).not.toMatch(/workbench-\$\{s\.id\}/);
expect(content).not.toMatch(/lg:grid-cols-\[320px/);
// 顶栏 ElSelect 切换任务
expect(content).toMatch(/ElSelect/);
expect(content).toMatch(/selectedIdModel/);
expect(content).toMatch(/admin\.schedule\.currentTask/);
});
});
@@ -1,441 +1,560 @@
/**
* features/admin/modules/schedules/components/ScheduleWorkbenchPanel.vue
* 定时任务工作台模式:侧边任务列表与运行记录表格。
* 依赖:schedules.context、lucide-vue-next。
* 逻辑:inject admin;筛选/查询运行记录、展开日志详情。
* 用途:排程工作台方案 C——无左栏;顶栏 ElSelect 切换任务;全宽执行记录。
* 依赖:schedules.context、Element Plus、lucide-vue-next(展开区图标)。
* 逻辑:选中任务上下文条 + 紧凑指标 + 筛选 + 运行表;保留企微 raw zip 深链提示。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {
ChevronDown, ChevronUp, Download, Edit3, Eye, FlaskConical, Power, PowerOff, Rocket, Trash2,
ChevronDown, ChevronUp, Download, Eye,
} from 'lucide-vue-next';
import {
ElButton,
ElDatePicker,
ElOption,
ElSelect,
ElSpace,
ElTag,
} from 'element-plus';
import { useSchedulesAdminContext } from '../composables/schedules.context';
const { t } = useI18n();
const admin = useSchedulesAdminContext();
const selectedIdModel = computed({
get: () => admin.selectedScheduleId,
set: (id: number | null) => {
if (id != null) void admin.viewScheduleRuns(id);
},
});
const skippedMetricLabel = computed(() => {
if (admin.isInboundRpaSchedule) return t('admin.schedule.totalSkippedReceipt');
if (admin.isOutboundRpaSchedule) return t('admin.schedule.totalSkippedOutbound');
if (admin.isInventoryRpaSchedule) return t('admin.schedule.totalSkippedInventory');
return t('admin.schedule.totalSkipped');
});
/**
* 顶栏切换排程时的 option 展示文案。
* @param name - 排程名称
* @param scheduleNo - 排程编号
*/
function scheduleOptionLabel(name: string, scheduleNo: string): string {
return `${name} · ${scheduleNo}`;
}
</script>
<template>
<div class="space-y-6">
<div class="grid grid-cols-2 gap-3 admin-panel-lg p-4 shadow-sm md:grid-cols-4 xl:grid-cols-8">
<div class="col-span-2 admin-stat-tile px-4 py-3 xl:col-span-3">
<div class="truncate text-base font-semibold text-primary">{{ admin.selectedSchedule?.name || $t('admin.schedule.noSelection') }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.selectedHint', { time: admin.selectedScheduleLatestRunAt }) }}</div>
<div class="schedule-workbench">
<div class="schedule-workbench__context">
<div class="schedule-workbench__switcher">
<span class="schedule-workbench__label">{{ t('admin.schedule.currentTask') }}</span>
<ElSelect
v-model="selectedIdModel"
filterable
class="schedule-workbench__select"
:placeholder="t('admin.schedule.noSelection')"
>
<ElOption
v-for="s in admin.schedules"
:key="s.id"
:label="scheduleOptionLabel(s.name, s.schedule_no)"
:value="s.id"
/>
</ElSelect>
<template v-if="admin.selectedSchedule">
<ElTag
:type="admin.selectedSchedule.enabled ? 'success' : 'info'"
effect="light"
size="small"
>
{{ admin.selectedSchedule.enabled ? t('admin.schedule.enabled') : t('admin.schedule.disabled') }}
</ElTag>
<code class="schedule-cron">{{ admin.selectedSchedule.cron_expr }}</code>
<div
v-if="admin.showsRpaWorkerStatus"
class="schedule-workbench__worker"
>
<span class="text-muted">{{ t('admin.schedule.rpaWorker.title') }}</span>
<ElTag
v-if="admin.rpaWorkerStatusLoading"
size="small"
type="info"
effect="plain"
>
{{ t('admin.schedule.rpaWorker.loading') }}
</ElTag>
<ElTag
v-else
size="small"
:type="admin.rpaWorkerStatus?.ready ? 'success' : 'danger'"
effect="light"
>
{{ admin.rpaWorkerStatus?.ready ? t('admin.schedule.rpaWorker.online') : t('admin.schedule.rpaWorker.offline') }}
</ElTag>
<span class="text-muted text-xs">
{{ t('admin.schedule.rpaWorker.lastHeartbeat', { time: admin.rpaWorkerLastHeartbeatAt }) }}
</span>
</div>
</template>
</div>
<div class="admin-stat-tile px-4 py-3 text-center">
<div class="text-base font-semibold text-primary">{{ admin.selectedScheduleRuns.length }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.runBatches') }}</div>
<ElSpace v-if="admin.selectedSchedule" wrap>
<ElButton @click="admin.openScheduleEditModal(admin.selectedSchedule)">
{{ t('admin.schedule.actions.edit') }}
</ElButton>
<ElButton
v-if="!admin.selectedSchedule.enabled"
type="success"
plain
@click="() => void admin.setScheduleEnabled(admin.selectedSchedule!.id, true)"
>
{{ t('admin.schedule.actions.start') }}
</ElButton>
<ElButton
v-else
type="warning"
plain
@click="() => void admin.setScheduleEnabled(admin.selectedSchedule!.id, false)"
>
{{ t('admin.schedule.actions.pause') }}
</ElButton>
<ElButton type="primary" plain @click="() => void admin.runScheduleNow(admin.selectedSchedule!.id)">
{{ t('admin.schedule.actions.run') }}
</ElButton>
<ElButton
v-if="admin.selectedSchedule.schedule_type === 'data_pipeline' && admin.selectedSchedule.data_source_type === 'database'"
@click="admin.openTestRunDialog(admin.selectedSchedule)"
>
{{ t('admin.schedule.actions.test') }}
</ElButton>
<ElButton type="danger" plain @click="() => void admin.deleteSchedule(admin.selectedSchedule!)">
{{ t('admin.schedule.actions.delete') }}
</ElButton>
</ElSpace>
</div>
<div class="schedule-stats-bar">
<div class="schedule-stat">
<span class="schedule-stat__value">{{ admin.selectedScheduleRuns.length }}</span>
<span class="schedule-stat__label">{{ t('admin.schedule.runBatches') }}</span>
</div>
<div class="admin-stat-tile px-4 py-3 text-center">
<div class="text-base font-semibold text-primary">{{ admin.selectedScheduleRunMetrics.total }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.totalProcessed') }}</div>
<div class="schedule-stat">
<span class="schedule-stat__value">{{ admin.selectedScheduleRunMetrics.total }}</span>
<span class="schedule-stat__label">{{ t('admin.schedule.totalProcessed') }}</span>
</div>
<div class="admin-stat-tile px-4 py-3 text-center">
<div class="text-base font-semibold text-emerald-700">{{ admin.selectedScheduleRunMetrics.success }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.totalSuccess') }}</div>
<div class="schedule-stat">
<span class="schedule-stat__value text-emerald-700">{{ admin.selectedScheduleRunMetrics.success }}</span>
<span class="schedule-stat__label">{{ t('admin.schedule.totalSuccess') }}</span>
</div>
<div class="admin-stat-tile px-4 py-3 text-center">
<div class="text-base font-semibold text-amber-600">{{ admin.selectedScheduleRunMetrics.skipped }}</div>
<div class="mt-1 text-xs text-muted">{{
admin.isInboundRpaSchedule
? $t('admin.schedule.totalSkippedReceipt')
: admin.isOutboundRpaSchedule
? $t('admin.schedule.totalSkippedOutbound')
: admin.isInventoryRpaSchedule
? $t('admin.schedule.totalSkippedInventory')
: $t('admin.schedule.totalSkipped')
}}</div>
<div class="schedule-stat">
<span class="schedule-stat__value text-amber-600">{{ admin.selectedScheduleRunMetrics.skipped }}</span>
<span class="schedule-stat__label">{{ skippedMetricLabel }}</span>
</div>
<div class="admin-stat-tile px-4 py-3 text-center">
<div class="text-base font-semibold text-rose-600">{{ admin.selectedScheduleRunMetrics.failed }}</div>
<div class="mt-1 text-xs text-muted">{{ $t('admin.schedule.totalFailed') }}</div>
<div class="schedule-stat">
<span class="schedule-stat__value text-rose-600">{{ admin.selectedScheduleRunMetrics.failed }}</span>
<span class="schedule-stat__label">{{ t('admin.schedule.totalFailed') }}</span>
</div>
</div>
<div class="admin-panel-lg p-6 shadow-sm">
<div class="grid grid-cols-1 gap-6 lg:grid-cols-[320px_minmax(0,1fr)]">
<div class="admin-panel-lg p-6 shadow-sm">
<div class="mb-4 flex items-center justify-between">
<h4 class="text-lg font-semibold text-primary">{{ $t('admin.schedule.listTitle') }}</h4>
<span class="text-xs text-muted">{{ $t('admin.schedule.switchByCard') }}</span>
</div>
<div class="space-y-3">
<div
v-for="s in admin.schedules"
:key="`workbench-${s.id}`"
class="w-full cursor-pointer rounded-2xl border px-4 py-4 text-left transition-all"
:class="admin.selectedScheduleId === s.id ? 'border-blue-300 bg-blue-50/60' : 'border-default bg-surface hover:border-blue-200 hover:bg-surface-soft'"
role="button"
tabindex="0"
@click="admin.viewScheduleRuns(s.id)"
@keydown.enter.prevent="admin.viewScheduleRuns(s.id)"
@keydown.space.prevent="admin.viewScheduleRuns(s.id)"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="truncate font-semibold text-primary">{{ s.name }}</div>
<div class="mt-0.5 text-xs text-muted">{{ s.schedule_no }}</div>
<div class="mt-2 flex flex-wrap items-center gap-2">
<button
type="button"
class="inline-flex items-center justify-center rounded-xl border border-default p-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
:title="$t('admin.schedule.actions.edit')"
@click.stop="admin.openScheduleEditModal(s)"
>
<Edit3 class="h-3 w-3" />
</button>
<button
v-if="!s.enabled"
class="inline-flex items-center justify-center rounded-xl border border-emerald-200 p-1.5 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-50"
:title="$t('admin.schedule.actions.start')"
@click.stop="admin.setScheduleEnabled(s.id, true)"
>
<Power class="h-3 w-3" />
</button>
<button
v-else
class="inline-flex items-center justify-center rounded-xl border border-amber-200 p-1.5 text-xs font-medium text-amber-700 transition-colors hover:bg-amber-50"
:title="$t('admin.schedule.actions.pause')"
@click.stop="admin.setScheduleEnabled(s.id, false)"
>
<PowerOff class="h-3 w-3" />
</button>
<button
class="inline-flex items-center justify-center rounded-xl border border-blue-200 p-1.5 text-xs font-medium text-blue-700 transition-colors hover:bg-blue-50"
:title="$t('admin.schedule.actions.run')"
@click.stop="admin.runScheduleNow(s.id)"
>
<Rocket class="h-3 w-3" />
</button>
<button
v-if="s.schedule_type === 'data_pipeline' && s.data_source_type === 'database'"
class="inline-flex items-center justify-center rounded-xl border border-violet-200 p-1.5 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
:title="$t('admin.schedule.actions.test')"
@click.stop="admin.openTestRunDialog(s)"
>
<FlaskConical class="h-3 w-3" />
</button>
<button
class="inline-flex items-center justify-center rounded-xl border border-rose-200 p-1.5 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50"
:title="$t('admin.schedule.actions.delete')"
@click.stop="admin.deleteSchedule(s)"
>
<Trash2 class="h-3 w-3" />
</button>
</div>
</div>
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="s.enabled ? 'bg-emerald-100 text-emerald-700' : 'bg-surface-strong text-secondary'">
{{ s.enabled ? $t('admin.schedule.enabled') : $t('admin.schedule.disabled') }}
</span>
</div>
</div>
</div>
</div>
<div v-if="admin.selectedSchedule" class="schedule-workbench__runs">
<div class="schedule-workbench__runs-head">
<div>
<div v-if="admin.selectedSchedule" class="admin-panel p-4">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<div>
<h3 class="text-lg font-semibold text-primary">{{ $t('admin.schedule.recordsTitle', { name: admin.selectedSchedule.name }) }}</h3>
<p class="mt-1 text-sm text-muted">{{ $t('admin.schedule.recordsSubtitle') }}</p>
</div>
<div
v-if="admin.showsRpaWorkerStatus"
class="inline-flex items-center gap-2 rounded-lg border border-default px-3 py-2 text-xs"
>
<span class="text-muted">{{ $t('admin.schedule.rpaWorker.title') }}</span>
<span
v-if="admin.rpaWorkerStatusLoading"
class="rounded-full bg-surface-soft px-2 py-0.5 text-secondary"
>
{{ $t('admin.schedule.rpaWorker.loading') }}
</span>
<span
v-else
class="rounded-full px-2 py-0.5 font-medium"
:class="admin.rpaWorkerStatus?.ready ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'"
>
{{ admin.rpaWorkerStatus?.ready ? $t('admin.schedule.rpaWorker.online') : $t('admin.schedule.rpaWorker.offline') }}
</span>
<span class="text-muted">
{{ $t('admin.schedule.rpaWorker.lastHeartbeat', { time: admin.rpaWorkerLastHeartbeatAt }) }}
</span>
<span
v-if="!admin.rpaWorkerStatusLoading && admin.rpaWorkerStatus && !admin.rpaWorkerStatus.ready && admin.rpaWorkerStatus.detail_message"
class="max-w-[360px] truncate text-amber-700"
:title="admin.rpaWorkerStatus.detail_message"
>
{{ admin.rpaWorkerStatus.detail_message }}
</span>
</div>
</div>
<div>
<div class="mb-3 flex flex-wrap items-center gap-2 text-xs">
<label class="text-muted">{{ $t('admin.schedule.filterStart') }}</label>
<input type="datetime-local" step="1" v-model="admin.scheduleRunStartedAfter" class="!min-w-0 !w-[170px] !py-1 !px-2 !text-xs rounded-lg border border-default" />
<label class="text-muted">{{ $t('admin.schedule.filterEnd') }}</label>
<input type="datetime-local" step="1" v-model="admin.scheduleRunStartedBefore" class="!min-w-0 !w-[170px] !py-1 !px-2 !text-xs rounded-lg border border-default" />
<select v-model="admin.scheduleRunStatusFilter" class="!min-w-0 !w-[90px] !py-1 !px-2 !text-xs rounded-lg border border-default">
<option v-for="opt in admin.scheduleRunStatusOptions" :key="opt.value" :value="opt.value">
{{ opt.label }}
</option>
</select>
<button
class="inline-flex items-center rounded-lg bg-brand-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-brand-700"
@click="admin.viewScheduleRuns(admin.selectedSchedule.id)"
>
{{ $t('admin.schedule.query') }}
</button>
<button
class="inline-flex items-center rounded-lg border border-default px-2.5 py-1 text-xs font-medium text-secondary hover:bg-surface-soft"
@click="admin.resetScheduleRunFilters(); admin.viewScheduleRuns(admin.selectedSchedule.id)"
>
{{ $t('admin.schedule.reset') }}
</button>
</div>
<div class="admin-table-wrap max-h-[calc(100vh-20rem)] rounded-xl border border-subtle scrollbar-thin">
<table
class="admin-table table-fixed text-xs"
:style="{ minWidth: `${admin.scheduleRunColumnDefs.reduce((sum, col) => sum + col.width, 0)}px` }"
>
<colgroup>
<col
v-for="col in admin.scheduleRunColumnDefs"
:key="col.key"
:style="{
width: `${col.width}px`,
minWidth: `${col.width}px`,
maxWidth: `${col.width}px`,
}"
/>
</colgroup>
<thead class="sticky top-0 z-10 admin-table-sticky-head">
<tr class="text-muted">
<th
v-for="(col, colIndex) in admin.scheduleRunColumnDefs"
:key="col.key"
class="group relative max-w-0 overflow-hidden admin-table-sticky-head px-4 py-3 text-xs font-semibold uppercase select-none"
>
<span class="block truncate pr-2" :title="col.label">{{ col.label }}</span>
<span
class="absolute inset-y-0 -right-1 z-10 w-2 cursor-col-resize"
@mousedown.prevent="admin.startScheduleColResize(colIndex, $event)"
:title="$t('admin.schedule.resizeColumn', { label: col.label })"
></span>
</th>
</tr>
</thead>
<tbody>
<tr v-if="admin.scheduleRunsLoading">
<td colspan="11" class="px-4 py-8 text-center text-sm text-muted">{{ $t('admin.schedule.queryingRuns') }}</td>
</tr>
<tr v-else-if="admin.filteredScheduleRuns.length === 0">
<td colspan="11" class="px-4 py-8 text-center text-sm text-muted">{{ $t('admin.schedule.noRunRecords') }}</td>
</tr>
<tr
v-else
v-for="r in admin.filteredScheduleRuns"
:key="r.id"
class="text-secondary transition"
>
<td class="max-w-0 truncate px-4 py-2.5" :title="r.run_no">{{ r.run_no }}</td>
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.formatDateTime(r.started_at)">{{ admin.formatDateTime(r.started_at) }}</td>
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.formatDateTime(r.finished_at)">{{ admin.formatDateTime(r.finished_at) }}</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<div class="flex min-w-0 items-center gap-1 overflow-hidden">
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="admin.getScheduleRunStatusBadge(r.status).cls">
{{ admin.getScheduleRunStatusBadge(r.status).label }}
</span>
<span v-if="r.error_message" class="min-w-0 truncate text-xs text-muted" :title="r.error_message">...</span>
</div>
</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.total_count }}</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.success_count }}</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.skipped_count ?? 0 }}</td>
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.getScheduleRunFailedCountTitle(r)">
<span>{{ r.failed_count }}</span>
<span
v-if="admin.isScheduleRunExcelExportFailed(r)"
class="ml-1 text-xs font-medium text-amber-600"
>+Excel</span>
</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<span v-if="r.wecom_notified" class="inline-flex max-w-full shrink-0 items-center gap-1 truncate text-xs text-emerald-600" :title="$t('admin.schedule.notified')">
<svg class="h-3.5 w-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>
{{ $t('admin.schedule.notified') }}
</span>
<span v-else-if="r.wecom_notify_error" class="block truncate text-xs text-amber-500" :title="r.wecom_notify_error">{{ $t('admin.schedule.notifyError') }}</span>
<span v-else class="text-xs text-muted">-</span>
</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<div class="flex min-w-0 flex-wrap items-center gap-1 overflow-hidden">
<a
v-if="r.total_count > 0"
href="#"
@click.prevent="admin.downloadScheduleExcel(r.id)"
class="inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-lg border border-default px-2 py-1 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
>
<Download class="h-3 w-3 shrink-0" />
{{ $t('admin.schedule.downloadDetail') }}
</a>
<span v-else class="text-muted">-</span>
</div>
</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<div class="flex min-w-0 items-center overflow-hidden">
<button
v-if="(r.step_logs && r.step_logs.length > 0) || r.dify_execution_snapshot || r.kb_sync_status"
@click="admin.expandedScheduleRunId = admin.expandedScheduleRunId === r.id ? null : r.id"
class="inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-lg border border-blue-200 px-2 py-1 text-xs font-medium text-blue-600 transition-colors hover:bg-blue-50"
>
<Eye class="h-3 w-3 shrink-0" />
{{ $t('admin.schedule.log') }}
<ChevronDown v-if="admin.expandedScheduleRunId !== r.id" class="h-3 w-3 shrink-0" />
<ChevronUp v-else class="h-3 w-3 shrink-0" />
</button>
<span v-else class="text-muted">-</span>
</div>
</td>
</tr>
<tr
v-if="admin.expandedScheduleRun"
:key="'expanded-' + admin.expandedScheduleRunId"
>
<td colspan="11" class="w-full max-w-none px-4 py-3 bg-surface-soft/60">
<div class="min-w-0 w-full max-w-full space-y-3">
<div
v-if="admin.wecomRawZipPromptRunId === admin.expandedScheduleRun.id && admin.expandedScheduleRun.inventory_raw_zip_available"
class="rounded-xl border border-blue-200 bg-blue-50/80 p-4"
>
<p class="text-sm font-medium text-blue-900">{{ $t('admin.schedule.rawInventoryZipWecomHint') }}</p>
<button
type="button"
class="mt-3 inline-flex items-center gap-2 rounded-xl border border-blue-300 bg-surface px-4 py-2 text-sm font-semibold text-blue-700 shadow-sm transition-colors hover:bg-blue-50"
@click="admin.downloadScheduleInventoryRawZip(admin.expandedScheduleRun.id)"
>
<Download class="h-4 w-4 shrink-0" />
{{ $t('admin.schedule.downloadInventoryRawZipPackage') }}
</button>
</div>
<div
v-if="admin.wecomRawZipPromptRunId === admin.expandedScheduleRun.id && admin.expandedScheduleRun.inbound_raw_zip_available"
class="rounded-xl border border-blue-200 bg-blue-50/80 p-4"
>
<p class="text-sm font-medium text-blue-900">{{ $t('admin.schedule.rawInboundZipWecomHint') }}</p>
<button
type="button"
class="mt-3 inline-flex items-center gap-2 rounded-xl border border-blue-300 bg-surface px-4 py-2 text-sm font-semibold text-blue-700 shadow-sm transition-colors hover:bg-blue-50"
@click="admin.downloadScheduleInboundRawZip(admin.expandedScheduleRun.id)"
>
<Download class="h-4 w-4 shrink-0" />
{{ $t('admin.schedule.downloadInboundRawZipPackage') }}
</button>
</div>
<div
v-if="admin.wecomRawZipPromptRunId === admin.expandedScheduleRun.id && admin.expandedScheduleRun.outbound_raw_zip_available"
class="rounded-xl border border-blue-200 bg-blue-50/80 p-4"
>
<p class="text-sm font-medium text-blue-900">{{ $t('admin.schedule.rawOutboundZipWecomHint') }}</p>
<button
type="button"
class="mt-3 inline-flex items-center gap-2 rounded-xl border border-blue-300 bg-surface px-4 py-2 text-sm font-semibold text-blue-700 shadow-sm transition-colors hover:bg-blue-50"
@click="admin.downloadScheduleOutboundRawZip(admin.expandedScheduleRun.id)"
>
<Download class="h-4 w-4 shrink-0" />
{{ $t('admin.schedule.downloadOutboundRawZipPackage') }}
</button>
</div>
<div
v-if="admin.expandedScheduleRun.kb_sync_status"
class="rounded-xl border border-emerald-200 bg-emerald-50/50 p-3 text-xs text-secondary"
>
<div class="font-bold text-emerald-800">{{ $t('admin.schedule.kbSync.title') }}</div>
<div class="mt-1">
<span class="font-semibold text-muted">{{ $t('admin.schedule.kbSync.status') }}:</span>
{{ admin.expandedScheduleRun.kb_sync_status }}
</div>
<div v-if="admin.expandedScheduleRun.kb_document_id" class="mt-1">
<span class="font-semibold text-muted">{{ $t('admin.schedule.kbSync.document') }}:</span>
{{ admin.expandedScheduleRun.kb_document_id }}
</div>
<div v-if="admin.expandedScheduleRun.kb_sync_error" class="mt-1 text-rose-600">
{{ admin.expandedScheduleRun.kb_sync_error }}
</div>
</div>
<div
v-if="admin.expandedScheduleRun.dify_execution_snapshot"
class="rounded-xl border border-indigo-200 bg-indigo-50/50 p-3"
>
<div class="mb-2 flex flex-wrap items-start justify-between gap-x-4 gap-y-1">
<h5 class="min-w-0 text-xs font-bold uppercase text-indigo-800">{{ $t('admin.schedule.difySnapshot.title') }}</h5>
<time
class="shrink-0 whitespace-nowrap text-[10px] text-indigo-600/80"
:title="admin.expandedScheduleRun.dify_execution_snapshot.captured_at || '-'"
>
{{ admin.formatDateTime(admin.expandedScheduleRun.dify_execution_snapshot.captured_at) }}
</time>
</div>
<div v-if="admin.expandedScheduleRun.dify_execution_snapshot.dify_enabled" class="space-y-2 text-xs text-secondary">
<div class="break-words">
<span class="font-semibold text-muted">{{ $t('admin.schedule.difySnapshot.agent') }}:</span>
{{ admin.expandedScheduleRun.dify_execution_snapshot.dify_agent_name || '-' }}
<span class="text-muted">{{ $t('admin.schedule.difySnapshot.agentId', { id: admin.expandedScheduleRun.dify_execution_snapshot.dify_agent_id ?? '-' }) }}</span>
</div>
<div v-if="admin.expandedScheduleRun.dify_execution_snapshot.dify_app_id">
<span class="font-semibold text-muted">{{ $t('admin.schedule.difySnapshot.difyAppId') }}:</span>
{{ admin.expandedScheduleRun.dify_execution_snapshot.dify_app_id }}
</div>
<div>
<span class="mb-1 block font-semibold text-muted">{{ $t('admin.schedule.difySnapshot.systemPrompt') }}:</span>
<pre
v-if="admin.expandedScheduleRun.dify_execution_snapshot.dify_system_prompt"
class="max-h-[240px] overflow-auto whitespace-pre-wrap rounded-lg border border-indigo-100 bg-surface p-3 font-mono text-[11px] leading-relaxed text-primary"
>{{ admin.expandedScheduleRun.dify_execution_snapshot.dify_system_prompt }}</pre>
<span v-else class="text-muted">{{ $t('admin.schedule.difySnapshot.notConfiguredUseDefault') }}</span>
</div>
</div>
<div v-else class="text-xs text-muted">{{ $t('admin.schedule.difySnapshot.notEnabledRun') }}</div>
</div>
<div class="space-y-2">
<div class="flex flex-wrap items-center justify-between gap-2 mb-2">
<h5 class="text-xs font-bold text-secondary uppercase">{{ $t('admin.schedule.runLogs') }}</h5>
<span class="text-xs text-muted">{{ $t('admin.schedule.stepsCount', { count: admin.expandedScheduleRun.step_logs?.length || 0 }) }}</span>
</div>
<div
v-for="(log, li) in admin.expandedScheduleRun.step_logs || []"
:key="li"
class="rounded-xl border p-3"
:class="log.status === 'failed' ? 'border-rose-200 bg-rose-50/40' : 'border-default bg-surface'"
>
<div class="flex items-center gap-2 mb-1">
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold"
:class="(admin.stepStatusMap[log.status] || admin.stepStatusMap.success || { cls: 'bg-surface-soft text-secondary' }).cls">
{{ (admin.stepStatusMap[log.status] || { label: log.status }).label }}
</span>
<span class="text-xs font-semibold text-secondary">{{ admin.stepLabelMap[log.step] || log.step }}</span>
<span v-if="log.row_id" class="text-[10px] text-muted">row_id={{ log.row_id }}</span>
<span v-if="log.duration_ms != null" class="text-[10px] text-muted">{{ log.duration_ms }}ms</span>
</div>
<details v-if="log.detail" class="mt-1">
<summary class="cursor-pointer text-[10px] font-semibold text-muted hover:text-secondary">{{ $t('admin.schedule.viewDetail') }}</summary>
<pre class="admin-pre-block">{{ JSON.stringify(log.detail, null, 2) }}</pre>
</details>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div v-else class="rounded-2xl border border-dashed border-default bg-surface px-4 py-10 text-center text-sm text-muted">
{{ $t('admin.schedule.noSelectionHint') }}
</div>
<h3 class="text-base font-semibold text-primary">
{{ t('admin.schedule.recordsTitle', { name: admin.selectedSchedule.name }) }}
</h3>
<p class="mt-1 text-sm text-muted">{{ t('admin.schedule.recordsSubtitle') }}</p>
</div>
</div>
<div class="schedule-filters">
<ElDatePicker
v-model="admin.scheduleRunStartedAfter"
type="datetime"
value-format="YYYY-MM-DDTHH:mm:ss"
:placeholder="t('admin.schedule.filterStart')"
class="schedule-filter-date"
/>
<ElDatePicker
v-model="admin.scheduleRunStartedBefore"
type="datetime"
value-format="YYYY-MM-DDTHH:mm:ss"
:placeholder="t('admin.schedule.filterEnd')"
class="schedule-filter-date"
/>
<ElSelect
v-model="admin.scheduleRunStatusFilter"
class="schedule-filter-status"
:placeholder="t('admin.schedule.columns.status')"
>
<ElOption
v-for="opt in admin.scheduleRunStatusOptions"
:key="opt.value"
:label="opt.label"
:value="opt.value"
/>
</ElSelect>
<ElButton type="primary" @click="admin.viewScheduleRuns(admin.selectedSchedule.id)">
{{ t('admin.schedule.query') }}
</ElButton>
<ElButton @click="admin.resetScheduleRunFilters(); admin.viewScheduleRuns(admin.selectedSchedule.id)">
{{ t('admin.schedule.reset') }}
</ElButton>
</div>
<div class="admin-table-wrap max-h-[calc(100vh-22rem)] scrollbar-thin">
<table
class="admin-table table-fixed text-xs"
:style="{ minWidth: `${admin.scheduleRunColumnDefs.reduce((sum, col) => sum + col.width, 0)}px` }"
>
<colgroup>
<col
v-for="col in admin.scheduleRunColumnDefs"
:key="col.key"
:style="{
width: `${col.width}px`,
minWidth: `${col.width}px`,
maxWidth: `${col.width}px`,
}"
/>
</colgroup>
<thead class="sticky top-0 z-10 admin-table-sticky-head">
<tr class="text-muted">
<th
v-for="(col, colIndex) in admin.scheduleRunColumnDefs"
:key="col.key"
class="group relative max-w-0 overflow-hidden admin-table-sticky-head px-4 py-3 text-xs font-semibold uppercase select-none"
>
<span class="block truncate pr-2" :title="col.label">{{ col.label }}</span>
<span
class="absolute inset-y-0 -right-1 z-10 w-2 cursor-col-resize"
@mousedown.prevent="admin.startScheduleColResize(colIndex, $event)"
:title="t('admin.schedule.resizeColumn', { label: col.label })"
></span>
</th>
</tr>
</thead>
<tbody>
<tr v-if="admin.scheduleRunsLoading">
<td colspan="11" class="px-4 py-8 text-center text-sm text-muted">{{ t('admin.schedule.queryingRuns') }}</td>
</tr>
<tr v-else-if="admin.filteredScheduleRuns.length === 0">
<td colspan="11" class="px-4 py-8 text-center text-sm text-muted">{{ t('admin.schedule.noRunRecords') }}</td>
</tr>
<tr
v-else
v-for="r in admin.filteredScheduleRuns"
:key="r.id"
class="text-secondary transition"
>
<td class="max-w-0 truncate px-4 py-2.5" :title="r.run_no">{{ r.run_no }}</td>
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.formatDateTime(r.started_at)">{{ admin.formatDateTime(r.started_at) }}</td>
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.formatDateTime(r.finished_at)">{{ admin.formatDateTime(r.finished_at) }}</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<div class="flex min-w-0 items-center gap-1 overflow-hidden">
<span
class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="admin.getScheduleRunStatusBadge(r.status).cls"
>
{{ admin.getScheduleRunStatusBadge(r.status).label }}
</span>
<span v-if="r.error_message" class="min-w-0 truncate text-xs text-muted" :title="r.error_message">...</span>
</div>
</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.total_count }}</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.success_count }}</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.skipped_count ?? 0 }}</td>
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.getScheduleRunFailedCountTitle(r)">
<span>{{ r.failed_count }}</span>
<span
v-if="admin.isScheduleRunExcelExportFailed(r)"
class="ml-1 text-xs font-medium text-amber-600"
>+Excel</span>
</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<span
v-if="r.wecom_notified"
class="inline-flex max-w-full shrink-0 items-center gap-1 truncate text-xs text-emerald-600"
:title="t('admin.schedule.notified')"
>
{{ t('admin.schedule.notified') }}
</span>
<span
v-else-if="r.wecom_notify_error"
class="block truncate text-xs text-amber-500"
:title="r.wecom_notify_error"
>{{ t('admin.schedule.notifyError') }}</span>
<span v-else class="text-xs text-muted">-</span>
</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<div class="flex min-w-0 flex-wrap items-center gap-1 overflow-hidden">
<a
v-if="r.total_count > 0"
href="#"
class="inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-lg border border-default px-2 py-1 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
@click.prevent="admin.downloadScheduleExcel(r.id)"
>
<Download class="h-3 w-3 shrink-0" />
{{ t('admin.schedule.downloadDetail') }}
</a>
<span v-else class="text-muted">-</span>
</div>
</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<div class="flex min-w-0 items-center overflow-hidden">
<button
v-if="(r.step_logs && r.step_logs.length > 0) || r.dify_execution_snapshot || r.kb_sync_status"
class="inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-lg border border-blue-200 px-2 py-1 text-xs font-medium text-blue-600 transition-colors hover:bg-blue-50"
@click="admin.expandedScheduleRunId = admin.expandedScheduleRunId === r.id ? null : r.id"
>
<Eye class="h-3 w-3 shrink-0" />
{{ t('admin.schedule.log') }}
<ChevronDown v-if="admin.expandedScheduleRunId !== r.id" class="h-3 w-3 shrink-0" />
<ChevronUp v-else class="h-3 w-3 shrink-0" />
</button>
<span v-else class="text-muted">-</span>
</div>
</td>
</tr>
<tr
v-if="admin.expandedScheduleRun"
:key="'expanded-' + admin.expandedScheduleRunId"
>
<td colspan="11" class="w-full max-w-none px-4 py-3 bg-surface-soft/60">
<div class="min-w-0 w-full max-w-full space-y-3">
<div
v-if="admin.wecomRawZipPromptRunId === admin.expandedScheduleRun.id && admin.expandedScheduleRun.inventory_raw_zip_available"
class="rounded-xl border border-blue-200 bg-blue-50/80 p-4"
>
<p class="text-sm font-medium text-blue-900">{{ t('admin.schedule.rawInventoryZipWecomHint') }}</p>
<button
type="button"
class="mt-3 inline-flex items-center gap-2 rounded-xl border border-blue-300 bg-surface px-4 py-2 text-sm font-semibold text-blue-700 shadow-sm transition-colors hover:bg-blue-50"
@click="admin.downloadScheduleInventoryRawZip(admin.expandedScheduleRun.id)"
>
<Download class="h-4 w-4 shrink-0" />
{{ t('admin.schedule.downloadInventoryRawZipPackage') }}
</button>
</div>
<div
v-if="admin.wecomRawZipPromptRunId === admin.expandedScheduleRun.id && admin.expandedScheduleRun.inbound_raw_zip_available"
class="rounded-xl border border-blue-200 bg-blue-50/80 p-4"
>
<p class="text-sm font-medium text-blue-900">{{ t('admin.schedule.rawInboundZipWecomHint') }}</p>
<button
type="button"
class="mt-3 inline-flex items-center gap-2 rounded-xl border border-blue-300 bg-surface px-4 py-2 text-sm font-semibold text-blue-700 shadow-sm transition-colors hover:bg-blue-50"
@click="admin.downloadScheduleInboundRawZip(admin.expandedScheduleRun.id)"
>
<Download class="h-4 w-4 shrink-0" />
{{ t('admin.schedule.downloadInboundRawZipPackage') }}
</button>
</div>
<div
v-if="admin.wecomRawZipPromptRunId === admin.expandedScheduleRun.id && admin.expandedScheduleRun.outbound_raw_zip_available"
class="rounded-xl border border-blue-200 bg-blue-50/80 p-4"
>
<p class="text-sm font-medium text-blue-900">{{ t('admin.schedule.rawOutboundZipWecomHint') }}</p>
<button
type="button"
class="mt-3 inline-flex items-center gap-2 rounded-xl border border-blue-300 bg-surface px-4 py-2 text-sm font-semibold text-blue-700 shadow-sm transition-colors hover:bg-blue-50"
@click="admin.downloadScheduleOutboundRawZip(admin.expandedScheduleRun.id)"
>
<Download class="h-4 w-4 shrink-0" />
{{ t('admin.schedule.downloadOutboundRawZipPackage') }}
</button>
</div>
<div
v-if="admin.expandedScheduleRun.kb_sync_status"
class="rounded-xl border border-emerald-200 bg-emerald-50/50 p-3 text-xs text-secondary"
>
<div class="font-bold text-emerald-800">{{ t('admin.schedule.kbSync.title') }}</div>
<div class="mt-1">
<span class="font-semibold text-muted">{{ t('admin.schedule.kbSync.status') }}:</span>
{{ admin.expandedScheduleRun.kb_sync_status }}
</div>
<div v-if="admin.expandedScheduleRun.kb_document_id" class="mt-1">
<span class="font-semibold text-muted">{{ t('admin.schedule.kbSync.document') }}:</span>
{{ admin.expandedScheduleRun.kb_document_id }}
</div>
<div v-if="admin.expandedScheduleRun.kb_sync_error" class="mt-1 text-rose-600">
{{ admin.expandedScheduleRun.kb_sync_error }}
</div>
</div>
<div
v-if="admin.expandedScheduleRun.dify_execution_snapshot"
class="rounded-xl border border-indigo-200 bg-indigo-50/50 p-3"
>
<div class="mb-2 flex flex-wrap items-start justify-between gap-x-4 gap-y-1">
<h5 class="min-w-0 text-xs font-bold uppercase text-indigo-800">{{ t('admin.schedule.difySnapshot.title') }}</h5>
<time
class="shrink-0 whitespace-nowrap text-[10px] text-indigo-600/80"
:title="admin.expandedScheduleRun.dify_execution_snapshot.captured_at || '-'"
>
{{ admin.formatDateTime(admin.expandedScheduleRun.dify_execution_snapshot.captured_at) }}
</time>
</div>
<div v-if="admin.expandedScheduleRun.dify_execution_snapshot.dify_enabled" class="space-y-2 text-xs text-secondary">
<div class="break-words">
<span class="font-semibold text-muted">{{ t('admin.schedule.difySnapshot.agent') }}:</span>
{{ admin.expandedScheduleRun.dify_execution_snapshot.dify_agent_name || '-' }}
<span class="text-muted">{{ t('admin.schedule.difySnapshot.agentId', { id: admin.expandedScheduleRun.dify_execution_snapshot.dify_agent_id ?? '-' }) }}</span>
</div>
<div v-if="admin.expandedScheduleRun.dify_execution_snapshot.dify_app_id">
<span class="font-semibold text-muted">{{ t('admin.schedule.difySnapshot.difyAppId') }}:</span>
{{ admin.expandedScheduleRun.dify_execution_snapshot.dify_app_id }}
</div>
<div>
<span class="mb-1 block font-semibold text-muted">{{ t('admin.schedule.difySnapshot.systemPrompt') }}:</span>
<pre
v-if="admin.expandedScheduleRun.dify_execution_snapshot.dify_system_prompt"
class="max-h-[240px] overflow-auto whitespace-pre-wrap rounded-lg border border-indigo-100 bg-surface p-3 font-mono text-[11px] leading-relaxed text-primary"
>{{ admin.expandedScheduleRun.dify_execution_snapshot.dify_system_prompt }}</pre>
<span v-else class="text-muted">{{ t('admin.schedule.difySnapshot.notConfiguredUseDefault') }}</span>
</div>
</div>
<div v-else class="text-xs text-muted">{{ t('admin.schedule.difySnapshot.notEnabledRun') }}</div>
</div>
<div class="space-y-2">
<div class="mb-2 flex flex-wrap items-center justify-between gap-2">
<h5 class="text-xs font-bold uppercase text-secondary">{{ t('admin.schedule.runLogs') }}</h5>
<span class="text-xs text-muted">{{ t('admin.schedule.stepsCount', { count: admin.expandedScheduleRun.step_logs?.length || 0 }) }}</span>
</div>
<div
v-for="(log, li) in admin.expandedScheduleRun.step_logs || []"
:key="li"
class="rounded-xl border p-3"
:class="log.status === 'failed' ? 'border-rose-200 bg-rose-50/40' : 'border-default bg-surface'"
>
<div class="mb-1 flex items-center gap-2">
<span
class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold"
:class="(admin.stepStatusMap[log.status] || admin.stepStatusMap.success || { cls: 'bg-surface-soft text-secondary' }).cls"
>
{{ (admin.stepStatusMap[log.status] || { label: log.status }).label }}
</span>
<span class="text-xs font-semibold text-secondary">{{ admin.stepLabelMap[log.step] || log.step }}</span>
<span v-if="log.row_id" class="text-[10px] text-muted">row_id={{ log.row_id }}</span>
<span v-if="log.duration_ms != null" class="text-[10px] text-muted">{{ log.duration_ms }}ms</span>
</div>
<details v-if="log.detail" class="mt-1">
<summary class="cursor-pointer text-[10px] font-semibold text-muted hover:text-secondary">{{ t('admin.schedule.viewDetail') }}</summary>
<pre class="admin-pre-block">{{ JSON.stringify(log.detail, null, 2) }}</pre>
</details>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div
v-else
class="px-8 py-16 text-center text-sm text-muted"
>
{{ t('admin.schedule.noSelectionHint') }}
</div>
</div>
</template>
<style scoped>
.schedule-workbench__context {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: space-between;
gap: 12px 16px;
padding: 16px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.schedule-workbench__switcher {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
min-width: 0;
flex: 1;
}
.schedule-workbench__label {
font-size: 0.875rem;
color: var(--el-text-color-secondary);
white-space: nowrap;
}
.schedule-workbench__select {
width: min(100%, 28rem);
}
.schedule-workbench__worker {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 8px;
font-size: 0.75rem;
}
.schedule-stats-bar {
display: flex;
flex-wrap: wrap;
gap: 16px 32px;
padding: 12px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.schedule-stat {
display: inline-flex;
align-items: baseline;
gap: 8px;
}
.schedule-stat__value {
font-size: 1.125rem;
font-weight: 700;
color: var(--el-text-color-primary);
}
.schedule-stat__label {
font-size: 0.8125rem;
color: var(--el-text-color-secondary);
}
.schedule-workbench__runs-head {
padding: 16px 32px 0;
}
.schedule-filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
padding: 12px 32px 16px;
}
.schedule-filter-date {
width: 11.5rem;
}
.schedule-filter-status {
width: 8rem;
}
.schedule-cron {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 0.75rem;
color: var(--el-text-color-secondary);
}
.admin-table-wrap {
margin: 0 32px 24px;
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
overflow: auto;
}
</style>
@@ -1,11 +1,13 @@
<script setup lang="ts">
/**
* features/admin/modules/schedules/components/SchedulesPageOverlays.vue
* 定时任务页弹窗层:试运行、创建/编辑、删除确认。
* 用途:定时任务页弹层——试运行、创建/编辑抽屉、删除确认。
* 依赖:DeleteConfirmDialog、ScheduleCreateEditDrawer、ScheduleTestRunDialog、schedules.context。
* 逻辑:由 SchedulesPage 挂载;创建/编辑已改为右侧 ElDrawer。
*/
<script setup lang="ts">
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useSchedulesAdminContext } from '../composables/schedules.context';
import ScheduleCreateEditModal from './ScheduleCreateEditModal.vue';
import ScheduleCreateEditDrawer from './ScheduleCreateEditDrawer.vue';
import ScheduleTestRunDialog from './ScheduleTestRunDialog.vue';
const admin = useSchedulesAdminContext();
@@ -13,7 +15,7 @@ const admin = useSchedulesAdminContext();
<template>
<ScheduleTestRunDialog />
<ScheduleCreateEditModal />
<ScheduleCreateEditDrawer />
<DeleteConfirmDialog
v-model="admin.showDeleteConfirmDialog"
:title="admin.deleteConfirmTitle"
@@ -3,7 +3,8 @@
* 用途:锁定在途仓自动调拨 JSON POST 请求头契约——必须携带 Content-Type: application/json,
* 否则后端 Flask request.get_json 解析不到 body,导致默认 source_codes=[] 返回 400;
* 另锁定 D8 异步 202 契约(requestJson 对 200/202 均透传 envelope.data)与
* D9 调拨单清单(GET /runs/{run_no} 返回体 orders 数组透传)。
* D9 调拨单清单(GET /runs/{run_no} 返回体 orders 数组透传);
* 当前归档重解析 POST /sources/{code}/reparse(body 仅 record_kind)。
* 依赖:Vitest、vi.mock(@/shared/api/client)、transfer.api、getAuthHeaders。
* 逻辑:POST(create/execute/cancel/retry/manual-close)断言 headers 含 application/json,
* 且 body 序列化正确;GET/blob 端点不强制 Content-Type;
@@ -31,6 +32,10 @@ import {
downloadTransferInboundFiles,
downloadTransferSourceFiles,
executeTransferItems,
listEvidenceFiles,
reparseCurrentFile,
retryTransferSourceRpa,
retryTransferSourcesRpaBatch,
getTransferBacklogSummary,
getTransferMatching,
getTransferRun,
@@ -72,12 +77,43 @@ describe('transfer.api JSON request contract', () => {
expect(init.headers).toBeDefined();
});
it('按来源打包下载走 POST /sources/inbound-files(Task 3 路由更名)', () => {
downloadTransferSourceFiles(['DBS-AWSBI']);
it('按来源打包下载走 POST /sources/inbound-files,body 含 transfer_type', () => {
// [断言意图] 证据打包按所选调拨类型决定打进包的流,body 必须同时有 source_codes 与 transfer_type。
downloadTransferSourceFiles(['DBS-AWSBI'], 'in_transit_to_hub');
const [url, init] = requestBlob.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/in-transit-transfer/sources/inbound-files');
expect(init.method).toBe('POST');
expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'] }));
expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'], transfer_type: 'in_transit_to_hub' }));
});
it('单源重试 POST retry-rpa,body 带 record_kind,缺省 inbound', () => {
// [断言意图] 旧调用不传种类时仍提交 inbound;来源卡传 outbound 时 body 必须是该流。
retryTransferSourceRpa('DBS-AWSBI');
retryTransferSourceRpa('DBS-AWSBI', 'outbound');
const calls = requestJson.mock.calls as [string, RequestInit][];
expect(calls[0][0]).toBe('/api/in-transit-transfer/sources/DBS-AWSBI/retry-rpa');
expect(calls[0][1].body).toBe(JSON.stringify({ record_kind: 'inbound' }));
expect(calls[1][1].body).toBe(JSON.stringify({ record_kind: 'outbound' }));
});
it('批量重试 POST retry-rpa-batch,带来源类型时 body 含 transfer_type', () => {
retryTransferSourcesRpaBatch(['DBS-AWSBI'], 'hub_to_hub');
const [url, init] = requestJson.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/in-transit-transfer/sources/retry-rpa-batch');
expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'], transfer_type: 'hub_to_hub' }));
});
it('列出证据文件走 GET evidence-files 并带 record_kind', () => {
listEvidenceFiles('DSV360', 'outbound');
const [url] = requestJson.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/in-transit-transfer/sources/DSV360/evidence-files?record_kind=outbound');
});
it('当前文件重解析 POST reparse,body 只有 record_kind', () => {
reparseCurrentFile('DSV360_AWSDU', 'outbound');
const calls = requestJson.mock.calls as [string, RequestInit][];
expect(calls[0][0]).toBe('/api/in-transit-transfer/sources/DSV360_AWSDU/reparse');
expect(JSON.parse(String(calls[0][1].body))).toEqual({ record_kind: 'outbound' });
});
it('按明细行执行调拨 POST /items/execute 带 application/json 与 item_ids 契约', () => {
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more