feat(in-transit-transfer): 调拨类型配置化与库存异动档原子切换
调拨类型从四处硬编码升级为管理页可配置:范围规则(受控字段白名单,规则间且/值间或)、 仓库定义(映射档/固定仓双模式角色解析)、字段转换(批号前缀替换,匹配时快照固化到 scope_json)。 新建 transfer_movement_ledger 库存异动档(参照 ERP inaj_t):自然键幂等增量落档 (插入/换证更新/跳过/缺席不删/执行封存永不触碰),圈档互斥保证一条档记录一生只绑一次明细; 收料证据落地改写档、停写 items。transfer_invoice_items 出生翻转为匹配时从档圈定创建 (一次匹配永久写入 matching_id+ledger_record_id),回查对账/取消释放/执行门禁/待匹配桶全链路适配。 迁移 tt10→tt13 单 head:类型配置表、异动档、items 档外键、transfer_runs.transfer_type 放宽 String(64)。 随行披露:设计文档与实施计划、ADR 0001/0002、in-transit-transfer 术语表、 demand/funclist/technical 文档更新同批入库。
This commit is contained in:
1 parent
28d6085d07
commit
52c71ee46a
78 files changed
+7423
-1702
No files matched your search
@@ -32,5 +32,6 @@ import app.api.admin.shipping_process_gate # noqa: F401
|
||||
import app.api.admin.linked_services # noqa: F401
|
||||
import app.api.admin.procurement_contract # noqa: F401
|
||||
import app.api.admin.training_configs # noqa: F401
|
||||
import app.api.admin.transfer_type # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
api/admin/transfer_type.py
|
||||
|
||||
用途:调拨类型配置的管理 API(列表/创建/更新,ADR 0002 类型配置化)。
|
||||
依赖:admin blueprint、require_admin、transfer_type_config_service(Task 4)。
|
||||
逻辑:路由只做鉴权、参数形态门禁与错误码→HTTP 状态映射;业务校验、配置
|
||||
规范化与事务全在服务层。重复 code(服务层预检)与并发唯一键冲突
|
||||
(IntegrityError 兜底)统一映射 422 TRANSFER.TRANSFER_TYPE_CODE_EXISTS;
|
||||
code 不可变 422;更新目标不存在 404。本模块是稳定错误码 → 前端四语言
|
||||
errors.json 文案的 API 侧登记点(TRANSFER_TYPE_*/SCOPE/WAREHOUSE/TRANSFORM)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.core.response import ok, utc_iso
|
||||
from app.services.in_transit_transfer import transfer_type_config_service as service
|
||||
|
||||
# 稳定错误码统一转出(服务层常量 + 引擎码 + 匹配链码),避免 API 层散落字符串。
|
||||
ERR_NOT_CONFIGURED = service.TRANSFER_TYPE_NOT_CONFIGURED
|
||||
ERR_CODE_EXISTS = service.TRANSFER_TYPE_CODE_EXISTS
|
||||
ERR_CODE_IMMUTABLE = service.TRANSFER_TYPE_CODE_IMMUTABLE
|
||||
ERR_WAREHOUSE_INVALID = service.WAREHOUSE_CONFIG_INVALID
|
||||
ERR_SCOPE_INVALID = "TRANSFER.SCOPE_RULE_INVALID"
|
||||
ERR_TRANSFORM_INVALID = "TRANSFER.TRANSFORM_RULE_INVALID"
|
||||
|
||||
# 服务层业务码 → HTTP 状态映射:编码冲突/不可变是语义冲突(422)、更新目标
|
||||
# 不存在(404);不在表内的码(含 VALIDATION.INVALID_PARAM 与三块配置引擎码)
|
||||
# 保持 ValidationError 默认 400。
|
||||
_HTTP_STATUS_BY_CODE = {
|
||||
ERR_CODE_EXISTS: 422,
|
||||
ERR_CODE_IMMUTABLE: 422,
|
||||
ERR_NOT_CONFIGURED: 404,
|
||||
}
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按平台统一 envelope 返回管理 API 成功结果。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
def _reraise_with_status(exc: ValidationError) -> None:
|
||||
"""按稳定错误码改写 HTTP 状态后重抛;表外码原样透传(保持 400)。"""
|
||||
status = _HTTP_STATUS_BY_CODE.get(exc.code)
|
||||
if status is None:
|
||||
raise exc
|
||||
raise AppError(
|
||||
code=exc.code, message=exc.message, http_status=status, details=exc.details,
|
||||
) from exc
|
||||
|
||||
|
||||
def _request_payload() -> dict:
|
||||
"""读取 JSON body 并保证是 dict(非对象形态统一 400,防下游 AttributeError)。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError("request body must be a JSON object")
|
||||
return payload
|
||||
|
||||
|
||||
def _enforce_field_types(payload: dict) -> None:
|
||||
"""API 层参数形态门禁:enabled 只接受布尔/整数、sort_order 只接受整数。
|
||||
|
||||
防御字符串形态(如 "false")绕过 API 直达服务层被 bool() 强转为真值;
|
||||
业务校验(code 格式、names、三块配置)仍归服务层,此处只挡类型。
|
||||
"""
|
||||
if "enabled" in payload and not isinstance(payload["enabled"], (bool, int)):
|
||||
raise ValidationError(
|
||||
"enabled must be boolean or integer", details={"enabled": payload["enabled"]},
|
||||
)
|
||||
sort_order = payload.get("sort_order")
|
||||
if "sort_order" in payload and (not isinstance(sort_order, int) or isinstance(sort_order, bool)):
|
||||
raise ValidationError("sort_order must be integer", details={"sort_order": sort_order})
|
||||
|
||||
|
||||
def _warehouse_role_json(role) -> dict:
|
||||
"""WarehouseRole → 管理端 JSON 项(与入库规范化形态读写对称)。"""
|
||||
return {
|
||||
"mode": role.mode,
|
||||
"warehouse_code": role.warehouse_code,
|
||||
"external_org": role.external_org,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_config(dto) -> dict:
|
||||
"""TransferTypeConfigDTO → 管理 API 全量视图(三块配置全暴露,仅管理端可见)。"""
|
||||
return {
|
||||
"code": dto.code,
|
||||
"names": dict(dto.names),
|
||||
"enabled": dto.enabled,
|
||||
"sort_order": dto.sort_order,
|
||||
"scope_rules": [
|
||||
{"field": rule.field, "match": rule.match, "values": list(rule.values)}
|
||||
for rule in dto.scope_rules
|
||||
],
|
||||
"warehouse_config": {
|
||||
"from": _warehouse_role_json(dto.warehouse_config.from_role),
|
||||
"to": _warehouse_role_json(dto.warehouse_config.to_role),
|
||||
},
|
||||
"transform_rules": [
|
||||
{"field": rule.field, "op": rule.op, "source": rule.source, "target": rule.target}
|
||||
for rule in dto.transform_rules
|
||||
],
|
||||
"description": dto.description,
|
||||
"updated_at": utc_iso(dto.updated_at),
|
||||
}
|
||||
|
||||
|
||||
@admin_bp.route('/in-transit-transfer/transfer-types', methods=['GET'])
|
||||
@require_admin
|
||||
def list_transfer_types():
|
||||
"""全量类型配置(含停用),sort_order 升序——管理页列表。"""
|
||||
return _ok([_serialize_config(dto) for dto in service.list_configs()])
|
||||
|
||||
|
||||
@admin_bp.route('/in-transit-transfer/transfer-types', methods=['POST'])
|
||||
@require_admin
|
||||
def create_transfer_type():
|
||||
"""创建类型配置;重复 code(预检或并发唯一键)统一 422。"""
|
||||
payload = _request_payload()
|
||||
_enforce_field_types(payload)
|
||||
try:
|
||||
dto = service.create_config(payload, operator_id=_actor_id())
|
||||
except ValidationError as exc:
|
||||
_reraise_with_status(exc)
|
||||
except IntegrityError as exc:
|
||||
# [防御] 服务层唯一性预检在事务之前,并发窗口漏出的唯一键冲突兜底映射
|
||||
# 422,避免 500 漏给管理页(控制器裁定①)。
|
||||
raise AppError(
|
||||
code=ERR_CODE_EXISTS,
|
||||
message="transfer type code already exists",
|
||||
http_status=422,
|
||||
details={},
|
||||
) from exc
|
||||
return _ok(_serialize_config(dto), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/in-transit-transfer/transfer-types/<string:code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_transfer_type(code: str):
|
||||
"""更新类型配置(部分更新;改 code → 422,目标不存在 → 404)。"""
|
||||
payload = _request_payload()
|
||||
_enforce_field_types(payload)
|
||||
try:
|
||||
dto = service.update_config(code, payload, operator_id=_actor_id())
|
||||
except ValidationError as exc:
|
||||
_reraise_with_status(exc)
|
||||
return _ok(_serialize_config(dto))
|
||||
@@ -8,7 +8,8 @@
|
||||
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
||||
retrigger → 202,D11 唯一出口);首页「已执行」区块:已执行单分页查询
|
||||
(GET /documents,只读)与人工关闭失败单(POST /documents/{doc_no}/close,
|
||||
D18 废单不废行)。
|
||||
D18 废单不废行);调拨类型选择数据源(GET /transfer-types,仅启用、
|
||||
最小暴露,读 Task 4 transfer_type_config_service)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -50,6 +51,9 @@ from app.services.in_transit_transfer.serializers import (
|
||||
serialize_source,
|
||||
serialize_summary,
|
||||
)
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
get_enabled as list_enabled_transfer_types,
|
||||
)
|
||||
|
||||
in_transit_transfer_bp = Blueprint("in_transit_transfer", __name__)
|
||||
|
||||
@@ -92,8 +96,9 @@ def create_matching_api():
|
||||
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
|
||||
"receipt_date_from"/"receipt_date_to"(可选),
|
||||
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
|
||||
响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度)。
|
||||
"transfer_type": 必填(类型编码,配置化;缺失/未配置/停用 → 422)}。
|
||||
响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度);
|
||||
类型门禁失败 422(REQUIRED/NOT_CONFIGURED/DISABLED,规格 §11)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
@@ -101,6 +106,16 @@ def create_matching_api():
|
||||
source_codes = body.get("source_codes")
|
||||
if not isinstance(source_codes, list) or not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
# [D8 必填] transfer_type 缺失 fail-closed(稳定错误码,四语言已配齐);
|
||||
# 存在性/启停门禁由 create_matching → resolve_transfer_type 统一裁定。
|
||||
# [规格 §11] 类型门禁(REQUIRED/NOT_CONFIGURED/DISABLED)统一 422。
|
||||
transfer_type = str(body.get("transfer_type") or "").strip()
|
||||
if not transfer_type:
|
||||
raise ValidationError(
|
||||
"transfer_type is required",
|
||||
code="TRANSFER.TRANSFER_TYPE_REQUIRED",
|
||||
http_status=422,
|
||||
)
|
||||
business_date = str(body.get("business_date") or business_date_now())
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_matching(
|
||||
@@ -109,7 +124,7 @@ def create_matching_api():
|
||||
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,
|
||||
transfer_type=str(body.get("transfer_type")) if body.get("transfer_type") else None,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
return _ok(serialize_summary(summary), status=201)
|
||||
|
||||
@@ -124,7 +139,7 @@ def executable_items_api():
|
||||
@in_transit_transfer_bp.route("/matchings/<matching_id>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_matching_api(matching_id: str):
|
||||
"""恢复匹配进度与明细(页面刷新/会话恢复;明细按 scope 实时圈行并装饰行级状态)。"""
|
||||
"""恢复匹配进度与明细(页面刷新/会话恢复;明细=匹配自有出生行(2026-10-14 出生翻转)并装饰行级状态)。"""
|
||||
restored = restore_matching(matching_id, deps=transfer_deps.get_transfer_dependencies())
|
||||
return _ok({
|
||||
"summary": serialize_summary(restored["summary"]),
|
||||
@@ -705,6 +720,30 @@ def transfer_metrics_api():
|
||||
return _ok(collect_metrics())
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/transfer-types", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def transfer_types_api():
|
||||
"""调拨类型配置列表(启用中,最小暴露)——匹配创建的类型选择数据源。
|
||||
|
||||
仅返回 {code, names, sort_order, transform_rules} 四键:范围规则/仓库定义/
|
||||
描述属管理端配置资产,禁止对用户态暴露(最小暴露硬契约,见 Task 5 测试);
|
||||
enabled 由查询限定(get_enabled)、sort_order 升序。配置缺失返回空列表,
|
||||
不抛 NOT_CONFIGURED(该码留给匹配创建链路)。
|
||||
"""
|
||||
return _ok([
|
||||
{
|
||||
"code": dto.code,
|
||||
"names": dict(dto.names),
|
||||
"sort_order": dto.sort_order,
|
||||
"transform_rules": [
|
||||
{"field": rule.field, "op": rule.op, "source": rule.source, "target": rule.target}
|
||||
for rule in dto.transform_rules
|
||||
],
|
||||
}
|
||||
for dto in list_enabled_transfer_types()
|
||||
])
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def transfer_sources_api():
|
||||
@@ -847,7 +886,7 @@ def backlog_api():
|
||||
@in_transit_transfer_bp.route("/backlog/summary", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_summary_api():
|
||||
"""待处理异常汇总(含 3/5/7 天老化分级)。"""
|
||||
"""待处理异常汇总(含 3/5/7 天老化分级 + 待匹配桶计数 D16)。"""
|
||||
from app.services.in_transit_transfer.backlog_service import backlog_summary
|
||||
|
||||
summary = backlog_summary()
|
||||
@@ -855,6 +894,8 @@ def backlog_summary_api():
|
||||
'recoverable': summary.recoverable_count,
|
||||
'closed': summary.closed_count,
|
||||
'unknown': summary.unknown_count,
|
||||
# 首页待办看板第 4 张数字卡(D16):已落档尚未匹配的外部收料记录数。
|
||||
'pending_match': summary.pending_match_count,
|
||||
'aging': {
|
||||
'warn_3d': summary.warn_3d,
|
||||
'escalate_5d': summary.escalate_5d,
|
||||
@@ -863,6 +904,33 @@ def backlog_summary_api():
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog/pending-match", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_pending_match_api():
|
||||
"""首页待办看板「待匹配」桶清单(D16 只读:启用类型范围并集内已落档、
|
||||
尚未被任何匹配圈定的外部收料记录;无 item_id——不可勾选执行,
|
||||
前端仅提供只读清单与「去匹配」引导)。"""
|
||||
from app.services.in_transit_transfer.backlog_service import list_pending_match_records
|
||||
|
||||
return _ok([
|
||||
_serialize_pending_match_record(record)
|
||||
for record in list_pending_match_records()
|
||||
])
|
||||
|
||||
|
||||
def _serialize_pending_match_record(record) -> dict[str, Any]:
|
||||
"""「待匹配」桶项序列化(档记录只读投影七键;无 item_id)。"""
|
||||
return {
|
||||
'ledger_record_id': record.ledger_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,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
"""待处理池项序列化(明细字段与匹配窗口列一致)。"""
|
||||
return {
|
||||
|
||||
@@ -28,11 +28,14 @@ class ValidationError(AppError):
|
||||
*,
|
||||
code: str = "VALIDATION.INVALID_PARAM",
|
||||
details: dict[str, Any] | None = None,
|
||||
http_status: int = 400,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=400,
|
||||
# 默认 400(参数形态类校验);业务契约指定状态码时显式传入
|
||||
# (如调拨类型门禁 REQUIRED/NOT_CONFIGURED/DISABLED = 422,规格 §11)。
|
||||
http_status=http_status,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
@@ -5,6 +5,13 @@
|
||||
逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写
|
||||
状态/计数/Hash;匹配不存在时 fail-closed 抛 RuntimeError。业务收尾后
|
||||
handler 自行 finish_job(runner 仅兜底异常路径,正常完成不代收口)。
|
||||
【2026-10-14 出生翻转/快照自足确认】异步重跑的全部口径从 scope_json
|
||||
快照回读——transfer_type 编码 + scope_rules/transform_rules 覆盖传入
|
||||
(不读现行配置规则,在途匹配口径不被中途改配置扰动);类型门禁按
|
||||
require_enabled=False(「停用后存量不受影响」,规格 §4.1),仅要求配置
|
||||
仍存在(类型只有停用没有删除)。run_matching 传 matching_id:重跑圈档
|
||||
仅补建「未被有效 items 占用」的新档记录(D17:自有 items 不重复圈定/
|
||||
不重复评估他匹配行),并刷新本匹配自有 items。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -36,6 +43,8 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
|
||||
owned_attempt = int(job_row.attempts) if job_row is not None else None
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
# [快照自足] 类型/范围/转换规则全部回读 scope_json(无枚举依赖、不查现行
|
||||
# 配置规则);warehouse 路由的 fixed 定义随类型配置现行值(未入快照契约)。
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
source_codes = list(scope.get("source_codes") or [])
|
||||
result = run_matching(
|
||||
@@ -43,8 +52,13 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
|
||||
business_date=matching.business_date,
|
||||
deps=deps,
|
||||
run_no=matching.run.run_no if matching.run else "RUN-PENDING",
|
||||
# 类型范围随匹配落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
|
||||
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
|
||||
matching_id=matching.id,
|
||||
scope_rules_override=scope.get("scope_rules") if isinstance(scope.get("scope_rules"), list) else None,
|
||||
transform_rules_override=(
|
||||
scope.get("transform_rules") if isinstance(scope.get("transform_rules"), list) else None
|
||||
),
|
||||
require_enabled=False, # 存量重跑:停用类型不受影响(仅要求配置仍存在)
|
||||
)
|
||||
summary = result.summary
|
||||
matching.status = summary.status
|
||||
|
||||
@@ -208,8 +208,10 @@ from app.models.in_transit_transfer import (
|
||||
TransferDocument,
|
||||
TransferInvoiceItem,
|
||||
TransferMatching,
|
||||
TransferMovementLedger,
|
||||
TransferRun,
|
||||
TransferSourceJob,
|
||||
TransferTypeConfig,
|
||||
)
|
||||
from app.models.integration_connector import (
|
||||
IntegrationBinding,
|
||||
@@ -454,6 +456,8 @@ __all__ = [
|
||||
'TransferAttempt',
|
||||
'TransferAuditEvent',
|
||||
'TransferArchive',
|
||||
'TransferTypeConfig',
|
||||
'TransferMovementLedger',
|
||||
'IntegrationCredentialReference',
|
||||
'IntegrationClientInstance',
|
||||
'IntegrationInterfaceDefinition',
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
"""models/in_transit_transfer.py
|
||||
|
||||
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
|
||||
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive。
|
||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
|
||||
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive;另含调拨类型
|
||||
配置表 TransferTypeConfig(类型配置化,ADR 0002)与库存异动档
|
||||
TransferMovementLedger(外部系统收料/出货记录镜像,ADR 0001)。
|
||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁);
|
||||
source_file_id 外键指向 shipping_receipt_report_files(收料原样归档)。
|
||||
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
|
||||
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
|
||||
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
|
||||
Attempt 保留每次恢复/重查/执行事实,旧 Attempt 永不覆盖;
|
||||
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。
|
||||
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除;
|
||||
transfer_runs.transfer_type 合法值由 TransferTypeConfig 配置承接
|
||||
(原枚举 CHECK 约束已移除);
|
||||
TransferMovementLedger 以自然键 (source_code, record_kind, doc_no,
|
||||
line_no, line_seq, in_out_flag) 幂等增量落地外部记录,已执行记录经
|
||||
transfer_executed 封存(防二次调拨),来源文件删除后档事实留存
|
||||
(ON DELETE SET NULL,链接仅溯源)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -43,11 +52,6 @@ TRANSFER_RUN_STATUSES = (
|
||||
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
|
||||
# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。
|
||||
TRANSFER_RUN_TYPES = (
|
||||
'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub',
|
||||
)
|
||||
TRANSFER_SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
@@ -98,10 +102,6 @@ class TransferRun(Base):
|
||||
"trigger_type IN ('manual', 'schedule')",
|
||||
name='ck_transfer_runs_trigger_type',
|
||||
),
|
||||
CheckConstraint(
|
||||
f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})",
|
||||
name='ck_transfer_runs_transfer_type',
|
||||
),
|
||||
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
|
||||
Index('ix_transfer_runs_business_date', 'business_date'),
|
||||
)
|
||||
@@ -109,9 +109,11 @@ class TransferRun(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
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')
|
||||
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定匹配收料数据范围。
|
||||
# 调拨业务类型(合法值由 TransferTypeConfig 配置承接,合法 code 正则
|
||||
# ^[a-z][a-z0-9_]{1,63}$ 上限 64);决定匹配收料数据范围。列宽 64 与配置表
|
||||
# code 上限对齐(终审 I2:33~64 字符 code 建匹配时写 32 宽列会 DB 500)。
|
||||
transfer_type: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||||
String(64), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||||
)
|
||||
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
@@ -218,6 +220,9 @@ class TransferInvoiceItem(Base):
|
||||
"""匹配明细项;同一匹配内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
|
||||
|
||||
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
||||
【2026-10-14 出生翻转(ADR 0001/D4)】行不再由文件落地写入,而是匹配创建时
|
||||
从库存异动档圈定生成:ledger_record_id 指向档记录(业务字段=档原值),
|
||||
matching_id 创建即绑定(D17:一条档记录一生只生成一次 items 绑定)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'transfer_invoice_items'
|
||||
@@ -236,15 +241,23 @@ class TransferInvoiceItem(Base):
|
||||
# 单据级执行(T10)高频「按单查行」:document_id 单列索引(控制器裁决,
|
||||
# 并入 tt0d1e2f3a4b 避免额外迁移节点)。
|
||||
Index('ix_transfer_invoice_items_document_id', 'document_id'),
|
||||
# 匹配创建圈档的占用互斥检查(D17)高频「按档记录查行」:单列索引
|
||||
# (并入 tt12c3d4e5f6a7 避免额外迁移节点)。
|
||||
Index('ix_transfer_invoice_items_ledger_record_id', 'ledger_record_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 行归属解耦后 matching_id 仅留痕(首次创建值);落地证据同步行尚无匹配归属
|
||||
# (2026-09-25),放开非空。uq_transfer_invoice_items_matching_grain 含本列,
|
||||
# NULL 行不受该唯一约束保护——同步的幂等去重由 evidence_sync 应用层按
|
||||
# (source, invoice, material, receipt_date) 四元组负责(见 evidence_sync)。
|
||||
# 【2026-10-14 出生翻转】matching_id 回归「创建即绑定」:行由匹配创建时从档
|
||||
# 圈定生成(落地不再写 items,见 evidence_sync/ADR 0001),新行恒非空
|
||||
# (模型层不强制 NOT NULL,存量兼容,服务层保证);D17 圈档互斥的占用判定
|
||||
# 以本列 + 所属匹配状态为准(取消匹配即释放占用)。
|
||||
matching_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=True, index=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||||
# 【2026-10-14 出生翻转】行来源档记录外键(可空:隔离的历史行允许 NULL);
|
||||
# 行上业务字段=档原值,批号等转换只在系统边界按匹配快照规则派生(不落库)。
|
||||
ledger_record_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('transfer_movement_ledger.id'), nullable=True,
|
||||
)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
||||
@@ -289,6 +302,12 @@ class TransferInvoiceItem(Base):
|
||||
# (document_id 置 NULL)回到 ready_to_execute,可被重新勾选组建新单。
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
|
||||
document: Mapped[Optional['TransferDocument']] = relationship(back_populates='items')
|
||||
# 【2026-10-14 改锚(规格 §10)】行 → 档记录只读导航:file_current 门禁与行装饰
|
||||
# 的版本戳取档记录 file_sha256(档记录是证据权威)。纯 ORM relationship——
|
||||
# 不新增列/索引/约束(ledger_record_id 列与索引既有),无配套迁移。
|
||||
ledger_record: Mapped[Optional['TransferMovementLedger']] = relationship(
|
||||
foreign_keys=[ledger_record_id],
|
||||
)
|
||||
|
||||
|
||||
class TransferDocument(Base):
|
||||
@@ -476,6 +495,125 @@ class TransferArchive(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class TransferTypeConfig(Base):
|
||||
"""调拨类型配置(ADR 0002):编码/四语言名称/启停/排序 + 范围规则/仓库定义/转换规则。
|
||||
|
||||
code 创建后不可变(transfer_runs.transfer_type 引用);只有停用没有删除;
|
||||
配置为空时匹配链路 fail-closed(TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'transfer_type_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('code', name='uq_transfer_type_configs_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
names_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
enabled: Mapped[bool] = mapped_column(default=False, server_default=text('false'), nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False)
|
||||
scope_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
warehouse_config_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
transform_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class TransferMovementLedger(Base):
|
||||
"""库存异动档(ADR 0001):外部系统收料/出货记录的平台镜像(参照 ERP inaj_t 形态)。
|
||||
|
||||
用途:外部系统收料(一期)/出货(结构就位,record_kind='shipment')记录统一落档;
|
||||
匹配明细(items)由匹配创建时从档圈定生成(落地不再写 items,出生翻转)。
|
||||
幂等增量落地:自然键 (source_code, record_kind, doc_no, line_no, line_seq,
|
||||
in_out_flag) 唯一约束去重——不存在则插入、证据变化则原行更新、文件缺席不删;
|
||||
已执行记录 transfer_executed=true 封存(executed_doc_no 回写),永不更新、
|
||||
永不复活、永不再次被圈定(防二次调拨,档级封存兜底)。
|
||||
刻意双字段:record_kind(文件种类声明,权威)与 in_out_flag(数据列原值),
|
||||
两者矛盾即解析错位,由落档链路打审计事件,记录照常落档。
|
||||
可空语义:自然键成分一律 NOT NULL(line_seq/in_out_flag default '' 保证唯一
|
||||
约束可比),业务/证据列一律 nullable(外部列宽松落地);movement_date 可空——
|
||||
空值记录照常落档但不进收料日期圈定(日期条件恒排除 NULL)。
|
||||
source_file_id ON DELETE SET NULL:来源文件被清理(文件资产保留策略)后
|
||||
档记录必须留存(事实不随文件消失,链接仅溯源)。
|
||||
D 组 ⭐5 列(order_type/odm_id/odm_name/carton_id/pallet_id)为本期新增强
|
||||
业务字段(进解析 Profile 可映射);🔖预留列(doc_nature/movement_type/
|
||||
reason_code/source_ref_no/partner_code/remark)出货报告确认后直接映射,
|
||||
免后续迁移。
|
||||
"""
|
||||
|
||||
__tablename__ = 'transfer_movement_ledger'
|
||||
__table_args__ = (
|
||||
# 自然键唯一(幂等增量落地兜底;应用层按自然键查档先行)。
|
||||
UniqueConstraint(
|
||||
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
|
||||
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'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# --- A 单据标识(自然键成分,NOT NULL;line_seq/in_out_flag 可空成分 default '')---
|
||||
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 交叉校验用,不参与权威判定。
|
||||
in_out_flag: Mapped[str] = mapped_column(String(8), nullable=False, default='', server_default='')
|
||||
# --- B 物料与数量(数量 Decimal 文本,与 items.receipt_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)
|
||||
quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# --- 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,出货侧直接映射)---
|
||||
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)
|
||||
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)
|
||||
reason_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
source_ref_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
partner_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
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 矛盾打审计事件。
|
||||
record_kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
# 来源文件溯源:ON DELETE SET NULL(文件清理后档事实留存)。
|
||||
source_file_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_receipt_report_files.id', ondelete='SET NULL'), nullable=True,
|
||||
)
|
||||
file_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
sheet_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
row_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
# --- F 平台回写(档级封存:票据执行成功落单号时回写,永不解除)---
|
||||
transfer_executed: Mapped[bool] = mapped_column(
|
||||
default=False, server_default=text('false'), nullable=False,
|
||||
)
|
||||
executed_doc_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
|
||||
# 溯源关系:档案行 → 收料原样归档文件(单向,不回挂;ShippingReceiptReportFile
|
||||
# 不感知调拨域,避免跨域 back_populates 环)。
|
||||
source_file: Mapped[Optional['ShippingReceiptReportFile']] = relationship()
|
||||
|
||||
|
||||
@event.listens_for(TransferAuditEvent, 'before_update')
|
||||
def _reject_transfer_audit_update(_mapper, _connection, _target) -> None:
|
||||
"""拒绝 ORM 更新,确保审计事件不可改写。"""
|
||||
|
||||
@@ -162,6 +162,8 @@ agent_types:
|
||||
handler_config_schema: {}
|
||||
in_transit_transfer:
|
||||
label: 在途仓自动调拨
|
||||
# 调拨类型来自平台配置(管理端「在途调拨类型」维护,GET /transfer-types 下发),
|
||||
# 本清单与提示词不硬编码类型列表;Dify 平台侧如有副本需人工同步。
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: hybrid
|
||||
models:
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
|
||||
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
|
||||
Dify Chatflow 生命周期。
|
||||
【调拨类型语义 2026-10-14】调拨类型来自平台配置(管理端「在途调拨类型」
|
||||
维护,`GET /api/in-transit-transfer/transfer-types` 下发);提示词与本
|
||||
Handler 一律不硬编码类型列表,Dify 平台侧如有副本需人工同步。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -34,6 +34,7 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
recover_history: bool = True,
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: str | None = None,
|
||||
sender: WeComSender | None = None,
|
||||
recipients: list[str] | None = None) -> AutoTransferOutcome:
|
||||
"""执行一次自动调拨排程。
|
||||
@@ -48,6 +49,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
recover_history: 是否执行历史恢复。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小
|
||||
匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。
|
||||
transfer_type: 调拨类型编码(D8 匹配创建必填——排程任务参数承载;
|
||||
缺省 None 时匹配层 fail-closed 抛 TRANSFER_TYPE_REQUIRED)。
|
||||
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
|
||||
Returns:
|
||||
AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。
|
||||
@@ -65,6 +68,7 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
deps=deps,
|
||||
receipt_date_from=receipt_date_from,
|
||||
receipt_date_to=receipt_date_to,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
|
||||
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
"""在途调拨历史待处理池与老化分级。
|
||||
"""services/in_transit_transfer/backlog_service.py
|
||||
|
||||
在途调拨历史待处理池与老化分级 + 首页「待匹配」桶(D16)。
|
||||
|
||||
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
|
||||
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。
|
||||
依赖:models、status。
|
||||
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘;
|
||||
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部收料记录,
|
||||
规格 §10/D16:只读清单 + 计数,不可勾选执行)。
|
||||
依赖:models、status、matching_service(启用类型范围并集圈档)。
|
||||
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
|
||||
manually_closed / success / duplicate_success 永久排除。
|
||||
待匹配桶=启用类型范围并集圈档(复用匹配创建的固定条件底座:receipt/
|
||||
未封存/有收料日期/未被有效 items 占用——D17 占用判定一致),无 item_id
|
||||
不可执行;匹配圈定后记录离开本桶,取消匹配释放后回归。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +24,9 @@ from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
circle_ledger_records_scope_union,
|
||||
)
|
||||
from app.services.in_transit_transfer.status import TransferStatus
|
||||
|
||||
AGING_NORMAL = "normal"
|
||||
@@ -53,9 +63,26 @@ class BacklogItemDTO:
|
||||
result_code: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingMatchRecordDTO:
|
||||
"""「待匹配」桶单项(D16):档记录只读投影——无 item_id,不可勾选执行。
|
||||
|
||||
字段与规格 §12.3 只读清单列一致(单号/料号/品名/收料日期/来源/数量);
|
||||
quantity 为档原值文本(Decimal 文本,与 items.receipt_quantity 同约定)。
|
||||
"""
|
||||
|
||||
ledger_record_id: int
|
||||
doc_no: str
|
||||
material_code: Optional[str] = None
|
||||
material_name: Optional[str] = None
|
||||
movement_date: Optional[str] = None
|
||||
source_code: str = ""
|
||||
quantity: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class BacklogSummaryDTO:
|
||||
"""待处理池汇总(含老化分级计数)。"""
|
||||
"""待处理池汇总(含老化分级计数 + 待匹配桶计数)。"""
|
||||
|
||||
recoverable_count: int = 0
|
||||
closed_count: int = 0
|
||||
@@ -63,6 +90,8 @@ class BacklogSummaryDTO:
|
||||
warn_3d: int = 0
|
||||
escalate_5d: int = 0
|
||||
critical_7d: int = 0
|
||||
# 首页第 4 张数字卡(D16):已落档尚未匹配的外部收料记录数。
|
||||
pending_match_count: int = 0
|
||||
|
||||
|
||||
def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str:
|
||||
@@ -165,8 +194,36 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
return output
|
||||
|
||||
|
||||
def list_pending_match_records() -> list[PendingMatchRecordDTO]:
|
||||
"""首页待办看板「待匹配」桶清单(D16:已抓取尚未匹配的外部收料记录,只读)。
|
||||
|
||||
数据源=启用类型范围并集圈档(matching_service.circle_ledger_records_scope_union:
|
||||
固定条件 receipt/未封存/有收料日期/未被有效 items 占用,与匹配创建圈档和 D17
|
||||
占用判定同一实现)。数字变化口径:文件落地→涨;被匹配圈定→离开(占用);
|
||||
取消匹配→回归(释放占用);执行成功→封存恒排除。
|
||||
|
||||
不可执行:记录尚未经匹配/库存核对(无 items),本桶仅提供只读清单与
|
||||
「去匹配」引导,禁止任何勾选执行入口。
|
||||
|
||||
Returns:
|
||||
PendingMatchRecordDTO 列表(圈档稳定排序:收料日期 → 来源 → 单号 → id)。
|
||||
"""
|
||||
return [
|
||||
PendingMatchRecordDTO(
|
||||
ledger_record_id=record.id,
|
||||
doc_no=record.doc_no,
|
||||
material_code=record.material_code,
|
||||
material_name=record.material_name,
|
||||
movement_date=record.movement_date,
|
||||
source_code=record.source_code,
|
||||
quantity=record.quantity,
|
||||
)
|
||||
for record in circle_ledger_records_scope_union()
|
||||
]
|
||||
|
||||
|
||||
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
|
||||
"""计算待处理池汇总计数与老化分级。"""
|
||||
"""计算待处理池汇总计数、老化分级与待匹配桶计数。"""
|
||||
items = list_backlog(now=now)
|
||||
summary = BacklogSummaryDTO()
|
||||
for item in items:
|
||||
@@ -182,4 +239,7 @@ def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
|
||||
summary.escalate_5d += 1
|
||||
elif item.aging_level == AGING_CRITICAL_7D:
|
||||
summary.critical_7d += 1
|
||||
# [待匹配桶计数(D16)] 与行桶相互独立:档记录尚无 items 不进任何行桶,
|
||||
# 只有本计数可见(出生翻转后「抓到了没匹配」的唯一可见位)。
|
||||
summary.pending_match_count = len(list_pending_match_records())
|
||||
return summary
|
||||
@@ -3,7 +3,13 @@
|
||||
用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销;
|
||||
原因必填;取消前后状态进入审计。
|
||||
依赖:models、status、core.errors。
|
||||
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。
|
||||
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消;
|
||||
Run 转取消时其名下匹配(TransferMatching)同步转 cancelled,并按
|
||||
matching_id 圈定名下 ready 未建单行退役为 cancelled——
|
||||
【出生翻转/D17 占用释放出口(规格 §9)】出生行 run_id=None,必须按匹配
|
||||
圈定才能命中:ready 行退役(队列不再可见、执行门禁拒绝)+ 匹配→cancelled
|
||||
(阻断/未成熟行不再占用其圈定的档记录),档记录随即释放、可被后续匹配
|
||||
重新圈定;取消路径不写档(占用释放由状态判定自然达成)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +18,7 @@ from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
|
||||
|
||||
@@ -60,6 +66,28 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
|
||||
).count()
|
||||
if active == 0:
|
||||
run.status = status_machine.TransferRunStatus.CANCELLED.value
|
||||
# [D17 占用释放 + 可执行行退役(规格 §9)] Run 取消时名下未终态匹配同步
|
||||
# 转 cancelled,并按 matching_id 圈定其名下 items 退役:
|
||||
# - ready 且未建单的行 → cancelled(出生行 run_id=None,必须按匹配圈定
|
||||
# 才能命中——否则取消后行仍 ready,队列双份可见、可与重圈匹配双双
|
||||
# 执行=同批档记录二次写 ERP);
|
||||
# - blocked/not_matured 行保留阻断/未成熟解释(不占执行面),其占用
|
||||
# 随匹配状态=cancelled 释放(占用判定见 matching_service);
|
||||
# - executing/result_unknown 行不触碰(在飞/结果裁决中,既有取消语义)。
|
||||
# 取消路径不写档(占用释放由状态判定自然达成)。
|
||||
for matching in db.session.query(TransferMatching).filter_by(run_id=run.id).all():
|
||||
if matching.status in {"success", "failed", "cancelled", "expired"}:
|
||||
continue
|
||||
matching.status = status_machine.TransferRunStatus.CANCELLED.value
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(matching_id=matching.id).all():
|
||||
if (
|
||||
item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
and not item.external_document_no
|
||||
):
|
||||
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||
item.result_code = "cancelled"
|
||||
item.result_message = reason_value
|
||||
cancelled += 1
|
||||
run.completed_at = run.completed_at or datetime.utcnow()
|
||||
db.session.commit()
|
||||
return {"run_no": run.run_no, "cancelled_count": cancelled}
|
||||
@@ -1,94 +1,269 @@
|
||||
"""services/in_transit_transfer/evidence_sync.py
|
||||
|
||||
用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写,
|
||||
主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。
|
||||
依赖:file_parser / invoice_aggregator / transfer_type / source_file_status /
|
||||
matching_service(_item_evaluated_sha、_latest_usable_report_file 复用)/
|
||||
contracts / models / audit。
|
||||
逻辑:一次解析写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
|
||||
整行跳过(幂等,不续新鲜度);sha 变了证据没变 → 刷新名称/规格展示值并只换
|
||||
版本戳;证据变了(数量/批号/仓库)→ 刷新证据并重置回待查(旧库存是对旧数量
|
||||
查的,作废);历史残留 blocked_file_removed 行复现 → 无论证据变化与否无条件
|
||||
恢复待查(防御路径,2026-09-28 起同步不再新产生该码);缺席存续(只换版本戳
|
||||
到最新文件 sha,状态与结果码原样保留——收料 RPA 非全量导出,缺席≠删除;行
|
||||
复现时经 STEP 2 正常刷新)。全程零外部调用(不查 ERP、不触发 RPA);终态行
|
||||
绝不触碰,终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨);
|
||||
不 commit 只 flush(提交归调用方:落地桥自行 commit,匹配/重查随主事务)。
|
||||
13 状态冻结契约内表达待查态:status='matching' + result_code='pending_stock_check'。
|
||||
【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析失败
|
||||
标记(parse_failed 三列置空,投影恢复 ready);桥入口同步失败先 rollback
|
||||
(保持桥隔离),仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID /
|
||||
ReceiptFileSchemaError)把失败事实独立 commit 落到当前可用文件上。
|
||||
用途:收料证据同步——把来源最新可用收料文件解析并镜像落档(库存异动档
|
||||
transfer_movement_ledger,主链路),一次解析、写档不写明细。
|
||||
依赖:file_parser / ledger_sync / source_file_status / matching_service
|
||||
(_latest_usable_report_file 复用)/ contracts / models / audit。
|
||||
逻辑:【2026-10-14 出生翻转(ADR 0001/D3/D4)】本模块不再写 transfer_invoice_items
|
||||
——items 改为匹配创建时从档圈定(见 matching_service);落地产物=档行:
|
||||
①按自然键查档不存在 → 插入(record_kind/溯源五列随行);
|
||||
②同文件重落(sha 一致)→ 幂等跳过(档无 TTL,完全不动行);
|
||||
③证据变化 → 原行更新业务镜像列 + 换溯源(ledger_sync 五分类语义);
|
||||
④文件缺席的档行保留不删(收料 RPA 非全量导出,缺席≠删除);
|
||||
⑤已执行封存行(transfer_executed=true)永不更新永不复活。
|
||||
组装口径:解析行按调拨明细粒度 (doc_no, material_code, movement_date)
|
||||
聚合为领域行(数量相加、其余取组内首行、sheet/row_no 取首行)——与旧
|
||||
items 汇总粒度一致(档断言等价于原 items 断言),保证「档 → 匹配圈定 →
|
||||
严格数量比对」的数量语义不因翻转漂移。
|
||||
全程零外部调用(不查 ERP、不触发 RPA);不 commit 只 flush(提交归调用
|
||||
方:落地桥自行 commit,匹配/重查随主事务)。
|
||||
【档自然键坍缩守卫 终审 I3】组装产物按自然键 (doc_no, line_no, line_seq,
|
||||
in_out_flag) 复检:同键批内 ≥2 行且 material_code 不同(同单号多料号且
|
||||
行级项次全空的输入)→ 每个坍缩键写一条 ledger_natural_key_collapse 审计
|
||||
事件(结果=第二料号行被幂等吞掉,首见为准,数据行为不变)——把静默丢行
|
||||
变显式可观测;事件只在批内实际落档(inserted/updated>0)时打,幂等重落
|
||||
不重复打(防只追加审计表被同文件重落刷爆,与 ledger_sync 交叉校验事件
|
||||
同款防刷口径)。
|
||||
【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析
|
||||
失败标记(parse_failed 三列置空);桥入口同步失败先 rollback(保持桥隔离),
|
||||
仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID / ReceiptFileSchemaError)
|
||||
把失败事实独立 commit 落到当前可用文件上。
|
||||
【对齐入口退役 2026-10-14】align_scope_rows 已删除:匹配/重查不再对文件
|
||||
兜底重解析,改为对档对账(重查见 retry_service.requery_items 对档 reconciliation)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Mapping
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
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 ReceiptFileSchemaError, parse_movement_rows
|
||||
from app.services.in_transit_transfer.invoice_aggregator import aggregate_invoices
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_FILE_REMOVED,
|
||||
RouteNotResolvedError,
|
||||
_item_evaluated_sha,
|
||||
_latest_usable_report_file,
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
parse_movement_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.ledger_sync import (
|
||||
RECORD_KIND_RECEIPT,
|
||||
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,
|
||||
resolve_source_file_status,
|
||||
)
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
TransferType,
|
||||
filter_invoices_for_type,
|
||||
)
|
||||
|
||||
# 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码),
|
||||
# 表示「收料文件已落地、库存侧尚未核对」;禁用新状态值。
|
||||
# 表示「已出生/已重置、库存侧尚未核对」;禁用新状态值。出生翻转后该态出现在
|
||||
# 匹配创建的出生行(评估前置)与重查对账的证据刷新行(重置待查)。
|
||||
SYNC_RESULT_PENDING = "pending_stock_check"
|
||||
|
||||
# 终态集合与 matching_service 原地刷新口径一致:同步永不触碰既定事实。
|
||||
_TERMINAL_ITEM_STATUSES = frozenset({
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
status_machine.TransferStatus.CANCELLED.value,
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||
})
|
||||
# 档自然键坍缩审计事件 kind(终审 I3 冻结字面量;仓库事件 kind 无集中常量表,
|
||||
# 行内常量惯例——ledger_sync.LEDGER_CROSS_CHECK_EVENT 同款)。与交叉校验矛盾
|
||||
# (in_out_flag 错位)分 kind:修复动作不同(前者查导出模板项次列,后者查进出
|
||||
# 库别映射),运维按 kind 检索互不干扰。
|
||||
LEDGER_NATURAL_KEY_COLLAPSE_EVENT = "ledger_natural_key_collapse"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncOutcome:
|
||||
"""一次来源同步的结果计数(审计与兜底日志的数据源)。"""
|
||||
"""一次来源落档的结果计数(审计与兜底日志的数据源;五分类随 ledger_sync)。"""
|
||||
|
||||
source_code: str
|
||||
file_sha256: str
|
||||
inserted: int = 0 # 文件有、本地无 → 插入待查行
|
||||
refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留
|
||||
reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废)
|
||||
absent_kept: int = 0 # 文件里缺席 → 换戳保留状态(存续:缺席≠删除,2026-09-28)
|
||||
skipped: int = 0 # sha 未变的幂等跳过;终态四元组重落地亦计入(不复活)
|
||||
inserted: int = 0 # 自然键不存在 → 插入新档行
|
||||
updated: int = 0 # 证据变化 → 原行更新业务镜像列 + 换溯源
|
||||
skipped: int = 0 # sha 未变的幂等跳过;封存行命中亦计入(sealed_skipped 另计)
|
||||
sealed_skipped: int = 0 # 封存行(transfer_executed=true):永不更新永不复活
|
||||
cross_flagged: int = 0 # record_kind 与 in_out_flag 矛盾且本次实际落档的行数
|
||||
|
||||
|
||||
def _assemble_ledger_rows(
|
||||
parsed: list[ParsedReceiptRow],
|
||||
raw_rows: list[Any],
|
||||
) -> list[dict]:
|
||||
"""把解析行组装为落档领域行 dict(档断言等价于原 items 断言的粒度桥)。
|
||||
|
||||
核心逻辑:[STEP 1] 原始行按 (sheet, row_no) 建索引——ParsedReceiptRow 无扩展
|
||||
字段槽位(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 导出
|
||||
携带项次列,不命中该形态;该坍缩形态由 _detect_natural_key_collapses 检测并
|
||||
落 ledger_natural_key_collapse 审计事件(终审 I3,静默丢行 → 显式可观测)。
|
||||
|
||||
Args:
|
||||
parsed: 已校验解析行(parse_movement_rows 产物)。
|
||||
raw_rows: 原始领域行 dict 列表(ReadyReceiptFile.rows,扩展字段来源)。
|
||||
Returns:
|
||||
领域行 dict 列表(键=movement 契约 field code + 行级溯源 sheet_name/row_no,
|
||||
即 sync_ledger_rows 的 parsed_rows 契约)。
|
||||
"""
|
||||
raw_by_key: dict[tuple[str, Any], Mapping] = {}
|
||||
for raw in raw_rows or []:
|
||||
if not isinstance(raw, Mapping):
|
||||
continue
|
||||
raw_by_key[(str(raw.get("sheet") or "").strip(), raw.get("row_no"))] = raw
|
||||
|
||||
groups: dict[tuple[str, str, str], dict] = {}
|
||||
ordered: list[dict] = []
|
||||
for row in parsed:
|
||||
raw = raw_by_key.get((row.sheet, row.row_no)) or {}
|
||||
key = (row.invoice_no, row.material_no, row.receipt_date.isoformat())
|
||||
group = groups.get(key)
|
||||
if group is None:
|
||||
group = {
|
||||
"doc_no": row.invoice_no,
|
||||
# 无项次列的导出按空串落自然键(可空成分 NOT NULL + default '')。
|
||||
"line_no": str(raw.get("line_no") or "").strip(),
|
||||
"in_out_flag": str(raw.get("in_out_flag") or "").strip(),
|
||||
"material_code": row.material_no,
|
||||
"material_name": row.material_name,
|
||||
"specification": row.specification,
|
||||
"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)),
|
||||
"unit": row.unit,
|
||||
"movement_date": row.receipt_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(),
|
||||
"source_ref_no": str(raw.get("source_ref_no") or "").strip(),
|
||||
"partner_code": str(raw.get("partner_code") or "").strip(),
|
||||
"remark": str(raw.get("remark") or "").strip(),
|
||||
"sheet_name": row.sheet,
|
||||
"row_no": row.row_no,
|
||||
}
|
||||
groups[key] = group
|
||||
ordered.append(group)
|
||||
else:
|
||||
# [数量聚合] 同 (单号,料号,日期) 多行数量相加(与旧 items 汇总同口径)。
|
||||
group["quantity"] = group["quantity"] + Decimal(str(row.receipt_quantity))
|
||||
|
||||
rows: list[dict] = []
|
||||
for group in ordered:
|
||||
flattened = dict(group)
|
||||
flattened["quantity"] = str(group["quantity"])
|
||||
rows.append(flattened)
|
||||
return rows
|
||||
|
||||
|
||||
def _natural_key_text(value: Any) -> str:
|
||||
"""自然键/料号成分归一化(与 ledger_sync._key_text 同口径):None → 空串 + strip。
|
||||
|
||||
Args:
|
||||
value: 领域行 dict 成分原值。
|
||||
Returns:
|
||||
可比对的归一化文本。
|
||||
"""
|
||||
return "" if value is None else str(value).strip()
|
||||
|
||||
|
||||
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 判据即料号不同)。首见序返回,保证审计内容确定。
|
||||
|
||||
Args:
|
||||
rows: _assemble_ledger_rows 产物(成分已归一化)。
|
||||
Returns:
|
||||
坍缩键信息列表(仅含坍缩键):doc_no/line_no/line_seq/in_out_flag +
|
||||
material_codes(首见序全量料号)+ dropped_material_codes(首见后被吞料号)。
|
||||
"""
|
||||
seen: dict[tuple[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")),
|
||||
)
|
||||
material = _natural_key_text(row.get("material_code"))
|
||||
entry = seen.get(key)
|
||||
if entry is None:
|
||||
seen[key] = {"key": key, "materials": [material], "dropped": []}
|
||||
elif material not in entry["materials"]:
|
||||
entry["materials"].append(material)
|
||||
entry["dropped"].append(material)
|
||||
return [
|
||||
{
|
||||
"doc_no": entry["key"][0], "line_no": entry["key"][1],
|
||||
"line_seq": entry["key"][2], "in_out_flag": entry["key"][3],
|
||||
"material_codes": entry["materials"],
|
||||
"dropped_material_codes": entry["dropped"],
|
||||
}
|
||||
for entry in seen.values() if entry["dropped"]
|
||||
]
|
||||
|
||||
|
||||
def _natural_key_collapse_event(*, source_code: str, collapse: dict):
|
||||
"""构造档自然键坍缩审计事件(未落库,由调用方 add——build 契约同 ledger_sync)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(自然键成分,整批一致)。
|
||||
collapse: _detect_natural_key_collapses 的单条坍缩键信息。
|
||||
Returns:
|
||||
已计算 Hash 的 TransferAuditEvent(event_type=ledger_natural_key_collapse,
|
||||
result='failure':数据质量降级——行被吞是既成事实,须运维介入核导出模板)。
|
||||
"""
|
||||
natural_key = "/".join((
|
||||
source_code, RECORD_KIND_RECEIPT,
|
||||
collapse["doc_no"], collapse["line_no"], collapse["line_seq"], collapse["in_out_flag"],
|
||||
))
|
||||
return build_transfer_audit_event(
|
||||
event_type=LEDGER_NATURAL_KEY_COLLAPSE_EVENT,
|
||||
aggregate_type="transfer_movement_ledger",
|
||||
# aggregate_id 列宽 String(128):超长截断防御(全量字段在 after 快照留存,
|
||||
# 与 ledger_sync._cross_check_event 同款防御)。
|
||||
aggregate_id=natural_key[:128],
|
||||
actor_type="system",
|
||||
result="failure",
|
||||
after={
|
||||
"source_code": source_code, "record_kind": RECORD_KIND_RECEIPT,
|
||||
"doc_no": collapse["doc_no"], "line_no": collapse["line_no"],
|
||||
"line_seq": collapse["line_seq"], "in_out_flag": collapse["in_out_flag"],
|
||||
"material_codes": collapse["material_codes"],
|
||||
"dropped_material_codes": collapse["dropped_material_codes"],
|
||||
"resolution": "first_seen_wins",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
|
||||
"""解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。
|
||||
"""解析来源最新可用收料文件并幂等落档(零外部调用,flush 不 commit)。
|
||||
|
||||
【AI 触发时机】收料 RPA 回调桥(sync_and_commit_for_callback)与来源解析
|
||||
失败重试入口调用;不要在匹配/重查链路调用(匹配从档圈定,不写档)。
|
||||
|
||||
【解析失败分层 2026-09-29】成功返回前清除当前可用文件的解析失败标记
|
||||
(parse_failed 三列置空,来源投影恢复 ready)——能走到成功返回即代表该
|
||||
文件已成功解析;无标记时为 no-op。
|
||||
(parse_failed 三列置空)——能走到成功返回即代表该文件已成功解析;无标记时
|
||||
为 no-op。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
deps: TransferDeps(只用 file_repository 与 route_resolver)。
|
||||
deps: TransferDeps(只用 file_repository)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。
|
||||
now: 落档时间基准(插入/更新显式续 updated_at)。
|
||||
Returns:
|
||||
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None(该分支
|
||||
不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。
|
||||
@@ -96,152 +271,45 @@ 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)
|
||||
invoices = filter_invoices_for_type(
|
||||
aggregate_invoices(parsed, file_version=ready.file_version),
|
||||
TransferType.IN_TRANSIT_TO_HUB,
|
||||
|
||||
# [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,
|
||||
parsed_rows=assembled,
|
||||
file_meta=FileMeta(
|
||||
source_file_id=report.id if report is not None else None,
|
||||
file_version=ready.file_version,
|
||||
file_sha256=ready.checksum,
|
||||
),
|
||||
now=now,
|
||||
)
|
||||
# [档自然键坍缩守卫 终审 I3] 组装产物复检:同自然键批内料号不同(同单号多
|
||||
# 料号且项次全空)→ 每个坍缩键写一条审计事件(行处理不变,首见为准——把
|
||||
# 静默丢行变显式可观测)。只在批内实际落档(inserted/updated>0)时打事件:
|
||||
# 幂等重落(sha 未变全跳过)不重复打,防只追加审计表被同文件重落刷爆
|
||||
# (与 ledger_sync 交叉校验事件「矛盾标记随落档动作发生」同款防刷口径)。
|
||||
collapses = _detect_natural_key_collapses(assembled)
|
||||
if collapses and (outcome.inserted or outcome.updated):
|
||||
for collapse in collapses:
|
||||
db.session.add(_natural_key_collapse_event(
|
||||
source_code=source_code, collapse=collapse))
|
||||
result = SyncOutcome(
|
||||
source_code=source_code,
|
||||
file_sha256=ready.checksum or "",
|
||||
inserted=outcome.inserted,
|
||||
updated=outcome.updated,
|
||||
skipped=outcome.skipped,
|
||||
sealed_skipped=outcome.sealed_skipped,
|
||||
cross_flagged=outcome.cross_flagged,
|
||||
)
|
||||
|
||||
# [STEP 1] 圈定本来源全部非终态既有行,按四元组建索引(matching_id 已放开
|
||||
# 非空,落地行不受 uq_transfer_invoice_items_matching_grain 保护,幂等去重
|
||||
# 由本应用层四元组负责)。
|
||||
existing = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == source_code,
|
||||
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
by_key = {(r.source_code, r.invoice_no, r.material_no, r.receipt_date): r for r in existing}
|
||||
|
||||
# [终态去重圈] 终态行同样纳入四元组去重范围(只查四列,轻量):若只在非终态
|
||||
# 行内去重,来源全终态后同文件重落地(同日 RPA 重试再触发落地桥 / align 兜底
|
||||
# 重解析)时 quad 缺席索引会被当全新行重插 pending——已执行的调拨单「复活」
|
||||
# 回待办池,存在以新 doc_no 二次真实执行的风险。终态不复活是冻结约束:
|
||||
# 重落地对终态行既不重插也不触碰。
|
||||
terminal_keys = {
|
||||
tuple(r)
|
||||
for r in TransferInvoiceItem.query.with_entities(
|
||||
TransferInvoiceItem.source_code,
|
||||
TransferInvoiceItem.invoice_no,
|
||||
TransferInvoiceItem.material_no,
|
||||
TransferInvoiceItem.receipt_date,
|
||||
).filter(
|
||||
TransferInvoiceItem.source_code == source_code,
|
||||
TransferInvoiceItem.status.in_(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
}
|
||||
|
||||
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "absent_kept": 0, "skipped": 0}
|
||||
incoming_keys: set[tuple] = set()
|
||||
|
||||
# [STEP 2] 文件内单逐张三分类:跳过 / 插入 / 刷新+重置。
|
||||
for invoice in invoices:
|
||||
receipt_date_iso = invoice.receipt_date.isoformat()
|
||||
key = (source_code, invoice.invoice_no, invoice.material_no, receipt_date_iso)
|
||||
incoming_keys.add(key)
|
||||
row = by_key.get(key)
|
||||
# [终态不复活] 该四元组已有终态行(已执行/已关闭等):同文件重落地跳过
|
||||
# 整行——不重插新 pending 行,也不触碰终态行本身(计数归 skipped 口径)。
|
||||
# 必须在插入判定之前拦截,否则全终态来源重落地会重开已执行的调拨单。
|
||||
if row is None and key in terminal_keys:
|
||||
counters["skipped"] += 1
|
||||
continue
|
||||
# [证据变化判定] 只比对收料事实(数量/批号/仓库);material_name 等展示
|
||||
# 字段不触发重置(重置会作废旧库存查询,代价是重查)。
|
||||
evidence_changed = row is None or (
|
||||
str(row.receipt_quantity) != str(invoice.receipt_quantity)
|
||||
or (row.lot_no or "") != (invoice.lot_no or "")
|
||||
or (row.receipt_warehouse_code or "") != (invoice.warehouse_code or "")
|
||||
)
|
||||
if row is not None and not evidence_changed and _item_evaluated_sha(row) == ready.checksum:
|
||||
counters["skipped"] += 1 # [幂等] 同文件重复落地:零写入(不续新鲜度)
|
||||
continue
|
||||
if row is None:
|
||||
from_wh, to_wh = _resolve_route_best_effort(deps, source_code, invoice)
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None, # 落地行尚无匹配归属(列已放开非空)
|
||||
source_code=source_code,
|
||||
invoice_no=invoice.invoice_no,
|
||||
material_no=invoice.material_no,
|
||||
material_name=invoice.material_name,
|
||||
specification=invoice.specification,
|
||||
receipt_date=receipt_date_iso,
|
||||
status=status_machine.TransferStatus.MATCHING.value,
|
||||
result_code=SYNC_RESULT_PENDING,
|
||||
result_message=None,
|
||||
from_warehouse=from_wh,
|
||||
to_warehouse=to_wh,
|
||||
receipt_quantity=str(invoice.receipt_quantity),
|
||||
external_quantity=None,
|
||||
lot_no=invoice.lot_no or "",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
unit="", # 单位只取 ERP stock_unit,匹配查询时落列
|
||||
raw_lines_json=[
|
||||
{"sheet": line.sheet, "row_no": line.row_no,
|
||||
"file_version": line.file_version, "file_sha256": ready.checksum}
|
||||
for line in invoice.raw_lines
|
||||
],
|
||||
updated_at=now,
|
||||
))
|
||||
counters["inserted"] += 1
|
||||
continue
|
||||
# [Important② 复现行] 历史残留消失标记行(blocked_file_removed)重新出现
|
||||
# 在最新文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)
|
||||
# 已失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。
|
||||
# 非终态行恢复不违反终态冻结。历史残留行防御(2026-09-28 起同步不再新产生该码)。
|
||||
restored_from_removed = row.result_code == RESULT_FILE_REMOVED
|
||||
# [版本戳] 行随最新文件版本刷新(复现行与普通行同路径换新戳,对齐入口
|
||||
# 据此收敛直通)。
|
||||
row.raw_lines_json = [
|
||||
{"sheet": line.sheet, "row_no": line.row_no,
|
||||
"file_version": line.file_version, "file_sha256": ready.checksum}
|
||||
for line in invoice.raw_lines
|
||||
]
|
||||
# [Important① 展示字段] 名称/规格属展示字段:进入非跳过分支即刷新
|
||||
# (放在证据分支判断之外)——是否重置待查只由三证据字段决定,避免纯
|
||||
# 名称变更落入 refreshed 后展示值随新戳固化(align 直通后永不更新)。
|
||||
row.material_name = invoice.material_name
|
||||
row.specification = invoice.specification
|
||||
if evidence_changed:
|
||||
# [STEP 3] 收料事实变化:刷新证据值(数量/批号/仓库)。
|
||||
row.receipt_quantity = str(invoice.receipt_quantity)
|
||||
row.lot_no = invoice.lot_no or ""
|
||||
row.receipt_warehouse_code = invoice.warehouse_code or ""
|
||||
if evidence_changed or restored_from_removed:
|
||||
# [重置/恢复] 值变 → 重置回待查(旧库存是对旧数量查的,作废);
|
||||
# 复现行 → 恢复待查(重新进入待办池,计数同归 reset_pending 口径)。
|
||||
row.status = status_machine.TransferStatus.MATCHING.value
|
||||
row.result_code = SYNC_RESULT_PENDING
|
||||
row.result_message = None
|
||||
row.external_quantity = None # 旧库存对旧数量,作废待重查
|
||||
# [库存查得时刻] 库存作废即置空取数时刻(不变式:本字段=当前
|
||||
# external_quantity 的取数时间;NULL=无库存数据,stale 不判定)。
|
||||
row.inventory_checked_at = None
|
||||
counters["reset_pending"] += 1
|
||||
else:
|
||||
counters["refreshed"] += 1
|
||||
# refreshed/absent_kept 只换文件版本戳——本分支不续期 inventory_checked_at
|
||||
#(2026-09-29 起 stale 判定时钟,换戳≠查过库存),仅 updated_at 照常续期。
|
||||
row.updated_at = now
|
||||
|
||||
# [STEP 4] 文件里缺席的非终态行 → 存续处理(2026-09-28 语义升级):收料 RPA
|
||||
# 导出非全量,缺席≠删除(行业存续原则)——保留原 status/result_code/message,
|
||||
# 只把版本戳换到最新文件 sha(保留 sheet/row_no 行定位):对齐入口 row_shas
|
||||
# 收敛直通、执行门禁②继续放行(历史行不会被 TRANSFER.FILE_CHANGED 死锁)。
|
||||
# 行日后复现时 evaluated_sha≠新文件 sha,自然走 STEP 2 刷新/重置分支;真实
|
||||
# 删除由人工关闭兜底(待处理池 3/5/7 天老化防遗忘)。终态行不在 by_key,
|
||||
# 绝不触碰。
|
||||
for key, row in by_key.items():
|
||||
if key in incoming_keys:
|
||||
continue
|
||||
row.raw_lines_json = [
|
||||
{**line, "file_version": ready.file_version, "file_sha256": ready.checksum}
|
||||
for line in (row.raw_lines_json or [])
|
||||
]
|
||||
row.updated_at = now
|
||||
counters["absent_kept"] += 1
|
||||
|
||||
# [STEP 5] 只 flush 不 commit:落地桥自行 commit,匹配/重查随主事务。
|
||||
db.session.flush()
|
||||
outcome = SyncOutcome(source_code=source_code, file_sha256=ready.checksum or "", **counters)
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_EVIDENCE_SYNCED",
|
||||
aggregate_type="transfer_source",
|
||||
@@ -249,92 +317,38 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
|
||||
actor_type="system",
|
||||
result="success",
|
||||
after={
|
||||
"file_sha256": outcome.file_sha256,
|
||||
"inserted": outcome.inserted, "refreshed": outcome.refreshed,
|
||||
"reset_pending": outcome.reset_pending, "absent_kept": outcome.absent_kept,
|
||||
"skipped": outcome.skipped,
|
||||
"file_sha256": result.file_sha256,
|
||||
"record_kind": RECORD_KIND_RECEIPT,
|
||||
"inserted": result.inserted, "updated": result.updated,
|
||||
"skipped": result.skipped, "sealed_skipped": result.sealed_skipped,
|
||||
"cross_flagged": result.cross_flagged,
|
||||
},
|
||||
))
|
||||
# [解析失败分层 2026-09-29] 同步成功 = 当前可用文件已成功解析:清除其解析
|
||||
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。查询口径与
|
||||
# source_file_status 一致(_latest_usable_report_file);只 flush 不 commit,
|
||||
# 提交归调用方(桥自行 commit / 匹配随主事务)。无可用 ORM 文件(Fake
|
||||
# 仓库测试场景/文件已清理)时为 no-op。
|
||||
report = _latest_usable_report_file(source_code)
|
||||
# 失败标记(若此前失败过),来源状态投影随之恢复 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)
|
||||
return outcome
|
||||
|
||||
|
||||
def align_scope_rows(*, source_codes: list[str], deps, business_date: str, now: datetime) -> dict:
|
||||
"""兜底对齐入口:行版本戳 ≠ 最新文件 sha 的来源才重新解析(一致直通零开销)。
|
||||
|
||||
【AI 触发时机】:匹配(run_matching STEP 0)与重查(requery_* STEP 0)调用;
|
||||
落地同步(主链路)失败的静默兜底——稳态下 sha 一致,本函数零解析直通。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例编码列表。
|
||||
deps: TransferDeps(透传 sync_source_rows)。
|
||||
business_date: 业务日期(文件新鲜度口径)。
|
||||
now: 新鲜度基准。
|
||||
Returns:
|
||||
{source_code: SyncOutcome|None};None=已对齐或无可用文件(未解析)。
|
||||
"""
|
||||
outcomes: dict = {}
|
||||
for code in source_codes:
|
||||
latest = resolve_source_file_status(source_code=code) or {}
|
||||
latest_sha = latest.get("file_sha256")
|
||||
if not latest_sha:
|
||||
outcomes[code] = None
|
||||
continue
|
||||
rows = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == code,
|
||||
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
row_shas = {_item_evaluated_sha(r) for r in rows}
|
||||
if row_shas == {latest_sha}:
|
||||
outcomes[code] = None # 已对齐:直通
|
||||
continue
|
||||
outcomes[code] = sync_source_rows(source_code=code, deps=deps,
|
||||
business_date=business_date, now=now)
|
||||
return outcomes
|
||||
|
||||
|
||||
def _resolve_route_best_effort(deps, source_code: str, invoice) -> tuple[str, str]:
|
||||
"""同步期预解析路由落列(纯配置查表);解析失败留空不阻断(匹配时再解析)。
|
||||
|
||||
Args:
|
||||
deps: TransferDeps(只用 route_resolver)。
|
||||
source_code: 来源实例编码。
|
||||
invoice: AggregatedInvoice(取 invoice_no / warehouse_code)。
|
||||
Returns:
|
||||
(from_warehouse, to_warehouse);未配置路由返回 ("", "")。
|
||||
"""
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=source_code, invoice_no=invoice.invoice_no,
|
||||
warehouse_code=invoice.warehouse_code or "",
|
||||
)
|
||||
return route.from_warehouse, route.to_warehouse
|
||||
except RouteNotResolvedError:
|
||||
return "", ""
|
||||
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)。
|
||||
【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类
|
||||
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上。
|
||||
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上;
|
||||
丢失的落档由回调重试/来源「重试 RPA」入口(本地重解析)兜底
|
||||
(原 align 兜底入口已随对档对账切换退役)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(收料单元行上的 source_code)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at)。
|
||||
now: 落档时间基准。
|
||||
Returns:
|
||||
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志;
|
||||
True=落档成功或无事可做(无可用文件);False=落档失败(已记日志;
|
||||
schema 类失败尽力把解析失败标记落库并独立提交,标记失败仅告警不影响返回)。
|
||||
"""
|
||||
from flask import current_app
|
||||
@@ -344,24 +358,24 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
|
||||
business_date=business_date, now=now)
|
||||
# [桥隔离] sync_source_rows 只 flush 不 commit;桥由回调主链路在归档
|
||||
# commit 之后独立调用,提交时机不归调用方管(B3 持久性教训),必须
|
||||
# 在此自行提交,否则请求结束 session 回滚会丢掉已解析的待办行。
|
||||
# 在此自行提交,否则请求结束 session 回滚会丢掉已解析的档行。
|
||||
db.session.commit()
|
||||
if outcome is not None:
|
||||
current_app.logger.info(
|
||||
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s absent=%s skipped=%s",
|
||||
source_code, outcome.inserted, outcome.refreshed,
|
||||
outcome.reset_pending, outcome.absent_kept, outcome.skipped)
|
||||
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s updated=%s skipped=%s sealed=%s cross=%s",
|
||||
source_code, outcome.inserted, outcome.updated,
|
||||
outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
|
||||
# [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,同步崩溃
|
||||
# 绝不允许波及收料归档终态;丢失的同步由对齐入口 align_scope_rows 兜底。
|
||||
# [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,落档崩溃
|
||||
# 绝不允许波及收料归档终态;丢失的落档由回调重试/人工重取兜底。
|
||||
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)
|
||||
# 落库——通用异常(网络/DB 故障等)不是文件解析问题,不落标记。标记写入后
|
||||
# 独立 commit(B3:桥自行提交;同步数据已回滚,本次 commit 只持久化失败
|
||||
# 独立 commit(B3:桥自行提交;落档数据已回滚,本次 commit 只持久化失败
|
||||
# 事实),桥隔离语义保持,仍返回 False。
|
||||
# [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows
|
||||
# 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。
|
||||
|
||||
@@ -37,6 +37,7 @@ from app.models import (
|
||||
TransferDocument,
|
||||
TransferInvoiceItem,
|
||||
TransferMatching,
|
||||
TransferMovementLedger,
|
||||
TransferRun,
|
||||
User,
|
||||
)
|
||||
@@ -57,9 +58,8 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
_item_evaluated_sha,
|
||||
scope_item_query,
|
||||
item_external_lot_no,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.orchestrator import (
|
||||
create_execution_run_for_items,
|
||||
@@ -151,9 +151,25 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv
|
||||
).all()
|
||||
by_id = {row.id: row for row in rows}
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
# [防御性双保险(规格 §9)] 所属匹配已取消的行不得执行:取消路径已把匹配
|
||||
# 名下 ready 行退役,此处按匹配状态再拒一次(防绕过取消路径的状态组合)。
|
||||
from app.models import TransferMatching as _Matching
|
||||
|
||||
row_matching_ids = {row.matching_id for row in rows if row.matching_id is not None}
|
||||
cancelled_matching_ids: set[int] = set()
|
||||
if row_matching_ids:
|
||||
cancelled_matching_ids = {
|
||||
mid for (mid,) in (
|
||||
db.session.query(_Matching.id)
|
||||
.filter(_Matching.id.in_(row_matching_ids), _Matching.status == "cancelled")
|
||||
.all()
|
||||
)
|
||||
}
|
||||
invalid = [
|
||||
i for i in ordered_ids
|
||||
if by_id.get(i) is None or by_id[i].status != ready_status
|
||||
if by_id.get(i) is None
|
||||
or by_id[i].status != ready_status
|
||||
or by_id[i].matching_id in cancelled_matching_ids
|
||||
]
|
||||
if invalid:
|
||||
raise ValidationError(
|
||||
@@ -606,18 +622,18 @@ def _recheck_stock_for_document(
|
||||
"""
|
||||
grouped: dict[str, list[tuple[TransferInvoiceItem, RouteMapping]]] = {}
|
||||
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 "",
|
||||
)
|
||||
# [外部形态 + 仓库定义] 行级路由解析叠加行所属匹配类型的仓库定义
|
||||
# (fixed 覆盖映射档);批号经匹配快照转换规则派生(与匹配/重查同一口径)。
|
||||
from app.services.in_transit_transfer.retry_service import _route_for_item
|
||||
|
||||
route = _route_for_item(deps, item)
|
||||
grouped.setdefault(str(route.external_org or "").strip(), []).append((item, route))
|
||||
kept: list[TransferInvoiceItem] = []
|
||||
for external_org, entries in grouped.items():
|
||||
# [外部形态] 写前复查与匹配/重查同一批号派生口径(movement_contract.external_lot_no)。
|
||||
targets = [
|
||||
StockTarget(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
lot_no=item_external_lot_no(item),
|
||||
)
|
||||
for item, route in entries
|
||||
]
|
||||
@@ -632,7 +648,7 @@ def _recheck_stock_for_document(
|
||||
for item, route in entries:
|
||||
row = stock.lookup_row(
|
||||
material_no=item.material_no,
|
||||
warehouse_code=route.from_warehouse, lot_no=external_lot_no(item.lot_no),
|
||||
warehouse_code=route.from_warehouse, lot_no=item_external_lot_no(item),
|
||||
)
|
||||
# [库存查得时刻] 写前复查是真实取数:无论查无/漂移/通过,随后落定的
|
||||
# external_quantity 都以本次取数为准(stale 判定时钟,见 _item_dto)。
|
||||
@@ -861,12 +877,12 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
"""
|
||||
grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {}
|
||||
for item in items:
|
||||
# [外部形态] 聚合键批号按 WTP→HOW 派生(movement_contract.external_lot_no):
|
||||
# ERP 行粒度=外部批号身份,同一 ERP 批次不得因 WMS 前缀形态差异拆行;
|
||||
# 行下传 lot_no(key[1])随键即为外部形态。
|
||||
# [外部形态] 聚合键批号经行所属匹配快照转换规则派生(类型配置驱动,
|
||||
# 如 WTP→HOW):ERP 行粒度=外部批号身份,同一 ERP 批次不得因 WMS 前缀
|
||||
# 形态差异拆行;行下传 lot_no(key[1])随键即为外部形态,行落库保持原值。
|
||||
key = (
|
||||
str(item.material_no or "").strip(),
|
||||
external_lot_no(item.lot_no),
|
||||
item_external_lot_no(item),
|
||||
str(item.from_warehouse or "").strip(),
|
||||
str(item.to_warehouse or "").strip(),
|
||||
)
|
||||
@@ -922,15 +938,47 @@ def _order_snapshot(*, run_no: str, order: TransferOrder, final_only: bool, line
|
||||
}
|
||||
|
||||
|
||||
def _seal_ledger_records(items: list[TransferInvoiceItem], *, executed_doc_no: str | None) -> None:
|
||||
"""档级封存回写(规格 §9 防二次执行的档级兜底)。
|
||||
|
||||
【AI 触发时机】仅 _apply_result 的 success/duplicate_success 分支调用——票据
|
||||
执行成功落 ERP 单号时,把单内行关联的档记录置 transfer_executed=true +
|
||||
executed_doc_no。失败/未知态不得调用(执行未成事实,记录仍可被圈定、
|
||||
仍应可见于待匹配桶)。幂等:等值重复回写无副作用(封存位布尔语义,首次/
|
||||
末次等效,复用单 duplicate_success 重跑恒封存);行无档关联(遗留行)跳过。
|
||||
回写只 flush 不 commit(随调用方事务,与六态落位同生命周期)。
|
||||
|
||||
Args:
|
||||
items: 本单(或遗留单行路径)参与落位的行集。
|
||||
executed_doc_no: 回写单号(ERP 单号优先,缺失回退平台单号;为空直接跳过)。
|
||||
"""
|
||||
if not executed_doc_no:
|
||||
return
|
||||
record_ids = {item.ledger_record_id for item in items if item.ledger_record_id is not None}
|
||||
if not record_ids:
|
||||
return
|
||||
records = (
|
||||
db.session.query(TransferMovementLedger)
|
||||
.filter(TransferMovementLedger.id.in_(record_ids))
|
||||
.all()
|
||||
)
|
||||
for record in records:
|
||||
record.transfer_executed = True
|
||||
record.executed_doc_no = executed_doc_no
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _apply_result(*, doc: TransferDocument | None, items: list[TransferInvoiceItem], attempt: TransferAttempt, result: Any) -> None:
|
||||
"""按写结果六态落位单、行与 Attempt(result_unknown 为终态,禁止自动重试)。
|
||||
|
||||
六态落位(D7②/D11):
|
||||
- success / duplicate_success → 单与行推进成功族 + ERP 单号一致。
|
||||
- success / duplicate_success → 单与行推进成功族 + ERP 单号一致;
|
||||
并档级封存回写(_seal_ledger_records:items 关联档记录
|
||||
transfer_executed=true + executed_doc_no,规格 §9 防二次执行)。
|
||||
- result_unknown → 单/行 result_unknown 终态(唯一出口 = 人工 retrigger)。
|
||||
- business_failed / technical_failed → 行 blocked_recoverable
|
||||
(R6 裁决后非末步超时/失败已由引擎归 technical_failed),单保留失败态
|
||||
待人工关闭(D18)或复用重跑(D7①②)。
|
||||
待人工关闭(D18)或复用重跑(D7①②);档记录不封存(未成事实)。
|
||||
"""
|
||||
attempt.response_summary_json = {
|
||||
"status": result.status,
|
||||
@@ -950,6 +998,14 @@ def _apply_result(*, doc: TransferDocument | None, items: list[TransferInvoiceIt
|
||||
item.external_document_no = result.document_no
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
# [档级封存回写(规格 §9)] 票据成功落 ERP 单号即封存其档记录:
|
||||
# 防同一外部收料记录经新匹配二次执行;圈档/待匹配桶/队列的固定条件
|
||||
# transfer_executed=false 恒排除已封存记录。幂等等值覆盖(复用单重跑恒封存)。
|
||||
_seal_ledger_records(
|
||||
items,
|
||||
executed_doc_no=str(result.document_no or "").strip()
|
||||
or (doc.doc_no if doc is not None else None),
|
||||
)
|
||||
attempt.status = "success"
|
||||
elif result.status == "result_unknown":
|
||||
for item in items:
|
||||
@@ -1204,10 +1260,10 @@ def execute_matching_items(
|
||||
actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> ExecuteOutcome:
|
||||
"""按匹配 scope 圈定 ready 行并按单执行(chat action / 自动排程共用入口)。
|
||||
"""按匹配自有 items 圈定 ready 行并按单执行(chat action / 自动排程共用入口)。
|
||||
|
||||
行归属与匹配解耦(原地刷新)后,"这份匹配覆盖哪些行"由 scope 重新圈定
|
||||
(scope_item_query:来源 + 收料日期区间 + 调拨类型前缀);本入口按 scope 取
|
||||
【出生翻转】行由匹配创建时从档圈定且创建即绑定(matching_id),"这份匹配
|
||||
覆盖哪些行"=自有 items(scope_item_query 实时圈行已退役);本入口按匹配取
|
||||
ready_to_execute 行(可选 invoice_nos 过滤)后委托 execute_items 执行,
|
||||
两道门禁与单据级组建单由 execute_items/prepare_execution 统一裁定。
|
||||
|
||||
@@ -1222,8 +1278,11 @@ def execute_matching_items(
|
||||
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
ready_rows = (
|
||||
scope_item_query(matching)
|
||||
.filter(TransferInvoiceItem.status == ready_status)
|
||||
TransferInvoiceItem.query
|
||||
.filter(
|
||||
TransferInvoiceItem.matching_id == matching.id,
|
||||
TransferInvoiceItem.status == ready_status,
|
||||
)
|
||||
.order_by(TransferInvoiceItem.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""services/in_transit_transfer/field_transforms.py
|
||||
|
||||
用途:调拨类型字段转换规则引擎——「外部系统值→ERP 值」的受控派生
|
||||
(一期仅 lot_no 前缀替换),只在系统边界生效;行与档保持文件原值。
|
||||
依赖:app.core.errors.ValidationError。
|
||||
逻辑:parse 校验白名单 → TransformRule 元组;apply 按序链式派生(未命中恒等)。
|
||||
【AI 触发时机】任何把行上字段值发往外部系统或按派生值聚合/展示的场景
|
||||
(库存查询 targets、写前复查、建单单行、票行聚合键、前端批号展示),
|
||||
必须经本引擎按当前匹配快照的规则求值;禁止直接调用硬编码前缀转换。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 受控字段/转换方式词表(封闭可扩展;新增须同步管理页下拉与 technical.md)。
|
||||
TRANSFORM_FIELDS: frozenset[str] = frozenset({"lot_no"})
|
||||
TRANSFORM_OPS: frozenset[str] = frozenset({"prefix_replace"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransformRule:
|
||||
"""单条转换规则:field 字段 / op 转换方式 / source 原前缀 / target 新前缀。"""
|
||||
|
||||
field: str
|
||||
op: str
|
||||
source: str
|
||||
target: str
|
||||
|
||||
|
||||
def parse_transform_rules(raw: list[dict] | None) -> tuple[TransformRule, ...]:
|
||||
"""校验并解析转换规则 JSON;空列表/None = 恒等(无转换)。
|
||||
|
||||
Args:
|
||||
raw: [{"field", "op", "source", "target"}],来自调拨类型配置 JSON;
|
||||
空列表/None 合法(= 该类型不做字段转换)。
|
||||
Returns:
|
||||
TransformRule 元组(source/target 统一大写,保证匹配口径一致)。
|
||||
Raises:
|
||||
ValidationError: field 不在 TRANSFORM_FIELDS、op 不在 TRANSFORM_OPS、
|
||||
或 source/target 为空(code=TRANSFER.TRANSFORM_RULE_INVALID)。
|
||||
"""
|
||||
rules: list[TransformRule] = []
|
||||
for item in raw or []:
|
||||
field, op = str(item.get("field", "")), str(item.get("op", ""))
|
||||
source, target = str(item.get("source", "")), str(item.get("target", ""))
|
||||
if field not in TRANSFORM_FIELDS or op not in TRANSFORM_OPS or not source or not target:
|
||||
raise ValidationError(
|
||||
f"invalid transform rule: {field}/{op}", code="TRANSFER.TRANSFORM_RULE_INVALID",
|
||||
details={"field": field, "op": op},
|
||||
)
|
||||
rules.append(TransformRule(field=field, op=op, source=source.upper(), target=target.upper()))
|
||||
return tuple(rules)
|
||||
|
||||
|
||||
def apply_field_transforms(field: str, value: str | None, rules: Sequence[TransformRule]) -> str | None:
|
||||
"""按规则序链式派生;未命中规则恒等返回原值(None/空串透传)。
|
||||
|
||||
Args:
|
||||
field: 行字段名(仅 TRANSFORM_FIELDS 内的字段会被规则命中)。
|
||||
value: 该字段当前原值(来自行/档,永不被本函数改写——只返回新值)。
|
||||
rules: parse_transform_rules 产出的规则元组,按配置序链式生效。
|
||||
Returns:
|
||||
派生后的新值;None 与空串原样透传(不做前缀替换)。
|
||||
"""
|
||||
result = value
|
||||
for rule in rules:
|
||||
if rule.field != field or not result:
|
||||
continue
|
||||
if rule.op == "prefix_replace" and result.upper().startswith(rule.source):
|
||||
result = rule.target + result[len(rule.source):]
|
||||
return result
|
||||
|
||||
|
||||
def transform_rules_note(rules: Sequence[TransformRule]) -> str:
|
||||
"""转换规则审计说明。
|
||||
|
||||
Args:
|
||||
rules: parse_transform_rules 产出的规则元组。
|
||||
Returns:
|
||||
如 "lot_no prefix_replace WTP->HOW THEN lot_no prefix_replace HOW->HOWX"
|
||||
的人读字符串(空规则返回空串),供审计日志/详情页展示。
|
||||
"""
|
||||
return " THEN ".join(f"{r.field} {r.op} {r.source}->{r.target}" for r in rules)
|
||||
@@ -0,0 +1,262 @@
|
||||
"""services/in_transit_transfer/ledger_sync.py
|
||||
|
||||
用途:库存异动档落地(ADR 0001)——外部记录镜像落地:把解析产物(movement 契约
|
||||
领域行)按自然键幂等镜像到 transfer_movement_ledger;语义与 evidence_sync
|
||||
三分类同源(插入/跳过/原行更新,ADR 0001),一期收料(record_kind='receipt'),
|
||||
shipment 为预留合法值(校验放行,不特判)。
|
||||
依赖: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
|
||||
并写 ledger_cross_check_failed 审计事件,记录照常落档;矛盾标记随落档动作
|
||||
发生(插入/更新时)——幂等重落不重复打事件,防只追加审计表被同文件重落刷爆;
|
||||
封存行不落档故不标记(sealed_skipped 即信号)。
|
||||
只 flush 不 commit(与 evidence_sync 同契约,提交归调用方:落地桥自行 commit,
|
||||
匹配/执行随主事务)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import TransferMovementLedger
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
# 契约字段 code ↔ 档列名 1:1 镜像不变式(import 期锁定;MOVEMENT_FIELDS 追加字段
|
||||
# 时必须同步 TransferMovementLedger 模型列,否则此处导入即失败——fail-fast)。
|
||||
_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"
|
||||
# 交叉校验矛盾审计事件 kind(任务简报冻结字面量;仓库事件 kind 无集中常量表,行内字面量惯例)。
|
||||
LEDGER_CROSS_CHECK_EVENT = "ledger_cross_check_failed"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileMeta:
|
||||
"""一次落地的来源文件证据三元组(溯源的文件级成分;Task 11 从归档文件组装)。
|
||||
|
||||
Args:
|
||||
source_file_id: 收料原样归档文件 id(shipping_receipt_report_files.id;
|
||||
测试/极端场景可为 None——档事实留存不依赖文件存在)。
|
||||
file_version: 文件版本号(Task 13 执行门禁 file_current 比对依据)。
|
||||
file_sha256: 文件 SHA-256(幂等跳过判定的唯一证据指纹)。
|
||||
"""
|
||||
|
||||
source_file_id: int | None = None
|
||||
file_version: str | None = None
|
||||
file_sha256: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LedgerSyncOutcome:
|
||||
"""一次落档的结果计数(审计与兜底日志的数据源;字段顺序为任务简报冻结契约)。"""
|
||||
|
||||
inserted: int = 0 # 自然键不存在 → 插入新档行
|
||||
updated: int = 0 # 证据变化 → 原行更新业务镜像列 + 换溯源
|
||||
skipped: int = 0 # sha 未变的幂等跳过;同批自然键重复的后续行亦计入
|
||||
sealed_skipped: int = 0 # 封存行(transfer_executed=true)命中即计:永不更新永不复活
|
||||
cross_flagged: int = 0 # record_kind 与 in_out_flag 矛盾且本次实际落档的行数
|
||||
|
||||
|
||||
def _key_text(value: Any) -> str:
|
||||
"""自然键成分归一化:None → 空串,其余 str + strip(键成分 NOT NULL 恒有值可比)。"""
|
||||
return "" if value is None else str(value).strip()
|
||||
|
||||
|
||||
def _mirror_text(value: Any) -> str | None:
|
||||
"""业务镜像值归一化:None 保留(宽松落地可空),其余 str + strip 原样落档。"""
|
||||
return None if value is None else str(value).strip()
|
||||
|
||||
|
||||
def _opt_int(value: Any) -> int | None:
|
||||
"""可选整数(row_no):缺失/无效宽容置 None(溯源缺失不打断落地)。"""
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _cross_check_event(
|
||||
*,
|
||||
source_code: str,
|
||||
record_kind: str,
|
||||
key: tuple[str, str, str, str],
|
||||
sheet_name: str | None,
|
||||
row_no: int | None,
|
||||
file_meta: FileMeta,
|
||||
):
|
||||
"""构造交叉校验矛盾审计事件(未落库,由调用方 add——build 契约同 audit 模块)。
|
||||
|
||||
Args:
|
||||
source_code / record_kind: 来源实例编码与记录种类。
|
||||
key: 自然键四成分 (doc_no, line_no, line_seq, in_out_flag)(已归一化)。
|
||||
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))
|
||||
return build_transfer_audit_event(
|
||||
event_type=LEDGER_CROSS_CHECK_EVENT,
|
||||
aggregate_type="transfer_movement_ledger",
|
||||
# aggregate_id 列宽 String(128):超长截断防御(全量字段在 after 快照留存)。
|
||||
aggregate_id=natural_key[:128],
|
||||
actor_type="system",
|
||||
result="failure",
|
||||
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,
|
||||
"file_version": file_meta.file_version, "file_sha256": file_meta.file_sha256,
|
||||
"sheet_name": sheet_name, "row_no": row_no,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def sync_ledger_rows(
|
||||
*,
|
||||
source_code: str,
|
||||
record_kind: str,
|
||||
parsed_rows: list[dict],
|
||||
file_meta: FileMeta,
|
||||
now: datetime,
|
||||
) -> LedgerSyncOutcome:
|
||||
"""按自然键幂等落地一批领域行到库存异动档(零外部调用,flush 不 commit)。
|
||||
|
||||
【AI 触发时机】Task 11 接线后由落地主链路(evidence_sync 同步入口)在收料
|
||||
文件落地成功时调用;未来出货报告接入时以 record_kind='shipment' 复用。
|
||||
不要在匹配/执行链路调用本函数(匹配从档圈定,不写档)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(自然键成分,整批一致)。
|
||||
record_kind: 记录种类(文件种类声明,权威):'receipt' 一期;'shipment'
|
||||
预留合法值(校验放行,不特判)。
|
||||
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(缺失按空串落档,
|
||||
必填校验归解析层,本函数不做二次阻断)。
|
||||
file_meta: 来源文件证据三元组(FileMeta);file_sha256 为 None 时无法证明
|
||||
与档行同源,一律走更新分支(宁可重写不误跳)。
|
||||
now: 落档时间基准(插入/更新显式续 updated_at;跳过不续——完全不动行)。
|
||||
Returns:
|
||||
LedgerSyncOutcome 五分类计数(inserted/updated/skipped/sealed_skipped/
|
||||
cross_flagged)。
|
||||
"""
|
||||
counters = {"inserted": 0, "updated": 0, "skipped": 0, "sealed_skipped": 0, "cross_flagged": 0}
|
||||
|
||||
# [STEP 1] 只圈定批内 doc_no 的既有档行(含封存行——封存命中必须可见),按自然键
|
||||
# 建索引;source_code/record_kind 整批恒定,键只留四成分。档「缺席不删、永不
|
||||
# 删除」行数单调增长(评审 Important 修复):按 source+kind 全量水化会使每次
|
||||
# 落地成本随历史线性膨胀(Task 11 接生产落地热路径),故追加 doc_no IN 批内
|
||||
# 过滤——批外键本就查不到、不参与任何分支,语义与全量查询 100% 等价;
|
||||
# in_([]) 空批由 SQLAlchemy 渲染恒假子句,安全。
|
||||
doc_nos = sorted({_key_text(raw.get("doc_no")) for raw in parsed_rows})
|
||||
existing = (
|
||||
TransferMovementLedger.query.filter_by(
|
||||
source_code=source_code, record_kind=record_kind,
|
||||
)
|
||||
.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}
|
||||
# 同批自然键去重索引(首见为准):批内重复若不拦截,二次插入会撞
|
||||
# uq_transfer_movement_ledger_natural_key 唯一约束炸 flush。
|
||||
landed: dict[tuple[str, str, str, str], TransferMovementLedger] = {}
|
||||
|
||||
# [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)
|
||||
sheet_name = _mirror_text(raw.get("sheet_name"))
|
||||
row_no = _opt_int(raw.get("row_no"))
|
||||
|
||||
row = by_key.get(key) or landed.get(key)
|
||||
# [封存不触碰] 封存是最高优先事实:命中即计 sealed_skipped 并跳过一切写
|
||||
# (与来件 sha 无关)——永不更新、永不复活,防已执行记录被二次调拨。
|
||||
if row is not None and row.transfer_executed:
|
||||
counters["sealed_skipped"] += 1
|
||||
continue
|
||||
# [幂等跳过] 行 file_sha256 与来件一致 = 同一文件重落:完全不动行
|
||||
#(不续 updated_at,档无 TTL);meta 无 sha 时无法证明同源,不跳过。
|
||||
if (
|
||||
row is not None
|
||||
and file_meta.file_sha256 is not None
|
||||
and row.file_sha256 == file_meta.file_sha256
|
||||
):
|
||||
counters["skipped"] += 1
|
||||
continue
|
||||
|
||||
# [交叉校验] receipt 行出现出库语义 '-1' 即解析错位:计 cross_flagged 并写
|
||||
# 审计事件,记录照常落档。仅在插入/更新(实际落档)时判定——幂等重落
|
||||
#(sha 未变跳过)不重复打事件,封存行不落档故不标记。
|
||||
if record_kind == RECORD_KIND_RECEIPT and in_out_flag in RECEIPT_CONTRADICTORY_FLAGS:
|
||||
counters["cross_flagged"] += 1
|
||||
db.session.add(_cross_check_event(
|
||||
source_code=source_code, record_kind=record_kind, key=key,
|
||||
sheet_name=sheet_name, row_no=row_no, file_meta=file_meta,
|
||||
))
|
||||
|
||||
# [镜像取值] 业务值一律从领域行 dict 按契约 code 取(扩展字段无独立槽位);
|
||||
# 自然键成分同源同值,插入/更新统一按全字段镜像写入(更新时键成分等值重写
|
||||
# 为无操作,SQLAlchemy 等值列不入 UPDATE)。
|
||||
mirror = {code: _mirror_text(raw.get(code)) for code in _MOVEMENT_CODES}
|
||||
if row is None:
|
||||
# [插入] 自然键不存在:新档行,record_kind + 溯源五列随行写入。
|
||||
row = TransferMovementLedger(
|
||||
source_code=source_code,
|
||||
record_kind=record_kind,
|
||||
**mirror,
|
||||
source_file_id=file_meta.source_file_id,
|
||||
file_version=file_meta.file_version,
|
||||
file_sha256=file_meta.file_sha256,
|
||||
sheet_name=sheet_name,
|
||||
row_no=row_no,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(row)
|
||||
landed[key] = row
|
||||
counters["inserted"] += 1
|
||||
else:
|
||||
# [原行更新] 证据变化:业务镜像列整体换新 + 换溯源五件套与 updated_at
|
||||
#(sha 变而业务值未变时重写等值为无操作,仅溯源换新,计数同归 updated)。
|
||||
for code, value in mirror.items():
|
||||
setattr(row, code, value)
|
||||
row.source_file_id = file_meta.source_file_id
|
||||
row.file_version = file_meta.file_version
|
||||
row.file_sha256 = file_meta.file_sha256
|
||||
row.sheet_name = sheet_name
|
||||
row.row_no = row_no
|
||||
row.updated_at = now
|
||||
counters["updated"] += 1
|
||||
|
||||
# [STEP 3] 缺席不删:文件里没有的自然键本函数从不触碰(收料 RPA 非全量导出,
|
||||
# 缺席≠删除),无对应计数(Outcome 契约无 absent 字段)。
|
||||
# [STEP 4] 只 flush 不 commit:与 evidence_sync 同契约,提交归调用方
|
||||
#(落地桥自行 commit,匹配/执行随主事务)。
|
||||
db.session.flush()
|
||||
return LedgerSyncOutcome(**counters)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -40,14 +40,22 @@ class MovementField:
|
||||
required: bool = False
|
||||
|
||||
|
||||
# 定死的 11 个通用异动字段(领域契约,不配置化)。
|
||||
# 定死的通用异动字段(领域契约,不配置化):11 个核心字段 + 扩展可选维度字段。
|
||||
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
|
||||
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
|
||||
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生收敛为 external_lot_no() 唯一实现——
|
||||
# 库存查询 / 建单下传 / 单行聚合 / 展示统一按外部形态;落库保持文件原形态(证据原则)。
|
||||
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生曾收敛为 external_lot_no() 唯一实现。
|
||||
# [PROMPT_UPDATE] 2026-10-14(Task 11 切换):external_lot_no() 硬编码退役——批号
|
||||
# 外部形态改由调拨类型配置的转换规则驱动(field_transforms 引擎,匹配快照固化),
|
||||
# 行与档始终保存文件原形态(证据原则不变)。
|
||||
# [PROMPT_UPDATE] 2026-09-24:追加第 11 字段 unit(交易单位,计划 D4)——ERP 写入
|
||||
# 行必填(gls_cm19),但解析层放行空值(不产生解析失败),空值由匹配阶段行级
|
||||
# blocked_missing_unit 阻断;unit 不参与幂等/匹配,也不进匹配 Hash 快照(口径冻结)。
|
||||
# [PROMPT_UPDATE] 2026-10-14:追加 7 个可选维度字段(Task 8,调拨类型配置化+库存
|
||||
# 异动档项目)——line_seq/specification/order_type/odm_id/odm_name/carton_id/pallet_id,
|
||||
# 全部 required=False, is_identity=False,只追加不重排(unit 仍为第 11 字段);
|
||||
# 解析层缺列容忍自动继承(row.get 投影,缺列不报错);幂等键 doc_no 与身份集
|
||||
# (doc_no/material_code/movement_date)不变;字段值由库存异动档按 code 取值落档
|
||||
# (Task 10),管理端字段目录/解析 Profile 映射白名单按 MOVEMENT_FIELDS 派生自动继承。
|
||||
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
|
||||
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
|
||||
@@ -60,6 +68,14 @@ MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True),
|
||||
MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True),
|
||||
MovementField("unit", "单位", MovementFieldValueType.TEXT),
|
||||
# ---- 2026-10-14 扩展:可选维度字段(展示/圈档/异动档取值,非匹配身份) ----
|
||||
MovementField("line_seq", "项序", MovementFieldValueType.TEXT),
|
||||
MovementField("specification", "规格", MovementFieldValueType.TEXT),
|
||||
MovementField("order_type", "订单类型", MovementFieldValueType.TEXT),
|
||||
MovementField("odm_id", "ODM编号", MovementFieldValueType.TEXT),
|
||||
MovementField("odm_name", "ODM名称", MovementFieldValueType.TEXT),
|
||||
MovementField("carton_id", "箱号", MovementFieldValueType.TEXT),
|
||||
MovementField("pallet_id", "栈板号", MovementFieldValueType.TEXT),
|
||||
)
|
||||
|
||||
|
||||
@@ -81,25 +97,3 @@ def movement_identity_fields() -> set[str]:
|
||||
def movement_field_codes() -> set[str]:
|
||||
"""全部定死字段名集合。"""
|
||||
return {field.code for field in MOVEMENT_FIELDS}
|
||||
|
||||
|
||||
def external_lot_no(lot_no: str | None) -> str:
|
||||
"""批号外部形态派生:WMS 批号 WTP 前缀 → 外部系统真实批号 HOW 前缀。
|
||||
|
||||
【AI 触发时机】任何把行上 lot_no 发往外部系统的场景——库存查询 targets、
|
||||
写前库存复查、建单单行——组装参数前必须经本函数转换;单行聚合键与展示列
|
||||
「拨出/拨入批号」同规则(前端 features/chat/components/messages/transferBatch.ts
|
||||
deriveBatchNo 为本函数的展示侧镜像,改动须双侧同步)。行上落库值保持文件
|
||||
原形态(证据原则:raw_lines 对账/审计复算以文件为准),转换只发生在外部
|
||||
系统边界。
|
||||
|
||||
Args:
|
||||
lot_no: 行上批号原值(文件证据形态;None/空白按空串处理)。
|
||||
Returns:
|
||||
外部系统批号形态:WTP 前缀识别大小写不敏感,余串逐字保留;
|
||||
非 WTP 前缀原样返回;空输入返回空串。
|
||||
"""
|
||||
value = str(lot_no or "").strip()
|
||||
if value.upper().startswith("WTP"):
|
||||
return f"HOW{value[3:]}"
|
||||
return value
|
||||
@@ -5,7 +5,8 @@
|
||||
依赖:models、status、date_policy、matching_service(编号生成/TransferDeps)。
|
||||
逻辑:执行 Run 与匹配解耦(不回写 matching.run_id / confirmed_at);D8 异步拆分后
|
||||
Run 初始态为 queued(prepare 段只建 Run+关联行+建单,worker 段置 executing);
|
||||
行归属由调用方按 scope 圈定(见 matching_service.scope_item_query)后显式传入,
|
||||
行归属由调用方圈定(出生翻转后 items 创建即绑定 matching_id,restore/执行
|
||||
入口按匹配自有 items 圈行)后显式传入,
|
||||
本模块只负责"建 Run + 关联选中行",已关联(run_id 非空)的行跳过。
|
||||
"""
|
||||
|
||||
|
||||
@@ -1,22 +1,31 @@
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 外部系统)。
|
||||
"""在途调拨人工重试服务(基于冻结快照仅重新查询 外部系统)。
|
||||
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
|
||||
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
|
||||
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断;
|
||||
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制);
|
||||
重查前置兜底对齐(STEP 0,同 run_matching):两个批量重查入口先 align_scope_rows
|
||||
补救落地同步失败/迟到的证据,再圈行重查(待处理池后门不得基于过期证据作答);
|
||||
【2026-10-14 对档对账(ADR 0001/规格 §9)】requery_items(匹配号入口)前置
|
||||
「对档重圈 → 与本匹配自有 items 对账」:档新增记录 → 补建 item(绑同一
|
||||
匹配);档证据变 → 刷新 item 证据并重置待查;档记录消失 → item 失效隔离
|
||||
(沿用 blocked_file_removed 语义退出主视图)。圈档复用匹配创建的同一函数
|
||||
(_circle_ledger_records:固定条件单点实现)+ 同一快照规则(scope_json),
|
||||
D17 占用互斥排除「其他匹配」的有效占用(本匹配自有 items 不构成占用);
|
||||
终态行(已执行/人工关闭/取消/在流)绝不触碰——已执行行不得被证据刷新
|
||||
复活(防同批档证据更新促成二次写 ERP)。
|
||||
原 align_scope_rows 文件兜底对齐已随出生翻转退役(重查不再对文件对账);
|
||||
库存查询按组织批量(2026-09-29):全部重查/恢复/单据重试入口统一经
|
||||
_recheck_items_batch——路由解析按 external_org 分组,一组一次
|
||||
capabilities.query_stock(与执行链写前复查同形态),行级评估 / Attempt /
|
||||
审计 / 新鲜度续期保持单行粒度;N 行重查 = 每组织 1 次外部调用,
|
||||
禁止回退逐行单查(N 行 N 次调用会打崩外部系统);
|
||||
file_removed 失效行不可重查:匹配号圈行路径由 scope 谓词排除,按 id 直取与
|
||||
路由解析叠加类型仓库定义(resolve_warehouse:fixed 覆盖映射档);
|
||||
file_removed 失效行不可重查:匹配号圈行路径由对账口径排除,按 id 直取与
|
||||
单行入口由资格门禁 _gate_retryable_item 兜底拒绝(拒绝逻辑单点闭环,消失
|
||||
证据不可用旧库存翻回可执行);
|
||||
交易单位唯一来源=ERP 库存行 stock_unit(img09):重查命中且数量一致但 ERP
|
||||
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替)。
|
||||
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替);
|
||||
批号查询目标经行所属匹配快照的转换规则派生(item_external_lot_no)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,20 +43,24 @@ from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.evidence_sync import align_scope_rows
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_EXTERNAL_QUERY_FAILED,
|
||||
RESULT_EXECUTABLE,
|
||||
RESULT_FILE_REMOVED,
|
||||
RESULT_MISSING_UNIT,
|
||||
RESULT_ROUTE_NOT_RESOLVED,
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
scope_item_query,
|
||||
_born_item_from_record,
|
||||
_circle_ledger_records,
|
||||
_resolve_route_with_config,
|
||||
_SYNC_TERMINAL_STATUSES,
|
||||
item_external_lot_no,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.scope_rules import parse_scope_rules
|
||||
from app.services.in_transit_transfer.serializers import DOCUMENT_STATUS_GROUPS
|
||||
from app.services.in_transit_transfer.transfer_type import resolve_transfer_type
|
||||
|
||||
RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
|
||||
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
|
||||
@@ -62,6 +75,38 @@ _RETRYABLE_STATUSES = {
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _route_for_item(deps: TransferDeps, item: TransferInvoiceItem) -> RouteMapping:
|
||||
"""行级路由解析:映射档解析 + 行所属匹配类型的仓库定义(mapped/fixed)叠加。
|
||||
|
||||
Args:
|
||||
deps: 注入依赖(route_resolver=映射档解析)。
|
||||
item: 重查行(matching_id 关联的匹配快照携带 transfer_type)。
|
||||
Returns:
|
||||
RouteMapping(fixed 角色按类型配置覆盖仓库/法人;无匹配或快照无类型码
|
||||
时透传映射档——存量兼容兜底)。
|
||||
Raises:
|
||||
RouteNotResolvedError / ValidationError: 映射档不可解析或类型配置脏数据
|
||||
(fail-closed,调用方按行级前置解析失败隔离)。
|
||||
"""
|
||||
config = None
|
||||
if item.matching_id is not None and item.matching is not None:
|
||||
scope = item.matching.scope_json if isinstance(item.matching.scope_json, dict) else {}
|
||||
type_code = scope.get("transfer_type")
|
||||
if type_code:
|
||||
# 存量重跑/重查不要求类型仍启用(「停用后存量不受影响」)。
|
||||
config = resolve_transfer_type(type_code, require_enabled=False)
|
||||
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 "",
|
||||
)
|
||||
return _resolve_route_with_config(
|
||||
deps, config,
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
|
||||
|
||||
def _gate_retryable_item(item_id: int) -> TransferInvoiceItem:
|
||||
"""单行重查资格门禁(单行与按 id 批量入口共用的拒绝单点)。
|
||||
|
||||
@@ -232,18 +277,16 @@ def _recheck_items_batch(
|
||||
行未被触碰、未建 Attempt;批量入口转为该行 ok=False,单行入口原样上抛
|
||||
保持历史 fail-closed 行为)。
|
||||
"""
|
||||
# [STEP 1] 行级前置解析(行级隔离):路由解析 + 收料数量解析,失败行原位
|
||||
# 跳过、不拖垮整批;行仓库字段刷新为本次解析值——查询与后续执行写路径必须
|
||||
# 用同一仓库值:行上旧值可能来自更早配置(路由已漂移),也可能为空(如
|
||||
# blocked_missing_unit 行在路由解析前被阻断)。
|
||||
# [STEP 1] 行级前置解析(行级隔离):路由解析(叠加行所属匹配类型的仓库
|
||||
# 定义,fixed 覆盖映射档)+ 收料数量解析,失败行原位跳过、不拖垮整批;行仓库
|
||||
# 字段刷新为本次解析值——查询与后续执行写路径必须用同一仓库值:行上旧值可能
|
||||
# 来自更早配置(路由已漂移),也可能为空(如 blocked_missing_unit 行在路由
|
||||
# 解析前被阻断)。
|
||||
resolved: list[tuple[TransferInvoiceItem, RouteMapping, Decimal]] = []
|
||||
row_errors: dict[int, Exception] = {}
|
||||
for item in items:
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
route = _route_for_item(deps, item)
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
except Exception as exc: # noqa: BLE001 —— 行级隔离:路由漂移/缺失/脏数量只影响该行
|
||||
row_errors[item.id] = exc
|
||||
@@ -286,12 +329,13 @@ def _recheck_items_batch(
|
||||
db.session.add(attempts[item.id])
|
||||
db.session.flush()
|
||||
try:
|
||||
# [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。
|
||||
# [外部形态] 查询目标与回查同用行所属匹配快照转换规则派生批号
|
||||
# (item_external_lot_no;行落库保持档原形)。
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
lot_no=item_external_lot_no(item),
|
||||
) for item, route, _receipt_qty in entries],
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
@@ -314,7 +358,7 @@ def _recheck_items_batch(
|
||||
# [外部形态] 回查键与查询目标同用派生批号(三元组精确匹配)。
|
||||
stock_row = stock.lookup_row(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
lot_no=item_external_lot_no(item),
|
||||
)
|
||||
statuses[item.id] = _apply_recheck_outcome(
|
||||
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
|
||||
@@ -380,18 +424,6 @@ def requery_items_by_ids(
|
||||
ids = [int(x) for x in (item_ids or []) if x is not None]
|
||||
if not ids:
|
||||
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
|
||||
# [口径] 受影响来源=按 id 查回行的 source_code 去重(先查行→对齐→再重查)。
|
||||
source_rows = (
|
||||
db.session.query(TransferInvoiceItem.source_code)
|
||||
.filter(TransferInvoiceItem.id.in_(ids))
|
||||
.all()
|
||||
)
|
||||
affected_sources = sorted({(code or "").strip() for (code,) in source_rows})
|
||||
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
|
||||
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于任何
|
||||
# 重查读取执行,否则待处理池后门会基于过期证据放行旧库存。
|
||||
align_scope_rows(source_codes=affected_sources, deps=deps,
|
||||
business_date=str(business_date_now()), now=datetime.utcnow())
|
||||
results_by_id: dict[int, dict] = {}
|
||||
eligible: list[TransferInvoiceItem] = []
|
||||
for item_id in ids:
|
||||
@@ -411,19 +443,164 @@ def requery_items_by_ids(
|
||||
return {"total": len(ids), "results": [results_by_id[item_id] for item_id in ids]}
|
||||
|
||||
|
||||
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行,按组织批量查询并刷新。
|
||||
def _reconcile_items_with_ledger(
|
||||
matching, *, deps: TransferDeps, wanted_doc_nos: list[str] | None,
|
||||
) -> None:
|
||||
"""对档重圈并与本匹配自有 items 对账(出生翻转后重查的前置步骤,规格 §9)。
|
||||
|
||||
圈行口径与匹配卡实时视图同源(scope_item_query:来源+收料日期区间+调拨类型),
|
||||
行归属 matching_id 不参与——行归属解耦后行不随匹配迁移,视图能看到的历史行
|
||||
(matching_id 指向旧匹配)必须同样可被本次匹配的重查触达,否则出现「卡片提示
|
||||
重查、重查却查不到行」的死锁(2026-09-24 修复)。
|
||||
核心逻辑:[STEP 1] 按匹配快照规则(scope_rules + 来源 + 收料日期范围)圈定
|
||||
档记录——复用匹配创建的同一圈档函数 _circle_ledger_records(固定条件单点
|
||||
实现,杜绝谓词漂移),排除已执行封存、其他匹配的有效占用(D17;本匹配自有
|
||||
items 不构成占用)。[STEP 2] 三分类对账(**终态守卫:SUCCESS/DUPLICATE_
|
||||
SUCCESS/MANUALLY_CLOSED/CANCELLED/EXECUTING/RESULT_UNKNOWN 行绝不触碰——
|
||||
已执行行不得被证据刷新复活,否则同批档证据更新会促成二次写 ERP**):
|
||||
①档有行无(自有 items 未覆盖的圈中记录)→ 补建 item(绑同一匹配;
|
||||
类型配置缺失/路由不可解析时行级落 blocked(可解释、可重查),不影响
|
||||
其余行——口径与 _route_for_item 的逐行兜底对齐);
|
||||
②档证据变(数量/批号/仓库与 item 不一致)→ 刷新 item 证据并重置待查
|
||||
(旧库存是对旧数量查的,作废),展示字段照常刷新(仅非终态行);
|
||||
③自有 item 的档记录消失(防御:档缺席不删,仅异常清理场景)→ 失效隔离
|
||||
(blocked_file_removed,退出主视图,恢复走人工恢复;仅非终态行)。
|
||||
只 flush 不 commit(随调用方事务:requery_items 末尾 _recheck_items_batch
|
||||
的组粒度提交兜底持久化)。
|
||||
|
||||
Args:
|
||||
matching_no: 匹配编号(经 scope_json 圈定行集)。
|
||||
matching: 匹配 ORM 行(scope_json 快照 + 自有 items)。
|
||||
deps: 注入依赖(路由解析)。
|
||||
wanted_doc_nos: 可选单号过滤(invoice_nos 限定重查范围时同步约束补圈)。
|
||||
"""
|
||||
from app.core.errors import ValidationError as _ValidationError
|
||||
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
get_by_code as get_type_config,
|
||||
)
|
||||
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
rules = parse_scope_rules(scope.get("scope_rules"))
|
||||
now = datetime.utcnow()
|
||||
|
||||
# [STEP 1] 快照规则圈档(共享圈档函数:与匹配创建同一固定条件实现)。
|
||||
sources = [str(code) for code in (scope.get("source_codes") or [])]
|
||||
records: list = []
|
||||
if sources:
|
||||
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"),
|
||||
exclude_occupied_by_matching_id=matching.id,
|
||||
doc_nos=wanted_doc_nos,
|
||||
)
|
||||
|
||||
# 类型配置(仓库定义):从快照类型码读现行配置(存量不要求启用)。
|
||||
# [逐行容错] 类型缺失/脏配置不炸整次重查:config=None 时补建行走行级阻断
|
||||
# (口径与 _route_for_item 的逐行兜底对齐;类型只有停用没有删除,正常不触发)。
|
||||
type_code = str(scope.get("transfer_type") or "")
|
||||
config = None
|
||||
if type_code:
|
||||
try:
|
||||
config = get_type_config(type_code)
|
||||
except _ValidationError:
|
||||
config = None
|
||||
|
||||
# [终态守卫·占用面] own_by_record 收全部自有行(含终态):档记录已被本匹配
|
||||
# 任一行(含已执行行)绑定时按「档有行有」处理——终态绑定永不补建第二个 item
|
||||
#(否则已执行记录将以新待查行复活 → 二次写 ERP)。
|
||||
own_by_record = {
|
||||
item.ledger_record_id: item
|
||||
for item in matching.items
|
||||
if item.ledger_record_id is not None
|
||||
}
|
||||
for record in records:
|
||||
item = own_by_record.get(record.id)
|
||||
if item is None:
|
||||
# [①补建] 档新增记录:绑同一匹配(D17:本匹配占用即成立)。
|
||||
route = None
|
||||
route_failed = False
|
||||
try:
|
||||
if config is None:
|
||||
raise _ValidationError(f"transfer type config missing: {type_code}")
|
||||
route = _resolve_route_with_config(
|
||||
deps, config,
|
||||
source_code=record.source_code, invoice_no=record.doc_no,
|
||||
warehouse_code=record.warehouse_code or "",
|
||||
)
|
||||
except Exception: # noqa: BLE001 —— 类型缺失/路由失败:行级阻断降级,不影响其余行
|
||||
route = None
|
||||
route_failed = True
|
||||
born = _born_item_from_record(
|
||||
record, matching_id=matching.id,
|
||||
route=route, now=now,
|
||||
)
|
||||
if route_failed:
|
||||
# [行级阻断] 可解释、可重查(配置/路由修复后重查即恢复)。
|
||||
born.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
born.result_code = RESULT_ROUTE_NOT_RESOLVED
|
||||
born.result_message = (
|
||||
f"transfer type config missing: {type_code}" if config is None
|
||||
else f"route not resolved for source {record.source_code}"
|
||||
)
|
||||
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 "")
|
||||
or (item.lot_no or "") != (record.lot_no or "")
|
||||
or (item.receipt_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.lot_no = record.lot_no or ""
|
||||
item.receipt_warehouse_code = record.warehouse_code or ""
|
||||
# 重置待查:旧库存是对旧数量查的,作废;取数时刻同步置空。
|
||||
item.status = status_machine.TransferStatus.MATCHING.value
|
||||
item.result_code = SYNC_RESULT_PENDING
|
||||
item.result_message = None
|
||||
item.external_quantity = None
|
||||
item.inventory_checked_at = None
|
||||
item.updated_at = now
|
||||
|
||||
# [③失效隔离] 自有 item 的档记录不存在(档缺席不删,正常不触发;防御
|
||||
# 异常清理)→ 沿用 blocked_file_removed 语义退出主视图(仅非终态行;
|
||||
# 终态行的既定事实永不改写)。
|
||||
from app.models import TransferMovementLedger as _Ledger
|
||||
|
||||
record_ids = {record.id for record in records}
|
||||
for item in matching.items:
|
||||
if item.status in _SYNC_TERMINAL_STATUSES:
|
||||
continue
|
||||
if item.ledger_record_id is None or item.ledger_record_id in record_ids:
|
||||
continue
|
||||
if db.session.get(_Ledger, item.ledger_record_id) is None:
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = RESULT_FILE_REMOVED
|
||||
item.result_message = "ledger record removed"
|
||||
item.updated_at = now
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 外部系统 库存:先对档对账(补建/刷新/隔离),再圈自有可重查行批量刷新。
|
||||
|
||||
【2026-10-14 对档对账(规格 §9)】原 scope_item_query 实时圈行退役——行由
|
||||
匹配创建时从档圈定且创建即绑定,重查改为:按匹配快照规则对档重圈 → 与本
|
||||
匹配自有 items 对账(档新增记录补建 / 档证据变刷新重置 / 档记录消失隔离)→
|
||||
自有可重查行按组织批量重查。重查只对账本匹配自己的 items,不受 D17 圈档
|
||||
互斥影响(自有占用不排除)。
|
||||
|
||||
Args:
|
||||
matching_no: 匹配编号(scope_json 快照供圈档规则/类型码)。
|
||||
deps: 注入依赖(capabilities = 外部系统网关客户端)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该 scope 全部可重查行。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该匹配全部可重查行
|
||||
(对账补圈同受此约束,避免范围外补建)。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
@@ -434,21 +611,16 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
matching = TransferMatching.query.filter_by(matching_no=matching_no).first()
|
||||
if matching is None:
|
||||
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
|
||||
# [口径一致] 受影响来源=scope_json 的 source_codes(与 scope_item_query 圈行同源,
|
||||
# 提取口径同 matching_service.scope_item_query:非 dict 视为空 scope)。
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
affected_sources = sorted({str(code) for code in (scope.get("source_codes") or [])})
|
||||
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
|
||||
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于 scope
|
||||
# 圈行执行,否则重查会圈到过期行、基于过期证据放行旧库存。
|
||||
align_scope_rows(source_codes=affected_sources, deps=deps,
|
||||
business_date=str(business_date_now()), now=datetime.utcnow())
|
||||
# [口径统一] 圈行必须与匹配卡视图同谓词(scope:来源+日期区间+类型前缀)——
|
||||
# 行归属解耦后 matching_id 停留在首次创建值,按它圈行会漏掉全部存量行。
|
||||
# file_removed 行排除:消失证据不可重查恢复(唯一出口=人工关闭/出清)。
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
|
||||
# [STEP A] 对档对账(补建/刷新/隔离,只 flush;持久化随后续组粒度提交)。
|
||||
_reconcile_items_with_ledger(matching, deps=deps, wanted_doc_nos=wanted or None)
|
||||
|
||||
# [STEP B] 自有可重查行(阻断/可执行)批量重查;file_removed 隔离行排除
|
||||
# (消失证据不可重查恢复,唯一出口=人工关闭/等对档修复)。
|
||||
query = (
|
||||
scope_item_query(matching)
|
||||
.filter(
|
||||
TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.matching_id == matching.id,
|
||||
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
|
||||
or_(
|
||||
TransferInvoiceItem.result_code.is_(None),
|
||||
@@ -456,7 +628,6 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
),
|
||||
)
|
||||
)
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
if wanted:
|
||||
query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted))
|
||||
items = query.order_by(TransferInvoiceItem.id).all()
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""services/in_transit_transfer/scope_rules.py
|
||||
|
||||
用途:调拨类型范围规则引擎——受控字段白名单上的「字段+匹配方式+值列表」规则,
|
||||
规则间 AND、规则内多值 OR;内存谓词与 SQL 编译双形态共用同一解析结果,
|
||||
供匹配创建圈档、重查对账、管理页校验三处单一口径。
|
||||
依赖:app.core.errors.ValidationError;SQLAlchemy Select(编译形态)。
|
||||
逻辑:parse 校验词表/匹配方式/值非空 → ScopeRule 元组;evaluate 逐规则 AND、
|
||||
逐值 OR(prefix/contains 大小写不敏感);apply_scope_filters 生成等价 SQL。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Mapping, Sequence
|
||||
|
||||
from sqlalchemy import Select, and_, or_, func
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 受控字段词表(封闭可扩展;新增字段须同步管理页下拉与 technical.md)。
|
||||
SCOPE_FIELDS: frozenset[str] = frozenset({
|
||||
"source_code", "doc_no", "warehouse_code", "storage_code", "lot_no",
|
||||
"movement_date", "record_kind", "in_out_flag", "order_type", "odm_id",
|
||||
"odm_name", "carton_id", "pallet_id", "material_code", "doc_nature",
|
||||
"movement_type", "reason_code", "partner_code",
|
||||
})
|
||||
|
||||
_MATCHES = ("prefix", "equals", "contains", "in")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScopeRule:
|
||||
"""单条范围规则:field 字段 / match 匹配方式 / values 值列表(规则内 OR)。"""
|
||||
|
||||
field: str
|
||||
match: str
|
||||
values: tuple[str, ...]
|
||||
|
||||
|
||||
def parse_scope_rules(raw: list[dict] | None) -> tuple[ScopeRule, ...]:
|
||||
"""校验并解析范围规则 JSON(管理页保存与匹配快照共用)。
|
||||
|
||||
Args:
|
||||
raw: [{"field", "match", "values"}];空列表/None 合法(=不限,由调用方决定是否放行)。
|
||||
Returns:
|
||||
ScopeRule 元组。
|
||||
Raises:
|
||||
ValidationError: 字段不在 SCOPE_FIELDS、match 非法、values 空/非字符串。
|
||||
"""
|
||||
rules: list[ScopeRule] = []
|
||||
for item in raw or []:
|
||||
field, match = str(item.get("field", "")), str(item.get("match", ""))
|
||||
values = item.get("values") or []
|
||||
if field not in SCOPE_FIELDS:
|
||||
raise ValidationError(f"unknown scope field: {field}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field})
|
||||
if match not in _MATCHES or not values or not all(isinstance(v, str) and v.strip() for v in values):
|
||||
raise ValidationError(f"invalid scope rule: {field}/{match}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field, "match": match})
|
||||
rules.append(ScopeRule(field=field, match=match, values=tuple(v.strip() for v in values)))
|
||||
return tuple(rules)
|
||||
|
||||
|
||||
def _hit(value: str | None, rule: ScopeRule) -> bool:
|
||||
text = str(value or "").strip().upper()
|
||||
if not text:
|
||||
return False
|
||||
if rule.match == "prefix":
|
||||
return text.startswith(tuple(v.upper() for v in rule.values))
|
||||
if rule.match == "equals":
|
||||
return text in {v.upper() for v in rule.values}
|
||||
if rule.match == "contains":
|
||||
return any(v.upper() in text for v in rule.values)
|
||||
return text in {v.upper() for v in rule.values} # in
|
||||
|
||||
|
||||
def evaluate_scope(record: Mapping[str, Any], rules: Sequence[ScopeRule]) -> bool:
|
||||
"""内存求值:规则间 AND、规则内多值 OR(匹配/测试/小数据场景)。"""
|
||||
return all(_hit(record.get(rule.field), rule) for rule in rules)
|
||||
|
||||
|
||||
def apply_scope_filters(query: Select, model: type, rules: Sequence[ScopeRule]) -> Select:
|
||||
"""SQL 编译(与 evaluate_scope 同口径):圈档与重查对账共用,防谓词漂移。"""
|
||||
clauses = []
|
||||
for rule in rules:
|
||||
col = getattr(model, rule.field)
|
||||
upper = func.upper(col)
|
||||
if rule.match == "prefix":
|
||||
clauses.append(or_(*(upper.like(f"{v.upper()}%") for v in rule.values)))
|
||||
elif rule.match == "equals":
|
||||
clauses.append(upper.in_([v.upper() for v in rule.values]))
|
||||
elif rule.match == "contains":
|
||||
clauses.append(or_(*(upper.contains(v.upper()) for v in rule.values)))
|
||||
else:
|
||||
clauses.append(upper.in_([v.upper() for v in rule.values]))
|
||||
return query.filter(and_(*clauses)) if clauses else query
|
||||
|
||||
|
||||
def scope_rules_note(rules: Sequence[ScopeRule]) -> str:
|
||||
"""范围规则审计说明(写 scope_json 旁路人读字段)。"""
|
||||
parts = []
|
||||
for rule in rules:
|
||||
parts.append(f"{rule.field} {rule.match} {'|'.join(rule.values)}")
|
||||
return " AND ".join(parts)
|
||||
@@ -12,7 +12,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.matching_service import item_external_lot_no
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
|
||||
@@ -149,11 +149,11 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
name_by_key: dict[tuple[str, str, str, str], str] = {}
|
||||
reason_by_key: dict[tuple[str, str, str, str], str] = {}
|
||||
for item in ordered:
|
||||
# [外部形态] join 键与 _build_order_lines 聚合键同形(批号 WTP→HOW 派生),
|
||||
# 否则 WTP 前缀行的品名/原因投影 lookup 会 miss。
|
||||
# [外部形态] join 键与 _build_order_lines 聚合键同形(批号经行所属匹配
|
||||
# 快照转换规则派生),否则 WTP 前缀行的品名/原因投影 lookup 会 miss。
|
||||
key = (
|
||||
str(item.material_no or "").strip(),
|
||||
external_lot_no(item.lot_no),
|
||||
item_external_lot_no(item),
|
||||
str(item.from_warehouse or "").strip(),
|
||||
str(item.to_warehouse or "").strip(),
|
||||
)
|
||||
|
||||
@@ -1,127 +1,84 @@
|
||||
"""在途调拨类型契约。
|
||||
"""在途调拨类型契约(配置化,ADR 0002)。
|
||||
|
||||
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
|
||||
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝匹配,规则先冻结)。
|
||||
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
|
||||
逻辑:类型决定匹配纳入哪些收料单——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
的单(大小写不敏感,范围外单与收料日期范围过滤同语义,静默排除不入明细);
|
||||
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
|
||||
类型 3 规则待业务定义。范围判断统一走 invoice_in_scope 谓词(匹配过滤与
|
||||
scope 行圈定共用);调用方必须先 ensure_transfer_type_supported 再过滤。
|
||||
用途:匹配链路的类型门禁唯一入口——把 API/服务传入的类型编码解析为
|
||||
transfer_type_configs 配置 DTO(存在性/启停校验 fail-closed)。
|
||||
依赖:transfer_type_config_service(get_by_code,唯一读取口径)、app.core.errors。
|
||||
逻辑:【2026-10-14 配置化切换】类型不再硬编码枚举:合法值=配置表 code,
|
||||
数据范围/仓库定义/转换规则全部随配置(scope_rules / warehouse_config /
|
||||
transform_rules),匹配创建时快照进 scope_json。本模块只做「编码 → 配置
|
||||
DTO」的门禁解析:None/空 → REQUIRED;无此码(含空配置表)→ NOT_CONFIGURED;
|
||||
停用 → DISABLED(require_enabled=False 供存量匹配的重跑/重查使用——
|
||||
「停用后新匹配不可选,存量不受影响」,规格 §4.1)。
|
||||
旧枚举/前缀常量/谓词(TransferType / SUPPORTED_TRANSFER_TYPES /
|
||||
normalize_transfer_type / ensure_transfer_type_supported / invoice_in_scope /
|
||||
filter_invoices_for_type / transfer_type_scope_note)已随翻转退役:
|
||||
范围职责移交 scope_rules 引擎 + 匹配快照,批号转换移交 field_transforms。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import Iterable
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
TransferTypeConfigDTO,
|
||||
get_by_code,
|
||||
)
|
||||
|
||||
# 类型不支持(占位类型被调用)时的稳定错误码。
|
||||
TRANSFER_TYPE_NOT_SUPPORTED = "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
|
||||
# 匹配创建未携带类型编码(必填缺失)的稳定错误码(规格 §11,四语言已配齐)。
|
||||
TRANSFER_TYPE_REQUIRED = "TRANSFER.TRANSFER_TYPE_REQUIRED"
|
||||
# 配置表为空或无此编码(fail-closed,D8 不做种子数据)。
|
||||
TRANSFER_TYPE_NOT_CONFIGURED = "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
|
||||
# 类型存在但已停用(停用后新匹配不可选)。
|
||||
TRANSFER_TYPE_DISABLED = "TRANSFER.TRANSFER_TYPE_DISABLED"
|
||||
|
||||
|
||||
class TransferType(StrEnum):
|
||||
"""调拨业务类型(值与前端/i18n、transfer_runs.transfer_type 列一致)。"""
|
||||
def resolve_transfer_type(code: str | None, *, require_enabled: bool = True) -> TransferTypeConfigDTO:
|
||||
"""把类型编码解析为配置 DTO(匹配链路的类型门禁唯一入口)。
|
||||
|
||||
IN_TRANSIT_TO_HUB = "in_transit_to_hub" # 在途仓至HUB仓
|
||||
HUB_REPAIR_OUT = "hub_repair_out" # HUB仓维修出(占位)
|
||||
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
|
||||
|
||||
|
||||
# 一期已实现匹配/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
|
||||
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
|
||||
|
||||
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES: tuple[str, ...] = ("HOM", "HOX", "WTP")
|
||||
|
||||
# 类型 2(HUB仓维修出)数据范围:ODM ID 精确值;待 movement 文件暴露 odm_id 后启用。
|
||||
HUB_REPAIR_OUT_ODM_ID = "HoxinRMA"
|
||||
|
||||
|
||||
def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
|
||||
"""规范化调拨类型入参;缺省/空值回落到类型 1(存量调用方语义不变)。
|
||||
【AI 触发时机】匹配创建(run_matching / create_matching / API 必填校验)与
|
||||
存量匹配的重跑/重查需要类型配置(范围规则/仓库定义/转换规则)时,
|
||||
必须经本函数解析;禁止绕过配置直取编码或假设固定类型。
|
||||
|
||||
Args:
|
||||
value: 前端/API 传入的调拨类型值。
|
||||
code: 类型编码(transfer_type_configs.code,创建后不可变)。
|
||||
require_enabled: True(默认)=停用类型拒绝(新匹配路径);False=存量
|
||||
匹配的重跑/重查放行停用类型(「存量不受影响」语义)。
|
||||
Returns:
|
||||
TransferType 枚举。
|
||||
TransferTypeConfigDTO(scope_rules/warehouse_config/transform_rules 均为
|
||||
引擎解析后的受控对象)。
|
||||
Raises:
|
||||
ValidationError: 非法类型值(不在枚举内)。
|
||||
ValidationError: code 为 None/空白 → TRANSFER.TRANSFER_TYPE_REQUIRED;
|
||||
配置表无此码(含空表)→ TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED;
|
||||
停用且 require_enabled → TRANSFER.TRANSFER_TYPE_DISABLED。
|
||||
"""
|
||||
raw = str(value.value if isinstance(value, TransferType) else (value or "")).strip()
|
||||
if not raw:
|
||||
return TransferType.IN_TRANSIT_TO_HUB
|
||||
try:
|
||||
return TransferType(raw)
|
||||
except ValueError as exc:
|
||||
cleaned = str(code or "").strip()
|
||||
if not cleaned:
|
||||
raise ValidationError(
|
||||
f"unknown transfer type: {raw}",
|
||||
code="TRANSFER.TRANSFER_TYPE_INVALID",
|
||||
details={"transfer_type": raw},
|
||||
) from exc
|
||||
|
||||
|
||||
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
|
||||
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入匹配。
|
||||
|
||||
Args:
|
||||
transfer_type: 已规范化的调拨类型。
|
||||
Raises:
|
||||
ValidationError: 类型未实现(TRANSFER_TYPE_NOT_SUPPORTED)。
|
||||
"""
|
||||
if transfer_type not in SUPPORTED_TRANSFER_TYPES:
|
||||
raise ValidationError(
|
||||
f"transfer type not supported yet: {transfer_type.value}",
|
||||
code=TRANSFER_TYPE_NOT_SUPPORTED,
|
||||
details={"transfer_type": transfer_type.value},
|
||||
"transfer_type is required",
|
||||
code=TRANSFER_TYPE_REQUIRED,
|
||||
http_status=422, # 规格 §11:匹配创建类型门禁统一 422
|
||||
)
|
||||
# 复用配置服务的唯一读取口径:脏配置在其读取侧已被引擎拦截(fail-closed)。
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
TRANSFER_TYPE_NOT_CONFIGURED as _NOT_CONFIGURED,
|
||||
)
|
||||
|
||||
|
||||
def invoice_in_scope(invoice_no: str, transfer_type: TransferType | str | None) -> bool:
|
||||
"""判断 Invoice 单号是否落在调拨类型的收料数据范围内(单一判断口径)。
|
||||
|
||||
用途:匹配过滤(filter_invoices_for_type)与 scope 行圈定(matching_service
|
||||
的 scope_item_query)共用本谓词,避免"单过滤"与"行圈定"口径漂移。
|
||||
|
||||
Args:
|
||||
invoice_no: 收料单单号(大小写不敏感,前后空白忽略;空值恒 False)。
|
||||
transfer_type: 调拨类型(未规范化值允许,缺省/空回落类型 1)。
|
||||
Returns:
|
||||
True 表示该单在类型范围内(应纳入匹配/scope 查询);
|
||||
占位类型(规则未启用)恒 False。
|
||||
"""
|
||||
resolved = normalize_transfer_type(transfer_type)
|
||||
if resolved == TransferType.IN_TRANSIT_TO_HUB:
|
||||
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
|
||||
return str(invoice_no or "").strip().upper().startswith(prefixes)
|
||||
# 类型 2/3 的范围规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
|
||||
return False
|
||||
|
||||
|
||||
def filter_invoices_for_type(
|
||||
invoices: Iterable[AggregatedInvoice],
|
||||
transfer_type: TransferType,
|
||||
) -> list[AggregatedInvoice]:
|
||||
"""按类型的收料数据范围过滤汇总单(返回保留项,保持原顺序)。
|
||||
|
||||
Args:
|
||||
invoices: 已汇总的收料单。
|
||||
transfer_type: 已规范化且已确认支持的调拨类型。
|
||||
Returns:
|
||||
类型范围内的单列表(判断口径统一走 invoice_in_scope)。
|
||||
"""
|
||||
return [
|
||||
invoice for invoice in invoices
|
||||
if invoice_in_scope(invoice.invoice_no, transfer_type)
|
||||
]
|
||||
|
||||
|
||||
def transfer_type_scope_note(transfer_type: TransferType) -> str:
|
||||
"""类型的范围规则说明(写入 TransferMatching.scope_json 供审计追溯)。"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
return f"invoice_prefix:{'+'.join(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES).lower()}"
|
||||
if transfer_type == TransferType.HUB_REPAIR_OUT:
|
||||
return f"odm_id:{HUB_REPAIR_OUT_ODM_ID}"
|
||||
return "pending_rule"
|
||||
try:
|
||||
config = get_by_code(cleaned)
|
||||
except ValidationError as exc:
|
||||
if exc.code == _NOT_CONFIGURED:
|
||||
# 归一为本模块稳定错误码(匹配链路与 API 复用同一码面)。
|
||||
raise ValidationError(
|
||||
f"transfer type not configured: {cleaned}",
|
||||
code=TRANSFER_TYPE_NOT_CONFIGURED,
|
||||
details={"transfer_type": cleaned},
|
||||
http_status=422, # 规格 §11:空配置/停用类型 → 422
|
||||
) from exc
|
||||
raise
|
||||
if require_enabled and not config.enabled:
|
||||
raise ValidationError(
|
||||
f"transfer type is disabled: {cleaned}",
|
||||
code=TRANSFER_TYPE_DISABLED,
|
||||
details={"transfer_type": cleaned},
|
||||
http_status=422, # 规格 §11:空配置/停用类型 → 422
|
||||
)
|
||||
return config
|
||||
@@ -0,0 +1,459 @@
|
||||
"""services/in_transit_transfer/transfer_type_config_service.py
|
||||
|
||||
用途:调拨类型配置域服务(ADR 0002)——transfer_type_configs 表的唯一 CRUD 入口:
|
||||
列表/启用列表/按码读取/创建/更新(code 创建后不可变,只有停用没有删除),
|
||||
以及 mapped/fixed 双模式仓库角色解析 resolve_warehouse(Task 11 路由接入、
|
||||
Task 5 管理 API 消费)。
|
||||
依赖:models.in_transit_transfer.TransferTypeConfig、app.db(db.session)、
|
||||
scope_rules.parse_scope_rules、field_transforms.parse_transform_rules、
|
||||
app.core.errors.ValidationError;RouteMapping 仅类型标注(TYPE_CHECKING)。
|
||||
逻辑:写路径先过三块配置 parse 门禁(范围规则/仓库定义/转换规则)→ 组装规范化
|
||||
JSON 后走 ORM 插入/更新(JSON 四列无 server_default,禁止原生 SQL 插入);
|
||||
读路径 DTO 组装同样全部走 parse——库内脏数据在读取侧也被拦截(fail-closed);
|
||||
resolve_warehouse 按 role 取 from/to 角色:mapped 透传 RouteMapping,
|
||||
fixed 覆盖仓库、external_org 非空才覆盖法人。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.in_transit_transfer import TransferTypeConfig
|
||||
from app.services.in_transit_transfer.field_transforms import TransformRule, parse_transform_rules
|
||||
from app.services.in_transit_transfer.scope_rules import ScopeRule, parse_scope_rules
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.services.in_transit_transfer.matching_service import RouteMapping
|
||||
|
||||
# 稳定错误码(Task 5 同步四语言 errors.json;参数形态类失败走既有通用码)。
|
||||
TRANSFER_TYPE_NOT_CONFIGURED = "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
|
||||
TRANSFER_TYPE_CODE_EXISTS = "TRANSFER.TRANSFER_TYPE_CODE_EXISTS"
|
||||
TRANSFER_TYPE_CODE_IMMUTABLE = "TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE"
|
||||
WAREHOUSE_CONFIG_INVALID = "TRANSFER.WAREHOUSE_CONFIG_INVALID"
|
||||
|
||||
# code 契约:小写字母开头,仅小写字母/数字/下划线,总长 2..64(与列宽一致)。
|
||||
CODE_PATTERN = re.compile(r"^[a-z][a-z0-9_]{1,63}$")
|
||||
|
||||
# 参数形态类校验失败复用既有通用码(不新增四语言条目,管理页表单层先行拦截)。
|
||||
_PARAM_INVALID = "VALIDATION.INVALID_PARAM"
|
||||
|
||||
_WAREHOUSE_MODES = ("mapped", "fixed")
|
||||
_WAREHOUSE_ROLE_KEYS = {"from": "from_role", "to": "to_role"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WarehouseRole:
|
||||
"""单角色仓库定义:mapped=沿用来源映射档;fixed=类型固定仓库(可覆盖法人)。"""
|
||||
|
||||
mode: str
|
||||
warehouse_code: str | None = None
|
||||
external_org: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WarehouseConfig:
|
||||
"""类型仓库定义:拨出(from)/拨入(to)两角色各自 mapped 或 fixed。"""
|
||||
|
||||
from_role: WarehouseRole
|
||||
to_role: WarehouseRole
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferTypeConfigDTO:
|
||||
"""调拨类型配置读取视图:三块配置均为引擎解析后的受控对象(非原始 JSON)。"""
|
||||
|
||||
code: str
|
||||
names: dict[str, Any]
|
||||
enabled: bool
|
||||
sort_order: int
|
||||
scope_rules: tuple[ScopeRule, ...]
|
||||
warehouse_config: WarehouseConfig
|
||||
transform_rules: tuple[TransformRule, ...]
|
||||
description: str | None
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
def _reject_param(message: str, **details: Any) -> ValidationError:
|
||||
"""参数形态类校验失败的统一出口(通用码 + 定位详情)。"""
|
||||
return ValidationError(message, code=_PARAM_INVALID, details=details)
|
||||
|
||||
|
||||
def _clean_str(value: Any) -> str | None:
|
||||
"""字符串规范化:非字符串 → None;空白串 → None;其余去首尾空白。"""
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
return value.strip() or None
|
||||
|
||||
|
||||
def _parse_warehouse_config(raw: dict | None) -> WarehouseConfig:
|
||||
"""校验并规范化仓库定义 JSON(保存与读取共用;非法 fail-closed)。
|
||||
|
||||
Args:
|
||||
raw: {"from": {...}, "to": {...}},角色项缺省视为 mapped(沿用映射档);
|
||||
mapped 项不消费固定仓库值(规范化为纯 {"mode": "mapped"})。
|
||||
Returns:
|
||||
规范化后的 WarehouseConfig。
|
||||
Raises:
|
||||
ValidationError: code=TRANSFER.WAREHOUSE_CONFIG_INVALID——mode 不在白名单、
|
||||
fixed 缺非空 warehouse_code、或结构非 dict。
|
||||
"""
|
||||
if raw is None:
|
||||
raw = {}
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError(
|
||||
"warehouse_config must be an object", code=WAREHOUSE_CONFIG_INVALID,
|
||||
)
|
||||
|
||||
def _role(role_key: str) -> WarehouseRole:
|
||||
entry = raw.get(role_key)
|
||||
if entry is None:
|
||||
return WarehouseRole(mode="mapped")
|
||||
if not isinstance(entry, dict):
|
||||
raise ValidationError(
|
||||
f"warehouse role {role_key} must be an object", code=WAREHOUSE_CONFIG_INVALID,
|
||||
details={"role": role_key},
|
||||
)
|
||||
mode = str(entry.get("mode", ""))
|
||||
if mode not in _WAREHOUSE_MODES:
|
||||
raise ValidationError(
|
||||
f"invalid warehouse mode: {mode}", code=WAREHOUSE_CONFIG_INVALID,
|
||||
details={"role": role_key, "mode": mode},
|
||||
)
|
||||
if mode != "fixed":
|
||||
return WarehouseRole(mode="mapped")
|
||||
warehouse_code = _clean_str(entry.get("warehouse_code"))
|
||||
if not warehouse_code:
|
||||
raise ValidationError(
|
||||
f"fixed warehouse role requires warehouse_code: {role_key}",
|
||||
code=WAREHOUSE_CONFIG_INVALID, details={"role": role_key},
|
||||
)
|
||||
return WarehouseRole(
|
||||
mode="fixed", warehouse_code=warehouse_code,
|
||||
external_org=_clean_str(entry.get("external_org")),
|
||||
)
|
||||
|
||||
return WarehouseConfig(from_role=_role("from"), to_role=_role("to"))
|
||||
|
||||
|
||||
def _warehouse_role_json(role: WarehouseRole) -> dict[str, Any]:
|
||||
"""WarehouseRole → 规范化 JSON 项(mapped 固化空值,保证读写对称)。"""
|
||||
return {"mode": role.mode, "warehouse_code": role.warehouse_code, "external_org": role.external_org}
|
||||
|
||||
|
||||
def _warehouse_config_json(config: WarehouseConfig) -> dict[str, Any]:
|
||||
"""WarehouseConfig → 入库 JSON(from/to 键与规格 §7 示例一致)。"""
|
||||
return {
|
||||
"from": _warehouse_role_json(config.from_role),
|
||||
"to": _warehouse_role_json(config.to_role),
|
||||
}
|
||||
|
||||
|
||||
def _to_dto(row: TransferTypeConfig) -> TransferTypeConfigDTO:
|
||||
"""ORM 行 → DTO;三块配置全部重走 parse,库内脏数据在读取侧被拦截。
|
||||
|
||||
Raises:
|
||||
ValidationError: 脏数据命中任一引擎白名单校验(SCOPE/WAREHOUSE/TRANSFORM)。
|
||||
"""
|
||||
return TransferTypeConfigDTO(
|
||||
code=row.code,
|
||||
names=dict(row.names_json or {}),
|
||||
enabled=bool(row.enabled),
|
||||
sort_order=int(row.sort_order or 0),
|
||||
scope_rules=parse_scope_rules(row.scope_rules_json),
|
||||
warehouse_config=_parse_warehouse_config(row.warehouse_config_json),
|
||||
transform_rules=parse_transform_rules(row.transform_rules_json),
|
||||
description=row.description,
|
||||
updated_at=row.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _query_by_code(code: str) -> TransferTypeConfig | None:
|
||||
"""按 code 精确查询(入参去首尾空白;不查 None/空串)。"""
|
||||
cleaned = str(code or "").strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
return db.session.query(TransferTypeConfig).filter(TransferTypeConfig.code == cleaned).one_or_none()
|
||||
|
||||
|
||||
def _scope_rules_of(payload: dict) -> tuple[ScopeRule, ...]:
|
||||
"""解析 payload 中的范围规则(parse 门禁复用 Task 2 引擎,非法透传其错误码)。
|
||||
|
||||
Raises:
|
||||
ValidationError: TRANSFER.SCOPE_RULE_INVALID(规则字段/匹配方式/值非法)。
|
||||
"""
|
||||
return parse_scope_rules(payload.get("scope_rules"))
|
||||
|
||||
|
||||
def _enforce_scope_policy(payload: dict, rules: tuple[ScopeRule, ...]) -> None:
|
||||
"""空规则默认拒绝(防误圈全量);payload 显式确认(allow_empty_scope_rules)才放行。
|
||||
|
||||
[规格 §6] 是否允许「空=不限」由管理页显式确认——本服务默认要求至少一条。
|
||||
"""
|
||||
if rules or payload.get("allow_empty_scope_rules") is True:
|
||||
return
|
||||
raise _reject_param("scope_rules requires at least one rule unless explicitly confirmed")
|
||||
|
||||
|
||||
def _validated_names(payload: dict, *, required: bool) -> dict[str, Any] | None:
|
||||
"""校验 names:dict 且含非空 zh-CN(四语言名称的门禁底线)。
|
||||
|
||||
Args:
|
||||
payload: 创建/更新载荷。
|
||||
required: 创建恒为 True(names_json 必须含非空 zh-CN,缺 key 同拒);
|
||||
更新为 False(未提供保持原值,提供则同门禁校验)。
|
||||
Returns:
|
||||
names dict(更新未提供时 None,由调用方保持原值)。
|
||||
Raises:
|
||||
ValidationError: required 且缺 key、非 dict、缺 zh-CN 或 zh-CN 非非空字符串。
|
||||
"""
|
||||
if "names" not in payload:
|
||||
if required:
|
||||
raise _reject_param("names is required with non-empty zh-CN")
|
||||
return None
|
||||
names = payload.get("names")
|
||||
zh = names.get("zh-CN") if isinstance(names, dict) else None
|
||||
if not isinstance(zh, str) or not zh.strip():
|
||||
raise _reject_param("names requires non-empty zh-CN", names=names)
|
||||
return dict(names)
|
||||
|
||||
|
||||
def _coerce_sort_order(value: Any) -> int:
|
||||
"""sort_order 宽松转 int(JSON 数字/数字字符串),失败走参数校验码。"""
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _reject_param(f"invalid sort_order: {value!r}", sort_order=value) from exc
|
||||
|
||||
|
||||
def list_configs() -> list[TransferTypeConfigDTO]:
|
||||
"""全量类型配置(含停用),按 sort_order 升序、code 次序稳定排序。
|
||||
|
||||
Returns:
|
||||
TransferTypeConfigDTO 列表(管理页列表用;含停用项)。
|
||||
Raises:
|
||||
ValidationError: 任一行的范围规则/仓库定义/转换规则为脏数据时,经 _to_dto
|
||||
抛对应引擎错误码(TRANSFER.SCOPE_RULE_INVALID /
|
||||
TRANSFER.WAREHOUSE_CONFIG_INVALID / TRANSFER.TRANSFORM_RULE_INVALID,
|
||||
fail-closed,不降级返回脏配置)。
|
||||
"""
|
||||
rows = (
|
||||
db.session.query(TransferTypeConfig)
|
||||
.order_by(TransferTypeConfig.sort_order.asc(), TransferTypeConfig.code.asc())
|
||||
.all()
|
||||
)
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
|
||||
def get_enabled() -> list[TransferTypeConfigDTO]:
|
||||
"""启用中的类型配置,按 sort_order 升序(chat 侧类型列表与 Task 5 公开接口用)。
|
||||
|
||||
Returns:
|
||||
仅 enabled 的 TransferTypeConfigDTO 列表。
|
||||
Raises:
|
||||
ValidationError: 脏数据同 list_configs——读取侧 parse fail-closed
|
||||
(对应引擎错误码,不降级返回脏配置)。
|
||||
"""
|
||||
rows = (
|
||||
db.session.query(TransferTypeConfig)
|
||||
.filter(TransferTypeConfig.enabled.is_(True))
|
||||
.order_by(TransferTypeConfig.sort_order.asc(), TransferTypeConfig.code.asc())
|
||||
.all()
|
||||
)
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
|
||||
def get_by_code(code: str) -> TransferTypeConfigDTO:
|
||||
"""按 code 读取单个类型配置。
|
||||
|
||||
Args:
|
||||
code: 类型编码(创建后不可变的业务主键)。
|
||||
Returns:
|
||||
TransferTypeConfigDTO。
|
||||
Raises:
|
||||
ValidationError: 不存在 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED(匹配链
|
||||
fail-closed 同码);脏配置 → 对应引擎错误码。
|
||||
"""
|
||||
row = _query_by_code(code)
|
||||
if row is None:
|
||||
raise ValidationError(
|
||||
f"transfer type not configured: {code}", code=TRANSFER_TYPE_NOT_CONFIGURED,
|
||||
details={"code": code},
|
||||
)
|
||||
return _to_dto(row)
|
||||
|
||||
|
||||
def create_config(payload: dict, operator_id: int | None = None) -> TransferTypeConfigDTO:
|
||||
"""创建类型配置(写入唯一入口;JSON 四列必须经 ORM 插入,无 server_default)。
|
||||
|
||||
Args:
|
||||
payload: {code, names, enabled?, sort_order?, scope_rules?, warehouse_config?,
|
||||
transform_rules?, description?, allow_empty_scope_rules?}。
|
||||
operator_id: 创建人 users.id(可空,系统初始化场景)。
|
||||
Returns:
|
||||
新建配置的 TransferTypeConfigDTO。
|
||||
Raises:
|
||||
ValidationError: code 重复 → TRANSFER.TRANSFER_TYPE_CODE_EXISTS;code 格式
|
||||
非法/缺 zh-CN/空 scope_rules 未显式确认 → 通用参数码;
|
||||
规则/仓库/转换非法 → 对应引擎错误码。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
raise _reject_param("payload must be an object")
|
||||
|
||||
# [STEP 1] code 契约:格式先行(唯一性后置到 DB 前查重)。
|
||||
code = _clean_str(payload.get("code"))
|
||||
if not code or not CODE_PATTERN.match(code):
|
||||
raise _reject_param(f"invalid transfer type code: {code!r}", code=code)
|
||||
|
||||
# [STEP 2] names 必填且含非空 zh-CN(创建路径硬门禁,缺 key 同拒)。
|
||||
names = _validated_names(payload, required=True)
|
||||
|
||||
# [STEP 3] 三块配置 parse 门禁:范围规则(含空规则默认拒绝)、仓库定义、转换规则。
|
||||
scope_rules = _scope_rules_of(payload)
|
||||
_enforce_scope_policy(payload, scope_rules)
|
||||
warehouse_config = _parse_warehouse_config(payload.get("warehouse_config"))
|
||||
transform_rules = parse_transform_rules(payload.get("transform_rules"))
|
||||
|
||||
# [STEP 4] 唯一性预检(并发窗口由 uq_transfer_type_configs_code 兜底)。
|
||||
if _query_by_code(code) is not None:
|
||||
raise ValidationError(
|
||||
f"transfer type code already exists: {code}", code=TRANSFER_TYPE_CODE_EXISTS,
|
||||
details={"code": code},
|
||||
)
|
||||
|
||||
# [STEP 5] ORM 插入:JSON 列写入规范化结果(读回必可 parse,读写对称)。
|
||||
row = TransferTypeConfig(
|
||||
code=code,
|
||||
names_json=names,
|
||||
enabled=bool(payload.get("enabled", False)),
|
||||
sort_order=_coerce_sort_order(payload.get("sort_order", 0)),
|
||||
scope_rules_json=[
|
||||
{"field": r.field, "match": r.match, "values": list(r.values)} for r in scope_rules
|
||||
],
|
||||
warehouse_config_json=_warehouse_config_json(warehouse_config),
|
||||
transform_rules_json=[
|
||||
{"field": r.field, "op": r.op, "source": r.source, "target": r.target}
|
||||
for r in transform_rules
|
||||
],
|
||||
description=_clean_str(payload.get("description")),
|
||||
created_by=operator_id,
|
||||
updated_by=operator_id,
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
return _to_dto(row)
|
||||
|
||||
|
||||
def update_config(code: str, payload: dict, operator_id: int | None = None) -> TransferTypeConfigDTO:
|
||||
"""更新类型配置(部分更新:payload 未提供的字段保持原值;code 不可变)。
|
||||
|
||||
原子校验:所有提供的键先全量 parse/校验,全部通过后才统一赋值提交——
|
||||
任一键非法时整单拒绝且行保持原值(不落半截变更,评审 Finding 2 契约)。
|
||||
|
||||
Args:
|
||||
code: 目标类型编码(路径参数)。
|
||||
payload: 待更新字段;含 code 且与目标不等 → 改名被拒。
|
||||
operator_id: 更新人 users.id(可空)。
|
||||
Returns:
|
||||
更新后的 TransferTypeConfigDTO。
|
||||
Raises:
|
||||
ValidationError: 不存在 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED;改 code →
|
||||
TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE;字段校验失败同 create
|
||||
(引擎错误码或参数形态码),抛出时行未被修改。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
raise _reject_param("payload must be an object")
|
||||
row = _query_by_code(code)
|
||||
if row is None:
|
||||
raise ValidationError(
|
||||
f"transfer type not configured: {code}", code=TRANSFER_TYPE_NOT_CONFIGURED,
|
||||
details={"code": code},
|
||||
)
|
||||
|
||||
# [STEP 1] code 不可变(transfer_runs.transfer_type 引用它,改名即断链)。
|
||||
payload_code = payload.get("code")
|
||||
if payload_code is not None and str(payload_code).strip() != row.code:
|
||||
raise ValidationError(
|
||||
f"transfer type code is immutable: {row.code}", code=TRANSFER_TYPE_CODE_IMMUTABLE,
|
||||
details={"code": row.code, "attempted": payload_code},
|
||||
)
|
||||
|
||||
# [STEP 2] 全量预校验(与 create 同构):所有可更新键先 parse/校验到 updates,
|
||||
# 任一非法即整体抛出——此阶段不触碰 ORM 行,杜绝半截变更残留 session
|
||||
# (评审 Finding 2:形如 {"description": 新值, "transform_rules": 非法}
|
||||
# 的载荷禁止先改 description 再抛错)。
|
||||
updates: dict[str, Any] = {}
|
||||
names = _validated_names(payload, required=False)
|
||||
if names is not None:
|
||||
updates["names_json"] = names
|
||||
if "scope_rules" in payload:
|
||||
scope_rules = _scope_rules_of(payload)
|
||||
_enforce_scope_policy(payload, scope_rules)
|
||||
updates["scope_rules_json"] = [
|
||||
{"field": r.field, "match": r.match, "values": list(r.values)} for r in scope_rules
|
||||
]
|
||||
if "warehouse_config" in payload:
|
||||
warehouse_config = _parse_warehouse_config(payload.get("warehouse_config"))
|
||||
updates["warehouse_config_json"] = _warehouse_config_json(warehouse_config)
|
||||
if "transform_rules" in payload:
|
||||
transform_rules = parse_transform_rules(payload.get("transform_rules"))
|
||||
updates["transform_rules_json"] = [
|
||||
{"field": r.field, "op": r.op, "source": r.source, "target": r.target}
|
||||
for r in transform_rules
|
||||
]
|
||||
if "enabled" in payload:
|
||||
updates["enabled"] = bool(payload.get("enabled"))
|
||||
if "sort_order" in payload:
|
||||
updates["sort_order"] = _coerce_sort_order(payload.get("sort_order"))
|
||||
if "description" in payload:
|
||||
updates["description"] = _clean_str(payload.get("description"))
|
||||
|
||||
# [STEP 3] 全部通过后统一赋值(键为本函数白名单字面量)+ updated_by,一次提交。
|
||||
for attr, value in updates.items():
|
||||
setattr(row, attr, value)
|
||||
row.updated_by = operator_id
|
||||
|
||||
db.session.commit()
|
||||
return _to_dto(row)
|
||||
|
||||
|
||||
def resolve_warehouse(
|
||||
route_mapped: "RouteMapping", config: WarehouseConfig, role: str,
|
||||
) -> tuple[str, str]:
|
||||
"""按角色解析运行期 (external_org, warehouse_code):mapped 透传、fixed 覆盖。
|
||||
|
||||
【AI 触发时机】匹配圈档/建单/库存查询需要「拨出仓、拨入仓、法人」三元组时,
|
||||
必须经本函数按类型配置解析;禁止绕过配置直取 RouteMapping 或硬编码仓库。
|
||||
|
||||
Args:
|
||||
route_mapped: 来源路由映射档解析结果(DefaultRouteResolver 产物)。
|
||||
config: 类型配置的仓库定义(WarehouseConfig)。
|
||||
role: "from"(拨出)或 "to"(拨入),其他值 fail-closed。
|
||||
Returns:
|
||||
(external_org, warehouse_code):mapped 双双透传映射档;fixed 取配置仓库,
|
||||
external_org 非空覆盖法人、为空沿用映射档。
|
||||
Raises:
|
||||
ValidationError: role 非法,或 fixed 角色缺 warehouse_code
|
||||
(TRANSFER.WAREHOUSE_CONFIG_INVALID;解析侧兜底防线)。
|
||||
"""
|
||||
if role == "from":
|
||||
role_config = config.from_role
|
||||
elif role == "to":
|
||||
role_config = config.to_role
|
||||
else:
|
||||
raise ValidationError(
|
||||
f"unknown warehouse role: {role}", code=WAREHOUSE_CONFIG_INVALID, details={"role": role},
|
||||
)
|
||||
if role_config.mode == "fixed":
|
||||
if not role_config.warehouse_code:
|
||||
raise ValidationError(
|
||||
f"fixed warehouse role requires warehouse_code: {role}",
|
||||
code=WAREHOUSE_CONFIG_INVALID, details={"role": role},
|
||||
)
|
||||
return (role_config.external_org or route_mapped.external_org, role_config.warehouse_code)
|
||||
warehouse = route_mapped.from_warehouse if role == "from" else route_mapped.to_warehouse
|
||||
return (route_mapped.external_org, warehouse)
|
||||
@@ -107,6 +107,11 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
# [出生翻转 2026-10-14] 调拨类型配置化(D8 匹配创建必填):排程参数
|
||||
# job_params.transfer_type 承载类型编码,原样透传匹配层;缺省 None 时
|
||||
# 匹配层 fail-closed(TRANSFER_TYPE_REQUIRED 随 errors 硬失败透出),
|
||||
# 不回落固定类型(类型=平台配置,排程不隐式假设)。
|
||||
transfer_type = str(params.get("transfer_type") or "").strip() or None
|
||||
outcome = run_auto_transfer(
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
@@ -114,6 +119,7 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
recover_history=recover_history,
|
||||
receipt_date_from=receipt_date_from,
|
||||
receipt_date_to=receipt_date_to,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
|
||||
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
|
||||
|
||||
Reference in new issue
Block a user