feat(in-transit-transfer): inbound/outbound 幂等重命名与解析用途分层

- receipt→inbound 三件套改名(回调桥/文件门禁/触发服务),回调链幂等去重,迁移 tt14 同步台账键与测试基建
- 库存解析用途分层 onhand/inbound/outbound(迁移 tt15):解析档案、文件存储与下载名按用途隔离,管理端表单同步
- 「成熟」概念退役(迁移 tt16):数据无成熟属性,日期边界由调用方入参严格判定
- backlog 新增重解析服务,在途重识别投影 processing,EML 父项不再停留处理中
- 收料 RPA 回调/归档/排程链路同步改名挂点,运维脚本复位假完成状态
- 文档随批:ADR 0003 模块边界决策、10-15/10-16 计划与设计、调拨文档族与 demand/tec/funclist
- 同步 chat/errors 文案四语言、调拨前端卡片与 e2e、测试全家
This commit is contained in:
hugo committed 2026-10-16 19:43:49 +08:00
1 parent 43dceaf027
commit 8102a1fe44
151 files changed
+8057 -2382

No files matched your search

-1
View File
@@ -238,7 +238,6 @@ IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=86400
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS=2
# 归档 bucket(MinIO;凭据复用 MINIO_*)
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
+198 -67
View File
@@ -9,7 +9,9 @@
retrigger → 202,D11 唯一出口);首页「已执行」区块:已执行单分页查询
(GET /documents,只读)与人工关闭失败单(POST /documents/{doc_no}/close,
D18 废单不废行);调拨类型选择数据源(GET /transfer-types,仅启用、
最小暴露,读 Task 4 transfer_type_config_service)。
最小暴露,读 Task 4 transfer_type_config_service);待匹配桶维护(spec §6):
「清空并重新解析」预检(GET /backlog/pending-match/reparse-preview,只读)
与执行(POST /backlog/pending-match/reparse,单事务由 service 提交并落审计)。
"""
from __future__ import annotations
@@ -60,6 +62,25 @@ in_transit_transfer_bp = Blueprint("in_transit_transfer", __name__)
TRANSFER_AGENT_CODE = "in_transit_transfer"
def _parse_int_arg(name: str, default: int, *, minimum: int, maximum: int | None = None) -> int:
"""解析整数查询参数(缺省回默认值;下限钳制必填,上限可选;非法 400)。
分页参数统一入口(/documents、/backlog、/backlog/pending-match 共用,
2026-10-16 由 list_documents_api 内嵌函数提升为模块级)。
"""
raw = (request.args.get(name) or "").strip()
if not raw:
return default
try:
value = int(raw)
except ValueError as exc:
raise ValidationError(f"{name} must be an integer") from exc
value = max(minimum, value)
if maximum is not None:
value = min(maximum, value)
return value
def _require_user():
"""校验当前登录用户;未认证抛 UnauthorizedError。"""
user = get_current_user()
@@ -95,7 +116,7 @@ def create_matching_api():
"""创建或复用一次调拨匹配(只读,不写 外部系统)。
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
"receipt_date_from"/"receipt_date_to"(可选),
"movement_date_from"/"movement_date_to"(可选,明细异动日期范围),
"transfer_type": 必填(类型编码,配置化;缺失/未配置/停用 → 422)}。
响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度);
类型门禁失败 422(REQUIRED/NOT_CONFIGURED/DISABLED,规格 §11)。
@@ -122,8 +143,8 @@ def create_matching_api():
source_codes=[str(item).strip() for item in source_codes],
business_date=business_date,
deps=deps,
receipt_date_from=str(body.get("receipt_date_from")) if body.get("receipt_date_from") else None,
receipt_date_to=str(body.get("receipt_date_to")) if body.get("receipt_date_to") else None,
movement_date_from=str(body.get("movement_date_from")) if body.get("movement_date_from") else None,
movement_date_to=str(body.get("movement_date_to")) if body.get("movement_date_to") else None,
transfer_type=transfer_type,
)
return _ok(serialize_summary(summary), status=201)
@@ -162,10 +183,10 @@ def requery_items_api(matching_no: str):
))
@in_transit_transfer_bp.route("/sources/receipt-files", methods=["POST"])
@in_transit_transfer_bp.route("/sources/inbound-files", methods=["POST"])
@require_transfer_permission
def download_source_receipt_files_api():
"""按选中来源打包下载各自最新归档收料文件(zip);记录访问审计。"""
def download_source_inbound_files_api():
"""按选中来源打包下载各自最新归档入站文件(ShippingReceiptReport RPA 产物,zip);记录访问审计。"""
import io
import zipfile
from pathlib import Path as _Path
@@ -174,7 +195,7 @@ def download_source_receipt_files_api():
from app.models import ShippingReceiptReportFile
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition
body = request.get_json(silent=True) or {}
source_codes = body.get("source_codes")
@@ -194,8 +215,8 @@ def download_source_receipt_files_api():
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=code),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/匹配取文件同口径,
# 单一事实来源见 receipt_file_gate。
usable_receipt_file_condition(),
# 单一事实来源见 inbound_file_gate。
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
@@ -207,11 +228,11 @@ def download_source_receipt_files_api():
archive.writestr(f"{code}-{safe_name}", data)
included.append(code)
if not included:
raise NotFoundError("no archived receipt files", code="SHIPPING.RECEIPT_FILE_NOT_FOUND")
raise NotFoundError("no archived inbound files", code="SHIPPING.INBOUND_FILE_NOT_FOUND")
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
aggregate_type="in_transit_source",
aggregate_id=",".join(included),
actor_type="user",
@@ -226,7 +247,7 @@ def download_source_receipt_files_api():
buffer,
mimetype="application/zip",
as_attachment=True,
download_name=f"receipt-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip",
download_name=f"inbound-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip",
)
@@ -342,11 +363,11 @@ def list_documents_api():
Query:
status_group ∈ {success, failed, executing, result_unknown}(可选,缺省全部;
非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表,
按收料日期过滤——列表展示的业务日期口径,2026-09-29 由 created_at 切换);
按异动日期过滤——列表展示的业务日期口径,2026-09-29 由 created_at 切换);
page(默认 1);page_size(默认 20,上限 100)。
口径:分组计数恒全量(GROUP BY status 对全部单统计,不受筛选影响——
失败/结果未知/执行中=未完结即待办,全量才不漏;成功=累计产出);
列表按 收料日期→数据源→拨出/拨入库位 升序分页(2026-09-29 与可调拨
列表按 异动日期→数据源→拨出/拨入库位 升序分页(2026-09-29 与可调拨
明细/待处理池/结果卡统一口径,跨数据源不再乱序;执行落库时间仅作
同序兜底),cancelled 不展示(无产生路径)。
响应:{groups, total, page, page_size, orders:[serialize_executed_order 投影]}。
@@ -365,20 +386,6 @@ def list_documents_api():
except ValueError as exc:
raise ValidationError(f"{name} must be YYYY-MM-DD") from exc
def _parse_int(name: str, default: int, *, minimum: int, maximum: int | None = None) -> int:
"""解析整数查询参数(缺省回默认值;下限钳制必填,上限可选)。"""
raw = (request.args.get(name) or "").strip()
if not raw:
return default
try:
value = int(raw)
except ValueError as exc:
raise ValidationError(f"{name} must be an integer") from exc
value = max(minimum, value)
if maximum is not None:
value = min(maximum, value)
return value
# [STEP 1] 参数校验:status_group 白名单外 400(fail-closed)。
status_group = (request.args.get("status_group") or "").strip()
if status_group and status_group not in DOCUMENT_STATUS_GROUPS:
@@ -387,8 +394,9 @@ def list_documents_api():
)
date_from = _parse_date("date_from")
date_to = _parse_date("date_to")
page = _parse_int("page", 1, minimum=1)
page_size = _parse_int("page_size", 20, minimum=1, maximum=100)
# 整数分页参数解析复用模块级 _parse_int_arg(2026-10-16 自本函数内嵌提升)。
page = _parse_int_arg("page", 1, minimum=1)
page_size = _parse_int_arg("page_size", 20, minimum=1, maximum=100)
# [STEP 2] 分组计数恒全量:GROUP BY status 对全部单统计,不受任何筛选影响。
counts = dict(
@@ -402,21 +410,21 @@ def list_documents_api():
}
# [STEP 3] 列表查询:status_group / 时间窗仅作用列表;cancelled 恒不展示。
# [2026-09-29 口径] 时间窗按收料日期过滤(receipt_date 为 ISO 日期字符串,
# 字典序即时间序);排序与可调拨明细/结果卡统一:收料日期→数据源→库位升序,
# [2026-09-29 口径] 时间窗按异动日期过滤(movement_date 为 ISO 日期字符串,
# 字典序即时间序);排序与可调拨明细/结果卡统一:异动日期→数据源→库位升序,
# created_at/id 兜底稳定分页(跨数据源不再按落库序乱序)。
query = TransferDocument.query.filter(TransferDocument.status != "cancelled")
if status_group:
query = query.filter(TransferDocument.status.in_(DOCUMENT_STATUS_GROUPS[status_group]))
if date_from:
query = query.filter(TransferDocument.receipt_date >= date_from.isoformat())
query = query.filter(TransferDocument.movement_date >= date_from.isoformat())
if date_to:
window_end = (date_to + timedelta(days=1)).isoformat()
query = query.filter(TransferDocument.receipt_date < window_end)
query = query.filter(TransferDocument.movement_date < window_end)
total = query.count()
docs = (
query.order_by(
TransferDocument.receipt_date.asc(),
TransferDocument.movement_date.asc(),
TransferDocument.source_code.asc(),
TransferDocument.from_warehouse.asc(),
TransferDocument.to_warehouse.asc(),
@@ -609,10 +617,10 @@ def exceptions_excel_api(run_no: str):
)
@in_transit_transfer_bp.route("/runs/<run_no>/receipt-files", methods=["GET"])
@in_transit_transfer_bp.route("/runs/<run_no>/inbound-files", methods=["GET"])
@require_transfer_permission
def receipt_files_api(run_no: str):
"""下载本次收料来源文件(清单 + 原始行追溯,zip);记录访问审计。"""
def inbound_files_api(run_no: str):
"""下载本次入站来源文件(清单 + 原始行追溯,zip);记录访问审计。"""
import io
import json
import zipfile
@@ -635,7 +643,7 @@ def receipt_files_api(run_no: str):
"business_date": run.business_date,
**dict(file_snapshot.get(source_code) or {}),
}
archive.writestr(f"{source_code}-receipt-info.json", json.dumps(manifest, ensure_ascii=False, indent=2))
archive.writestr(f"{source_code}-inbound-info.json", json.dumps(manifest, ensure_ascii=False, indent=2))
rows = []
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).all():
for line in (item.raw_lines_json or []):
@@ -648,7 +656,7 @@ def receipt_files_api(run_no: str):
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
aggregate_type="transfer_run",
aggregate_id=run_no,
run_no=run_no,
@@ -663,7 +671,7 @@ def receipt_files_api(run_no: str):
io.BytesIO(buffer.getvalue()),
mimetype="application/zip",
as_attachment=True,
download_name=f"receipt-files-{run_no}.zip",
download_name=f"inbound-files-{run_no}.zip",
)
@@ -680,12 +688,12 @@ def erp_inventory_api(run_no: str):
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,external_quantity,result,external_document_no"]
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,movement_quantity,external_quantity,result,external_document_no"]
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all():
lines.append(",".join([
str(item.invoice_no), str(item.source_code), str(item.material_no),
str(item.from_warehouse), str(item.to_warehouse),
str(item.receipt_quantity), str(item.external_quantity or ""),
str(item.movement_quantity), str(item.external_quantity or ""),
str(item.result_code or item.status), str(item.external_document_no or ""),
]))
data = ("\n".join(lines) + "\n").encode("utf-8")
@@ -749,7 +757,7 @@ def transfer_types_api():
def transfer_sources_api():
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
每来源附收料文件状态(ready/parse_failed/fetching/failed/expired/none + has_ready_file),
每来源附入站文件状态(ready/parse_failed/fetching/failed/expired/none + has_ready_file),
供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
"""
@@ -774,20 +782,20 @@ def transfer_sources_api():
@in_transit_transfer_bp.route("/sources/<source_code>/retry-rpa", methods=["POST"])
@require_transfer_permission
def retry_source_rpa_api(source_code: str):
"""对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。
"""对指定来源重新触发一次入站 RPA 抓取(复用货代 ShippingReceiptReport trigger 链路,shipping_notice 域术语保留)。
【AI 触发时机】来源收料文件不可用需要恢复时调用:解析失败(parse_failed)先
【AI 触发时机】来源入站文件不可用需要恢复时调用:解析失败(parse_failed)先
本地重解析已归档文件;文件缺失/失效(none/expired/failed)才重新触发 RPA 抓取。
解析失败优先本地重解析(解析失败分层 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,
(file_status=parse_failed)。其余状态沿用原路径:重新触发一次入站 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.receipt_trigger_service import trigger_receipt_rpa
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
source_code = str(source_code).strip()
@@ -810,11 +818,11 @@ def retry_source_rpa_api(source_code: str):
"reparsed": True,
})
# [STEP 2] 其余状态沿用原路径:重新触发一次收料 RPA 抓取(202 + fetching)。
outcome = trigger_receipt_rpa(
# [STEP 2] 其余状态沿用原路径:重新触发一次入站 RPA 抓取(202 + fetching)。
outcome = trigger_inbound_rpa(
source_code=source_code,
business_date=str(business_date_now()),
reason="transfer_retry_receipt",
reason="transfer_retry_inbound",
)
status = resolve_source_file_status(source_code=source_code)
if not outcome.get("ok"):
@@ -835,11 +843,11 @@ def retry_source_rpa_api(source_code: str):
@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)。
"""批量重试多来源入站 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器;
合并单文件后 Worker 单次登录串行导出全部来源(与收料排程路径同效率)。
合并单文件后 Worker 单次登录串行导出全部来源(与 ShippingReceiptReport RPA 排程路径同效率)。
请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与
fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。
@@ -848,12 +856,12 @@ def retry_sources_rpa_batch_api():
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.receipt_trigger_service import trigger_receipt_rpa_batch
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa_batch
outcome = trigger_receipt_rpa_batch(
outcome = trigger_inbound_rpa_batch(
source_codes=source_codes,
business_date=str(business_date_now()),
reason="transfer_retry_receipt",
reason="transfer_retry_inbound",
)
return _ok(outcome)
@@ -861,12 +869,56 @@ def retry_sources_rpa_batch_api():
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
@require_transfer_permission
def backlog_api():
"""待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。"""
"""待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。
Query(全部可选;不带 page/page_size 时保持历史行为返回全量数组——向后兼容):
page(默认 1);page_size(默认 20,上限 100)——任一提供即切换为
分页 envelope {items, total, page, page_size}(2026-10-16 服务端分页:
池为无界增长集合,千行级全量拉取放大载荷与老化查询规模);
keyword(Invoice/料号/品名/来源 子串大小写不敏感,与前端池内筛选同字段集);
result_filter ∈ {all, recoverable, closed, unknown}(缺省 all,白名单外 400)。
注意:keyword/result_filter 仅在分页模式下生效(兼容模式下为历史行为,
筛选参数被忽略——前端恒带分页参数,不受影响)。
口径:total=筛选后全量计数(供前端分页器);排序与全量版同一业务稳定键;
老化批量查询只对当前页行执行。审计 after.item_count 记录当前页行数。
"""
from app import db
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.backlog_service import list_backlog
from app.services.in_transit_transfer.backlog_service import (
RESULT_FILTER_CHOICES,
BACKLOG_PAGE_DEFAULT,
BACKLOG_PAGE_SIZE_DEFAULT,
BACKLOG_PAGE_SIZE_MAX,
list_backlog,
list_backlog_page,
)
keyword = (request.args.get("keyword") or "").strip()
result_filter = (request.args.get("result_filter") or "").strip() or "all"
if result_filter not in RESULT_FILTER_CHOICES:
raise ValidationError(
f"result_filter must be one of {sorted(RESULT_FILTER_CHOICES)}",
)
paginated = bool((request.args.get("page") or "").strip() or (request.args.get("page_size") or "").strip())
if paginated:
page_data = list_backlog_page(
keyword=keyword or None,
result_filter=result_filter,
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),
)
items = page_data.items
payload: dict[str, Any] | list[dict[str, Any]] = {
'items': [_serialize_backlog_item(item) for item in items],
'total': page_data.total,
'page': page_data.page,
'page_size': page_data.page_size,
}
else:
items = list_backlog()
payload = [_serialize_backlog_item(item) for item in items]
items = list_backlog()
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type='TRANSFER_BACKLOG_VIEWED',
@@ -880,7 +932,7 @@ def backlog_api():
after={'item_count': len(items)},
))
db.session.commit()
return _ok([_serialize_backlog_item(item) for item in items])
return _ok(payload)
@in_transit_transfer_bp.route("/backlog/summary", methods=["GET"])
@@ -894,7 +946,7 @@ def backlog_summary_api():
'recoverable': summary.recoverable_count,
'closed': summary.closed_count,
'unknown': summary.unknown_count,
# 首页待办看板第 4 张数字卡(D16):已落档尚未匹配的外部收料记录数。
# 首页待办看板第 4 张数字卡(D16):已落档尚未匹配的外部入站记录数。
'pending_match': summary.pending_match_count,
'aging': {
'warn_3d': summary.warn_3d,
@@ -908,9 +960,34 @@ def backlog_summary_api():
@require_transfer_permission
def backlog_pending_match_api():
"""首页待办看板「待匹配」桶清单(D16 只读:启用类型范围并集内已落档、
尚未被任何匹配圈定的外部收料记录;无 item_id——不可勾选执行,
前端仅提供只读清单与「去匹配」引导)。"""
from app.services.in_transit_transfer.backlog_service import list_pending_match_records
尚未被任何匹配圈定的外部入站记录;无 item_id——不可勾选执行,
前端仅提供只读清单与「去匹配」引导)。
Query(可选;不带 page/page_size 时保持历史行为返回全量数组——向后兼容):
page(默认 1);page_size(默认 20,上限 100)——任一提供即切换为
分页 envelope {records, total, page, page_size}(2026-10-16 服务端分页:
桶为 951 行级大池,全量序列化/传输从 O(桶) 降到 O(页))。
"""
from app.services.in_transit_transfer.backlog_service import (
BACKLOG_PAGE_DEFAULT,
BACKLOG_PAGE_SIZE_DEFAULT,
BACKLOG_PAGE_SIZE_MAX,
list_pending_match_records,
list_pending_match_records_page,
)
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),
)
return _ok({
'records': [_serialize_pending_match_record(record) for record in page_data.records],
'total': page_data.total,
'page': page_data.page,
'page_size': page_data.page_size,
})
return _ok([
_serialize_pending_match_record(record)
@@ -931,6 +1008,60 @@ def _serialize_pending_match_record(record) -> dict[str, Any]:
}
@in_transit_transfer_bp.route("/backlog/pending-match/reparse-preview", methods=["GET"])
@require_transfer_permission
def pending_match_reparse_preview_api():
"""待匹配桶「清空并重新解析」预检(只读;spec §6 确认弹窗数据源)。
【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。
"""
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()))
@in_transit_transfer_bp.route("/backlog/pending-match/reparse", methods=["POST"])
@require_transfer_permission
def pending_match_reparse_api():
"""待匹配桶「清空并重新解析」执行(spec §6;单事务由 service 提交)。
【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}。
"""
from app.services.in_transit_transfer.backlog_reparse_service import reparse_pending_match
payload = request.get_json(silent=True) or {}
source_code = str(payload.get("source_code") or "").strip()
if not source_code:
raise ValidationError("source_code is required")
user = _require_user()
outcome = reparse_pending_match(
source_code=source_code,
operator=str(getattr(user, "username", "") or user.id),
now=datetime.utcnow(),
)
return _ok({
"source_code": outcome.source_code,
"cleared": outcome.cleared,
"reinserted": outcome.reinserted,
"date_skipped": outcome.date_skipped,
"kept_unrebuildable": outcome.kept_unrebuildable,
"unlinked_items": outcome.unlinked_items,
"collapses": outcome.collapses,
"files": list(outcome.files),
})
def _serialize_backlog_item(item) -> dict[str, Any]:
"""待处理池项序列化(明细字段与匹配窗口列一致)。"""
return {
@@ -943,12 +1074,12 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
'age_days': item.age_days,
'aging_level': item.aging_level,
'last_attempt_at': item.last_attempt_at,
'receipt_date': item.receipt_date,
'movement_date': item.movement_date,
'material_name': item.material_name,
'from_warehouse': item.from_warehouse,
'to_warehouse': item.to_warehouse,
'lot_no': item.lot_no,
'receipt_quantity': item.receipt_quantity,
'movement_quantity': item.movement_quantity,
'external_quantity': item.external_quantity,
'result_code': item.result_code,
}
+4 -3
View File
@@ -1359,9 +1359,10 @@ def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no:
path = Path(storage_path).resolve() if storage_path else None
if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file():
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
download_name = str(
inventory_file.source_file_name or f'{inventory_file.inventory_file_no}{path.suffix or ".xlsx"}',
).strip()
from app.services.shipping_notice.inventory_file_store import build_inventory_download_name
download_name = build_inventory_download_name(
inventory_file, source_file_name=inventory_file.source_file_name, path=path,
)
from app.services.shipping_notice.fulfillment_audit import record_access_audit
record_access_audit(
action='download_task_line_inventory_file',
-3
View File
@@ -299,9 +299,6 @@ class Config:
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip()
IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS = int(
os.getenv('IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS', '2') or '2'
)
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
)
@@ -64,7 +64,6 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
matching.status = summary.status
matching.counts_json = {
"file_invoice_count": summary.counts.file_invoice_count,
"not_matured_count": summary.counts.not_matured_count,
"matched_count": summary.counts.matched_count,
"executable_count": summary.counts.executable_count,
"blocked_count": summary.counts.blocked_count,
+43 -30
View File
@@ -3,9 +3,9 @@
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive;另含调拨类型
配置表 TransferTypeConfig(类型配置化,ADR 0002)与库存异动档
TransferMovementLedger(外部系统收料/出货记录镜像,ADR 0001)。
TransferMovementLedger(外部系统入站/出站记录镜像,ADR 0001)。
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁);
source_file_id 外键指向 shipping_receipt_report_files(收料原样归档)。
source_file_id 外键指向 shipping_receipt_report_files(ShippingReceiptReport 原样归档,入站证据)。
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
@@ -14,8 +14,8 @@
transfer_runs.transfer_type 合法值由 TransferTypeConfig 配置承接
(原枚举 CHECK 约束已移除);
TransferMovementLedger 以自然键 (source_code, record_kind, doc_no,
line_no, line_seq, in_out_flag) 幂等增量落地外部记录,已执行记录经
transfer_executed 封存(防二次调拨),来源文件删除后档事实留存
line_no, line_seq, in_out_flag, carton_id, lot_no) 幂等增量落地外部记录,
已执行记录经 transfer_executed 封存(防二次调拨),来源文件删除后档事实留存
(ON DELETE SET NULL,链接仅溯源)。
"""
@@ -43,9 +43,10 @@ from app.core.errors import ValidationError
from app.models.base import Base
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
# 【not_matured 已退役 2026-10-16】成熟概念删除,存量行经 tt16 重映射 cancelled。
TRANSFER_ITEM_STATUSES = (
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
'success', 'duplicate_success', 'blocked_recoverable',
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
)
TRANSFER_RUN_STATUSES = (
@@ -110,7 +111,7 @@ class TransferRun(Base):
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
# 调拨业务类型(合法值由 TransferTypeConfig 配置承接,合法 code 正则
# ^[a-z][a-z0-9_]{1,63}$ 上限 64);决定匹配收料数据范围。列宽 64 与配置表
# ^[a-z][a-z0-9_]{1,63}$ 上限 64);决定匹配入站数据范围。列宽 64 与配置表
# code 上限对齐(终审 I2:33~64 字符 code 建匹配时写 32 宽列会 DB 500)。
transfer_type: Mapped[str] = mapped_column(
String(64), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
@@ -217,7 +218,7 @@ class TransferMatching(Base):
class TransferInvoiceItem(Base):
"""匹配明细项;同一匹配内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
"""匹配明细项;同一匹配内 (来源,Invoice,料号,异动日期) 唯一,保留原始行追溯。
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
【2026-10-14 出生翻转(ADR 0001/D4)】行不再由文件落地写入,而是匹配创建时
@@ -228,7 +229,7 @@ class TransferInvoiceItem(Base):
__tablename__ = 'transfer_invoice_items'
__table_args__ = (
UniqueConstraint(
'matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
'matching_id', 'source_code', 'invoice_no', 'material_no', 'movement_date',
name='uq_transfer_invoice_items_matching_grain',
),
CheckConstraint(
@@ -262,19 +263,19 @@ class TransferInvoiceItem(Base):
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
# 入站文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
movement_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim,
# 不换算);空值行在匹配阶段落 blocked_missing_unit。unit 不参与匹配 Hash(口径冻结)。
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default='', server_default='')
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
receipt_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
movement_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
# [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟,
# 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段,
@@ -339,7 +340,7 @@ class TransferDocument(Base):
# 建表同语义(部分唯一,非全组唯一)。
Index(
'uq_transfer_documents_group_live',
'source_code', 'external_org', 'receipt_date', 'from_warehouse', 'to_warehouse',
'source_code', 'external_org', 'movement_date', 'from_warehouse', 'to_warehouse',
unique=True,
postgresql_where=text(UNRESOLVED_DOC_STATUS_WHERE),
sqlite_where=text(UNRESOLVED_DOC_STATUS_WHERE),
@@ -352,7 +353,7 @@ class TransferDocument(Base):
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
external_org: Mapped[str] = mapped_column(String(64), nullable=False)
receipt_date: Mapped[str] = mapped_column(String(16), nullable=False)
movement_date: Mapped[str] = mapped_column(String(16), nullable=False)
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
# 提交标识(D3 终身复用):同组复用单时保持首建值不变;唯一性由
@@ -523,19 +524,24 @@ class TransferTypeConfig(Base):
class TransferMovementLedger(Base):
"""库存异动档(ADR 0001):外部系统收料/出货记录的平台镜像(参照 ERP inaj_t 形态)。
"""库存异动档(ADR 0001):外部系统入站/出站记录的平台镜像(参照 ERP inaj_t 形态)。
用途:外部系统收料(一期)/出货(结构就位,record_kind='shipment')记录统一落档;
用途:外部系统入站(一期)/出站(结构就位,record_kind='outbound')记录统一落档;
匹配明细(items)由匹配创建时从档圈定生成(落地不再写 items,出生翻转)。
幂等增量落地:自然键 (source_code, record_kind, doc_no, line_no, line_seq,
in_out_flag) 唯一约束去重——不存在则插入、证据变化则原行更新、文件缺席不删;
in_out_flag, carton_id, lot_no) 唯一约束去重——不存在则插入、证据变化则原行
更新、文件缺席不删(tt14 扩维:真实 WMS 行身份=单据+行+箱/批,carton_id/
lot_no 加入键防同箱/批塌缩丢行;R7 终审:两列同步 NOT NULL + default '',
nullable 成分的 NULL 不参与 PG/SQLite 唯一比对会逃逸约束,空值成分一律以
空串入库保证唯一约束可比);
已执行记录 transfer_executed=true 封存(executed_doc_no 回写),永不更新、
永不复活、永不再次被圈定(防二次调拨,档级封存兜底)。
刻意双字段:record_kind(文件种类声明,权威)与 in_out_flag(数据列原值),
两者矛盾即解析错位,由落档链路打审计事件,记录照常落档。
可空语义:自然键成分一律 NOT NULL(line_seq/in_out_flag default '' 保证唯一
约束可比),业务/证据列一律 nullable(外部列宽松落地);movement_date 可空——
空值记录照常落档但不进收料日期圈定(日期条件恒排除 NULL)。
可空语义:自然键 8 成分一律 NOT NULL(line_seq/in_out_flag/carton_id/lot_no
default '' 保证唯一约束可比、防 PG NULL 逃逸唯一比对),业务/证据列一律
nullable(外部列宽松落地);movement_date 可空——空值记录照常落档但不进
异动日期圈定(日期条件恒排除 NULL)。
source_file_id ON DELETE SET NULL:来源文件被清理(文件资产保留策略)后
档记录必须留存(事实不随文件消失,链接仅溯源)。
D 组 ⭐5 列(order_type/odm_id/odm_name/carton_id/pallet_id)为本期新增强
@@ -546,12 +552,15 @@ class TransferMovementLedger(Base):
__tablename__ = 'transfer_movement_ledger'
__table_args__ = (
# 自然键唯一(幂等增量落地兜底;应用层按自然键查档先行)。
# 自然键唯一(幂等增量落地兜底;应用层按自然键查档先行)。tt14 扩维 8 成分:
# carton_id/lot_no 进键(真实 WMS 行身份=单据+行+箱/批),R7 终审同步
# NOT NULL + default ''(可空成分以空串入库,防 PG NULL 逃逸唯一比对)。
UniqueConstraint(
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
'carton_id', 'lot_no',
name='uq_transfer_movement_ledger_natural_key',
),
# 匹配创建圈档主路径:来源 + 记录种类 + 收料日期范围扫描。
# 匹配创建圈档主路径:来源 + 记录种类 + 异动日期范围扫描。
Index('ix_transfer_movement_ledger_source_kind_date', 'source_code', 'record_kind', 'movement_date'),
# 档级封存/待匹配桶扫描:按记录种类过滤已执行位。
Index('ix_transfer_movement_ledger_kind_executed', 'record_kind', 'transfer_executed'),
@@ -562,24 +571,28 @@ class TransferMovementLedger(Base):
doc_no: Mapped[str] = mapped_column(String(64), nullable=False)
line_no: Mapped[str] = mapped_column(String(32), nullable=False)
line_seq: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
# 数据列原值(收料=收发标记),与 record_kind 交叉校验用,不参与权威判定。
# 数据列原值(入站=收发标记),与 record_kind 交叉校验用,不参与权威判定。
in_out_flag: Mapped[str] = mapped_column(String(8), nullable=False, default='', server_default='')
# --- B 物料与数量(数量 Decimal 文本,与 items.receipt_quantity 同约定)---
# --- 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)
specification: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 批号原值(tt14 起入自然键:NOT NULL + default '' 防 PG NULL 逃逸唯一比对;
# 空值成分以空串入库保证唯一约束可比,与 line_seq/in_out_flag 同口径)。
lot_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# --- C 仓储与日期(movement_date 可空:空值不进收料日期圈定)---
# --- C 仓储与日期(movement_date 可空:空值不进异动日期圈定)---
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
storage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
# --- D 业务属性(⭐本期新增强业务字段;🔖预留列,nullable,出货侧直接映射)---
# --- D 业务属性(⭐本期新增强业务字段;carton_id tt14 起入自然键 NOT NULL
# --- default '';🔖预留列 nullable,出货侧直接映射)---
order_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
odm_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
carton_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 箱号(tt14 起入自然键:NOT NULL + default '',与 lot_no 同口径,防 NULL 逃逸唯一比对)。
carton_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
pallet_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
doc_nature: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
movement_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -589,7 +602,7 @@ class TransferMovementLedger(Base):
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# --- E 平台溯源(证据字段:evidence_sync 原行更新时整体换新)---
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
# 文件种类声明('receipt'/'shipment',权威);与 in_out_flag 矛盾打审计事件。
# 文件种类声明(tt14 值迁移后 'inbound'/'outbound',权威);与 in_out_flag 矛盾打审计事件。
record_kind: Mapped[str] = mapped_column(String(16), nullable=False)
# 来源文件溯源:ON DELETE SET NULL(文件清理后档事实留存)。
source_file_id: Mapped[Optional[int]] = mapped_column(
@@ -609,7 +622,7 @@ class TransferMovementLedger(Base):
)
executed_doc_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 溯源关系:档案行 → 收料原样归档文件(单向,不回挂;ShippingReceiptReportFile
# 溯源关系:档案行 → ShippingReceiptReport 原样归档文件(单向,不回挂; ShippingReceiptReportFile
# 不感知调拨域,避免跨域 back_populates 环)。
source_file: Mapped[Optional['ShippingReceiptReportFile']] = relationship()
@@ -158,15 +158,18 @@ class ShippingInventorySourceParsingBindingAudit(Base):
class ShippingInventoryParsingProfile(Base):
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
"""可跨源复用的通用文件解析规则(在手/入站/出站按 purpose 区分)。
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表",
用途以 purpose 字段为准,勿按表名推断只服务库存。
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
purpose='onhand':在手库存文件(原 inventory),端点用 ShippingInventoryField
库存字段目录(既有语义);
purpose='inbound':入站收料文件(原 movement),端点用定死领域字段
(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id /
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='inbound');
purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。
"""
__tablename__ = 'shipping_inventory_parsing_profiles'
@@ -175,13 +178,13 @@ class ShippingInventoryParsingProfile(Base):
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
CheckConstraint(
"purpose IN ('inventory', 'movement')",
"purpose IN ('onhand', 'inbound', 'outbound')",
name='ck_shipping_inventory_parsing_profiles_purpose',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='inventory', server_default='inventory')
purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='onhand', server_default='onhand')
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
@@ -30,7 +30,7 @@ class ShippingReceiptReportConfig(Base):
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
)
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
# 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。
# 收料文件解析规则(purpose='inbound');定死领域字段端点。空则无法解析收料文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
)
@@ -259,7 +259,7 @@ def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[
'id': config.id, 'inventory_source_id': config.inventory_source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
# 异动解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
# 入站解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
'parsing_profile_id': config.parsing_profile_id,
'parsing_profile': ({
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
@@ -270,23 +270,23 @@ def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[
}
def _validate_movement_profile_binding(profile_id: Any) -> int | None:
"""校验收料配置绑定的异动解析规则:必须已发布且 purpose='movement';空值表示解绑。
def _validate_inbound_profile_binding(profile_id: Any) -> int | None:
"""校验收料配置绑定的入站解析规则:必须已发布且 purpose='inbound';空值表示解绑。
Args:
profile_id: 请求中的 parsing_profile_id;None/空串表示解绑。
Returns:
规整后的规则 id 或 None。
Raises:
ValidationError: 规则不存在/未发布/用途不是 movement(fail-closed,防误绑库存规则)。
ValidationError: 规则不存在/未发布/用途不是 inbound(fail-closed,防误绑在手/出站规则)。
"""
if profile_id is None or str(profile_id).strip() == '':
return None
profile = db.session.get(ShippingInventoryParsingProfile, int(profile_id))
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
raise ValidationError(
'Receipt movement parsing profile must be published with purpose movement',
code='SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID',
'Inbound parsing profile must be published with purpose inbound',
code='SHIPPING.INBOUND_PROFILE_INVALID',
)
return profile.id
@@ -352,7 +352,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
config.config_version += 1
config.report_path_json = path
config.query_parameters_json = parameters
config.parsing_profile_id = _validate_movement_profile_binding(data.get('parsing_profile_id'))
config.parsing_profile_id = _validate_inbound_profile_binding(data.get('parsing_profile_id'))
config.updated_by = actor_id
db.session.flush()
after = _receipt_report_config_payload(config)
@@ -108,7 +108,7 @@ def archive_snapshot(
"""归档一份对象并持久化索引 + 审计。
Args:
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
object_type: 对象类型(external_inventory_snapshot / exception_excel / inbound_file)。
object_id: 业务对象编号(matching_no / run_no)。
data: 待归档字节。
original_filename: 原始文件名。
@@ -32,8 +32,8 @@ class AutoTransferOutcome:
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes: list[str] | None = None,
recover_history: bool = True,
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
movement_date_from: str | None = None,
movement_date_to: str | None = None,
transfer_type: str | None = None,
sender: WeComSender | None = None,
recipients: list[str] | None = None) -> AutoTransferOutcome:
@@ -47,8 +47,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
deps: 注入依赖。
source_codes: 来源实例列表(缺省全部启用来源)。
recover_history: 是否执行历史恢复。
receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小
匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。
movement_date_from / movement_date_to: 可选异动日期范围(测试/排障缩小
匹配面;留空=全部积压;非法范围由匹配层抛 ValidationError)。
transfer_type: 调拨类型编码(D8 匹配创建必填——排程任务参数承载;
缺省 None 时匹配层 fail-closed 抛 TRANSFER_TYPE_REQUIRED)。
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
@@ -66,8 +66,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes=source_codes or [],
business_date=business_date,
deps=deps,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
transfer_type=transfer_type,
)
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
@@ -0,0 +1,375 @@
"""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
(占用排除口径,只读引用)、file_asset_storage、audit。
逻辑:桶数据 100% 可由 MinIO 归档重建(原件长期保留 + 档行 sheet/row_no 溯源),
清空不是破坏性操作而是「从证据重建」。安全不变量:先全量预解析入内存,
任一归档解析失败 → 整体中止 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」门禁且
缺席不删;本服务是显式的历史重建通道,仅管理端「清空并重新解析」动作
触发,禁止在运行期收料落地链路调用。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from sqlalchemy import func
from app import db
from app.core.errors import AppError
from app.models import ShippingInventorySource, TransferInvoiceItem, TransferMovementLedger
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.evidence_sync import (
_detect_natural_key_collapses,
_natural_key_collapse_event,
parse_archive_to_ledger_rows,
)
from app.services.in_transit_transfer.ledger_sync import (
RECORD_KIND_INBOUND,
FileMeta,
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"
@dataclass(frozen=True)
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,归档时间升序)。
"""
source_code: str
cleared: int = 0
reinserted: int = 0
date_skipped: int = 0
kept_unrebuildable: int = 0
unlinked_items: int = 0
collapses: int = 0
files: tuple[dict, ...] = field(default_factory=tuple)
def _load_published_inbound_profile(source_code: str):
"""加载来源当前绑定的「已发布 inbound」解析规则(与运行期取数同口径)。
核心逻辑:来源(enabled)→ 收料配置 → parsing_profile,须 published 且
purpose='inbound'——与 latest_ready_file 的规则门禁一致,防止重建用了
运行期不会使用的规则口径。只读查询。
Args:
source_code: 来源实例编码。
Returns:
ShippingInventoryParsingProfile;无启用来源/无收料配置/规则缺失或
非 published inbound 时返回 None(=无重建通道)。
"""
source = ShippingInventorySource.query.filter_by(
source_code=source_code, enabled=True).first()
if source is None:
return None
config = source.receipt_report_config
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
if profile is None or profile.status != "published" or profile.purpose != "inbound":
return None
return profile
def _partition_deletable(
source_code: str, files: list[ReparseableArchiveFile],
) -> 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=其中
证据可得(可删可重建)子集。
"""
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.transfer_executed.is_(False),
_effective_occupancy_filter(),
)
.all()
)
deletable = [row for row in candidates if row.source_file_id in available_ids]
return candidates, deletable
def preview_pending_match_reparse(*, source_code: str, now: datetime) -> dict:
"""清空并重新解析预检(只读,确认弹窗数据源,spec §6 入口)。
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」确认弹窗展示预检结果
时调用;不要在运行期收料落地链路调用(运行期走 evidence_sync,当日语义)。
files[].rows 预估口径(分辨率裁决 #5,取实现简单者):现有档行按
source_file_id 计数近似(含封存/占用行),不在预检里解析归档字节——预检
只读零副作用,行数仅供弹窗展示,精确值以执行结果为准。
Args:
source_code: 来源实例编码。
now: 保留期判定时刻(与执行时刻口径一致)。
Returns:
{files: [{archived_at, sha256, rows}(归档时间升序)],
profile: {code, version} | None,
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)
# 预估行数:现有档行按溯源文件计数(单查询分组;档行与归档文件多对一)。
file_ids = [record.file_id for record in files]
counts: dict[int, int] = {}
if file_ids:
counts = {
source_file_id: count
for source_file_id, count in db.session.query(
TransferMovementLedger.source_file_id,
func.count(TransferMovementLedger.id),
)
.filter(
TransferMovementLedger.source_code == source_code,
TransferMovementLedger.record_kind == RECORD_KIND_INBOUND,
TransferMovementLedger.source_file_id.in_(file_ids),
)
.group_by(TransferMovementLedger.source_file_id)
.all()
}
return {
"files": [
{
"archived_at": record.archived_at.isoformat(),
"sha256": record.sha256,
"rows": counts.get(record.file_id, 0),
}
for record in files
],
"profile": (
{"code": profile.profile_code, "version": profile.version}
if profile is not None else None
),
"clearable_rows": len(deletable),
"kept_rows": len(_candidates) - len(deletable),
}
def reparse_pending_match(*, source_code: str, operator: str, now: datetime) -> ReparseOutcome:
"""清空并重新解析一个来源的待匹配桶(spec §6;单事务,本函数提交)。
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」动作调用;
禁止在运行期收料落地链路调用(运行期走 evidence_sync,当日语义)。
删除前置动作(R9/方案 D):指向待删集合的 items(已取消匹配/已隔离的废弃
行)先同事务置空 ledger_record_id 再删行——普通 FK 无 ondelete,不置空则
PG flush 撞 IntegrityError 且每次重建复发;有效占用行的 items 不受影响。
Raises:
AppError: TRANSFER.REPARSE_PARSE_FAILED——①无已发布入站解析规则
(无重建通道,删了装不回去故拒绝执行);②任一归档文件解析
失败。两种情况整体中止且未删除任何行(先解析后删除是本函数
的安全不变量;解析阶段只读,中止时不 rollback 不触碰调用方
事务状态)。
"""
# [STEP 1] 重建通道与可重建文件清单(维护路径,无当日门禁;规则门禁与
# 运行期同口径——published inbound)。无规则=无重建通道,拒绝执行。
profile = _load_published_inbound_profile(source_code)
if profile is None:
raise AppError(
code=REPARSE_PARSE_FAILED,
message=f"reparse aborted: no published inbound parsing profile (source={source_code})",
http_status=422,
details={"source_code": source_code, "reason": "no_published_inbound_profile"},
)
repository = ShippingInboundFileRepository()
files = repository.list_reparseable_archived_files(source_code, now)
definition = profile.definition_json or {}
# [STEP 2] 全量预解析入内存(归档字节→原始行经仓库 _extract_movement_rows,
# 原始行→档行经 evidence_sync.parse_archive_to_ledger_rows 单一口径);
# 任一失败 → AppError 整体中止(此时未执行任何删除,一行未删)。
prepared: list[tuple[ReparseableArchiveFile, list[dict]]] = []
for record in files:
try:
data = file_asset_storage.get_bytes(record.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)
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,
"file_id": record.file_id,
"storage_key": record.storage_key,
"sha256": record.sha256,
"reason": str(exc)[:500],
},
) 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)
kept_unrebuildable = len(candidates) - len(deletable)
deletable_ids = [row.id for row in deletable]
unlinked_items = 0
if deletable_ids:
unlinked_items = (
TransferInvoiceItem.query
.filter(TransferInvoiceItem.ledger_record_id.in_(deletable_ids))
.update({TransferInvoiceItem.ledger_record_id: None}, synchronize_session=False)
)
for row in deletable:
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)时记,防重放刷事件。
reinserted = 0
date_skipped = 0
collapses = 0
file_summaries: list[dict[str, Any]] = []
for record, assembled in prepared:
outcome = sync_ledger_rows(
source_code=source_code,
record_kind=RECORD_KIND_INBOUND,
parsed_rows=assembled,
file_meta=FileMeta(
source_file_id=record.file_id,
file_version=record.file_version,
file_sha256=record.sha256,
),
now=now,
)
reinserted += outcome.inserted
date_skipped += outcome.date_skipped
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))
collapses += len(file_collapses)
file_summaries.append({
"file_id": record.file_id,
"sha256": record.sha256,
"archived_at": record.archived_at.isoformat(),
"inserted": outcome.inserted,
})
# [STEP 5] 审计事件 + 单次 commit(提交归属模式同 evidence_sync 桥:调用方
# 不感知事务时机;payload=操作人/来源/文件概要/规则 code+version/前后计数)。
db.session.add(build_transfer_audit_event(
event_type=REPARSE_EVENT,
aggregate_type="transfer_source",
aggregate_id=source_code,
actor_type="user",
actor_id=operator,
actor_display=operator,
result="success",
after={
"operator": operator,
"source_code": source_code,
"files": [
{"file_id": record.file_id, "sha256": record.sha256}
for record, _assembled in prepared
],
"profile_code": profile.profile_code,
"profile_version": profile.version,
"cleared": len(deletable),
"reinserted": reinserted,
"date_skipped": date_skipped,
"kept": kept_unrebuildable,
"unlinked_items": unlinked_items,
"collapses": collapses,
},
))
db.session.commit()
return ReparseOutcome(
source_code=source_code,
cleared=len(deletable),
reinserted=reinserted,
date_skipped=date_skipped,
kept_unrebuildable=kept_unrebuildable,
unlinked_items=unlinked_items,
collapses=collapses,
files=tuple(file_summaries),
)
@@ -4,13 +4,13 @@
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘;
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部收料记录,
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部入站记录,
规格 §10/D16:只读清单 + 计数,不可勾选执行)。
依赖:models、status、matching_service(启用类型范围并集圈档)。
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
manually_closed / success / duplicate_success 永久排除。
待匹配桶=启用类型范围并集圈档(复用匹配创建的固定条件底座:receipt/
未封存/有收料日期/未被有效 items 占用——D17 占用判定一致),无 item_id
待匹配桶=启用类型范围并集圈档(复用匹配创建的固定条件底座:inbound/
未封存/有异动日期/未被有效 items 占用——D17 占用判定一致),无 item_id
不可执行;匹配圈定后记录离开本桶,取消匹配释放后回归。
"""
@@ -20,7 +20,7 @@ from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from sqlalchemy import func
from sqlalchemy import func, or_
from app import db
from app.models import TransferAttempt, TransferInvoiceItem
@@ -38,6 +38,29 @@ AGING_CLOSED = "closed"
_BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
# 结果筛选切片(前端首页计数卡切片与池内筛选同口径);all=三态并集。
RESULT_FILTER_RECOVERABLE = "recoverable"
RESULT_FILTER_CLOSED = "closed"
RESULT_FILTER_UNKNOWN = "unknown"
RESULT_FILTER_ALL = "all"
_ALL_BACKLOG_STATUSES = (
_BACKLOG_RECOVERABLE,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
)
_RESULT_FILTER_STATUSES: dict[str, tuple[str, ...]] = {
RESULT_FILTER_ALL: _ALL_BACKLOG_STATUSES,
RESULT_FILTER_RECOVERABLE: (_BACKLOG_RECOVERABLE,),
RESULT_FILTER_CLOSED: (TransferStatus.MANUALLY_CLOSED.value,),
RESULT_FILTER_UNKNOWN: (TransferStatus.RESULT_UNKNOWN.value,),
}
RESULT_FILTER_CHOICES = (RESULT_FILTER_ALL, *_RESULT_FILTER_STATUSES.keys())
# 服务端分页默认值/上限(与已执行单 /documents 接口同口径:默认 20、上限 100)。
BACKLOG_PAGE_DEFAULT = 1
BACKLOG_PAGE_SIZE_DEFAULT = 20
BACKLOG_PAGE_SIZE_MAX = 100
@dataclass(frozen=True)
class BacklogItemDTO:
@@ -52,12 +75,12 @@ class BacklogItemDTO:
age_days: int
aging_level: str
last_attempt_at: Optional[str] = None
receipt_date: Optional[str] = None
movement_date: Optional[str] = None
material_name: Optional[str] = None
from_warehouse: Optional[str] = None
to_warehouse: Optional[str] = None
lot_no: Optional[str] = None
receipt_quantity: Optional[str] = None
movement_quantity: Optional[str] = None
external_quantity: Optional[str] = None
# 最近一次结果码(如 blocked_file_removed);供前端区分「文件已移除」徽标
result_code: Optional[str] = None
@@ -67,8 +90,8 @@ class BacklogItemDTO:
class PendingMatchRecordDTO:
"""「待匹配」桶单项(D16):档记录只读投影——无 item_id,不可勾选执行。
字段与规格 §12.3 只读清单列一致(单号/料号/品名/收料日期/来源/数量);
quantity 为档原值文本(Decimal 文本,与 items.receipt_quantity 同约定)。
字段与规格 §12.3 只读清单列一致(单号/料号/品名/异动日期/来源/数量);
quantity 为档原值文本(Decimal 文本,与 items.movement_quantity 同约定)。
"""
ledger_record_id: int
@@ -90,10 +113,33 @@ class BacklogSummaryDTO:
warn_3d: int = 0
escalate_5d: int = 0
critical_7d: int = 0
# 首页第 4 张数字卡(D16):已落档尚未匹配的外部收料记录数。
# 首页第 4 张数字卡(D16):已落档尚未匹配的外部入站记录数。
pending_match_count: int = 0
@dataclass(frozen=True)
class BacklogPageDTO:
"""待处理池分页结果(2026-10-16 服务端分页:池为无界增长集合,
全量拉取在千行级放大网络载荷与老化批量查询规模;items=当前页切片,
total=筛选后全量计数供前端分页器)。"""
items: list[BacklogItemDTO]
total: int
page: int
page_size: int
@dataclass(frozen=True)
class PendingMatchPageDTO:
"""「待匹配」桶分页结果(951 行级大池;圈档并集无法合成单查询,
计数在 Python 侧取 len,但序列化/传输只出当前页)。"""
records: list[PendingMatchRecordDTO]
total: int
page: int
page_size: int
def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str:
"""按积压天数计算老化等级(0-2 普通 / 3 预警 / 5 升级 / 7+ 严重)。"""
if age_days >= critical:
@@ -129,40 +175,55 @@ def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
return {item_id: latest for item_id, latest in rows}
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None):
"""待处理池基础查询(状态集合 + 可选来源/关键字过滤)。
排序:收料日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键,
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
以此排序会让正在处理的行在列表中跳位。
keyword 与前端池内筛选同字段集(Invoice/料号/品名/来源,2026-10-16 随
服务端分页下推),大小写不敏感子串匹配(ilike)。
Args:
now: 判定时刻(默认当前时间)。
statuses: 池内状态白名单(result_filter 切片或三态并集)。
source_code: 可选来源过滤。
keyword: 可选关键字(子串大小写不敏感)。
Returns:
BacklogItemDTO 列表。
未排序的 SQLAlchemy Query(排序由调用方统一拼 _BACKLOG_ORDER_BY)。
"""
current = now or datetime.utcnow()
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status.in_([
_BACKLOG_RECOVERABLE,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
]),
)
query = TransferInvoiceItem.query.filter(TransferInvoiceItem.status.in_(statuses))
if source_code:
query = query.filter_by(source_code=source_code)
pool_rows = query.order_by(
TransferInvoiceItem.receipt_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
TransferInvoiceItem.id.asc(),
).all()
latest_map = _latest_attempt_times([row.id for row in pool_rows])
if keyword:
like = f"%{keyword}%"
query = query.filter(or_(
TransferInvoiceItem.invoice_no.ilike(like),
TransferInvoiceItem.material_no.ilike(like),
TransferInvoiceItem.material_name.ilike(like),
TransferInvoiceItem.source_code.ilike(like),
))
return query
# 全链路统一业务稳定键排序(异动日期→数据源→Invoice→创建时间→id 兜底)。
_BACKLOG_ORDER_BY = (
TransferInvoiceItem.movement_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
TransferInvoiceItem.id.asc(),
)
def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[BacklogItemDTO]:
"""池行 → DTO 组装(老化判定需 Attempt 最近时间,批量单条 GROUP BY 查询)。
Args:
rows: 当前页(或全量)池行,须已按业务稳定键排序。
current: 老化判定的当前时刻。
Returns:
BacklogItemDTO 列表(与输入同序)。
"""
latest_map = _latest_attempt_times([row.id for row in rows])
output: list[BacklogItemDTO] = []
for item in pool_rows:
for item in rows:
latest = latest_map.get(item.id)
base = latest if latest is not None else item.updated_at
age = max(0, int((current - base).total_seconds() // 86400))
@@ -182,23 +243,88 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
age_days=age,
aging_level=level,
last_attempt_at=latest.isoformat() if latest is not None else None,
receipt_date=item.receipt_date,
movement_date=item.movement_date,
material_name=item.material_name,
from_warehouse=item.from_warehouse,
to_warehouse=item.to_warehouse,
lot_no=item.lot_no,
receipt_quantity=str(item.receipt_quantity) if item.receipt_quantity is not None else None,
movement_quantity=str(item.movement_quantity) if item.movement_quantity is not None else None,
external_quantity=str(item.external_quantity) if item.external_quantity is not None else None,
result_code=item.result_code,
))
return output
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)——全量(兼容口径,未分页)。
排序:异动日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键,
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
以此排序会让正在处理的行在列表中跳位。
分页场景请用 list_backlog_page(2026-10-16),本函数保留供无参兼容调用。
Args:
now: 判定时刻(默认当前时间)。
source_code: 可选来源过滤。
Returns:
BacklogItemDTO 列表。
"""
current = now or datetime.utcnow()
rows = _backlog_base_query(
_ALL_BACKLOG_STATUSES, source_code=source_code
).order_by(*_BACKLOG_ORDER_BY).all()
return _backlog_dtos(rows, current)
def list_backlog_page(
*,
now: datetime | None = None,
source_code: str | None = None,
keyword: str | None = None,
result_filter: str = RESULT_FILTER_ALL,
page: int = BACKLOG_PAGE_DEFAULT,
page_size: int = BACKLOG_PAGE_SIZE_DEFAULT,
) -> BacklogPageDTO:
"""待处理池分页查询(2026-10-16 服务端分页 + 筛选下推)。
【AI 触发时机】前端待处理池视图按页/筛选拉取时经 API 调用;禁止绕过
result_filter 白名单(fail-closed,非 all/recoverable/closed/unknown 由
API 层 400)。筛选(result_filter/keyword)与计数口径一致:total 为
筛选后全量计数,供前端分页器展示;老化批量查询只对当前页行执行
(千行级池的响应规模从 O(池) 降到 O(页))。
Args:
now: 判定时刻(默认当前时间)。
source_code: 可选来源过滤。
keyword: 可选关键字(Invoice/料号/品名/来源,子串大小写不敏感)。
result_filter: 结果切片(all/recoverable/closed/unknown)。
page: 页码(1 起)。
page_size: 每页行数(1..100)。
Returns:
BacklogPageDTO(items=当前页切片,total=筛选后全量计数)。
"""
current = now or datetime.utcnow()
statuses = _RESULT_FILTER_STATUSES.get(result_filter)
if statuses is None:
# 防御:API 层已做白名单 400,这里兜底回三态并集(service 直调场景不炸)
statuses = _ALL_BACKLOG_STATUSES
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
total = base.count()
rows = (
base.order_by(*_BACKLOG_ORDER_BY)
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return BacklogPageDTO(items=_backlog_dtos(rows, current), total=total, page=page, page_size=page_size)
def list_pending_match_records() -> list[PendingMatchRecordDTO]:
"""首页待办看板「待匹配」桶清单(D16:已抓取尚未匹配的外部收料记录,只读)。
"""首页待办看板「待匹配」桶清单(D16:已抓取尚未匹配的外部入站记录,只读)。
数据源=启用类型范围并集圈档(matching_service.circle_ledger_records_scope_union:
固定条件 receipt/未封存/有收料日期/未被有效 items 占用,与匹配创建圈档和 D17
固定条件 inbound/未封存/有异动日期/未被有效 items 占用,与匹配创建圈档和 D17
占用判定同一实现)。数字变化口径:文件落地→涨;被匹配圈定→离开(占用);
取消匹配→回归(释放占用);执行成功→封存恒排除。
@@ -206,7 +332,7 @@ def list_pending_match_records() -> list[PendingMatchRecordDTO]:
「去匹配」引导,禁止任何勾选执行入口。
Returns:
PendingMatchRecordDTO 列表(圈档稳定排序:收料日期 → 来源 → 单号 → id)。
PendingMatchRecordDTO 列表(圈档稳定排序:异动日期 → 来源 → 单号 → id)。
"""
return [
PendingMatchRecordDTO(
@@ -222,6 +348,44 @@ def list_pending_match_records() -> list[PendingMatchRecordDTO]:
]
def list_pending_match_records_page(
*,
page: int = BACKLOG_PAGE_DEFAULT,
page_size: int = BACKLOG_PAGE_SIZE_DEFAULT,
) -> PendingMatchPageDTO:
"""「待匹配」桶分页清单(2026-10-16 服务端分页;只读语义与全量版一致)。
圈档=启用类型范围并集(多类型逐范围圈取后按 id 去重,无法合成单查询),
故 total 在 Python 侧取 len;切片后仅当前页做 DTO 投影/序列化,
951 行级大池的响应规模从 O(桶) 降到 O(页)。
Args:
page: 页码(1 起)。
page_size: 每页行数(1..100)。
Returns:
PendingMatchPageDTO(records=当前页切片,total=桶全量计数)。
"""
rows = circle_ledger_records_scope_union()
start = (page - 1) * page_size
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),
page=page,
page_size=page_size,
)
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
"""计算待处理池汇总计数、老化分级与待匹配桶计数。"""
items = list_backlog(now=now)
@@ -8,7 +8,7 @@
matching_id 圈定名下 ready 未建单行退役为 cancelled——
【出生翻转/D17 占用释放出口(规格 §9)】出生行 run_id=None,必须按匹配
圈定才能命中:ready 行退役(队列不再可见、执行门禁拒绝)+ 匹配→cancelled
(阻断/未成熟行不再占用其圈定的档记录),档记录随即释放、可被后续匹配
(阻断行不再占用其圈定的档记录),档记录随即释放、可被后续匹配
重新圈定;取消路径不写档(占用释放由状态判定自然达成)。
"""
@@ -71,7 +71,7 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
# - ready 且未建单的行 → cancelled(出生行 run_id=None,必须按匹配圈定
# 才能命中——否则取消后行仍 ready,队列双份可见、可与重圈匹配双双
# 执行=同批档记录二次写 ERP);
# - blocked/not_matured 行保留阻断/未成熟解释(不占执行面),其占用
# - blocked 行保留阻断解释(不占执行面),其占用
# 随匹配状态=cancelled 释放(占用判定见 matching_service);
# - executing/result_unknown 行不触碰(在飞/结果裁决中,既有取消语义)。
# 取消路径不写档(占用释放由状态判定自然达成)。
@@ -14,8 +14,9 @@ from decimal import Decimal
from typing import Iterable
# ---- 一期冻结错误码(TDD §7.3)-------------------------------------------
# 【TRANSFER_INBOUND_NOT_MATURED 已退役 2026-10-16】成熟概念删除(未上线期不设
# 兼容层);前端四语言 errors.json 同键一并移除。
TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED"
TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED"
TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
@@ -32,7 +33,6 @@ TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED"
KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
TRANSFER_PERMISSION_DENIED,
TRANSFER_RECEIPT_NOT_MATURED,
TRANSFER_FILE_NOT_READY,
TRANSFER_FILE_SCHEMA_INVALID,
TRANSFER_INVOICE_CONFLICT,
@@ -67,7 +67,6 @@ class MatchingCountsDTO:
"""匹配计数。"""
file_invoice_count: int = 0
not_matured_count: int = 0
matched_count: int = 0
executable_count: int = 0
blocked_count: int = 0
@@ -101,13 +100,13 @@ class MatchingItemDTO:
to_warehouse: str
to_quantity: Decimal
result: str
receipt_date: str | None = None
movement_date: str | None = None
reason: str = ""
external_document_no: str | None = None
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
lot_no: str = ""
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
receipt_warehouse_code: str = ""
# 入站文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
movement_warehouse_code: str = ""
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):展示与 ERP 写入行输入,
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
unit: str = ""
@@ -129,14 +128,13 @@ class MatchingSummaryDTO:
"""匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。
estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单
五元组 (external_org, source_code, receipt_date, from_warehouse, to_warehouse)
五元组 (external_org, source_code, movement_date, from_warehouse, to_warehouse)
去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。
"""
matching_id: str
status: str
business_date: str
eligible_receipt_date_to: str
expires_at: str
counts: MatchingCountsDTO
estimated_transfer_quantity: str
@@ -1,11 +1,13 @@
"""在途调拨业务日期与成熟度策略。
"""在途调拨业务日期与日期解析。
用途:固定业务时区 Asia/Shanghai,实现 T+lag 成熟规则(默认 T+2:收料日期 ≤ T-2
可匹配,T-1/当天 not_matured,未来日期阻断);统一 parse_date 归一化收料日期
(ISO + DSV SSRS 美式 MM/DD/YYYY[ HH:MM:SS])。
依赖:标准库 zoneinfo / datetime;可选 Flask current_app(读成熟滞后配置)。
用途:固定业务时区 Asia/Shanghai,统一 parse_date 归一化异动日期(ISO + DSV SSRS
美式 MM/DD/YYYY[ HH:MM:SS]);提供业务日换算与 UTC 存储窗口换算。
依赖:标准库 zoneinfo / datetime。
逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync
复用,避免各服务各自计算导致口径漂移。
【成熟度规则已退役 2026-10-16】数据无成熟属性——日期边界由调用方入参严格
给定(交互匹配=用户选择的范围;自动排程=任务 T−N 偏移参数);引擎只保留
「截止 ≤ 业务日期」的入参合法性与未来日期阻断(数据错误)。
"""
from __future__ import annotations
@@ -15,15 +17,6 @@ from zoneinfo import ZoneInfo
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
# 成熟度结果
MATURITY_ELIGIBLE = "eligible"
MATURITY_NOT_MATURED = "not_matured"
MATURITY_FUTURE = "future"
# 成熟滞后天数默认值(T+2:收料日期 ≤ T-2 才可匹配;与海外的时差余量)。
# 可经环境变量 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS 覆盖(settings 装载)。
DEFAULT_MATURITY_LAG_DAYS = 2
# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。
_US_DATE_FORMATS = (
"%m/%d/%Y %H:%M:%S",
@@ -35,7 +28,7 @@ _US_DATE_FORMATS = (
def parse_date(value: date | datetime | str) -> date:
"""将 date/datetime 或日期字符串归一化为 date。
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 收料);
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 入站文件);
均失败则 ValueError(fail-closed)。
Args:
@@ -59,7 +52,7 @@ def parse_date(value: date | datetime | str) -> date:
return datetime.fromisoformat(text).date()
except ValueError:
pass
# [STEP] DSV SSRS 收料 Date Received:美式月/日/年(可带时分秒)。
# [STEP] DSV SSRS 入站 Date Received:美式月/日/年(可带时分秒)。
for fmt in _US_DATE_FORMATS:
try:
return datetime.strptime(text, fmt).date()
@@ -105,53 +98,3 @@ def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, dat
.replace(tzinfo=None)
)
return start_utc, start_utc + timedelta(hours=24)
def maturity_lag_days() -> int:
"""读取成熟滞后天数(app 配置优先,缺省回退 DEFAULT_MATURITY_LAG_DAYS)。
Returns:
成熟滞后天数 lag;无 Flask app 上下文(纯单元测试/脚本)时回退默认值,
保持策略函数可纯调用。
"""
try:
from flask import current_app
return int(current_app.config.get(
"IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS") or DEFAULT_MATURITY_LAG_DAYS)
except RuntimeError: # 无 app 上下文
return DEFAULT_MATURITY_LAG_DAYS
def maturity_status(receipt_date: date | str, business_date: date | str,
lag_days: int | None = None) -> str:
"""按 T+lag 规则判定收料日期成熟度(默认 lag=2)。
Args:
receipt_date: 收料日期。
business_date: 当前业务日期 T。
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
Returns:
'eligible'(receipt ≤ T-lag)、'not_matured'(T-lag < receipt ≤ T)或
'future'(receipt > T,结构化阻断)。
"""
receipt = parse_date(receipt_date)
business = parse_date(business_date)
lag = maturity_lag_days() if lag_days is None else int(lag_days)
if receipt > business:
return MATURITY_FUTURE
if receipt > business - timedelta(days=lag):
return MATURITY_NOT_MATURED
return MATURITY_ELIGIBLE
def eligible_receipt_date_to(business_date: date | str, lag_days: int | None = None) -> date:
"""返回可进入匹配的收料截止日期(业务日期 T - lag 天,默认 T-2)。
Args:
business_date: 当前业务日期。
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
Returns:
T - lag 天。
"""
lag = maturity_lag_days() if lag_days is None else int(lag_days)
return parse_date(business_date) - timedelta(days=lag)
@@ -2,8 +2,8 @@
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:movement_file_repository / capability_client / matching_service / models / Flask config。
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
逻辑:默认实现直接接线真实链路 —— 入站文件行读取走 movement_file_repository
(复用 ShippingReceiptReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed);
策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_
@@ -20,7 +20,7 @@ from flask import current_app
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.capability_client import CapabilityClient
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
from app.services.in_transit_transfer.movement_file_repository import ShippingInboundFileRepository
from app.services.in_transit_transfer.matching_service import (
RouteMapping,
RouteNotResolvedError,
@@ -39,7 +39,7 @@ class DefaultRouteResolver:
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
inventory_match 源优先「入站文件仓库列 == 货代仓库」精确匹配,匹配不到回退
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
"""
@@ -50,7 +50,7 @@ class DefaultRouteResolver:
Args:
source_code: 来源实例编码(须启用)。
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
warehouse_code: 入站文件「仓库」列原值(inventory_match 源的映射匹配键)。
Returns:
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
Raises:
@@ -64,7 +64,7 @@ class DefaultRouteResolver:
).all()
selected = None
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
# [匹配] 入站仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
key = str(warehouse_code or '').strip().upper()
if key:
@@ -147,7 +147,7 @@ def get_transfer_dependencies() -> TransferDeps:
if _override is not None:
return _override
return TransferDeps(
file_repository=ShippingReceiptFileRepository(),
file_repository=ShippingInboundFileRepository(),
rpa_trigger=_DefaultRpaTrigger(),
route_resolver=DefaultRouteResolver(),
capabilities=_build_capability_client(),
@@ -156,18 +156,18 @@ def get_transfer_dependencies() -> TransferDeps:
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
"""默认入站 RPA 触发器:委托真实触发服务(trigger_inbound_rpa)。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
真实链路 = 落单元行 + 原子写 trigger 文件;来源/ShippingReceiptReportConfig 缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时
直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。
另在本类前置守卫: ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时
直接返回 RPA_INBOUND_PROFILE_MISSING,不触发徒劳抓取。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
# [守卫] ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳:
# 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
@@ -176,10 +176,10 @@ class _DefaultRpaTrigger:
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is not None:
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'}
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
return {'ok': False, 'error_code': 'RPA_INBOUND_PROFILE_MISSING'}
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
outcome = trigger_inbound_rpa(source_code=source_code, business_date=business_date, reason=reason)
return {
"ok": bool(outcome.get("ok")),
"callback_id": outcome.get("callback_id"),
@@ -1,6 +1,6 @@
"""services/in_transit_transfer/evidence_sync.py
用途:收料证据同步——把来源最新可用收料文件解析并镜像落档(库存异动档
用途:入站证据同步——把来源最新可用入站文件(ShippingReceiptReport RPA 产物)解析并镜像落档(库存异动档
transfer_movement_ledger,主链路),一次解析、写档不写明细。
依赖:file_parser / ledger_sync / source_file_status / matching_service
(_latest_usable_report_file 复用)/ contracts / models / audit。
@@ -8,8 +8,8 @@
——items 改为匹配创建时从档圈定(见 matching_service);落地产物=档行:
①按自然键查档不存在 → 插入(record_kind/溯源五列随行);
②同文件重落(sha 一致)→ 幂等跳过(档无 TTL,完全不动行);
③证据变化 → 原行更新业务镜像列 + 换溯源(ledger_sync 五分类语义);
④文件缺席的档行保留不删(收料 RPA 非全量导出,缺席≠删除);
③证据变化 → 原行更新业务镜像列 + 换溯源(ledger_sync 六分类语义);
④文件缺席的档行保留不删(入站 RPA 非全量导出,缺席≠删除);
⑤已执行封存行(transfer_executed=true)永不更新永不复活。
组装口径:解析行按调拨明细粒度 (doc_no, material_code, movement_date)
聚合为领域行(数量相加、其余取组内首行、sheet/row_no 取首行)——与旧
@@ -17,8 +17,9 @@
严格数量比对」的数量语义不因翻转漂移。
全程零外部调用(不查 ERP、不触发 RPA);不 commit 只 flush(提交归调用
方:落地桥自行 commit,匹配/重查随主事务)。
【档自然键坍缩守卫 终审 I3】组装产物按自然键 (doc_no, line_no, line_seq,
in_out_flag) 复检:同键批内 ≥2 行且 material_code 不同(同单号多料号且
【档自然键坍缩守卫 终审 I3】组装产物按档自然键行级六成分 (doc_no, line_no,
line_seq, in_out_flag, carton_id, lot_no) 复检:同键批内 ≥2 行且 material_code
不同(同单号多料号且
行级项次全空的输入)→ 每个坍缩键写一条 ledger_natural_key_collapse 审计
事件(结果=第二料号行被幂等吞掉,首见为准,数据行为不变)——把静默丢行
变显式可观测;事件只在批内实际落档(inserted/updated>0)时打,幂等重落
@@ -26,10 +27,14 @@
同款防刷口径)。
【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析
失败标记(parse_failed 三列置空);桥入口同步失败先 rollback(保持桥隔离),
仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID / ReceiptFileSchemaError)
仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID / MovementFileSchemaError)
把失败事实独立 commit 落到当前可用文件上。
【对齐入口退役 2026-10-14】align_scope_rows 已删除:匹配/重查不再对文件
兜底重解析,改为对档对账(重查见 retry_service.requery_items 对档 reconciliation)。
【解析口径单一化 2026-10-15(spec §6)】「原始行→档行」的解析+组装抽为模块级
纯函数 parse_archive_to_ledger_rows:运行期本模块与维护重建
(backlog_reparse_service 清空并重解析)共用同一实现,杜绝两套解析漂移;
归档字节→原始行的提取段仍在 movement_file_repository._extract_movement_rows。
"""
from __future__ import annotations
@@ -43,19 +48,19 @@ from app import db
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
MovementFileSchemaError,
ParsedMovementRow,
parse_movement_rows,
)
from app.services.in_transit_transfer.ledger_sync import (
RECORD_KIND_RECEIPT,
RECORD_KIND_INBOUND,
FileMeta,
sync_ledger_rows,
)
from app.services.in_transit_transfer.matching_service import _latest_usable_report_file
from app.services.in_transit_transfer.source_file_status import (
clear_receipt_parse_failure,
record_receipt_parse_failure,
clear_inbound_parse_failure,
record_inbound_parse_failure,
)
# 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码),
@@ -72,7 +77,8 @@ LEDGER_NATURAL_KEY_COLLAPSE_EVENT = "ledger_natural_key_collapse"
@dataclass(frozen=True)
class SyncOutcome:
"""一次来源落档的结果计数(审计与兜底日志的数据源;五分类随 ledger_sync)。"""
"""一次来源落档的结果计数(审计与兜底日志的数据源;计数随 ledger_sync 同源,
date_skipped(异动日期空值)在 ledger_sync 落档过滤阶段消化,不透传本层)。"""
source_code: str
file_sha256: str
@@ -84,25 +90,26 @@ class SyncOutcome:
def _assemble_ledger_rows(
parsed: list[ParsedReceiptRow],
parsed: list[ParsedMovementRow],
raw_rows: list[Any],
) -> list[dict]:
"""把解析行组装为落档领域行 dict(档断言等价于原 items 断言的粒度桥)。
核心逻辑:[STEP 1] 原始行按 (sheet, row_no) 建索引——ParsedReceiptRow 无扩展
核心逻辑:[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 账面)语义不变。
注意:原始行无「项次」且同单号多料号时,自然键 (doc_no, line_no='', ...)
会折叠多料号行为一条档记录(档自然键不含料号,规格 §4.2)——真实 WMS 导出
注意:原始行无「项次」且同单号多料号时,自然键 (doc_no, line_no='', ...,
carton_id 等值, lot_no 等值) 会折叠多料号行为一条档记录(档自然键不含料号,
规格 §4.2;carton_id/lot_no 为键成分,批内等值才折叠)——真实 WMS 导出
携带项次列,不命中该形态;该坍缩形态由 _detect_natural_key_collapses 检测并
落 ledger_natural_key_collapse 审计事件(终审 I3,静默丢行 → 显式可观测)。
Args:
parsed: 已校验解析行(parse_movement_rows 产物)。
raw_rows: 原始领域行 dict 列表(ReadyReceiptFile.rows,扩展字段来源)。
raw_rows: 原始领域行 dict 列表(ReadyInboundFile.rows,扩展字段来源)。
Returns:
领域行 dict 列表(键=movement 契约 field code + 行级溯源 sheet_name/row_no,
即 sync_ledger_rows 的 parsed_rows 契约)。
@@ -117,7 +124,7 @@ def _assemble_ledger_rows(
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.receipt_date.isoformat())
key = (row.invoice_no, row.material_no, row.movement_date.isoformat())
group = groups.get(key)
if group is None:
group = {
@@ -131,16 +138,16 @@ def _assemble_ledger_rows(
"warehouse_code": row.warehouse_code,
"storage_code": str(raw.get("storage_code") or "").strip(),
"lot_no": row.lot_no,
"quantity": Decimal(str(row.receipt_quantity)),
"quantity": Decimal(str(row.movement_quantity)),
"unit": row.unit,
"movement_date": row.receipt_date.isoformat(),
"movement_date": row.movement_date.isoformat(),
"line_seq": str(raw.get("line_seq") or "").strip(),
"order_type": str(raw.get("order_type") or "").strip(),
"odm_id": str(raw.get("odm_id") or "").strip(),
"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(),
# 🔖预留列(出货报告确认后直接映射):收料侧照常透传原值。
# 🔖预留列(出货报告确认后直接映射):入站侧照常透传原值。
"doc_nature": str(raw.get("doc_nature") or "").strip(),
"movement_type": str(raw.get("movement_type") or "").strip(),
"reason_code": str(raw.get("reason_code") or "").strip(),
@@ -154,7 +161,7 @@ def _assemble_ledger_rows(
ordered.append(group)
else:
# [数量聚合] 同 (单号,料号,日期) 多行数量相加(与旧 items 汇总同口径)。
group["quantity"] = group["quantity"] + Decimal(str(row.receipt_quantity))
group["quantity"] = group["quantity"] + Decimal(str(row.movement_quantity))
rows: list[dict] = []
for group in ordered:
@@ -179,24 +186,28 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
"""检测批内档自然键坍缩(终审 I3,纯函数不改行)。
【AI 触发时机】sync_source_rows 组装落档前调用;不要在匹配/执行链路调用。
判定:档自然键四成分 (doc_no, line_no, line_seq, in_out_flag)(source_code/
record_kind 整批恒定不入键)批内出现 ≥2 行且 material_code 不同 → 该键坍缩
(落地侧第二料号行必被幂等吞掉)。同料号多行不算坍缩(数量聚合合法形态,
且规格 §4.2 判据即料号不同)。首见序返回,保证审计内容确定。
判定:档自然键行级六成分 (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
不同 → 该键坍缩(落地侧第二料号行必被幂等吞掉)。同料号多行不算坍缩(数量
聚合合法形态,且规格 §4.2 判据即料号不同)。首见序返回,保证审计内容确定。
Args:
rows: _assemble_ledger_rows 产物(成分已归一化)。
Returns:
坍缩键信息列表(仅含坍缩键):doc_no/line_no/line_seq/in_out_flag +
material_codes(首见序全量料号)+ dropped_material_codes(首见后被吞料号)。
坍缩键信息列表(仅含坍缩键):doc_no/line_no/line_seq/in_out_flag/
carton_id/lot_no + material_codes(首见序全量料号)+ dropped_material_codes
(首见后被吞料号)。
"""
seen: dict[tuple[str, str, str, str], dict] = {}
seen: dict[tuple[str, str, str, str, str, str], dict] = {}
for row in rows:
key = (
_natural_key_text(row.get("doc_no")),
_natural_key_text(row.get("line_no")),
_natural_key_text(row.get("line_seq")),
_natural_key_text(row.get("in_out_flag")),
_natural_key_text(row.get("carton_id")),
_natural_key_text(row.get("lot_no")),
)
material = _natural_key_text(row.get("material_code"))
entry = seen.get(key)
@@ -209,6 +220,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],
"material_codes": entry["materials"],
"dropped_material_codes": entry["dropped"],
}
@@ -227,8 +239,9 @@ def _natural_key_collapse_event(*, source_code: str, collapse: dict):
result='failure':数据质量降级——行被吞是既成事实,须运维介入核导出模板)。
"""
natural_key = "/".join((
source_code, RECORD_KIND_RECEIPT,
source_code, RECORD_KIND_INBOUND,
collapse["doc_no"], collapse["line_no"], collapse["line_seq"], collapse["in_out_flag"],
collapse["carton_id"], collapse["lot_no"],
))
return build_transfer_audit_event(
event_type=LEDGER_NATURAL_KEY_COLLAPSE_EVENT,
@@ -239,9 +252,10 @@ def _natural_key_collapse_event(*, source_code: str, collapse: dict):
actor_type="system",
result="failure",
after={
"source_code": source_code, "record_kind": RECORD_KIND_RECEIPT,
"source_code": source_code, "record_kind": RECORD_KIND_INBOUND,
"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"],
"material_codes": collapse["material_codes"],
"dropped_material_codes": collapse["dropped_material_codes"],
"resolution": "first_seen_wins",
@@ -249,10 +263,35 @@ def _natural_key_collapse_event(*, source_code: str, collapse: dict):
)
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
"""解析来源最新可用收料文件并幂等落档(零外部调用,flush 不 commit)。
def parse_archive_to_ledger_rows(*, source_code: str, rows: list[dict]) -> list[dict]:
"""归档原始行 → 档行领域 dict 列表(解析+组装单一口径,运行期/重建共用)。
【AI 触发时机】收料 RPA 回调桥(sync_and_commit_for_callback)与来源解析
【AI 触发时机】运行期落档(sync_source_rows)与维护重建
(backlog_reparse_service 清空并重解析,spec §6)在把归档原始行组装为落档
领域行时都必须经本函数;禁止任何一方绕开自组解析(两套解析=映射漂移温床)。
「归档字节 → 本函数入参原始行」的提取段在
movement_file_repository._extract_movement_rows(latest_ready_file 与重建路径
同一实现),本函数承接其后的行校验解析(parse_movement_rows)与明细粒度
聚合组装(_assemble_ledger_rows)——两段合起来才是完整的「归档字节→档行」。
Args:
source_code: 来源实例编码(解析行来源身份一致性校验)。
rows: 归档原始行 dict 列表(ReadyInboundFile.rows 同构:领域字段 +
溯源 sheet/row_no)。
Returns:
领域行 dict 列表(sync_ledger_rows 的 parsed_rows 契约)。
Raises:
MovementFileSchemaError: 任一行必填缺失/非法值(调用方按场景分层处理:
运行期落解析失败标记;重建整体中止 TRANSFER.REPARSE_PARSE_FAILED)。
"""
parsed = parse_movement_rows(source_code=source_code, rows=rows)
return _assemble_ledger_rows(parsed, rows)
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
"""解析来源最新可用入站文件并幂等落档(零外部调用,flush 不 commit)。
【AI 触发时机】入站 RPA 回调桥(sync_and_commit_for_callback)与来源解析
失败重试入口调用;不要在匹配/重查链路调用(匹配从档圈定,不写档)。
【解析失败分层 2026-09-29】成功返回前清除当前可用文件的解析失败标记
@@ -271,18 +310,18 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date)
if ready is None:
return None
# [STEP 1] 解析:schema 类失败原样上抛(桥内 rollback + 落解析失败标记)。
parsed = parse_movement_rows(source_code=source_code, rows=ready.rows)
# [STEP 1] 解析+组装领域行(明细粒度聚合):经 parse_archive_to_ledger_rows
# 单一口径(运行期与重建共用,schema 类失败原样上抛——桥内 rollback +
# 落解析失败标记)。
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=list(ready.rows))
# [STEP 2] 组装领域行(明细粒度聚合)并幂等落档;ledger_sync 只 flush 不
# commit(提交归调用方:桥自行 commit,匹配/重查随主事务)。
# 溯源文件 id:当前可用归档文件(Fake 仓库测试场景/文件已清理时为 None,
# 档事实留存不依赖文件存在)。
# [STEP 2] 幂等落档;ledger_sync 只 flush 不 commit(提交归调用方:桥自行
# commit,匹配/重查随主事务)。溯源文件 id:当前可用归档文件(Fake 仓库
# 测试场景/文件已清理时为 None,档事实留存不依赖文件存在)。
report = _latest_usable_report_file(source_code)
assembled = _assemble_ledger_rows(parsed, ready.rows)
outcome = sync_ledger_rows(
source_code=source_code,
record_kind=RECORD_KIND_RECEIPT,
record_kind=RECORD_KIND_INBOUND,
parsed_rows=assembled,
file_meta=FileMeta(
source_file_id=report.id if report is not None else None,
@@ -318,7 +357,7 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
result="success",
after={
"file_sha256": result.file_sha256,
"record_kind": RECORD_KIND_RECEIPT,
"record_kind": RECORD_KIND_INBOUND,
"inserted": result.inserted, "updated": result.updated,
"skipped": result.skipped, "sealed_skipped": result.sealed_skipped,
"cross_flagged": result.cross_flagged,
@@ -328,23 +367,23 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。只 flush 不 commit,
# 提交归调用方。无可用 ORM 文件时为 no-op。
if report is not None and report.parse_failed_at is not None:
clear_receipt_parse_failure(report=report)
clear_inbound_parse_failure(report=report)
return result
def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: datetime) -> bool:
"""收料回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
"""入站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
【AI 触发时机】:收料 RPA 回调 success 终态落文件后由
shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路
的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。
【AI 触发时机】:入站 RPA 回调 success 终态落文件后由
shipping_notice 域 ShippingReceiptReport 归档存储的桥函数调用——桥是记账
不是入站链路的正确性依赖,任何异常不得向 ShippingReceiptReport 归档主链路传播(B3:必须自行 commit)。
【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上;
丢失的落档由回调重试/来源「重试 RPA」入口(本地重解析)兜底
(原 align 兜底入口已随对档对账切换退役)。
Args:
source_code: 来源实例编码(收料单元行上的 source_code)。
source_code: 来源实例编码(入站单元行上的 source_code)。
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
now: 落档时间基准。
Returns:
@@ -367,27 +406,27 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged)
return True
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
# [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,落档崩溃
# 绝不允许波及收料归档终态;丢失的落档由回调重试/人工重取兜底。
# [桥隔离] 为什么吞异常:桥是记账不是入站链路的正确性依赖,落档崩溃
# 绝不允许波及 ShippingReceiptReport 归档终态;丢失的落档由回调重试/人工重取兜底。
current_app.logger.warning(
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
db.session.rollback()
# [解析失败分层 2026-09-29] rollback 之后再写标记,避免脏会话污染写路径;
# 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / ReceiptFileSchemaError)
# 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / MovementFileSchemaError)
# 落库——通用异常(网络/DB 故障等)不是文件解析问题,不落标记。标记写入后
# 独立 commit(B3:桥自行提交;落档数据已回滚,本次 commit 只持久化失败
# 事实),桥隔离语义保持,仍返回 False。
# [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows
# 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。
# 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉,
# B3(任何异常不得向收料归档主链路传播)优先于标记落库,丢失标记由下次重试补。
# B3(任何异常不得向 ShippingReceiptReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。
try:
code = getattr(exc, "code", None) or ""
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, ReceiptFileSchemaError):
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, MovementFileSchemaError):
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
report = _latest_usable_report_file(source_code)
if report is not None:
record_receipt_parse_failure(
record_inbound_parse_failure(
report=report,
error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID),
error_message=str(detail)[:2000],
@@ -400,7 +439,7 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
def _default_deps():
"""装配默认 TransferDeps(桥入口专用:收料链路无 deps 可透传)。
"""装配默认 TransferDeps(桥入口专用:入站链路无 deps 可透传)。
Returns:
TransferDeps(测试经 deps._override 注入 Fake 时返回注入值)。
@@ -82,12 +82,12 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
"""按阻断原因归类 Sheet。"""
sheet = workbook.create_sheet(sheet_name)
sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"])
sheet.append(["Invoice", "来源", "料号", "异动数量", "外部系统 数量", "原因"])
for item in items:
if (item.result_code or "") in codes or item.status in codes:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.receipt_quantity, item.external_quantity or "",
item.movement_quantity, item.external_quantity or "",
item.result_message or item.result_code or item.status,
])
@@ -191,7 +191,7 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv
changed.append(item.id)
if changed:
raise ValidationError(
"source receipt file changed since evaluation", code="TRANSFER.FILE_CHANGED",
"source inbound file changed since evaluation", code="TRANSFER.FILE_CHANGED",
details={"changed_item_ids": changed},
)
return items
@@ -213,7 +213,7 @@ def prepare_execution(
核心逻辑:[STEP 1] 两道门禁(见 _gated_items);[STEP 2] 建 queued Run 并关联
行(orchestrator);[STEP 3] 写前路由解析取 external_org,按 D1 五元组
(external_org, source_code, receipt_date, from_warehouse, to_warehouse,全部
(external_org, source_code, movement_date, from_warehouse, to_warehouse,全部
.strip() 规范化)分组建单(_ensure_document:新建/复用/阻断三分支);
[STEP 4] TRANSFER_RUN {run_id, item_ids} 恰入队一次 → 返回 queued 摘要。
@@ -239,13 +239,13 @@ def prepare_execution(
for item in items:
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
warehouse_code=item.movement_warehouse_code or "",
)
org = str(route.external_org or "").strip()
key = (
org,
str(item.source_code or "").strip(),
str(item.receipt_date or "").strip(),
str(item.movement_date or "").strip(),
str(item.from_warehouse or "").strip(),
str(item.to_warehouse or "").strip(),
)
@@ -318,7 +318,7 @@ def _ensure_document(
) -> tuple[TransferDocument | None, list[TransferInvoiceItem]]:
"""D7① 三分支组建单:同组无单新建 / 失败单复用 / result_unknown·executing 阻断。
组键 = D1 五元组(external_org, source_code, receipt_date, from_warehouse,
组键 = D1 五元组(external_org, source_code, movement_date, from_warehouse,
to_warehouse,全部 .strip() 规范化)。
分支语义:
@@ -338,7 +338,7 @@ def _ensure_document(
Returns:
(单或 None, 处理后的 items)——分支③返回 (None, blocked items)。
"""
org, source_code, receipt_date, from_wh, to_wh = group_key
org, source_code, movement_date, from_wh, to_wh = group_key
def _live() -> TransferDocument | None:
"""查同组未完结单(no_autoflush 防止半建对象提前落库干扰判定)。"""
@@ -347,7 +347,7 @@ def _ensure_document(
TransferDocument.query.filter(
TransferDocument.source_code == source_code,
TransferDocument.external_org == org,
TransferDocument.receipt_date == receipt_date,
TransferDocument.movement_date == movement_date,
TransferDocument.from_warehouse == from_wh,
TransferDocument.to_warehouse == to_wh,
TransferDocument.status.in_(UNRESOLVED_DOC_STATUSES),
@@ -363,7 +363,7 @@ def _ensure_document(
# [分支①] 新建 pending 单(D2/D3 幂等锚一次生成终身复用)。
doc = TransferDocument(
run_id=run.id, source_code=source_code, external_org=org,
receipt_date=receipt_date, from_warehouse=from_wh, to_warehouse=to_wh,
movement_date=movement_date, from_warehouse=from_wh, to_warehouse=to_wh,
doc_no=next_document_no(org, sequence_loader=_sequence_loader),
submit_timestamp=new_submit_timestamp(),
status="pending",
@@ -559,7 +559,7 @@ def _recheck_gates(run: TransferRun, deps: TransferDeps) -> tuple[str, str] | No
evaluated_sha = _item_evaluated_sha(item)
latest = latest_files.get(item.source_code) or {}
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
return ("file_changed", "source receipt file changed since evaluation")
return ("file_changed", "source inbound file changed since evaluation")
return None
@@ -600,7 +600,7 @@ def _recheck_stock_for_document(
【为什么】TTL 门禁退役(2026-09-25)后写前安全的最后防线:匹配到 worker 执行
之间存在时间窗,账面可能已被其他业务挪用/清零;在 create_transfer 之前按
「收料数量 == 账面」严格相等再裁一次,防止对错误数量建单。
「异动数量 == 账面」严格相等再裁一次,防止对错误数量建单。
【为什么不复查 final_only】result_unknown/executing 续跑(final_only=True)单
可能已在 ERP 建成,D7② 只触发末步——此时任何阻断都是假失败,故调用方保证
final_only 路径不进入本函数。
@@ -660,7 +660,7 @@ def _recheck_stock_for_document(
item.result_message = "external inventory not found (write recheck)"
item.external_quantity = "0"
continue
if classify_quantity_match(Decimal(item.receipt_quantity), row.quantity) != RESULT_EXECUTABLE:
if classify_quantity_match(Decimal(item.movement_quantity), row.quantity) != RESULT_EXECUTABLE:
# 数量漂移:原位刷新最新账面并移出本单(fail-closed,不写 ERP)。
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_quantity_mismatch"
@@ -711,7 +711,7 @@ def _execute_document(
continue # 人工关闭/取消行不复活(D18 语义:人工决定不被自动覆盖)。
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
warehouse_code=item.movement_warehouse_code or "",
)
if (
route.from_warehouse != item.from_warehouse
@@ -762,8 +762,8 @@ def _execute_document(
external_org=doc.external_org,
doc_no=doc.doc_no,
submit_timestamp=doc.submit_timestamp,
# D1:制单日期(gls_cm06)必须等于组收料日期;过账日期=执行当天业务日。
doc_date=doc.receipt_date,
# D1:制单日期(gls_cm06)必须等于组异动日期;过账日期=执行当天业务日。
doc_date=doc.movement_date,
posting_date=str(business_date_now()),
from_warehouse=doc.from_warehouse,
to_warehouse=doc.to_warehouse,
@@ -890,7 +890,7 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
lines: list[dict] = []
for index, key in enumerate(sorted(grouped), start=1):
group = grouped[key]
total = sum((Decimal(item.receipt_quantity) for item in group), Decimal("0"))
total = sum((Decimal(item.movement_quantity) for item in group), Decimal("0"))
quantity = total.quantize(_QUANTITY_QUANT)
unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "")
invoices = ",".join(sorted({item.invoice_no for item in group}))
@@ -999,7 +999,7 @@ def _apply_result(*, doc: TransferDocument | None, items: list[TransferInvoiceIt
item.result_code = None
item.result_message = None
# [档级封存回写(规格 §9)] 票据成功落 ERP 单号即封存其档记录:
# 防同一外部收料记录经新匹配二次执行;圈档/待匹配桶/队列的固定条件
# 防同一外部入站记录经新匹配二次执行;圈档/待匹配桶/队列的固定条件
# transfer_executed=false 恒排除已封存记录。幂等等值覆盖(复用单重跑恒封存)。
_seal_ledger_records(
items,
@@ -1172,7 +1172,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
# [遗留兜底] 路由复查 → 单行临时单 → 写 Attempt → 调用 → 行级六态落位。
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
warehouse_code=item.movement_warehouse_code or "",
)
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
_mark_recheck_blocked(item, "matching_expired", "route mapping changed since matching")
@@ -1182,7 +1182,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
external_org=str(route.external_org or "").strip(),
doc_no=f"LEGACY-{item.id}",
submit_timestamp=new_submit_timestamp(),
doc_date=item.receipt_date or "",
doc_date=item.movement_date or "",
posting_date=str(business_date_now()),
from_warehouse=item.from_warehouse,
to_warehouse=item.to_warehouse,
@@ -1336,15 +1336,15 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
movement_date=item.movement_date,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
to_quantity=Decimal(item.movement_quantity),
result=result,
reason=item.result_message or "",
external_document_no=item.external_document_no,
receipt_warehouse_code=item.receipt_warehouse_code or "",
movement_warehouse_code=item.movement_warehouse_code or "",
# T7 交接补齐:交易单位原值透传(执行结果视图 unit 不再恒空,计划 D4)。
unit=str(item.unit or ""),
))
@@ -1364,7 +1364,7 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
reason=result,
# 行级人话原因(阻断单号等),前端优先展示、状态码标签兜底。
message=str(item.result_message or "").strip(),
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
facts=f"异动 {item.movement_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
))
return RunResultDTO(
run_no=run.run_no,
@@ -1422,7 +1422,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
(D9,无独立进度卡);逐单亮 ERP 单号与状态徽标。
核心逻辑:[STEP 1] 按 run_id 取单(复用单 run_id 指现任 Run,投影不丢),
展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):收料日期 → 数据源 →
展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):异动日期 → 数据源 →
拨出/拨入库位升序,created_at/id 兜底稳定排序(跨数据源不再按建单序出现
日期乱序);[STEP 2] 每单行集取自单挂接行(document_id →
items,复用单新旧行全量),按 ERP 行粒度(物料+批号+拨出/拨入库位,与
@@ -1434,7 +1434,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
Returns:
orders 数组(计划 Task 11 JSON 规格逐键 + T13-3 控制器裁决扩充):
[{doc_no, receipt_date, from_warehouse, to_warehouse, status,
[{doc_no, movement_date, from_warehouse, to_warehouse, status,
erp_document_no, error_message, lines: [{invoice_no, material_no,
material_name, lot_no, quantity(6 位小数字符串), unit, reason}]}]。
行 reason 契约(框线图失败行原因展示,偏离 Task 11 五键字面属控制器裁决):
@@ -1446,7 +1446,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
docs = (
TransferDocument.query.filter_by(run_id=run.id)
.order_by(
TransferDocument.receipt_date.asc(),
TransferDocument.movement_date.asc(),
TransferDocument.source_code.asc(),
TransferDocument.from_warehouse.asc(),
TransferDocument.to_warehouse.asc(),
@@ -1,9 +1,11 @@
"""在途调拨收料文件字段/结构校验。
"""在途调拨异动文件字段/结构校验。
用途:校验收料文件必填列(Invoice No/料号/收料日期/收料数量)、数量与日期合法性、
来源身份一致性,输出 ParsedReceiptRow 供 Invoice 汇总。
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_receipt_quantity。
用途:校验异动文件必填列(单号/料号/异动日期/异动数量)、数量与日期合法性、
来源身份一致性,输出 ParsedMovementRow 供 Invoice 汇总。
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_inbound_quantity。
逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。
tt14 入站化后统一走 movement 契约字段(parse_movement_rows 单一入口,
旧字段投影链路已并入,无兼容层)。
"""
from __future__ import annotations
@@ -16,14 +18,11 @@ from typing import Any, Iterable, Mapping
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.date_policy import parse_date
from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_receipt_quantity
REQUIRED_FIELDS = ("sheet", "row_no", "invoice_no", "material_no", "receipt_date", "receipt_quantity")
from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_inbound_quantity
@dataclass(frozen=True)
class ParsedReceiptRow:
"""单行已校验收料记录。"""
class ParsedMovementRow:
"""单行已校验异动记录。"""
source_code: str
sheet: str
@@ -32,20 +31,21 @@ class ParsedReceiptRow:
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
# 异动日期/异动数量(tt14 入站化:明细方向中立,与异动档 movement_date 对齐)。
movement_date: date
movement_quantity: Decimal
lot_no: str = ""
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
# 来源文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
warehouse_code: str = ""
# 交易单位列原值(movement 契约第 11 字段 unit,计划 D4):仅 trim 空白、
# 不做单位换算/清洗;空值不产生解析失败,由匹配阶段行级 blocked_missing_unit 阻断。
unit: str = ""
class ReceiptFileSchemaError(AppError):
"""收料文件结构/字段校验失败(整行阻断)。"""
class MovementFileSchemaError(AppError):
"""异动文件结构/字段校验失败(整行阻断)。"""
def __init__(self, message: str = "receipt file schema invalid", *, rows: list[dict[str, Any]] | None = None):
def __init__(self, message: str = "movement file schema invalid", *, rows: list[dict[str, Any]] | None = None):
super().__init__(
code=TRANSFER_FILE_SCHEMA_INVALID,
message=message,
@@ -59,48 +59,49 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
rows.append({"row_no": row_no, "reason": reason})
def _is_unusable_receipt_row(date_value: Any, quantity_raw: Any) -> bool:
"""判断是否为"非可用收料事实"的行:跳过,不参与匹配,也不阻断整文件。
def _is_unusable_movement_row(date_value: Any, quantity_raw: Any) -> bool:
"""判断是否为"非可用异动事实"的行:跳过,不参与匹配,也不阻断整文件。
WMS 异动报告会携带三类非可用收料行,均不是可用的收料事实:
① 未收料在途 ASN(Date Received 空、Qty Received 0);
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章);
③ 零数量收料行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
WMS 异动报告会携带三类非可用异动行,均不是可用的异动事实:
① 未收货在途 ASN(Date Received 空、Qty Received 0);
② 收货执行中(ASN Status=Executing,Qty Received 已计数但收货日期未盖章);
③ 零数量异动行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
WTP26082227 实测——扫码收货数量记在他行/收货取消的占位行)。
收料日期与正数量是行级匹配身份与成熟过滤的必要字段;此类行跳过后由下次排程
异动日期与正数量是行级匹配身份与日期圈定的必要字段;此类行跳过后由下次排程
抓取补齐(WMS 补数量/盖章后自然带出),不得整文件阻断。
"""
if not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()):
return True
try:
# 只跳过恰好为 0 的零收料行;负数属数据损坏,交由 validate_receipt_quantity 阻断。
# 只跳过恰好为 0 的零异动行;负数属数据损坏,交由 validate_inbound_quantity 阻断。
return Decimal(str(quantity_raw)) == 0
except (InvalidOperation, ValueError, TypeError):
# 数量缺失/空:日期已盖章但无数量,同为零收料家族;非数字垃圾交由
# validate_receipt_quantity 按非法数量阻断,不在此吞掉。
# 数量缺失/空:日期已盖章但无数量,同为零异动家族;非数字垃圾交由
# validate_inbound_quantity 按非法数量阻断,不在此吞掉。
return not str(quantity_raw or "").strip()
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedMovementRow]:
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
字段契约(领域定死)见 movement_contract.MOVEMENT_FIELDS;映射关系:
doc_no → invoice_no(幂等/汇总键)
quantity → receipt_quantity(严格数量匹配)
movement_date → receipt_date(成熟过滤)
quantity → movement_quantity(严格数量匹配)
movement_date → movement_date(日期圈定;tt14 入站化后明细侧同名对齐)
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
unit 原值透传至 ParsedReceiptRow.unit(movement 契约第 11 字段,仅 trim,
warehouse_code 透传至 ParsedMovementRow.warehouse_code(inventory_match 源路由匹配键);
unit 原值透传至 ParsedMovementRow.unit(movement 契约第 11 字段,仅 trim,
空值不阻断解析——行级 missing_unit 阻断在匹配阶段);
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
storage_code 仍仅展示保留。旧字段名投影链路(tt14 前的直连列名解析)已并入
本函数(入站化,无兼容层),校验逻辑一致。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 通用异动原始行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
已校验的 ParsedMovementRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
MovementFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
@@ -108,31 +109,8 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
projection={
"invoice_no": "doc_no",
"material_no": "material_code",
"receipt_quantity": "quantity",
"receipt_date": "movement_date",
},
)
def parse_receipt_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""校验并解析收料文件行。
Args:
source_code: 任务来源实例(用于校验行内来源身份一致性)。
rows: 原始文件行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
rows=rows,
projection={
"invoice_no": "invoice_no",
"material_no": "material_no",
"receipt_quantity": "receipt_quantity",
"receipt_date": "receipt_date",
"movement_quantity": "quantity",
"movement_date": "movement_date",
},
)
@@ -142,33 +120,33 @@ def _parse_rows(
source_code: str,
rows: Iterable[Mapping[str, Any]],
projection: Mapping[str, str],
) -> list[ParsedReceiptRow]:
) -> list[ParsedMovementRow]:
"""按字段名投影校验并解析原始行。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 原始文件行 dict。
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
projection: 调拨语义字段(invoice_no/material_no/movement_quantity/movement_date)
到原始行字段名的映射(如 {invoice_no: doc_no})。
Returns:
已校验的 ParsedReceiptRow 列表("无异动日期"的在途/执行中行已跳过)。
已校验的 ParsedMovementRow 列表("无异动日期"的在途/执行中行已跳过)。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
MovementFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
invoice_key = str(projection.get("invoice_no") or "invoice_no")
material_key = str(projection.get("material_no") or "material_no")
quantity_key = str(projection.get("receipt_quantity") or "receipt_quantity")
date_key = str(projection.get("receipt_date") or "receipt_date")
quantity_key = str(projection.get("movement_quantity") or "movement_quantity")
date_key = str(projection.get("movement_date") or "movement_date")
errors: list[dict[str, Any]] = []
parsed: list[ParsedReceiptRow] = []
parsed: list[ParsedMovementRow] = []
for raw in rows:
row = raw if isinstance(raw, Mapping) else {}
row_no = row.get("row_no")
invoice_no = str(row.get(invoice_key) or "").strip()
material_no = str(row.get(material_key) or "").strip()
sheet = str(row.get("sheet") or "").strip()
receipt_date_value = row.get(date_key)
movement_date_value = row.get(date_key)
quantity_raw = row.get(quantity_key)
if not sheet or not row_no:
@@ -184,19 +162,19 @@ def _parse_rows(
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
if _is_unusable_receipt_row(receipt_date_value, quantity_raw):
if _is_unusable_movement_row(movement_date_value, quantity_raw):
continue
try:
receipt_date = parse_date(receipt_date_value)
movement_date = parse_date(movement_date_value)
except ValueError:
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_value!r}")
_fail(errors, row_no=row_no, reason=f"invalid_movement_date: {movement_date_value!r}")
continue
try:
quantity = validate_receipt_quantity(quantity_raw)
quantity = validate_inbound_quantity(quantity_raw)
except QuantityValidationError as exc:
_fail(errors, row_no=row_no, reason=str(exc))
continue
parsed.append(ParsedReceiptRow(
parsed.append(ParsedMovementRow(
source_code=str(source_code),
sheet=sheet,
row_no=int(row_no),
@@ -204,8 +182,8 @@ def _parse_rows(
material_no=material_no,
material_name=str(row.get("material_name") or "").strip(),
specification=str(row.get("specification") or "").strip(),
receipt_date=receipt_date,
receipt_quantity=quantity,
movement_date=movement_date,
movement_quantity=quantity,
lot_no=str(row.get("lot_no") or "").strip(),
warehouse_code=str(row.get("warehouse_code") or "").strip(),
# unit 原值透传(movement 契约第 11 字段):仅 trim,空值解析放行。
@@ -215,5 +193,5 @@ def _parse_rows(
# 诊断落库:消息携带前 3 条行级明细(行号+原因),随 parse_error_message
# 落库自描述(2026-10-08 CRANE 零数量行事故:此前只有通用消息、无法定位)。
summary = '; '.join(f"row {r.get('row_no')}: {r.get('reason')}" for r in errors[:3])
raise ReceiptFileSchemaError(f"receipt file schema invalid: {summary}", rows=errors)
raise MovementFileSchemaError(f"movement file schema invalid: {summary}", rows=errors)
return parsed
@@ -1,7 +1,8 @@
"""在途调拨收料文件 Ready 复用与来源级 RPA 触发。
"""在途调拨入站文件 Ready 复用与来源级 RPA 触发。
用途:按 (source_code, business_date, purpose=receipt) 检查最新 ready 文件;
存在则复用,不存在则按来源实例触发一次收料 RPA;存在活动 Source Job
用途:按 (source_code, business_date, 入站解析规则绑定) 检查最新 ready 文件;
存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingReceiptReport RPA
产物,shipping_notice 域术语保留);存在活动 Source Job
时绑定已有任务,保证并发请求只触发一次抓取。
依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。
逻辑:文件仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身;
@@ -19,8 +20,8 @@ STAGE_FAILED = "failed"
@dataclass(frozen=True)
class ReadyReceiptFile:
"""当日最新 ready 收料文件快照(含已提取行,供解析)。"""
class ReadyInboundFile:
"""当日最新 ready 入站文件快照(含已提取行,供解析)。"""
source_code: str
business_date: str
@@ -35,30 +36,30 @@ class FilePreparationResult:
"""来源级文件准备结果。"""
stage: str
file: ReadyReceiptFile | None = None
file: ReadyInboundFile | None = None
error_code: str | None = None
error_message: str | None = None
class ReceiptFileRepository(Protocol):
"""收料 ready 文件仓库协议。"""
class InboundFileRepository(Protocol):
"""入站 ready 文件仓库协议。"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
"""返回该来源当日最新 ready 文件;不存在返回 None。"""
class RpaTrigger(Protocol):
"""收料 RPA 触发协议(DBS/Crane 共用)。"""
"""入站 RPA 触发协议(DBS/Crane 共用)。"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
"""触发一次收料抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。"""
"""触发一次入站抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。"""
def ensure_receipt_file_ready(
def ensure_inbound_file_ready(
*,
source_code: str,
business_date: str,
repository: ReceiptFileRepository,
repository: InboundFileRepository,
rpa_trigger: RpaTrigger,
active_source_job_key: str | None = None,
) -> FilePreparationResult:
@@ -1,6 +1,7 @@
"""在途调拨收料回调桥。
"""在途调拨入站回调桥。
用途:货代收料 RPA 回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
用途:货代入站 RPA(入站证据 = ShippingReceiptReport RPA 产物,shipping_notice 域,术语保留)
回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。
依赖:models(TransferSourceJob)、datetime。
逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作,
@@ -19,7 +20,7 @@ _WAITING_RPA_CALLBACK = 'waiting_rpa_callback'
_FAILED = 'failed'
def advance_source_job_from_receipt_callback(
def advance_source_job_from_inbound_callback(
*, source_code: str, file_no: str | None = None, file_sha256: str | None = None,
callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None,
) -> TransferSourceJob | None:
@@ -27,8 +28,8 @@ def advance_source_job_from_receipt_callback(
Args:
source_code: 回调所属来源实例。
file_no: 收料文件号(success 时)。
file_sha256: 收料文件 sha256(success 时)。
file_no: 入站文件号(success 时)。
file_sha256: 入站文件 sha256(success 时)。
callback_ok / error_code / error_message: 回调终态。
Returns:
被推进的任务;无等待任务或已终态时返回 None。
@@ -50,18 +51,18 @@ def advance_source_job_from_receipt_callback(
job.finished_at = datetime.utcnow()
else:
job.status = _FAILED
job.error_code = error_code or 'RPA_RECEIPT_CALLBACK_FAILED'
job.error_message = error_message or 'receipt rpa callback failed'
job.error_code = error_code or 'RPA_INBOUND_CALLBACK_FAILED'
job.error_message = error_message or 'inbound rpa callback failed'
job.finished_at = datetime.utcnow()
db.session.flush()
return job
def recover_stale_waiting_source_jobs() -> int:
"""把超过收料回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
"""把超过入站回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与收料超时回收同批调用;
不自动重试 RPA——用户可在来源选择卡手动重试(与收料回收"绝不自动重试"口径一致)。
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与入站超时回收同批调用;
不自动重试 RPA——用户可在来源选择卡手动重试(与入站回收"绝不自动重试"口径一致)。
Returns:
本次回收的任务数。
"""
@@ -79,8 +80,8 @@ def recover_stale_waiting_source_jobs() -> int:
)
for job in stale:
job.status = _FAILED
job.error_code = 'RPA_RECEIPT_CALLBACK_TIMEOUT'
job.error_message = f'receipt rpa callback not received within {timeout}s'
job.error_code = 'RPA_INBOUND_CALLBACK_TIMEOUT'
job.error_message = f'inbound rpa callback not received within {timeout}s'
job.finished_at = datetime.utcnow()
if stale:
db.session.commit()
@@ -1,8 +1,9 @@
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
"""在途调拨入站归档文件的可用性门禁(单一事实来源)。
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
用途:把「一份 ShippingReceiptReportFile(入站证据 = ShippingReceiptReport RPA 产物,
shipping_notice 域,术语保留)是否可用于调拨链路」的判定收敛为本模块,
供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
入站文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
@@ -32,8 +33,8 @@ def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
)
def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「当前可用的收料归档文件」SQL 条件。
def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「当前可用的入站归档文件」SQL 条件。
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
+ 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载
@@ -51,7 +52,7 @@ def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnEleme
)
def expired_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
@@ -1,14 +1,15 @@
"""在途调拨真实收料 RPA 触发服务。
"""在途调拨入站 RPA 触发服务。
用途:为单个或多个来源触发收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = ShippingReceiptReport RPA 产物,
复用货代 ShippingReceiptReport trigger 链路,shipping_notice 域术语保留),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
先落 RPA 单元运行行(awaiting_rpa,回调按 callback_id 查库可达),
再装配入站 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer,shipping_notice 域)、models、db。
逻辑:list_inbound_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/ShippingReceiptReportConfig 缺失/rpa_profile 缺失时
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
trigger_receipt_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
trigger_inbound_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
"""
@@ -26,7 +27,7 @@ RouteTriggerWriter = Callable[..., str | None]
def _build_trigger_unit(
*, source_code: str, business_date: str, reason: str,
) -> dict[str, Any]:
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
"""装配单来源入站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
"""
@@ -37,10 +38,10 @@ def _build_trigger_unit(
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is None:
raise RuntimeError(f'receipt config missing: {source_code}')
raise RuntimeError(f'inbound config missing: {source_code}')
profile = source.rpa_profile
if profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
raise RuntimeError(f'inbound source profile unavailable: {source_code}')
query_parameters = [
dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict)
]
@@ -53,7 +54,7 @@ def _build_trigger_unit(
}
return {
'inventory_source_id': source.id,
'callback_id': f'receipt:{uuid.uuid4().hex}',
'callback_id': f'inbound:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
'warehouse_id': None,
@@ -73,11 +74,11 @@ def _build_trigger_unit(
}
def list_receipt_capable_source_codes() -> list[str]:
"""列出可产出收料文件的启用来源实例(enabled 库存源 + 已配置收料报表)。
def list_inbound_capable_source_codes() -> list[str]:
"""列出可产出入站文件的启用来源实例(enabled 库存源 + 已配置 ShippingReceiptReport)。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——收料文件只能
来自已配置收料报表的站点,与货代收料 RPA 排程的站点口径保持一致。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件(ShippingReceiptReport
RPA 产物)只能来自已配置 ShippingReceiptReport 的站点,与货代 ShippingReceiptReport RPA 排程的站点口径一致。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
@@ -91,14 +92,14 @@ def list_receipt_capable_source_codes() -> list[str]:
return [str(code) for (code,) in rows]
def trigger_receipt_rpa(
def trigger_inbound_rpa(
*,
source_code: str,
business_date: str,
reason: str = 'transfer_retry_receipt',
reason: str = 'transfer_retry_inbound',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源收料 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
"""触发一次来源入站 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
Args:
source_code: 来源实例编码。
@@ -112,14 +113,14 @@ def trigger_receipt_rpa(
try:
unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
except RuntimeError as exc:
return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
return {"ok": False, "error_code": "RPA_INBOUND_CONFIG_MISSING", "error_message": str(exc)}
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
# 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun
unit = ShippingReceiptRpaUnitRun(
unit = ShippingInboundRpaUnitRun(
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
inventory_source_id=unit_payload['inventory_source_id'],
source_code=unit_payload['source_code'],
@@ -145,10 +146,10 @@ def trigger_receipt_rpa(
})
if not path:
unit.status = 'failed'
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
unit.error_message = 'receipt trigger directory unavailable'
unit.error_code = 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
unit.error_message = 'inbound trigger directory unavailable'
db.session.commit()
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
return {"ok": False, "error_code": "RPA_INBOUND_TRIGGER_UNAVAILABLE"}
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
unit.trigger_snapshot_json = unit_payload
@@ -156,21 +157,21 @@ def trigger_receipt_rpa(
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
def trigger_receipt_rpa_batch(
def trigger_inbound_rpa_batch(
*,
source_codes: list[str],
business_date: str,
reason: str = 'transfer_retry_receipt',
reason: str = 'transfer_retry_inbound',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""批量触发多来源收料 RPA:全部有效来源合并写**一个** batch trigger 文件。
"""批量触发多来源入站 RPA:全部有效来源合并写**一个** batch trigger 文件。
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
行级单来源重试仍走 trigger_receipt_rpa(一源一文件语义不变)。
行级单来源重试仍走 trigger_inbound_rpa(一源一文件语义不变)。
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批;
parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行
ShippingReceiptRpaUnitRun 再一次性 write_receipt_export_batch_trigger 原子落盘。
RPA 单元运行行再一次性 write_receipt_export_batch_trigger 原子落盘。
Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。
Args:
@@ -187,13 +188,13 @@ def trigger_receipt_rpa_batch(
跳过:{source_code, ok: false, error_code, error_message})。
"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
results: list[dict[str, Any]] = []
units: list[ShippingReceiptRpaUnitRun] = []
units: list[ShippingInboundRpaUnitRun] = []
unit_payloads: list[dict[str, Any]] = []
# [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。
@@ -216,7 +217,7 @@ def trigger_receipt_rpa_batch(
except RuntimeError as exc:
results.append({
'source_code': code, 'ok': False,
'error_code': 'RPA_RECEIPT_CONFIG_MISSING', 'error_message': str(exc),
'error_code': 'RPA_INBOUND_CONFIG_MISSING', 'error_message': str(exc),
})
if not unit_payloads:
@@ -225,11 +226,11 @@ def trigger_receipt_rpa_batch(
db.session.commit()
if reparse_recovered:
return {"ok": True, "triggered": False, "results": results}
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_NO_TRIGGERABLE_SOURCE", "results": results}
return {"ok": False, "triggered": False, "error_code": "RPA_INBOUND_NO_TRIGGERABLE_SOURCE", "results": results}
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
for payload in unit_payloads:
unit = ShippingReceiptRpaUnitRun(
unit = ShippingInboundRpaUnitRun(
inventory_source_id=payload['inventory_source_id'],
source_code=payload['source_code'],
connector_type=payload['connector_type'],
@@ -257,10 +258,10 @@ def trigger_receipt_rpa_batch(
if not path:
for unit in units:
unit.status = 'failed'
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
unit.error_message = 'receipt trigger directory unavailable'
unit.error_code = 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
unit.error_message = 'inbound trigger directory unavailable'
db.session.commit()
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE", "results": results}
return {"ok": False, "triggered": False, "error_code": "RPA_INBOUND_TRIGGER_UNAVAILABLE", "results": results}
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
for unit, payload in zip(units, unit_payloads):
@@ -1,9 +1,10 @@
"""在途调拨 Invoice 多行汇总。
用途:相同 Invoice+料号+收料日期 的多行只汇总收料数量,并永久保留原始
用途:相同 Invoice+料号+异动日期 的多行只汇总异动数量,并永久保留原始
Sheet/行号/文件版本;同 Invoice 跨料号或跨日期自然拆分为多张发票。
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
逻辑:汇总键 (source_code, invoice_no, material_no, receipt_date)。
逻辑:汇总键 (source_code, invoice_no, material_no, movement_date)(tt14 入站化:
明细字段方向中立,日期/数量键统一 movement_*)。
"""
from __future__ import annotations
@@ -15,7 +16,7 @@ from typing import Iterable
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_INVOICE_CONFLICT, RawLineRefDTO
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow
from app.services.in_transit_transfer.file_parser import ParsedMovementRow
@dataclass(frozen=True)
@@ -27,11 +28,11 @@ class AggregatedInvoice:
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
movement_date: date
movement_quantity: Decimal
raw_lines: tuple[RawLineRefDTO, ...]
lot_no: str = ""
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
# 组内首行来源仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
warehouse_code: str = ""
# 组内首行交易单位原值(movement 契约第 11 字段 unit,计划 D4):与 lot_no 同为
# 「组内首行」口径;空值在匹配阶段行级 blocked_missing_unit 阻断,不在此换算/清洗。
@@ -39,7 +40,7 @@ class AggregatedInvoice:
class InvoiceConflictError(AppError):
"""同一 Invoice 出现冲突(多料号/多收料日期),整单阻断。"""
"""同一 Invoice 出现冲突(多料号/多异动日期),整单阻断。"""
def __init__(self, message: str = "invoice conflict", *, invoice_no: str, conflict: str):
super().__init__(
@@ -50,11 +51,11 @@ class InvoiceConflictError(AppError):
)
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice+料号+收料日期 汇总收料数量并保留原始行证据。
def aggregate_invoices(rows: Iterable[ParsedMovementRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice+料号+异动日期 汇总异动数量并保留原始行证据。
汇总键 (source_code, invoice_no, material_no, receipt_date):Invoice 语义为
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨收料日期时
汇总键 (source_code, invoice_no, material_no, movement_date):Invoice 语义为
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨异动日期时
自然拆分为多张发票(部分交付场景),不做整单阻断。
Args:
rows: 已校验的解析行。
@@ -62,14 +63,14 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
Returns:
汇总后的 Invoice 列表(按汇总键排序)。
"""
grouped: dict[tuple[str, str, str, date], list[ParsedReceiptRow]] = {}
grouped: dict[tuple[str, str, str, date], list[ParsedMovementRow]] = {}
for row in rows:
grouped.setdefault(
(row.source_code, row.invoice_no, row.material_no, row.receipt_date), [],
(row.source_code, row.invoice_no, row.material_no, row.movement_date), [],
).append(row)
invoices: list[AggregatedInvoice] = []
for (source_code, invoice_no, material_no, receipt_date), group in sorted(grouped.items()):
for (source_code, invoice_no, material_no, movement_date_key), group in sorted(grouped.items()):
first = group[0]
raw_lines = tuple(
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
@@ -81,8 +82,8 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
material_no=material_no,
material_name=first.material_name,
specification=first.specification,
receipt_date=receipt_date,
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
movement_date=movement_date_key,
movement_quantity=sum((row.movement_quantity for row in group), Decimal("0")),
raw_lines=raw_lines,
lot_no=first.lot_no,
warehouse_code=first.warehouse_code,
@@ -2,20 +2,24 @@
用途:库存异动档落地(ADR 0001)——外部记录镜像落地:把解析产物(movement 契约
领域行)按自然键幂等镜像到 transfer_movement_ledger;语义与 evidence_sync
三分类同源(插入/跳过/原行更新,ADR 0001),一期收料(record_kind='receipt'),
shipment 为预留合法值(校验放行,不特判)。
三分类同源(插入/跳过/原行更新,ADR 0001),一期入站(record_kind='inbound'),
outbound 为预留合法值(出货侧结构就位,校验放行,不特判)。
依赖:models/in_transit_transfer.TransferMovementLedger、audit.build_transfer_audit_event、
movement_contract.MOVEMENT_FIELDS(档列镜像取值的唯一字段来源)。不解析文件
(parsed_rows 由调用方/Task 11 接线从解析产物组装)、不查外部系统、零外部调用。
逻辑:规格 §5 五条幂等语义——①自然键 (doc_no, line_no, line_seq, in_out_flag)
查档不存在 → 插入(record_kind/溯源五列随行写入);②行 file_sha256 与来件
一致 → 跳过(完全不动行,不续 updated_at——档无 TTL,无新鲜度概念);
③证据变化 → 原行更新业务镜像列 + 换溯源(source_file_id/file_version/
file_sha256/sheet_name/row_no/updated_at);④文件缺席的档行不删(收料 RPA
非全量导出,缺席≠删除——本函数从不删除,无需显式处理);⑤transfer_executed=true
封存行永不更新永不复活(sealed_skipped 计数;封存是最高优先事实,命中即计,
与来件 sha 无关;同文件重落不产生第二行,自然键唯一索引 DB 兜底)。
record_kind 与 in_out_flag 矛盾(receipt 行出库语义 '-1')→ 计 cross_flagged
逻辑:落档前先滤 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/溯源五列随行写入);②行
file_sha256 与来件一致 → 跳过(完全不动行,不续 updated_at——档无 TTL,
无新鲜度概念);③证据变化 → 原行更新业务镜像列 + 换溯源(source_file_id/
file_version/file_sha256/sheet_name/row_no/updated_at);④文件缺席的档行
不删(入站 RPA 非全量导出,缺席≠删除——本函数从不删除,无需显式处理);
⑤transfer_executed=true 封存行永不更新永不复活(sealed_skipped 计数;封存
是最高优先事实,命中即计,与来件 sha 无关;同文件重落不产生第二行,自然键
唯一索引 DB 兜底)。
record_kind 与 in_out_flag 矛盾(inbound 行出库语义 '-1')→ 计 cross_flagged
并写 ledger_cross_check_failed 审计事件,记录照常落档;矛盾标记随落档动作
发生(插入/更新时)——幂等重落不重复打事件,防只追加审计表被同文件重落刷爆;
封存行不落档故不标记(sealed_skipped 即信号)。
@@ -39,10 +43,12 @@ from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
_MOVEMENT_CODES: tuple[str, ...] = tuple(f.code for f in MOVEMENT_FIELDS)
assert set(_MOVEMENT_CODES) <= {c.name for c in TransferMovementLedger.__table__.columns}
# record_kind='receipt' 的出库语义值:收料记录出现该进出库别即解析错位(交叉校验矛盾)。
RECEIPT_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"})
# 收料记录种类字面量(一期唯一传入值;shipment 预留,矛盾判定暂只覆盖 receipt 侧)。
RECORD_KIND_RECEIPT = "receipt"
# record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。
INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"})
# 记录种类字面量:inbound=入站(ShippingReceiptReport RPA 产物,shipping_notice 域术语保留);
# outbound=出站(出货侧结构就位)。
RECORD_KIND_INBOUND = "inbound"
RECORD_KIND_OUTBOUND = "outbound"
# 交叉校验矛盾审计事件 kind(任务简报冻结字面量;仓库事件 kind 无集中常量表,行内字面量惯例)。
LEDGER_CROSS_CHECK_EVENT = "ledger_cross_check_failed"
@@ -52,7 +58,7 @@ class FileMeta:
"""一次落地的来源文件证据三元组(溯源的文件级成分;Task 11 从归档文件组装)。
Args:
source_file_id: 收料原样归档文件 id(shipping_receipt_report_files.id;
source_file_id: 入站原样归档文件 id(shipping_receipt_report_files.id;
测试/极端场景可为 None——档事实留存不依赖文件存在)。
file_version: 文件版本号(Task 13 执行门禁 file_current 比对依据)。
file_sha256: 文件 SHA-256(幂等跳过判定的唯一证据指纹)。
@@ -65,11 +71,12 @@ class FileMeta:
@dataclass(frozen=True)
class LedgerSyncOutcome:
"""一次落档的结果计数(审计与兜底日志的数据源;字段顺序为任务简报冻结契约)。"""
"""一次落档的结果计数(审计与兜底日志的数据源;字段名为冻结契约,顺序自 date_skipped 引入后不再承诺)。"""
inserted: int = 0 # 自然键不存在 → 插入新档行
updated: int = 0 # 证据变化 → 原行更新业务镜像列 + 换溯源
skipped: int = 0 # sha 未变的幂等跳过;同批自然键重复的后续行亦计入
date_skipped: int = 0 # movement_date 空=未发生异动,不落档
sealed_skipped: int = 0 # 封存行(transfer_executed=true)命中即计:永不更新永不复活
cross_flagged: int = 0 # record_kind 与 in_out_flag 矛盾且本次实际落档的行数
@@ -98,7 +105,7 @@ def _cross_check_event(
*,
source_code: str,
record_kind: str,
key: tuple[str, str, str, str],
key: tuple[str, str, str, str, str, str],
sheet_name: str | None,
row_no: int | None,
file_meta: FileMeta,
@@ -107,14 +114,17 @@ def _cross_check_event(
Args:
source_code / record_kind: 来源实例编码与记录种类。
key: 自然键四成分 (doc_no, line_no, line_seq, in_out_flag)(已归一化)。
key: 自然键六成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
lot_no)(已归一化;箱号/批号随 tt14 键扩维入事件,保证矛盾行可唯一定位)。
sheet_name / row_no: 行级溯源(入事件快照辅助定位来源行)。
file_meta: 来源文件证据三元组。
Returns:
已计算 Hash 的 TransferAuditEvent(event_type=ledger_cross_check_failed)。
"""
doc_no, line_no, line_seq, in_out_flag = key
natural_key = "/".join((source_code, record_kind, doc_no, line_no, line_seq, in_out_flag))
doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no = key
natural_key = "/".join((
source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
))
return build_transfer_audit_event(
event_type=LEDGER_CROSS_CHECK_EVENT,
aggregate_type="transfer_movement_ledger",
@@ -125,7 +135,7 @@ def _cross_check_event(
after={
"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,
"in_out_flag": in_out_flag, "carton_id": carton_id, "lot_no": lot_no,
"file_version": file_meta.file_version, "file_sha256": file_meta.file_sha256,
"sheet_name": sheet_name, "row_no": row_no,
},
@@ -142,32 +152,45 @@ def sync_ledger_rows(
) -> LedgerSyncOutcome:
"""按自然键幂等落地一批领域行到库存异动档(零外部调用,flush 不 commit)。
【AI 触发时机】Task 11 接线后由落地主链路(evidence_sync 同步入口)在收料
文件落地成功时调用;未来出货报告接入时以 record_kind='shipment' 复用。
【AI 触发时机】Task 11 接线后由落地主链路(evidence_sync 同步入口)在入站
文件落地成功时调用;未来出货报告接入时以 record_kind='outbound' 复用。
不要在匹配/执行链路调用本函数(匹配从档圈定,不写档)。
Args:
source_code: 来源实例编码(自然键成分,整批一致)。
record_kind: 记录种类(文件种类声明,权威):'receipt' 一期;'shipment'
预留合法值(校验放行,不特判)。
record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingReceiptReport
RPA 产物);'outbound' 出货侧(预留合法值,校验放行,不特判)。
parsed_rows: 领域行 dict 列表,每行键=movement 契约 field code
(movement_contract.MOVEMENT_FIELDS:既有 11 + 扩展 7,与
档列名 1:1 镜像),值为解析原值(None=缺失,宽松落地);
可另含可选行级溯源键 sheet_name(str)/row_no(int)(由接线方
从解析产物 ParsedReceiptRow 组装);未知键忽略。行必含自然键
成分 doc_no/line_no/line_seq/in_out_flag(缺失按空串落档,
必填校验归解析层,本函数不做二次阻断)。
从解析产物 ParsedMovementRow 组装);未知键忽略。行必含自然键
成分 doc_no/line_no/line_seq/in_out_flag/carton_id/lot_no
(缺失按空串落档,必填校验归解析层,本函数不做二次阻断);
movement_date 为空(None/空白)的行不入档(未发生异动,
计入 date_skipped)。
file_meta: 来源文件证据三元组(FileMeta);file_sha256 为 None 时无法证明
与档行同源,一律走更新分支(宁可重写不误跳)。
now: 落档时间基准(插入/更新显式续 updated_at;跳过不续——完全不动行)。
Returns:
LedgerSyncOutcome 五分类计数(inserted/updated/skipped/sealed_skipped/
cross_flagged)。
LedgerSyncOutcome 六分类计数(inserted/updated/skipped/date_skipped/
sealed_skipped/cross_flagged)。
"""
counters = {"inserted": 0, "updated": 0, "skipped": 0, "sealed_skipped": 0, "cross_flagged": 0}
counters = {
"inserted": 0, "updated": 0, "skipped": 0,
"date_skipped": 0, "sealed_skipped": 0, "cross_flagged": 0,
}
# [STEP 0] movement_date 非空才落档:空值=未发生异动(未收 ASN/未发货订单行),
# 落档即幽灵行(永不进匹配圈档)。解析层 file_parser 已滤一轮(异动语义),
# 此处是映射无关的第二道防线:Profile 无论把哪列配到 movement_date,空值都进不了档。
total_in = len(parsed_rows)
parsed_rows = [raw for raw in parsed_rows if _key_text(raw.get("movement_date"))]
counters["date_skipped"] = total_in - len(parsed_rows)
# [STEP 1] 只圈定批内 doc_no 的既有档行(含封存行——封存命中必须可见),按自然键
# 建索引;source_code/record_kind 整批恒定,键只留四成分。档「缺席不删、永不
# 建索引;source_code/record_kind 整批恒定,键只留行级六成分(tt14 扩维:
# carton_id/lot_no——真实 WMS 行身份=单据+行+箱/批)。档「缺席不删、永不
# 删除」行数单调增长(评审 Important 修复):按 source+kind 全量水化会使每次
# 落地成本随历史线性膨胀(Task 11 接生产落地热路径),故追加 doc_no IN 批内
# 过滤——批外键本就查不到、不参与任何分支,语义与全量查询 100% 等价;
@@ -180,18 +203,23 @@ def sync_ledger_rows(
.filter(TransferMovementLedger.doc_no.in_(doc_nos))
.all()
)
by_key = {(r.doc_no, r.line_no, r.line_seq, r.in_out_flag): r for r in existing}
by_key = {
(r.doc_no, r.line_no, r.line_seq, r.in_out_flag, r.carton_id, r.lot_no): r
for r in existing
}
# 同批自然键去重索引(首见为准):批内重复若不拦截,二次插入会撞
# uq_transfer_movement_ledger_natural_key 唯一约束炸 flush。
landed: dict[tuple[str, str, str, str], TransferMovementLedger] = {}
landed: dict[tuple[str, str, str, str, str, str], TransferMovementLedger] = {}
# [STEP 2] 逐行五分类:封存 → 跳过 → 插入/更新(矛盾标记随落档动作判定)。
# [STEP 2] 逐行六分类:日期空 → 封存 → 跳过 → 插入/更新(矛盾标记随落档动作判定)。
for raw in parsed_rows:
doc_no = _key_text(raw.get("doc_no"))
line_no = _key_text(raw.get("line_no"))
line_seq = _key_text(raw.get("line_seq"))
in_out_flag = _key_text(raw.get("in_out_flag"))
key = (doc_no, line_no, line_seq, 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)
sheet_name = _mirror_text(raw.get("sheet_name"))
row_no = _opt_int(raw.get("row_no"))
@@ -211,10 +239,10 @@ def sync_ledger_rows(
counters["skipped"] += 1
continue
# [交叉校验] receipt 行出现出库语义 '-1' 即解析错位:计 cross_flagged 并写
# [交叉校验] inbound 行出现出库语义 '-1' 即解析错位:计 cross_flagged 并写
# 审计事件,记录照常落档。仅在插入/更新(实际落档)时判定——幂等重落
#(sha 未变跳过)不重复打事件,封存行不落档故不标记。
if record_kind == RECORD_KIND_RECEIPT and in_out_flag in RECEIPT_CONTRADICTORY_FLAGS:
if record_kind == RECORD_KIND_INBOUND and in_out_flag in INBOUND_CONTRADICTORY_FLAGS:
counters["cross_flagged"] += 1
db.session.add(_cross_check_event(
source_code=source_code, record_kind=record_kind, key=key,
@@ -254,7 +282,7 @@ def sync_ledger_rows(
row.updated_at = now
counters["updated"] += 1
# [STEP 3] 缺席不删:文件里没有的自然键本函数从不触碰(收料 RPA 非全量导出,
# [STEP 3] 缺席不删:文件里没有的自然键本函数从不触碰(入站 RPA 非全量导出,
# 缺席≠删除),无对应计数(Outcome 契约无 absent 字段)。
# [STEP 4] 只 flush 不 commit:与 evidence_sync 同契约,提交归调用方
#(落地桥自行 commit,匹配/执行随主事务)。
@@ -1,7 +1,7 @@
"""在途调拨匹配服务(匹配出生翻转:从档圈行建 items)。
用途:编排「校验类型 → 从库存异动档圈行建 items(D17 占用互斥)→ T+lag 成熟过滤
(默认 T+2)→ 路由分组批量查 外部系统 库存 → 严格数量比对落位 → 匹配快照与
用途:编排「校验类型 → 从库存异动档圈行建 items(D17 占用互斥)→ 未来日期阻断
→ 路由分组批量查 外部系统 库存 → 严格数量比对落位 → 匹配快照与
Hash」,并支持匹配进度恢复(restore)与重查对档对账(见 retry_service)。
依赖:transfer_type(配置门禁)/ transfer_type_config_service(resolve_warehouse)/
scope_rules(圈档编译器)/ field_transforms(批号派生)/ ledger(档模型)/
@@ -9,15 +9,15 @@
audit / models。
逻辑:【2026-10-14 出生翻转(ADR 0001/D4/D17)】文件落地不再写 items——行由
本服务在匹配创建时从档圈定生成并「创建即绑定」匹配:固定条件(record_kind=
'receipt' + 来源 IN + movement_date 范围 + transfer_executed=false +
'inbound' + 来源 IN + movement_date 范围 + transfer_executed=false +
movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+
未被有效 items 占用(D17:不存在所属匹配未取消且未被失效隔离的 item 引用;
取消匹配即释放占用)。逐记录建 item(ledger_record_id 外键、业务字段=档
原值、receipt_quantity=record.quantity、raw_lines 单行溯源);仓库经
原值、movement_quantity=record.quantity、raw_lines 单行溯源);仓库经
resolve_warehouse 按类型定义(mapped/fixed)落 from/to;既有库存评估链
不变(继续以 items 为工作单元)。来源实例独立处理,任一来源失败不阻断
其他来源;【失败分层 2026-09-29】路由不可解析只落行级 blocked_route_not_
resolved;当天收料不查询 外部系统;匹配 Hash 从 scope_json 快照内容 +
resolved;当天入站不查询 外部系统;匹配 Hash 从 scope_json 快照内容 +
business_date + file_snapshot 计算(无环境变量/全局态,2026-09-22 陷阱
根因防御);create_matching 先落 Run + Matching 再驱动管道(行出生即绑定
matching_id),末尾统一提交;restore 与可调拨明细按匹配自有 items 圈行
@@ -56,10 +56,6 @@ from app.services.in_transit_transfer.contracts import (
RawLineRefDTO,
)
from app.services.in_transit_transfer.date_policy import (
eligible_receipt_date_to,
MATURITY_FUTURE,
MATURITY_NOT_MATURED,
maturity_status,
parse_date,
)
from app.services.in_transit_transfer.field_transforms import (
@@ -68,12 +64,13 @@ from app.services.in_transit_transfer.field_transforms import (
parse_transform_rules,
)
from app.services.in_transit_transfer.file_preparation import (
ReceiptFileRepository,
InboundFileRepository,
RpaTrigger,
ensure_receipt_file_ready,
ensure_inbound_file_ready,
)
from app.services.in_transit_transfer.ledger_sync import RECORD_KIND_INBOUND
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition
from app.services.in_transit_transfer.scope_rules import (
ScopeRule,
apply_scope_filters,
@@ -96,8 +93,8 @@ from app.services.in_transit_transfer.transfer_type_config_service import (
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
# 明细结果值(对应 Invoice 项状态)
# 【RESULT_NOT_MATURED 已退役 2026-10-16】成熟概念删除(未上线不设兼容层)。
RESULT_EXECUTABLE = "executable"
RESULT_NOT_MATURED = "not_matured"
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
RESULT_FUTURE_DATE = "blocked_future_date"
@@ -156,7 +153,7 @@ class RouteResolver(Protocol):
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
"""返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
"""返回 Invoice 的路由(warehouse_code 为入站文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
@dataclass(frozen=True)
@@ -188,7 +185,7 @@ class MatchingRunResult:
class TransferDeps:
"""匹配/执行依赖集合(测试注入 Fake 替身)。"""
file_repository: ReceiptFileRepository
file_repository: InboundFileRepository
rpa_trigger: RpaTrigger
route_resolver: RouteResolver
capabilities: Any
@@ -205,20 +202,20 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCoun
def _latest_usable_report_file(source_code: str) -> ShippingReceiptReportFile | None:
"""返回某来源当前「可用」(当天抓取且未清理未过期)的收料归档文件,最新优先。
"""返回某来源当前「可用」(当天抓取且未清理未过期)的入站归档文件,最新优先。
【AI 触发时机】解析失败分层(2026-09-29)需要把失败事实写到来源当前可用
文件上(parse_failed 三列)、或落档成功后清除其标记、或档落地回填
source_file_id 时调用——查询口径与
source_file_status.resolve_source_file_status 的可用文件判定一致
(receipt_file_gate.usable_receipt_file_condition),防止两处口径漂移。
(inbound_file_gate.usable_inbound_file_condition),防止两处口径漂移。
核心逻辑:[STEP 1] 按 source_code(经 ShippingReceiptReportFile.unit_run
关联 ShippingReceiptRpaUnitRun.source_code)+ 可用门禁过滤;[STEP 2] 按
关联单元运行行的 source_code)+ 可用门禁过滤;[STEP 2] 按
created_at/id 倒序取最新一份。只读不写、不 flush 不 commit。
Args:
source_code: 来源实例编码(收料执行单元行上的 source_code)。
source_code: 来源实例编码(入站执行单元行上的 source_code)。
Returns:
最新的可用 ShippingReceiptReportFile;来源无可用文件(未抓取/已失效/
已清理)返回 None。
@@ -228,35 +225,38 @@ def _latest_usable_report_file(source_code: str) -> ShippingReceiptReportFile |
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
usable_receipt_file_condition(),
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
def _validate_receipt_date_range(
business_date: str, receipt_date_from: str | None, receipt_date_to: str | None,
def _validate_movement_date_range(
business_date: str, movement_date_from: str | None, movement_date_to: str | None,
) -> tuple[date | None, date | None]:
"""校验可选收料日期范围(纯校验无副作用;run_matching / create_matching 共用)。
"""校验可选异动日期范围(纯校验无副作用;run_matching / create_matching 共用)。
【成熟规则已退役 2026-10-16】日期边界由调用方入参严格给定(交互=用户选择;
排程=任务 T−N 偏移参数),引擎只做入参合法性校验。
Args:
business_date: 业务日期 T(成熟规则基准)。
receipt_date_from / receipt_date_to: 可选收料日期范围。
business_date: 业务日期 T(未来日期阻断的基准)。
movement_date_from / movement_date_to: 可选异动日期范围(约束明细 movement_date)。
Returns:
(range_from, range_to) 解析后的日期(未提供为 None)。
Raises:
ValidationError: 起始晚于截止,或截止超出成熟规则(业务日期-lag)。
ValidationError: 起始晚于截止,或截止晚于业务日期(未来日期无账可核)。
"""
range_from = parse_date(receipt_date_from) if receipt_date_from else None
range_to = parse_date(receipt_date_to) if receipt_date_to else None
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
if range_from and range_to and range_from > range_to:
raise ValidationError(
"receipt date range is invalid", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
"movement date range is invalid", code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID",
)
if range_to and range_to > eligible_receipt_date_to(business_date):
if range_to and range_to > parse_date(business_date):
raise ValidationError(
"receipt date range end exceeds receipt maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
"movement date range end is later than business date", code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID",
)
return range_from, range_to
@@ -305,15 +305,15 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
def _circle_ledger_base_query(*, exclude_occupied_by_matching_id: int | None = None):
"""圈档固定条件底座(匹配创建圈档/重查对账/首页待匹配桶共享的唯一实现)。
固定条件(规格 §6/§9):record_kind='receipt'(一期)、transfer_executed=false
固定条件(规格 §6/§9):record_kind='inbound'(一期入站)、transfer_executed=false
(档级封存防二次执行——已执行记录永不再次被圈定)、movement_date 非空(可空
记录照常落档但不进收料日期圈定)、未被有效 items 占用(D17,见
记录照常落档但不进异动日期圈定)、未被有效 items 占用(D17,见
_effective_occupancy_filter;取消匹配即释放占用)。
【单一口径纪律】任何新的圈档消费方必须经本底座组合查询,禁止第三处手写
固定条件(双份维护=谓词漂移温床)。
"""
return TransferMovementLedger.query.filter(
TransferMovementLedger.record_kind == "receipt",
TransferMovementLedger.record_kind == RECORD_KIND_INBOUND,
TransferMovementLedger.transfer_executed.is_(False),
TransferMovementLedger.movement_date.isnot(None),
_effective_occupancy_filter(exclude_matching_id=exclude_occupied_by_matching_id),
@@ -321,7 +321,7 @@ def _circle_ledger_base_query(*, exclude_occupied_by_matching_id: int | None = N
def _order_circled_ledger(query):
"""圈档结果稳定排序(收料日期 → 来源 → 单号 → id,与明细视图同口径)。"""
"""圈档结果稳定排序(异动日期 → 来源 → 单号 → id,与明细视图同口径)。"""
return query.order_by(
TransferMovementLedger.movement_date.asc(),
TransferMovementLedger.source_code.asc(),
@@ -333,18 +333,18 @@ 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 固定条件(receipt/未封存/有收料日期/
每类型查询复用 _circle_ledger_base_query 固定条件(inbound/未封存/有异动日期/
未被有效 items 占用)+ apply_scope_filters 单一编译器——与匹配创建圈档同口径,
杜绝谓词漂移。无启用类型 → 空集(fail-closed:无类型即无范围,与匹配创建
NOT_CONFIGURED 语义一致)。已封存记录恒不在结果中(固定条件)。
Returns:
档记录列表(收料日期 → 来源 → 单号 → id 稳定排序)。
档记录列表(异动日期 → 来源 → 单号 → id 稳定排序)。
"""
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
@@ -365,8 +365,8 @@ def _circle_ledger_records(
*,
source_codes: list[str],
rules: tuple[ScopeRule, ...],
receipt_date_from: str | None,
receipt_date_to: str | None,
movement_date_from: str | None,
movement_date_to: str | None,
exclude_occupied_by_matching_id: int | None = None,
doc_nos: list[str] | None = None,
) -> list[TransferMovementLedger]:
@@ -380,21 +380,21 @@ def _circle_ledger_records(
Args:
source_codes: 来源实例编码列表。
rules: 范围规则元组(parse_scope_rules 产物)。
receipt_date_from / receipt_date_to: 可选收料日期范围(ISO 字符串)。
movement_date_from / movement_date_to: 可选异动日期范围(ISO 字符串)。
exclude_occupied_by_matching_id: 重查对账场景传入本匹配 id——本匹配自有
items 不构成占用(允许刷新/补建);匹配创建圈档不传(任何有效占用
都排除)。
doc_nos: 可选单号过滤(重查 invoice_nos 限定范围时约束补圈)。
Returns:
档记录列表(收料日期 → 来源 → 单号 → id 稳定排序,与明细视图同口径)。
档记录列表(异动日期 → 来源 → 单号 → id 稳定排序,与明细视图同口径)。
"""
query = _circle_ledger_base_query(
exclude_occupied_by_matching_id=exclude_occupied_by_matching_id,
).filter(TransferMovementLedger.source_code.in_([str(code) for code in source_codes]))
if receipt_date_from:
query = query.filter(TransferMovementLedger.movement_date >= str(receipt_date_from))
if receipt_date_to:
query = query.filter(TransferMovementLedger.movement_date <= str(receipt_date_to))
if movement_date_from:
query = query.filter(TransferMovementLedger.movement_date >= str(movement_date_from))
if movement_date_to:
query = query.filter(TransferMovementLedger.movement_date <= str(movement_date_to))
query = apply_scope_filters(query, TransferMovementLedger, rules)
if doc_nos:
query = query.filter(TransferMovementLedger.doc_no.in_(doc_nos))
@@ -446,14 +446,14 @@ def _born_item_from_record(
material_no=record.material_code or "",
material_name=record.material_name or "",
specification=record.specification or "",
receipt_date=record.movement_date,
movement_date=record.movement_date,
lot_no=record.lot_no or "",
receipt_warehouse_code=record.warehouse_code or "",
movement_warehouse_code=record.warehouse_code or "",
# 交易单位只取 ERP stock_unit(匹配评估落列),出生行置空。
unit="",
from_warehouse=route.from_warehouse if route else "",
to_warehouse=route.to_warehouse if route else "",
receipt_quantity=str(record.quantity or "0"),
movement_quantity=str(record.quantity or "0"),
external_quantity=None,
status=status_machine.TransferStatus.MATCHING.value,
result_code=SYNC_RESULT_PENDING,
@@ -506,8 +506,8 @@ def run_matching(
deps: TransferDeps,
active_source_job_key: str | None = None,
run_no: str = "RUN-PENDING",
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
movement_date_from: str | None = None,
movement_date_to: str | None = None,
transfer_type: str | None = None,
matching_id: int | None = None,
scope_rules_override: list[dict] | None = None,
@@ -530,7 +530,7 @@ def run_matching(
deps: 注入的文件仓库 / RPA / 路由 / 外部系统 依赖。
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
run_no: Run 编号(契约兼容保留;当前管道不消费,仅调用方留痕)。
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
movement_date_from / movement_date_to: 可选异动日期查询范围。
transfer_type: 调拨类型编码(必填;配置驱动,见 resolve_transfer_type)。
matching_id: 匹配行 id(出生即绑定;create_matching / 异步重跑传入)。
缺省时仅用于管道级直调(测试):行暂无归属,调用方负责回填。
@@ -547,7 +547,7 @@ def run_matching(
if not source_codes:
raise ValidationError("source_codes is required")
config = resolve_transfer_type(transfer_type, require_enabled=require_enabled)
_validate_receipt_date_range(business_date, receipt_date_from, receipt_date_to)
_validate_movement_date_range(business_date, movement_date_from, movement_date_to)
# [快照规则] 存量重跑用快照(快照自足);创建路径用类型配置现行值。
scope_rules = (
parse_scope_rules(scope_rules_override)
@@ -560,7 +560,7 @@ def run_matching(
now = datetime.utcnow()
# [STEP 0] 来源文件状态快照(进度展示与缺文件 RPA 触发;不阻断档圈定):
# resolve 命中(含 sha)→ file_ready 留痕;未命中 → ensure_receipt_file_ready
# resolve 命中(含 sha)→ file_ready 留痕;未命中 → ensure_inbound_file_ready
#(缺文件触发 RPA,既有 UX 保留);parse_failed 文件如实标 failed(解析失败
# 分层:失败事实由落档桥落库,匹配不再解析)。
sources: list[SourceProgressDTO] = []
@@ -572,11 +572,11 @@ def run_matching(
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code="TRANSFER_FILE_SCHEMA_INVALID",
error_message="receipt file parse failed; see source file status",
error_message="inbound file parse failed; see source file status",
))
continue
if not checksum:
prepared = ensure_receipt_file_ready(
prepared = ensure_inbound_file_ready(
source_code=source_code, business_date=business_date,
repository=deps.file_repository, rpa_trigger=deps.rpa_trigger,
active_source_job_key=active_source_job_key,
@@ -619,7 +619,7 @@ def run_matching(
# [STEP 0b 圈档建 items(出生翻转核心)] 圈定未占用档记录并逐记录建 item。
ledger_records = _circle_ledger_records(
source_codes=list(source_codes), rules=scope_rules,
receipt_date_from=receipt_date_from, receipt_date_to=receipt_date_to,
movement_date_from=movement_date_from, movement_date_to=movement_date_to,
)
born: list[TransferInvoiceItem] = []
for record in ledger_records:
@@ -652,7 +652,7 @@ def run_matching(
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
)
.order_by(
TransferInvoiceItem.receipt_date.asc().nulls_last(),
TransferInvoiceItem.movement_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
@@ -680,8 +680,7 @@ def run_matching(
counts = MatchingCountsDTO(
file_invoice_count=sum(1 for item in items),
not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED),
matched_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED),
matched_count=len(items),
executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE),
blocked_count=sum(1 for item in items if item.result.startswith("blocked_")),
pending_stock_check_count=pending_stock_check_count,
@@ -691,7 +690,7 @@ def run_matching(
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
)
# [2026-10-12 单据数口径修正] 预计 ERP 单据数 ≠ 可执行行数:执行建单按五元组
# (external_org, source_code, receipt_date, from_warehouse, to_warehouse) 分组,
# (external_org, source_code, movement_date, from_warehouse, to_warehouse) 分组,
# 同组多行合并一张 ERP 单(execution_service.prepare_execution 同键同 .strip()
# 规范化)。本值 = 可执行行按同款五元组去重后的组数;行上 external_org 由
# 匹配评估随路由解析填齐(_evaluate_items 评估分支)。
@@ -699,7 +698,7 @@ def run_matching(
(
item.external_org,
str(item.source_code or "").strip(),
str(item.receipt_date or "").strip(),
str(item.movement_date or "").strip(),
str(item.from_warehouse or "").strip(),
str(item.to_warehouse or "").strip(),
)
@@ -710,8 +709,8 @@ def run_matching(
scope_json = {
"transfer_type": config.code,
"source_codes": [str(code) for code in source_codes],
"receipt_date_from": receipt_date_from,
"receipt_date_to": receipt_date_to,
"movement_date_from": movement_date_from,
"movement_date_to": movement_date_to,
"scope_rules": [
{"field": rule.field, "match": rule.match, "values": list(rule.values)}
for rule in scope_rules
@@ -735,9 +734,6 @@ def run_matching(
matching_id="", # 落库时回填
status=_summary_status(sources_tuple, counts),
business_date=business_date,
eligible_receipt_date_to=str(
(date.fromisoformat(business_date) - timedelta(days=1))
),
expires_at="",
counts=counts,
estimated_transfer_quantity=str(estimated_quantity),
@@ -758,7 +754,7 @@ def _evaluate_items(
file_snapshot: dict[str, Any],
now: datetime,
) -> tuple[list[MatchingItemDTO], int]:
"""对工作集 items 执行「成熟过滤→路由分组批量查库存→落位」(既有评估链)。
"""对工作集 items 执行「未来日期阻断→路由分组批量查库存→落位」(既有评估链)。
【出生翻转】工作集=匹配自有 items(或本次出生行);路由解析叠加类型仓库
定义(resolve_warehouse:mapped 透传映射档 / fixed 覆盖);批号查询目标经
@@ -766,6 +762,8 @@ def _evaluate_items(
result_message/external_quantity/from_warehouse/to_warehouse/unit/updated_at);
raw_lines 版本戳归出生/重查对账所有,匹配不碰。
【失败分层 2026-09-29】路由不可解析只落行级 blocked_route_not_resolved。
【成熟过滤已退役 2026-10-16】数据无成熟属性——全部圈中行进路由解析与 ERP
查询;仅未来异动日期仍阻断(数据错误,blocked_future_date)。
Returns:
(items DTO 列表, pending_count)——pending_count=落位前的待查行数。
@@ -773,29 +771,22 @@ def _evaluate_items(
# 延迟引用(evidence_sync 顶层反向导入本模块,模块级互相引用会循环导入)。
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位;成熟行
# 逐行重解析路由(配置可能已变:以本次解析值为准,执行期写前复查兜底漂移)。
# [STEP 1] 未来日期阻断与路由解析(不查询):异动日期晚于业务日期的行直接
# 落位(数据错误);其余行逐行重解析路由(配置可能已变:以本次解析值为准,
# 执行期写前复查兜底漂移)。
business_day = parse_date(business_date)
pending_count = 0
matured: list[tuple[TransferInvoiceItem, RouteMapping]] = []
routable: list[tuple[TransferInvoiceItem, RouteMapping]] = []
output: list[MatchingItemDTO] = []
for row in working:
# [口径] 待查行计数先于落位统计(落位会改写 result_code)。
if (row.status == status_machine.TransferStatus.MATCHING.value
and row.result_code == SYNC_RESULT_PENDING):
pending_count += 1
maturity = maturity_status(row.receipt_date, business_date)
if maturity == MATURITY_NOT_MATURED:
row.status = status_machine.TransferStatus.NOT_MATURED.value
row.result_code = RESULT_NOT_MATURED
row.result_message = f"receipt not matured before {eligible_receipt_date_to(business_date).isoformat()}"
row.updated_at = now
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.inventory_stale_ttl_seconds)))
continue
if maturity == MATURITY_FUTURE:
if parse_date(row.movement_date) > business_day:
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
row.result_code = RESULT_FUTURE_DATE
row.result_message = "future receipt date"
row.result_message = "future movement date"
row.updated_at = now
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.inventory_stale_ttl_seconds)))
@@ -804,7 +795,7 @@ def _evaluate_items(
route = _resolve_route_with_config(
deps, config,
source_code=row.source_code, invoice_no=row.invoice_no,
warehouse_code=row.receipt_warehouse_code or "",
warehouse_code=row.movement_warehouse_code or "",
)
except RouteNotResolvedError:
# [2026-09-25 行级化 / 2026-09-29 失败分层] 路由不可解析:行落
@@ -819,12 +810,12 @@ def _evaluate_items(
int(deps.strategy.inventory_stale_ttl_seconds)))
continue
row.from_warehouse, row.to_warehouse = route.from_warehouse, route.to_warehouse
matured.append((row, route))
routable.append((row, route))
# [STEP 2] 按(来源, 外部组织)分组——来源实例为执行边界(故障域隔离:
# 一个来源的网关绑定缺失不得波及同组织其他来源的查询结果)。
groups: dict[tuple[str, str], list[tuple[TransferInvoiceItem, RouteMapping]]] = {}
for row, route in matured:
for row, route in routable:
groups.setdefault((row.source_code, route.external_org), []).append((row, route))
for (_group_source, external_org), entries in groups.items():
@@ -891,7 +882,7 @@ def _evaluate_items(
row.inventory_checked_at = now
row.unit = ""
else:
match = classify_quantity_match(Decimal(row.receipt_quantity), stock_row.quantity)
match = classify_quantity_match(Decimal(row.movement_quantity), stock_row.quantity)
row.external_quantity = str(stock_row.quantity)
row.inventory_checked_at = now
row.unit = stock_unit
@@ -924,7 +915,7 @@ def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
【2026-10-14 改锚】行当前性从「行出生 sha vs 最新文件 sha」改为「item → 档
记录 file_sha256 == 该来源最新可用文件 sha」:档记录是证据权威,记录被
新版文件原行更新(file_sha256 换新)后行经档即见新版本——档记录无变化
(仍持最新文件 sha)即当前,不再因行出生戳陈旧误判过期(收料 RPA 非全
(仍持最新文件 sha)即当前,不再因行出生戳陈旧误判过期(入站 RPA 非全
量导出,证据未变的行重落后出生戳恒滞后,旧口径会把可执行行永久卡死在
FILE_CHANGED)。行无档关联(隔离的历史行)回读 raw_lines_json 首条
file_sha256(存量兼容);档记录存在但无 sha → None(版本未知,消费方
@@ -962,8 +953,8 @@ def create_matching(
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
movement_date_from: str | None = None,
movement_date_to: str | None = None,
transfer_type: str | None = None,
) -> MatchingSummaryDTO:
"""运行匹配并落库 TransferRun + SourceJob + TransferMatching(行出生即绑定)。
@@ -975,13 +966,13 @@ def create_matching(
Args:
source_codes / business_date / deps: 同 run_matching。
receipt_date_from / receipt_date_to / transfer_type: 同 run_matching。
movement_date_from / movement_date_to / transfer_type: 同 run_matching。
Returns:
匹配摘要(matching_id 已回填)。
"""
# [前置 fail-closed] 类型门禁与日期范围校验先于任何落库(无副作用,异常即整单拒绝)。
config = resolve_transfer_type(transfer_type)
_validate_receipt_date_range(business_date, receipt_date_from, receipt_date_to)
_validate_movement_date_range(business_date, movement_date_from, movement_date_to)
run_no = _generate_no("RUN", business_date)
now = datetime.utcnow()
run = TransferRun(
@@ -1018,8 +1009,8 @@ def create_matching(
business_date=business_date,
deps=deps,
active_source_job_key=active_source_job_key,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
transfer_type=config.code,
matching_id=matching.id,
)
@@ -1065,7 +1056,6 @@ def create_matching(
matching_id=matching.matching_no,
status=matching.status,
business_date=matching.business_date,
eligible_receipt_date_to=result.summary.eligible_receipt_date_to,
expires_at=matching.expires_at.isoformat() if matching.expires_at else "",
counts=result.summary.counts,
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
@@ -1120,7 +1110,7 @@ def restore_matching(
TransferInvoiceItem.query
.filter(TransferInvoiceItem.matching_id == matching.id)
.order_by(
TransferInvoiceItem.receipt_date.asc().nulls_last(),
TransferInvoiceItem.movement_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
@@ -1143,16 +1133,12 @@ def restore_matching(
}
# [STEP 3] counts 按自有行实时聚合。
# matched_count 为"未成熟以外"的可用总数(与 run_matching 语义一致);
# pending/invalid 两桶为 2026-09-25 counts 契约扩展(同口径内存计算)。
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
not_matured_status = status_machine.TransferStatus.NOT_MATURED.value
not_matured_count = sum(1 for row in rows if row.status == not_matured_status)
counts = MatchingCountsDTO(
file_invoice_count=len(rows),
not_matured_count=not_matured_count,
matched_count=len(rows) - not_matured_count,
matched_count=len(rows),
executable_count=sum(1 for row in rows if row.status == ready_status),
blocked_count=sum(1 for row in rows if row.status == blocked_status),
pending_stock_check_count=sum(
@@ -1166,9 +1152,6 @@ def restore_matching(
matching_id=matching.matching_no,
status=matching.status,
business_date=matching.business_date,
eligible_receipt_date_to=str(
date.fromisoformat(matching.business_date) - timedelta(days=1)
),
expires_at=matching.expires_at.isoformat() if matching.expires_at else "",
counts=counts,
estimated_transfer_quantity=matching.estimated_transfer_quantity or "0",
@@ -1232,16 +1215,16 @@ def _item_dto(
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
movement_date=item.movement_date,
lot_no=item.lot_no or "",
receipt_warehouse_code=item.receipt_warehouse_code or "",
movement_warehouse_code=item.movement_warehouse_code or "",
# 交易单位原值(movement 契约第 11 字段):restore/明细队列视图与
# 序列化(serializers)均已透传(T11 接线完成)。
unit=item.unit or "",
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
to_quantity=Decimal(item.movement_quantity),
result=item.result_code or (
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
),
@@ -1295,7 +1278,7 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
moment = now or datetime.utcnow()
ttl_seconds = int(deps.strategy.inventory_stale_ttl_seconds)
# [稳定排序] 收料日期(空值最后)→ 数据源 → Invoice → 创建时间:与重查/恢复
# [稳定排序] 异动日期(空值最后)→ 数据源 → Invoice → 创建时间:与重查/恢复
# 等操作无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位;
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
rows = (
@@ -1312,7 +1295,7 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
),
)
.order_by(
TransferInvoiceItem.receipt_date.asc().nulls_last(),
TransferInvoiceItem.movement_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
@@ -1,10 +1,10 @@
"""在途调拨通用异动/移动表领域字段契约。
用途:定义调拨消费的异动(入库/出库/收料/出货)文件领域字段——业务定死、不配置化。
用途:定义调拨消费的异动(入站/出站)文件领域字段——业务定死、不配置化。
未来出货/入库 Excel 复用同一套字段,靠 in_out_flag 区分方向。
依赖:标准库 dataclasses / enum。
逻辑:字段清单是 immutable 常量;幂等键为 doc_no,严格数量字段为 quantity,
成熟过滤字段为 movement_date;字段映射由 movement_parser 完成。
日期圈定过滤字段为 movement_date;字段映射由 file_parser.parse_movement_rows 完成。
"""
from __future__ import annotations
@@ -41,7 +41,7 @@ class MovementField:
# 定死的通用异动字段(领域契约,不配置化):11 个核心字段 + 扩展可选维度字段。
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingReceiptReport External ASN #);
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生曾收敛为 external_lot_no() 唯一实现。
# [PROMPT_UPDATE] 2026-10-14(Task 11 切换):external_lot_no() 硬编码退役——批号
@@ -1,31 +1,59 @@
"""在途调拨真实异动(收料/出货)文件仓库。
"""在途调拨真实异动(入站/出站)文件仓库。
用途:读取货代收料链路已落库的 ShippingReceiptReportFile(对象存储原始 xlsx),
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、receipt_file_gate(可用性门禁)、openpyxl。
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
用途:读取货代入站链路已落库的 ShippingReceiptReportFile(入站证据 = ShippingReceiptReport RPA
产物,shipping_notice 域术语保留;对象存储原始 xlsx),
用该来源 ShippingReceiptReportConfig 绑定的 inbound 解析规则(purpose='inbound',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyInboundFile。
依赖: ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、inbound_file_gate(可用性门禁)、openpyxl。
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内
折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。
另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道):同一 join
路径但显式去掉当日门禁,仅供 backlog_reparse_service 使用,运行期禁用。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import datetime
from io import BytesIO
from typing import Any, Mapping
from sqlalchemy import or_
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition
# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。
_HEADER_WS_RE = re.compile(r"\s+")
@dataclass(frozen=True)
class ReparseableArchiveFile:
"""一份「可重建」归档文件的维护视图(清空重建专用记录,非运行期取数契约)。
Args:
file_id: 归档文件 id(shipping_receipt_report_files.id,档行溯源列同源)。
storage_key: 对象存储键(重建时按此取归档字节)。
sha256: 文件 SHA-256(重落幂等指纹 / FileMeta.file_sha256)。
file_version: 文件版本戳(sha256: 前缀派生,与 latest_ready_file 同口径)。
archived_at: 归档时间(created_at;重建按此升序重落)。
original_filename: 原始文件名(预检清单/审计展示)。
"""
file_id: int
storage_key: str
sha256: str
file_version: str
archived_at: datetime
original_filename: str
def _normalize_header_label(value: Any) -> str:
"""归一化表头/别名文本:去首尾空白,内部任意空白(含 \\n)压成单空格。
@@ -37,20 +65,20 @@ def _normalize_header_label(value: Any) -> str:
return _HEADER_WS_RE.sub(" ", str(value or "").strip())
class ShippingReceiptFileRepository:
"""真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。"""
class ShippingInboundFileRepository:
"""真实入站/异动 ready 文件仓库(复用 ShippingReceiptReport 归档 + inbound 解析规则)。"""
def __init__(self) -> None:
self._storage = file_asset_storage
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
"""返回该来源最新且当天(业务日)抓取的未过期入站文件;否则返回 None。
Args:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
business_date: 业务日期(用于展示,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
ReadyInboundFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
@@ -62,7 +90,7 @@ class ShippingReceiptFileRepository:
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
return None
report = (
@@ -70,8 +98,8 @@ class ShippingReceiptFileRepository:
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。
usable_receipt_file_condition(),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 inbound_file_gate。
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
@@ -86,7 +114,7 @@ class ShippingReceiptFileRepository:
sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None,
header_row_index=(profile.definition_json or {}).get('header_row_index'),
)
return ReadyReceiptFile(
return ReadyInboundFile(
source_code=source_code,
business_date=business_date,
file_no=report.original_filename or str(report.id),
@@ -95,6 +123,57 @@ class ShippingReceiptFileRepository:
rows=tuple(rows),
)
def list_reparseable_archived_files(self, source_code: str, now: datetime) -> list[ReparseableArchiveFile]:
"""清空重建专用:该来源全部可重建归档(未清理+未过保留期),不设当日门禁。
【AI 触发时机】仅待匹配「清空并重新解析」维护链路使用;运行期落档
(evidence_sync)禁止改用本方法——当日 fail-closed 门禁是运行期语义,
本方法是显式的历史重建通道(spec §6),两者不得混用。
核心逻辑:join 路径与 latest_ready_file 的归档文件查询同款
(ShippingReceiptReportFile → unit_run.has(source_code=...)),但显式去掉
「当天业务日抓取」新鲜度门禁——重建对象正是历史归档;保留期口径与
inbound_file_gate 一致(archive_expires_at 为空视为长期有效),未清理
(archive_deleted_at 空)且未过保留期(expires > now)才可重建。按归档
时间升序返回(重建必须按归档时间序重落,保证幂等重放顺序确定)。
只读查询,不触碰对象存储字节(字节由调用方按需经 file_asset_storage 取)。
Args:
source_code: 来源实例编码(经收料执行单元行 source_code 关联)。
now: 保留期判定时刻。
Returns:
ReparseableArchiveFile 列表(archived_at 升序;无可重建归档为空表)。
"""
from app.models import ShippingReceiptReportFile
reports = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
# 维护通道可用性 = 未清理 + 未过保留期(NULL=长期有效,与
# inbound_file_gate 保留期口径一致);【刻意无当日门禁】。
ShippingReceiptReportFile.archive_deleted_at.is_(None),
or_(
ShippingReceiptReportFile.archive_expires_at.is_(None),
ShippingReceiptReportFile.archive_expires_at > now,
),
)
.order_by(ShippingReceiptReportFile.created_at.asc(), ShippingReceiptReportFile.id.asc())
.all()
)
return [
ReparseableArchiveFile(
file_id=report.id,
storage_key=report.storage_key,
sha256=report.sha256,
file_version=f"sha256:{report.sha256}"[:64],
archived_at=report.created_at,
original_filename=report.original_filename,
)
for report in reports
]
def _extract_movement_rows(
data: bytes,
@@ -59,7 +59,6 @@ def create_execution_run_for_items(
source_codes_json=sorted({item.source_code for item in candidates}),
counts_json={
"file_invoice_count": len(candidates),
"not_matured_count": 0,
"matched_count": len(candidates),
"executable_count": len(candidates),
"blocked_count": 0,
@@ -1,6 +1,6 @@
"""在途调拨严格数量门禁。
用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
用途:实现"异动数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
禁止部分调拨、数量容差与隐式截断。
依赖:标准库 decimal。
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
@@ -18,11 +18,11 @@ MATCH_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
class QuantityValidationError(ValueError):
"""收料数量非法(0、负数、非数字)。"""
"""入站数量非法(0、负数、非数字)。"""
def validate_receipt_quantity(value: Any) -> Decimal:
"""校验并归一化收料数量。
def validate_inbound_quantity(value: Any) -> Decimal:
"""校验并归一化入站数量。
Args:
value: 数字或数字字符串。
@@ -34,9 +34,9 @@ def validate_receipt_quantity(value: Any) -> Decimal:
try:
quantity = Decimal(str(value))
except (InvalidOperation, ValueError) as exc:
raise QuantityValidationError(f"invalid receipt quantity: {value!r}") from exc
raise QuantityValidationError(f"invalid inbound quantity: {value!r}") from exc
if quantity <= 0:
raise QuantityValidationError(f"receipt quantity must be positive: {value!r}")
raise QuantityValidationError(f"inbound quantity must be positive: {value!r}")
return quantity
@@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool:
return Decimal(str(left)) == Decimal(str(right))
def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str:
def classify_quantity_match(inbound_quantity: Any, external_quantity: Any | None) -> str:
"""按严格相等规则分类数量匹配结果。
Args:
receipt_quantity: 收料数量。
inbound_quantity: 入站异动数量。
external_quantity: 外部系统 账面库存;None 表示无库存。
Returns:
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
"""
if external_quantity is None:
return MATCH_INVENTORY_NOT_FOUND
if strict_quantities_equal(receipt_quantity, external_quantity):
if strict_quantities_equal(inbound_quantity, external_quantity):
return MATCH_EXECUTABLE
return MATCH_QUANTITY_MISMATCH
@@ -98,12 +98,12 @@ def _route_for_item(deps: TransferDeps, item: TransferInvoiceItem) -> RouteMappi
if config is None:
return deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
warehouse_code=item.movement_warehouse_code or "",
)
return _resolve_route_with_config(
deps, config,
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
warehouse_code=item.movement_warehouse_code or "",
)
@@ -117,7 +117,7 @@ def _gate_retryable_item(item_id: int) -> TransferInvoiceItem:
Raises:
NotFoundError: item 不存在。
ValidationError: result_unknown 只读 / 状态不可重试 / file_removed 行
不可重查(消失证据不可恢复:证据行的源单已从最新收料文件中消失,
不可重查(消失证据不可恢复:证据行的源单已从最新入站文件中消失,
重查只会用外部系统旧库存把行翻回可执行,唯一出口=人工关闭 /
等重新同步恢复该行)。
"""
@@ -184,7 +184,7 @@ def _degrade_recheck_row(item: TransferInvoiceItem, *, attempt: TransferAttempt,
def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttempt,
before_status: str, receipt_qty: Decimal, stock_row,
before_status: str, inbound_qty: Decimal, stock_row,
operation_id: str, request_id: str | None) -> str:
"""行级评估收口:账面对照落状态/结果码/外部数量/单位,关闭 Attempt 并写审计。
@@ -192,14 +192,14 @@ def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttemp
item: 重查行(Attempt 已创建并 flush)。
attempt: 该行本次 external_query Attempt(running 态)。
before_status: 重查前状态(审计 before)。
receipt_qty: 行收料数量(严格相等判定的基准)。
inbound_qty: 行异动数量(严格相等判定的基准)。
stock_row: 批量查询结果中该行的账面行(StockRow);查无记录为 None。
operation_id / request_id: 审计上下文(查询 operation_id 组内共享)。
Returns:
重查后的行状态。
"""
stock_qty = stock_row.quantity if stock_row is not None else None
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
if stock_qty is None or classify_quantity_match(inbound_qty, stock_qty) != RESULT_EXECUTABLE:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
item.result_message = "external inventory not found" if stock_qty is None else "strict quantity mismatch"
@@ -278,7 +278,7 @@ def _recheck_items_batch(
保持历史 fail-closed 行为)。
"""
# [STEP 1] 行级前置解析(行级隔离):路由解析(叠加行所属匹配类型的仓库
# 定义,fixed 覆盖映射档)+ 收料数量解析,失败行原位跳过、不拖垮整批;行仓库
# 定义,fixed 覆盖映射档)+ 异动数量解析,失败行原位跳过、不拖垮整批;行仓库
# 字段刷新为本次解析值——查询与后续执行写路径必须用同一仓库值:行上旧值可能
# 来自更早配置(路由已漂移),也可能为空(如 blocked_missing_unit 行在路由
# 解析前被阻断)。
@@ -287,7 +287,7 @@ def _recheck_items_batch(
for item in items:
try:
route = _route_for_item(deps, item)
receipt_qty = Decimal(item.receipt_quantity)
inbound_qty = Decimal(item.movement_quantity)
except Exception as exc: # noqa: BLE001 —— 行级隔离:路由漂移/缺失/脏数量只影响该行
row_errors[item.id] = exc
logger.warning(
@@ -298,7 +298,7 @@ def _recheck_items_batch(
if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse:
item.from_warehouse = route.from_warehouse
item.to_warehouse = route.to_warehouse
resolved.append((item, route, receipt_qty))
resolved.append((item, route, inbound_qty))
# [STEP 2] 按组织分组(同写前复查的 external_org 分组口径):同组行共享
# 一次批量查询,N 行 = 每组织 1 次外部调用。
@@ -314,7 +314,7 @@ def _recheck_items_batch(
operation_id = f"op-{uuid.uuid4().hex[:12]}"
attempts: dict[int, TransferAttempt] = {}
before_statuses: dict[int, str] = {}
for item, route, receipt_qty in entries:
for item, route, inbound_qty in entries:
item.attempt_no += 1
before_statuses[item.id] = item.status
attempts[item.id] = TransferAttempt(
@@ -323,7 +323,7 @@ def _recheck_items_batch(
request_snapshot_json={
"invoice_no": item.invoice_no, "external_org": external_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
"quantity": str(inbound_qty),
},
)
db.session.add(attempts[item.id])
@@ -336,7 +336,7 @@ def _recheck_items_batch(
targets=[StockTarget(
material_no=item.material_no, warehouse_code=route.from_warehouse,
lot_no=item_external_lot_no(item),
) for item, route, _receipt_qty in entries],
) for item, route, _inbound_qty in entries],
)
except Exception as exc: # noqa: BLE001
# [降级] 外部系统网关/绑定故障是组级事实:组内各行统一降级为
@@ -347,14 +347,14 @@ def _recheck_items_batch(
"transfer recheck org query failed (degrade rows): org=%s rows=%s error=%s",
external_org, len(entries), detail,
)
for item, route, receipt_qty in entries:
for item, route, inbound_qty in entries:
statuses[item.id] = _degrade_recheck_row(
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
detail=detail, operation_id=operation_id, request_id=request_id,
)
db.session.commit()
continue
for item, route, receipt_qty in entries:
for item, route, inbound_qty in entries:
# [外部形态] 回查键与查询目标同用派生批号(三元组精确匹配)。
stock_row = stock.lookup_row(
material_no=item.material_no, warehouse_code=route.from_warehouse,
@@ -362,7 +362,7 @@ def _recheck_items_batch(
)
statuses[item.id] = _apply_recheck_outcome(
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
receipt_qty=receipt_qty, stock_row=stock_row,
inbound_qty=inbound_qty, stock_row=stock_row,
operation_id=operation_id, request_id=request_id,
)
db.session.commit()
@@ -448,7 +448,7 @@ def _reconcile_items_with_ledger(
) -> None:
"""对档重圈并与本匹配自有 items 对账(出生翻转后重查的前置步骤,规格 §9)。
核心逻辑:[STEP 1] 按匹配快照规则(scope_rules + 来源 + 收料日期范围)圈定
核心逻辑:[STEP 1] 按匹配快照规则(scope_rules + 来源 + 异动日期范围)圈定
档记录——复用匹配创建的同一圈档函数 _circle_ledger_records(固定条件单点
实现,杜绝谓词漂移),排除已执行封存、其他匹配的有效占用(D17;本匹配自有
items 不构成占用)。[STEP 2] 三分类对账(**终态守卫:SUCCESS/DUPLICATE_
@@ -486,8 +486,8 @@ def _reconcile_items_with_ledger(
records = _circle_ledger_records(
source_codes=sources,
rules=rules,
receipt_date_from=scope.get("receipt_date_from"),
receipt_date_to=scope.get("receipt_date_to"),
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,
)
@@ -542,23 +542,23 @@ def _reconcile_items_with_ledger(
)
db.session.add(born)
continue
# [②证据对账] 只比对收料事实(数量/批号/仓库);名称/规格为展示字段。
# [②证据对账] 只比对异动事实(数量/批号/仓库);名称/规格为展示字段。
# [终态守卫·刷新面] 终态行(已执行/人工关闭/取消/在流)绝不触碰(含
# updated_at)——旧 evidence_sync「终态行绝不触碰/不复活」冻结约束在
# 翻转后的延续(防同批档证据更新促成二次写 ERP);非终态行照常对账。
if item.status in _SYNC_TERMINAL_STATUSES:
continue
evidence_changed = (
str(item.receipt_quantity) != str(record.quantity or "")
str(item.movement_quantity) != str(record.quantity or "")
or (item.lot_no or "") != (record.lot_no or "")
or (item.receipt_warehouse_code or "") != (record.warehouse_code or "")
or (item.movement_warehouse_code or "") != (record.warehouse_code or "")
)
item.material_name = record.material_name or ""
item.specification = record.specification or ""
if evidence_changed:
item.receipt_quantity = str(record.quantity or "0")
item.movement_quantity = str(record.quantity or "0")
item.lot_no = record.lot_no or ""
item.receipt_warehouse_code = record.warehouse_code or ""
item.movement_warehouse_code = record.warehouse_code or ""
# 重置待查:旧库存是对旧数量查的,作废;取数时刻同步置空。
item.status = status_machine.TransferStatus.MATCHING.value
item.result_code = SYNC_RESULT_PENDING
@@ -41,11 +41,9 @@ def serialize_summary(summary) -> dict[str, Any]:
"matching_id": summary.matching_id,
"status": summary.status,
"business_date": summary.business_date,
"eligible_receipt_date_to": summary.eligible_receipt_date_to,
"expires_at": summary.expires_at,
"counts": {
"file_invoice_count": summary.counts.file_invoice_count,
"not_matured_count": summary.counts.not_matured_count,
"matched_count": summary.counts.matched_count,
"executable_count": summary.counts.executable_count,
"blocked_count": summary.counts.blocked_count,
@@ -74,7 +72,7 @@ def serialize_item(item) -> dict[str, Any]:
"specification": item.specification,
"invoice_no": item.invoice_no,
"lot_no": item.lot_no,
"receipt_date": item.receipt_date,
"movement_date": item.movement_date,
"from_warehouse": item.from_warehouse,
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"to_warehouse": item.to_warehouse,
@@ -137,7 +135,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
items: 单挂接行集(TransferInvoiceItem 列表,调用方保证顺序)。
Returns:
单投影 dict(8 键):{doc_no, receipt_date, from_warehouse, to_warehouse,
单投影 dict(8 键):{doc_no, movement_date, from_warehouse, to_warehouse,
status, erp_document_no, error_message, lines}。
"""
# 延迟引用 execution_service 的行聚合(模块级互相引用会循环导入;
@@ -166,7 +164,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
reason_by_key[key] = message
return {
"doc_no": doc.doc_no,
"receipt_date": doc.receipt_date,
"movement_date": doc.movement_date,
"from_warehouse": doc.from_warehouse,
"to_warehouse": doc.to_warehouse,
"status": doc.status,
@@ -174,7 +172,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
"error_message": doc.error_message,
"lines": [
{
# 行级溯源收料通知号(2026-09-29 契约扩充,随 ERP 写入行同款口径
# 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
"invoice_no": line["invoice_no"],
"material_no": line["material_no"],
@@ -212,7 +210,7 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
"submit_timestamp": doc.submit_timestamp,
"status": base["status"],
"status_group": order_status_group(doc.status),
"receipt_date": base["receipt_date"],
"movement_date": base["movement_date"],
"from_warehouse": base["from_warehouse"],
"to_warehouse": base["to_warehouse"],
"erp_document_no": base["erp_document_no"],
@@ -227,10 +225,10 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
# deriveBatchNo 镜像转换(与匹配卡/可调拨明细/待办池同规则)。
"lot_no": item.lot_no or "",
"quantity": item.receipt_quantity,
"quantity": item.movement_quantity,
"unit": item.unit or "",
}
# 行序对齐统一规则第三键(2026-09-29):同单内收料日期/数据源恒同
# 行序对齐统一规则第三键(2026-09-29):同单内异动日期/数据源恒同
# (组键含两者),按 invoice_no 升序、id 兜底稳定排序。
for item in sorted(items, key=lambda row: (str(row.invoice_no or ""), row.id))
],
@@ -1,16 +1,17 @@
"""在途调拨来源收料文件状态投影服务。
"""在途调拨来源入站文件状态投影服务。
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
用途:只读货代入站链路(入站证据 = ShippingReceiptReport RPA 产物,shipping_notice 域,术语保留)
已有事实(ShippingInboundRpaUnitRun 别名 + ShippingReceiptReportFile),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 /
无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
receipt_file_gate(可用/失效判定单一事实来源)。
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
见 receipt_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile ,前者经域内别名引用)、
inbound_file_gate(可用/失效判定单一事实来源)。
逻辑:按来源取该来源最新入站执行单元;命中可用门禁(当天业务日抓取且未过期,
见 inbound_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→
parse_failed(不可当 ready,仍带 file_no/file_sha256 便于诊断);
有进行中单元 → fetching;最新单元为失败终态 → failed;
文件仍在但已失效 → expired;否则 → none。
record_receipt_parse_failure / clear_receipt_parse_failure 维护解析失败三列
record_inbound_parse_failure / clear_inbound_parse_failure 维护解析失败三列
(写入与清除均只 flush 不 commit,事务归属调用方)。
"""
@@ -19,24 +20,25 @@ from __future__ import annotations
from datetime import datetime
from app import db
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.services.in_transit_transfer.receipt_file_gate import (
expired_receipt_file_condition,
usable_receipt_file_condition,
from app.models import ShippingReceiptReportFile
from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun
from app.services.in_transit_transfer.inbound_file_gate import (
expired_inbound_file_condition,
usable_inbound_file_condition,
)
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
FAILED_UNIT_STATUSES = ('failed', 'cancelled')
# 空数据(no_receipt_data):抓取成功但当日无收料记录,属业务结果而非故障,
# 独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
# 空数据(RPA empty 回调契约值,shipping_notice 域术语保留):抓取成功但当日无入站记录,
# 属业务结果而非故障,独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
NO_DATA_UNIT_STATUSES = ('empty',)
def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的收料文件状态投影。
"""返回某来源的入站文件状态投影。
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
inbound_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
@@ -49,7 +51,7 @@ def resolve_source_file_status(*, source_code: str) -> dict:
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
usable_receipt_file_condition(),
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
@@ -72,23 +74,23 @@ def resolve_source_file_status(*, source_code: str) -> dict:
}
active_unit = (
ShippingReceiptRpaUnitRun.query
ShippingInboundRpaUnitRun.query
.filter_by(source_code=source_code)
.filter(ShippingReceiptRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.filter(ShippingInboundRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(ShippingInboundRpaUnitRun.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 = (
ShippingReceiptRpaUnitRun.query
ShippingInboundRpaUnitRun.query
.filter_by(source_code=source_code)
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.order_by(ShippingInboundRpaUnitRun.id.desc())
.first()
)
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
# 空数据:抓取成功但当日无收料记录——如实投影 no_data,不得与抓取失败混淆。
# 空数据:抓取成功但当日无入站记录——如实投影 no_data,不得与抓取失败混淆。
return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
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}
@@ -99,7 +101,7 @@ def resolve_source_file_status(*, source_code: str) -> dict:
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
expired_receipt_file_condition(),
expired_inbound_file_condition(),
)
.first()
)
@@ -109,18 +111,18 @@ def resolve_source_file_status(*, source_code: str) -> dict:
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
def record_receipt_parse_failure(
def record_inbound_parse_failure(
*,
report: ShippingReceiptReportFile,
error_code: str,
error_message: str,
now: datetime | None = None,
) -> None:
"""标记一份收料归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
"""标记一份入站归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
【AI 触发时机】收料归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、
【AI 触发时机】入站归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、
让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后
改调 clear_receipt_parse_failure。
改调 clear_inbound_parse_failure。
核心逻辑:[STEP 1] 写入失败时间(now 或当前 UTC)与截断后的错误码/错误信息;
[STEP 2] db.session.flush() 使投影同事务内立即可见。只 flush 不 commit,
@@ -140,8 +142,8 @@ def record_receipt_parse_failure(
db.session.flush()
def clear_receipt_parse_failure(*, report: ShippingReceiptReportFile) -> None:
"""清除一份收料归档文件的解析失败标记(三列置空),投影恢复 ready。
def clear_inbound_parse_failure(*, report: ShippingReceiptReportFile) -> None:
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态
投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。
@@ -1,15 +1,17 @@
"""在途调拨状态机与转换门禁。
用途:定义提示词冻结的 13 个业务状态(TransferStatus)、Run 生命周期
用途:定义提示词冻结的 12 个业务状态(TransferStatus)、Run 生命周期
(TransferRunStatus)与通知状态(TransferNotificationStatus),
并强制所有状态转换走服务端门禁。
依赖:app.core.errors.AppError。
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
result_unknown / manually_closed / success / duplicate_success /
not_matured / cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义:
cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义:
DOCUMENT_RETRIGGER_TRANSITIONS 允许 result_unknown 单经人工 retrigger
→ executing,D11 唯一出口;QUEUED Run 经 worker 领取 → executing);
通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。
【not_matured 状态已退役 2026-10-16】成熟概念删除(数据无成熟属性,
日期边界由调用方入参给定);存量行经 tt16 迁移重映射为 cancelled。
"""
from __future__ import annotations
@@ -23,7 +25,7 @@ INVALID_STATE_TRANSITION_CODE = "TRANSFER.INVALID_STATE_TRANSITION"
class TransferStatus(StrEnum):
"""Invoice 项业务状态(含提示词冻结的全部 13 个状态)。"""
"""Invoice 项业务状态(含提示词冻结的全部 12 个状态)。"""
FILE_PENDING = "file_pending"
FILE_READY = "file_ready"
@@ -33,7 +35,6 @@ class TransferStatus(StrEnum):
SUCCESS = "success"
DUPLICATE_SUCCESS = "duplicate_success"
BLOCKED_RECOVERABLE = "blocked_recoverable"
NOT_MATURED = "not_matured"
RESULT_UNKNOWN = "result_unknown"
MANUALLY_CLOSED = "manually_closed"
CANCELLED = "cancelled"
@@ -72,7 +73,6 @@ TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.NOTIFICATION_FAILED.value,
})
@@ -89,7 +89,6 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
TransferStatus.MATCHING.value: frozenset({
TransferStatus.READY_TO_EXECUTE.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.READY_TO_EXECUTE.value: frozenset({
@@ -114,7 +113,6 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.NOT_MATURED.value: frozenset(),
TransferStatus.SUCCESS.value: frozenset(),
TransferStatus.DUPLICATE_SUCCESS.value: frozenset(),
# [T10/R7 出边] result_unknown 行唯一出边 = 人工 retrigger 驱动 → executing
@@ -59,10 +59,9 @@ class WecomSummarySender:
matched=counts.get("matched_count", 0),
pending=counts.get("pending_stock_check_count", 0),
),
"可执行: {executable} 数量不符: {blocked} 未成熟: {not_matured}".format(
"可执行: {executable} 数量不符: {blocked}".format(
executable=counts.get("executable_count", 0),
blocked=counts.get("blocked_count", 0),
not_matured=counts.get("not_matured_count", 0),
),
])
@@ -1,9 +1,11 @@
"""
backend/app/services/schedule/freight_receipt_rpa_finalize.py
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微。
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。
依赖:ShippingReceiptRpaUnitRun、shipping_receipt_rpa_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom;
超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。
"""
from __future__ import annotations
@@ -12,6 +14,7 @@ from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from sqlalchemy import func
from app import db
from app.models import ScheduleRun, ScheduleTask
@@ -394,6 +397,38 @@ def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitR
return max(stamps)
def _fail_receipt_unit_with_timeout(
unit: ShippingReceiptRpaUnitRun, *, now: datetime, timeout_seconds: int,
run_no: str | None = None,
) -> None:
"""单个收料单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。
核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——run 级扫描与孤儿
单元扫描共用本函数收口单元,防止两条路径语义漂移。只改单元不 commit,
事务归属调用方。
Args:
unit: 待收口的非终态收料单元。
now: 收口时刻(同批单元共享同一时间戳)。
timeout_seconds: 超时窗(写入错误文案与审计 metadata)。
run_no: 所属排程 run 号(run 级回收传实;孤儿单元无排程,保持 None)。
Returns:
None。
"""
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
unit.status = 'failed'
unit.error_code = 'RPA.RECEIPT_CALLBACK_TIMEOUT'
unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds'
unit.finished_at = now
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_timeout', aggregate_type='shipping_receipt_unit',
aggregate_id=str(unit.id), run_no=run_no, actor_type='worker', actor_id='schedule-recovery',
unit_id=unit.id, result='failure', before=before,
after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'timeout_seconds': timeout_seconds},
)
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。
@@ -412,18 +447,7 @@ def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_se
now = datetime.utcnow()
pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}]
for unit in pending:
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
unit.status = 'failed'
unit.error_code = 'RPA.RECEIPT_CALLBACK_TIMEOUT'
unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds'
unit.finished_at = now
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_timeout', aggregate_type='shipping_receipt_unit',
aggregate_id=str(unit.id), run_no=run.run_no, actor_type='worker', actor_id='schedule-recovery',
unit_id=unit.id, result='failure', before=before,
after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'timeout_seconds': timeout_seconds},
)
_fail_receipt_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no)
run.status = 'failed'
run.finished_at = now
run.duration_ms = int((now - run.started_at).total_seconds() * 1000)
@@ -463,3 +487,46 @@ def recover_all_stale_receipt_rpa_schedule_runs() -> int:
if recovered:
db.session.commit()
return recovered
def recover_all_stale_orphan_receipt_units() -> int:
"""回收按需触发(无排程绑定)的超时收料单元,解除来源投影永久 fetching。
【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台
重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 inbound_trigger_service),
不在 run 级扫描(recover_all_stale_receipt_rpa_schedule_runs 按 run 遍历)范围内;
Worker 网页异常关闭后回调永不到达,若不回收则来源投影(source_file_status)
永久 fetching、前端重试按钮永久锁死(2026-10-16 事故根因)。
核心逻辑:[STEP 1] 扫 schedule_run_id IS NULL、状态非终态、活动锚
(coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取
无 started_at 时以 created_at 兜底;注意 run 级 _receipt_last_activity 是
笔间静默口径、刻意不含 created_at,两者语义不同)超过
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_receipt_rpa_unit)
原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。
[STEP 2] 逐单元经 _fail_receipt_unit_with_timeout 收口(failed +
RPA.RECEIPT_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」
(与 recover_stale_waiting_source_jobs 口径一致)。
Returns:
本次回收的单元数。
"""
timeout_seconds = _receipt_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
orphans = (
ShippingReceiptRpaUnitRun.query
.filter(
ShippingReceiptRpaUnitRun.schedule_run_id.is_(None),
ShippingReceiptRpaUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')),
func.coalesce(ShippingReceiptRpaUnitRun.started_at, ShippingReceiptRpaUnitRun.created_at) < cutoff,
)
.all()
)
if not orphans:
return 0
now = datetime.utcnow()
for unit in orphans:
_fail_receipt_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds)
db.session.commit()
return len(orphans)
@@ -1,15 +1,16 @@
"""自动调拨排程。
用途:自动处理当日新成熟可调拨项与历史可恢复异常;执行结果通知统一走
用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走
排程「启用通知」通用企微通知,本任务不自建领域通知。
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)、
inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、
date_policy(业务日与日期解析)。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
不依赖其他排程成功;来源留空兜底为全部启用收料来源;可选收料日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层;
空数据日(无 run_no 且无 errors)置 domain_notification_managed 保持
静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
该偏移参数是自动处理面的唯一日期边界(成熟规则已退役 2026-10-16,
未配置即处理全部圈中数据);空数据日(无 run_no 且无 errors)置
domain_notification_managed 保持静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
"""
from __future__ import annotations
@@ -21,7 +22,7 @@ from app.models import ScheduleRun, ScheduleTask
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
from app.services.schedule.job_registry import ScheduleExecuteResult
@@ -31,12 +32,12 @@ def _task_params(task: ScheduleTask) -> dict[str, Any]:
def _wanted_source_codes(task: ScheduleTask) -> list[str]:
"""提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。
"""提取结构化 source_codes;留空回落为全部启用且已配置收料报表(入站证据)的来源。
Args:
task: 排程任务(job_params.source_codes 可为列表/字符串/缺省)。
Returns:
去空白后的来源编码列表;留空时为 list_receipt_capable_source_codes() 结果。
去空白后的来源编码列表;留空时为 list_inbound_capable_source_codes() 结果。
"""
params = _task_params(task)
values = params.get("source_codes") or []
@@ -44,12 +45,12 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
values = [values]
codes = [str(item).strip() for item in values if str(item).strip()]
if not codes:
codes = list_receipt_capable_source_codes()
codes = list_inbound_capable_source_codes()
return codes
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
"""把「T−N 偏移天数」参数换算为执行日口径的具体收料日期(T−N)。
"""把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。
Args:
business_date: 业务日期 T(YYYY-MM-DD)。
@@ -79,10 +80,10 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
可选收料日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
偏移非法(负数/小数/非数字)快速失败不执行;范围越界由匹配层
ValidationError 落 errors 走硬失败路径。
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面
(成熟规则已退役:未配置偏移即处理全部圈中数据);偏移非法(负数/小数/
非数字)快速失败不执行;范围越界由匹配层 ValidationError 落 errors 走硬失败路径。
Args:
task: 排程任务(job_params: source_codes/recover_history/
@@ -99,10 +100,10 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
# 防止坏参数被静默忽略后退化成全量积压处理。
param_errors: list[str] = []
receipt_date_from = _offset_to_date(
business_date, params.get("receipt_from_offset_days"), "收料日期起点", param_errors)
receipt_date_to = _offset_to_date(
business_date, params.get("receipt_to_offset_days"), "收料日期终点", param_errors)
movement_date_from = _offset_to_date(
business_date, params.get("receipt_from_offset_days"), "异动日期起点", param_errors)
movement_date_to = _offset_to_date(
business_date, params.get("receipt_to_offset_days"), "异动日期终点", param_errors)
if param_errors:
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
@@ -117,8 +118,8 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
deps=deps,
source_codes=source_codes,
recover_history=recover_history,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
transfer_type=transfer_type,
)
@@ -612,7 +612,7 @@ def _register_builtin_platform_jobs() -> None:
"label": "收料日期起(T-N)",
"label_key": "admin.schedule.form.transferReceiptDateFrom",
"required": False,
"help": "填天数 N,按执行日换算收料日期下限 T−N;例:4=从 T−4 起。留空=全部成熟积压(默认 ≤ T-2)。",
"help": "填天数 N,按执行日换算异动日期下限 T−N;例:4=从 T−4 起。留空=全部积压。",
},
{
"key": "receipt_to_offset_days",
@@ -620,7 +620,7 @@ def _register_builtin_platform_jobs() -> None:
"label": "收料日期止(T-N)",
"label_key": "admin.schedule.form.transferReceiptDateTo",
"required": False,
"help": "填天数 N,按执行日换算收料日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于成熟上限(默认 T-2)。",
"help": "填天数 N,按执行日换算异动日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于执行日业务日期。",
},
),
defaults={"source_codes": [], "recover_history": True},
@@ -24,6 +24,7 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.freight_receipt_rpa_finalize import (
recover_all_stale_orphan_receipt_units,
recover_all_stale_receipt_rpa_schedule_runs,
recover_stale_receipt_rpa_schedule_runs,
is_awaiting_receipt_rpa_schedule_run,
@@ -370,7 +371,7 @@ def prepare_schedule_queue() -> int:
# 调拨来源等待回调 Job 的超时回收与下方 RPA 心跳告警同属每轮领取维护:
# 不能挂在 worker 启动一次性分支里,否则进程长期驻留期间超时任务永远无法终态化。
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
from app.services.in_transit_transfer.inbound_callback_bridge import recover_stale_waiting_source_jobs
transfer_stale = recover_stale_waiting_source_jobs()
if transfer_stale:
@@ -383,6 +384,13 @@ def prepare_schedule_queue() -> int:
if receipt_stale:
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale)
# 按需触发(无排程)孤儿单元同口径回收(2026-10-16):调拨工作台重试/自动调拨
# 补抓创建的单元 schedule_run_id 为 NULL,上方 run 级扫描按 run 遍历覆盖不到;
# 网页异常关闭后回调永不到达,不回收则来源投影永久 fetching、重试按钮永久锁死。
orphan_stale = recover_all_stale_orphan_receipt_units()
if orphan_stale:
current_app.logger.info("[schedule-worker] recovered %d stale orphan receipt RPA units", orphan_stale)
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
@@ -1,7 +1,8 @@
"""
services/shipping_notice/inventory_file_store.py
用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。
用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影;构造下载展示名
(build_inventory_download_name:企微压缩包短名规则 + exported_at 数据截止时间点)。
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT);
fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution:
@@ -15,6 +16,7 @@ import re
import hashlib
import shutil
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
@@ -190,10 +192,88 @@ def resolve_task_inventory_download(task: ShippingNotice) -> tuple[Path, str] |
path = Path(storage_path).resolve()
if not path.is_file():
return None
filename = str(inv_file.source_file_name or f'{inv_file.inventory_file_no}{path.suffix or ".xlsx"}').strip()
filename = build_inventory_download_name(
inv_file, source_file_name=inv_file.source_file_name, path=path,
)
return path, filename
_DOWNLOAD_SEQ_PREFIX_RE = re.compile(r'^(\d{1,4})_')
_DOWNLOAD_RUN_TS_RE = re.compile(r'RUN(\d{8,14})')
# 规范名形态:{seq}_{source}_{warehouse}_{12位时间}.<后缀>。source/warehouse 为单 token
# ([^_]+,\w 会把下划线吞进段里导致 worker 长名被误判为规范名);时间固定 12 位
# (exported_at / rpa_run_no / mtime 三条回退路径均格式化为 %Y%m%d%H%M)。命中即原样返回。
_DOWNLOAD_CANONICAL_RE = re.compile(r'^\d{1,4}_[^_]+_[^_]+_\d{12}\.[A-Za-z0-9]{3,5}$')
_DOWNLOAD_NAME_SANITIZE_RE = re.compile(r'[^\w.\-]+')
def build_inventory_download_name(
inv_file: ShippingInventoryFile,
*,
source_file_name: str | None,
path: Path | None = None,
) -> str:
"""构造库存快照的下载展示名:复用企微压缩包短名规则并附加数据截止时间点。
【AI 触发时机】:任务级/行级库存文件下载接口构造 download_name 时调用;
上传、解析、匹配链路禁止使用——登记名 source_file_name 保持 worker 原始名作审计。
核心逻辑:目标格式 `{seq}_{source}_{warehouse}_{yyyyMMddHHmm}.xlsx`(seq 取 worker
原名前缀,与企微压缩包内文件一一对应,取不到则省略);时间点取 exported_at
(数据截止时刻),缺失时回退 rpa_run_no 内嵌 RUN 时间戳,再回退托管文件 mtime;
warehouse 连续重复段去重(AWSDU_AWSDU → AWSDU);已是规范名或 source/warehouse
信息不足时原样返回(幂等,禁止凭空造名)。
Args:
inv_file: 库存快照行(source_code/warehouse_id/warehouse_code/exported_at/rpa_run_no)。
source_file_name: worker 原始文件名(如 006_inventory_RUN…_DSV360_AWSDU_AWSDU_….xlsx)。
path: 托管文件路径;exported_at 与 rpa_run_no 均缺失时用其 mtime 兜底时间点。
Returns:
下载展示文件名;worker 原始名缺失时回退 inventory_file_no + 后缀(既有行为)。
"""
base = str(source_file_name or '').strip()
if not base:
suffix = Path(path or base).suffix or '.xlsx'
return f'{inv_file.inventory_file_no}{suffix.lower()}'
if _DOWNLOAD_CANONICAL_RE.match(base):
return base
seq_match = _DOWNLOAD_SEQ_PREFIX_RE.match(base)
seq = f"{int(seq_match.group(1)):03d}" if seq_match else ''
source = str(inv_file.source_code or '').strip()
warehouse_candidates = [
str(inv_file.warehouse_id or '').strip(),
str(inv_file.warehouse_code or '').strip(),
]
warehouse = next((item for item in warehouse_candidates if item), '')
timestamp = ''
if inv_file.exported_at is not None:
timestamp = inv_file.exported_at.strftime('%Y%m%d%H%M')
if not timestamp:
run_ts = _DOWNLOAD_RUN_TS_RE.search(str(inv_file.rpa_run_no or ''))
if run_ts:
timestamp = run_ts.group(1)[:12]
if not timestamp and path is not None:
try:
timestamp = datetime.fromtimestamp(path.stat().st_mtime).strftime('%Y%m%d%H%M')
except OSError:
timestamp = ''
parts = [part for part in (seq, source, warehouse, timestamp) if part]
if not source or not warehouse or not timestamp or not parts:
# source/warehouse/时间点任一缺失都不足以构造规范名,保持原名避免误导。
return base
sanitized = [_DOWNLOAD_NAME_SANITIZE_RE.sub('_', part).strip('_') for part in parts]
# token 级连续重复去重(worker 曾把 site+warehouse 同值拼成 AWSDU_AWSDU):
# 按下划线拆开折叠相邻重复段,同时覆盖段内与跨段重复。
tokens: list[str] = []
for part in sanitized:
for token in part.split('_'):
if token and (not tokens or tokens[-1] != token):
tokens.append(token)
suffix = Path(base).suffix or '.xlsx'
return "_".join(tokens) + suffix.lower()
def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。"""
cached_rows = [
@@ -23,6 +23,7 @@ from app.models import (
ShippingInventorySource,
ShippingInventoryStructureAnalysis,
ShippingOrderField,
ShippingReceiptReportConfig,
)
@@ -56,9 +57,9 @@ def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> se
return match_ids | quantity_ids
# 异动(movement)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
# 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
"""校验 movement 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
"""校验 inbound 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
movement_codes = {field.code for field in MOVEMENT_FIELDS}
@@ -79,13 +80,13 @@ def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
return mapped_codes
def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, Any]:
def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]:
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。
Args:
raw: 解析定义对象。
purpose: 'inventory'(沿用库存字段目录与 match_keys)或
'movement'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
purpose: 'onhand'/'outbound'(沿用库存字段目录与 match_keys)或
'inbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
"""
if not isinstance(raw, dict):
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
@@ -98,7 +99,7 @@ def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, A
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if purpose == 'movement':
if purpose == 'inbound':
_required_movement_field_ids(raw)
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
@@ -232,8 +233,8 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
db.session.add(profile)
purpose = str(data.get('purpose') or profile.purpose or 'inventory').strip().lower()
if purpose not in {'inventory', 'movement'}:
purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower()
if purpose not in {'onhand', 'inbound', 'outbound'}:
raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if profile_id and purpose != profile.purpose:
raise ValidationError(
@@ -289,13 +290,13 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
)
from app.services.shipping_notice.order_schema import service as order_schema_service
# movement 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;inventory 维持原约束。
# inbound 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand/outbound 维持原约束。
referenced_field_ids = {
str(item.get('order_field_id') or '')
for item in (profile.definition_json or {}).get('match_keys', [])
if isinstance(item, dict)
}
if profile.purpose != 'movement':
if profile.purpose != 'inbound':
published_field_ids = {
str(item.get('field_id') or '')
for item in order_schema_service.get_published_contract().get('fields', [])
@@ -315,13 +316,17 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
def retire(profile_id: int) -> dict[str, Any]:
"""退役无库存源引用的 published Profile,避免使现有 Source 静默失效。"""
"""退役无库存源/收料报表配置引用的 published Profile,避免使现有绑定静默失效。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'published':
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID')
if ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count():
bound_sources = ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count()
# 收料报表配置(ShippingReceiptReportConfig)同样绑定解析 Profile:退役前必须一并核查,
# 否则入站文件解析链(inbound purpose)会静默失去规则。
bound_receipt_configs = ShippingReceiptReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
if bound_sources or bound_receipt_configs:
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED')
profile.status = 'retired'
db.session.commit()
@@ -453,7 +453,7 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
saved = inventory_parsing_profile.save_draft({
'profile_code': data.get('profile_code'),
'display_name': data.get('display_name'),
# 用途随请求透传(缺省沿用既有草稿/默认 inventory):movement 草稿端点为定死领域字段。
# 用途随请求透传(缺省沿用既有草稿/默认 onhand):inbound 草稿端点为定死领域字段。
'purpose': data.get('purpose'),
'file_format': analysis.file_format,
'sample_analysis_id': analysis.id,
@@ -4,7 +4,7 @@
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线);
每笔终态回调回写 ScheduleRun 进度计数(对齐库存 inventory-batch-progress)。
依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、
audit_service、freight_receipt_rpa_finalize、in_transit_transfer.receipt_callback_bridge(惰性导入)、
audit_service、freight_receipt_rpa_finalize、in_transit_transfer.inbound_callback_bridge(惰性导入)、
in_transit_transfer.evidence_sync(惰性导入,仅 success 终态)。
逻辑:success/empty/failed 三个终态分支各自 commit 后调用 _advance_transfer_source_job;
empty 落库 error_code=no_receipt_data(对齐库存 no_inventory_data);
@@ -70,8 +70,8 @@ def _advance_transfer_source_job(
"""
try:
from app import db
from app.services.in_transit_transfer.receipt_callback_bridge import advance_source_job_from_receipt_callback
advanced = advance_source_job_from_receipt_callback(
from app.services.in_transit_transfer.inbound_callback_bridge import advance_source_job_from_inbound_callback
advanced = advance_source_job_from_inbound_callback(
source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256,
callback_ok=ok, error_code=error_code, error_message=error_message,
)
@@ -104,6 +104,9 @@ class _ConversationProjectionLoadContext:
# 冻结选择计划中每个 Intake 的附件项(含已选/跳过状态),用于把尚未物化的
# 「已选但未识别」附件展示出来,便于排查未识别原因。
planned_attachments_by_intake_no: dict[str, list[dict[str, Any]]]
# reparse_pending Case 且后继 Run 仍 queued/processing 的文档 id 集合;
# EML 聚合叶子据此把在途重识别投影为 processing(与摘要 _status 同判词)。
active_reparse_document_ids: set[int]
prefetched_gate_attempts: list[ShippingProcessGateAttempt]
read_cache: dict[str, Any]
@@ -346,12 +349,32 @@ def _conversation_projection_load_context(
str(getattr(intake, 'source_type', '') or '').strip().lower() == 'eml'
for intake in intakes
)
# [STEP] 在途重解析文档集:reparse_pending Case 的后继 Run 仍 queued/processing
# 时系统正在重新识别该文件。EML 聚合叶子据此统一改判 processing,避免 Case
# 被排除后退化成无入口 waiting_human(与摘要 _status 同判词,回归盲窗)。
active_reparse_document_ids: set[int] = set()
reparse_source_run_ids = {
int(case.run_id)
for case in read_cache['current_case_by_document_id'].values()
if case.confirmed_task_id is None
and case.run_id is not None
and str(case.status or '').strip().lower() == 'reparse_pending'
}
if reparse_source_run_ids:
for successor in ShippingOrderProcessingRun.query.filter(
ShippingOrderProcessingRun.reparse_of_run_id.in_(reparse_source_run_ids),
ShippingOrderProcessingRun.status.in_(('queued', 'processing')),
).all():
marker = (successor.input_snapshot_json or {}).get('review_reparse')
if isinstance(marker, dict) and int(marker.get('document_id') or 0) > 0:
active_reparse_document_ids.add(int(marker['document_id']))
return _ConversationProjectionLoadContext(
documents_by_intake_id=documents_by_intake_id,
intakes_by_no={str(intake.intake_no): intake for intake in intakes},
planned_attachments_by_intake_no=(
_frozen_attachment_plan_by_intake(intake_ids) if has_eml_intake else {}
),
active_reparse_document_ids=active_reparse_document_ids,
prefetched_gate_attempts=prefetched_gate_attempts,
read_cache=read_cache,
)
@@ -2721,6 +2744,25 @@ def _eml_aggregate_document_children(
summary['candidate_count'] = int(
has_current_candidate
)
if (
existing is None
and load_context is not None
and int(document.id) in load_context.active_reparse_document_ids
):
# [STEP] 重解析后继 Run 在途:该文档正在重新识别。无 OT 叶子按旧
# Case/Unit 事实会退化成无入口 waiting_human(回归盲窗),这里与摘要
# _status 同判词改判 processing,保留接收解析阶段入口、不下发任何动作。
leaf.update({
'status': 'processing',
'stage': 'document_parsing',
'user_status': 'running',
'user_stage': 'document_parsing',
'user_group': 'processing',
'blocking_reason': None,
'available_actions': [],
'primary_action': None,
'intake_parse_authorized': True,
})
leaf['source_summary'] = summary
# 文件主动作保留 Case / Gate 已裁决的真实动作码。生命周期导航由
# ui_state.lifecycle_entries 单独表达,不能为消除重复而篡改业务动作。
@@ -4053,7 +4095,8 @@ def project_conversation_processing_summary(
绑定的可复核 Candidate;不得用「Case 存在」或「文档上另有未绑定 Candidate」
抬升 candidate_count / waiting_review→order_review。
开放 Case 的用户态须先认活跃 STP Job(queued/running → running),再认草稿
开放 Case 的用户态须先认在途重解析后继 Run(reparse_pending → running),
再认活跃 STP Job(queued/running → running),再认草稿
can_auto_create+can_build 未超时(waiting_to_start → running),与工作台
project_case_user_status 同源;不得仅因 Case 未确认就判 waiting_human。
"""
@@ -4310,6 +4353,39 @@ def project_conversation_processing_summary(
)
}
# [STEP] 开放 Case 的在途重解析探测:reparse_pending Case 的后继 Run
# (reparse_of_run_id 指向源 Run)仍 queued/processing 时,系统正在重新识别
# 该文件。摘要首屏禁止加载 Plan/Unit,故只按谱系列 + 快照标记判定,命中即判
# processing(回归 2026-10-14 批次中心重解析盲窗:五阶段按钮全消 + 冻结待人工)。
active_reparse_by_document_id: dict[int, str] = {}
reparse_source_run_ids = {
int(case.run_id)
for case in current_case_by_document_id.values()
if case.confirmed_task_id is None
and case.run_id is not None
and str(case.status or '').strip().lower() == 'reparse_pending'
}
if reparse_source_run_ids:
for successor in (
ShippingOrderProcessingRun.query.options(load_only(
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.reparse_of_run_id,
ShippingOrderProcessingRun.status,
ShippingOrderProcessingRun.input_snapshot_json,
)).filter(
ShippingOrderProcessingRun.reparse_of_run_id.in_(reparse_source_run_ids),
ShippingOrderProcessingRun.status.in_(('queued', 'processing')),
).order_by(ShippingOrderProcessingRun.id.desc()).all()
):
marker = (successor.input_snapshot_json or {}).get('review_reparse')
if not isinstance(marker, dict):
continue
reparse_document_id = int(marker.get('document_id') or 0)
if reparse_document_id > 0:
active_reparse_by_document_id.setdefault(
reparse_document_id, str(successor.status or ''),
)
# [STEP] 开放 Case 批量预取活跃 STP Job(与 full 会话投影同构前缀),
# 供摘要 _status 在判 waiting_human 前与工作台同源认「系统仍在建单」。
_OPEN_CASE_STATUSES_FOR_STP = {
@@ -4446,6 +4522,10 @@ def project_conversation_processing_summary(
if case is not None and case.confirmed_task_id is None and case_status in _OPEN_CASE_STATUSES_FOR_STP:
# 活跃 STP 或 waiting_to_start = 系统仍在建单;与 project_case_user_status 对齐。
doc_id = int(case.document_id) if case.document_id is not None else int(document.id)
if doc_id in active_reparse_by_document_id:
# 重解析后继 Run 在途(queued/processing):系统正在重新识别本文件,
# 先于 STP/草稿判 running;终态由 finalize_document_reparse 收口改判。
return 'running', 'document_parsing', None
stp_status = active_stp_status_by_document_id.get(doc_id)
if stp_status in {'queued', 'running'}:
mapped = project_case_user_status(case, {'status': stp_status})
@@ -4618,6 +4698,12 @@ def project_conversation_processing_summary(
'variant': 'primary',
'label_key': 'shipping.actions.open_order_review',
}
if int(document.id) in active_reparse_by_document_id:
# 重解析在途:不下发任何动作(服务端幂等复用在途后继),但保留接收解析
# 阶段入口,否则批次中心该行会退化成无五阶段按钮的 waiting_human。
available_actions = []
primary_action = None
intake_parse_authorized = True
leaf = {
'work_item_type': 'order_task',
'work_item_no': f'DOCUMENT:{document.id}',
@@ -0,0 +1,89 @@
"""tt14 入站化:receipt_* 列更名 movement_*、record_kind 值迁移、自然键扩 8 成分
Revision ID: tt14a5f6a7b8c9
Revises: mh15f6a7b8c9
Create Date: 2026-10-15 10:00:00.000000
用途:落实 spec D1/D6——真实 WMS 文件行身份是「单据+行+箱/批」,自然键扩
carton_id+lot_no;receipt 说辞一次性更名(无兼容层)。明细/单据列是方向
中立(出站调拨同样产生明细),按控制器裁决用 movement_*(与异动档
transfer_movement_ledger.movement_date 命名对齐),不用 inbound_*。
依赖:mh15f6a7b8c9 为实施时 flask db heads 显示的实际单 head(并行会话已把
eah8c9d0e1f2 与 tt13d4e5f6a7b8 合并,本迁移链接其后避免双头)。
逻辑:batch_alter_table 完成 RENAME(PG/SQLite 双兼容);record_kind 值迁移为
数据 UPDATE(未上线为空操作,test 环境兜底);唯一约束按 8 成分重建,
进键维度列 carton_id/lot_no 同步 NOT NULL + default ''(R7 终审:nullable
成分的 NULL 不参与唯一比对会逃逸约束;落档链路恒写 '',无存量 NULL)。
列类型取自建表迁移(it1a2b3c4d5e/it2c3d4e5f6a7/tt0d1e2f3a4b)逐一核对。
"""
from alembic import op
import sqlalchemy as sa
revision = "tt14a5f6a7b8c9"
down_revision = "mh15f6a7b8c9"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""receipt_* 列更名 movement_*、record_kind 值迁移 receipt→inbound、自然键扩 8 成分。"""
with op.batch_alter_table("transfer_invoice_items") as batch:
batch.alter_column("receipt_date", new_column_name="movement_date",
existing_type=sa.String(length=16), existing_nullable=True)
batch.alter_column("receipt_quantity", new_column_name="movement_quantity",
existing_type=sa.String(length=40), existing_nullable=False)
batch.alter_column("receipt_warehouse_code", new_column_name="movement_warehouse_code",
existing_type=sa.String(length=64), existing_nullable=False)
with op.batch_alter_table("transfer_documents") as batch:
batch.alter_column("receipt_date", new_column_name="movement_date",
existing_type=sa.String(length=16), existing_nullable=False)
op.execute("UPDATE transfer_movement_ledger SET record_kind='inbound' WHERE record_kind='receipt'")
op.execute("UPDATE transfer_movement_ledger SET record_kind='outbound' WHERE record_kind='shipment'")
with op.batch_alter_table("transfer_movement_ledger") as batch:
# R7(终审修复):carton_id/lot_no 进键即 NOT NULL + default ''——nullable
# 成分在 PG/SQLite 唯一比对中 NULL≠NULL,会逃逸唯一约束(同箱同批塌缩)。
# 落档链路恒写 '',无存量 NULL(未上线),SET NOT NULL 安全。
batch.alter_column("carton_id", existing_type=sa.String(length=64),
nullable=False, server_default='', existing_server_default=None)
batch.alter_column("lot_no", existing_type=sa.String(length=64),
nullable=False, server_default='', existing_server_default=None)
batch.drop_constraint("uq_transfer_movement_ledger_natural_key", type_="unique")
batch.create_unique_constraint(
"uq_transfer_movement_ledger_natural_key",
["source_code", "record_kind", "doc_no", "line_no", "line_seq",
"in_out_flag", "carton_id", "lot_no"],
)
def downgrade() -> None:
"""回滚:自然键收回 6 成分、维度列还原可空无默认、record_kind 值还原、列名还原。
注意:收窄为 6 成分唯一约束时,要求不存在同 6 元组异 carton/lot 并存数据,
否则约束重建 IntegrityError(固有语义,非缺陷——6 成分键本就无法区分同键多箱/批)。
"""
with op.batch_alter_table("transfer_movement_ledger") as batch:
# 对称还原 tt14 upgrade:server_default=None 渲染 DROP DEFAULT(PG),SQLite
# batch 重建表时不携带默认值(alembic 1.19 语义,False=不动、None=移除)。
batch.alter_column("carton_id", existing_type=sa.String(length=64),
nullable=True, server_default=None, existing_server_default='')
batch.alter_column("lot_no", existing_type=sa.String(length=64),
nullable=True, server_default=None, existing_server_default='')
batch.drop_constraint("uq_transfer_movement_ledger_natural_key", type_="unique")
batch.create_unique_constraint(
"uq_transfer_movement_ledger_natural_key",
["source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag"],
)
op.execute("UPDATE transfer_movement_ledger SET record_kind='receipt' WHERE record_kind='inbound'")
op.execute("UPDATE transfer_movement_ledger SET record_kind='shipment' WHERE record_kind='outbound'")
with op.batch_alter_table("transfer_documents") as batch:
batch.alter_column("movement_date", new_column_name="receipt_date",
existing_type=sa.String(length=16), existing_nullable=False)
with op.batch_alter_table("transfer_invoice_items") as batch:
batch.alter_column("movement_date", new_column_name="receipt_date",
existing_type=sa.String(length=16), existing_nullable=True)
batch.alter_column("movement_quantity", new_column_name="receipt_quantity",
existing_type=sa.String(length=40), existing_nullable=False)
batch.alter_column("movement_warehouse_code", new_column_name="receipt_warehouse_code",
existing_type=sa.String(length=64), existing_nullable=False)
@@ -0,0 +1,66 @@
"""tt15 purpose 枚举改版:inventory/movement → onhand/inbound/outbound
Revision ID: tt15b6a7b8c9d0
Revises: tt14a5f6a7b8c9
Create Date: 2026-10-15 12:00:00.000000
用途:通用文件解析规则表 shipping_inventory_parsing_profiles.purpose 由二值
(inventory / movement)扩为方向化三元枚举(onhand / inbound / outbound):
onhand=在手库存文件(原 inventory),inbound=入站收料文件(原 movement),
outbound=出站文件(结构就位,暂无运行时消费方)。
依赖:tt14a5f6a7b8c9 为实施时 flask db heads 显示的实际单 head;purpose 列与旧
CHECK 由 b17e3d4c5a60 / if1b2c3d4e5g 建立。
逻辑:四个操作按序执行——DROP 旧 CHECK → 数据 UPDATE(inventory→onhand、
movement→inbound)→ ADD 新 CHECK → SET DEFAULT 'onhand'。SQLite 不支持裸
ALTER TABLE DROP CONSTRAINT / ALTER COLUMN SET DEFAULT,故 DDL 全部走
batch_alter_table(batch 重建表,SQLite 往返可执行),PG 端渲染等价于裸
ALTER 语句;数据 UPDATE 用 op.execute 独立执行(不进 batch)。
downgrade 对称:outbound 行无 1:1 旧值,迁移到 'movement'(结构就位语义最接近)。
"""
from alembic import op
import sqlalchemy as sa
revision = "tt15b6a7b8c9d0"
down_revision = "tt14a5f6a7b8c9"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""purpose 枚举改版:换 CHECK、迁移存量值、default 置 'onhand'。"""
with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch:
batch.drop_constraint(
"ck_shipping_inventory_parsing_profiles_purpose", type_="check",
)
op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='onhand' WHERE purpose='inventory'")
op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='inbound' WHERE purpose='movement'")
with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch:
batch.create_check_constraint(
"ck_shipping_inventory_parsing_profiles_purpose",
"purpose IN ('onhand', 'inbound', 'outbound')",
)
batch.alter_column(
"purpose", existing_type=sa.String(length=16), existing_nullable=False,
server_default="onhand", existing_server_default="inventory",
)
def downgrade() -> None:
"""回滚:default 还原 'inventory'、换回旧 CHECK,存量值对称还原(outbound→movement)。"""
with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch:
batch.drop_constraint(
"ck_shipping_inventory_parsing_profiles_purpose", type_="check",
)
batch.alter_column(
"purpose", existing_type=sa.String(length=16), existing_nullable=False,
server_default="inventory", existing_server_default="onhand",
)
op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='inventory' WHERE purpose='onhand'")
op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='movement' WHERE purpose IN ('inbound', 'outbound')")
with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch:
batch.create_check_constraint(
"ck_shipping_inventory_parsing_profiles_purpose",
"purpose IN ('inventory', 'movement')",
)
@@ -0,0 +1,62 @@
"""retire not_matured item status (maturity concept removal 2026-10-16)
Revision ID: tt16a7b8c9d0e1f2
Revises: tt15b6a7b8c9d0
Create Date: 2026-10-16
用途:「成熟」概念退役(用户裁定:数据无成熟属性,日期边界由调用方入参严格
给定)——transfer_invoice_items.status 冻结枚举删去 'not_matured'
(13 态 → 12 态),CHECK 约束 ck_transfer_invoice_items_status 同步重建。
数据迁移:存量 not_matured 行重映射为 'cancelled'(语义最近=未进入执行且不再
可执行;D17 占用过滤本就排除 cancelled,占用随之自然释放)。result_code
保留历史值 'not_matured' 不改写(无约束的自由文本,留审计溯源)。
降级:仅重建旧 CHECK(含 not_matured);已重映射的行无法还原原状态(dev 数据,
有损降级,docstring 如实声明)。
依赖:无数据依赖;与 tt14/tt15 并行域迁移同链(单 head 顺序 tt14→tt15→tt16)。
"""
from alembic import op
revision = 'tt16a7b8c9d0e1f2'
down_revision = 'tt15b6a7b8c9d0'
branch_labels = None
depends_on = None
# 12 态枚举(与 app.models.in_transit_transfer.TRANSFER_ITEM_STATUSES 同步;
# 迁移文件不 import 应用模型,避免迁移期模型漂移牵连)。
_ITEM_STATUSES_V12 = (
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
'success', 'duplicate_success', 'blocked_recoverable',
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
)
_ITEM_STATUSES_V13 = ('not_matured',) + _ITEM_STATUSES_V12[:8] + _ITEM_STATUSES_V12[8:]
def _statuses_sql(statuses: tuple[str, ...]) -> str:
return ', '.join(repr(s) for s in statuses)
def upgrade() -> None:
# [STEP 1] 存量 not_matured 行重映射 cancelled(必须先于 CHECK 重建,否则
# 旧值撞新约束);占用释放由 D17 占用过滤排除 cancelled 自然达成。
op.execute(
"UPDATE transfer_invoice_items SET status = 'cancelled' "
"WHERE status = 'not_matured'"
)
# [STEP 2] CHECK 重建:旧约束 → 12 态新约束。
op.drop_constraint('ck_transfer_invoice_items_status', 'transfer_invoice_items', type_='check')
op.create_check_constraint(
'ck_transfer_invoice_items_status',
'transfer_invoice_items',
f"status IN ({_statuses_sql(_ITEM_STATUSES_V12)})",
)
def downgrade() -> None:
# [STEP 1] CHECK 回退到 13 态(已重映射的 cancelled 行无法识别还原,有损降级)。
op.drop_constraint('ck_transfer_invoice_items_status', 'transfer_invoice_items', type_='check')
op.create_check_constraint(
'ck_transfer_invoice_items_status',
'transfer_invoice_items',
f"status IN ({_statuses_sql(_ITEM_STATUSES_V13)})",
)
+265 -35
View File
@@ -1,14 +1,17 @@
"""在途调拨匹配 API 契约测试(L2,Flask test client)。
用途:验证 POST /matchings 创建(含 envelope/权限/参数校验)与
GET /matchings/{id} 进度恢复;无权限 403、未认证 401。
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。
GET /matchings/{id} 进度恢复;无权限 403、未认证 401;
待匹配桶「清空并重新解析」预检/执行端点(spec §6,Task 7)。
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes、factories。
逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或
in_transit_transfer Agent 授权校验。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
@@ -422,18 +425,18 @@ def test_exceptions_excel_download(app, transfer_db, client, admin_headers, tran
assert audit.run_no == run_no
def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
"""下载收料来源文件 → 200(zip),记录访问审计。"""
def test_inbound_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
"""下载出入站来源文件 → 200(zip),记录访问审计。"""
_create_matching(client, admin_headers)
executed = _execute_ready_items(app, client, admin_headers)
run_no = executed.get_json()["data"]["run_no"]
response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers)
response = client.get(f"{API_PREFIX}/runs/{run_no}/inbound-files", headers=admin_headers)
assert response.status_code == 200
assert response.content_type.startswith("application/zip")
with app.app_context():
from app.models import TransferAuditEvent
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED").first()
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_INBOUND_FILES_DOWNLOADED").first()
assert audit is not None
@@ -458,7 +461,7 @@ def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_
_create_matching(client, admin_headers)
executed = _execute_ready_items(app, client, admin_headers)
run_no = executed.get_json()["data"]["run_no"]
for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files",
for path in (f"{API_PREFIX}/runs/{run_no}/inbound-files",
f"{API_PREFIX}/runs/{run_no}/external-inventory",
f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"):
response = client.get(path, headers=unauthorized_headers)
@@ -512,6 +515,118 @@ def test_backlog_forbidden_without_permission(app, transfer_db, client, unauthor
assert response.status_code == 403
def test_backlog_pagination_envelope_and_compat(app, transfer_db, client, admin_headers, transfer_deps):
"""GET /backlog 分页 envelope 与无参兼容:带 page/page_size 回
{items,total,page,page_size},无参保持历史全量数组(向后兼容口径)。"""
_create_matching(client, admin_headers)
with app.app_context():
from app.models import TransferInvoiceItem
item = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
item.status = "blocked_recoverable"
item.result_code = "blocked_quantity_mismatch"
db.session.commit()
# 无参 → 历史数组形状(向后兼容;现有前端/测试依赖不破)。
legacy = client.get(f"{API_PREFIX}/backlog", headers=admin_headers)
assert legacy.status_code == 200
assert isinstance(legacy.get_json()["data"], list)
# 带分页参数 → envelope;单行池:首页 1 行、total=1。
paged = client.get(
f"{API_PREFIX}/backlog?page=1&page_size=1&result_filter=recoverable",
headers=admin_headers,
)
assert paged.status_code == 200
data = paged.get_json()["data"]
assert set(data.keys()) == {"items", "total", "page", "page_size"}
assert len(data["items"]) == 1 and data["items"][0]["invoice_no"] == "HOM-001"
assert data["total"] == 1 and data["page"] == 1 and data["page_size"] == 1
# 越界页:offset 超出 total → 空切片(分页推进语义)。
page2 = client.get(
f"{API_PREFIX}/backlog?page=2&page_size=1&result_filter=recoverable",
headers=admin_headers,
).get_json()["data"]
assert page2["items"] == [] and page2["total"] == 1
def test_backlog_result_filter_and_keyword_pushdown(app, transfer_db, client, admin_headers, transfer_deps):
"""GET /backlog 筛选下推:result_filter 白名单切片、keyword 跨四字段子串、
白名单外 400(fail-closed)。"""
_create_matching(client, admin_headers)
with app.app_context():
from app.models import TransferInvoiceItem
first = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
first.status = "blocked_recoverable"
first.result_code = "blocked_quantity_mismatch"
# 第二种池内状态:把可执行行翻成人工关闭(进池、落 closed 切片)。
second = TransferInvoiceItem.query.filter_by(invoice_no="HOX-002").first()
second.status = "manually_closed"
second.result_message = "线下处理"
db.session.commit()
recoverable = client.get(
f"{API_PREFIX}/backlog?page=1&page_size=50&result_filter=recoverable",
headers=admin_headers,
).get_json()["data"]
assert {entry["invoice_no"] for entry in recoverable["items"]} == {"HOM-001"}
assert recoverable["total"] == 1
closed = client.get(
f"{API_PREFIX}/backlog?page=1&page_size=50&result_filter=closed",
headers=admin_headers,
).get_json()["data"]
assert {entry["invoice_no"] for entry in closed["items"]} == {"HOX-002"}
keyword = client.get(
f"{API_PREFIX}/backlog?page=1&page_size=50&keyword=HOX-002",
headers=admin_headers,
).get_json()["data"]
assert {entry["invoice_no"] for entry in keyword["items"]} == {"HOX-002"}
invalid = client.get(
f"{API_PREFIX}/backlog?page=1&result_filter=bogus",
headers=admin_headers,
)
assert invalid.status_code == 400
def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client, admin_headers, monkeypatch):
"""GET /backlog/pending-match 分页 envelope 与无参兼容:带参回
{records,total,page,page_size},无参保持历史数组(圈档伪造 25 行验证切片)。"""
from types import SimpleNamespace
rows = [
SimpleNamespace(
ledger_record_id=None, id=i + 1, doc_no=f"HOM-{900 + i}",
material_code=f"MAT-{i}", material_name="未匹配物料",
movement_date="2026-08-05", source_code="DBS-AWSBI", quantity="1",
)
for i in range(25)
]
monkeypatch.setattr(
"app.services.in_transit_transfer.backlog_service.circle_ledger_records_scope_union",
lambda: rows,
)
legacy = client.get(f"{API_PREFIX}/backlog/pending-match", headers=admin_headers)
assert legacy.status_code == 200
assert isinstance(legacy.get_json()["data"], list)
assert len(legacy.get_json()["data"]) == 25
paged = client.get(
f"{API_PREFIX}/backlog/pending-match?page=2&page_size=20",
headers=admin_headers,
)
assert paged.status_code == 200
data = paged.get_json()["data"]
assert set(data.keys()) == {"records", "total", "page", "page_size"}
assert len(data["records"]) == 5 # 25 行第 2 页余量
assert data["total"] == 25 and data["page"] == 2 and data["page_size"] == 20
assert data["records"][0]["doc_no"] == "HOM-920" # 第 21 行(稳定排序切片)
def test_list_transfer_sources(app, client, admin_headers):
"""来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。"""
response = client.get(f"{API_PREFIX}/sources", headers=admin_headers)
@@ -537,7 +652,7 @@ def test_list_transfer_sources_forbidden(app, client, unauthorized_headers):
# 两条路径均不触发 RPA、不返回 202/fetching)
# ---------------------------------------------------------------------------
def _seed_parse_failed_receipt_file(source_code: str):
def _seed_parse_failed_inbound_file(source_code: str):
"""造一条「当日可用但解析失败」的收料归档文件(success 单元 + parse_failed 三列)。
与 tests/services/in_transit_transfer/test_source_file_status.py 同款最小造数:
@@ -579,13 +694,13 @@ def _seed_parse_failed_receipt_file(source_code: str):
def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_headers, monkeypatch):
"""parse_failed 且有可用文件 → retry 先本地重解析(sync),不触发 RPA(200 非 202)。"""
called = {"sync": 0, "rpa": 0}
_seed_parse_failed_receipt_file("DSV360_AWSDU")
_seed_parse_failed_inbound_file("DSV360_AWSDU")
def fake_sync(*, source_code, business_date, now):
# 断言意图:重解析路径 sync 恰好 1 次;成功链路清除解析失败标记使投影回
# ready(请求会话内重查后清除并 commit,保证端点再解析可见)。
from app.models import ShippingReceiptReportFile
from app.services.in_transit_transfer.source_file_status import clear_receipt_parse_failure
from app.services.in_transit_transfer.source_file_status import clear_inbound_parse_failure
called["sync"] += 1
file = (
@@ -595,7 +710,7 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header
.first()
)
if file is not None:
clear_receipt_parse_failure(report=file)
clear_inbound_parse_failure(report=file)
db.session.commit()
return True
@@ -604,7 +719,7 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header
fake_sync,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa",
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa",
lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"},
)
response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers)
@@ -623,7 +738,7 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header
def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_headers, monkeypatch):
"""sync 返回 True 但投影仍 parse_failed → ok=False(不触发 RPA、不回 202)。"""
called = {"sync": 0, "rpa": 0}
_seed_parse_failed_receipt_file("DSV360_AWSDU")
_seed_parse_failed_inbound_file("DSV360_AWSDU")
def fake_sync(*, source_code, business_date, now):
# 断言意图:sync 返回 True 不代表投影恢复——标记未清除时端点必须如实报
@@ -636,7 +751,7 @@ def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_h
fake_sync,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa",
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa",
lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"},
)
response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers)
@@ -660,7 +775,7 @@ def test_retry_rpa_batch_requires_source_codes(app, client, admin_headers):
def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_headers, monkeypatch):
"""批量端点把 source_codes 原样交给 trigger_receipt_rpa_batch 并回传结果 envelope。"""
"""批量端点把 source_codes 原样交给 trigger_inbound_rpa_batch 并回传结果 envelope。"""
captured: dict = {}
def fake_batch(*, source_codes, business_date, reason):
@@ -671,7 +786,7 @@ def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_h
}
monkeypatch.setattr(
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa_batch", fake_batch,
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch", fake_batch,
)
response = client.post(
f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers,
@@ -681,7 +796,7 @@ def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_h
body = response.get_json()["data"]
# [断言意图] 端点只做参数卡控与转发:来源列表原样下传、reason 固定业务语义。
assert captured["source_codes"] == ["DSV360_AWSDU", "DSV360_AWSSG"]
assert captured["reason"] == "transfer_retry_receipt"
assert captured["reason"] == "transfer_retry_inbound"
assert body["ok"] is True and body["triggered"] is True
assert [item["source_code"] for item in body["results"]] == ["DSV360_AWSDU", "DSV360_AWSSG"]
@@ -833,7 +948,7 @@ def test_retrigger_endpoint_requires_authentication(client):
# T11:202 契约收口 + GET /runs/{run_no} 调拨单清单(orders)投影(D9 融合卡数据源)
# ---------------------------------------------------------------------------
def _receipt_row(row_no: int, doc_no: str, lot_no: str, material: str,
def _movement_row(row_no: int, doc_no: str, lot_no: str, material: str,
movement_date: str, quantity: str, *, unit: str = "PCS",
material_name: str | None = None) -> dict:
"""构造一条收料文件行(movement 字段键;多单场景自定义行集用)。"""
@@ -853,7 +968,7 @@ def _custom_transfer_deps(monkeypatch, rows: list[dict], stocks: list[tuple[str,
"""
file_payload = {
"source_code": "DBS-AWSBI", "business_date": "2026-08-06",
"file_purpose": "receipt", "file_no": "REC-T11", "file_version": "v11",
"file_purpose": "inbound", "file_no": "REC-T11", "file_version": "v11",
"checksum": "d" * 64, "status": "ready", "rows": rows,
}
deps, erp, _ = make_transfer_deps(file_payload)
@@ -913,9 +1028,9 @@ def test_run_projection_returns_order_list_with_multi_status(
monkeypatch,
rows=[
# 三张单:收料日期入 D1 组键 → 三个组各一单(组建单按组键升序)。
_receipt_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_receipt_row(2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"),
_receipt_row(3, "HOX-C", "LOT-30", "MAT-003", "2026-08-03", "300.25", unit="KG"),
_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_movement_row(2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"),
_movement_row(3, "HOX-C", "LOT-30", "MAT-003", "2026-08-03", "300.25", unit="KG"),
],
stocks=[("MAT-001", "LOT-10", "500"), ("MAT-002", "LOT-20", "700"),
("MAT-003", "LOT-30", "300.25")],
@@ -937,7 +1052,7 @@ def test_run_projection_returns_order_list_with_multi_status(
assert len(orders) == 3
# 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位;本例同数据源,
# 收料日期升序,与建单的组键序一致)。
assert [t["receipt_date"] for t in orders] == ["2026-08-03", "2026-08-04", "2026-08-05"]
assert [t["movement_date"] for t in orders] == ["2026-08-03", "2026-08-04", "2026-08-05"]
by_status = {t["status"]: t for t in orders}
assert set(by_status) == {"success", "business_failed", "result_unknown"}
@@ -947,11 +1062,11 @@ def test_run_projection_returns_order_list_with_multi_status(
# (+invoice_no:行级溯源收料通知号 2026-09-29 契约扩充;含 reason:框线图
# 失败行原因展示契约,控制器裁决扩充,T13-3)。
assert set(success.keys()) == {
"doc_no", "receipt_date", "from_warehouse", "to_warehouse",
"doc_no", "movement_date", "from_warehouse", "to_warehouse",
"status", "erp_document_no", "error_message", "lines",
}
assert success["doc_no"].startswith("HX-CN01-OR-")
assert success["receipt_date"] == "2026-08-05"
assert success["movement_date"] == "2026-08-05"
assert success["from_warehouse"] == "DBS-TRANSIT"
assert success["to_warehouse"] == "HUB-CN01"
assert success["erp_document_no"]
@@ -997,7 +1112,7 @@ def test_run_projection_order_lines_include_reused_order_old_and_new_rows(
"""复用单行集全量投影:失败单复用后,旧行与新行都在 orders.lines(D7①②)。"""
deps, erp = _custom_transfer_deps(
monkeypatch,
rows=[_receipt_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个")],
rows=[_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个")],
stocks=[("MAT-001", "LOT-10", "500")],
)
erp.write_scenarios["HOM-A"] = "business_failed"
@@ -1014,8 +1129,8 @@ def test_run_projection_order_lines_include_reused_order_old_and_new_rows(
_custom_transfer_deps(
monkeypatch,
rows=[
_receipt_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_receipt_row(3, "HOM-C", "LOT-30", "MAT-003", "2026-08-05", "300", unit="PCS"),
_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_movement_row(3, "HOM-C", "LOT-30", "MAT-003", "2026-08-05", "300", unit="PCS"),
],
stocks=[("MAT-001", "LOT-10", "500"), ("MAT-003", "LOT-30", "300")],
)
@@ -1072,7 +1187,7 @@ def _seed_document(
five = {key: (group or {}).get(key) or default for key, default in (
("source_code", "DBS-AWSBI"),
("external_org", "ORGA"),
("receipt_date", "2026-08-05"),
("movement_date", "2026-08-05"),
("from_warehouse", "DBS-TRANSIT"),
("to_warehouse", f"HUB-{doc_no}"),
)}
@@ -1096,10 +1211,10 @@ def _seed_document(
material_no=spec.get("material_no", f"MAT-{index}"),
material_name=spec.get("material_name", f"物料{index}"),
lot_no=spec.get("lot_no", "LOT-1"),
receipt_date=five["receipt_date"],
movement_date=five["movement_date"],
from_warehouse=five["from_warehouse"],
to_warehouse=five["to_warehouse"],
receipt_quantity=spec.get("quantity", "10"),
movement_quantity=spec.get("quantity", "10"),
unit=spec.get("unit", "PCS"),
status=spec.get("status", "executing"),
result_code=spec.get("result_code"),
@@ -1195,7 +1310,7 @@ def test_list_documents_order_projection_and_items(app, transfer_db, client, adm
assert data["total"] == 1
order = data["orders"][0]
# 断言意图:计划 Task 17 响应契约逐键——单头字段 + items(invoice 粒度)。
for key in ("doc_no", "submit_timestamp", "status", "status_group", "receipt_date",
for key in ("doc_no", "submit_timestamp", "status", "status_group", "movement_date",
"from_warehouse", "to_warehouse", "erp_document_no", "error_message",
"created_at", "items"):
assert key in order
@@ -1262,10 +1377,10 @@ def test_list_documents_date_range_filters_list_only(app, transfer_db, client, a
with app.app_context():
now = datetime(2026, 9, 24, 10, 0, 0)
_seed_document(transfer_db, docs_matching, "D-OLD-1", "2026-08-06 09:00:00", "business_failed",
group={"receipt_date": "2026-08-25"},
group={"movement_date": "2026-08-25"},
created_at=now - timedelta(days=30))
_seed_document(transfer_db, docs_matching, "D-NEW-1", "2026-08-06 10:00:00", "business_failed",
group={"receipt_date": "2026-09-23"},
group={"movement_date": "2026-09-23"},
created_at=now - timedelta(days=1))
transfer_db.session.commit()
@@ -1310,7 +1425,7 @@ def test_close_document_detaches_items_and_releases_group_lock(
from app.models import TransferAuditEvent, TransferDocument, TransferInvoiceItem
group = {
"source_code": "DBS-AWSBI", "external_org": "ORGA", "receipt_date": "2026-08-05",
"source_code": "DBS-AWSBI", "external_org": "ORGA", "movement_date": "2026-08-05",
"from_warehouse": "DBS-TRANSIT", "to_warehouse": "HUB-CN01",
}
with app.app_context():
@@ -1449,3 +1564,118 @@ def test_document_run_no_projection_and_audit_with_real_run(
event = TransferAuditEvent.query.filter_by(event_type="TRANSFER_DOCUMENT_CLOSED").one()
assert event.aggregate_id == "D-RUN-1"
assert event.run_no == "RUN-DOC-REAL-1"
# ---------------------------------------------------------------------------
# 待匹配桶「清空并重新解析」(spec §6,Task 7):预检 + 执行端点
# ---------------------------------------------------------------------------
REPARSE_SOURCE = "CRANE_API"
REPARSE_OLD_SHA = "9" * 64
REPARSE_SHA_A = "a1" + "0" * 62
def _seed_reparse_endpoint_world(app, monkeypatch):
"""端点用例种子:来源+已发布入站规则+一份可用归档+一条旧映射档行。
归档字节经 FakeArchiveStorage 注入并替换 file_asset_storage.get_bytes
(单例对象级替换,service/repository 引用同源生效)。
Returns:
(archive_file, fake_storage) 元组。
"""
from tests.services.in_transit_transfer import factories
fake = factories.FakeArchiveStorage()
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
source, _profile = factories.seed_inbound_reparse_source(REPARSE_SOURCE)
archive = factories.seed_reparse_archive_file(
source, sha=REPARSE_SHA_A, storage_key=f"archive/{REPARSE_SOURCE}/a.xlsx",
created_at=datetime(2026, 10, 10, 8, 0, 0))
fake.objects[f"archive/{REPARSE_SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-P1", "1", "I", "MAT-P1", "连接器", "LOT-P1", 500, "2026-08-05"],
])
with app.app_context():
factories.seed_reparse_ledger_row(
REPARSE_SOURCE, "ASN-P1", source_file_id=archive.id, sha=REPARSE_OLD_SHA)
return archive, fake
def test_pending_match_reparse_preview_endpoint(app, transfer_db, client, admin_headers, monkeypatch):
"""GET /backlog/pending-match/reparse-preview → 200 envelope,预检四键形状。"""
_archive, _fake = _seed_reparse_endpoint_world(app, monkeypatch)
response = client.get(
f"{API_PREFIX}/backlog/pending-match/reparse-preview?source_code={REPARSE_SOURCE}",
headers=admin_headers,
)
assert response.status_code == 200
body = response.get_json()
assert body["success"] is True and body.get("request_id")
data = body["data"]
assert set(data.keys()) == {"files", "profile", "clearable_rows", "kept_rows"}
assert data["profile"]["version"] == 1 and data["profile"]["code"]
assert data["clearable_rows"] == 1 and data["kept_rows"] == 0
assert data["files"][0]["sha256"] == REPARSE_SHA_A
assert data["files"][0]["rows"] == 1
def test_pending_match_reparse_preview_requires_source_code(app, client, admin_headers):
"""缺 source_code → 400(参数校验,envelope error)。"""
response = client.get(
f"{API_PREFIX}/backlog/pending-match/reparse-preview", headers=admin_headers)
assert response.status_code == 400
def test_pending_match_reparse_endpoint_executes_and_audits(app, transfer_db, client, admin_headers, monkeypatch):
"""POST /backlog/pending-match/reparse → 200 envelope,清空重落计数 + 审计事件。"""
from app.models import TransferAuditEvent, TransferMovementLedger
archive, _fake = _seed_reparse_endpoint_world(app, monkeypatch)
response = client.post(
f"{API_PREFIX}/backlog/pending-match/reparse", headers=admin_headers,
json={"source_code": REPARSE_SOURCE},
)
assert response.status_code == 200
body = response.get_json()
assert body["success"] is True
data = body["data"]
assert (data["cleared"], data["reinserted"]) == (1, 1)
assert data["kept_unrebuildable"] == 0
assert data["collapses"] == 0 # [断言意图] 坍缩计数随端点透出(无坍缩=0)
assert data["files"][0]["sha256"] == REPARSE_SHA_A
with app.app_context():
transfer_db.session.expire_all()
row = TransferMovementLedger.query.filter_by(
source_code=REPARSE_SOURCE, doc_no="ASN-P1").one()
# [断言意图] 新映射值随执行生效且溯源换新(真实 source_file_id/sha256)。
assert row.quantity == "500" and row.file_sha256 == REPARSE_SHA_A
assert row.source_file_id == archive.id
event = TransferAuditEvent.query.filter_by(
event_type="TRANSFER_PENDING_MATCH_REPARSED").one()
assert event.aggregate_id == REPARSE_SOURCE
assert event.after_json["operator"] == "admin"
assert event.after_json["cleared"] == 1 and event.after_json["reinserted"] == 1
def test_pending_match_reparse_requires_authentication(client):
"""未认证:预检/执行均 401(envelope error)。"""
preview = client.get(f"{API_PREFIX}/backlog/pending-match/reparse-preview?source_code=X")
execute = client.post(f"{API_PREFIX}/backlog/pending-match/reparse", json={"source_code": "X"})
assert preview.status_code == 401
assert execute.status_code == 401
def test_pending_match_reparse_forbidden_without_permission(app, client, unauthorized_headers):
"""无 in_transit_transfer Agent 权限:预检/执行均 403(越权检查)。"""
preview = client.get(
f"{API_PREFIX}/backlog/pending-match/reparse-preview?source_code=X",
headers=unauthorized_headers)
execute = client.post(
f"{API_PREFIX}/backlog/pending-match/reparse", headers=unauthorized_headers,
json={"source_code": "X"})
assert preview.status_code == 403
assert execute.status_code == 403
+5 -5
View File
@@ -695,7 +695,7 @@ def dbs_ready_file() -> dict:
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-001",
"file_version": "v3",
"checksum": "d" * 64,
@@ -723,7 +723,7 @@ def crane_ready_file() -> dict:
return {
"source_code": "CRANE-SZ",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-002",
"file_version": "v4",
"checksum": "c" * 64,
@@ -737,15 +737,15 @@ def crane_ready_file() -> dict:
@pytest.fixture
def same_day_receipt_file() -> dict:
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。
def same_day_inbound_file() -> dict:
"""含业务日期当天异动数据的文件(成熟规则已退役:当天数据正常进匹配)。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
"""
return {
"source_code": "DBS-AWSSG",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-003",
"file_version": "v2",
"checksum": "s" * 64,
+3 -3
View File
@@ -23,12 +23,12 @@ from app.services.schedule.queue_service import (
def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycle(app, monkeypatch):
"""关键断言:调拨来源等待回调 Job 的超时回收每轮领取都执行,不只在 worker 启动时扫一次。
[STEP 1] 用计数桩替换 receipt_callback_bridge.recover_stale_waiting_source_jobs(queue_service
[STEP 1] 用计数桩替换 inbound_callback_bridge.recover_stale_waiting_source_jobs(queue_service
在函数体内延迟 import,桩生效)并复位 _worker_initialized,隔离模块级启动标记。
[STEP 2] 连续两轮调用真实 prepare_schedule_queue(空库下其余恢复均为 no-op)。
[STEP 3] 第二轮后计数必须为 2:若回收仍挂在启动一次性分支,第二次调用不会触发,计数停留 1。
"""
from app.services.in_transit_transfer import receipt_callback_bridge
from app.services.in_transit_transfer import inbound_callback_bridge
from app.services.schedule import queue_service
from app.services.shipping_notice import rpa_worker_heartbeat_alert
@@ -41,7 +41,7 @@ def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycl
def _fake_heartbeat(**_kwargs):
return {"skipped": True, "reason": "test_stub"}
monkeypatch.setattr(receipt_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
monkeypatch.setattr(inbound_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
monkeypatch.setattr(rpa_worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
monkeypatch.setattr(queue_service, "_worker_initialized", False)
@@ -1,8 +1,8 @@
"""在途调拨测试固定夹具:时钟、收料文件样例、外部替身与数据库隔离。
"""在途调拨测试固定夹具:时钟、入站文件样例、外部替身与数据库隔离。
用途:为 tests/services/in_transit_transfer 提供与 TDD 文档一致的固定输入
(fixed_clock 默认 2026-08-06 09:00:00+08:00、dbs/crane ready 文件、
same_day_receipt_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。
same_day_inbound_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。
依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。
逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB;
请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。
@@ -34,22 +34,6 @@ def _stub_doc_sequence(monkeypatch):
)
@pytest.fixture(autouse=True)
def _pin_maturity_lag_legacy(request):
"""在途套件钉成熟滞后=1(T+1)。
用途:存量夹具生态按 T+1 语义构建(fixed_clock 业务日 2026-08-06、收料日期
2026-08-05=T-1);生产默认 T+2(settings IN_TRANSIT_TRANSFER_MATURITY_
LAG_DAYS=2)的边界行为由 test_matching_service / test_date_policy 专项
用例显式覆盖,不被本钉值掩盖。
逻辑:仅对已请求 app 的用例钉值(request.fixturenames 判定),pure_unit 用例
(如 test_date_policy)不触碰 Flask,继续走 date_policy 的无上下文回退。
"""
if "app" in getattr(request, "fixturenames", []):
app = request.getfixturevalue("app")
app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 1
@pytest.fixture(autouse=True)
def _seed_default_transfer_type(request):
"""默认启用类型配置种子(autouse,出生翻转后匹配创建必填且配置驱动)。
@@ -1,67 +1,16 @@
"""在途调拨领域测试的对象工厂。
用途:集中构造合法 Invoice / 文件行 / 预检 DTO,避免各测试重复内联样板。
依赖:标准库(dataclasses / decimal)。
用途:集中构造调拨类型配置种子与「清空并重新解析」(spec §6)用例种子
(来源+入站解析规则+归档文件+档行),避免各测试重复内联样板。
依赖:标准库(datetime)、openpyxl(内存 xlsx 构造)。
逻辑:工厂只生成业务合法的默认值;测试用 override 注入变体。
归档文件字节不落真存储:用例经 FakeArchiveStorage 注入并 monkeypatch
file_asset_storage.get_bytes。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any
@dataclass(frozen=True)
class ReceiptRow:
"""单行收料文件记录(含 Sheet/行号追溯证据)。"""
sheet: str = "Receipt"
row_no: int = 1
invoice_no: str = "HOM-001"
material_no: str = "MAT-001"
material_name: str = "连接器组件"
specification: str = "A 型 / 24PIN"
receipt_date: str = "2026-08-05"
receipt_quantity: str = "1200"
source_code: str = "DBS-AWSBI"
def to_dict(self) -> dict[str, Any]:
"""转 dict,供 parser/aggregator 输入。"""
return {
"sheet": self.sheet,
"row_no": self.row_no,
"invoice_no": self.invoice_no,
"material_no": self.material_no,
"material_name": self.material_name,
"specification": self.specification,
"receipt_date": self.receipt_date,
"receipt_quantity": self.receipt_quantity,
"source_code": self.source_code,
}
def make_invoice_item(
*,
invoice_no: str = "HOM-001",
source_code: str = "DBS-AWSBI",
material_no: str = "MAT-001",
receipt_quantity: Decimal | str | int = "1200",
external_quantity: Decimal | str | int | None = "1200",
receipt_date: str = "2026-08-05",
) -> dict[str, Any]:
"""构造一条预检明细项(默认严格匹配、可执行)。"""
return {
"invoice_no": invoice_no,
"source_code": source_code,
"material_no": material_no,
"material_name": "连接器组件",
"specification": "A 型 / 24PIN",
"receipt_date": receipt_date,
"receipt_quantity": Decimal(str(receipt_quantity)),
"external_quantity": None if external_quantity is None else Decimal(str(external_quantity)),
}
from datetime import datetime
# ---------------------------------------------------------------------------
# 调拨类型配置种子(出生翻转后匹配创建必填且配置驱动,Task 11)
@@ -114,3 +63,215 @@ def seed_transfer_type_config(
db.session.add(row)
db.session.commit()
return row
# ---------------------------------------------------------------------------
# 清空并重新解析(spec §6,Task 7)用例种子
# ---------------------------------------------------------------------------
# 入站解析规则缺省 field_mapping(movement 定死领域字段 → 表头别名,CRANE 风格)。
INBOUND_MOVEMENT_FIELD_MAPPING = {
"doc_no": "单据编号",
"line_no": "项次",
"in_out_flag": "进出库别",
"material_code": "料号",
"material_name": "品名",
"lot_no": "批号",
"quantity": "数量",
"movement_date": "异动日期",
}
# 与 INBOUND_MOVEMENT_FIELD_MAPPING 对齐的 xlsx 表头行(build_movement_xlsx 缺省表头)。
INBOUND_MOVEMENT_HEADERS = ["单据编号", "项次", "进出库别", "料号", "品名", "批号", "数量", "异动日期"]
def build_movement_xlsx(data_rows: list[list], *, sheet_name: str = "Receipt",
headers: list[str] | None = None) -> bytes:
"""构造内存 xlsx 字节(表头 + 数据行),供归档假存储注入。
Args:
data_rows: 数据行(列序与 headers 一致;数量 int、日期 str)。
sheet_name: 工作表标题(溯源 sheet 字段来源)。
headers: 表头行;缺省 INBOUND_MOVEMENT_HEADERS。
Returns:
xlsx 原始字节。
"""
from io import BytesIO
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = sheet_name
ws.append(list(headers if headers is not None else INBOUND_MOVEMENT_HEADERS))
for row in data_rows:
ws.append(list(row))
buf = BytesIO()
wb.save(buf)
return buf.getvalue()
class FakeArchiveStorage:
"""file_asset_storage 内存假件(storage_key → bytes),按 repo_fakes 风格最小实现。"""
def __init__(self, objects: dict[str, bytes] | None = None) -> None:
self.objects: dict[str, bytes] = dict(objects or {})
def get_bytes(self, storage_key: str) -> bytes:
"""读取注入对象;缺失键抛 KeyError(用例内即失败,不静默)。"""
return self.objects[storage_key]
def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None = None,
version: int = 1, field_mapping: dict | None = None,
sheet_name: str = "Receipt", header_row_index: int = 1,
status: str = "published"):
"""建「启用来源 + 已发布 inbound 解析规则 + 收料配置绑定」全套种子(幂等)。
用途:清空并重新解析(spec §6)服务/端点用例的来源侧种子;来源自身
parsing_profile(在手口径)按约束置最小占位行,真实重建规则挂
ShippingReceiptReportConfig.parsing_profile_id(与运行期口径一致)。
Args:
source_code: 来源实例编码。
profile_code: 入站解析规则 code(缺省 MV_<source_code>)。
version: 入站解析规则版本。
field_mapping: 领域字段→表头别名;缺省 INBOUND_MOVEMENT_FIELD_MAPPING。
sheet_name / header_row_index: definition_json 结构参数。
status: 入站规则状态(缺省 published;用例可注入 draft 验证 abort)。
Returns:
(ShippingInventorySource, ShippingInventoryParsingProfile) 元组。
"""
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingRpaProfile,
ShippingReceiptReportConfig,
)
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
if source is not None:
config = source.receipt_report_config
return source, (config.parsing_profile if config else None)
resolved_code = profile_code or f"MV_{source_code}"
onhand = ShippingInventoryParsingProfile(
purpose="onhand", profile_code=f"ONHAND_{source_code}", display_name=source_code,
version=1, status="published", file_format="xlsx",
definition_json={}, structure_definition_json={},
)
profile = ShippingInventoryParsingProfile(
purpose="inbound", profile_code=resolved_code, display_name=resolved_code,
version=version, status=status, file_format="xlsx",
definition_json={
"sheet_name": sheet_name, "header_row_index": header_row_index,
"field_mapping": dict(
INBOUND_MOVEMENT_FIELD_MAPPING if field_mapping is None else field_mapping),
},
structure_definition_json={},
)
rpa = ShippingRpaProfile(
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="dbs",
login_url="https://test.invalid/dbs", login_config_json={"auth_mode": "password"},
)
template = ShippingExcelTemplate(
template_code=f"TPL_{source_code}", display_name=source_code, version=1,
status="published", storage_provider="minio", storage_bucket="test",
storage_key=f"test/{source_code}/template.xlsx", original_filename="template.xlsx",
file_checksum="0" * 64, definition_json={}, definition_checksum="0" * 64,
)
source = ShippingInventorySource(
source_code=source_code, display_name=source_code, connector_type="dbs",
rpa_profile=rpa, parsing_profile=onhand, excel_template=template,
warehouse_resolution_mode="fixed", fixed_warehouse_id="AWSDU", enabled=True,
)
db.session.add_all([onhand, profile, rpa, template, source])
db.session.flush()
db.session.add(ShippingReceiptReportConfig(
inventory_source_id=source.id, parsing_profile_id=profile.id))
db.session.commit()
return source, profile
def seed_reparse_archive_file(source, *, sha: str, storage_key: str, created_at: datetime,
archive_expires_at: datetime | None = None,
archive_deleted_at: datetime | None = None,
callback_id: str | None = None):
"""建一条收料执行单元 + 原样归档文件行(清空重建用例种子)。
字节不落真存储:用例把 build_movement_xlsx 产物注入 FakeArchiveStorage
(键=storage_key)并 monkeypatch file_asset_storage.get_bytes。
Args:
source: seed_inbound_reparse_source 返回的来源行。
sha: 归档文件 sha256(唯一约束 unit_run+sha,用例间取不同值)。
storage_key: 对象存储键(与假存储注入键一致)。
created_at: 归档时间(= repository 的 archived_at,排序依据)。
archive_expires_at: 保留期截止;None=长期有效。
archive_deleted_at: 清理时间;None=未清理。
callback_id: 收料执行单元回调键(缺省按 sha 派生保证唯一)。
Returns:
已入库的 ShippingReceiptReportFile。
"""
from app import db
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type,
callback_id=callback_id or f"cb-{sha[:12]}",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = ShippingReceiptReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=storage_key, original_filename=f"{callback_id or 'cb'}.xlsx",
file_size=16, sha256=sha, created_at=created_at,
archive_expires_at=archive_expires_at, archive_deleted_at=archive_deleted_at,
)
db.session.add(report)
db.session.commit()
return report
def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1",
in_out_flag: str = "I", lot_no: str = "LOT-1",
source_file_id: int | None = None,
sha: str = "9" * 64, quantity: str = "1",
material_code: str = "MAT-OLD", material_name: str = "旧映射名称",
movement_date: str = "2026-08-05",
transfer_executed: bool = False,
executed_doc_no: str | None = None,
updated_at: datetime | None = None):
"""插一条旧映射库存异动档行(清空重建用例种子;业务值=旧映射形态)。
Args:
source_code / doc_no: 来源与单号(自然键主干)。
line_no / in_out_flag / lot_no: 自然键可变成分(与解析行对齐便于断言覆写)。
source_file_id: 溯源归档文件 id;None=证据缺失行形态。
sha: 档行 file_sha256(缺省 9*64 表示旧文件指纹)。
quantity / material_code / material_name / movement_date: 旧业务值。
transfer_executed / executed_doc_no: 封存形态注入。
updated_at: 显式更新时间(封存不动行断言用)。
Returns:
已入库的 TransferMovementLedger。
"""
from app import db
from app.models import TransferMovementLedger
row = TransferMovementLedger(
source_code=source_code, record_kind="inbound",
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,
quantity=quantity, movement_date=movement_date,
source_file_id=source_file_id, file_version=None, file_sha256=sha,
transfer_executed=transfer_executed, executed_doc_no=executed_doc_no,
updated_at=updated_at or datetime(2026, 10, 1, 8, 0, 0),
)
db.session.add(row)
db.session.commit()
return row
@@ -285,7 +285,7 @@ class FakeRPA:
})
if source_code in self.fail_on:
return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
return {"ok": True, "callback_id": f"inbound:{source_code}:{business_date}"}
class FakeWeCom:
@@ -1,7 +1,7 @@
"""在途调拨测试的仓库/路由/依赖替身。
用途:为 file_preparation / matching_service / API / Job 测试提供可注入的
ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps;
InboundFileRepository、RouteResolver 与组装好的 TransferDeps;
并提供 seed_rows_from_file 迁移桥(2026-09-25 起匹配不解析文件,
行须经 evidence_sync 落地)。
依赖:app.services.in_transit_transfer(仅类型)、fakes。
@@ -13,15 +13,15 @@ from __future__ import annotations
from datetime import datetime
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
from app.services.in_transit_transfer.matching_service import RouteMapping, TransferDeps
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA
class FakeReceiptFileRepository:
class FakeInboundFileRepository:
"""按 (source_code, business_date) 返回可注入 ready 文件。"""
def __init__(self, files: dict[tuple[str, str], ReadyReceiptFile] | None = None) -> None:
def __init__(self, files: dict[tuple[str, str], ReadyInboundFile] | None = None) -> None:
self.files = files or {}
self.lookups: list[tuple[str, str]] = []
# 一次性覆盖:下一次 latest_ready_file 对该来源返回此文件(用后即弃,
@@ -34,7 +34,7 @@ class FakeReceiptFileRepository:
Args:
source_code: 来源实例编码(覆盖该来源的下一次查询)。
rows: 文件原始行集(透传为 ReadyReceiptFile.rows)。
rows: 文件原始行集(透传为 ReadyInboundFile.rows)。
checksum: 文件 sha256 版本戳。
file_version: 文件版本号(缺省 "override")。
"""
@@ -42,12 +42,12 @@ class FakeReceiptFileRepository:
"rows": tuple(rows), "checksum": checksum, "file_version": file_version,
}
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
"""记录查询并返回匹配文件;有一次性覆盖时优先返回并消费之。"""
self.lookups.append((source_code, business_date))
override = self._next_files.pop(source_code, None)
if override is not None:
return ReadyReceiptFile(
return ReadyInboundFile(
source_code=source_code,
business_date=business_date,
file_no=f"REC-OVERRIDE-{source_code}",
@@ -64,7 +64,7 @@ def seed_rows_from_file(source_code: str, deps: TransferDeps, business_date: str
【2026-09-25】匹配不再解析文件(行由 evidence_sync 落地);凡旧用例
「文件夹具直接进 run_matching/create_matching」的,须先经本助手把文件行
落成待查行(status='matching' + result_code='pending_stock_check'),
再进入匹配管道(成熟过滤→查库存→落位)。须在 app/DB 上下文内调用。
再进入匹配管道(未来日期阻断→查库存→落位)。须在 app/DB 上下文内调用。
Args:
source_code: 来源实例编码(须与 deps.file_repository 注入的文件一致)。
@@ -82,11 +82,11 @@ def seed_rows_from_file(source_code: str, deps: TransferDeps, business_date: str
)
def make_ready_repo(*files: dict) -> FakeReceiptFileRepository:
"""由 fixture 文件 dict 构建仓库;rows 透传为 ReadyReceiptFile.rows。"""
repository = FakeReceiptFileRepository()
def make_ready_repo(*files: dict) -> FakeInboundFileRepository:
"""由 fixture 文件 dict 构建仓库;rows 透传为 ReadyInboundFile.rows。"""
repository = FakeInboundFileRepository()
for item in files:
repository.files[(item["source_code"], item["business_date"])] = ReadyReceiptFile(
repository.files[(item["source_code"], item["business_date"])] = ReadyInboundFile(
source_code=item["source_code"],
business_date=item["business_date"],
file_no=item["file_no"],
@@ -20,7 +20,6 @@ def _summary(executable_count: int) -> MatchingSummaryDTO:
matching_id="MTG-20260928-ABC123",
status="matched",
business_date="2026-09-28",
eligible_receipt_date_to="2026-09-27",
expires_at="2026-09-28T10:00:00",
counts=MatchingCountsDTO(executable_count=executable_count),
estimated_transfer_quantity="0",
@@ -66,8 +65,8 @@ def test_executes_and_propagates_result_when_executable(monkeypatch):
assert outcome.errors == []
def test_passes_receipt_date_range_to_matching(monkeypatch):
"""可选收料日期范围透传匹配层;缺省时为 None(=全部成熟积压)。"""
def test_passes_movement_date_range_to_matching(monkeypatch):
"""可选异动日期范围透传匹配层;缺省时为 None(=全部积压)。"""
captured = {}
def _fake_create(**kwargs):
@@ -78,15 +77,15 @@ def test_passes_receipt_date_range_to_matching(monkeypatch):
at.run_auto_transfer(
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
receipt_date_from="2026-09-01", receipt_date_to="2026-09-05",
movement_date_from="2026-09-01", movement_date_to="2026-09-05",
)
# 断言:显式范围原样透传(成熟上限/起止合法性由匹配层 ValidationError 卡控)。
assert captured["receipt_date_from"] == "2026-09-01"
assert captured["receipt_date_to"] == "2026-09-05"
# 断言:显式范围原样透传(起止合法性由匹配层 ValidationError 卡控)。
assert captured["movement_date_from"] == "2026-09-01"
assert captured["movement_date_to"] == "2026-09-05"
at.run_auto_transfer(
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
)
# 断言:缺省(留空)不缩小匹配面,范围参数为 None。
assert captured["receipt_date_from"] is None
assert captured["receipt_date_to"] is None
assert captured["movement_date_from"] is None
assert captured["movement_date_to"] is None
@@ -0,0 +1,372 @@
"""backlog_reparse_service:清空并重解析的守卫矩阵(spec §6,Task 7)。
用途:锁死「清空并重新解析」的安全不变量与五条守卫——①正常路径旧映射行被清、
按当前模板重落、计数/溯源正确、审计事件落库;②任一归档解析失败整体中止
一行不删(先解析后删除);③封存行(transfer_executed=true)与被有效 items
占用行幸存;④证据缺失(归档已清理/过保留期/无溯源)的行保留并计入
kept_unrebuildable;⑤预检形状(files/profile/clearable_rows/kept_rows)。
依赖:factories(来源/归档/档行种子 + FakeArchiveStorage + build_movement_xlsx)、
app fixture。
逻辑:归档文件字节经假存储注入(monkeypatch file_asset_storage.get_bytes);
归档文件 created_at 均早于 NOW 数日——若 repository 仍带运行期「当日抓取」
门禁则清单为空,本套件即红(锁定维护路径无当日门禁)。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.core.errors import AppError
from app.models import (
TransferAuditEvent,
TransferInvoiceItem,
TransferMatching,
TransferMovementLedger,
)
from app.services.in_transit_transfer import evidence_sync
from app.services.in_transit_transfer.backlog_reparse_service import (
preview_pending_match_reparse,
reparse_pending_match,
)
from tests.services.in_transit_transfer import factories
pytestmark = [pytest.mark.usefixtures("app")]
SOURCE = "CRANE_NA"
NOW = datetime(2026, 10, 15, 10, 0, 0)
OLD_SHA = "9" * 64
SHA_A = "a" * 64
SHA_B = "b" * 64
SHA_GONE = "e" * 64 # 已过保留期归档文件的 sha(证据缺失形态)
REPARSE_EVENT = "TRANSFER_PENDING_MATCH_REPARSED"
@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_world(*, profile_status: str = "published") -> tuple:
"""标准场景种子:来源+已发布入站规则 + 两份可用归档(A 先 B 后)。
Returns:
(source, profile, file_a, file_b) 元组。
"""
source, profile = factories.seed_inbound_reparse_source(SOURCE, status=profile_status)
file_a = factories.seed_reparse_archive_file(
source, sha=SHA_A, storage_key=f"archive/{SOURCE}/a.xlsx",
created_at=datetime(2026, 10, 10, 8, 0, 0))
file_b = factories.seed_reparse_archive_file(
source, sha=SHA_B, storage_key=f"archive/{SOURCE}/b.xlsx",
created_at=datetime(2026, 10, 11, 8, 0, 0))
return source, profile, file_a, file_b
def _count_ledger(source_code: str = SOURCE) -> int:
"""该来源 inbound 档行总数(中止/幸存断言主对象)。"""
return TransferMovementLedger.query.filter_by(
source_code=source_code, record_kind="inbound").count()
def test_reparse_clears_and_relands(app, archive_storage):
# [断言意图] 正常路径:旧映射行全清(3)、按当前模板重落(3)、date_skipped
# 计入结果、审计事件 TRANSFER_PENDING_MATCH_REPARSED 落库且 payload 完整
# (operator/source_code/files/profile/cleared/reinserted/date_skipped/kept)。
source, profile, file_a, file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 300, "2026-08-05"],
])
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([
["ASN-B1", "1", "I", "MAT-3", "模块", "LOT-3", 700, "2026-08-06"],
])
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id,
sha=OLD_SHA, quantity="1")
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id,
sha=OLD_SHA, quantity="2")
factories.seed_reparse_ledger_row(SOURCE, "ASN-B1", source_file_id=file_b.id,
sha=OLD_SHA, quantity="3")
assert _count_ledger() == 3
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert (outcome.cleared, outcome.reinserted) == (3, 3) # [断言意图] 清 3 落 3
assert outcome.date_skipped == 0 and outcome.kept_unrebuildable == 0
assert _count_ledger() == 3 # [断言意图] 无重复无丢失
db.session.expire_all()
a1 = TransferMovementLedger.query.filter_by(
source_code=SOURCE, doc_no="ASN-A1").one()
# [断言意图] 新映射值生效:业务值来自当前归档重解析,溯源换新文件三元组
# (真实 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")
assert a1.movement_date == "2026-08-05"
# [断言意图] 文件顺序:按归档时间升序逐文件重落(files 概要 A 在前)。
assert [f["sha256"] for f in outcome.files] == [SHA_A, SHA_B]
assert [f["inserted"] for f in outcome.files] == [2, 1]
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert event.aggregate_type == "transfer_source"
assert event.aggregate_id == SOURCE
payload = event.after_json
assert payload["operator"] == "admin" and payload["source_code"] == SOURCE
assert payload["cleared"] == 3 and payload["reinserted"] == 3
assert payload["date_skipped"] == 0 and payload["kept"] == 0
assert payload["profile_code"] == profile.profile_code
assert payload["profile_version"] == 1
assert [f["sha256"] for f in payload["files"]] == [SHA_A, SHA_B]
def test_abort_on_parse_failure_deletes_nothing(app, archive_storage):
# [断言意图] 安全不变量:任一归档解析失败(坏表头→必填缺失)→ 整体中止
# TRANSFER.REPARSE_PARSE_FAILED,一行未删、无审计事件(先解析后删除)。
_source, _profile, file_a, file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
])
# 坏文件:表头与绑定别名全不匹配 → 数据行缺单号 → 解析必失败。
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx(
[["X1", 100, "X2"]], headers=["只此一列", "随便", "没有映射"])
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id, sha=OLD_SHA)
factories.seed_reparse_ledger_row(SOURCE, "ASN-B1", source_file_id=file_b.id, sha=OLD_SHA)
with pytest.raises(AppError) as exc_info:
reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert exc_info.value.code == "TRANSFER.REPARSE_PARSE_FAILED"
# [断言意图] 中止详情可精确定位失败文件:details 逐项断言(来源/文件身份/
# 失败原因),不得用 or 短路式恒真断言掩盖缺键。
details = exc_info.value.details
assert details["source_code"] == SOURCE
assert details["sha256"] == SHA_B # 失败文件=坏表头那份
assert details["storage_key"] == f"archive/{SOURCE}/b.xlsx"
assert details["file_id"] == file_b.id
assert "missing_invoice_no" in details["reason"] # 行级失败原因透传
assert _count_ledger() == 3 # [断言意图] 一行未删
assert TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).count() == 0
def test_sealed_and_occupied_rows_survive(app, archive_storage):
# [断言意图] 删除范围三重过滤:封存行(transfer_executed=true)不动不复活;
# 被有效 items 占用行不被删除(item 引用保持有效),重落按常规幂等语义
# 走原行更新(新映射值生效、无第二行)。
_source, _profile, file_a, _file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 600, "2026-08-05"],
])
# 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([])
sealed_at = datetime(2026, 10, 2, 8, 0, 0)
sealed = factories.seed_reparse_ledger_row(
SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA, quantity="1",
transfer_executed=True, executed_doc_no="TRF-9", updated_at=sealed_at)
occupied = factories.seed_reparse_ledger_row(
SOURCE, "ASN-A2", line_no="1", in_out_flag="I", lot_no="LOT-2",
source_file_id=file_a.id, sha=OLD_SHA, quantity="2")
db.session.add(TransferInvoiceItem(
matching_id=None, ledger_record_id=occupied.id, source_code=SOURCE,
invoice_no="ASN-A2", material_no="MAT-OLD", from_warehouse="W1",
to_warehouse="W2", movement_quantity="2", status="matching",
result_code="pending_stock_check",
))
db.session.commit()
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert outcome.cleared == 0 # [断言意图] 无可删行
assert outcome.reinserted == 0 # [断言意图] 封存跳过+占用原行更新
assert _count_ledger() == 2 # [断言意图] 无新增行
db.session.expire_all()
sealed_after = TransferMovementLedger.query.filter_by(id=sealed.id).one()
assert sealed_after.transfer_executed is True
assert sealed_after.executed_doc_no == "TRF-9"
assert sealed_after.quantity == "1" # [断言意图] 封存行零写入
occupied_after = TransferMovementLedger.query.filter_by(id=occupied.id).one()
assert occupied_after.quantity == "600" # [断言意图] 占用行走更新分支换新映射
assert occupied_after.file_sha256 == SHA_A
item = TransferInvoiceItem.query.filter_by(ledger_record_id=occupied.id).one()
assert item.result_code == "pending_stock_check" # [断言意图] item 引用仍然有效
def test_unrebuildable_rows_kept_and_reported(app, archive_storage):
# [断言意图] 证据缺失行保留并计入 kept_unrebuildable:归档已过保留期
# (repository 可用清单排除)或无溯源(source_file_id=NULL)的行原样留存。
source, _profile, file_a, _file_b = _seed_world()
expired = factories.seed_reparse_archive_file(
source, sha=SHA_GONE, storage_key=f"archive/{SOURCE}/gone.xlsx",
created_at=datetime(2026, 10, 9, 8, 0, 0),
archive_expires_at=datetime(2026, 10, 14, 0, 0, 0)) # NOW 前已过保留期
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
])
# 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([])
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
factories.seed_reparse_ledger_row(SOURCE, "ASN-X", source_file_id=expired.id,
sha=SHA_GONE, quantity="9")
factories.seed_reparse_ledger_row(SOURCE, "ASN-Y", source_file_id=None,
sha=None, quantity="8")
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert (outcome.cleared, outcome.reinserted) == (1, 1) # [断言意图] 仅可重建行被清/重落
assert outcome.kept_unrebuildable == 2 # [断言意图] 证据缺失=2 行
db.session.expire_all()
kept_x = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-X").one()
kept_y = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-Y").one()
assert kept_x.quantity == "9" and kept_x.file_sha256 == SHA_GONE # [断言意图] 原样留存
assert kept_y.quantity == "8" and kept_y.file_sha256 is None
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert event.after_json["kept"] == 2
def test_preview_shape(app, archive_storage):
# [断言意图] 预检形状:files(archived_at/sha256/预估行数,按归档时间升序)、
# profile{code,version}、clearable_rows(可重建可清除)与 kept_rows(证据缺失
# 保留)与执行口径 1:1;只读(不删行、不落审计、不重落)。
source, profile, file_a, file_b = _seed_world()
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id,
sha=OLD_SHA, transfer_executed=True,
executed_doc_no="TRF-8")
factories.seed_reparse_ledger_row(SOURCE, "ASN-Y", source_file_id=None,
sha=None, quantity="8")
preview = preview_pending_match_reparse(source_code=SOURCE, now=NOW)
assert set(preview.keys()) == {"files", "profile", "clearable_rows", "kept_rows"}
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()
# [断言意图] 预估行数口径=现有档行按 source_file_id 计数(含封存;docstring 声明),
# 不在预检里解析归档字节。
assert preview["files"][0]["rows"] == 2 and preview["files"][1]["rows"] == 0
assert preview["clearable_rows"] == 1 # [断言意图] 仅未封存未占用有据行
assert preview["kept_rows"] == 1 # [断言意图] 证据缺失行计入保留
assert _count_ledger() == 3 # [断言意图] 预检只读零副作用
assert TransferAuditEvent.query.count() == 0
def test_reparse_aborts_without_published_profile(app, archive_storage):
# [断言意图] 无已发布入站规则=无重建通道:即使存在档行也整体中止
# (REPARSE_PARSE_FAILED),一行不删——防「删了装不回去」。
factories.seed_inbound_reparse_source(SOURCE, status="draft")
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=None, sha=None)
with pytest.raises(AppError) as exc_info:
reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert exc_info.value.code == "TRANSFER.REPARSE_PARSE_FAILED"
assert _count_ledger() == 1 # [断言意图] 一行未删
def test_cancelled_and_isolated_items_unlinked_before_delete(app, archive_storage):
# [断言意图] R9/方案 D(FK 悬挂修复):已取消匹配 items 与 blocked_file_removed
# 隔离 items 仍持有待删档行的 ledger_record_id(普通 FK 无 ondelete)——删除前
# 必须同事务置空,否则 PG flush 撞 IntegrityError 且此后每次重建复发。
# 范围严格限于待删集合:有效占用行不在删除集,其 items 引用保持不变。
_source, _profile, file_a, file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 600, "2026-08-05"],
])
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([
["ASN-B1", "1", "I", "MAT-3", "模块", "LOT-3", 700, "2026-08-06"],
])
row_a1 = factories.seed_reparse_ledger_row(
SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
row_a2 = factories.seed_reparse_ledger_row(
SOURCE, "ASN-A2", lot_no="LOT-2", source_file_id=file_a.id, sha=OLD_SHA)
row_b1 = factories.seed_reparse_ledger_row(
SOURCE, "ASN-B1", lot_no="LOT-3", source_file_id=file_b.id, sha=OLD_SHA)
# ① 已取消匹配的 item → 引用待删行 row_a1。
matching = TransferMatching(
matching_no="MTG-R9-1", business_date="2026-08-06", status="cancelled",
scope_json={}, file_snapshot_json={}, counts_json={}, matching_hash="sha256:r9",
)
db.session.add(matching)
db.session.flush()
cancelled_item = TransferInvoiceItem(
matching_id=matching.id, ledger_record_id=row_a1.id, source_code=SOURCE,
invoice_no="ASN-A1", material_no="MAT-OLD", from_warehouse="W1",
to_warehouse="W2", movement_quantity="1", status="cancelled",
)
# ② 失效隔离 item(blocked_file_removed 不构成占用)→ 引用待删行 row_a2。
isolated_item = TransferInvoiceItem(
matching_id=None, ledger_record_id=row_a2.id, source_code=SOURCE,
invoice_no="ASN-A2", material_no="MAT-OLD", from_warehouse="W1",
to_warehouse="W2", movement_quantity="2", status="cancelled",
result_code="blocked_file_removed",
)
# ③ 对照:有效占用 item(普通 pending 引用即占用)→ row_b1 不在删除集。
occupied_item = TransferInvoiceItem(
matching_id=None, ledger_record_id=row_b1.id, source_code=SOURCE,
invoice_no="ASN-B1", material_no="MAT-OLD", from_warehouse="W1",
to_warehouse="W2", movement_quantity="3", status="matching",
result_code="pending_stock_check",
)
db.session.add_all([cancelled_item, isolated_item, occupied_item])
db.session.commit()
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
# [断言意图] 删除成功(无 FK IntegrityError)且仅删未占用两行;解绑计数=2。
assert (outcome.cleared, outcome.reinserted) == (2, 2)
assert outcome.unlinked_items == 2
db.session.expire_all()
# [断言意图] 待删行的两枚废弃 items 引用被置空(溯源装饰让位于可重建性)。
assert TransferInvoiceItem.query.filter_by(id=cancelled_item.id).one().ledger_record_id is None
assert TransferInvoiceItem.query.filter_by(id=isolated_item.id).one().ledger_record_id is None
# [断言意图] 占用行不在删除集:行原样幸存(原行更新换新映射),其 item 引用
# 仍指向同一档行 id——有效匹配的圈定关系不受重建波及。
row_b1_after = TransferMovementLedger.query.filter_by(id=row_b1.id).one()
assert row_b1_after.quantity == "700" and row_b1_after.file_sha256 == SHA_B
assert TransferInvoiceItem.query.filter_by(id=occupied_item.id).one().ledger_record_id == row_b1.id
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert event.after_json["unlinked_items"] == 2
def test_reparse_writes_collapse_audit_for_multi_material_same_key(app, archive_storage):
# [断言意图] 终审遗留(坍缩审计接重建路径):重建与运行期同一坍缩守卫——同自然键
# 六成分批内双料号(行级项次全空)重落时第二料号行仍被幂等吞掉(首见为准,
# 行为与运行期一致),但必须落 ledger_natural_key_collapse 审计事件——改模板
# 后的清空重建恰是坍缩易发时刻,静默吞行必须显式可观测;重建概要审计携带
# collapses 计数。
_source, _profile, file_a, _file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-C1", "1", "I", "MAT-X", "物料甲", "LOT-9", 500, "2026-08-05"],
["ASN-C1", "1", "I", "MAT-Y", "物料乙", "LOT-9", 300, "2026-08-05"],
])
# 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([])
factories.seed_reparse_ledger_row(SOURCE, "ASN-C1", lot_no="LOT-9",
source_file_id=file_a.id, sha=OLD_SHA)
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert (outcome.cleared, outcome.reinserted) == (1, 1) # [断言意图] 旧行清 1、重落仅首见 1 行
assert outcome.collapses == 1 # [断言意图] 坍缩键计数进结果
db.session.expire_all()
rows = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-C1").all()
assert len(rows) == 1 and rows[0].material_code == "MAT-X" # [断言意图] 首见为准吞行不丢账
# [断言意图] 坍缩审计事件落库且与运行期同构造:定位单号、failure 级、料号可追溯。
event = TransferAuditEvent.query.filter_by(
event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).one()
assert "ASN-C1" in event.aggregate_id
assert event.result == "failure"
assert event.after_json["material_codes"] == ["MAT-X", "MAT-Y"]
assert event.after_json["dropped_material_codes"] == ["MAT-Y"]
assert event.after_json["resolution"] == "first_seen_wins"
# [断言意图] 重建概要事件携带坍缩计数(运维一眼判断本次重建是否有数据质量降级)。
reparse_event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert reparse_event.after_json["collapses"] == 1
@@ -44,7 +44,7 @@ def test_aging_level_thresholds():
def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file):
"""待处理池收纳 blocked_recoverable,排除 success / not_matured。"""
"""待处理池收纳 blocked_recoverable,排除 success(not_matured 已退役)。"""
_blocked_matching(dbs_ready_file)
items = list_backlog()
invoice_set = {item.invoice_no for item in items}
@@ -59,14 +59,14 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file):
updated_at 会让正在处理的行跳位(用户实测:恢复后被处理的行跳到列表末尾)。
业务稳定键下,触碰前后列表顺序完全一致。
"""
_blocked_matching(dbs_ready_file) # HOM-001(receipt 2026-08-05)与 HOX-002 不进池,构造两笔 blocked
_blocked_matching(dbs_ready_file) # HOM-001(inbound 2026-08-05)与 HOX-002 不进池,构造两笔 blocked
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
# 手工造第二笔 blocked:不同收料日期、更晚创建
second = TransferInvoiceItem(
matching_id=item.matching_id, source_code=item.source_code,
invoice_no="HOM-002", material_no="MAT-003", material_name="垫片",
receipt_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
receipt_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found",
movement_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
movement_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found",
)
db.session.add(second)
db.session.commit()
@@ -129,7 +129,7 @@ def test_backlog_summary_includes_pending_match_count(transfer_db, dbs_ready_fil
from app.models import TransferMovementLedger
db.session.add(TransferMovementLedger(
source_code="DBS-AWSBI", record_kind="receipt",
source_code="DBS-AWSBI", record_kind="inbound",
doc_no="HOM-901", line_no="1", line_seq="", in_out_flag="",
material_code="MAT-9", material_name="未匹配物料", specification="",
lot_no="LOT-9", quantity="55", unit="PCS",
@@ -29,7 +29,6 @@ pytestmark = pytest.mark.pure_unit
EXPECTED_ERROR_CODES = {
"TRANSFER_PERMISSION_DENIED",
"TRANSFER_RECEIPT_NOT_MATURED",
"TRANSFER_FILE_NOT_READY",
"TRANSFER_FILE_SCHEMA_INVALID",
"TRANSFER_INVOICE_CONFLICT",
@@ -67,13 +66,13 @@ def test_require_known_error_code_rejects_unknown():
def test_matching_counts_dto_fields():
"""匹配计数 DTO 包含文件内/未成熟/已匹配/可执行/阻断五类计数。"""
"""匹配计数 DTO 包含文件内/已匹配/可执行/阻断等计数(not_matured 已退役)。"""
counts = MatchingCountsDTO(
file_invoice_count=40, not_matured_count=8, matched_count=32,
file_invoice_count=40, matched_count=32,
executable_count=27, blocked_count=5,
)
assert counts.executable_count == 27
assert counts.not_matured_count == 8
assert counts.matched_count == 32
def test_matching_summary_dto_carries_estimate_and_hash():
@@ -82,9 +81,8 @@ def test_matching_summary_dto_carries_estimate_and_hash():
matching_id="MTG-20260806-001",
status="ready_to_execute",
business_date="2026-08-06",
eligible_receipt_date_to="2026-08-05",
expires_at="2026-08-06T09:20:00+08:00",
counts=MatchingCountsDTO(40, 8, 32, 27, 5),
counts=MatchingCountsDTO(40, 32, 27, 5),
estimated_transfer_quantity="18460",
estimated_external_write_count=27,
matching_hash="sha256:abc",
@@ -1,9 +1,12 @@
"""在途调拨日期成熟度策略测试(L0 纯单元)。
"""在途调拨业务日期与日期解析测试(L0 纯单元)。
用途:验证 T+lag 成熟规则(默认 T+2)、当天/T-1 not_matured、未来日期阻断与上海业务时区;
以及 parse_date 对 ISO / 美式 MM/DD/YYYY 收料日期的归一化。
用途:验证 parse_date 对 ISO / 美式 MM/DD/YYYY 异动日期的归一化与上海业务时区
换算(business_date_now / business_date_utc_window)。
依赖:app.services.in_transit_transfer.date_policy(纯函数)。
逻辑:全部断言只依赖业务日期与收料日期,不接触 Flask/DB(pure_unit)。
逻辑:全部断言只依赖入参日期,不接触 Flask/DB(pure_unit)。
【成熟度规则已退役 2026-10-16】原 T+lag 成熟策略用例随概念一并删除;
日期边界现在由调用方入参给定(交互=用户范围,排程=T−N 偏移参数),
引擎仅保留「截止 ≤ 业务日期」入参校验(matching_service 用例覆盖)。
"""
from __future__ import annotations
@@ -16,63 +19,11 @@ import pytest
from app.services.in_transit_transfer.date_policy import (
business_date_now,
business_date_utc_window,
eligible_receipt_date_to,
maturity_status,
parse_date,
)
pytestmark = pytest.mark.pure_unit
BUSINESS_T = date(2026, 8, 6)
def test_same_day_receipt_is_not_matured():
"""当天收料必须返回 not_matured;成熟门禁不查询 外部系统(调用次数由服务层保证为 0)。"""
assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured"
def test_yesterday_receipt_is_not_matured():
"""T+2 默认:昨天(T-1)收料尚未成熟(海外时差:28 号最早处理 26 号)。"""
assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "not_matured"
def test_t_minus_2_receipt_is_eligible():
"""T+2 默认:前天(T-2)收料起可预检(纯单元无 app 上下文 → 回退默认 lag=2)。"""
assert maturity_status(date(2026, 8, 4), BUSINESS_T) == "eligible"
def test_older_receipt_is_eligible():
"""更早收料同样可预检。"""
assert maturity_status(date(2026, 8, 1), BUSINESS_T) == "eligible"
def test_future_receipt_is_blocked():
"""未来日期收料返回结构化阻断值。"""
assert maturity_status(date(2026, 8, 7), BUSINESS_T) == "future"
def test_maturity_status_accepts_iso_strings():
"""字符串日期与 date 对象等价。"""
assert maturity_status("2026-08-04", "2026-08-06") == "eligible"
assert maturity_status("2026-08-05", "2026-08-06") == "not_matured"
assert maturity_status("2026-08-06", "2026-08-06") == "not_matured"
def test_explicit_lag_days_overrides_default():
"""显式 lag=1 复现旧 T+1 口径(兼容回滚与测试钉值场景)。"""
assert maturity_status(date(2026, 8, 5), BUSINESS_T, lag_days=1) == "eligible"
assert maturity_status(date(2026, 8, 6), BUSINESS_T, lag_days=1) == "not_matured"
def test_eligible_receipt_date_to_is_t_minus_two():
"""可调拨收料截止日期 = 业务日期 - 2 天(默认 lag)。"""
assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 4)
def test_eligible_receipt_date_to_explicit_lag():
"""显式 lag=1 时截止 = 业务日期 - 1 天。"""
assert eligible_receipt_date_to(BUSINESS_T, lag_days=1) == date(2026, 8, 5)
def test_business_date_now_uses_shanghai_across_utc_midnight():
"""UTC 17:00(北京时间次日 01:00)业务日期不得漂移回 UTC 日期。"""
@@ -108,17 +59,11 @@ def test_business_date_utc_window_maps_shanghai_day_to_utc():
assert (end_next - start_next).total_seconds() == 24 * 3600
def test_invalid_date_string_raises():
"""非法日期字符串必须抛 ValueError,不得静默解析。"""
with pytest.raises(ValueError):
maturity_status("2026/13/99", BUSINESS_T)
def test_parse_date_accepts_us_mdy_with_time():
"""DSV SSRS Date Received(美式带时分秒)须解析为业务 date。
[断言意图] 收料文件常见 '08/13/2026 13:08:00';仅认 ISO 会导致
evidence_sync 整链 invalid_receipt_date,transfer_invoice_items 零写入。
[断言意图] 异动文件常见 '08/13/2026 13:08:00';仅认 ISO 会导致
evidence_sync 整链 invalid_movement_date,transfer_invoice_items 零写入。
"""
assert parse_date("08/13/2026 13:08:00") == date(2026, 8, 13)
assert parse_date("6/11/2026 08:37:07") == date(2026, 6, 11)
@@ -37,7 +37,7 @@ def _ledger_rows(source_code="DBS-AWSBI") -> list[TransferMovementLedger]:
"""按自然键序取某来源全部档行(断言主对象)。"""
return (
TransferMovementLedger.query
.filter_by(source_code=source_code, record_kind="receipt")
.filter_by(source_code=source_code, record_kind="inbound")
.order_by(TransferMovementLedger.doc_no.asc(), TransferMovementLedger.id.asc())
.all()
)
@@ -96,10 +96,10 @@ def test_sync_inserts_ledger_rows_without_erp(app, dbs_ready_file):
assert outcome is not None and outcome.inserted == 2 # [断言意图] 两张单各一条档行
rows = _ledger_rows()
assert len(rows) == 2
assert all(row.record_kind == "receipt" for row in rows)
assert all(row.record_kind == "inbound" for row in rows)
hom = _by_doc("HOM-001")
# [断言意图] 数量聚合等价于旧 items 汇总断言:500+700=1200(档是匹配圈定的
# 数量真相源,与旧 items receipt_quantity 等值)。
# 数量真相源,与旧 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"
@@ -217,7 +217,7 @@ def test_sync_refreshes_display_fields_on_evidence_change(app, dbs_ready_file):
assert hom.specification == "改规格 / NEW"
def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog):
def test_inbound_bridge_is_failure_isolated(app, monkeypatch, caplog):
# [断言意图] 落档崩溃只记日志:异常绝不向收料回调链路传播。
from app.services.in_transit_transfer import evidence_sync
@@ -233,7 +233,7 @@ def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog):
assert any("TRANSFER_EVIDENCE_SYNC" in r.message for r in caplog.records)
def test_receipt_bridge_commits_ledger_on_success(app, dbs_ready_file, monkeypatch):
def test_inbound_bridge_commits_ledger_on_success(app, dbs_ready_file, monkeypatch):
# [断言意图] 成功路径自行 commit(B3 教训:不依赖调用方提交时机);
# 端到端一遍:桥 → 解析 → 聚合落档(档行持久化,items 停写)。
from app.services.in_transit_transfer import evidence_sync
@@ -250,15 +250,15 @@ def test_receipt_bridge_commits_ledger_on_success(app, dbs_ready_file, monkeypat
assert TransferInvoiceItem.query.count() == 0 # [断言意图] items 停写
def test_receipt_bridge_skips_when_no_file(app):
def test_inbound_bridge_skips_when_no_file(app):
# [断言意图] 来源无可用文件:静默返回 True(无事发生,非错误)。
from app.services.in_transit_transfer import evidence_sync
assert evidence_sync.sync_and_commit_for_callback(
source_code="NO-SUCH", business_date="2026-09-25", now=NOW) is True
def test_receipt_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, monkeypatch):
# [断言意图] 桥内同步抛 ReceiptFileSchemaError(schema 类解析失败)→ 失败事实
def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, monkeypatch):
# [断言意图] 桥内同步抛 MovementFileSchemaError(schema 类解析失败)→ 失败事实
# 独立 commit 落到当前可用文件(parse_failed 三列),来源投影转 parse_failed;
# 同步数据已回滚(桥隔离保持)。
from app import db
@@ -269,7 +269,7 @@ def test_receipt_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m
report = _seed_usable_report_file(
source_code="DBS-AWSBI", sha="d" * 64, callback_id="cb-schema-bad")
deps, _, _ = make_transfer_deps(dbs_ready_file)
# 行缺单号(doc_no 置空)→ 解析必抛 ReceiptFileSchemaError(行级 missing_invoice_no)。
# 行缺单号(doc_no 置空)→ 解析必抛 MovementFileSchemaError(行级 missing_invoice_no)。
bad_row = {**dbs_ready_file["rows"][0], "doc_no": ""}
deps.file_repository.set_next_file(
source_code="DBS-AWSBI", rows=[bad_row], checksum="d" * 64)
@@ -294,13 +294,13 @@ def test_sync_success_clears_parse_failed_mark(app, dbs_ready_file):
# [断言意图] 同步成功 = 当前可用文件已成功解析:此前落下的 parse_failed 三列
# 被清除,来源投影恢复 ready(只 flush 不 commit,事务归属调用方不变)。
from app.services.in_transit_transfer.source_file_status import (
record_receipt_parse_failure,
record_inbound_parse_failure,
resolve_source_file_status,
)
report = _seed_usable_report_file(
source_code="DBS-AWSBI", sha="d" * 64, callback_id="cb-schema-clear")
record_receipt_parse_failure(
record_inbound_parse_failure(
report=report, error_code="TRANSFER_FILE_SCHEMA_INVALID", error_message="stale mark")
assert resolve_source_file_status(
source_code="DBS-AWSBI")["file_status"] == "parse_failed" # [断言意图] 前置:确已标记
@@ -319,12 +319,12 @@ def test_sync_success_clears_parse_failed_mark(app, dbs_ready_file):
def test_sync_writes_cross_flag_for_contradictory_in_out_flag(app):
# [断言意图] record_kind='receipt' 行出现出库语义 '-1':照常落档 + 计
# [断言意图] record_kind='inbound' 行出现出库语义 '-1':照常落档 + 计
# cross_flagged(解析错位标记由 ledger_sync 落审计事件,档不拒收)。
deps, _, _ = make_transfer_deps({
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-X",
"file_version": "v1",
"checksum": "x" * 64,
@@ -343,15 +343,16 @@ def test_sync_writes_cross_flag_for_contradictory_in_out_flag(app):
def _collapsed_multi_material_file() -> dict:
"""同单号双料号、行级 line_no/line_seq/in_out_flag 全空的坍缩形态文件。
"""同单号双料号、行级 line_no/line_seq/in_out_flag 全空且 carton/lot 等值的坍缩形态文件。
档自然键 (source_code, record_kind, doc_no, line_no, line_seq, in_out_flag)
不含料号:两行在批内折叠为同一自然键,第二料号行会被幂等吞掉(首见为准)。
档自然键 (source_code, record_kind, doc_no, line_no, line_seq, in_out_flag,
carton_id, lot_no) 不含料号(tt14 起含箱号/批号,批内等值才同键):两行在批内
折叠为同一自然键,第二料号行会被幂等吞掉(首见为准)。
"""
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-C1",
"file_version": "v1",
"checksum": "c1" + "0" * 62,
@@ -360,7 +361,7 @@ def _collapsed_multi_material_file() -> dict:
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-C1", "lot_no": "LOT-A",
"material_code": "MAT-A", "movement_date": "2026-08-05", "quantity": "10",
"source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-C1", "lot_no": "LOT-B",
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-C1", "lot_no": "LOT-A",
"material_code": "MAT-B", "movement_date": "2026-08-05", "quantity": "20",
"source_code": "DBS-AWSBI"},
],
@@ -63,7 +63,7 @@ def _file(rows: list[dict], *, checksum: str = READY_SHA) -> dict:
"""由行构造 DBS-AWSBI ready 收料文件 dict。"""
return {
"source_code": "DBS-AWSBI", "business_date": "2026-08-06",
"file_purpose": "receipt", "file_no": "REC-TEST", "file_version": "v9",
"file_purpose": "inbound", "file_no": "REC-TEST", "file_version": "v9",
"checksum": checksum, "status": "ready", "rows": rows,
}
@@ -146,7 +146,7 @@ def _order_call(erp, doc: TransferDocument) -> dict:
# 场景①:两单不同收料日期 → 两张单各一单号(D1 收料日期入组键)
# ---------------------------------------------------------------------------
def test_two_receipt_dates_create_two_documents(
def test_two_movement_dates_create_two_documents(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""不同收料日期的同来源行必须拆为两张单,各自终身独立单号/时间戳。"""
@@ -162,7 +162,7 @@ def test_two_receipt_dates_create_two_documents(
docs = _docs_of(run)
# 断言意图:收料日期入组键(D1)→ 两日期两单,且单初态 pending。
assert len(docs) == 2
assert {doc.receipt_date for doc in docs} == {"2026-08-05", "2026-08-04"}
assert {doc.movement_date for doc in docs} == {"2026-08-05", "2026-08-04"}
assert all(doc.status == "pending" for doc in docs)
assert len({doc.doc_no for doc in docs}) == 2
assert len({doc.submit_timestamp for doc in docs}) == 2
@@ -205,7 +205,7 @@ def test_same_order_same_material_lot_across_invoices_aggregates_line(
# 场景③:制单日期=组收料日期(gls_cm06 必须等于 Excel 异动日期,D1)
# ---------------------------------------------------------------------------
def test_order_doc_date_equals_group_receipt_date(
def test_order_doc_date_equals_group_movement_date(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""单 doc_date 必须等于组收料日期;posting_date 为执行当天业务日。"""
@@ -221,7 +221,7 @@ def test_order_doc_date_equals_group_receipt_date(
call = _order_call(erp, doc)
# 断言意图:制单日期=组收料日期(2026-08-05),过账日期=执行当天(run 业务日)。
assert call.doc_date == "2026-08-05"
assert doc.receipt_date == "2026-08-05"
assert doc.movement_date == "2026-08-05"
assert call.posting_date == run.business_date
@@ -418,9 +418,9 @@ def test_result_unknown_order_blocks_new_rows(
db.session.add(TransferInvoiceItem(
matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="HOM-NEW",
material_no="MAT-009", material_name="新行", specification="",
receipt_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
receipt_quantity="100", unit="PCS", status="ready_to_execute",
receipt_warehouse_code="DBS-TRANSIT",
movement_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
movement_quantity="100", unit="PCS", status="ready_to_execute",
movement_warehouse_code="DBS-TRANSIT",
raw_lines_json=[{"sheet": "Receipt", "row_no": 9, "file_version": "v9", "file_sha256": READY_SHA}],
))
db.session.commit()
@@ -543,7 +543,7 @@ def test_partial_unique_index_race_falls_back_to_reuse(
if state["called"] == 1:
winner = TransferDocument(
source_code=doc.source_code, external_org=doc.external_org,
receipt_date=doc.receipt_date, from_warehouse=doc.from_warehouse,
movement_date=doc.movement_date, from_warehouse=doc.from_warehouse,
to_warehouse=doc.to_warehouse,
doc_no="HX-CN01-OR-26099999999", submit_timestamp="concurrent" + "0" * 38,
status="pending",
@@ -560,7 +560,7 @@ def test_partial_unique_index_race_falls_back_to_reuse(
db.session.expire_all()
docs = TransferDocument.query.filter_by(
source_code="DBS-AWSBI", receipt_date="2026-08-05",
source_code="DBS-AWSBI", movement_date="2026-08-05",
).all()
# 断言意图:竞态后同组仅一张单(DB 部分唯一索引兜底 + 复用重试成立)。
assert len(docs) == 1
@@ -838,7 +838,7 @@ def test_serialize_run_orders_projects_multi_status_order_list(
docs = _docs_of(run)
assert len(docs) == 2
# 按单号注入写场景:收料日期 08-04 单失败、08-05 单成功(组建单按组键升序)。
by_date = {doc.receipt_date: doc for doc in docs}
by_date = {doc.movement_date: doc for doc in docs}
erp.write_scenarios_by_doc[by_date["2026-08-04"].doc_no] = "business_failed"
execute_run(run_id=run.id, deps=deps)
@@ -849,13 +849,13 @@ def test_serialize_run_orders_projects_multi_status_order_list(
assert len(orders) == 2
# 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位,跨数据源
# 不再随建单序乱序;本例同数据源,收料日期升序)。
assert [t["receipt_date"] for t in orders] == ["2026-08-04", "2026-08-05"]
assert [t["movement_date"] for t in orders] == ["2026-08-04", "2026-08-05"]
failed, success = orders
# 断言意图:计划 Task 11 JSON 规格逐键——order 八键、line 七键(+invoice_no:
# 行级溯源收料通知号 2026-09-29 契约扩充;+reason:框线图失败行原因展示契约,
# 控制器裁决扩充,T13-3)。
assert set(failed.keys()) == {
"doc_no", "receipt_date", "from_warehouse", "to_warehouse",
"doc_no", "movement_date", "from_warehouse", "to_warehouse",
"status", "erp_document_no", "error_message", "lines",
}
assert failed["status"] == "business_failed"
@@ -897,12 +897,12 @@ def test_order_lines_group_by_external_lot_form():
item_wtp = TransferInvoiceItem(
invoice_no="HOX-900", material_no="MAT-900", lot_no="WTP26060612",
from_warehouse="W1", to_warehouse="W2",
receipt_quantity="200", unit="PCS", matching=matching,
movement_quantity="200", unit="PCS", matching=matching,
)
item_how = TransferInvoiceItem(
invoice_no="HOX-901", material_no="MAT-900", lot_no="HOW26060612",
from_warehouse="W1", to_warehouse="W2",
receipt_quantity="50", unit="PCS", matching=matching,
movement_quantity="50", unit="PCS", matching=matching,
)
lines = _build_order_lines([item_wtp, item_how])
# [断言意图] WTP/HOW 两形态同属一个 ERP 批次 → 聚合为一行且数量相加,
@@ -930,11 +930,11 @@ def test_serialize_order_reason_join_uses_external_lot_form():
item = TransferInvoiceItem(
invoice_no="HOX-900", material_no="MAT-900", material_name="汇流排",
lot_no="WTP26060612", from_warehouse="W1", to_warehouse="W2",
receipt_quantity="200", unit="PCS", result_message="strict quantity mismatch",
movement_quantity="200", unit="PCS", result_message="strict quantity mismatch",
matching=matching,
)
doc = SimpleNamespace(
doc_no="DOC-1", receipt_date="2026-08-05", from_warehouse="W1",
doc_no="DOC-1", movement_date="2026-08-05", from_warehouse="W1",
to_warehouse="W2", status="failed", erp_document_no=None, error_message=None,
)
order = serialize_order(doc, [item])
@@ -12,16 +12,16 @@ import pytest
from app.services.in_transit_transfer.file_preparation import (
FilePreparationResult,
ReadyReceiptFile,
ReceiptFileRepository,
ensure_receipt_file_ready,
ReadyInboundFile,
InboundFileRepository,
ensure_inbound_file_ready,
)
from tests.services.in_transit_transfer.fakes import FakeRPA
from tests.services.in_transit_transfer.repo_fakes import FakeReceiptFileRepository
from tests.services.in_transit_transfer.repo_fakes import FakeInboundFileRepository
def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyReceiptFile:
return ReadyReceiptFile(
def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyInboundFile:
return ReadyInboundFile(
source_code=source_code,
business_date=business_date,
file_no=f"REC-{source_code}-001",
@@ -33,9 +33,9 @@ def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08
def test_ready_file_reused_without_rpa_trigger():
"""当日 ready 文件存在 → 复用(stage=file_ready),不触发 RPA。"""
repository = FakeReceiptFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()})
repository = FakeInboundFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()})
rpa = FakeRPA()
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -46,9 +46,9 @@ def test_ready_file_reused_without_rpa_trigger():
def test_missing_file_triggers_rpa_once():
"""缺文件 → 触发 RPA 一次并进入 waiting_rpa_callback。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -60,9 +60,9 @@ def test_missing_file_triggers_rpa_once():
def test_active_source_job_binds_existing_task_no_new_trigger():
"""存在活动 Source Job → 绑定已有任务,不重复触发 RPA。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
)
@@ -72,10 +72,10 @@ def test_active_source_job_binds_existing_task_no_new_trigger():
def test_concurrent_requests_share_one_trigger():
"""并发请求携带同一活动键 → 全部绑定已有任务,不重复触发 RPA。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
for _ in range(3):
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
)
@@ -85,13 +85,13 @@ def test_concurrent_requests_share_one_trigger():
def test_without_active_key_each_call_triggers_once():
"""无活动键时每次调用各触发一次;幂等由调用方 SourceJob 唯一键兜底。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
ensure_receipt_file_ready(
ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
ensure_receipt_file_ready(
ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -100,10 +100,10 @@ def test_without_active_key_each_call_triggers_once():
def test_rpa_trigger_failure_is_fail_closed():
"""RPA 触发失败 → stage=failed 且带错误码,不误报 file_ready。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
rpa.fail_on.add("DBS-AWSBI")
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -113,14 +113,14 @@ def test_rpa_trigger_failure_is_fail_closed():
def test_dbs_and_crane_sources_isolated():
"""DBS 失败不影响 Crane 的文件准备(来源隔离)。"""
repository = FakeReceiptFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")})
repository = FakeInboundFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")})
rpa = FakeRPA()
rpa.fail_on.add("DBS-AWSBI")
dbs_result = ensure_receipt_file_ready(
dbs_result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
crane_result = ensure_receipt_file_ready(
crane_result = ensure_inbound_file_ready(
source_code="CRANE-SZ", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -12,8 +12,8 @@ from datetime import datetime, timedelta
from app import db
from app.models import TransferSourceJob, TransferRun
from app.services.in_transit_transfer.receipt_callback_bridge import (
advance_source_job_from_receipt_callback,
from app.services.in_transit_transfer.inbound_callback_bridge import (
advance_source_job_from_inbound_callback,
)
@@ -31,7 +31,7 @@ def _make_waiting_job(run_no: str, source_code: str = "DSV360_AWSDU") -> Transfe
def test_success_callback_advances_job_to_file_ready(app):
"""成功回调(含文件号/sha256)应把最新等待任务推进为 file_ready。"""
job = _make_waiting_job("RUN-BRIDGE-1")
advanced = advance_source_job_from_receipt_callback(
advanced = advance_source_job_from_inbound_callback(
source_code=job.source_code, file_no="42", file_sha256="abc", callback_ok=True,
)
assert advanced is not None and advanced.status == "file_ready"
@@ -41,7 +41,7 @@ def test_success_callback_advances_job_to_file_ready(app):
def test_recover_stale_waiting_source_jobs(app):
"""超过收料回调超时的等待任务回收为 failed;新任务不动。"""
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
from app.services.in_transit_transfer.inbound_callback_bridge import recover_stale_waiting_source_jobs
stale = _make_waiting_job("RUN-BRIDGE-STALE-1", "DSV360_AWSDU")
stale.updated_at = datetime.utcnow() - timedelta(seconds=3600)
@@ -51,5 +51,5 @@ def test_recover_stale_waiting_source_jobs(app):
db.session.expire_all()
assert recovered == 1
assert db.session.get(TransferSourceJob, stale.id).status == "failed"
assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_RECEIPT_CALLBACK_TIMEOUT"
assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_INBOUND_CALLBACK_TIMEOUT"
assert db.session.get(TransferSourceJob, fresh.id).status == "waiting_rpa_callback"
@@ -1,9 +1,12 @@
"""在途调拨收料文件字段/结构校验测试(L0 纯单元)。
"""在途调拨异动文件字段/结构校验测试(L0 纯单元)。
用途:验证必填列缺失、空值、非法数量(0/负数/非数字)、非法日期与
来源身份不一致均整行阻断并抛出 ReceiptFileSchemaError。
来源身份不一致均整行阻断并抛出 MovementFileSchemaError。
依赖:app.services.in_transit_transfer.file_parser(纯函数)。
逻辑:解析不接触文件存储;所有错误带行号细节,供预检页展示原因。
tt14 入站化后统一走 movement 契约行(parse_movement_rows 单一入口),
本文件聚焦「原始行 → 调拨语义字段」投影后的校验行为(与
test_movement_parser 的契约映射用例互补)。
"""
from __future__ import annotations
@@ -14,22 +17,22 @@ from decimal import Decimal
import pytest
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
parse_receipt_rows,
MovementFileSchemaError,
ParsedMovementRow,
parse_movement_rows,
)
pytestmark = pytest.mark.pure_unit
VALID_ROW = {
"sheet": "Receipt",
"sheet": "Movement",
"row_no": 10,
"invoice_no": "INV-001",
"material_no": "MAT-001",
"doc_no": "INV-001",
"material_code": "MAT-001",
"material_name": "连接器组件",
"specification": "A 型 / 24PIN",
"receipt_date": "2026-08-05",
"receipt_quantity": "500",
"movement_date": "2026-08-05",
"quantity": "500",
"source_code": "DBS-AWSBI",
}
@@ -43,83 +46,83 @@ def _rows(**overrides) -> list[dict]:
def test_valid_rows_parse():
"""合法行解析出全部字段(数量 Decimal、日期 date)。"""
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows())
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
assert len(parsed) == 1
row = parsed[0]
assert isinstance(row, ParsedReceiptRow)
assert isinstance(row, ParsedMovementRow)
assert row.invoice_no == "INV-001"
assert row.material_no == "MAT-001"
assert row.material_name == "连接器组件"
assert row.specification == "A 型 / 24PIN"
assert row.receipt_date == date(2026, 8, 5)
assert row.receipt_quantity == Decimal("500")
assert row.sheet == "Receipt"
assert row.movement_date == date(2026, 8, 5)
assert row.movement_quantity == Decimal("500")
assert row.sheet == "Movement"
assert row.row_no == 10
def test_missing_invoice_no_rejected():
"""Invoice No 缺失必须整行阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(invoice_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(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(material_no=""))
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(material_code=""))
def test_invalid_quantity_rejected():
"""非数字数量必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc"))
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc"))
def test_zero_quantity_stamped_row_skipped():
"""零数量收料行(日期已盖章、数量 0)为非可用收料事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。"""
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
"""零数量异动行(日期已盖章、数量 0)为非可用异动事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。"""
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="0"))
assert parsed == []
def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed():
"""合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。"""
rows = [
dict(VALID_ROW, row_no=788, invoice_no="WTP26082227", receipt_quantity="0",
receipt_date="2026-10-01 14:37:43"),
dict(VALID_ROW, row_no=789, invoice_no="INV-002", receipt_quantity="120"),
dict(VALID_ROW, row_no=788, doc_no="WTP26082227", quantity="0",
movement_date="2026-10-01 14:37:43"),
dict(VALID_ROW, row_no=789, doc_no="INV-002", quantity="120"),
]
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
assert [row.row_no for row in parsed] == [789]
assert parsed[0].invoice_no == "INV-002"
def test_negative_quantity_rejected():
"""负数数量必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="-5"))
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="-5"))
def test_invalid_date_rejected():
"""非法日期必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_date="2026/13/99"))
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99"))
def test_source_identity_mismatch_rejected():
"""行内来源与任务来源不一致(Callback 身份漂移)必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
def test_missing_sheet_or_row_no_rejected():
"""Sheet/原始行号缺失无法追溯,必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0))
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0))
def test_material_name_and_specification_optional():
"""品名/规格允许为空(后续由明细 DTO 展示空值)。"""
parsed = parse_receipt_rows(
parsed = parse_movement_rows(
source_code="DBS-AWSBI",
rows=_rows(material_name="", specification=""),
)
@@ -129,8 +132,8 @@ def test_material_name_and_specification_optional():
def test_error_carries_row_details():
"""错误细节必须携带行号与原因,供页面定位。"""
with pytest.raises(ReceiptFileSchemaError) as excinfo:
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc"))
with pytest.raises(MovementFileSchemaError) as excinfo:
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, quantity="abc"))
details = excinfo.value.details
assert any(str(item.get("row_no")) == "77" for item in details.get("rows", []))
@@ -138,12 +141,12 @@ def test_error_carries_row_details():
def test_schema_error_message_carries_row_details():
"""诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。"""
rows = [
dict(VALID_ROW, row_no=5, invoice_no=""),
dict(VALID_ROW, row_no=9, receipt_quantity="abc"),
dict(VALID_ROW, row_no=5, doc_no=""),
dict(VALID_ROW, row_no=9, quantity="abc"),
]
with pytest.raises(ReceiptFileSchemaError) as exc_info:
parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
# [断言意图] 消息不再只是通用 "receipt file schema invalid",须含行号与原因;
with pytest.raises(MovementFileSchemaError) as exc_info:
parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
# [断言意图] 消息不再只是通用 "movement file schema invalid",须含行号与原因;
# 明细同时保留在 details.rows 供管理端展示。
text = str(exc_info.value) or (exc_info.value.message or "")
assert "row 5" in text and "missing_invoice_no" in text
@@ -1,9 +1,9 @@
"""真实收料 RPA 触发服务测试。
用途:验证 trigger_receipt_rpa / trigger_receipt_rpa_batch 按来源装配收料 trigger unit
用途:验证 trigger_inbound_rpa / trigger_inbound_rpa_batch 按来源装配收料 trigger unit
并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa(_batch)、
依赖:app(SQLite)fixture、inbound_trigger_service.trigger_inbound_rpa(_batch)、
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False;
批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批,
@@ -15,9 +15,9 @@ from __future__ import annotations
import pytest
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.services.in_transit_transfer.receipt_trigger_service import (
trigger_receipt_rpa,
trigger_receipt_rpa_batch,
from app.services.in_transit_transfer.inbound_trigger_service import (
trigger_inbound_rpa,
trigger_inbound_rpa_batch,
)
@@ -38,7 +38,7 @@ def receipt_source():
return source
def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source):
"""来源有效 → 写入 trigger 并返回 callback_id / trigger_path。"""
calls = {}
@@ -48,9 +48,9 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
calls['payload'] = payload or {}
return f'/tmp/trigger/{run_no}.json'
result = trigger_receipt_rpa(
result = trigger_inbound_rpa(
source_code='DSV360_AWSDU', business_date='2026-08-06',
reason='transfer_retry_receipt', writer=fake_writer,
reason='transfer_retry_inbound', writer=fake_writer,
)
assert result['ok'] is True
assert result['callback_id']
@@ -65,25 +65,25 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
def test_trigger_receipt_rpa_disabled_source_fails_closed(app):
def test_trigger_inbound_rpa_disabled_source_fails_closed(app):
"""来源停用 → ok=False,不写 trigger。"""
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
source.enabled = False
from app import db
db.session.commit()
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
result = trigger_inbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
assert result['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
assert result['error_code'] == 'RPA_INBOUND_CONFIG_MISSING'
def test_trigger_receipt_rpa_missing_config_fails_closed(app):
def test_trigger_inbound_rpa_missing_config_fails_closed(app):
"""来源启用但无收料配置 → ok=False。"""
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
result = trigger_inbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
"""触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
@@ -96,9 +96,9 @@ def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receip
captured["units"] = units
return "trigger.json"
outcome = trigger_receipt_rpa(
outcome = trigger_inbound_rpa(
source_code=receipt_source.source_code, business_date="2026-09-17",
reason="transfer_retry_receipt", writer=fake_writer,
reason="transfer_retry_inbound", writer=fake_writer,
)
assert outcome["ok"] is True
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
@@ -111,13 +111,13 @@ def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receip
assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id
def _bind_published_movement_profile(config: ShippingReceiptReportConfig) -> None:
"""给收料配置绑定一条已发布 movement 规则(仅满足守卫校验,不参与解析)。"""
def _bind_published_inbound_profile(config: ShippingReceiptReportConfig) -> None:
"""给收料配置绑定一条已发布 inbound 规则(仅满足守卫校验,不参与解析)。"""
from app import db
from app.models import ShippingInventoryParsingProfile
profile = ShippingInventoryParsingProfile(
purpose='movement', profile_code='MOVE_TRIGGER_STD', display_name='收料异动规则',
purpose='inbound', profile_code='MOVE_TRIGGER_STD', display_name='入站解析规则',
version=1, status='published', file_format='xlsx',
definition_json={'sheet_name': None, 'header_row_index': 1,
'field_mapping': {'doc_no': '单据编号', 'material_code': '料号',
@@ -137,7 +137,7 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
with app.app_context():
config = ShippingReceiptReportConfig.query.filter_by(
inventory_source_id=receipt_source.id).one()
_bind_published_movement_profile(config)
_bind_published_inbound_profile(config)
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
outcome = _DefaultRpaTrigger().trigger(
@@ -148,8 +148,8 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt_source, tmp_path, monkeypatch):
"""收料配置存在但未绑已发布 movement 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_source, tmp_path, monkeypatch):
"""收料配置存在但未绑已发布 inbound 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
@@ -158,27 +158,27 @@ def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt
)
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
assert outcome["ok"] is False
assert outcome["error_code"] == "RPA_RECEIPT_MOVEMENT_PROFILE_MISSING"
assert outcome["error_code"] == "RPA_INBOUND_PROFILE_MISSING"
assert list(tmp_path.glob("receipt_export_batch_*.json")) == []
def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
from app.models import ShippingReceiptRpaUnitRun
outcome = trigger_receipt_rpa(
outcome = trigger_inbound_rpa(
source_code=receipt_source.source_code, business_date="2026-09-17",
reason="transfer_retry_receipt", writer=lambda *a, **k: None,
reason="transfer_retry_inbound", writer=lambda *a, **k: None,
)
assert outcome["ok"] is False
unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
ShippingReceiptRpaUnitRun.id.desc()).first()
assert unit.status == "failed"
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
assert unit.error_code == "RPA_INBOUND_TRIGGER_UNAVAILABLE"
# ---------------------------------------------------------------------------
# 批量触发(trigger_receipt_rpa_batch):多来源合并一个 batch trigger 文件,
# 批量触发(trigger_inbound_rpa_batch):多来源合并一个 batch trigger 文件,
# Worker 单次浏览器会话串行处理(2026-10-09 批量重试效率修复)。
# ---------------------------------------------------------------------------
@@ -214,7 +214,7 @@ def second_receipt_source(app):
return source
def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
from app.models import ShippingReceiptRpaUnitRun
@@ -224,9 +224,9 @@ def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt
calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}})
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_receipt_rpa_batch(
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
reason='transfer_retry_receipt', writer=fake_writer,
reason='transfer_retry_inbound', writer=fake_writer,
)
# [断言意图] 合并单文件是本修复的核心:writer 恰好调用 1 次、units 装下全部来源。
assert len(calls) == 1
@@ -244,7 +244,7 @@ def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt
assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']}
def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
def test_trigger_inbound_rpa_batch_skips_invalid_source(app, receipt_source):
"""单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。"""
captured: dict = {}
@@ -252,7 +252,7 @@ def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
captured['units'] = units
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_receipt_rpa_batch(
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-09',
writer=fake_writer,
)
@@ -262,36 +262,36 @@ def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
by_code = {item['source_code']: item for item in outcome['results']}
assert by_code['DSV360_AWSDU']['ok'] is True
assert by_code['DSV360_NOPE']['ok'] is False
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_INBOUND_CONFIG_MISSING'
def test_trigger_receipt_rpa_batch_all_invalid_no_trigger(app):
"""全部来源无效 → 不写 trigger,ok=False + RPA_RECEIPT_NO_TRIGGERABLE_SOURCE。"""
outcome = trigger_receipt_rpa_batch(
def test_trigger_inbound_rpa_batch_all_invalid_no_trigger(app):
"""全部来源无效 → 不写 trigger,ok=False + RPA_INBOUND_NO_TRIGGERABLE_SOURCE。"""
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_NOPE'], business_date='2026-10-09',
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_RECEIPT_NO_TRIGGERABLE_SOURCE'
assert outcome['error_code'] == 'RPA_INBOUND_NO_TRIGGERABLE_SOURCE'
def test_trigger_receipt_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
from app.models import ShippingReceiptRpaUnitRun
outcome = trigger_receipt_rpa_batch(
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
writer=lambda *a, **k: None,
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
assert outcome['error_code'] == 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
assert {row.status for row in rows} == {'failed'}
assert {row.error_code for row in rows} == {'RPA_RECEIPT_TRIGGER_UNAVAILABLE'}
assert {row.error_code for row in rows} == {'RPA_INBOUND_TRIGGER_UNAVAILABLE'}
def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch):
def test_trigger_inbound_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch):
"""parse_failed 来源先本地重解析(成功则不触发 RPA),与单来源端点分层语义一致。"""
statuses = {
'DSV360_AWSDU': [
@@ -320,7 +320,7 @@ def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receip
def fake_writer(run_no, units, payload=None):
raise AssertionError('reparsed source must not be triggered via RPA')
outcome = trigger_receipt_rpa_batch(
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU'], business_date='2026-10-09', writer=fake_writer,
)
# [断言意图] 重解析恢复 ready → 无需写盘,整体 ok=True(请求已达成目的)。
@@ -1,9 +1,10 @@
"""在途调拨 Invoice 多行汇总与冲突测试(L0 纯单元)。
用途:验证相同 Invoice 多行只汇总收料数量并永久保留原始行追溯;
同一 Invoice 出现多料号/多收料日期时整单阻断(InvoiceConflictError)。
用途:验证相同 Invoice 多行只汇总异动数量并永久保留原始行追溯;
同一 Invoice 出现多料号/多异动日期时自然拆分(InvoiceConflictError 保留为防御)。
依赖:app.services.in_transit_transfer.invoice_aggregator + file_parser。
逻辑:汇总键为 (source_code, invoice_no);冲突判定基于料号与收料日期。
逻辑:汇总键为 (source_code, invoice_no);拆分维度为料号与异动日期。
tt14 入站化后经 parse_movement_rows(movement 契约行)构造解析行。
"""
from __future__ import annotations
@@ -13,7 +14,7 @@ from decimal import Decimal
import pytest
from app.services.in_transit_transfer.file_parser import parse_receipt_rows
from app.services.in_transit_transfer.file_parser import parse_movement_rows
from app.services.in_transit_transfer.invoice_aggregator import (
AggregatedInvoice,
aggregate_invoices,
@@ -23,19 +24,19 @@ pytestmark = pytest.mark.pure_unit
def _parsed(rows: list[dict]) -> list:
"""将原始行解析为 ParsedReceiptRow。"""
return parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
"""将原始 movement 契约行解析为 ParsedMovementRow。"""
return parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
def _row(invoice_no: str, *, material_no: str = "MAT-001", material_name: str = "连接器组件",
specification: str = "A 型 / 24PIN", receipt_date: str = "2026-08-05",
quantity: str = "500", row_no: int = 10, sheet: str = "Receipt",
def _row(doc_no: str, *, material_code: str = "MAT-001", material_name: str = "连接器组件",
specification: str = "A 型 / 24PIN", movement_date: str = "2026-08-05",
quantity: str = "500", row_no: int = 10, sheet: str = "Movement",
warehouse_code: str = "WMS-A") -> dict:
return {
"sheet": sheet, "row_no": row_no, "invoice_no": invoice_no,
"material_no": material_no, "material_name": material_name,
"specification": specification, "receipt_date": receipt_date,
"receipt_quantity": quantity, "source_code": "DBS-AWSBI",
"sheet": sheet, "row_no": row_no, "doc_no": doc_no,
"material_code": material_code, "material_name": material_name,
"specification": specification, "movement_date": movement_date,
"quantity": quantity, "source_code": "DBS-AWSBI",
"warehouse_code": warehouse_code,
}
@@ -50,11 +51,11 @@ def test_same_invoice_multiple_rows_sum_quantity():
assert len(invoices) == 1
invoice = invoices[0]
assert invoice.invoice_no == "INV-001"
assert invoice.receipt_quantity == Decimal("1200")
assert invoice.movement_quantity == Decimal("1200")
assert len(invoice.raw_lines) == 2
assert invoice.raw_lines[0].row_no == 10
assert invoice.raw_lines[1].row_no == 11
assert all(line.sheet == "Receipt" for line in invoice.raw_lines)
assert all(line.sheet == "Movement" for line in invoice.raw_lines)
def test_distinct_invoices_stay_separate_and_sorted():
@@ -70,41 +71,41 @@ def test_distinct_invoices_stay_separate_and_sorted():
def test_same_invoice_multiple_materials_split_into_separate_invoices():
"""同一 Invoice(ASN)跨料号 → 按料号拆分为多张调拨发票,不再整单阻断。"""
rows = [
_row("ASN-001", material_no="MAT-001", row_no=1, quantity="100"),
_row("ASN-001", material_no="MAT-002", row_no=2, quantity="200"),
_row("ASN-001", material_code="MAT-001", row_no=1, quantity="100"),
_row("ASN-001", material_code="MAT-002", row_no=2, quantity="200"),
]
invoices = aggregate_invoices(_parsed(rows))
# [断言意图] Invoice 语义 = 调拨拨出单据号;料号维度自然拆分,保留各自数量与原始行。
assert [(i.material_no, i.receipt_quantity) for i in invoices] == [
assert [(i.material_no, i.movement_quantity) for i in invoices] == [
("MAT-001", Decimal("100")), ("MAT-002", Decimal("200")),
]
assert all(i.invoice_no == "ASN-001" for i in invoices)
def test_same_invoice_material_multiple_dates_split_by_date():
"""同 Invoice 同料号跨收料日期(部分交付)→ 按日期拆分,不再整单阻断。"""
"""同 Invoice 同料号跨异动日期(部分交付)→ 按日期拆分,不再整单阻断。"""
rows = [
_row("ASN-001", receipt_date="2026-08-05", row_no=1, quantity="100"),
_row("ASN-001", receipt_date="2026-08-06", row_no=2, quantity="50"),
_row("ASN-001", movement_date="2026-08-05", row_no=1, quantity="100"),
_row("ASN-001", movement_date="2026-08-06", row_no=2, quantity="50"),
]
invoices = aggregate_invoices(_parsed(rows))
assert [str(i.receipt_date) for i in invoices] == ["2026-08-05", "2026-08-06"]
assert [i.receipt_quantity for i in invoices] == [Decimal("100"), Decimal("50")]
assert [str(i.movement_date) for i in invoices] == ["2026-08-05", "2026-08-06"]
assert [i.movement_quantity for i in invoices] == [Decimal("100"), Decimal("50")]
def test_aggregated_invoice_keeps_material_identity():
"""汇总结果保留料号、品名、规格与收料日期。"""
"""汇总结果保留料号、品名、规格与异动日期。"""
rows = [
_row("INV-001", material_no="MAT-001", material_name="连接器组件",
specification="A 型 / 24PIN", receipt_date="2026-08-05", row_no=1),
_row("INV-001", material_no="MAT-001", row_no=2),
_row("INV-001", material_code="MAT-001", material_name="连接器组件",
specification="A 型 / 24PIN", movement_date="2026-08-05", row_no=1),
_row("INV-001", material_code="MAT-001", row_no=2),
]
invoices = aggregate_invoices(_parsed(rows))
invoice = invoices[0]
assert invoice.material_no == "MAT-001"
assert invoice.material_name == "连接器组件"
assert invoice.specification == "A 型 / 24PIN"
assert invoice.receipt_date == date(2026, 8, 5)
assert invoice.movement_date == date(2026, 8, 5)
def test_aggregated_invoice_keeps_first_row_warehouse_code():
@@ -3,12 +3,12 @@
用途:锁定 ledger_sync.sync_ledger_rows 的规格 §5 五条幂等语义——首落插入、
同文件重落全跳过(完全不动行)、证据变原行更新+换溯源、缺席不删、
封存行(transfer_executed=True)永不更新永不复活;以及交叉校验矛盾
(receipt 行出库语义 '-1')计 cross_flagged 并写 ledger_cross_check_failed
(inbound 行出库语义 '-1')计 cross_flagged 并写 ledger_cross_check_failed
审计事件且记录照常落档;shipment 预留合法值放行、同批自然键重复首见为准。
依赖:app fixture(pytestmark)、models.TransferMovementLedger / TransferAuditEvent、
ledger_sync.sync_ledger_rows / FileMeta。
逻辑:parsed_rows 以「movement 契约 field code → 值」的领域行 dict 直接构造
(扩展字段值从 dict 取,非 ParsedReceiptRow 属性——Task 11 接线同形态);
(扩展字段值从 dict 取,非 ParsedMovementRow 属性——Task 11 接线同形态);
直连 SQLite 内存库断言行级状态与审计事件,全程零外部调用。
"""
@@ -60,7 +60,7 @@ def _meta(*, sha: str = SHA_V1, version: str = "v1", file_id: int = 101) -> File
return FileMeta(source_file_id=file_id, file_version=version, file_sha256=sha)
def _sync(parsed_rows, *, record_kind: str = "receipt", meta: FileMeta | None = None, now=NOW):
def _sync(parsed_rows, *, record_kind: str = "inbound", meta: FileMeta | None = None, now=NOW):
"""按默认来源发起一次落档(省略重复实参)。"""
return sync_ledger_rows(
source_code=SOURCE, record_kind=record_kind,
@@ -69,14 +69,14 @@ def _sync(parsed_rows, *, record_kind: str = "receipt", meta: FileMeta | None =
def test_first_landing_inserts_rows_with_provenance():
# [断言意图] 首落五分类归插入:业务镜像列(含扩展字段)与溯源五列随行写入。
# [断言意图] 首落六分类归插入:业务镜像列(含扩展字段)与溯源五列随行写入。
outcome = _sync([_row(), _row(doc_no="HOM-20261014-002", line_no="20")])
assert (outcome.inserted, outcome.updated, outcome.skipped,
outcome.sealed_skipped, outcome.cross_flagged) == (2, 0, 0, 0, 0)
rows = TransferMovementLedger.query.order_by(TransferMovementLedger.doc_no).all()
assert len(rows) == 2
first = rows[0]
assert (first.source_code, first.record_kind) == (SOURCE, "receipt")
assert (first.source_code, first.record_kind) == (SOURCE, "inbound")
assert first.quantity == "12.5" and first.lot_no == "WTP123"
# 扩展字段取自领域行 dict(movement 契约 code ↔ 档列 1:1 镜像)。
assert first.specification == "C 型" and first.order_type == "ZRO1"
@@ -146,8 +146,8 @@ def test_sealed_row_never_updated_nor_revived():
assert TransferMovementLedger.query.count() == 1 # 永不复活(同键无第二行)
def test_receipt_outbound_flag_cross_flagged_but_landed():
# [断言意图] receipt 行出库语义 '-1':计 cross_flagged、写审计事件,记录照常落档;
def test_inbound_outbound_flag_cross_flagged_but_landed():
# [断言意图] inbound 行出库语义 '-1':计 cross_flagged、写审计事件,记录照常落档;
# 幂等重落同一矛盾文件不重复打事件(只追加审计表防刷爆)。
outcome = _sync([_row(in_out_flag="-1"), _row(doc_no="HOM-20261014-002", line_no="20")])
assert (outcome.cross_flagged, outcome.inserted) == (1, 2)
@@ -167,10 +167,10 @@ def test_receipt_outbound_flag_cross_flagged_but_landed():
def test_shipment_kind_is_legal_and_not_cross_flagged():
# [断言意图] record_kind='shipment' 为预留合法值:校验放行、无 receipt 侧矛盾判定。
outcome = _sync([_row(in_out_flag="-1")], record_kind="shipment")
# [断言意图] record_kind='outbound'(出货侧,预留)为合法值:校验放行、无 inbound 侧矛盾判定。
outcome = _sync([_row(in_out_flag="-1")], record_kind="outbound")
assert (outcome.inserted, outcome.cross_flagged) == (1, 0)
assert TransferMovementLedger.query.one().record_kind == "shipment"
assert TransferMovementLedger.query.one().record_kind == "outbound"
def test_sealed_row_dominates_even_when_sha_unchanged():
@@ -193,11 +193,46 @@ def test_duplicate_natural_key_in_batch_first_wins():
assert TransferMovementLedger.query.one().quantity == "12.5"
def test_carton_dimension_expands_natural_key():
# [断言意图] 同单号同行不同箱号=两行独立落档(旧四成分键会塌缩为首见为准丢行)。
outcome = _sync([
_row(doc_no="DUB1", line_no="10", carton_id="C1", quantity="5"),
_row(doc_no="DUB1", line_no="10", carton_id="C2", quantity="7"),
], record_kind="inbound")
assert (outcome.inserted, outcome.date_skipped) == (2, 0)
def test_lot_no_expands_natural_key():
# [断言意图] 同单号同行不同批号=两行独立落档(tt14 键扩维防同批号塌缩丢行)。
outcome = _sync([
_row(doc_no="WTP1", line_no="1", lot_no="HOW001", quantity="1"),
_row(doc_no="WTP1", line_no="1", lot_no="HOW002", quantity="2"),
], record_kind="inbound")
assert outcome.inserted == 2
def test_empty_movement_date_rows_skipped():
# [断言意图] movement_date 空 = 未发生异动:不落档、不计入其他分类(date_skipped 单列)。
outcome = _sync([
_row(doc_no="EXP1", line_no="1", movement_date="", quantity="3"),
_row(doc_no="OK1", line_no="1", movement_date="2026-10-15", quantity="1"),
], record_kind="inbound")
assert (outcome.inserted, outcome.date_skipped) == (1, 1)
def test_constants_inbound_outbound():
# [断言意图] record_kind 常量契约:说辞清扫(Task 3)以这些常量名为准,不再散落字面量。
from app.services.in_transit_transfer import ledger_sync
assert ledger_sync.RECORD_KIND_INBOUND == "inbound"
assert ledger_sync.RECORD_KIND_OUTBOUND == "outbound"
assert ledger_sync.INBOUND_CONTRADICTORY_FLAGS == frozenset({"-1"})
def test_batch_external_doc_no_row_untouched_by_landing():
# [断言意图] 评审 Important 回归(STEP 1 只圈批内 doc_no):同来源同种类的批外
# 档行不被水化、不被触碰(updated_at/内容不变),outcome 计数只反映批内。
db.session.add(TransferMovementLedger(
source_code=SOURCE, record_kind="receipt",
source_code=SOURCE, record_kind="inbound",
doc_no="HOM-20261013-999", line_no="1", line_seq="", in_out_flag="1",
quantity="7", file_sha256=SHA_V1, file_version="v0", source_file_id=201,
updated_at=NOW,
@@ -66,9 +66,9 @@ def test_items_are_born_bound_to_matching(transfer_db, dbs_ready_file):
assert row.ledger_record_id is not None
hom = next(row for row in rows if row.invoice_no == "HOM-001")
# [断言意图] 业务字段=档原值:数量=档聚合值(500+700),批号/仓库/日期同档。
assert hom.receipt_quantity == "1200"
assert hom.lot_no == "LOT-10" and hom.receipt_date == "2026-08-05"
assert hom.receipt_warehouse_code == "" # 夹具行无仓库列 → 档原值为空串
assert hom.movement_quantity == "1200"
assert hom.lot_no == "LOT-10" and hom.movement_date == "2026-08-05"
assert hom.movement_warehouse_code == "" # 夹具行无仓库列 → 档原值为空串
def test_rematching_never_accumulates_or_steals_rows(transfer_db, dbs_ready_file):
@@ -1,6 +1,6 @@
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
用途:验证 T+lag 成熟过滤(套件钉 lag=1)、严格数量匹配、来源隔离、
用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
@@ -55,7 +55,6 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
)
summary = result.summary
assert summary.counts.executable_count == 3
assert summary.counts.not_matured_count == 0
assert summary.counts.blocked_count == 0
assert summary.status == "ready_to_execute"
assert summary.matching_hash.startswith("sha256:")
@@ -77,7 +76,7 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
def test_estimated_document_count_merges_same_group(dbs_ready_file):
"""[2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
场景:同源同日两张 Invoice,五元组(org, source, receipt_date, from, to)
场景:同源同日两张 Invoice,五元组(org, source, movement_date, from, to)
全同 → 执行期合并一张 ERP 单,预估数 = 1 而非可执行行数 2;
并断言 DTO external_org 随路由解析透出(前端勾选行预估的分组输入)。
"""
@@ -96,16 +95,16 @@ def test_estimated_document_count_merges_same_group(dbs_ready_file):
assert items["HOX-002"].external_org == "HX-CN01"
def test_estimated_document_count_splits_by_receipt_date():
def test_estimated_document_count_splits_by_movement_date():
"""[2026-10-12 单据数口径修正] 同源同仓库但收料日期不同 → 五元组不同,预估 = 2。
锁定分组的日期维度:execution_service.prepare_execution 以 receipt_date 入键,
锁定分组的日期维度:execution_service.prepare_execution 以 movement_date 入键,
跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。
"""
deps, erp, _ = _deps({
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-009",
"file_version": "v9",
"checksum": "e" * 64,
@@ -129,17 +128,20 @@ def test_estimated_document_count_splits_by_receipt_date():
assert result.summary.estimated_external_write_count == 2
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
"""当天收料 → not_matured,外部系统 调用次数为 0。"""
deps, erp, _ = _deps(same_day_receipt_file)
def test_same_day_data_reaches_erp_query(same_day_inbound_file):
"""【成熟退役 2026-10-16】当天异动数据不再被成熟门禁跳过:正常进 ERP 查询。
[断言意图] 夹具未种库存 → 行落 blocked_inventory_not_found;关键契约是
网关调用必须发生(=1),证明日期不再构成评估前置过滤。
"""
deps, erp, _ = _deps(same_day_inbound_file)
seed_rows_from_file("DBS-AWSSG", deps, "2026-08-06")
result = run_matching(
source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
)
assert result.summary.counts.not_matured_count == 1
assert result.summary.counts.executable_count == 0
assert result.summary.estimated_external_write_count == 0
assert_erp_calls(erp, 0)
assert result.summary.counts.blocked_count == 1
assert_erp_calls(erp, 1)
def test_quantity_mismatch_blocked_no_write(dbs_ready_file):
@@ -175,7 +177,7 @@ def _wtp_lot_file() -> dict:
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-900",
"file_version": "v9",
"checksum": "e" * 64,
@@ -282,7 +284,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"].receipt_date == "2026-08-05"
assert restored_items["HOM-001"].movement_date == "2026-08-05"
assert restored_items["HOM-001"].lot_no == "LOT-10"
assert restored_items["HOX-002"].lot_no == "LOT-20"
@@ -365,7 +367,7 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
assert summary.counts.file_invoice_count == 2
def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file):
def test_movement_date_range_filters_invoices(transfer_db, dbs_ready_file):
"""收料日期范围作为匹配查询范围:范围外发票不进入明细。"""
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
@@ -373,63 +375,39 @@ def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file):
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
receipt_date_from="2026-08-05", receipt_date_to="2026-08-05", transfer_type="in_transit_to_hub"
movement_date_from="2026-08-05", movement_date_to="2026-08-05", 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,
receipt_date_from="2026-08-01", receipt_date_to="2026-08-04", transfer_type="in_transit_to_hub"
movement_date_from="2026-08-01", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub"
)
assert empty.counts.file_invoice_count == 0
def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file):
"""卡控:截止日期超出成熟规则(业务日期-lag,套件钉值 lag=1)必须拒绝。"""
def test_movement_date_range_end_beyond_business_date_rejected(transfer_db, dbs_ready_file):
"""卡控(成熟退役后唯一日期校验):截止晚于业务日期(未来日期)必须拒绝。
[断言意图] 截止=业务日期当天(2026-08-06)现在合法(旧成熟规则会拒绝 T-1/
当天);只有严格晚于业务日期才拒——未来日期无账可核。
"""
from app.core.errors import ValidationError
deps, erp, _ = _deps(dbs_ready_file)
with pytest.raises(ValidationError) as exc_info:
create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
receipt_date_from="2026-08-04", receipt_date_to="2026-08-06", transfer_type="in_transit_to_hub"
movement_date_from="2026-08-04", movement_date_to="2026-08-07", transfer_type="in_transit_to_hub"
)
assert exc_info.value.code == "TRANSFER.RECEIPT_DATE_RANGE_INVALID"
assert exc_info.value.code == "TRANSFER.MOVEMENT_DATE_RANGE_INVALID"
def test_t_plus_2_default_boundary_yesterday_not_matured(app, dbs_ready_file):
"""生产默认 lag=2 边界:昨天(T-1)收料 not_matured,改到 T-2 后可预检。
[断言意图] 套件 conftest 把 lag 钉为 1(存量夹具语义);本用例显式恢复生产
默认 2,锁定真实默认口径不被钉值掩盖(海外时差:28 号最早处理 26 号)。
"""
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")
app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 2 # 覆盖套件钉值,锁生产默认
result = run_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
# [边界反转] 截止=业务日期当天合法(旧行为 lag=1 下会被拒)。
empty = 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"
)
# [断言意图] 夹具行收料 2026-08-05(T-1):默认 lag=2 下全部未成熟,零 ERP 调用。
assert result.summary.counts.not_matured_count == 2
assert result.summary.counts.executable_count == 0
assert_erp_calls(erp, 0)
# [边界] 收料日期改到 T-2(2026-08-04)后即可进入匹配并严格匹配成功。
# [出生翻转] 成熟基准在档(movement_date):改档记录日期,并释放首跑占用
#(管道直调行无匹配归属,测试直接清空=释放;生产释放走取消匹配)后重跑。
from app.models import TransferMovementLedger
for record in TransferMovementLedger.query.filter_by(source_code="DBS-AWSBI").all():
record.movement_date = "2026-08-04"
TransferInvoiceItem.query.delete()
db.session.flush()
result2 = run_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
)
assert result2.summary.counts.executable_count == 2
assert empty.counts.file_invoice_count == 0
def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file):
@@ -464,7 +442,7 @@ def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file):
def test_run_matching_consumes_movement_field_rows(app):
"""run_matching 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。"""
# [断言意图] 真实仓库 rows 以 doc_no/material_code/quantity/movement_date 为键;
# 匹配应正确产出 executable 明细而非 ReceiptFileSchemaError
# 匹配应正确产出 executable 明细而非 MovementFileSchemaError
# 注:sheet/row_no 为解析校验必带的溯源字段(与 parse_movement_rows 契约一致,同校验)。
deps, erp_fake, _rpa = make_transfer_deps(
{
@@ -490,7 +468,7 @@ def test_run_matching_consumes_movement_field_rows(app):
def test_type1_filters_invoices_by_prefix(app):
"""类型 1(在途仓至HUB仓)只纳入 INVOICE 前缀 HOM/HOX/WTP 的单,范围外静默排除。"""
# [断言意图] INV-9 不匹配任何前缀 → 不入明细、不产生 blocked 行;
# HOM/HOX/WTP 前缀单正常走完整匹配(成熟 + 外部系统 匹配)。
# HOM/HOX/WTP 前缀单正常走完整匹配(日期圈定 + 外部系统 匹配)。
deps, erp_fake, _rpa = make_transfer_deps(
{
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
@@ -549,7 +527,7 @@ def test_create_matching_persists_transfer_type_on_run_and_scope(transfer_db):
# 随匹配落库(快照自足,展示/重跑/审计不查配置表)。
assert scope["transfer_type"] == "in_transit_to_hub"
assert scope["source_codes"] == ["DSV360_AWSDU"]
assert scope["receipt_date_from"] is None and scope["receipt_date_to"] is None
assert scope["movement_date_from"] is None and scope["movement_date_to"] is None
assert scope["scope_rules"] == [
{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]},
]
@@ -672,19 +650,19 @@ def test_executable_list_stale_clock_is_inventory_checked_at(app, dbs_ready_file
db.session.add(TransferInvoiceItem(
matching_id=None, source_code="DBS-AWSBI", invoice_no="HOX-OLD",
material_no="MAT-001", material_name="n", specification="",
receipt_date="2026-09-01", status="ready_to_execute", result_code=None,
movement_date="2026-09-01", status="ready_to_execute", result_code=None,
result_message=None, from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
receipt_quantity="1200", external_quantity="1200", lot_no="LOT-10",
receipt_warehouse_code="W1", unit="PCS", raw_lines_json=[],
movement_quantity="1200", external_quantity="1200", lot_no="LOT-10",
movement_warehouse_code="W1", unit="PCS", raw_lines_json=[],
inventory_checked_at=old_ts,
))
db.session.add(TransferInvoiceItem(
matching_id=None, source_code="DBS-AWSBI", invoice_no="HOX-NOCHK",
material_no="MAT-001", material_name="n", specification="",
receipt_date="2026-09-01", status="ready_to_execute", result_code=None,
movement_date="2026-09-01", status="ready_to_execute", result_code=None,
result_message=None, from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
receipt_quantity="1200", external_quantity=None, lot_no="LOT-10",
receipt_warehouse_code="W1", unit="PCS", raw_lines_json=[],
movement_quantity="1200", external_quantity=None, lot_no="LOT-10",
movement_warehouse_code="W1", unit="PCS", raw_lines_json=[],
))
db.session.commit()
payload = list_executable_items()
@@ -704,7 +682,7 @@ def _seed_ledger_record(doc_no: str, *, material: str = "MAT-LED", quantity: str
from app.models import TransferMovementLedger
record = TransferMovementLedger(
source_code=source_code, record_kind="receipt",
source_code=source_code, record_kind="inbound",
doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="",
material_code=material, material_name="档物料", specification="",
lot_no=f"LOT-{doc_no}", quantity=quantity, unit="PCS",
@@ -0,0 +1,177 @@
"""tt14a5f6a7b8c9 入站化迁移契约测试。
用途:锁定 tt14 迁移与模型两侧契约——transfer_invoice_items/transfer_documents
receipt_* 列更名 movement_*(明细/单据方向中立,与异动档 movement_date
对齐);transfer_movement_ledger.record_kind 值迁移 receipt→inbound /
shipment→outbound;自然键唯一约束重建为 8 成分(追加 carton_id/lot_no)。
依赖:migrations/versions(it1a2b3c4d5e 建表 → it2c3d4e5f6a7 → tt0d1e2f3a4b →
tt11b2c3d4e5f → tt14)、app_ctx(根 conftest app fixture 上下文别名)。
逻辑:revision 链断言 + 模型属性/约束成分断言 + SQLite 真实 upgrade/downgrade/
upgrade 往返(test_migration_widen_transfer_run_type 同款模式)。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import pytest
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
pytestmark = pytest.mark.pure_unit
MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions"
@pytest.fixture
def app_ctx(app):
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
return app
def _load(revision_prefix: str):
for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix}*.py")):
spec = importlib.util.spec_from_file_location(path.stem, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
raise AssertionError(f"migration {revision_prefix} not found")
def test_revision_chains_from_mh15_head():
migration = _load("tt14a5f6a7b8c9")
assert migration.down_revision == "mh15f6a7b8c9"
def test_model_inbound_columns_and_ledger_key(app_ctx):
from app.models.in_transit_transfer import (
TransferDocument, TransferInvoiceItem, TransferMovementLedger,
)
item_cols = {c.name for c in TransferInvoiceItem.__table__.columns}
assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= item_cols
assert not {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} & item_cols
doc_cols = {c.name for c in TransferDocument.__table__.columns}
assert "movement_date" in doc_cols and "receipt_date" not in doc_cols
ledger_uq = next(
c for c in TransferMovementLedger.__table__.constraints
if getattr(c, "name", "") == "uq_transfer_movement_ledger_natural_key"
)
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",
]
# R7 终审:进键维度列必须 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"):
assert ledger_cols[name].nullable is False, f"{name} 进键即 NOT NULL"
assert ledger_cols[name].default.arg == ''
assert ledger_cols[name].server_default.arg == ''
def _ledger_natural_key(connection) -> list[str]:
"""从 SQLite 反射 transfer_movement_ledger 自然键唯一约束的列序。"""
constraints = sa.inspect(connection).get_unique_constraints("transfer_movement_ledger")
for constraint in constraints:
if constraint.get("name") == "uq_transfer_movement_ledger_natural_key":
return list(constraint["column_names"])
raise AssertionError("uq_transfer_movement_ledger_natural_key not found in SQLite schema")
def _item_column_names(connection) -> set[str]:
return {c["name"] for c in sa.inspect(connection).get_columns("transfer_invoice_items")}
def _doc_column_names(connection) -> set[str]:
return {c["name"] for c in sa.inspect(connection).get_columns("transfer_documents")}
def _ledger_dimension_column(connection, name: str) -> dict:
"""从 SQLite 反射 transfer_movement_ledger 维度列(DDL 往返断言用)。"""
columns = {c["name"]: c for c in sa.inspect(connection).get_columns("transfer_movement_ledger")}
assert name in columns
return columns[name]
def test_sqlite_roundtrip_upgrade_downgrade_upgrade():
"""SQLite 真实往返:upgrade 更名+扩键 / downgrade 精确还原 / 再 upgrade。
[断言意图] 前置链(it1a2b3c4d5e 建表 + it2c3d4e5f6a7 加仓库列 + tt0d1e2f3a4b
建单表 + tt11b2c3d4e5f 建档表)就位后,tt14 的 batch RENAME 不丢列、自然键
唯一约束随往返在 6/8 成分间精确翻转,证明 DDL 可回滚且与模型同构。
"""
engine = sa.create_engine("sqlite:///:memory:")
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
# batch copy-and-move 反射时按 FK autoload 目标表:内存库无 Flask 全量
# 元数据,先建最小 users / shipping_receipt_report_files 桩表满足反射。
sa.Table(
"users", sa.MetaData(),
sa.Column("id", sa.Integer(), primary_key=True),
).create(connection)
sa.Table(
"shipping_receipt_report_files", sa.MetaData(),
sa.Column("id", sa.Integer(), primary_key=True),
).create(connection)
# it2c3d4e5f6a7 同时给库存来源映射表加列(与调拨列无关):建最小桩表承接。
sa.Table(
"shipping_inventory_external_mappings", sa.MetaData(),
sa.Column("id", sa.Integer(), primary_key=True),
).create(connection)
for revision in ("it1a2b3c4d5e", "it2c3d4e5f6a7", "tt0d1e2f3a4b", "tt11b2c3d4e5f"):
base = _load(revision)
base.op = operations
base.upgrade()
# 前置基线:items/documents 仍是 receipt_* 列,档自然键为 6 成分。
assert {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} <= _item_column_names(connection)
assert "receipt_date" in _doc_column_names(connection)
assert _ledger_natural_key(connection) == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
]
migration = _load("tt14a5f6a7b8c9")
migration.op = operations
migration.upgrade()
item_cols = _item_column_names(connection)
assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= item_cols
assert not {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} & item_cols
assert "movement_date" in _doc_column_names(connection)
assert "receipt_date" not in _doc_column_names(connection)
# [断言意图] 自然键扩 8 成分(真实 WMS 行身份=单据+行+箱/批)。
assert _ledger_natural_key(connection) == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq",
"in_out_flag", "carton_id", "lot_no",
]
# [断言意图] 维度列 NOT NULL + default ''(R7:防 NULL 逃逸唯一比对)。
for name in ("carton_id", "lot_no"):
column = _ledger_dimension_column(connection, name)
assert column["nullable"] is False
assert "''" in str(column.get("default") or "")
migration.downgrade()
assert {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} <= _item_column_names(connection)
assert "movement_date" not in _item_column_names(connection)
assert "receipt_date" in _doc_column_names(connection)
assert _ledger_natural_key(connection) == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
]
# [断言意图] downgrade 对称还原:维度列回 nullable=True 且默认值移除。
for name in ("carton_id", "lot_no"):
column = _ledger_dimension_column(connection, name)
assert column["nullable"] is True
assert "''" not in str(column.get("default") or "")
migration.upgrade()
assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= _item_column_names(connection)
assert _ledger_natural_key(connection) == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq",
"in_out_flag", "carton_id", "lot_no",
]
@@ -73,10 +73,10 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
material_no="MAT-001",
material_name="连接器组件",
specification="A 型 / 24PIN",
receipt_date="2026-08-05",
movement_date="2026-08-05",
from_warehouse="DBS-TRANSIT",
to_warehouse="HUB-CN01",
receipt_quantity="1200",
movement_quantity="1200",
external_quantity="1200",
status="ready_to_execute",
raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}],
@@ -123,10 +123,10 @@ def test_invoice_item_unique_per_matching(transfer_db):
source_code="DBS-AWSBI",
invoice_no=invoice_no,
material_no="MAT-001",
receipt_date="2026-08-05",
movement_date="2026-08-05",
from_warehouse="DBS-TRANSIT",
to_warehouse="HUB-CN01",
receipt_quantity="1200",
movement_quantity="1200",
external_quantity="1200",
status="ready_to_execute",
raw_lines_json=[],
@@ -162,9 +162,9 @@ def test_invoice_item_status_check_constraint(transfer_db):
transfer_db.session.flush()
transfer_db.session.add(TransferInvoiceItem(
matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="INV-999",
material_no="MAT-9", receipt_date="2026-08-05",
material_no="MAT-9", movement_date="2026-08-05",
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
receipt_quantity="1", external_quantity="1",
movement_quantity="1", external_quantity="1",
status="no_such_status", raw_lines_json=[],
))
with pytest.raises(IntegrityError):
@@ -3,7 +3,7 @@
用途:锁定调拨定死的通用异动/移动字段契约(领域定死、不配置化;D4 追加第 11 字段
unit;2026-10-14 调拨类型配置化+库存异动档项目追加 7 个可选维度字段——
line_seq/specification/order_type/odm_id/odm_name/carton_id/pallet_id),
以及通用异动解析器 parse_movement_rows 把字段映射到调拨 ParsedReceiptRow。
以及通用异动解析器 parse_movement_rows 把字段映射到调拨 ParsedMovementRow。
依赖:app.services.in_transit_transfer.movement_contract + file_parser(纯函数)。
逻辑:字段契约是 immutable 常量;解析只认契约字段,供未来出货/入库 Excel 复用;
追加字段全部可选非身份,缺列容忍语义由既有 row.get 投影自动继承。
@@ -16,7 +16,7 @@ from decimal import Decimal
import pytest
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow, parse_movement_rows
from app.services.in_transit_transfer.file_parser import ParsedMovementRow, parse_movement_rows
from app.services.in_transit_transfer.movement_contract import (
MOVEMENT_FIELDS,
MovementField,
@@ -180,4 +180,4 @@ def test_extract_movement_rows_normalizes_ssrs_wrapped_headers():
assert rows[0]['row_no'] == 3
parsed = parse_movement_rows(source_code='DSV360_AWSBI_BYAWSPHX01', rows=rows)
assert parsed[0].invoice_no == 'ASN-PHX-1'
assert parsed[0].receipt_quantity == 24
assert parsed[0].movement_quantity == 24
@@ -1,9 +1,9 @@
"""通用异动表解析器测试(L0 纯单元)。
用途:验证 parse_movement_rows 把通用异动字段(doc_no/line_no/...)映射到
调拨 ParsedReceiptRow(invoice_no=doc_no, receipt_quantity=quantity,
receipt_date=movement_date),并保留既有校验(必填/非法值/来源一致)。
依赖:app.services.in_transit_transfer.movement_parser(纯函数)。
调拨 ParsedMovementRow(invoice_no=doc_no, movement_quantity=quantity,
movement_date=movement_date),并保留既有校验(必填/非法值/来源一致)。
依赖:app.services.in_transit_transfer.file_parser.parse_movement_rows(纯函数)。
逻辑:字段映射后进入既有 file_parser 校验链路,保证下游 invoice_aggregator 不变。
"""
@@ -15,8 +15,8 @@ from decimal import Decimal
import pytest
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
ParsedMovementRow,
MovementFileSchemaError,
parse_movement_rows,
)
@@ -46,41 +46,41 @@ def _rows(**overrides) -> list[dict]:
def test_valid_movement_row_maps_to_parsed_rows():
"""通用字段映射为调拨行:doc_no→invoice_no、quantity→receipt_quantity、movement_date→receipt_date。"""
"""通用字段映射为调拨行:doc_no→invoice_no、quantity→movement_quantity、movement_date→movement_date(tt14 入站化后明细侧同名对齐)。"""
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
assert len(parsed) == 1
row = parsed[0]
assert isinstance(row, ParsedReceiptRow)
assert isinstance(row, ParsedMovementRow)
assert row.invoice_no == "MOV-001"
assert row.material_no == "MAT-001"
assert row.material_name == "连接器组件"
assert row.receipt_date == date(2026, 8, 5)
assert row.receipt_quantity == Decimal("500")
assert row.movement_date == date(2026, 8, 5)
assert row.movement_quantity == Decimal("500")
assert row.sheet == "Movement"
assert row.row_no == 7
def test_missing_doc_no_rejected():
"""单号缺失阻断。"""
with pytest.raises(ReceiptFileSchemaError):
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no=""))
def test_invalid_quantity_rejected():
"""非数字数量阻断。"""
with pytest.raises(ReceiptFileSchemaError):
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc"))
def test_invalid_movement_date_rejected():
"""非法异动日期阻断。"""
with pytest.raises(ReceiptFileSchemaError):
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99"))
def test_source_identity_mismatch_rejected():
"""来源身份漂移阻断。"""
with pytest.raises(ReceiptFileSchemaError):
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
@@ -124,9 +124,9 @@ def test_receiving_in_progress_rows_are_skipped():
def test_unparseable_date_still_fails():
"""日期有值但不可解析仍是数据损坏——跳过守卫不得吞掉真正的脏数据。"""
corrupted = dict(VALID_MOVEMENT_ROW, row_no=5, doc_no="MOV-300", movement_date="not-a-date")
with pytest.raises(ReceiptFileSchemaError) as exc_info:
with pytest.raises(MovementFileSchemaError) as exc_info:
parse_movement_rows(source_code="DBS-AWSBI", rows=[corrupted])
assert any("invalid_receipt_date" in error.get("reason", "")
assert any("invalid_movement_date" in error.get("reason", "")
for error in exc_info.value.details["rows"])
@@ -140,4 +140,4 @@ def test_datetime_cell_and_timed_string_dates_are_accepted():
movement_date="2026-09-08 00:00:00")
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[datetime_cell, timed_string])
# [断言意图] WMS 报表真实日期形态不能被 ISO 纯日期校验误杀。
assert [row.receipt_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)]
assert [row.movement_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)]
@@ -16,7 +16,7 @@ from app.services.in_transit_transfer.quantity import (
QuantityValidationError,
classify_quantity_match,
strict_quantities_equal,
validate_receipt_quantity,
validate_inbound_quantity,
)
pytestmark = pytest.mark.pure_unit
@@ -27,12 +27,12 @@ def test_equal_quantities_are_executable():
assert classify_quantity_match(Decimal("1200"), Decimal("1200")) == "executable"
def test_erp_greater_than_receipt_is_blocked():
def test_erp_greater_than_inbound_is_blocked():
"""外部系统 库存大于收料数量 → 阻断(不允许部分调拨)。"""
assert classify_quantity_match(Decimal("1200"), Decimal("1500")) == "blocked_quantity_mismatch"
def test_erp_less_than_receipt_is_blocked():
def test_erp_less_than_inbound_is_blocked():
"""外部系统 库存小于收料数量 → 阻断。"""
assert classify_quantity_match(Decimal("1200"), Decimal("800")) == "blocked_quantity_mismatch"
@@ -47,27 +47,27 @@ def test_decimal_scale_equality_is_exact():
assert strict_quantities_equal(Decimal("1.0"), Decimal("1.00"))
def test_zero_receipt_quantity_rejected():
def test_zero_movement_quantity_rejected():
"""收料数量为 0 非法。"""
with pytest.raises(QuantityValidationError):
validate_receipt_quantity(Decimal("0"))
validate_inbound_quantity(Decimal("0"))
def test_negative_receipt_quantity_rejected():
def test_negative_movement_quantity_rejected():
"""收料数量为负数非法。"""
with pytest.raises(QuantityValidationError):
validate_receipt_quantity(Decimal("-5"))
validate_inbound_quantity(Decimal("-5"))
def test_non_numeric_quantity_rejected():
"""非数字数量非法(解析层不得静默截断)。"""
with pytest.raises(QuantityValidationError):
validate_receipt_quantity("abc")
validate_inbound_quantity("abc")
def test_string_numeric_quantity_normalized():
"""字符串数字归一化为 Decimal 后参与严格比较。"""
assert validate_receipt_quantity("1200") == Decimal("1200")
assert validate_inbound_quantity("1200") == Decimal("1200")
assert strict_quantities_equal("1200", Decimal("1200"))
@@ -48,7 +48,7 @@ def _cap_deps(file, gw):
def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
"""成熟 Invoice 的库存查询经网关;严格数量匹配仍由领域控制。"""
"""圈中行的库存查询经网关;严格数量匹配仍由领域控制。"""
gw = FakeGateway(inventory={
("MAT-001", "DBS-TRANSIT", "LOT-10"): "1200",
("MAT-002", "DBS-TRANSIT", "LOT-20"): "1200",
@@ -70,17 +70,21 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
assert item.from_quantity == Decimal("1200")
def test_not_matured_not_queried(app, same_day_receipt_file):
"""当天收料(not_matured)不查外部系统——网关零调用。"""
def test_same_day_data_queried_through_gateway(app, same_day_inbound_file):
"""【成熟退役 2026-10-16】当天异动数据照常经网关查询(无免查日期)。
[断言意图] 夹具未种库存 → 行落 blocked_inventory_not_found;关键契约是
网关调用必须发生——日期不再构成评估前置过滤。
"""
gw = FakeGateway(inventory={})
deps = _cap_deps(same_day_receipt_file, gw)
deps = _cap_deps(same_day_inbound_file, gw)
seed_rows_from_file("DBS-AWSSG", deps, "2026-08-06")
result = run_matching(
source_codes=["DBS-AWSSG"], business_date="2026-08-06",
deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub"
)
assert gw.calls == []
assert result.items[0].result == "not_matured"
assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls)
assert result.items[0].result == "blocked_inventory_not_found"
def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file):
@@ -1,7 +1,7 @@
"""首页队列「待匹配」桶与执行门禁改锚测试(Task 12,规格 §10,D16/D17)。
用途:锁定两块契约——
①「待匹配」桶口径(D16):档记录 ∈ 启用类型范围并集、record_kind='receipt'、
①「待匹配」桶口径(D16):档记录 ∈ 启用类型范围并集、record_kind='inbound'、
未封存(transfer_executed=false)、无有效 items(D17 占用判定一致);
匹配圈定后离开、取消匹配释放后回归;无 item_id 不可勾选执行;
②file_current 门禁改锚(规格 §10):行当前性 = item → 档记录 file_sha256 ==
@@ -38,7 +38,7 @@ NOW = datetime(2026, 10, 14, 12, 0, 0)
def _seed_ledger(doc_no: str, *, quantity: str = "100", lot_no: str = "LOT-1",
sha: str = "a" * 64, row_no: int = 1, source_code: str = "DBS-AWSBI",
record_kind: str = "receipt", movement_date: str | None = "2026-10-13",
record_kind: str = "inbound", movement_date: str | None = "2026-10-13",
transfer_executed: bool = False, executed_doc_no: str | None = None):
"""种子一条档记录(缺省=默认类型范围内的收料记录,与 test_requery_scope 同款)。"""
row = TransferMovementLedger(
@@ -140,11 +140,11 @@ def test_pending_match_bucket_excludes_sealed_shipment_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="shipment") # 出货记录(一期不进桶)
_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) # 收料日期空值(不进圈定)
# [断言意图] 桶只收「启用类型范围并集内、receipt、未封存、有收料日期、无 items」的档记录。
# [断言意图] 桶只收「启用类型范围并集内、inbound、未封存、有异动日期、无 items」的档记录。
assert _pending_doc_nos() == {"HOM-1"}
@@ -197,10 +197,10 @@ def _seed_ready_item_with_ledger(sha: str = "a" * 64):
matching_id=None, run_id=None, ledger_record_id=record.id,
source_code="DBS-AWSBI", invoice_no=record.doc_no,
material_no="MAT-1", material_name="物料1", specification="",
receipt_date="2026-10-13", status="ready_to_execute", result_code=None,
movement_date="2026-10-13", status="ready_to_execute", result_code=None,
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
receipt_quantity="100", external_quantity="100",
lot_no="LOT-1", receipt_warehouse_code="", unit="PCS",
movement_quantity="100", external_quantity="100",
lot_no="LOT-1", movement_warehouse_code="", unit="PCS",
raw_lines_json=[{"sheet": "Receipt", "row_no": 1,
"file_version": "v1", "file_sha256": sha}],
inventory_checked_at=NOW,
@@ -35,8 +35,8 @@ def _seed(scope_sources, matching_no):
matching = TransferMatching(
matching_no=matching_no, run_id=run.id, business_date="2026-09-24",
status="success",
scope_json={"source_codes": scope_sources, "receipt_date_from": None,
"receipt_date_to": None, "transfer_type": "in_transit_to_hub"},
scope_json={"source_codes": scope_sources, "movement_date_from": None,
"movement_date_to": None, "transfer_type": "in_transit_to_hub"},
file_snapshot_json={}, mapping_version="v0", strategy_version="v0",
counts_json={}, estimated_transfer_quantity="0",
estimated_external_write_count=0, matching_hash="sha256:x",
@@ -53,10 +53,10 @@ def _seed_row(source_code, invoice_no, lot_no, matching=None):
matching_id=matching.id if matching is not None else None,
source_code=source_code, invoice_no=invoice_no,
material_no="MAT-1", material_name="n", specification="",
receipt_date="2026-09-20", status="blocked_recoverable",
movement_date="2026-09-20", status="blocked_recoverable",
result_code="blocked_quantity_mismatch", result_message="strict quantity mismatch",
from_warehouse="W-FROM", to_warehouse="W-TO", receipt_quantity="36",
external_quantity="30", lot_no=lot_no, receipt_warehouse_code="W1",
from_warehouse="W-FROM", to_warehouse="W-TO", movement_quantity="36",
external_quantity="30", lot_no=lot_no, movement_warehouse_code="W1",
unit="PCS", raw_lines_json=[],
)
db.session.add(row)
@@ -39,9 +39,9 @@ NOW = datetime(2026, 10, 14, 12, 0, 0)
def _seed_ledger(doc_no: str, *, quantity: str = "100", lot_no: str = "LOT-1",
sha: str = "a" * 64, row_no: int = 1) -> TransferMovementLedger:
"""种子一条收料档记录(DBS-AWSBI / receipt / 2026-10-13)。"""
"""种子一条入站档记录(DBS-AWSBI / inbound / 2026-10-13)。"""
row = TransferMovementLedger(
source_code="DBS-AWSBI", record_kind="receipt",
source_code="DBS-AWSBI", record_kind="inbound",
doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="",
material_code="MAT-1", material_name="物料1", specification="",
lot_no=lot_no, quantity=quantity, unit="PCS",
@@ -69,8 +69,8 @@ def _seed_matching(matching_no: str) -> TransferMatching:
scope_json={
"transfer_type": "in_transit_to_hub",
"source_codes": ["DBS-AWSBI"],
"receipt_date_from": None,
"receipt_date_to": None,
"movement_date_from": None,
"movement_date_to": None,
"scope_rules": [{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}],
"scope_note": "doc_no prefix HOM|HOX|WTP",
"transform_rules": [],
@@ -91,10 +91,10 @@ def _seed_own_item(matching: TransferMatching, ledger: TransferMovementLedger) -
matching_id=matching.id, run_id=matching.run_id, ledger_record_id=ledger.id,
source_code="DBS-AWSBI", invoice_no=ledger.doc_no,
material_no="MAT-1", material_name="物料1", specification="",
receipt_date="2026-10-13", status="blocked_recoverable",
movement_date="2026-10-13", status="blocked_recoverable",
result_code="blocked_quantity_mismatch", result_message="strict quantity mismatch",
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", receipt_quantity=ledger.quantity,
external_quantity="30", lot_no=ledger.lot_no, receipt_warehouse_code="",
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", movement_quantity=ledger.quantity,
external_quantity="30", lot_no=ledger.lot_no, movement_warehouse_code="",
unit="PCS", raw_lines_json=[{"sheet": "Receipt", "row_no": ledger.row_no,
"file_version": "v1", "file_sha256": ledger.file_sha256}],
)
@@ -118,7 +118,7 @@ def test_requery_births_item_for_new_ledger_record(app):
assert born.matching_id == matching.id
assert born.run_id is None # 执行 Run 关联归 orchestrator
assert born.ledger_record_id == new_record.id
assert born.receipt_quantity == "50"
assert born.movement_quantity == "50"
assert born.status == "matching" and born.result_code == "pending_stock_check" # 待查态
@@ -140,7 +140,7 @@ def test_requery_refreshes_item_when_ledger_evidence_changed(app):
requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1")
db.session.refresh(item)
assert item.receipt_quantity == "180" # [断言意图] 证据刷新
assert item.movement_quantity == "180" # [断言意图] 证据刷新
assert item.material_name == "改名物料" # [断言意图] 展示字段随档换新
assert item.status == "matching" and item.result_code == "pending_stock_check" # 重置待查
assert item.external_quantity is None and item.inventory_checked_at is None # 旧库存作废
@@ -172,7 +172,7 @@ def test_requery_skips_file_removed_rows(app):
record = _seed_ledger("HOM-1")
removed = _seed_own_item(matching, record)
removed.result_code = "blocked_file_removed"
removed.result_message = "receipt row removed from latest file"
removed.result_message = "inbound row removed from latest file"
db.session.flush()
deps, _, _ = make_transfer_deps()
@@ -198,7 +198,7 @@ def test_retry_item_rejects_file_removed_row(app):
record = _seed_ledger("HOM-1")
row = _seed_own_item(matching, record)
row.result_code = "blocked_file_removed"
row.result_message = "receipt row removed from latest file"
row.result_message = "inbound row removed from latest file"
db.session.flush()
deps, _, _ = make_transfer_deps()
@@ -215,7 +215,7 @@ def test_requery_by_ids_rejects_file_removed_row(app):
record = _seed_ledger("HOM-1")
row = _seed_own_item(matching, record)
row.result_code = "blocked_file_removed"
row.result_message = "receipt row removed from latest file"
row.result_message = "inbound row removed from latest file"
db.session.flush()
deps, _, _ = make_transfer_deps()
@@ -227,7 +227,7 @@ def test_requery_by_ids_rejects_file_removed_row(app):
def test_requery_never_touches_terminal_rows(app):
# [断言意图·Critical-1] 部分行已 SUCCESS 的匹配 + 档证据变化 + 重查:
# SUCCESS 行原样(status/result/updated_at/receipt_quantity 均不变,防已执行
# SUCCESS 行原样(status/result/updated_at/movement_quantity 均不变,防已执行
# 行被重置复活 → 二次写 ERP);非终态行照常刷新重置。
matching = _seed_matching("MTG-T1")
rec1 = _seed_ledger("HOM-1", quantity="100")
@@ -239,7 +239,7 @@ def test_requery_never_touches_terminal_rows(app):
done.result_message = None
db.session.flush()
frozen = (done.status, done.result_code, done.result_message,
done.updated_at, done.receipt_quantity, done.external_quantity)
done.updated_at, done.movement_quantity, done.external_quantity)
rec1.quantity = "150" # 档证据变化(两行同批)
rec2.quantity = "999"
@@ -253,10 +253,10 @@ def test_requery_never_touches_terminal_rows(app):
blocked = db.session.get(TransferInvoiceItem, blocked.id)
# [断言意图] 终态行零写入:含 updated_at 在内全部字段保持原值。
assert (done.status, done.result_code, done.result_message,
done.updated_at, done.receipt_quantity, done.external_quantity) == frozen
done.updated_at, done.movement_quantity, done.external_quantity) == frozen
assert done.status == "success"
# [断言意图] 非终态行正常对账:证据刷新 + 重置待查。
assert blocked.receipt_quantity == "150"
assert blocked.movement_quantity == "150"
assert blocked.status == "matching" and blocked.result_code == "pending_stock_check"
assert blocked.external_quantity is None and blocked.inventory_checked_at is None
@@ -271,7 +271,7 @@ def _wtp_lot_matching(transfer_db):
file_dict = {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-900",
"file_version": "v9",
"checksum": "e" * 64,
@@ -63,7 +63,7 @@ def test_fixed_source_uses_single_mapping_in_transit_code(app):
assert route.external_org == 'TGHX'
def test_inventory_match_prefers_receipt_warehouse_exact_mapping(app):
def test_inventory_match_prefers_inbound_warehouse_exact_mapping(app):
"""inventory_match 源:收料仓库与某行货代仓库精确匹配 → 取该行在途仓编码。"""
with app.app_context():
source = _seed_inventory_match_source()
@@ -3,7 +3,7 @@
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
依赖:schedule.job_registry、receipt_trigger_service、in_transit_transfer_job。
依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
"""
@@ -89,10 +89,10 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
return source
def test_list_receipt_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
def test_list_inbound_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
"""缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。"""
from app.models import ShippingReceiptReportConfig
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True)
_make_receipt_source(transfer_db, "DBS_OFF", enabled=False)
@@ -103,7 +103,7 @@ def test_list_receipt_capable_source_codes_filters_by_enabled_and_config(app, tr
))
transfer_db.session.commit()
result = list_receipt_capable_source_codes()
result = list_inbound_capable_source_codes()
assert "CRANE_SGP" in result
assert "DBS_OFF" not in result
assert "CRANE_NOCONF" not in result
@@ -116,7 +116,7 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
from app.models import ScheduleTask
from app.services.schedule.in_transit_transfer_job import _wanted_source_codes
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP", "DBS_HUB"])
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP", "DBS_HUB"])
empty = ScheduleTask(job_params={"source_codes": []})
assert _wanted_source_codes(empty) == ["CRANE_SGP", "DBS_HUB"]
explicit = ScheduleTask(job_params={"source_codes": ["DBS_HUB"]})
@@ -130,7 +130,7 @@ def test_handler_empty_data_day_stays_silent(monkeypatch):
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
captured = {}
def _fake_auto_transfer(**kwargs):
@@ -147,8 +147,8 @@ def test_handler_empty_data_day_stays_silent(monkeypatch):
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
assert "sender" not in captured
assert "recipients" not in captured
assert captured["receipt_date_from"] is None
assert captured["receipt_date_to"] is None
assert captured["movement_date_from"] is None
assert captured["movement_date_to"] is None
assert captured["source_codes"] == ["CRANE_SGP"]
assert captured["recover_history"] is True
assert run.response_summary_json["domain_notification_managed"] is True
@@ -164,7 +164,7 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
captured = {}
@@ -181,8 +181,8 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
# 断言:T=2026-10-12,起4止2 换算为 T−4~T−2 的具体日期透传匹配层。
assert captured["business_date"] == "2026-10-12"
assert captured["receipt_date_from"] == "2026-10-08"
assert captured["receipt_date_to"] == "2026-10-10"
assert captured["movement_date_from"] == "2026-10-08"
assert captured["movement_date_to"] == "2026-10-10"
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
@@ -190,7 +190,7 @@ def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
def _must_not_run(**kwargs):
raise AssertionError("run_auto_transfer must not run with invalid offsets")
@@ -205,7 +205,7 @@ def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
)
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
assert results == []
assert any("收料日期起点" in e for e in errors)
assert any("异动日期起点" in e for e in errors)
assert not (run.response_summary_json or {}).get("domain_notification_managed")
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
@@ -213,7 +213,7 @@ def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:小数偏移同样快速失败。
assert any("收料日期终点" in e for e in errors)
assert any("异动日期终点" in e for e in errors)
def test_handler_run_day_uses_framework_notification(monkeypatch):
@@ -221,7 +221,7 @@ def test_handler_run_day_uses_framework_notification(monkeypatch):
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
def _fake_auto_transfer(**kwargs):
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
@@ -245,7 +245,7 @@ def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
def _fake_auto_transfer(**kwargs):
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
@@ -185,8 +185,8 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
from app import db
from app.models import ShippingReceiptReportFile
from app.services.in_transit_transfer.source_file_status import (
clear_receipt_parse_failure,
record_receipt_parse_failure,
clear_inbound_parse_failure,
record_inbound_parse_failure,
resolve_source_file_status,
)
@@ -199,12 +199,12 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
)
db.session.add(report)
db.session.commit()
record_receipt_parse_failure(
record_inbound_parse_failure(
report=report, error_code="TRANSFER_FILE_SCHEMA_INVALID", error_message="bad",
)
db.session.commit()
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "parse_failed"
clear_receipt_parse_failure(report=report)
clear_inbound_parse_failure(report=report)
db.session.commit()
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready"
@@ -218,3 +218,32 @@ def test_empty_unit_is_no_data(app, receipt_unit_run):
status = resolve_source_file_status(source_code=SOURCE_CODE)
assert status['file_status'] == 'no_data'
assert status['has_ready_file'] is False
def test_stale_orphan_unit_sweeps_projection_to_failed(app):
"""孤儿单元(按需触发无排程)超时回收后,投影 fetching 翻转为 failed。
网页异常关闭事故回归(2026-10-16):按需触发的单元 schedule_run_id=NULL,
回收扫描覆盖前投影永久 fetching、前端重试按钮(file_status !== 'fetching'
门禁)永久锁死;回收后必须翻转 failed 解锁重新触发 RPA。
"""
from app import db
from app.models import ShippingInventorySource, ShippingReceiptRpaUnitRun
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_orphan_receipt_units
with app.app_context():
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
db.session.add(ShippingReceiptRpaUnitRun(
schedule_run_id=None, inventory_source_id=source.id, source_code=source.source_code,
connector_type='dbs', callback_id='inbound-orphan-status', status='awaiting_rpa',
config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=5),
))
db.session.commit()
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'fetching'
# [断言意图] 回收扫描后投影必须翻转为 failed:这是前端重试门禁
# (file_status !== 'fetching')解锁的依据,也是本测试与事故的直接回归点。
assert recover_all_stale_orphan_receipt_units() == 1
db.session.expire_all()
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'failed'
@@ -26,7 +26,7 @@ pytestmark = pytest.mark.pure_unit
PROMPT_STATUSES = {
"file_pending", "file_ready", "matching", "ready_to_execute", "executing",
"success", "duplicate_success", "blocked_recoverable", "not_matured",
"success", "duplicate_success", "blocked_recoverable",
"result_unknown", "manually_closed", "cancelled", "notification_failed",
}
@@ -102,11 +102,6 @@ def test_unknown_status_rejected():
assert_transition_allowed("no_such_status", TransferStatus.SUCCESS.value)
def test_not_matured_has_no_outgoing_edges():
"""not_matured 无出边:当天不得查询 外部系统、不得生成调拨单。"""
assert ITEM_TRANSITIONS[TransferStatus.NOT_MATURED.value] == frozenset()
def test_run_transition_queued_to_executing_path():
"""Run 生命周期:queued → preparing_files → matching → ready_to_execute → executing。"""
assert_transition_allowed(TransferRunStatus.QUEUED.value, TransferRunStatus.PREPARING_FILES.value, transitions=RUN_TRANSITIONS)
@@ -18,17 +18,20 @@ from app import db
from app.models import ShippingReceiptReportFile
from app.models.in_transit_transfer import TransferMovementLedger
# 自然键成分(幂等增量落地的去重键,规格 §4.2):全部 NOT NULL,可空成分 default ''。
# 自然键成分(幂等增量落地的去重键,规格 §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 逃逸唯一比对)。
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_CONSTRAINT = 'uq_transfer_movement_ledger_natural_key'
# 规格 §4.2 全部业务/证据列(除自然键成分与回写布尔外一律 nullable)。
NULLABLE_BUSINESS_COLUMNS = (
'material_code', 'material_name', 'specification', 'lot_no', 'quantity', 'unit',
'material_code', 'material_name', 'specification', 'quantity', 'unit',
'warehouse_code', 'storage_code', 'movement_date',
'order_type', 'odm_id', 'odm_name', 'carton_id', 'pallet_id',
'order_type', 'odm_id', 'odm_name', 'pallet_id',
'doc_nature', 'movement_type', 'reason_code', 'source_ref_no', 'partner_code', 'remark',
'source_file_id', 'file_version', 'file_sha256', 'sheet_name', 'row_no',
'executed_doc_no',
@@ -46,26 +49,27 @@ def _column_map() -> dict:
def test_table_name_and_natural_key_constraint(app_ctx):
"""表名固定;自然键六成分构成 uq_transfer_movement_ledger_natural_key 唯一约束。"""
"""表名固定;自然键八成分(tt14 扩维 carton_id/lot_no)构成唯一约束。"""
assert TransferMovementLedger.__tablename__ == 'transfer_movement_ledger'
constraints = {
c.name: [col.name for col in c.columns]
for c in TransferMovementLedger.__table__.constraints
if c.name
}
assert constraints[NATURAL_KEY_CONSTRAINT] == list(NATURAL_KEY_COLUMNS)
assert constraints[NATURAL_KEY_CONSTRAINT] == list(
NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS,
)
def test_natural_key_columns_not_null_with_empty_default(app_ctx):
"""自然键成分全部 NOT NULL;line_seq/in_out_flag 等可空成分 default ''。"""
"""自然键 8 成分全部 NOT NULL;可空语义成分 default ''(R7:carton_id/lot_no 同口径)。"""
cols = _column_map()
for name in NATURAL_KEY_COLUMNS:
for name in NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS:
assert cols[name].nullable is False, f"{name} 必须参与自然键即 NOT NULL"
assert cols['line_seq'].default.arg == ''
assert cols['in_out_flag'].default.arg == ''
# 与 TransferInvoiceItem 同约定:空值成分以空串入库(唯一约束可比)。
assert cols['line_seq'].server_default.arg == ''
assert cols['in_out_flag'].server_default.arg == ''
# 与落档链路同口径:可空语义成分以空串入库(唯一约束可比,防 PG NULL 逃逸)。
for name in ('line_seq', 'in_out_flag', 'carton_id', 'lot_no'):
assert cols[name].default.arg == ''
assert cols[name].server_default.arg == ''
def test_business_columns_nullable_and_types(app_ctx):
@@ -74,7 +78,7 @@ def test_business_columns_nullable_and_types(app_ctx):
for name in NULLABLE_BUSINESS_COLUMNS:
assert cols[name].nullable is True, f"{name} 为可空业务列"
assert cols['quantity'].type.length == 40 # 数量 Decimal 文本,与 items 同约定
assert cols['movement_date'].type.length == 16 # 日期文本,与 items.receipt_date 同约定
assert cols['movement_date'].type.length == 16 # 日期文本,与 items.movement_date 同约定
assert cols['remark'].type.python_type is str # 预留列 remark 为 Text
@@ -137,7 +141,11 @@ def test_ledger_roundtrip_with_defaults(transfer_db):
def test_duplicate_natural_key_rejected(transfer_db):
"""自然键唯一约束 DB 兜底:同 (source, kind, doc, line, seq, flag) 二次落地必须失败。"""
"""自然键唯一约束 DB 兜底:同八成分二次落地必须失败。
carton_id/lot_no(R7)与 line_seq/in_out_flag 同口径:ORM default '' + DB
server_default '',未传维度列的行以空串入键即可触发约束。
"""
def _make() -> TransferMovementLedger:
return TransferMovementLedger(
source_code='DBS-AWSBI',
@@ -95,7 +95,7 @@ def test_missing_unit_still_parses():
_row(1, "HOM-901"),
_row(2, "HOM-902", unit=" "),
])
# [断言意图] 缺列与纯空白等价归一为空串,解析不抛 ReceiptFileSchemaError。
# [断言意图] 缺列与纯空白等价归一为空串,解析不抛 MovementFileSchemaError。
assert [row.unit for row in parsed] == ["", ""]
assert [row.invoice_no for row in parsed] == ["HOM-901", "HOM-902"]
@@ -186,15 +186,15 @@ def test_matching_hash_freezes_unit_value_out_of_snapshot(app):
assert hash_kg == hash_pcs
def test_matching_hash_unchanged_when_unit_backfilled_on_not_matured_rows(app):
"""未成熟行补 unit 前后 Hash 不变:既有成熟过滤先行,unit 追加校验不扰动历史行结果。"""
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"),
))
deps_after, _erp_b, _rpa = make_transfer_deps(_file(
_row(1, "HOM-901", unit="KG", movement_date="2026-08-06"),
))
seed_rows_from_file("DBS-AWSBI", deps_before, "2026-08-06") # 行落地一次(当日收料 → 未成熟)
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
hash_after = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_after, transfer_type="in_transit_to_hub").summary.matching_hash
# [断言意图] 口径冻结锁定:对同一行集补 unit 列,历史预检(匹配)哈希不变。
@@ -222,10 +222,10 @@ def test_invoice_item_unit_column_roundtrip(transfer_db):
source_code="DBS-AWSBI",
invoice_no=invoice_no,
material_no="MAT-001",
receipt_date="2026-08-05",
movement_date="2026-08-05",
from_warehouse="DBS-TRANSIT",
to_warehouse="HUB-CN01",
receipt_quantity="100",
movement_quantity="100",
status="ready_to_execute",
unit=unit,
raw_lines_json=[],
@@ -8,6 +8,8 @@
from __future__ import annotations
import pytest
from app.models import ShippingAuditEvent, ShippingInventorySource, User
from tests.conftest import parse_api_data, parse_api_error
@@ -156,8 +158,8 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
def _create_movement_profile(profile_code: str, *, status: str, purpose: str):
"""创建异动/库存解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
def _create_parsing_profile(profile_code: str, *, status: str, purpose: str):
"""创建入站/在手解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
from app import db
from app.models import ShippingInventoryParsingProfile
@@ -174,14 +176,14 @@ def _create_movement_profile(profile_code: str, *, status: str, purpose: str):
return profile
def test_receipt_config_binds_published_movement_profile(app, client):
"""绑定已发布 movement 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。"""
def test_receipt_config_binds_published_inbound_profile(app, client):
"""绑定已发布 inbound 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
profile = _create_movement_profile('CRANE_MOVE_STD', status='published', purpose='movement')
profile = _create_parsing_profile('CRANE_MOVE_STD', status='published', purpose='inbound')
profile_id = profile.id
payload = {**_dbs_payload(), 'parsing_profile_id': profile_id}
@@ -203,16 +205,16 @@ def test_receipt_config_binds_published_movement_profile(app, client):
assert audit.metadata_json['parsing_profile_id'] == profile_id
def test_receipt_config_rejects_draft_or_non_movement_profile(app, client):
"""draft/库存用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。"""
def test_receipt_config_rejects_draft_or_non_inbound_profile(app, client):
"""draft/在手用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
draft = _create_movement_profile('MOVE_DRAFT', status='draft', purpose='movement')
inventory_profile = _create_movement_profile('INV_PUBLISHED', status='published', purpose='inventory')
cases = [draft.id, inventory_profile.id, 999999]
draft = _create_parsing_profile('MOVE_DRAFT', status='draft', purpose='inbound')
onhand_profile = _create_parsing_profile('INV_PUBLISHED', status='published', purpose='onhand')
cases = [draft.id, onhand_profile.id, 999999]
for profile_id in cases:
response = client.put(
@@ -221,8 +223,8 @@ def test_receipt_config_rejects_draft_or_non_movement_profile(app, client):
headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400, f'profile_id={profile_id}'
# 关键断言:非"已发布 movement"绑定必须走统一错误码,fail-closed。
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID'
# 关键断言:非"已发布 inbound"绑定必须走统一错误码,fail-closed。
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_PROFILE_INVALID'
def test_receipt_config_empty_profile_id_unbinds(app, client):
@@ -232,7 +234,7 @@ def test_receipt_config_empty_profile_id_unbinds(app, client):
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
profile = _create_movement_profile('MOVE_UNBIND', status='published', purpose='movement')
profile = _create_parsing_profile('MOVE_UNBIND', status='published', purpose='inbound')
profile_id = profile.id
bound = client.put(
@@ -292,3 +294,36 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
)
assert rejected.status_code == 400
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
def test_retire_rejects_profile_bound_by_receipt_report_config(app):
"""绑定收料报表配置的 published 解析 Profile 退役必须被拒(退役守卫补查)。
背景:retire 此前只核查库存源(ShippingInventorySource)绑定,遗漏了
收料报表配置(ShippingReceiptReportConfig.parsing_profile_id)——入站文件
解析链会因规则退役静默失去规则。守卫补查后两者任一绑定都返回
SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED。
"""
from app import db
from app.models import ShippingReceiptReportConfig
from app.services.shipping_notice import inventory_parsing_profile
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
profile = _create_parsing_profile('MOVE_RETIRE_GUARD', status='published', purpose='inbound')
db.session.add(ShippingReceiptReportConfig(
inventory_source_id=source.id, parsing_profile_id=profile.id,
report_path_json={}, query_parameters_json=[],
))
db.session.commit()
profile_id = profile.id
# 关键断言:仅绑定收料配置(无库存源绑定)也必须拒绝退役,沿用既有错误码。
with pytest.raises(Exception) as exc_info:
inventory_parsing_profile.retire(profile_id)
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED'
# 关键断言:被拒后 Profile 状态保持 published,不得被半退役。
assert ShippingReceiptReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1
@@ -268,3 +268,70 @@ def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only():
# 回流旧写法(receipt_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。
assert source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()") > marker_init
assert "receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()" not in source
def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
"""按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。"""
from app import db
from app.models import ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_orphan_receipt_units
with app.app_context():
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
# 单元1:排队 5 分钟从未被领取(created_at 为锚,queued 分支);单元2:领取后
# 静默 5 分钟(started_at 为锚);单元3:30 秒前刚领取(健康在跑,不得误杀)。
stale_queued = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs',
callback_id='inbound-orphan-queued', status='queued', config_snapshot_json={},
created_at=datetime.utcnow() - timedelta(minutes=5),
)
stale_processing = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs',
callback_id='inbound-orphan-processing', status='processing', config_snapshot_json={},
created_at=datetime.utcnow() - timedelta(minutes=6),
started_at=datetime.utcnow() - timedelta(minutes=5),
)
fresh_processing = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs',
callback_id='inbound-orphan-fresh', status='processing', config_snapshot_json={},
created_at=datetime.utcnow() - timedelta(seconds=45),
started_at=datetime.utcnow() - timedelta(seconds=30),
)
db.session.add_all([stale_queued, stale_processing, fresh_processing])
db.session.commit()
# [断言意图] 调拨工作台按需触发单元 schedule_run_id=NULL,不在 run 级扫描
# (recover_all_stale_receipt_rpa_schedule_runs 按 run 遍历)范围内;网页异常
# 关闭后回调永不到达,必须由本扫描终态化(2026-10-16 事故回归),健康单元原样;
# 与 run 级回收同口径:只标失败、写审计,绝不自动创建重试单元。
assert recover_all_stale_orphan_receipt_units() == 2
db.session.refresh(stale_queued)
db.session.refresh(stale_processing)
db.session.refresh(fresh_processing)
assert stale_queued.status == 'failed'
assert stale_queued.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT'
assert stale_queued.finished_at is not None
assert stale_processing.status == 'failed'
assert fresh_processing.status == 'processing'
assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=stale_queued.id).count() == 0
# [断言意图] 审计须含失败结果与 before/after 快照——与 run 级回收同语义由测试锁定。
timeout_event = ShippingAuditEvent.query.filter_by(
event_type='shipping_receipt_rpa_callback_timeout', aggregate_id=str(stale_queued.id),
).one()
assert timeout_event.result == 'failure'
assert (timeout_event.after_snapshot_json or {}).get('status') == 'failed'
def test_orphan_receipt_recovery_is_wired_into_per_tick_maintenance():
"""哨兵回归:孤儿单元回收必须挂在每轮领取维护区(与 run 级扫描同区同轮)。"""
import inspect
from app.services.schedule import queue_service
source = inspect.getsource(queue_service)
# [断言意图] 调用点必须与 run 级收料扫描同在每轮维护区且在其后;
# 缺席或回流启动一次性分支都会复现「长驻进程期间来源永久 fetching」事故。
marker_run_scan = source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()")
assert source.index("recover_all_stale_orphan_receipt_units()") > marker_run_scan
@@ -0,0 +1,121 @@
"""
tests/test_inventory_download_name.py
用途:锁定 build_inventory_download_name 的下载展示名规范化契约——
复用企微压缩包短名规则({seq}_{source}_{warehouse})并附加 exported_at
数据截止时间点;worker 原始登记名不受影响。
依赖:models.ShippingInventoryFile、inventory_file_store.build_inventory_download_name。
逻辑:pure_unit;长名规范化、规范名幂等、exported_at → rpa_run_no → mtime 回退链、
warehouse 连续重复段去重(AWSDU_AWSDU → AWSDU)、无 seq 前缀省略、
source/warehouse/时间点任一缺失时保持原名(禁止凭空造名)、空名回退 inventory_file_no。
"""
from __future__ import annotations
import os
from datetime import datetime
import pytest
from app.models import ShippingInventoryFile
from app.services.shipping_notice.inventory_file_store import (
build_inventory_download_name,
)
pytestmark = pytest.mark.pure_unit
_WORKER_LONG_NAME = '006_inventory_RUN2026101423006F54E_DSV360_AWSDU_AWSDU_20261014231148.xlsx'
def _inv_file(**overrides) -> ShippingInventoryFile:
"""构造不落库的快照行;默认字段对齐 prod 4510042199 批次的真实登记值。"""
defaults = dict(
inventory_file_no='INV-20261014-0001',
source_file_name=_WORKER_LONG_NAME,
source_code='DSV360',
warehouse_id='AWSDU',
warehouse_code='AWSDU',
exported_at=datetime(2026, 10, 14, 23, 11, 48),
rpa_run_no='RUN2026101423006F54E',
)
defaults.update(overrides)
return ShippingInventoryFile(**defaults)
def test_worker_long_name_normalized_with_exported_at():
"""worker 长名 + exported_at → 短名 + 数据截止时间点(到分钟)。"""
name = build_inventory_download_name(
_inv_file(), source_file_name=_WORKER_LONG_NAME,
)
# 关键断言:seq 保留与企微 zip 可对应;时间点来自 exported_at 而非尾部保存时刻
assert name == '006_DSV360_AWSDU_202610142311.xlsx'
def test_canonical_name_is_idempotent():
"""已是规范名的输入必须原样返回(幂等,不二次追加时间戳)。"""
canonical = '006_DSV360_AWSDU_202610142311.xlsx'
# 关键断言:规范形态命中 _DOWNLOAD_CANONICAL_RE 后零变化
assert build_inventory_download_name(
_inv_file(), source_file_name=canonical,
) == canonical
def test_exported_at_missing_falls_back_to_run_no_timestamp():
"""exported_at 缺失时回退 rpa_run_no 内嵌 RUN 时间戳(到分钟)。"""
name = build_inventory_download_name(
_inv_file(exported_at=None), source_file_name=_WORKER_LONG_NAME,
)
# 关键断言:RUN2026101423006F54E → 202610142300(截取 12 位到分钟)
assert name == '006_DSV360_AWSDU_202610142300.xlsx'
def test_time_falls_back_to_file_mtime(tmp_path):
"""exported_at 与 rpa_run_no 均缺失时回退托管文件 mtime。"""
target = tmp_path / 'worker.xlsx'
target.write_bytes(b'x')
os.utime(target, (1770000000, 1770000000))
name = build_inventory_download_name(
_inv_file(exported_at=None, rpa_run_no=None),
source_file_name=_WORKER_LONG_NAME, path=target,
)
# 关键断言:不抛错且生成带 12 位时间点的规范名(具体值随 mtime)
assert name.count('_') >= 3 and name.endswith('.xlsx')
assert 'DSV360' in name and 'AWSDU' in name
def test_warehouse_duplicated_segments_collapsed():
"""warehouse 值自身含连续重复段(AWSDU_AWSDU)时折叠为单段。"""
name = build_inventory_download_name(
_inv_file(warehouse_id='AWSDU_AWSDU'), source_file_name=_WORKER_LONG_NAME,
)
# 关键断言:token 级连续重复去重后不出现 AWSDU_AWSDU
assert name == '006_DSV360_AWSDU_202610142311.xlsx'
def test_missing_seq_prefix_omits_seq():
"""worker 原名无数字前缀时规范名省略 seq 段而非补 000。"""
name = build_inventory_download_name(
_inv_file(source_file_name='inventory_export.xlsx'),
source_file_name='inventory_export.xlsx',
)
# 关键断言:无 seq 时以 source 开头且不产生空段
assert name == 'DSV360_AWSDU_202610142311.xlsx'
def test_insufficient_info_keeps_original_name():
"""source 缺失等信息不足时保持 worker 原名(禁止凭空造名)。"""
original = _WORKER_LONG_NAME
name = build_inventory_download_name(
_inv_file(source_code=None), source_file_name=original,
)
# 关键断言:缺 source 时零变化,避免生成无法归因的文件名
assert name == original
def test_empty_source_file_name_falls_back_to_file_no():
"""空登记名回退 inventory_file_no + 小写后缀(既有行为不变)。"""
name = build_inventory_download_name(
_inv_file(source_file_name=None), source_file_name=None,
)
# 关键断言:与改造前 resolve_task_inventory_download 的兜底行为逐字一致
assert name == 'INV-20261014-0001.xlsx'
@@ -283,39 +283,39 @@ def test_sample_analysis_rejects_invalid_file(app, tmp_path):
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID'
def test_profile_draft_purpose_passthrough_creates_movement_profile(app, tmp_path):
"""purpose='movement' 必须透传到解析规则:异动草稿不依赖库存字段目录与匹配键。"""
def test_profile_draft_purpose_passthrough_creates_inbound_profile(app, tmp_path):
"""purpose='inbound' 必须透传到解析规则:入站草稿不依赖库存字段目录与匹配键。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
# 关键断言:movement 映射直接用定死领域字段码作键,不需要订单匹配键。
# 关键断言:inbound 映射直接用定死领域字段码作键,不需要订单匹配键。
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
'profile_code': 'MOVE_STD', 'display_name': '收料异动标准', 'purpose': 'movement',
'profile_code': 'MOVE_STD', 'display_name': '入站解析标准', 'purpose': 'inbound',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
'match_keys': None,
}, actor_id=None)
assert profile['purpose'] == 'movement'
assert profile['purpose'] == 'inbound'
assert profile['definition']['match_keys'] == []
assert set(profile['definition']['field_mapping']) == {'doc_no', 'material_code', 'quantity', 'movement_date'}
def test_publish_movement_profile_skips_order_match_key_contract(app, tmp_path):
"""发布 movement 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。"""
def test_publish_inbound_profile_skips_order_match_key_contract(app, tmp_path):
"""发布 inbound 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。"""
from app.services.shipping_notice import inventory_parsing_profile
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
'profile_code': 'MOVE_PUB', 'display_name': '收料异动发布', 'purpose': 'movement',
'profile_code': 'MOVE_PUB', 'display_name': '入站解析发布', 'purpose': 'inbound',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
'match_keys': None,
}, actor_id=None)
# 关键断言:movement 草稿必须能直接发布(有样本证据即可),match_keys 为空是合法契约。
# 关键断言:inbound 草稿必须能直接发布(有样本证据即可),match_keys 为空是合法契约。
published = inventory_parsing_profile.publish(profile['id'], actor_id=None)
assert published['status'] == 'published'
assert published['checksum']
+274 -23
View File
@@ -1,26 +1,46 @@
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验)。
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验 + 迁移往返)。
用途:验证 inventory_parsing_profile._validate_definition(purpose=...) 分支——
movement 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
不查库存字段目录、无 match_keys);inventory 维持既有 match_keys 校验。
并用 app fixture 校验模型 purpose 列默认 'inventory'。
依赖:inventory_parsing_profile._validate_definition(纯)、app(SQLite)。
逻辑:_required_movement_field_ids 纯函数校验;模型列默认值经 app fixture 校验。
inbound 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
不查库存字段目录、无 match_keys);onhand/outbound 维持既有库存字段目录 + match_keys
校验(outbound 出站文件结构就位,暂无运行时消费方)。并用 app fixture 校验模型
purpose 列默认 'onhand'、CHECK 约束三元枚举,以及 tt15 迁移 SQLite 真实往返。
依赖:inventory_parsing_profile._validate_definition / save_draft(纯 + app SQLite)、
migrations/versions/tt15(batch_alter_table 改枚举)、app_ctx(根 conftest app
fixture 上下文别名)。
逻辑:_required_movement_field_ids 纯函数校验;模型列默认值/约束经 app fixture 校验;
迁移往返按 tt13/tt14 同款模式(手工复刻前置表结构 + upgrade→downgrade→upgrade)。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import pytest
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
from app.core.errors import ValidationError
from app.services.shipping_notice.inventory_parsing_profile import _validate_definition
from app.services.shipping_notice.inventory_parsing_profile import _validate_definition, save_draft
pytestmark = pytest.mark.pure_unit
REVISION = "tt15b6a7b8c9d0"
DOWN_REVISION = "tt14a5f6a7b8c9"
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" / "versions"
def _movement_definition() -> dict:
@pytest.fixture
def app_ctx(app):
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
return app
def _inbound_definition() -> dict:
return {
'sheet_name': 'Movement',
'sheet_name': 'Inbound',
'header_row_index': 1,
'field_mapping': {
'doc_no': '单据编号',
@@ -37,33 +57,264 @@ def _movement_definition() -> dict:
}
def test_movement_definition_validates_fixed_fields():
"""movement 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。"""
definition = _validate_definition(_movement_definition(), purpose='movement')
def test_inbound_definition_validates_fixed_fields():
"""inbound 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。"""
definition = _validate_definition(_inbound_definition(), purpose='inbound')
assert definition['field_mapping']['doc_no'] == '单据编号'
assert definition['field_mapping']['quantity'] == '数量'
assert definition['match_keys'] == []
def test_movement_definition_missing_fixed_field_rejected():
"""movement 缺 movement_date → 阻断。"""
raw = dict(_movement_definition())
def test_inbound_definition_missing_fixed_field_rejected():
"""inbound 缺 movement_date → 阻断。"""
raw = dict(_inbound_definition())
raw['field_mapping'] = {k: v for k, v in raw['field_mapping'].items() if k != 'movement_date'}
with pytest.raises(ValidationError):
_validate_definition(raw, purpose='movement')
_validate_definition(raw, purpose='inbound')
def test_movement_definition_rejects_unknown_field():
"""movement 引用非定死领域字段 → 阻断。"""
raw = dict(_movement_definition())
def test_inbound_definition_rejects_unknown_field():
"""inbound 引用非定死领域字段 → 阻断。"""
raw = dict(_inbound_definition())
raw['field_mapping'] = {**raw['field_mapping'], 'free_text': '随意列'}
with pytest.raises(ValidationError):
_validate_definition(raw, purpose='movement')
_validate_definition(raw, purpose='inbound')
def test_model_purpose_column_defaults_to_inventory(app):
"""模型 purpose 列默认 'inventory'(既有行不回填)。"""
def test_purpose_enum_values():
"""模型 purpose 列:default/server_default 均为 'onhand',CHECK 枚举恰为三元新枚举。"""
from app.models.shipping_inventory_config import ShippingInventoryParsingProfile
col = ShippingInventoryParsingProfile.__table__.columns["purpose"]
assert col.default.arg == "onhand" and col.server_default.arg == "onhand"
check = next(c for c in ShippingInventoryParsingProfile.__table__.constraints
if getattr(c, "name", "") == "ck_shipping_inventory_parsing_profiles_purpose")
sql = str(getattr(check, "sqltext", check))
for value in ("onhand", "inbound", "outbound"):
assert value in sql
for legacy in ("'inventory'", "'movement'"):
assert legacy not in sql
def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_format: str = 'xlsx') -> int:
"""构造最小化样本结构证据,使 save_draft 遵循生产环境的表头绑定门禁。"""
from app import db
from app.models import ShippingInventoryStructureAnalysis
item = ShippingInventoryStructureAnalysis(
source_kind='sample_upload', source_file_name='sample.xlsx', storage_path=None,
file_checksum='c' * 64, file_format=file_format, analysis_status='ready',
structure_json={'candidates': [{
'sheet_name': sheet_name, 'header_row_index': 1, 'headers': headers,
'columns': [{'header': header, 'duplicate': False} for header in headers],
}]},
suggested_mapping_json={}, validation_summary_json={}, sample_rows_json=[], warning_json=[],
)
db.session.add(item)
db.session.flush()
return item.id
def _catalog_mapping() -> dict[str, str]:
"""以库存字段目录 ID 构造 onhand/outbound 用解析映射(目录分支端点)。"""
from app.models import ShippingInventoryField
rows = {item.field_code: item for item in ShippingInventoryField.query.filter_by(status='active').all()}
return {
str(rows['part_number'].id): 'Supplier Sku',
str(rows['reservation_id'].id): 'Reservation ID',
str(rows['available_qty'].id): 'Qty Available',
}
def test_draft_accepts_outbound_and_rejects_legacy(app_ctx):
"""save_draft purpose='outbound' 通过校验;purpose='movement' 报 SHIPPING.INVENTORY_PARSING_PROFILE_INVALID。"""
from app import db
from app.models import ShippingOrderField
# 出站文件结构就位:outbound 走库存字段目录分支(与 onhand 同构),需行级订单匹配键。
order_field = ShippingOrderField(field_code='part_number', scope='line', value_type='string')
db.session.add(order_field)
db.session.flush()
headers = ['Supplier Sku', 'Reservation ID', 'Qty Available']
outbound = save_draft({
'profile_code': 'OUT_STD', 'display_name': '出站结构就位', 'purpose': 'outbound',
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers),
'definition': {
'header_row_index': 1,
'field_mapping': _catalog_mapping(),
'match_keys': [{'order_field_id': order_field.id, 'inventory_field_id': next(iter(_catalog_mapping()))}],
},
}, actor_id=None)
assert outbound['purpose'] == 'outbound'
with pytest.raises(ValidationError) as exc_info:
save_draft({
'profile_code': 'LEGACY_MOVE', 'display_name': '旧异动用途', 'purpose': 'movement',
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers),
'definition': {'header_row_index': 1, 'field_mapping': _catalog_mapping(), 'match_keys': []},
}, actor_id=None)
# 关键断言:旧枚举 movement 已从白名单移除,fail-closed 报统一错误码。
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
def test_model_purpose_column_defaults_to_onhand(app):
"""模型 purpose 列默认 'onhand'(存量 inventory 行由 tt15 数据迁移回填)。"""
from app.models import ShippingInventoryParsingProfile
existing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first()
assert existing is not None and existing.purpose == 'inventory'
assert existing is not None and existing.purpose == 'onhand'
def _load_migration(revision: str):
"""按 revision 加载迁移模块(test_migration_widen_transfer_run_type 同款,不加载 Flask 应用)。"""
for path in MIGRATIONS_DIR.glob("*.py"):
if path.name.startswith(f"{revision}_"):
spec = importlib.util.spec_from_file_location(f"migration_{revision}", path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
raise AssertionError(f"migration file for revision {revision} not found")
def test_tt15_revision_chains_from_tt14_head():
"""tt15 必须存在且挂在 tt14a5f6a7b8c9(实施时实际单 head)之后,且用 batch 模式保 SQLite 往返。"""
for path in MIGRATIONS_DIR.glob("*.py"):
if path.name.startswith(f"{REVISION}_"):
text = path.read_text(encoding="utf-8")
assert f"revision = '{REVISION}'" in text or f'revision = "{REVISION}"' in text
assert f"down_revision = '{DOWN_REVISION}'" in text or f'down_revision = "{DOWN_REVISION}"' in text
# SQLite 不支持裸 DROP CONSTRAINT / ALTER COLUMN SET DEFAULT:必须走 batch_alter_table。
assert "batch_alter_table" in text
return
raise AssertionError(f"migration file for revision {REVISION} not found")
def _prestate_metadata() -> sa.MetaData:
"""复刻 tt15 前置(tt14 末态)的 shipping_inventory_parsing_profiles 表结构。
按建表迁移 b17e3d4c5a60 与后续加列迁移(fc1d2e3f4a5b/f83d9e0f1a2b/a4c7e9f1b2d3/
if1b2c3d4e5g)汇总列集,purpose 保持旧枚举(default 'inventory' + 旧 CHECK),
作为 tt15 往返的真实前置。历史链祖先众多(a0b1c2d3e4f6…),整链重放不成比例,
手工复刻与 tt13 前置基线做法一致。
"""
md = sa.MetaData()
sa.Table("users", md, sa.Column("id", sa.Integer(), primary_key=True))
sa.Table(
"shipping_inventory_structure_analyses", md,
sa.Column("id", sa.Integer(), primary_key=True),
)
sa.Table(
"shipping_inventory_parsing_profiles", md,
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("purpose", sa.String(length=16), nullable=False, server_default="inventory"),
sa.Column("profile_code", sa.String(length=64), nullable=False),
sa.Column("display_name", sa.String(length=128), nullable=False),
sa.Column("version", sa.Integer(), server_default="1", nullable=False),
sa.Column("status", sa.String(length=16), server_default="draft", nullable=False),
sa.Column("file_format", sa.String(length=16), server_default="xlsx", nullable=False),
sa.Column("definition_json", sa.JSON(), nullable=False),
sa.Column("checksum", sa.String(length=64), nullable=True),
sa.Column("structure_definition_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False),
sa.Column("exact_structure_fingerprint", sa.String(length=64), nullable=True),
sa.Column("compatibility_fingerprint", sa.String(length=64), nullable=True),
sa.Column("fingerprint_version", sa.String(length=32), nullable=True),
sa.Column("sample_analysis_id", sa.Integer(), nullable=True),
sa.Column("sample_evidence_history_json", sa.JSON(), server_default=sa.text("'[]'"), nullable=False),
sa.Column("created_by", sa.Integer(), nullable=True),
sa.Column("published_by", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("published_at", sa.DateTime(), nullable=True),
sa.UniqueConstraint("profile_code", "version", name="uq_inventory_parsing_profiles_code_version"),
sa.CheckConstraint(
"purpose IN ('inventory', 'movement')",
name="ck_shipping_inventory_parsing_profiles_purpose",
),
sa.ForeignKeyConstraint(["sample_analysis_id"], ["shipping_inventory_structure_analyses.id"]),
sa.ForeignKeyConstraint(["created_by"], ["users.id"]),
sa.ForeignKeyConstraint(["published_by"], ["users.id"]),
)
return md
_LEGACY_ROW_COLUMNS = (
"purpose, profile_code, display_name, version, status, file_format, "
"definition_json, structure_definition_json, sample_evidence_history_json, created_at"
)
def _insert_profile(connection, *, purpose: str, profile_code: str) -> None:
"""按旧枚举直接插入一条解析规则行(旧 CHECK 放行 inventory/movement)。"""
connection.execute(sa.text(
f"INSERT INTO shipping_inventory_parsing_profiles ({_LEGACY_ROW_COLUMNS}) "
f"VALUES ('{purpose}', '{profile_code}', '{profile_code} 规则', 1, 'published', 'xlsx', "
f"'{{}}', '{{}}', '[]', '2026-01-01 00:00:00')"
))
def _purpose_by_code(connection) -> dict[str, str]:
rows = connection.execute(sa.text(
"SELECT profile_code, purpose FROM shipping_inventory_parsing_profiles"
)).fetchall()
return {code: purpose for code, purpose in rows}
def _column_default(connection, column: str) -> str:
columns = {c["name"]: c for c in sa.inspect(connection).get_columns("shipping_inventory_parsing_profiles")}
return str(columns[column].get("default") or "")
def test_tt15_sqlite_roundtrip_upgrade_downgrade_upgrade():
"""SQLite 真实往返:upgrade 换枚举并迁数据 / downgrade 对称还原 / 再 upgrade。
[断言意图] 前置表(旧枚举 default 'inventory' + 旧 CHECK)就位后,tt15 的
batch DROP CHECK → 数据 UPDATE → ADD CHECK → SET DEFAULT 不丢列、不丢数据;
存量 inventory→onhand、movement→inbound 精确映射;新 CHECK 真实生效
(outbound 放行、旧值拒写);downgrade 对称(outbound/inbound→movement 结构就位
语义最接近),default/CHECK 翻转可回滚。
"""
engine = sa.create_engine("sqlite:///:memory:")
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
_prestate_metadata().create_all(connection)
_insert_profile(connection, purpose='inventory', profile_code='LEG_INV')
_insert_profile(connection, purpose='movement', profile_code='LEG_MOVE')
# 前置基线:旧 CHECK 放行 inventory/movement、拒新枚举。
_insert_profile(connection, purpose='movement', profile_code='BASE_MOVE')
assert "inventory" in _column_default(connection, "purpose")
migration = _load_migration(REVISION)
migration.op = operations
migration.upgrade()
# [断言意图] 数据迁移:inventory→onhand、movement→inbound。
assert _purpose_by_code(connection) == {
'LEG_INV': 'onhand', 'LEG_MOVE': 'inbound', 'BASE_MOVE': 'inbound',
}
# [断言意图] 列默认值翻转为 'onhand'。
assert "onhand" in _column_default(connection, "purpose")
# [断言意图] 新 CHECK 真实生效:outbound 放行、旧值 inventory 拒写。
_insert_profile(connection, purpose='outbound', profile_code='NEW_OUT')
with pytest.raises(sa.exc.IntegrityError):
_insert_profile(connection, purpose='inventory', profile_code='REJECT_OLD')
migration.downgrade()
# [断言意图] downgrade 对称:onhand→inventory,inbound/outbound→movement。
assert _purpose_by_code(connection) == {
'LEG_INV': 'inventory', 'LEG_MOVE': 'movement', 'BASE_MOVE': 'movement', 'NEW_OUT': 'movement',
}
assert "inventory" in _column_default(connection, "purpose")
# [断言意图] 旧 CHECK 还原:inventory 放行、新值 onhand 拒写。
_insert_profile(connection, purpose='inventory', profile_code='BACK_INV')
with pytest.raises(sa.exc.IntegrityError):
_insert_profile(connection, purpose='onhand', profile_code='REJECT_NEW')
migration.upgrade()
assert _purpose_by_code(connection) == {
'LEG_INV': 'onhand', 'LEG_MOVE': 'inbound', 'BASE_MOVE': 'inbound',
'NEW_OUT': 'inbound', 'BACK_INV': 'onhand',
}
assert "onhand" in _column_default(connection, "purpose")
@@ -12,6 +12,7 @@ from __future__ import annotations
import uuid
import re
from datetime import datetime
from io import BytesIO
from types import SimpleNamespace
from unittest.mock import patch
@@ -3483,3 +3484,168 @@ def test_summary_failed_run_does_not_project_document_completed_as_upload_comple
assert leaf['user_group'] == 'failed'
assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
assert leaf['ui_state']['primary_action']['code'] == 'reparse'
def _seed_reparse_pending_case(suffix: str):
"""构造「reparse_pending Case + 在途/终态后继 Run」的重解析盲窗现场。
返回 (user, agent, session, intake, document, source_run, case, successor_run)。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewStream
from app.services.shipping_notice.order_extraction_plan import (
ensure_order_extraction_plan,
)
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, agent, session, intake, document = _seed_run_input(suffix=suffix)
intake.source_type = 'eml'
source_run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
source_run.status = 'review_required'
source_run.phase = 'review_required'
# 服务层终态转换会释放 Intake 链接(run 终态收口);直接改状态须同样释放,
# 否则 PDF 级重解析互斥会把该文档视为仍被源 Run 占用。
for member in source_run.intakes:
member.released_at = datetime.utcnow()
plan = ensure_order_extraction_plan(source_run)
case = ShippingOrderReviewCase(
case_no=f'SORC-{suffix}',
run_id=source_run.id,
unit_id=plan.units[0].id,
document_id=document.id,
owner_user_id=user.id,
status='reparse_pending',
)
stream = ShippingOrderReviewStream(
document_id=document.id,
content_identity=(document.content_hash or suffix)[:96],
owner_user_id=user.id,
)
db.session.add_all([case, stream])
db.session.flush()
stream.current_case_id = case.id
case.stream_id = stream.id
# create_order_extraction_run 会在快照写入 review_reparse 标记
# (document_id/source_case_no),探测查询直接消费该标记。
successor_run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
reparse_of_run=source_run,
selected_document_id=document.id,
reparse_case_no=case.case_no,
)
db.session.commit()
return user, agent, session, intake, document, source_run, case, successor_run
def test_summary_projects_inflight_reparse_as_processing(app) -> None:
"""[回归] 重解析盲窗:reparse_pending Case 的后继 Run 在途时,摘要必须判
processing(处理中组)并保留接收解析阶段入口,不得下发任何动作,
也不能退化成无五阶段按钮的 waiting_human(2026-10-14 批次中心缺陷)。
"""
with app.app_context():
(
user, _agent, session, intake, document,
_source_run, _case, successor_run,
) = _seed_reparse_pending_case(suffix='SUMMARY-REPARSE-INFLIGHT')
assert successor_run.status == 'queued'
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
conv = payload['conversation_processing']
leaves = [
child
for rows in conv['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
]
leaf = next(
child for child in leaves
if int(child['source_summary']['document_id']) == int(document.id)
)
# 关键断言 1:在途重解析 = 系统处理中,不是待人工。
assert leaf['user_status'] == 'running'
assert leaf['user_group'] == 'processing'
assert leaf['status'] == 'processing'
assert leaf['stage'] == 'document_parsing'
assert conv['summary']['processing_files'] == 1
# 关键断言 2:不下发任何动作(服务端幂等复用在途后继,禁止再次提交)。
assert leaf['available_actions'] == []
assert leaf['primary_action'] is None
assert leaf['blocking_reason'] is None
# 关键断言 3:五阶段入口保留(接收解析为 current),按钮不再整排消失。
assert leaf['intake_parse_authorized'] is True
entries = leaf['ui_state']['lifecycle_entries']
assert [entry['code'] for entry in entries] == [
'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete',
]
assert entries[0]['state'] == 'current'
assert all(entry['state'] != 'current' for entry in entries[1:])
# 后继 Run 终态失败后(未收口前):无在途事实即回落 waiting_human 原判。
successor_run.status = 'failed'
db.session.commit()
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
leaves = [
child
for rows in payload['conversation_processing']['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
]
leaf = next(
child for child in leaves
if int(child['source_summary']['document_id']) == int(document.id)
)
assert leaf['user_status'] == 'waiting_human'
assert leaf['user_group'] == 'waiting_human'
assert leaf['intake_parse_authorized'] is False
def test_eml_leaf_projects_inflight_reparse_as_processing(app) -> None:
"""[回归] 全量投影同判词:reparse_pending 盲窗里的无 OT 叶子必须改判
processing 并保留接收解析入口,而不是按陈旧 Unit 事实投影成无入口待人工。
"""
from app.services.shipping_notice.shipping_processing_projection import (
_conversation_projection_load_context,
)
with app.app_context():
(
user, _agent, _session, intake, document,
source_run, _case, _successor_run,
) = _seed_reparse_pending_case(suffix='EML-REPARSE-INFLIGHT')
stale_unit = source_run.extraction_plan.units[0]
load_context = _conversation_projection_load_context([intake])
leaves = _eml_aggregate_document_children(
intake=intake,
order_task_children=[],
unit_by_document_id={document.id: stale_unit},
load_context=load_context,
)
assert document.id in load_context.active_reparse_document_ids
# 关键断言 1:与摘要同判词 —— 在途重识别 = 处理中。
assert leaves[0]['user_status'] == 'running'
assert leaves[0]['user_group'] == 'processing'
assert leaves[0]['stage'] == 'document_parsing'
# 关键断言 2:不下发动作,但接收解析阶段入口保留。
assert leaves[0]['available_actions'] == []
assert leaves[0]['primary_action'] is None
assert leaves[0]['intake_parse_authorized'] is True
entries = leaves[0]['ui_state']['lifecycle_entries']
assert len(entries) == 5
assert entries[0]['code'] == 'intake_parse'
assert entries[0]['state'] == 'current'
@@ -0,0 +1,18 @@
# Freight RPA 独立模块边界与单窗口同步发布
Freight RPA 的后端编排层原本寄生在 `services/shipping_notice/` 包内(约 10 个编排文件、6 个调度壳、12 条 Worker 回调路由散落在业务 blueprint),而 Windows Worker 早已通过「共享目录 trigger + HTTP 回调 + 心跳」与后端解耦,且 in_transit_transfer 已成为第二个消费方。2026-10-16 决策:把编排层收编为独立模块 `backend/app/services/freight_rpa/`(回调 blueprint `/api/freight-rpa/*`),与 onhand/inbound/outbound 术语改名合并实施;数据库表**全部留在原地**(阶段 A 只做模块归位),表所有权与「文件就绪」事件化重构留待阶段 B 单独立项。发布采用**单窗口同步发布**:批次 R(解耦+RPA 域新名)、S(shipping_notice 域 28 表 rename+存量数据迁移+前端大改名)、T(shipment→outbound)、D(文档收口)在同一发布窗口上线,后端+前端+Windows Worker 同窗口切换,**不做双路由、不留兼容层**。
模块定名 **freight_rpa 而非泛化 rpa**:env 命名空间 `FREIGHT_RPA_*` 是 AGENTS.md §8.1 红线,模块名与之一一对应;域中立件(心跳、凭据加解密、trigger 契约——Worker 侧 `scripts/freight_rpa/common/` 已是该形态)集中在 `freight_rpa/common/` 子层,未来出现第二个 RPA(如 HR RPA)时再上提为平台层。回调 URL 是写进 Worker 代码的跨进程契约,`/api/freight-rpa/*` 与未来的 `/api/hr-rpa/*` 天然并列、一次写对永不返工——这是本决策中最粘性的部分。
## Considered Options
- **泛化 `rpa` 模块**:被否。为尚不存在的第二个域预设接口(YAGNI),且 `rpa` 模块读 `FREIGHT_RPA_*` 变量名实不符;先域后平台的抽壳是廉价机械重构,反向特化更别扭。
- **回调 URL 短期双路由**:被否(用户拍板同步发布)。代价是发布窗口纪律变硬(暂停排程、禁止手动 RPA、备回滚镜像),换取无新旧路由并存期的简单性。
- **批次分开发布**:被否(用户统一测试)。实施顺序仍按 R→S→T→D(避免旧名搬两次家),但四批同一发布窗口,安全网依赖「全部迁移带可执行 downgrade + test 环境预演」。
## Consequences
- 发布窗口协议成为硬约束:暂停三个 RPA 排程任务、窗口内禁止工作台手动触发 RPA(retry_rpa/rpa-upload 也走回调)、CIFS 共享目录随窗口一次迁移、备好旧后端镜像与旧 Worker 包作为整体回滚单元。
- 本轮全部新迁移(28 表 rename、存量枚举值 UPDATE)必须带可执行 downgrade,并在 test 环境完整预演 upgrade→冒烟→downgrade→再 upgrade。
- `services/freight_rpa/` 不得 import `shipping_notice` 的 workflow/状态机模块(只 import models 与纯工具);表所有权裁决、回调事务化、`ShippingInventorySource` 拆分属于阶段 B,需新 ADR。
- 术语基线与 glossary 见 `docs/features/freight-rpa/GLOSSARY.md`;评估事实与分批清单见 `docs/superpowers/plans/2026-10-16-freight-rpa-decouple-and-rename-evaluation.md`。
+6 -5
View File
@@ -36,7 +36,7 @@
## 货代收料 RPA(2026-08)
- 保留现有库存 RPA 的 Worker、trigger、callback、快照和匹配链路;收料使用独立 `freight-receipt-rpa` 排程与 Worker。
- 保留现有库存 RPA 的 Worker、trigger、callback、快照和匹配链路;收料 RPA 使用独立 `freight-receipt-rpa` 排程与 Worker。
- 在既有库存站点维护一对一收料配置,仅复用 RPA Profile/登录/密文凭据;DBS 收料路径、受控条件和 Warehouse 独立保存;Crane 不维护 Warehouse 或查询条件。
- DBS 按 `站点 × Warehouse` 分别导出、原样归档并逐文件企微推送;报表日期不传,保持 NULL。Crane 每站点强制进入 `#/inbound-details-query`,以页面默认条件导出固定 `Inbound Details`。
- 排程接收人与库存排程完全解耦;接收人仅能查看/下载获授权文件,管理员可配置、手动运行、重试失败单元、重发通知。
@@ -896,9 +896,10 @@ XFA 模板管理端暂不启用字段脱敏,树、拆分预览和样本验证
## 在途仓自动调拨 Agent(2026-08)
- 需求:仓库管理人员按收料来源实例(DBS-AWSBI / DBS-AWSSG / CRANE-SZ)核对收料文件与 ERP 账面库存后生成 ERP 调拨单;DBS/Crane 仅分组,来源实例为执行边界。
- 手工两步:选择来源实例 → 预检明细核对后直接生成 ERP 调拨单(无独立确认页);当天收料不查询 ERP;数量严格相等才可执行;不支持部分调拨/容差/单位换算/批次拆分。
- 需求:仓库管理人员按出入站来源实例(DBS-AWSBI / DBS-AWSSG / CRANE-SZ)核对入站文件与 ERP 账面库存后生成 ERP 调拨单;DBS/Crane 仅分组,来源实例为执行边界。
- 手工两步:选择来源实例 → 预检明细核对后直接生成 ERP 调拨单(无独立确认页);当天入站不查询 ERP;数量严格相等才可执行;不支持部分调拨/容差/单位换算/批次拆分。
- ERP 写入由后端确定性服务与 Worker 完成,Dify 不得直接调用 ERP;Invoice No 幂等;结果未知只读禁自动重试;通知失败不改变 ERP 结果。
- 2026-09-24 写路径口径修订(ERP 建单接线后):执行粒度由「按行」修订为「按票」——同五元组(外部组织/来源实例/收料日期/拨出库位/拨入库位)明细聚合建一张 ERP 调拨票,提交时组建、worker 逐票异步执行;ERP 写入经集成连接器统一出口(database 直连写 ERP 中间表 → 触发建单 WS,配置在管理端维护)。人工关票为失败票(business_failed/technical_failed)例外出口:票作废、票内行脱离回可执行队列;**结果未知票禁止人工关闭后重建**(唯一双单路径),唯一正确动作 = 重新触发(复用原票号/时间戳只触发末步,ERP 幂等回原单号)或 ERP 查单后人工标记。配置配方与 SOP 红线见 [features/in-transit-transfer/technical.md](features/in-transit-transfer/technical.md) §10。
- 2026-10-14 需求升级(调拨类型配置化 + 库存异动档):调拨类型不再由代码枚举——运营在管理端「在途调拨类型」页自助创建/启停类型(四块配置:基本信息/数据范围规则/仓库定义/字段转换),新增调拨场景(HUB仓维修出、HUB仓间调拨出/入)零发版;建立库存异动档作为外部系统收料/出货记录的唯一平台镜像(收料全量落档,范围外记录也可见),匹配明细改为匹配时从档圈定生成、已执行记录档级封存防二次调拨;首页新增「待匹配」桶让已抓取未匹配的记录可见。上线前提=目标环境无存量调拨数据(业务方 2026-10-14 确认)。设计规格见 [superpowers/specs/2026-10-14-transfer-type-config-and-movement-ledger-design.md](superpowers/specs/2026-10-14-transfer-type-config-and-movement-ledger-design.md),运维手册 technical.md §11。
- 2026-09-24 写路径口径修订(ERP 建单接线后):执行粒度由「按行」修订为「按票」——同五元组(外部组织/来源实例/异动日期/拨出库位/拨入库位)明细聚合建一张 ERP 调拨票,提交时组建、worker 逐票异步执行;ERP 写入经集成连接器统一出口(database 直连写 ERP 中间表 → 触发建单 WS,配置在管理端维护)。人工关票为失败票(business_failed/technical_failed)例外出口:票作废、票内行脱离回可执行队列;**结果未知票禁止人工关闭后重建**(唯一双单路径),唯一正确动作 = 重新触发(复用原票号/时间戳只触发末步,ERP 幂等回原单号)或 ERP 查单后人工标记。配置配方与 SOP 红线见 [features/in-transit-transfer/technical.md](features/in-transit-transfer/technical.md) §10。
- 2026-10-14 需求升级(调拨类型配置化 + 库存异动档):调拨类型不再由代码枚举——运营在管理端「在途调拨类型」页自助创建/启停类型(四块配置:基本信息/数据范围规则/仓库定义/字段转换),新增调拨场景(HUB仓维修出、HUB仓间调拨出/入)零发版;建立库存异动档作为外部系统入站/出站记录的唯一平台镜像(入站全量落档,范围外记录也可见),匹配明细改为匹配时从档圈定生成、已执行记录档级封存防二次调拨;首页新增「待匹配」桶让已抓取未匹配的记录可见。上线前提=目标环境无存量调拨数据(业务方 2026-10-14 确认)。设计规格见 [superpowers/specs/2026-10-14-transfer-type-config-and-movement-ledger-design.md](superpowers/specs/2026-10-14-transfer-type-config-and-movement-ledger-design.md),运维手册 technical.md §11。
- 2026-10-15 需求升级(入站/出站统一 + 幂等修复):模块从单一入站单据假设改版为入站(inbound)/出站(outbound)统一——明细/单据列改异动口径(`movement_*`:异动日期/异动数量),解析规则 purpose 三枚举 onhand/inbound/outbound(出站结构就位、证据链路未建);异动档自然键扩为 8 成分(单据+行+进出标志+箱号/批号,真实 WMS 文件实测消除行塌缩静默丢行)且**异动日期非空才落档**(未完成/已取消行不入档);新增待匹配桶「清空并重新解析」——解析规则修改后按来源预检并从 MinIO 归档证据重建档行(单事务、任一文件解析失败整体中止一行不删、审计留痕)。设计规格见 [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。
- 完整规格见 [features/in-transit-transfer/minimum-implementation-spec.md](features/in-transit-transfer/minimum-implementation-spec.md)。
+45
View File
@@ -0,0 +1,45 @@
# Freight RPA(货代 RPA)
货代域的浏览器自动化能力:Windows Worker 按共享目录 trigger 驱动 Playwright 抓取货代系统(DSV/Crane)文件,经 HTTP 回调与心跳回到后端 `freight_rpa` 模块。术语基线继承 2026-10-15 入站/出站改版(ADR 见 `docs/adr/0003-freight-rpa-module-boundary.md`)。
## Language
**Onhand(在手库存)**:
货代系统导出的在手库存文件(DSV/Crane 库存报表)。代码、契约、目录一律用 onhand;中文用户文案用「库存」。
_Avoid_: inventory(代码/契约中已退役)
**Inbound(入站)**:
货代系统导出的入站(收货)文件,即原「收料报表」。代码、契约、目录一律用 inbound;中文用户文案用「入站」;指货代开出的原始单据本身时可保留「收料报表」称谓。
_Avoid_: receipt(代码/契约中已退役)
**Outbound(出站)**:
出站(发货)文件。抓取链路本期未实施,仅解析规则(purpose 枚举)与目录结构就位。
_Avoid_: shipment(代码/契约中已退役;合同付款域的 shipment 指「发货款」节点,不属于本语境)
**Worker**:
运行在货代终端的 Playwright 自动化进程,轮询 trigger → 驱动浏览器 → 写 drop → 回调后端。
_Avoid_: RPA 机器人、爬虫
**Trigger**:
后端投递到共享目录的 JSON 任务文件,四态契约 claim → processing → processed/failed,带 schema 版本(`freight_rpa.onhand.v1` / `freight_rpa.inbound.v1`)。
_Avoid_: 任务单、指令文件
**Drop(产物目录)**:
Worker 写回导出文件的共享目录,与 trigger 目录成对。
_Avoid_: 下载目录
**回调(Callback)**:
Worker 完成后对 `/api/freight-rpa/*` 端点的 HTTP 通知,是 Worker→后端唯一的完成信号。
_Avoid_: 上报、推送
**心跳(Heartbeat)**:
Worker 定期上报存活状态;Redis TTL 做快速判定,DB 为权威事实。
_Avoid_: 健康检查(指 HTTP 探活时)
**RPA Profile(登录凭据配置)**:
站点登录凭据的加密配置(Fernet,密钥 `FREIGHT_RPA_CREDENTIAL_KEY`),与库存源绑定。
_Avoid_: 账号配置、凭据明文
**站点(Source)**:
一个货代抓取目标(如 DSV AWS、Crane NA),持有 RPA Profile 与解析规则绑定。(注意:Source 的表归属 shipping_notice 域,阶段 B 才裁决所有权。)
_Avoid_: 账号、客户
+21 -13
View File
@@ -16,16 +16,16 @@ _Avoid_: 海外仓
### 在途调拨 · 外部系统记录
**收料登记 (Receipt Registration)**:
**入站登记 (Inbound Registration)**:
外部系统在货物实际到达 HUB 仓时所做的入库登记记录;「在途仓至HUB仓」调拨的数据来源。
_Avoid_: 入库单、ASN
**出货登记 (Shipment Registration)**:
外部系统记录货物从 HUB 仓出库的登记记录(维修出、HUB 间调拨出的数据来源;出货 RPA 尚未建设)。
_Avoid_: 出库单
**出站登记 (Outbound Registration)**:
外部系统记录货物从 HUB 仓出库的登记记录(维修出、HUB 间调拨出的数据来源;出站 RPA 尚未建设)。
_Avoid_: 出库单、出货登记
**库存异动档 (Movement Ledger)**:
平台数据库中保存的外部系统收料/出货记录镜像;调拨类型的数据范围以本档的字段为准圈定。
平台数据库中保存的外部系统入站/出站记录镜像;调拨类型的数据范围以本档的字段为准圈定。
_Avoid_: 流水表、异动流水
### 在途调拨 · 调拨类型
@@ -35,16 +35,16 @@ _Avoid_: 流水表、异动流水
_Avoid_: 调拨单类型
**范围规则 (Scope Rule)**:
决定一个调拨类型从库存异动档纳入哪些记录的规则,按「字段 + 匹配方式 + 值列表」配置(如:收料单号前缀属于 HOM/HOX/WTP);由管理界面维护,不暴露 JSON。
决定一个调拨类型从库存异动档纳入哪些记录的规则,按「字段 + 匹配方式 + 值列表」配置(如:出入站单号前缀属于 HOM/HOX/WTP);由管理界面维护,不暴露 JSON。
**在途仓至HUB仓 (In-Transit to HUB)**:
第一个上线场景:货物到达 HUB 仓后,凭收料登记将在途仓库存调拨至 HUB 仓。范围规则现状=收料单号前缀 HOM/HOX/WTP。
第一个上线场景:货物到达 HUB 仓后,凭入站登记将在途仓库存调拨至 HUB 仓。范围规则现状=出入站单号前缀 HOM/HOX/WTP。
**HUB仓维修出 (HUB Repair Out)**:
货物从 HUB 仓送去维修:凭出货登记做 HUB 仓→维修仓的调拨;维修仓(目的仓)由调拨类型定义。待出货登记数据可用。
货物从 HUB 仓送去维修:凭出站登记做 HUB 仓→维修仓的调拨;维修仓(目的仓)由调拨类型定义。待出站登记数据可用。
**HUB仓间调拨 (HUB to HUB)**:
HUB 仓之间的调拨,分两个方向:**调拨出**凭出货登记、目的仓由调拨类型定义;**调拨入**凭收料登记、来源仓由调拨类型定义。待出货登记数据可用。
HUB 仓之间的调拨,分两个方向:**调拨出**凭出站登记、目的仓由调拨类型定义;**调拨入**凭入站登记、来源仓由调拨类型定义。待出站登记数据可用。
**仓库定义 (Warehouse Definition)**:
调拨类型上对「拨出仓库」「拨入仓库」两个角色的配置;每个角色的仓库来源可为**映射档**(沿用来源实例的仓库映射解析)或**固定值**(类型上直接指定仓库编码,可覆盖法人)。
@@ -57,12 +57,20 @@ _Avoid_: 仓库映射(专指映射档本身)
**匹配明细 (Matching Item)**:
一次匹配从异动档圈定并永久绑定的执行明细行,承载库存核对结果、执行状态与 ERP 单据关联;自创建起归属唯一匹配。
_Avoid_: 待办行、收料明细
_Avoid_: 待办行、入站明细
**记录类型 (Record Kind)**:
异动档记录的收料/出货属性,由解析文件种类在落档时声明写入;与数据行的出入库码交叉校验,不一致即异常。
异动档记录的入站/出站属性(inbound/outbound),由解析文件种类在落档时声明写入;与数据行的出入库码交叉校验,不一致即异常。
_Avoid_: 单据类型
**收料来源实例 (Receipt Source Instance)**:
一个外部系统的收料数据抓取通道(如 DSV360_AWSBI_BYAWSCMH01),调拨按来源实例为执行边界;本身也是范围规则可用的字段之一。
**解析类型 (Parsing Purpose)**:
已发布解析规则的适用文件种类枚举:`onhand`=库存文件、`inbound`=入站文件、`outbound`=出站文件;收料配置(入站证据绑定)只能绑定 `inbound` 规则。
_Avoid_: 库存/异动两值旧枚举(inventory/movement)
**出入站来源实例 (Inbound Source Instance)**:
一个外部系统的入站数据抓取通道(如 DSV360_AWSBI_BYAWSCMH01),调拨按来源实例为执行边界;本身也是范围规则可用的字段之一。入站证据=收料报表产物(shipping_notice 域收料 RPA 抓取,该域术语保留)。
_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 旧名时按本条映射理解。
_Avoid_: 把「收料」当作独立业务概念(在途调拨域已统一为入站);未经立项更名 shipping_notice 域保留的 receipt 旧名;新增代码用「收料」指代在途调拨业务
@@ -35,12 +35,12 @@
<div class="nav-label">最近对话</div>
<div class="history">
<button class="active" data-action="go-chat"><b>在途仓自动调拨</b><span>新建会话</span></button>
<button data-action="go-precheck"><b>DBS 昨日收料预检</b><span>PRE-20260818-001</span></button>
<button data-action="go-precheck"><b>DBS 昨日入站预检</b><span>PRE-20260818-001</span></button>
<button data-action="go-run"><b>自动调拨结果</b><span>AUTO-20260818-0900</span><i class="dot"></i></button>
<button data-action="go-backlog"><b>待处理调拨</b><span>6 笔可恢复异常</span><i class="dot bad"></i></button>
<div class="history-divider"></div>
<div class="history-label">评审对话走查(演示)</div>
<button class="walkthrough" data-action="chat-scene-intent"><b>处理昨天 DBS-AWSBI 的收料</b><span>发起调拨意图</span></button>
<button class="walkthrough" data-action="chat-scene-intent"><b>处理昨天 DBS-AWSBI 的入站</b><span>发起调拨意图</span></button>
<button class="walkthrough" data-action="chat-scene-status"><b>还有哪些待处理调拨?</b><span>历史待办状态</span></button>
<button class="walkthrough" data-action="chat-scene-mismatch"><b>INV-031 为什么不可调拨?</b><span>数量不一致说明</span></button>
<button class="walkthrough" data-action="chat-scene-recovery"><b>我已在 ERP 处理好库存,如何复查?</b><span>异常 ERP 复查</span></button>
@@ -59,10 +59,10 @@
const $ = id => document.getElementById(id);
const S = { selected:new Set(['DBS-AWSBI']), collapsed:new Set(), businessDate:'2026-08-18', backlogTab:'recoverable', modal:null, toastTimer:null, precheckRequery:'initial', historyOpen:false };
const sources = [
{ platform:'DBS', code:'DBS-AWSBI', name:'AWSBI 在途仓', warehouse:'AWSBI-TRANSIT', enabled:true, file:{ name:'DBS-AWSBI-receipt-20260818-v3.xlsx', downloadedAt:'RPA 下载于 08:00' } },
{ platform:'DBS', code:'DBS-AWSSG', name:'AWSSG 在途仓', warehouse:'AWSSG-TRANSIT', enabled:true, file:{ name:'DBS-AWSSG-receipt-20260818-v2.xlsx', downloadedAt:'RPA 下载于 08:02' } },
{ platform:'DBS', code:'DBS-AWSMY', name:'AWSMY 在途仓', warehouse:'AWSMY-TRANSIT', enabled:true, file:{ name:'DBS-AWSMY-receipt-20260818-v1.xlsx', downloadedAt:'RPA 下载于 08:05' } },
{ platform:'Crane', code:'CRANE-SZ', name:'深圳在途仓', warehouse:'CRANE-SZ-TRANSIT', enabled:true, file:{ name:'CRANE-SZ-receipt-20260818-v4.xlsx', downloadedAt:'RPA 下载于 08:01' } },
{ platform:'DBS', code:'DBS-AWSBI', name:'AWSBI 在途仓', warehouse:'AWSBI-TRANSIT', enabled:true, file:{ name:'DBS-AWSBI-inbound-20260818-v3.xlsx', downloadedAt:'RPA 下载于 08:00' } },
{ platform:'DBS', code:'DBS-AWSSG', name:'AWSSG 在途仓', warehouse:'AWSSG-TRANSIT', enabled:true, file:{ name:'DBS-AWSSG-inbound-20260818-v2.xlsx', downloadedAt:'RPA 下载于 08:02' } },
{ platform:'DBS', code:'DBS-AWSMY', name:'AWSMY 在途仓', warehouse:'AWSMY-TRANSIT', enabled:true, file:{ name:'DBS-AWSMY-inbound-20260818-v1.xlsx', downloadedAt:'RPA 下载于 08:05' } },
{ platform:'Crane', code:'CRANE-SZ', name:'深圳在途仓', warehouse:'CRANE-SZ-TRANSIT', enabled:true, file:{ name:'CRANE-SZ-inbound-20260818-v4.xlsx', downloadedAt:'RPA 下载于 08:01' } },
{ platform:'Crane', code:'CRANE-SG', name:'新加坡在途仓', warehouse:'CRANE-SG-TRANSIT', enabled:true, file:null },
{ platform:'Crane', code:'CRANE-HK', name:'香港在途仓', warehouse:'CRANE-HK-TRANSIT', enabled:false, file:null }
];
@@ -75,13 +75,13 @@
const setHeader = (sub,crumb) => { $('sub-title').textContent=sub; $('crumb').textContent=crumb; };
const facts = rows => `<div class="facts">${rows.map(([k,v])=>`<div class="fact"><span>${k}</span><b>${v}</b></div>`).join('')}</div>`;
const chatScenarios = {
welcome:{ label:'开始使用', user:'我想处理昨天的在途仓收料。', reply:'可以。我会先帮你进入来源实例选择,再由业务页面创建预检。DBS、Crane 是平台分组;实际选择单位是来源实例,例如 DBS-AWSBI。', evidence:'尚未创建调拨任务;不会读取 RPA 或查询 ERP。', action:'go-source', actionLabel:'选择处理范围' },
rule:{ label:'业务规则', user:'为什么今天不能调拨?', reply:'当天收料尚未成熟,不能进入 ERP 库存查询或调拨写入。系统默认处理昨天及更早的收料日期;当天 Invoice 会保留为 not_matured,待后续业务日期再处理。', evidence:'规则边界:not_matured 不查询 ERP、不创建 ERP 单据。', action:'go-source', actionLabel:'查看可选业务日期与来源' },
welcome:{ label:'开始使用', user:'我想处理昨天的在途仓入站。', reply:'可以。我会先帮你进入来源实例选择,再由业务页面创建预检。DBS、Crane 是平台分组;实际选择单位是来源实例,例如 DBS-AWSBI。', evidence:'尚未创建调拨任务;不会读取 RPA 或查询 ERP。', action:'go-source', actionLabel:'选择处理范围' },
rule:{ label:'业务规则', user:'为什么今天不能调拨?', reply:'当天入站尚未成熟,不能进入 ERP 库存查询或调拨写入。系统默认处理昨天及更早的异动日期;当天 Invoice 会保留为 not_matured,待后续业务日期再处理。', evidence:'规则边界:not_matured 不查询 ERP、不创建 ERP 单据。', action:'go-source', actionLabel:'查看可选业务日期与来源' },
status:{ label:'待处理状态', user:'现在还有多少待处理调拨?', reply:'演示数据中有 6 笔可恢复异常、2 笔已人工关闭,以及 1 笔结果未知。三类状态的允许操作不同,不能混合处理。', evidence:'可恢复异常可仅重查 ERP;已关闭可恢复;结果未知只读。', action:'go-backlog', actionLabel:'查看待处理调拨' },
intent:{ label:'发起调拨', user:'查询昨天 DBS-AWSBI 的可调拨数据。', reply:'我已理解为发起调拨意图,但不会直接写入 ERP。请先在页面选择 DBS-AWSBI 和业务日期,创建预检后核对并勾选严格匹配的 Invoice。', evidence:'需要经过:选择范围 → 预检核对 → 生成调拨单。', action:'go-source', actionLabel:'选择 DBS-AWSBI 并预检' },
progress:{ label:'文件与预检进度', user:'系统现在在做什么?', reply:'当创建预检时,系统会按来源实例显示真实阶段:优先使用任务创建前的最新有效收料文件;如果该文件不存在,才实时抓取并等待 RPA 回调。文件确定后,再汇总 Invoice 并查询 ERP。', evidence:'实时抓取期间会持续展示来源实例、阶段和等待原因;任务创建后文件版本冻结。', action:'go-source', actionLabel:'进入来源实例与预检流程' },
mismatch:{ label:'不可调拨原因', user:'INV-031 为什么不可调拨?', reply:'该 Invoice 当前收料数量为 300 PCS、ERP 账面库存为 280 PCS,未满足严格等量条件,因此不会进入 ERP 写入范围。', evidence:'可在 ERP 人工处理后,仅重新查询该异常的 ERP 库存;不会重新抓 RPA 或替换冻结文件。', action:'go-precheck', actionLabel:'查看 INV-031 预检与复查入口' },
recovery:{ label:'ERP 处理后复查', user:'我已经在 ERP 处理好了库存,下一步怎么做?', reply:'请进入原预检页,点击“我已处理 ERP,重新查询异常库存”。系统会为异常 Invoice 新增一条 ERP 查询 Attempt;若严格匹配,才会自动加入可生成调拨单范围。', evidence:'复查不更新 RPA 文件、不改变收料快照、不写入 ERP。', action:'go-precheck', actionLabel:'进入异常预检页' },
progress:{ label:'文件与预检进度', user:'系统现在在做什么?', reply:'当创建预检时,系统会按来源实例显示真实阶段:优先使用任务创建前的最新有效入站文件;如果该文件不存在,才实时抓取并等待 RPA 回调。文件确定后,再汇总 Invoice 并查询 ERP。', evidence:'实时抓取期间会持续展示来源实例、阶段和等待原因;任务创建后文件版本冻结。', action:'go-source', actionLabel:'进入来源实例与预检流程' },
mismatch:{ label:'不可调拨原因', user:'INV-031 为什么不可调拨?', reply:'该 Invoice 当前入站数量为 300 PCS、ERP 账面库存为 280 PCS,未满足严格等量条件,因此不会进入 ERP 写入范围。', evidence:'可在 ERP 人工处理后,仅重新查询该异常的 ERP 库存;不会重新抓 RPA 或替换冻结文件。', action:'go-precheck', actionLabel:'查看 INV-031 预检与复查入口' },
recovery:{ label:'ERP 处理后复查', user:'我已经在 ERP 处理好了库存,下一步怎么做?', reply:'请进入原预检页,点击“我已处理 ERP,重新查询异常库存”。系统会为异常 Invoice 新增一条 ERP 查询 Attempt;若严格匹配,才会自动加入可生成调拨单范围。', evidence:'复查不更新 RPA 文件、不改变入站快照、不写入 ERP。', action:'go-precheck', actionLabel:'进入异常预检页' },
safety:{ label:'结果未知说明', user:'为什么不能重试结果未知?', reply:'ERP 调用未返回可确认的成功或失败时,系统无法证明没有产生单据。再次提交存在重复写入风险,所以该状态只读,必须由 ERP 管理员线下核实。', evidence:'禁止:重试、关闭、恢复、重新执行;允许:查看已知事实与审计。', action:'go-unknown', actionLabel:'查看结果未知事项' },
schedule:{ label:'自动调拨结果', user:'最近一次自动调拨执行得怎么样?', reply:'自动排程按来源实例独立处理:每个实例使用其任务开始前的最新有效文件,分别预检、写入和汇总通知。一个实例失败不会阻断其他实例。', evidence:'演示 Run:DBS-AWSBI 成功 18 项;CRANE-SZ 文件获取超时并保留异常证据。', action:'go-run', actionLabel:'查看最近自动 Run' }
};
@@ -89,29 +89,29 @@
function chatPage(){
setHeader('Chat 首页 · 对话解释与业务入口','/chat/:agentId');
const key=chatScenario(), scene=key && chatScenarios[key];
const welcome=`<div class="chat-home-head"><div class="welcome-mark">AI</div><h1>你好,您已进入<span>在途仓自动调拨 Agent</span></h1><p>我会解释规则、展示收料文件与 ERP 查询进度;需要改变业务数据时,请在对应页面点击按钮确认。</p></div><section class="chat-todo-section" aria-label="今日待办"><p class="chat-todo-label">今日待办</p><div class="chat-today"><button class="today-item" data-action="go-source"><i class="today-icon">+</i><span><b>发起今日调拨预检</b><span>选择来源实例后,系统默认以昨天为业务日期处理可成熟收料。</span></span><i class="today-go">›</i></button></div></section><section class="chat-todo-section" aria-label="历史待办"><p class="chat-todo-label">历史待办</p><div class="chat-pending"><button class="pending-item primary" data-action="go-backlog-recoverable"><span class="pending-count">6</span><b>可恢复异常</b><span>可重新查询 ERP 库存后继续处理</span></button><button class="pending-item muted" data-action="go-backlog-closed"><span class="pending-count">2</span><b>已人工关闭</b><span>可查看原因并恢复处理</span></button><button class="pending-item warning" data-action="go-unknown"><span class="pending-count">1</span><b>结果未知</b><span>只读,需线下核实 ERP 事实</span></button></div></section>`;
const thread=scene?`<div class="chat-thread"><div class="bubble user-msg">${scene.user}</div><div class="bubble">${scene.reply}</div><div class="scope"><div><b>系统状态 / 可核验依据</b><span>${scene.evidence}</span></div></div><div class="chat-action">${button(scene.actionLabel,scene.action,'primary')}</div><div class="notice warn"><i>!</i><span>对话不会绕过业务按钮直接发起 ERP 写入;当天收料不会进入 ERP 查询或调拨。</span></div></div>`:welcome;
const welcome=`<div class="chat-home-head"><div class="welcome-mark">AI</div><h1>你好,您已进入<span>在途仓自动调拨 Agent</span></h1><p>我会解释规则、展示入站文件与 ERP 查询进度;需要改变业务数据时,请在对应页面点击按钮确认。</p></div><section class="chat-todo-section" aria-label="今日待办"><p class="chat-todo-label">今日待办</p><div class="chat-today"><button class="today-item" data-action="go-source"><i class="today-icon">+</i><span><b>发起今日调拨预检</b><span>选择来源实例后,系统默认以昨天为业务日期处理可成熟入站。</span></span><i class="today-go">›</i></button></div></section><section class="chat-todo-section" aria-label="历史待办"><p class="chat-todo-label">历史待办</p><div class="chat-pending"><button class="pending-item primary" data-action="go-backlog-recoverable"><span class="pending-count">6</span><b>可恢复异常</b><span>可重新查询 ERP 库存后继续处理</span></button><button class="pending-item muted" data-action="go-backlog-closed"><span class="pending-count">2</span><b>已人工关闭</b><span>可查看原因并恢复处理</span></button><button class="pending-item warning" data-action="go-unknown"><span class="pending-count">1</span><b>结果未知</b><span>只读,需线下核实 ERP 事实</span></button></div></section>`;
const thread=scene?`<div class="chat-thread"><div class="bubble user-msg">${scene.user}</div><div class="bubble">${scene.reply}</div><div class="scope"><div><b>系统状态 / 可核验依据</b><span>${scene.evidence}</span></div></div><div class="chat-action">${button(scene.actionLabel,scene.action,'primary')}</div><div class="notice warn"><i>!</i><span>对话不会绕过业务按钮直接发起 ERP 写入;当天入站不会进入 ERP 查询或调拨。</span></div></div>`:welcome;
return `<section class="page"><div class="chat-home">${thread}<div class="chat-input-wrap"><div class="chat-input"><textarea id="chat-input" aria-label="对话输入" rows="1" placeholder="问我任何事..."></textarea><div class="chat-input-tools"><button type="button" aria-label="语音功能" title="语音功能">♩</button><button type="button" class="kb-pill" aria-label="企业知识库" disabled>▤ 企业知识库⌄</button><button type="button" class="send" aria-label="发送" title="发送" data-action="chat-send">➤</button></div></div><div class="chat-input-hint">AI 可能会犯错,请核实重要信息。</div></div></div></section>`;
}
function sourcePage(){
setHeader('来源实例选择 · 本次调拨范围','/chat/:agentId?mode=transfer-source-selection');
const groups=[...new Set(sources.map(x=>x.platform))];
return `<section class="page"><div class="page-head">${button('← 返回对话','go-chat')}<div style="flex:1"><h1>选择收料来源实例</h1><p>DBS、Crane 仅为平台分组。请勾选实际需要处理的在途仓实例;未来新增实例会自动显示在对应平台。</p></div></div><div class="card"><div class="card-h"><div><h2>本次处理范围</h2><p>已选择的实例会独立准备文件、解析、预检与审计。</p></div></div><div class="card-b"><div class="source-toolbar"><input id="source-search" placeholder="搜索实例名称或编码,例如 AWSBI" /><button class="btn" data-action="select-enabled">全选已启用</button><button class="btn" data-action="clear-sources">清空</button><span class="count" id="source-count"></span></div><div id="source-groups">${groups.map(platform=>sourceGroup(platform)).join('')}</div><div class="sticky-actions">${button('取消','go-chat')}${button('确认范围并预检','start-precheck','primary')}</div></div></div></section>`;
return `<section class="page"><div class="page-head">${button('← 返回对话','go-chat')}<div style="flex:1"><h1>选择入站来源实例</h1><p>DBS、Crane 仅为平台分组。请勾选实际需要处理的在途仓实例;未来新增实例会自动显示在对应平台。</p></div></div><div class="card"><div class="card-h"><div><h2>本次处理范围</h2><p>已选择的实例会独立准备文件、解析、预检与审计。</p></div></div><div class="card-b"><div class="source-toolbar"><input id="source-search" placeholder="搜索实例名称或编码,例如 AWSBI" /><button class="btn" data-action="select-enabled">全选已启用</button><button class="btn" data-action="clear-sources">清空</button><span class="count" id="source-count"></span></div><div id="source-groups">${groups.map(platform=>sourceGroup(platform)).join('')}</div><div class="sticky-actions">${button('取消','go-chat')}${button('确认范围并预检','start-precheck','primary')}</div></div></div></section>`;
}
function sourceGroup(platform){ const items=sources.filter(x=>x.platform===platform); const collapsed=S.collapsed.has(platform); const fileRow=s=>s.file?`<div class="source-file"><span class="source-file-name" title="${text(s.file.name)}">${text(s.file.name)}</span><button class="icon-button" type="button" data-action="download-source-${s.code}" aria-label="下载 ${text(s.code)} 的收料 Excel" title="下载本地 RPA 收料 Excel">↓</button></div><span class="source-file-meta">${s.file.downloadedAt}</span>`:`<div class="source-file"><span class="source-file-empty">暂无可下载的本地 RPA 收料 Excel</span><button class="icon-button" type="button" disabled aria-label="暂无可下载文件" title="暂无可下载文件">↓</button></div>`; return `<section class="source-group" data-platform="${platform}"><div class="source-group-head"><b>${platform}</b><span>${items.filter(x=>x.enabled).length} 个已启用实例</span><button data-action="toggle-${platform}">${collapsed?'展开':'收起'}</button></div><div class="source-list" ${collapsed?'style="display:none"':''}>${items.map(s=>`<div class="source-item" data-source-row="${s.code}"><input type="checkbox" data-source="${s.code}" ${S.selected.has(s.code)?'checked':''} ${s.enabled?'':'disabled'} /><div class="source-detail"><b>${s.code}</b><span>${s.name} · 来源仓 ${s.warehouse}${s.enabled?'':' · 未启用'}</span>${fileRow(s)}</div></div>`).join('')}</div></section>`; }
function sourceGroup(platform){ const items=sources.filter(x=>x.platform===platform); const collapsed=S.collapsed.has(platform); const fileRow=s=>s.file?`<div class="source-file"><span class="source-file-name" title="${text(s.file.name)}">${text(s.file.name)}</span><button class="icon-button" type="button" data-action="download-source-${s.code}" aria-label="下载 ${text(s.code)} 的入站 Excel" title="下载本地 RPA 收料报表 Excel">↓</button></div><span class="source-file-meta">${s.file.downloadedAt}</span>`:`<div class="source-file"><span class="source-file-empty">暂无可下载的本地 RPA 收料报表 Excel</span><button class="icon-button" type="button" disabled aria-label="暂无可下载文件" title="暂无可下载文件">↓</button></div>`; return `<section class="source-group" data-platform="${platform}"><div class="source-group-head"><b>${platform}</b><span>${items.filter(x=>x.enabled).length} 个已启用实例</span><button data-action="toggle-${platform}">${collapsed?'展开':'收起'}</button></div><div class="source-list" ${collapsed?'style="display:none"':''}>${items.map(s=>`<div class="source-item" data-source-row="${s.code}"><input type="checkbox" data-source="${s.code}" ${S.selected.has(s.code)?'checked':''} ${s.enabled?'':'disabled'} /><div class="source-detail"><b>${s.code}</b><span>${s.name} · 来源仓 ${s.warehouse}${s.enabled?'':' · 未启用'}</span>${fileRow(s)}</div></div>`).join('')}</div></section>`; }
function precheckPage(){
setHeader('调拨预检 · 冻结的文件与 ERP 匹配结果','/chat/:agentId?mode=transfer-precheck&precheck_id=PRE-20260819-001');
const loading=S.precheckRequery==='loading', matched=S.precheckRequery==='matched';
const inv031=loading
? `<tr class="disabled"><td><input type="checkbox" disabled /></td><td>DBS-AWSBI</td><td>MAT-10001</td><td>连接器组件</td><td>A 型 / 24PIN</td><td><b>INV-031</b></td><td>AWSBI-TRANSIT</td><td><span class="chip gray">查询中…</span></td><td>HUB-SZ</td><td>300 PCS</td><td><small>仅重新查询 ERP;收料文件保持冻结。</small></td></tr>`
? `<tr class="disabled"><td><input type="checkbox" disabled /></td><td>DBS-AWSBI</td><td>MAT-10001</td><td>连接器组件</td><td>A 型 / 24PIN</td><td><b>INV-031</b></td><td>AWSBI-TRANSIT</td><td><span class="chip gray">查询中…</span></td><td>HUB-SZ</td><td>300 PCS</td><td><small>仅重新查询 ERP;入站文件保持冻结。</small></td></tr>`
: matched
? `<tr><td><input type="checkbox" data-invoice="INV-031" checked /></td><td>DBS-AWSBI</td><td>MAT-10001</td><td>连接器组件</td><td>A 型 / 24PIN</td><td><b>INV-031</b></td><td>AWSBI-TRANSIT</td><td>300 PCS<br /><small>最新查询 10:06</small></td><td>HUB-SZ</td><td>300 PCS</td><td>${tag('可执行','good')}<br /><button class="link" data-action="show-requery-history">查看历史比对</button></td></tr>`
: `<tr class="disabled"><td><input type="checkbox" disabled /></td><td>DBS-AWSBI</td><td>MAT-10001</td><td>连接器组件</td><td>A 型 / 24PIN</td><td><b>INV-031</b></td><td>AWSBI-TRANSIT</td><td>280 PCS<br /><small>上次查询 09:12 · Attempt 1</small></td><td>HUB-SZ</td><td>300 PCS</td><td>${tag('数量不一致','warn')}<br /><button class="link" data-action="show-requery-history">查看历史比对</button></td></tr>`;
const summary=matched?'已选 4 张 · 2 条调拨路由 · 预计调拨总数量 2,600 PCS · 预计 ERP 单据 4 张':'已选 3 张 · 2 条调拨路由 · 预计调拨总数量 2,300 PCS · 预计 ERP 单据 3 张';
const hint=loading?'正在仅查询 INV-031 的 ERP 库存;不会重新抓 RPA、替换文件或写入 ERP。':matched?'INV-031 已在 Attempt 2 匹配并加入 DBS-AWSBI → HUB-SZ 路由;核对后可直接生成调拨单。':'如果已在 ERP 完成人工库存处理,可只重查数量不一致项。每次结果新增 Attempt,冻结文件不变。';
const resultSummary=matched?'可执行 4 张 · 当天收料 1 张':'可执行 3 张 · 数量不一致 1 张 · 当天收料 1 张';
const resultSummary=matched?'可执行 4 张 · 当天入站 1 张':'可执行 3 张 · 数量不一致 1 张 · 当天入站 1 张';
const selectedCount=matched?4:3;
return `<section class="page"><div class="page-head">${button('← 返回修改范围','go-source')}<div style="flex:1"><h1>调拨预检</h1><div class="precheck-meta"><span>业务日期 2026-08-18 · 收料文件已固定</span><span>·</span><button class="link" data-action="show-file">查看文件</button></div></div>${tag('预检完成','good')}</div><div class="card"><div class="card-h"><div><h2>处理进度</h2><p>按来源实例查看文件与 ERP 查询结果。</p></div></div><div class="card-b"><div class="stage-list"><div class="stage good"><i class="mark"></i><div><b>DBS-AWSBI · 已完成</b><span>收料文件已就绪,ERP 库存已查询。</span></div>${tag('预检完成','good')}</div><div class="stage warn"><i class="mark"></i><div><b>DBS-AWSSG · 当天收料</b><span>INV-041 未进入 ERP 查询或调拨范围。</span></div>${tag('1 项未成熟','warn')}</div><div class="stage good"><i class="mark"></i><div><b>CRANE-SZ · 已完成</b><span>收料文件已就绪,ERP 库存已查询。</span></div>${tag('预检完成','good')}</div></div></div></div><div class="card" style="margin-top:16px"><div class="card-h"><div><h2>调拨预检明细</h2><p>核对物料、来源与仓库;数量不一致请先在 ERP 处理后重新查询。</p></div>${button(loading?'正在查询异常 ERP 库存…':'我已处理 ERP,重新查询异常库存(1)','requery-precheck',loading?'':'primary').replace('<button ','<button '+(loading?'disabled ':''))}</div><div class="card-b"><div class="precheck-summary">${resultSummary.split(' · ').map(item=>tag(item,item.includes('可执行')?'good':item.includes('不一致')?'warn':'gray')).join('')}</div><div class="table-wrap"><table class="table transfer-precheck-table"><thead><tr><th></th><th>收料来源</th><th>料号</th><th>品名</th><th>规格</th><th>Invoice</th><th>拨出仓库</th><th>拨出数量</th><th>拨入仓库</th><th>拨入数量</th><th>预检结果</th></tr></thead><tbody><tr><td><input type="checkbox" data-invoice="INV-001" checked /></td><td>DBS-AWSBI</td><td>MAT-10001</td><td>连接器组件</td><td>A 型 / 24PIN</td><td><b>INV-001</b></td><td>AWSBI-TRANSIT</td><td>500 PCS</td><td>HUB-SZ</td><td>500 PCS</td><td>${tag('可执行','good')}</td></tr><tr><td><input type="checkbox" data-invoice="INV-002" checked /></td><td>DBS-AWSBI</td><td>MAT-10002</td><td>控制器组件</td><td>标准型 / 48V</td><td><b>INV-002</b></td><td>AWSBI-TRANSIT</td><td>1,200 PCS</td><td>HUB-SZ</td><td>1,200 PCS</td><td>${tag('可执行','good')}</td></tr><tr><td><input type="checkbox" data-invoice="INV-008" checked /></td><td>CRANE-SZ</td><td>MAT-20008</td><td>传感器模组</td><td>SZ-8 / IP67</td><td><b>INV-008</b></td><td>CRANE-SZ-TRANSIT</td><td>600 PCS</td><td>HUB-SH</td><td>600 PCS</td><td>${tag('可执行','good')}</td></tr>${inv031}<tr class="disabled"><td><input type="checkbox" disabled /></td><td>DBS-AWSSG</td><td>MAT-10041</td><td>连接器组件</td><td>B 型 / 16PIN</td><td><b>INV-041</b></td><td>—</td><td>—</td><td>—</td><td>400 PCS</td><td>${tag('当天收料','gray')}</td></tr></tbody></table></div><div class="notice ${matched?'good':loading?'':'warn'}"><i>${matched?'✓':loading?'i':'!'}</i><span>${hint}</span></div><div class="confirm-band"><div><b id="selected-summary">${summary}</b><br /><small>点击后将创建、审核并过账 ERP 调拨单。</small></div>${button(`生成 ${selectedCount} 张调拨单`,'execute','primary')}</div></div></div></section>`;
return `<section class="page"><div class="page-head">${button('← 返回修改范围','go-source')}<div style="flex:1"><h1>调拨预检</h1><div class="precheck-meta"><span>业务日期 2026-08-18 · 入站文件已固定</span><span>·</span><button class="link" data-action="show-file">查看文件</button></div></div>${tag('预检完成','good')}</div><div class="card"><div class="card-h"><div><h2>处理进度</h2><p>按来源实例查看文件与 ERP 查询结果。</p></div></div><div class="card-b"><div class="stage-list"><div class="stage good"><i class="mark"></i><div><b>DBS-AWSBI · 已完成</b><span>入站文件已就绪,ERP 库存已查询。</span></div>${tag('预检完成','good')}</div><div class="stage warn"><i class="mark"></i><div><b>DBS-AWSSG · 当天入站</b><span>INV-041 未进入 ERP 查询或调拨范围。</span></div>${tag('1 项未成熟','warn')}</div><div class="stage good"><i class="mark"></i><div><b>CRANE-SZ · 已完成</b><span>入站文件已就绪,ERP 库存已查询。</span></div>${tag('预检完成','good')}</div></div></div></div><div class="card" style="margin-top:16px"><div class="card-h"><div><h2>调拨预检明细</h2><p>核对物料、来源与仓库;数量不一致请先在 ERP 处理后重新查询。</p></div>${button(loading?'正在查询异常 ERP 库存…':'我已处理 ERP,重新查询异常库存(1)','requery-precheck',loading?'':'primary').replace('<button ','<button '+(loading?'disabled ':''))}</div><div class="card-b"><div class="precheck-summary">${resultSummary.split(' · ').map(item=>tag(item,item.includes('可执行')?'good':item.includes('不一致')?'warn':'gray')).join('')}</div><div class="table-wrap"><table class="table transfer-precheck-table"><thead><tr><th></th><th>入站来源</th><th>料号</th><th>品名</th><th>规格</th><th>Invoice</th><th>拨出仓库</th><th>拨出数量</th><th>拨入仓库</th><th>拨入数量</th><th>预检结果</th></tr></thead><tbody><tr><td><input type="checkbox" data-invoice="INV-001" checked /></td><td>DBS-AWSBI</td><td>MAT-10001</td><td>连接器组件</td><td>A 型 / 24PIN</td><td><b>INV-001</b></td><td>AWSBI-TRANSIT</td><td>500 PCS</td><td>HUB-SZ</td><td>500 PCS</td><td>${tag('可执行','good')}</td></tr><tr><td><input type="checkbox" data-invoice="INV-002" checked /></td><td>DBS-AWSBI</td><td>MAT-10002</td><td>控制器组件</td><td>标准型 / 48V</td><td><b>INV-002</b></td><td>AWSBI-TRANSIT</td><td>1,200 PCS</td><td>HUB-SZ</td><td>1,200 PCS</td><td>${tag('可执行','good')}</td></tr><tr><td><input type="checkbox" data-invoice="INV-008" checked /></td><td>CRANE-SZ</td><td>MAT-20008</td><td>传感器模组</td><td>SZ-8 / IP67</td><td><b>INV-008</b></td><td>CRANE-SZ-TRANSIT</td><td>600 PCS</td><td>HUB-SH</td><td>600 PCS</td><td>${tag('可执行','good')}</td></tr>${inv031}<tr class="disabled"><td><input type="checkbox" disabled /></td><td>DBS-AWSSG</td><td>MAT-10041</td><td>连接器组件</td><td>B 型 / 16PIN</td><td><b>INV-041</b></td><td>—</td><td>—</td><td>—</td><td>400 PCS</td><td>${tag('当天入站','gray')}</td></tr></tbody></table></div><div class="notice ${matched?'good':loading?'':'warn'}"><i>${matched?'✓':loading?'i':'!'}</i><span>${hint}</span></div><div class="confirm-band"><div><b id="selected-summary">${summary}</b><br /><small>点击后将创建、审核并过账 ERP 调拨单。</small></div>${button(`生成 ${selectedCount} 张调拨单`,'execute','primary')}</div></div></div></section>`;
}
function runPage(){
setHeader('Run 结果 · ERP 调拨单','/chat/:agentId?mode=transfer-run&run_id=AUTO-20260818-0900');
@@ -120,13 +120,13 @@
documentRow('TRF-10001','AWSBI-TRANSIT','HUB-SZ',2,'1,700 PCS','<tr><td>MAT-10001</td><td>连接器组件</td><td>A 型 / 24PIN</td><td>INV-001</td><td>500 PCS</td></tr><tr><td>MAT-10002</td><td>控制器组件</td><td>标准型 / 48V</td><td>INV-002</td><td>1,200 PCS</td></tr>'),
documentRow('TRF-10008','CRANE-SZ-TRANSIT','HUB-SH',1,'600 PCS','<tr><td>MAT-20008</td><td>传感器模组</td><td>SZ-8 / IP67</td><td>INV-008</td><td>600 PCS</td></tr>')
].join('');
return `<section class="page"><div class="page-head">${button('← 返回对话','go-chat')}<div style="flex:1"><h1>自动调拨 Run 详情</h1><p>AUTO-20260818-0900 · 以 ERP 最终调拨单为准,展开可核对物料明细。</p></div>${tag('已完成','good')}</div><div class="card"><div class="card-h"><div><h2>执行结果</h2><p>本次已生成的 ERP 调拨单与未生成单据的异常分开显示。</p></div></div><div class="card-b">${facts([['业务日期','2026-08-18'],['已生成 ERP 单据','2 张'],['已完成物料','3 项'],['调拨总数量','2,300 PCS'],['未生成单据','2 项'],['触发方式','手动发起']])}<div class="result-downloads"><span>本次数据留底</span>${button('下载收料来源文件(2)','download-receipt-files')}${button('下载 ERP 库存表','download-erp-stock')}</div></div></div><div class="card" style="margin-top:16px"><div class="card-h"><div><h2>已生成 ERP 调拨单</h2><p>每条记录对应一张已创建、审核并过账的 ERP 单据。</p></div></div><div class="card-b">${documentRows}</div></div><div class="card" style="margin-top:16px"><div class="card-h"><div><h2>未生成 ERP 调拨单</h2><p>以下项目未写入 ERP,需要在处理完成后重新预检。</p></div>${button('进入待处理','go-backlog','primary')}</div><div class="card-b"><div class="table-wrap"><table class="table"><thead><tr><th>收料来源</th><th>Invoice</th><th>物料</th><th>未生成原因</th><th>当前事实</th></tr></thead><tbody><tr><td>DBS-AWSBI</td><td>INV-031</td><td>MAT-10001 · 连接器组件</td><td>${tag('数量不一致','warn')}</td><td>收料 300 PCS / ERP 280 PCS</td></tr><tr><td>DBS-AWSSG</td><td>INV-041</td><td>MAT-10041 · 连接器组件</td><td>${tag('当天收料','gray')}</td><td>未进入 ERP 查询或调拨范围</td></tr></tbody></table></div></div></div></section>`;
return `<section class="page"><div class="page-head">${button('← 返回对话','go-chat')}<div style="flex:1"><h1>自动调拨 Run 详情</h1><p>AUTO-20260818-0900 · 以 ERP 最终调拨单为准,展开可核对物料明细。</p></div>${tag('已完成','good')}</div><div class="card"><div class="card-h"><div><h2>执行结果</h2><p>本次已生成的 ERP 调拨单与未生成单据的异常分开显示。</p></div></div><div class="card-b">${facts([['业务日期','2026-08-18'],['已生成 ERP 单据','2 张'],['已完成物料','3 项'],['调拨总数量','2,300 PCS'],['未生成单据','2 项'],['触发方式','手动发起']])}<div class="result-downloads"><span>本次数据留底</span>${button('下载入站来源文件(2)','download-inbound-files')}${button('下载 ERP 库存表','download-erp-stock')}</div></div></div><div class="card" style="margin-top:16px"><div class="card-h"><div><h2>已生成 ERP 调拨单</h2><p>每条记录对应一张已创建、审核并过账的 ERP 单据。</p></div></div><div class="card-b">${documentRows}</div></div><div class="card" style="margin-top:16px"><div class="card-h"><div><h2>未生成 ERP 调拨单</h2><p>以下项目未写入 ERP,需要在处理完成后重新预检。</p></div>${button('进入待处理','go-backlog','primary')}</div><div class="card-b"><div class="table-wrap"><table class="table"><thead><tr><th>入站来源</th><th>Invoice</th><th>物料</th><th>未生成原因</th><th>当前事实</th></tr></thead><tbody><tr><td>DBS-AWSBI</td><td>INV-031</td><td>MAT-10001 · 连接器组件</td><td>${tag('数量不一致','warn')}</td><td>入站 300 PCS / ERP 280 PCS</td></tr><tr><td>DBS-AWSSG</td><td>INV-041</td><td>MAT-10041 · 连接器组件</td><td>${tag('当天入站','gray')}</td><td>未进入 ERP 查询或调拨范围</td></tr></tbody></table></div></div></div></section>`;
}
function backlogPage(){
setHeader('待处理调拨 · 可恢复、已关闭与结果未知分离','/chat/:agentId?mode=transfer-backlog');
const tab=S.backlogTab; const body=tab==='recoverable'?recoverable():tab==='closed'?closed():unknown(); return `<section class="page"><div class="page-head">${button('← 返回对话','go-chat')}<div style="flex:1"><h1>待处理调拨</h1><p>将可恢复异常、已人工关闭和结果未知隔离展示,避免把安全边界不同的事项混在同一张表中。</p></div></div><div class="card"><div class="card-h"><div><h2>跨 Run 待处理事项</h2><p>可恢复项只允许重新查询 ERP 库存,不更新文件、不抓 RPA、不直接写 ERP。</p></div></div><div class="card-b"><div class="tabs"><button class="tab ${tab==='recoverable'?'active':''}" data-action="tab-recoverable">可恢复异常 6</button><button class="tab ${tab==='closed'?'active':''}" data-action="tab-closed">已人工关闭 2</button><button class="tab ${tab==='unknown'?'active':''}" data-action="tab-unknown">结果未知 1</button></div>${body}</div></div></section>`;
}
function recoverable(){return `<div class="filters"><select><option>来源:全部</option><option>DBS</option><option>Crane</option></select><select><option>日期:全部</option><option>最近 3 天</option></select></div><div class="table-wrap"><table class="table"><thead><tr><th></th><th>来源实例 / 日期</th><th>Invoice</th><th>当前事实</th><th>最近查询</th><th></th></tr></thead><tbody><tr><td><input type="checkbox" checked /></td><td>DBS-AWSBI<br><small>2026-08-16</small></td><td><b>INV-031</b></td><td>收料 300 / ERP 280</td><td>09:12</td><td><button class="link" data-action="show-audit">证据</button></td></tr><tr><td><input type="checkbox" checked /></td><td>CRANE-SZ<br><small>2026-08-15</small></td><td><b>INV-042</b></td><td>收料 800 / ERP 0</td><td>09:12</td><td><button class="link" data-action="show-audit">证据</button></td></tr><tr><td><input type="checkbox" /></td><td>DBS-AWSSG<br><small>2026-08-14</small></td><td><b>INV-073</b></td><td>明确技术失败</td><td>08:50</td><td><button class="link" data-action="show-audit">证据</button></td></tr></tbody></table></div><div class="notice"><i>i</i><span>多选后每个 Invoice 都会重新查询 ERP 库存;满足严格等量的项目可返回预检明细后直接生成调拨单。</span></div><div class="actions">${button('重新查询 ERP 库存(2)','requery','primary')}${button('标记无需继续处理','close-item','danger')}</div>`}
function recoverable(){return `<div class="filters"><select><option>来源:全部</option><option>DBS</option><option>Crane</option></select><select><option>日期:全部</option><option>最近 3 天</option></select></div><div class="table-wrap"><table class="table"><thead><tr><th></th><th>来源实例 / 日期</th><th>Invoice</th><th>当前事实</th><th>最近查询</th><th></th></tr></thead><tbody><tr><td><input type="checkbox" checked /></td><td>DBS-AWSBI<br><small>2026-08-16</small></td><td><b>INV-031</b></td><td>入站 300 / ERP 280</td><td>09:12</td><td><button class="link" data-action="show-audit">证据</button></td></tr><tr><td><input type="checkbox" checked /></td><td>CRANE-SZ<br><small>2026-08-15</small></td><td><b>INV-042</b></td><td>入站 800 / ERP 0</td><td>09:12</td><td><button class="link" data-action="show-audit">证据</button></td></tr><tr><td><input type="checkbox" /></td><td>DBS-AWSSG<br><small>2026-08-14</small></td><td><b>INV-073</b></td><td>明确技术失败</td><td>08:50</td><td><button class="link" data-action="show-audit">证据</button></td></tr></tbody></table></div><div class="notice"><i>i</i><span>多选后每个 Invoice 都会重新查询 ERP 库存;满足严格等量的项目可返回预检明细后直接生成调拨单。</span></div><div class="actions">${button('重新查询 ERP 库存(2)','requery','primary')}${button('标记无需继续处理','close-item','danger')}</div>`}
function closed(){return `<div class="table-wrap"><table class="table"><thead><tr><th>Invoice</th><th>关闭原因</th><th>关闭人 / 时间</th><th></th></tr></thead><tbody><tr><td>INV-061</td><td>货代确认无需调拨</td><td>仓库管理人员 · 08-17 15:00</td><td><button class="link" data-action="restore-item">恢复处理</button></td></tr><tr><td>INV-068</td><td>业务已线下完成</td><td>仓库管理人员 · 08-17 16:20</td><td><button class="link" data-action="restore-item">恢复处理</button></td></tr></tbody></table></div><div class="notice"><i>i</i><span>恢复后回到“可恢复异常”池;原关闭原因、操作者和快照永久保留。</span></div>`}
function unknown(){return `<div class="notice bad"><i>!</i><span>ERP 未返回确定成功或失败。系统只展示已知事实,不提供重查、关闭、恢复或执行按钮。</span></div><div class="table-wrap"><table class="table"><thead><tr><th>Invoice</th><th>所属 Run</th><th>调用时间</th><th>Operation ID</th><th></th></tr></thead><tbody><tr><td><b>INV-052</b></td><td>AUTO-20260818-0900</td><td>09:17:21</td><td>OP-20260818-8891</td><td><button class="link" data-action="show-unknown">查看事实与 SOP</button></td></tr></tbody></table></div>`}
function render(){ const page=pageName(); document.body.classList.toggle('chat-mode',page==='chat'); document.body.classList.toggle('history-open',page==='chat'&&S.historyOpen); const renderer={chat:chatPage,source:sourcePage,precheck:precheckPage,run:runPage,backlog:backlogPage,unknown:backlogPage}[page]||chatPage; $('page').innerHTML=renderer(); bind(); if(page==='source') filterSources(); }
@@ -141,7 +141,7 @@
if(a==='execute'){toast('原型:已提交 Worker 创建、审核并过账 ERP 调拨单。关闭页面不会取消后台任务。');setTimeout(()=>goto('run'),650);return} if(a==='requery'){toast('原型:仅重新查询所选异常的 ERP 库存;文件版本不变,未写入 ERP。');setTimeout(()=>goto('precheck'),500);return} if(a==='requery-precheck'){S.precheckRequery='loading';render();toast('原型:正在重新查询 INV-031 的 ERP 库存;未抓取 RPA 文件。');setTimeout(()=>{S.precheckRequery='matched';render();toast('原型:INV-031 已匹配并加入可生成调拨单范围。');},900);return}
if(a==='tab-recoverable'){S.backlogTab='recoverable';render();return}if(a==='tab-closed'){S.backlogTab='closed';render();return}if(a==='tab-unknown'){S.backlogTab='unknown';render();return}if(a==='close-item'){openModal('close');return}if(a==='restore-item'){openModal('restore');return}
if(a==='modal-cancel'){$('modal-mask').classList.remove('show');return}if(a==='modal-confirm'){if(!$('reason').value.trim()){toast('请填写原因。');return}$('modal-mask').classList.remove('show');toast('原型:已追加审计并更新事项状态。');S.backlogTab=S.modal==='restore'?'recoverable':'closed';render();return}
if(a.startsWith('download-source-')){const source=sources.find(x=>x.code===a.slice(16));if(source?.file)toast(`原型:已下载 ${source.file.name};正式实现将记录下载访问审计。`);return}if(a==='download-receipt-files'){toast('原型:已下载本次 Run 使用的 DBS-AWSBI 与 CRANE-SZ 收料来源文件。');return}if(a==='download-erp-stock'){toast('原型:已下载本次预检冻结的 ERP 库存表。');return}if(a==='show-file'){toast('原型:展示冻结文件版本、checksum、原始行和下载访问审计。');return}if(a==='show-audit'){toast('原型:展示操作人、时间、动作、变更前后快照与关联 Run。');return}if(a==='show-requery-history'){toast('原型:Attempt 1 为收料 300 / ERP 280;最新 Attempt 会追加保存,原快照不被覆盖。');return}if(a==='show-unknown'){toast('原型:结果未知只能由 ERP 管理员线下核实;系统不生成第二次 ERP 写入。');return}if(a==='download'){toast('原型:下载 Run 创建时的固定异常 Excel,并记录下载审计。');return}if(a==='chat-send'){const q=($('chat-input')?.value||'').trim();const scene=q.includes('今天')?'rule':q.includes('待处理')?'status':q.includes('INV-031')||q.includes('不一致')?'mismatch':q.includes('ERP')&&q.includes('处理好')?'recovery':q.includes('未知')?'safety':q.includes('自动')||q.includes('排程')?'schedule':q.includes('现在')||q.includes('进度')?'progress':q.includes('调拨')||q.includes('昨天')?'intent':'welcome';return goto('chat',{scene});}
if(a.startsWith('download-source-')){const source=sources.find(x=>x.code===a.slice(16));if(source?.file)toast(`原型:已下载 ${source.file.name};正式实现将记录下载访问审计。`);return}if(a==='download-inbound-files'){toast('原型:已下载本次 Run 使用的 DBS-AWSBI 与 CRANE-SZ 入站来源文件。');return}if(a==='download-erp-stock'){toast('原型:已下载本次预检冻结的 ERP 库存表。');return}if(a==='show-file'){toast('原型:展示冻结文件版本、checksum、原始行和下载访问审计。');return}if(a==='show-audit'){toast('原型:展示操作人、时间、动作、变更前后快照与关联 Run。');return}if(a==='show-requery-history'){toast('原型:Attempt 1 为入站 300 / ERP 280;最新 Attempt 会追加保存,原快照不被覆盖。');return}if(a==='show-unknown'){toast('原型:结果未知只能由 ERP 管理员线下核实;系统不生成第二次 ERP 写入。');return}if(a==='download'){toast('原型:下载 Run 创建时的固定异常 Excel,并记录下载审计。');return}if(a==='chat-send'){const q=($('chat-input')?.value||'').trim();const scene=q.includes('今天')?'rule':q.includes('待处理')?'status':q.includes('INV-031')||q.includes('不一致')?'mismatch':q.includes('ERP')&&q.includes('处理好')?'recovery':q.includes('未知')?'safety':q.includes('自动')||q.includes('排程')?'schedule':q.includes('现在')||q.includes('进度')?'progress':q.includes('调拨')||q.includes('昨天')?'intent':'welcome';return goto('chat',{scene});}
}
function bind(){document.querySelectorAll('[data-action]').forEach(el=>el.onclick=()=>action(el.dataset.action));document.querySelectorAll('[data-source]').forEach(el=>el.onchange=()=>{el.checked?S.selected.add(el.dataset.source):S.selected.delete(el.dataset.source);const count=$('source-count');if(count)count.textContent=`已选 ${S.selected.size} 个来源实例`;});document.querySelectorAll('[data-invoice]').forEach(el=>el.onchange=()=>{const checked=[...document.querySelectorAll('[data-invoice]:checked')];const n=checked.length, total=checked.reduce((sum,x)=>sum+({"INV-001":500,"INV-002":1200,"INV-008":600,"INV-031":300}[x.dataset.invoice]||0),0);const t=$('selected-summary');if(t)t.textContent=`已选 ${n} 张 · 预计调拨总数量 ${total.toLocaleString()} PCS · 预计 ERP 写入 ${n} 张`;});}
window.addEventListener('popstate',render); render();
@@ -1,7 +1,7 @@
# 在途仓自动调拨 AI Agent 一期 TDD 实施与验证规范
> 状态:开发前冻结,所有实现必须先有失败测试再写业务代码
> 适用范围:在途仓自动调拨 Agent 一期,包括对话、后台排程、收料文件、ERP调拨、异常恢复、企业微信通知、后台配置发布和全链路审计
> 适用范围:在途仓自动调拨 Agent 一期,包括对话、后台排程、入站文件、ERP调拨、异常恢复、企业微信通知、后台配置发布和全链路审计
> 关联规格:[minimum-implementation-spec.md](./minimum-implementation-spec.md)
> 测试基线:后端 pytest;前端 Vitest + Vue Test Utils;E2E 使用 Playwright 约定;数据库 PostgreSQL 测试库;外部系统全部使用可控 Stub/Mock
@@ -37,10 +37,10 @@
以下任一前置条件失败,测试必须证明 ERP 写入调用次数为 `0`:
- 当天收料未成熟。
- 收料文件缺失、过期、checksum变化或结构漂移。
- 异动日期晚于业务日期(未来日期无账可核;【成熟规则已退役 2026-10-16】当天/昨天数据正常进匹配,日期边界由调用方入参给定)。
- 入站文件缺失、过期、checksum变化或结构漂移。
- Invoice字段冲突或一张Invoice跨多个料号/日期。
- ERP账面库存与收料数量不完全相等。
- ERP账面库存与入站数量不完全相等。
- 确认卡缺失、过期或快照变化。
- 来源、仓库、ERP组织映射缺失。
- 幂等键冲突且无法证明原单已审核过账。
@@ -83,9 +83,9 @@ backend/tests/services/in_transit_transfer/assertions.py
| --- | --- |
| `transfer_db` | 独立事务,测试结束回滚或清理所有调拨表 |
| `fixed_clock` | 默认 `2026-08-06 09:00:00+08:00`,可推进到下一业务日 |
| `dbs_ready_file` | 当日ready收料全量文件,含重复Invoice多行 |
| `crane_ready_file` | 当日ready收料全量文件,支持HTTP Callback完成 |
| `same_day_receipt_file` | 含业务日期当天收料,必须not_matured |
| `dbs_ready_file` | 当日ready入站全量文件,含重复Invoice多行 |
| `crane_ready_file` | 当日ready入站全量文件,支持HTTP Callback完成 |
| `same_day_inbound_file` | 含业务日期当天异动文件(成熟规则已退役:当天数据正常进匹配) |
| `erp_fake` | 查询账面库存;写接口原子新建/审核/过账;重复Invoice返回原单号 |
| `erp_timeout_fake` | 查询或写入超时,分别可配置已落单/未落单 |
| `rpa_fake` | 领取、Callback、失败、重复Callback、错误来源Callback |
@@ -133,8 +133,8 @@ timeout(after_commit=true, replay_query_unsupported=true)
{
"invoice_no": "INV-260806-001",
"material_no": "MAT-001",
"receipt_date": "2026-08-05",
"receipt_quantity": "1200",
"movement_date": "2026-08-05",
"movement_quantity": "1200",
"source_code": "DBS",
"source_warehouse": "DBS-TRANSIT",
"erp_org": "HX-CN01",
@@ -146,7 +146,7 @@ timeout(after_commit=true, replay_query_unsupported=true)
| 数据组 | 变体 | 预期 |
| --- | --- | --- |
| 日期 | 当天、昨天、更早、未来日期 | 当天not_matured;昨天及更早可预检;未来阻断 |
| 日期 | 当天、昨天、更早、未来日期 | 全部可预检(日期边界由调用方入参给定);仅未来日期阻断 |
| 汇总 | 同Invoice同料号两行 | 数量相加,保留两条原始行 |
| 冲突 | 同Invoice多个料号/日期/Sheet | 整Invoice阻断 |
| 数量 | 相等、大于、小于、0、负数、小数、非数字 | 只有完全相等可执行 |
@@ -158,21 +158,21 @@ timeout(after_commit=true, replay_query_unsupported=true)
## 5. L0 纯单元测试清单(先写这些)
### 5.1 日期成熟与范围
### 5.1 日期解析与范围
测试文件:`backend/tests/services/in_transit_transfer/test_date_policy.py`
必须先写的失败测试:
【成熟规则已退役 2026-10-16】T+lag 策略用例删除;保留日期解析/时区纯单元用例,
范围校验(截止≤业务日期)由 matching_service 用例覆盖:
1. 当天收料返回 `not_matured`,ERP查询调用为0。
2. 昨天收料进入预检。
3. 未来日期返回结构化阻断错误。
4. “今天可调拨”过滤成功项和`manually_closed`项。
1. 当天/昨天异动正常进入匹配(无日期前置过滤)。
2. 未来日期返回结构化阻断错误。
3. “今天可调拨”过滤成功项和`manually_closed`项。
5. Asia/Shanghai跨UTC午夜时业务日期不漂移。
### 5.2 文件字段和Invoice汇总
测试文件:`test_receipt_file_parser.py`、`test_invoice_aggregator.py`
测试文件:`test_inbound_file_parser.py`、`test_invoice_aggregator.py`
必须覆盖:
@@ -188,8 +188,8 @@ timeout(after_commit=true, replay_query_unsupported=true)
必须覆盖:
- 收料数量等于账面库存才返回`executable`。
- ERP库存大于或小于收料数量均阻断。
- 入站数量等于账面库存才返回`executable`。
- ERP库存大于或小于入站数量均阻断。
- 所有非法状态迁移抛出领域错误。
- `result_unknown`没有自动重试迁移路径。
- `manually_closed`永久禁止进入待处理池。
@@ -213,8 +213,8 @@ timeout(after_commit=true, replay_query_unsupported=true)
| 顺序 | 测试文件 | 先冻结的行为 | Green实现目标 |
| ---: | --- | --- | --- |
| 1 | `test_file_preparation.py` | 当日ready复用;缺失时同来源只触发一个RPA;DBS/Crane互不影响 | `ensure_receipt_file_ready` |
| 2 | `test_precheck_service.py` | 文件准备→成熟过滤→汇总→ERP查询→数量匹配;进度事件可恢复 | `precheck_service` |
| 1 | `test_file_preparation.py` | 当日ready复用;缺失时同来源只触发一个RPA;DBS/Crane互不影响 | `ensure_inbound_file_ready` |
| 2 | `test_precheck_service.py` | 文件准备→未来日期阻断→汇总→ERP查询→数量匹配;进度事件可恢复 | `precheck_service` |
| 3 | `test_execution_service.py` | 写前重新查询;确认Hash失效不写;逐项结果;写并发由上层控制 | `execution_service` |
| 4 | `test_erp_adapter.py` | SOAP请求字段、60秒超时、原子失败、重复Invoice投影 | `erp_adapter` |
| 5 | `test_orchestrator.py` | Run/SourceJob/Attempt持久化;只执行可执行项;单项失败不影响其它项 | `orchestrator` |
@@ -252,10 +252,10 @@ timeout(after_commit=true, replay_query_unsupported=true)
| 接口组 | 关键断言 |
| --- | --- |
| 来源CRUD | 收料用途、RPA/Callback类型、解析方案和固定来源仓必填;发货来源不受影响 |
| 来源CRUD | 入站用途、RPA/Callback类型、解析方案和固定来源仓必填;发货来源不受影响 |
| 策略草稿 | 只能管理员修改;禁止容差、部分调拨、result_unknown自动重试 |
| 映射CRUD | 同一路由只能一个ERP组织;来源仓强制来自来源配置;目标HUB缺失阻断发布 |
| 排程CRUD | 08:00收料与09:00调拨默认值;来源独立并发配置;不能重复启用相同来源活动任务 |
| 排程CRUD | 08:00入站与09:00调拨默认值;来源独立并发配置;不能重复启用相同来源活动任务 |
| 通知配置 | 所有人去重;空数据默认关闭;通知失败不改变业务状态 |
| 发布/校验 | 发布前完整门禁;版本Diff和before/after快照审计;Secret明文永不返回 |
@@ -265,7 +265,7 @@ timeout(after_commit=true, replay_query_unsupported=true)
```text
TRANSFER_PERMISSION_DENIED
TRANSFER_RECEIPT_NOT_MATURED
TRANSFER_INBOUND_NOT_MATURED
TRANSFER_FILE_NOT_READY
TRANSFER_FILE_SCHEMA_INVALID
TRANSFER_INVOICE_CONFLICT
@@ -323,7 +323,7 @@ frontend/src/features/chat/composables/useChatTransfer.spec.ts
必须验证:
- 文件准备卡逐来源显示DBS/Crane阶段,不伪造总百分比。
- 当天收料显示未成熟,不显示ERP库存异常。
- 当天异动正常展示匹配结果(成熟规则已退役,无未成熟态)。
- 预检卡展示可执行数、阻断数、预计调拨总数量和预计ERP写入数。
- 阻断项checkbox禁用,用户不能编辑数量、仓库或ERP组织。
- 确认卡显示10分钟倒计时和失效原因。
@@ -346,7 +346,7 @@ frontend/src/features/admin/modules/in-transit-transfer/TransferAuditPage.spec.t
必须验证:
- 收料用途与发货用途分开显示、保存和校验。
- 入站用途与发货用途分开显示、保存和校验。
- Crane显示HTTP Callback,不显示RPA密码字段。
- ERP地址、凭据、Secret只显示注入状态,DOM中不得出现明文。
- 策略禁止开启部分调拨、容差、result_unknown自动重试。
@@ -365,7 +365,7 @@ frontend/src/features/admin/modules/in-transit-transfer/TransferAuditPage.spec.t
1. 仓库管理员进入在途仓调拨Agent。
2. 点击“查询今天可调拨数据”。
3. 观察文件准备阶段:DBS复用ready,Crane实时Callback。
4. 预检完成后确认当天未成熟项未进入ERP查询。
4. 预检完成后确认明细行全部进入ERP查询(仅未来日期行阻断)。
5. 点击执行,确认卡展示范围、总数量和预计ERP写入。
6. 点击一次“执行调拨”。
7. 刷新页面,Run仍可恢复。
@@ -373,7 +373,7 @@ frontend/src/features/admin/modules/in-transit-transfer/TransferAuditPage.spec.t
### 10.2 自动排程
1. 触发08:00收料排程。
1. 触发08:00入站排程。
2. 触发09:00自动调拨排程。
3. 验证缺失文件时自动实时抓取。
4. 验证历史可恢复异常创建新Attempt。
@@ -397,7 +397,7 @@ frontend/src/features/admin/modules/in-transit-transfer/TransferAuditPage.spec.t
| 预检DTO恢复P95 | ≤500ms |
| 进度投影读取P95 | ≤500ms |
| 同来源重复RPA触发 | 0 |
| 当天收料ERP查询/写入 | 0 |
| 当天入站ERP查询/写入 | 0 |
| 未确认或过期确认ERP写入 | 0 |
| `result_unknown`自动重试 | 0 |
| 审计覆盖率 | 100% |
@@ -420,7 +420,7 @@ frontend/src/features/admin/modules/in-transit-transfer/TransferAuditPage.spec.t
```text
成功ERP单据数 <= 可执行Invoice数
ERP写入数量 = success数量 + duplicate_success数量
blocked / not_matured / result_unknown 不得产生ERP写调用
blocked / result_unknown 不得产生ERP写调用(not_matured 已随成熟规则退役)
manual_close后不得再次生成Attempt
每次Attempt只能有一个终态
每个Invoice在同一ERP组织内最多一个成功单号
@@ -442,7 +442,7 @@ manual_close后不得再次生成Attempt
先写文件解析、汇总、ready复用、RPA幂等、D+1和ERP查询Stub测试,再实现文件准备与预检服务。
验收:当前ready复用正确;缺失文件只触发一次RPA;当天收料ERP调用0;DBS/Crane互不阻断。
验收:当前ready复用正确;缺失文件只触发一次RPA;当天入站ERP调用0;DBS/Crane互不阻断。
### Phase 2:确认与ERP写入
@@ -500,7 +500,7 @@ cd ..\frontend; npm run test:unit; npm run build
| 等级 | 示例 | 发布要求 |
| --- | --- | --- |
| P0 | 未确认写ERP、重复建单、审计缺失、Secret泄露、当天收料写入 | 立即阻断,修复并回归全部高风险套件 |
| P0 | 未确认写ERP、重复建单、审计缺失、Secret泄露、当天入站写入 | 立即阻断,修复并回归全部高风险套件 |
| P1 | 历史失败不恢复、结果状态错误、通知与ERP结果耦合、错误权限放行 | 阻断生产,修复后通过对应阶段E2E |
| P2 | 进度文案缺失、Excel列顺序错误、非关键页面交互异常 | 可延期但必须有Issue和验收期限 |
| P3 | 视觉间距、非关键辅助文案 | 不阻断一期上线 |
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff. Show more