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

+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}',