Merge branch 'hugo-shipping-notice' into test
This commit is contained in:
commit
387b3157fe
113 files changed
+6036
-1759
No files matched your search
@@ -1,9 +1,9 @@
|
||||
"""backend/app/api/in_transit_transfer.py
|
||||
|
||||
用途:在途仓自动调拨用户态 API(仓库管理人员)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、precheck_service、deps。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps。
|
||||
逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id);
|
||||
Phase 1 提供预检创建(POST /prechecks)与进度恢复(GET /prechecks/{id})。
|
||||
Phase 1 提供匹配创建(POST /matchings)与进度恢复(GET /matchings/{id})。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,13 +22,21 @@ from app.services.in_transit_transfer.cancellation import cancel_run
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.excel_export import _MIME, build_exceptions_workbook
|
||||
from app.services.in_transit_transfer.execution_service import (
|
||||
execute_precheck,
|
||||
execute_items,
|
||||
get_run,
|
||||
serialize_run_result,
|
||||
)
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
|
||||
from app.services.in_transit_transfer.retry_service import requery_items as retry_service_requery_items, retry_item
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item, manual_close_items
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
create_matching,
|
||||
list_executable_items,
|
||||
restore_matching,
|
||||
)
|
||||
from app.services.in_transit_transfer.retry_service import (
|
||||
requery_items as retry_service_requery_items,
|
||||
requery_items_by_ids,
|
||||
retry_item,
|
||||
)
|
||||
from app.services.in_transit_transfer.serializers import (
|
||||
serialize_item,
|
||||
serialize_source,
|
||||
@@ -69,15 +77,15 @@ def _ok(payload: Any, *, status: int = 200):
|
||||
return ok(payload, request_id=getattr(g, "request_id", None), status=status)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks", methods=["POST"])
|
||||
@in_transit_transfer_bp.route("/matchings", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def create_precheck_api():
|
||||
"""创建或复用一次调拨预检(只读,不写 外部系统)。
|
||||
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 为预检摘要(precheck_id/hash/计数/来源进度)。
|
||||
响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
@@ -87,7 +95,7 @@ def create_precheck_api():
|
||||
raise ValidationError("source_codes is required")
|
||||
business_date = str(body.get("business_date") or business_date_now())
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_precheck(
|
||||
summary = create_matching(
|
||||
source_codes=[str(item).strip() for item in source_codes],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
@@ -98,11 +106,18 @@ def create_precheck_api():
|
||||
return _ok(serialize_summary(summary), status=201)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_id>", methods=["GET"])
|
||||
@in_transit_transfer_bp.route("/items/executable", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_precheck_api(precheck_id: str):
|
||||
"""恢复预检进度与明细(页面刷新/会话恢复)。"""
|
||||
restored = restore_precheck(precheck_id)
|
||||
def executable_items_api():
|
||||
"""可调拨明细(全局可执行行队列):勾选后 POST /items/execute 按行生成调拨单。"""
|
||||
return _ok(list_executable_items())
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/matchings/<matching_id>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_matching_api(matching_id: str):
|
||||
"""恢复匹配进度与明细(页面刷新/会话恢复;明细按 scope 实时圈行并装饰行级状态)。"""
|
||||
restored = restore_matching(matching_id, deps=transfer_deps.get_transfer_dependencies())
|
||||
return _ok({
|
||||
"summary": serialize_summary(restored["summary"]),
|
||||
"items": [serialize_item(item) for item in restored["items"]],
|
||||
@@ -110,41 +125,16 @@ def get_precheck_api(precheck_id: str):
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_id>/execute", methods=["POST"])
|
||||
@in_transit_transfer_bp.route("/matchings/<matching_no>/items/requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def execute_precheck_api(precheck_id: str):
|
||||
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
|
||||
|
||||
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
|
||||
响应:201 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
|
||||
if invoice_nos is not None and not isinstance(invoice_nos, list):
|
||||
raise ValidationError("invoice_nos must be a list")
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = execute_precheck(
|
||||
precheck_id=precheck_id,
|
||||
deps=deps,
|
||||
selected_invoice_nos=invoice_nos,
|
||||
)
|
||||
return _ok({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.status,
|
||||
"result": serialize_run_result(outcome.result),
|
||||
}, status=201)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_no>/items/requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def requery_items_api(precheck_no: str):
|
||||
def requery_items_api(matching_no: str):
|
||||
"""批量重查 外部系统 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body.get("invoice_nos"), list) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_service_requery_items(
|
||||
precheck_no=precheck_no, deps=deps, invoice_nos=invoice_nos,
|
||||
matching_no=matching_no, deps=deps, invoice_nos=invoice_nos,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
))
|
||||
|
||||
@@ -180,7 +170,7 @@ def download_source_receipt_files_api():
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=code),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/预检取文件同口径,
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/匹配取文件同口径,
|
||||
# 单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
@@ -255,6 +245,73 @@ def manual_close_item_api(item_id: int):
|
||||
return _ok(manual_close_item(item_id=item_id, reason=reason))
|
||||
|
||||
|
||||
def _require_item_ids(body: Any) -> list[int]:
|
||||
"""解析并校验批量操作的 item_ids(非空整数列表)。"""
|
||||
raw = body.get("item_ids") if isinstance(body, dict) else None
|
||||
if not isinstance(raw, list) or not raw:
|
||||
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
|
||||
try:
|
||||
return [int(x) for x in raw]
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("item_ids must be integers", code="TRANSFER.BATCH_ITEMS_REQUIRED") from exc
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/execute", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def execute_items_api():
|
||||
"""按行执行调拨(三层门禁:①存在且可执行 ②行级新鲜度 ③文件版本对账)。
|
||||
|
||||
请求体:{"item_ids": [int]}(匹配卡/待执行池勾选的真实明细行 id)。
|
||||
响应:200 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果;
|
||||
门禁失败 400,error.details 携带对应 id 列表
|
||||
(invalid_item_ids / stale_item_ids / changed_item_ids)。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = execute_items(
|
||||
item_ids=item_ids,
|
||||
deps=deps,
|
||||
actor_id=user.id,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
return _ok({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.status,
|
||||
"result": serialize_run_result(outcome.result),
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/batch-requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def batch_requery_items_api():
|
||||
"""批量重查外部系统库存(待处理池多选「重查」;单行隔离)。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(requery_items_by_ids(
|
||||
item_ids=item_ids, deps=deps,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/batch-manual-close", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def batch_manual_close_items_api():
|
||||
"""批量人工关闭异常项(原因必填,整批共用;单行隔离)。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
return _ok(manual_close_items(
|
||||
item_ids=item_ids, reason=str(body.get("reason") or ""),
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/exceptions.xlsx", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def exceptions_excel_api(run_no: str):
|
||||
@@ -301,8 +358,8 @@ def receipt_files_api(run_no: str):
|
||||
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
precheck = run.prechecks[0] if run.prechecks else None
|
||||
file_snapshot = precheck.file_snapshot_json if precheck and isinstance(precheck.file_snapshot_json, dict) else {}
|
||||
matching = run.matchings[0] if run.matchings else None
|
||||
file_snapshot = matching.file_snapshot_json if matching and isinstance(matching.file_snapshot_json, dict) else {}
|
||||
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
@@ -347,7 +404,7 @@ def receipt_files_api(run_no: str):
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/external-inventory", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def erp_inventory_api(run_no: str):
|
||||
"""下载本次预检冻结的 外部系统 库存表(csv);记录访问审计。"""
|
||||
"""下载本次匹配冻结的 外部系统 库存表(csv);记录访问审计。"""
|
||||
import io
|
||||
|
||||
from app import db
|
||||
@@ -403,7 +460,7 @@ def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认预检)与状态标识;保留期已到或非当天
|
||||
供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天
|
||||
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
|
||||
"""
|
||||
from app.models import ShippingInventorySource
|
||||
@@ -502,7 +559,7 @@ def backlog_summary_api():
|
||||
|
||||
|
||||
def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
"""待处理池项序列化。"""
|
||||
"""待处理池项序列化(明细字段与匹配窗口列一致)。"""
|
||||
return {
|
||||
'item_id': item.item_id,
|
||||
'source_code': item.source_code,
|
||||
@@ -513,4 +570,12 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
'age_days': item.age_days,
|
||||
'aging_level': item.aging_level,
|
||||
'last_attempt_at': item.last_attempt_at,
|
||||
'receipt_date': item.receipt_date,
|
||||
'material_name': item.material_name,
|
||||
'from_warehouse': item.from_warehouse,
|
||||
'to_warehouse': item.to_warehouse,
|
||||
'lot_no': item.lot_no,
|
||||
'receipt_quantity': item.receipt_quantity,
|
||||
'external_quantity': item.external_quantity,
|
||||
'result_code': item.result_code,
|
||||
}
|
||||
@@ -9,7 +9,7 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
contract_payment,
|
||||
file_check_run,
|
||||
in_transit_transfer_item,
|
||||
in_transit_transfer_precheck,
|
||||
in_transit_transfer_match,
|
||||
in_transit_transfer_run,
|
||||
kb_clean,
|
||||
kb_dify_sync,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""backend/app/jobs/handlers/in_transit_transfer_match.py
|
||||
|
||||
用途:异步执行在途调拨匹配(文件准备 + 只读匹配),并更新匹配状态。
|
||||
依赖:Job 注册表、matching_service、transfer 模型、transfer deps。
|
||||
逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写
|
||||
状态/计数/Hash;匹配不存在时 fail-closed 抛 RuntimeError。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import TransferMatching
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.matching_service import run_matching
|
||||
|
||||
|
||||
@register_handler(JobType.TRANSFER_MATCH)
|
||||
def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
|
||||
"""执行一次匹配 Job 并更新匹配状态。
|
||||
|
||||
【AI 触发时机】:仅由匹配创建异步路径入队;页面直连走 API 同步路径。
|
||||
"""
|
||||
payload = payload if isinstance(payload, dict) else {}
|
||||
matching_no = str(payload.get("matching_id") or "").strip()
|
||||
if not matching_no:
|
||||
raise RuntimeError("missing_transfer_matching_id")
|
||||
matching = db.session.query(TransferMatching).filter_by(matching_no=matching_no).first()
|
||||
if matching is None:
|
||||
raise RuntimeError(f"missing_transfer_matching: {matching_no}")
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
source_codes = list(scope.get("source_codes") or [])
|
||||
result = run_matching(
|
||||
source_codes=source_codes,
|
||||
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,
|
||||
)
|
||||
summary = result.summary
|
||||
matching.status = summary.status
|
||||
matching.counts_json = {
|
||||
"file_invoice_count": summary.counts.file_invoice_count,
|
||||
"not_matured_count": summary.counts.not_matured_count,
|
||||
"matched_count": summary.counts.matched_count,
|
||||
"executable_count": summary.counts.executable_count,
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
}
|
||||
matching.estimated_transfer_quantity = summary.estimated_transfer_quantity
|
||||
matching.estimated_external_write_count = summary.estimated_external_write_count
|
||||
matching.matching_hash = summary.matching_hash
|
||||
db.session.commit()
|
||||
@@ -1,56 +0,0 @@
|
||||
"""backend/app/jobs/handlers/in_transit_transfer_precheck.py
|
||||
|
||||
用途:异步执行在途调拨预检(文件准备 + 只读预检),并更新预检状态。
|
||||
依赖:Job 注册表、precheck_service、transfer 模型、transfer deps。
|
||||
逻辑:领取后按 payload.precheck_id 加载预检,运行 run_precheck 并回写
|
||||
状态/计数/Hash;预检不存在时 fail-closed 抛 RuntimeError。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import TransferPrecheck
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.precheck_service import run_precheck
|
||||
|
||||
|
||||
@register_handler(JobType.TRANSFER_PRECHECK)
|
||||
def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
|
||||
"""执行一次预检 Job 并更新预检状态。
|
||||
|
||||
【AI 触发时机】:仅由预检创建异步路径入队;页面直连走 API 同步路径。
|
||||
"""
|
||||
payload = payload if isinstance(payload, dict) else {}
|
||||
precheck_no = str(payload.get("precheck_id") or "").strip()
|
||||
if not precheck_no:
|
||||
raise RuntimeError("missing_transfer_precheck_id")
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=precheck_no).first()
|
||||
if precheck is None:
|
||||
raise RuntimeError(f"missing_transfer_precheck: {precheck_no}")
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
scope = precheck.scope_json if isinstance(precheck.scope_json, dict) else {}
|
||||
source_codes = list(scope.get("source_codes") or [])
|
||||
result = run_precheck(
|
||||
source_codes=source_codes,
|
||||
business_date=precheck.business_date,
|
||||
deps=deps,
|
||||
run_no=precheck.run.run_no if precheck.run else "RUN-PENDING",
|
||||
# 类型范围随预检落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
|
||||
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
|
||||
)
|
||||
summary = result.summary
|
||||
precheck.status = summary.status
|
||||
precheck.counts_json = {
|
||||
"file_invoice_count": summary.counts.file_invoice_count,
|
||||
"not_matured_count": summary.counts.not_matured_count,
|
||||
"prechecked_count": summary.counts.prechecked_count,
|
||||
"executable_count": summary.counts.executable_count,
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
}
|
||||
precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity
|
||||
precheck.estimated_external_write_count = summary.estimated_external_write_count
|
||||
precheck.precheck_hash = summary.precheck_hash
|
||||
db.session.commit()
|
||||
@@ -1,8 +1,9 @@
|
||||
"""backend/app/jobs/handlers/in_transit_transfer_run.py
|
||||
|
||||
用途:Run 级执行 Job:加载预检并驱动执行服务完成全部可执行项写入。
|
||||
用途:Run 级执行 Job:按匹配 scope 圈定 ready 行并驱动按行执行服务完成写入。
|
||||
依赖:execution_service、transfer deps、Job 注册表。
|
||||
逻辑:payload 携带 precheck_id;执行后预检与 Run 落库终态。
|
||||
逻辑:payload 携带 matching_id(仅用于 scope 圈行);三层门禁由 execute_items
|
||||
统一裁定,门禁失败即入队路径失败(fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -10,20 +11,20 @@ from __future__ import annotations
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.execution_service import execute_matching_items
|
||||
|
||||
|
||||
@register_handler(JobType.TRANSFER_RUN)
|
||||
def run_in_transit_transfer_run(_ctx, payload: dict) -> None:
|
||||
"""执行一个 Run(异步路径)。
|
||||
"""执行匹配 scope 内全部可执行行(异步路径)。
|
||||
|
||||
【AI 触发时机】:仅由执行 Run 入队路径调用;页面直连走 API 同步路径。
|
||||
"""
|
||||
payload = payload if isinstance(payload, dict) else {}
|
||||
precheck_id = str(payload.get("precheck_id") or "").strip()
|
||||
if not precheck_id:
|
||||
raise RuntimeError("missing_transfer_precheck_id")
|
||||
execute_precheck(
|
||||
precheck_id=precheck_id,
|
||||
matching_id = str(payload.get("matching_id") or "").strip()
|
||||
if not matching_id:
|
||||
raise RuntimeError("missing_transfer_matching_id")
|
||||
execute_matching_items(
|
||||
matching_id=matching_id,
|
||||
deps=transfer_deps.get_transfer_dependencies(),
|
||||
)
|
||||
@@ -8,6 +8,7 @@ backend/app/jobs/handlers/shipping_process_gate.py
|
||||
次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口;
|
||||
不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致;
|
||||
waiting_external 先结束当前 Job 再延迟入队新 Job;
|
||||
external-wait 轮询异常时回滚并按 Gate 现状重排/安静结束,保证轮询链不因瞬时冲突断裂;
|
||||
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
|
||||
"""
|
||||
|
||||
@@ -88,7 +89,37 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
||||
if external_wait_poll_gate_id and job is not None:
|
||||
from app.services.shipping_notice.process_gate_job_service import run_inventory_external_wait_poll
|
||||
|
||||
result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id)
|
||||
try:
|
||||
result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id)
|
||||
except Exception as exc:
|
||||
# [STEP] 轮询与库存回调可能以相反顺序争抢 Gate 行与候选行(2026-09-23 test job 8818,
|
||||
# 事务被毒化后以 InFailedSqlTransaction 收口,轮询链断裂导致 Gate 永久等待)。
|
||||
# 回滚后按 Gate 现状分流:仍在等待外部 → 结束本 Job 并延迟重排,保持轮询链不断;
|
||||
# Gate 已被回调等其他路径收口 → 安静结束。错误文本留在 result_json 供排查。
|
||||
db.session.rollback()
|
||||
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
|
||||
gate_status = str(getattr(gate, 'status', '') or '') if gate is not None else None
|
||||
if gate_status == 'waiting_external':
|
||||
poll = max(int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS', 30) or 30), 5)
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'status': 'waiting_external_requeued',
|
||||
'poll_error': sanitize_gate_error_text(exc, max_len=300),
|
||||
},
|
||||
owned_attempt=int(job.attempts or 0),
|
||||
)
|
||||
if gate is not None and gate.latest_attempt_id:
|
||||
schedule_waiting_external_poll(attempt_id=int(gate.latest_attempt_id))
|
||||
db.session.commit()
|
||||
return
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'status': 'poll_superseded', 'gate_status': gate_status},
|
||||
owned_attempt=int(job.attempts or 0),
|
||||
)
|
||||
db.session.commit()
|
||||
return
|
||||
finish_job(job.id, result=result, owned_attempt=int(job.attempts or 0))
|
||||
if str(result.get('gate_status') or '') == 'waiting_external':
|
||||
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
|
||||
|
||||
@@ -39,8 +39,8 @@ class JobType(StrEnum):
|
||||
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
|
||||
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
|
||||
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
|
||||
# 在途仓自动调拨:文件准备 + 只读预检(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
||||
TRANSFER_PRECHECK = 'in_transit_transfer_precheck'
|
||||
# 在途仓自动调拨:文件准备 + 只读匹配(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
||||
TRANSFER_MATCH = 'in_transit_transfer_match'
|
||||
TRANSFER_RUN = 'in_transit_transfer_run'
|
||||
TRANSFER_ITEM = 'in_transit_transfer_item'
|
||||
|
||||
@@ -83,7 +83,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
||||
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
|
||||
'transfer': frozenset({
|
||||
'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
||||
'in_transit_transfer_match', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
||||
}),
|
||||
}
|
||||
|
||||
|
||||
@@ -205,7 +205,7 @@ from app.models.in_transit_transfer import (
|
||||
TransferAttempt,
|
||||
TransferAuditEvent,
|
||||
TransferInvoiceItem,
|
||||
TransferPrecheck,
|
||||
TransferMatching,
|
||||
TransferRun,
|
||||
TransferSourceJob,
|
||||
)
|
||||
@@ -425,7 +425,7 @@ __all__ = [
|
||||
'ContractPaymentSyncState',
|
||||
'TransferRun',
|
||||
'TransferSourceJob',
|
||||
'TransferPrecheck',
|
||||
'TransferMatching',
|
||||
'TransferInvoiceItem',
|
||||
'TransferAttempt',
|
||||
'TransferAuditEvent',
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""models/in_transit_transfer.py
|
||||
|
||||
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Precheck、InvoiceItem、
|
||||
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
|
||||
Attempt、AuditEvent 与 Archive。
|
||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
|
||||
逻辑:Run 是异步真相源;InvoiceItem 按(precheck_id, invoice_no)唯一防止重复建单;
|
||||
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
|
||||
Attempt 保留每次恢复/重查事实,旧 Attempt 永不覆盖;
|
||||
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。
|
||||
"""
|
||||
@@ -33,12 +33,12 @@ from app.models.base import Base
|
||||
|
||||
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
|
||||
TRANSFER_ITEM_STATUSES = (
|
||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
|
||||
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
|
||||
)
|
||||
TRANSFER_RUN_STATUSES = (
|
||||
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
|
||||
@@ -48,13 +48,13 @@ TRANSFER_RUN_TYPES = (
|
||||
)
|
||||
TRANSFER_SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
TRANSFER_PRECHECK_STATUSES = (
|
||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
||||
TRANSFER_MATCH_STATUSES = (
|
||||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'failed', 'cancelled', 'expired',
|
||||
)
|
||||
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'external_query', 'external_write')
|
||||
TRANSFER_ATTEMPT_KINDS = ('match', 'rpa', 'external_query', 'external_write')
|
||||
TRANSFER_ATTEMPT_STATUSES = (
|
||||
'queued', 'running', 'waiting_external', 'success', 'failed',
|
||||
'result_unknown', 'superseded',
|
||||
@@ -63,7 +63,7 @@ TRANSFER_AUDIT_ACTOR_TYPES = ('user', 'system', 'worker', 'admin', 'rpa', 'sched
|
||||
|
||||
|
||||
class TransferRun(Base):
|
||||
"""一次调拨执行(或只读预检)的业务真相源。"""
|
||||
"""一次调拨执行(或只读匹配)的业务真相源。"""
|
||||
|
||||
__tablename__ = 'transfer_runs'
|
||||
__table_args__ = (
|
||||
@@ -91,7 +91,7 @@ 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仓间调拨);决定预检收料数据范围。
|
||||
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定匹配收料数据范围。
|
||||
transfer_type: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||||
)
|
||||
@@ -116,14 +116,14 @@ class TransferRun(Base):
|
||||
source_jobs: Mapped[list['TransferSourceJob']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan',
|
||||
)
|
||||
prechecks: Mapped[list['TransferPrecheck']] = relationship(
|
||||
matchings: Mapped[list['TransferMatching']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan',
|
||||
)
|
||||
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='run')
|
||||
|
||||
|
||||
class TransferSourceJob(Base):
|
||||
"""来源实例级的文件准备/预检执行单元;来源间互不阻断。"""
|
||||
"""来源实例级的文件准备/匹配执行单元;来源间互不阻断。"""
|
||||
|
||||
__tablename__ = 'transfer_source_jobs'
|
||||
__table_args__ = (
|
||||
@@ -155,25 +155,25 @@ class TransferSourceJob(Base):
|
||||
run: Mapped[TransferRun] = relationship(back_populates='source_jobs')
|
||||
|
||||
|
||||
class TransferPrecheck(Base):
|
||||
"""一次冻结快照的预检结果;确认/执行绑定其 Hash。"""
|
||||
class TransferMatching(Base):
|
||||
"""一次冻结快照的匹配结果;确认/执行绑定其 Hash。"""
|
||||
|
||||
__tablename__ = 'transfer_prechecks'
|
||||
__tablename__ = 'transfer_matchings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'),
|
||||
UniqueConstraint('matching_no', name='uq_transfer_matchings_matching_no'),
|
||||
CheckConstraint(
|
||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_PRECHECK_STATUSES)})",
|
||||
name='ck_transfer_prechecks_status',
|
||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_MATCH_STATUSES)})",
|
||||
name='ck_transfer_matchings_status',
|
||||
),
|
||||
Index('ix_transfer_prechecks_run_status', 'run_id', 'status'),
|
||||
Index('ix_transfer_prechecks_business_date', 'business_date'),
|
||||
Index('ix_transfer_matchings_run_status', 'run_id', 'status'),
|
||||
Index('ix_transfer_matchings_business_date', 'business_date'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
precheck_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
matching_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True, index=True)
|
||||
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='prechecking', server_default='prechecking')
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='matching', server_default='matching')
|
||||
scope_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
file_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -181,7 +181,7 @@ class TransferPrecheck(Base):
|
||||
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
estimated_external_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
matching_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
@@ -190,14 +190,14 @@ class TransferPrecheck(Base):
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
run: Mapped[Optional[TransferRun]] = relationship(back_populates='prechecks')
|
||||
run: Mapped[Optional[TransferRun]] = relationship(back_populates='matchings')
|
||||
items: Mapped[list['TransferInvoiceItem']] = relationship(
|
||||
back_populates='precheck', cascade='all, delete-orphan',
|
||||
back_populates='matching', cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class TransferInvoiceItem(Base):
|
||||
"""预检明细项;同一预检内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
|
||||
"""匹配明细项;同一匹配内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
|
||||
|
||||
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
||||
"""
|
||||
@@ -205,8 +205,8 @@ class TransferInvoiceItem(Base):
|
||||
__tablename__ = 'transfer_invoice_items'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
|
||||
name='uq_transfer_invoice_items_precheck_grain',
|
||||
'matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
|
||||
name='uq_transfer_invoice_items_matching_grain',
|
||||
),
|
||||
CheckConstraint(
|
||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})",
|
||||
@@ -218,7 +218,7 @@ class TransferInvoiceItem(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
precheck_id: Mapped[int] = mapped_column(ForeignKey('transfer_prechecks.id'), nullable=False, index=True)
|
||||
matching_id: Mapped[int] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=False, index=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
@@ -248,7 +248,7 @@ class TransferInvoiceItem(Base):
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
precheck: Mapped[TransferPrecheck] = relationship(back_populates='items')
|
||||
matching: Mapped[TransferMatching] = relationship(back_populates='items')
|
||||
run: Mapped[Optional[TransferRun]] = relationship(back_populates='items')
|
||||
attempts: Mapped[list['TransferAttempt']] = relationship(
|
||||
back_populates='item', cascade='all, delete-orphan',
|
||||
@@ -314,7 +314,7 @@ class TransferAuditEvent(Base):
|
||||
aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
precheck_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
matching_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
invoice_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
attempt_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
|
||||
@@ -166,7 +166,7 @@ agent_types:
|
||||
runtime_provider_default: hybrid
|
||||
models:
|
||||
- TransferRun
|
||||
- TransferPrecheck
|
||||
- TransferMatching
|
||||
- TransferInvoiceItem
|
||||
required_fields: []
|
||||
default_capabilities:
|
||||
@@ -186,7 +186,7 @@ agent_types:
|
||||
type: conversation_context
|
||||
keys:
|
||||
- run_no
|
||||
- precheck_id
|
||||
- matching_id
|
||||
requires_schedule_task: false
|
||||
presentation:
|
||||
layout: card
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
用途:在途仓自动调拨 Hybrid Handler。
|
||||
|
||||
依赖:agent_registry.handlers.base/registry。
|
||||
逻辑:在途调拨的进度与结果卡由 Chat Action(transfer.precheck / transfer.execute)
|
||||
逻辑:在途调拨的进度与结果卡由 Chat Action(transfer.match / transfer.execute)
|
||||
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
|
||||
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
|
||||
Dify Chatflow 生命周期。
|
||||
@@ -21,12 +21,12 @@ class InTransitTransferHandler(AgentHandler):
|
||||
"""
|
||||
在途仓自动调拨业务 Handler。
|
||||
|
||||
核心逻辑:预检/执行/结果卡不进入普通 Dify 生命周期(后台 Run 持久化 + 卡片消息
|
||||
核心逻辑:匹配/执行/结果卡不进入普通 Dify 生命周期(后台 Run 持久化 + 卡片消息
|
||||
+ Run API 恢复);prepare_stream / build_ui_state_event 预留领域扩展位。
|
||||
"""
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""Dify 流开始前:校验领域上下文(预留 run_no/precheck_id 锚点)。"""
|
||||
"""Dify 流开始前:校验领域上下文(预留 run_no/matching_id 锚点)。"""
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
用途:在途仓自动调拨 Agent 一期独立领域模块入口。
|
||||
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
|
||||
Phase 1 起扩展 file_preparation / precheck_service 等。
|
||||
Phase 1 起扩展 file_preparation / matching_service 等。
|
||||
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
|
||||
对外部系统(RPA/外部系统/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
|
||||
"""
|
||||
@@ -109,7 +109,7 @@ def archive_snapshot(
|
||||
|
||||
Args:
|
||||
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_id: 业务对象编号(precheck_no / run_no)。
|
||||
object_id: 业务对象编号(matching_no / run_no)。
|
||||
data: 待归档字节。
|
||||
original_filename: 原始文件名。
|
||||
content_type: MIME。
|
||||
|
||||
@@ -94,7 +94,7 @@ def _event_hash_inputs(event: TransferAuditEvent) -> dict[str, Any]:
|
||||
"aggregate_type": event.aggregate_type,
|
||||
"aggregate_id": event.aggregate_id,
|
||||
"run_no": event.run_no,
|
||||
"precheck_no": event.precheck_no,
|
||||
"matching_no": event.matching_no,
|
||||
"invoice_no": event.invoice_no,
|
||||
"item_id": event.item_id,
|
||||
"attempt_no": event.attempt_no,
|
||||
@@ -124,7 +124,7 @@ def build_transfer_audit_event(
|
||||
aggregate_type: str,
|
||||
aggregate_id: str,
|
||||
run_no: str | None = None,
|
||||
precheck_no: str | None = None,
|
||||
matching_no: str | None = None,
|
||||
invoice_no: str | None = None,
|
||||
item_id: str | None = None,
|
||||
attempt_no: str | None = None,
|
||||
@@ -144,7 +144,7 @@ def build_transfer_audit_event(
|
||||
|
||||
Args:
|
||||
event_type / aggregate_type / aggregate_id: 事件类型与聚合对象。
|
||||
run_no / precheck_no / invoice_no / item_id / attempt_no: 业务关联。
|
||||
run_no / matching_no / invoice_no / item_id / attempt_no: 业务关联。
|
||||
actor_*: 操作者(user/worker/schedule/admin/rpa)。
|
||||
request_id / operation_id: 关联上下文。
|
||||
before / after: 前后快照(自动脱敏并计算 Hash)。
|
||||
@@ -159,7 +159,7 @@ def build_transfer_audit_event(
|
||||
aggregate_type=aggregate_type,
|
||||
aggregate_id=aggregate_id,
|
||||
run_no=run_no,
|
||||
precheck_no=precheck_no,
|
||||
matching_no=matching_no,
|
||||
invoice_no=invoice_no,
|
||||
item_id=item_id,
|
||||
attempt_no=attempt_no,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""在途调拨自动排程编排(09:00 自动调拨)。
|
||||
|
||||
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
|
||||
用途:组合"每日恢复 → 自动匹配 → 自动执行 → 企微汇总通知",
|
||||
供 in-transit-transfer platform job 调用。
|
||||
依赖:recovery_service、precheck_service、execution_service、notification。
|
||||
依赖:recovery_service、matching_service、execution_service、notification。
|
||||
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 外部系统 结果。
|
||||
"""
|
||||
|
||||
@@ -12,9 +12,9 @@ from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.execution_service import execute_matching_items
|
||||
from app.services.in_transit_transfer.notification import WeComSender, notify_run_summary
|
||||
from app.services.in_transit_transfer.precheck_service import TransferDeps, create_precheck
|
||||
from app.services.in_transit_transfer.matching_service import TransferDeps, create_matching
|
||||
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
|
||||
|
||||
|
||||
@@ -52,12 +52,15 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
except Exception as exc: # noqa: BLE001
|
||||
outcome.errors.append(f"recovery_failed: {exc}")
|
||||
try:
|
||||
summary = create_precheck(
|
||||
summary = create_matching(
|
||||
source_codes=source_codes or [],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
)
|
||||
executed = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
# 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items
|
||||
# (三层门禁:可执行/行级新鲜度/文件版本对账);无可执行行时门禁抛错,
|
||||
# 与旧流程一致记入 errors 不阻断通知阶段。
|
||||
executed = execute_matching_items(matching_id=summary.matching_id, deps=deps)
|
||||
outcome.run_no = executed.run_no
|
||||
outcome.run_status = executed.status
|
||||
except Exception as exc: # noqa: BLE001
|
||||
|
||||
@@ -28,7 +28,7 @@ _BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BacklogItemDTO:
|
||||
"""待处理池单项。"""
|
||||
"""待处理池单项(明细字段与匹配窗口列一致,供异常表格直接渲染)。"""
|
||||
|
||||
item_id: int
|
||||
source_code: str
|
||||
@@ -39,6 +39,15 @@ class BacklogItemDTO:
|
||||
age_days: int
|
||||
aging_level: str
|
||||
last_attempt_at: Optional[str] = None
|
||||
receipt_date: Optional[str] = None
|
||||
material_name: Optional[str] = None
|
||||
from_warehouse: Optional[str] = None
|
||||
to_warehouse: Optional[str] = None
|
||||
lot_no: Optional[str] = None
|
||||
receipt_quantity: Optional[str] = None
|
||||
external_quantity: Optional[str] = None
|
||||
# 最近一次结果码(如 blocked_file_removed);供前端区分「文件已移除」徽标
|
||||
result_code: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -81,6 +90,10 @@ def _item_age_days(item: TransferInvoiceItem, now: datetime) -> int:
|
||||
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
|
||||
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
|
||||
|
||||
排序:收料日期 → Invoice → 创建时间(业务稳定键,与重查/恢复等操作无关)。
|
||||
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
|
||||
以此排序会让正在处理的行在列表中跳位。
|
||||
|
||||
Args:
|
||||
now: 判定时刻(默认当前时间)。
|
||||
source_code: 可选来源过滤。
|
||||
@@ -98,7 +111,12 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
if source_code:
|
||||
query = query.filter_by(source_code=source_code)
|
||||
output: list[BacklogItemDTO] = []
|
||||
for item in query.order_by(TransferInvoiceItem.updated_at.asc()).all():
|
||||
for item in query.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
).all():
|
||||
age = _item_age_days(item, current)
|
||||
latest = _latest_attempt(item)
|
||||
if item.status == TransferStatus.RESULT_UNKNOWN.value:
|
||||
@@ -117,6 +135,14 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
age_days=age,
|
||||
aging_level=level,
|
||||
last_attempt_at=latest.created_at.isoformat() if latest is not None else None,
|
||||
receipt_date=item.receipt_date,
|
||||
material_name=item.material_name,
|
||||
from_warehouse=item.from_warehouse,
|
||||
to_warehouse=item.to_warehouse,
|
||||
lot_no=item.lot_no,
|
||||
receipt_quantity=str(item.receipt_quantity) if item.receipt_quantity is not None else None,
|
||||
external_quantity=str(item.external_quantity) if item.external_quantity is not None else None,
|
||||
result_code=item.result_code,
|
||||
))
|
||||
return output
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨 Chat Action Handler。
|
||||
|
||||
用途:通过 Chat Turn Action 触发预检/执行,并输出结构化卡片事件
|
||||
(message_type=transfer-precheck / transfer-result),供前端 TransferMessageView 渲染。
|
||||
依赖:action_registry、action_schema.TurnEvent、precheck_service、execution_service、deps、serializers。
|
||||
逻辑:Dify 只产生受限候选 Action;真实预检/执行由本确定性 Handler 执行并流式输出卡片。
|
||||
用途:通过 Chat Turn Action 触发匹配/执行,并输出结构化卡片事件
|
||||
(message_type=transfer-match / transfer-result),供前端 TransferMessageView 渲染。
|
||||
依赖:action_registry、action_schema.TurnEvent、matching_service、execution_service、deps、serializers。
|
||||
逻辑:Dify 只产生受限候选 Action;真实匹配/执行由本确定性 Handler 执行并流式输出卡片。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,11 +15,11 @@ from app.services.chat.action_schema import TurnEvent
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck, get_run
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
|
||||
from app.services.in_transit_transfer.serializers import serialize_precheck_detail
|
||||
from app.services.in_transit_transfer.execution_service import execute_matching_items, get_run
|
||||
from app.services.in_transit_transfer.matching_service import create_matching, restore_matching
|
||||
from app.services.in_transit_transfer.serializers import serialize_matching_detail
|
||||
|
||||
ACTION_TRANSFER_PRECHECK = "transfer.precheck"
|
||||
ACTION_TRANSFER_MATCH = "transfer.match"
|
||||
ACTION_TRANSFER_EXECUTE = "transfer.execute"
|
||||
|
||||
|
||||
@@ -33,15 +33,15 @@ def _message(content: str, message_type: str, payload: dict[str, Any]) -> TurnEv
|
||||
|
||||
|
||||
@register_action_handler
|
||||
class TransferPrecheckAction:
|
||||
"""预检 Action:创建(或恢复)预检并输出预检卡。"""
|
||||
class TransferMatchAction:
|
||||
"""匹配 Action:创建(或恢复)匹配并输出匹配卡。"""
|
||||
|
||||
action_type = ACTION_TRANSFER_PRECHECK
|
||||
action_type = ACTION_TRANSFER_MATCH
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
"""执行只读预检并输出 transfer-precheck 卡片。
|
||||
"""执行只读匹配并输出 transfer-match 卡片。
|
||||
|
||||
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
|
||||
【AI 触发时机】:用户表达"查询今天可调拨 / 匹配"等意图后由候选 Action 触发;
|
||||
只读,不写 外部系统。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
@@ -49,17 +49,17 @@ class TransferPrecheckAction:
|
||||
business_date = str(payload.get("business_date") or business_date_now())
|
||||
transfer_type = str(payload.get("transfer_type")) if payload.get("transfer_type") else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_precheck(
|
||||
summary = create_matching(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
detail = restore_precheck(summary.precheck_id)
|
||||
detail = restore_matching(summary.matching_id, deps=deps)
|
||||
yield _message(
|
||||
content="调拨预检完成",
|
||||
message_type="transfer-precheck",
|
||||
payload={"kind": "precheck", **serialize_precheck_detail(detail)},
|
||||
content="调拨匹配完成",
|
||||
message_type="transfer-match",
|
||||
payload={"kind": "match", **serialize_matching_detail(detail)},
|
||||
)
|
||||
|
||||
|
||||
@@ -72,18 +72,20 @@ class TransferExecuteAction:
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
"""执行勾选范围并输出 transfer-result 卡片。
|
||||
|
||||
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
|
||||
后台确定性服务完成写前复查与 外部系统 原子写入。
|
||||
【AI 触发时机】:用户在匹配卡点击"直接生成调拨单"后触发;
|
||||
后台按匹配 scope 圈定 ready 行(invoice_nos 过滤)后按行执行,
|
||||
三层门禁(可执行/行级新鲜度/文件版本对账)与写前复查、
|
||||
外部系统 原子写入由确定性服务完成。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
precheck_id = str(payload.get("precheck_id") or "").strip()
|
||||
matching_id = str(payload.get("matching_id") or "").strip()
|
||||
invoice_nos = payload.get("invoice_nos")
|
||||
invoice_nos = [str(item).strip() for item in invoice_nos] if isinstance(invoice_nos, list) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = execute_precheck(
|
||||
precheck_id=precheck_id,
|
||||
outcome = execute_matching_items(
|
||||
matching_id=matching_id,
|
||||
deps=deps,
|
||||
selected_invoice_nos=invoice_nos,
|
||||
invoice_nos=invoice_nos,
|
||||
)
|
||||
run_view = get_run(outcome.run_no)
|
||||
yield _message(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨并发参数与单写者约束。
|
||||
|
||||
用途:冻结来源并发(2)、外部系统 查询并发(2)与 外部系统 写并发(1)默认值;
|
||||
外部系统 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
外部系统 写并发恒为 1,同匹配只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
依赖:无(纯常量)。
|
||||
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
|
||||
"""
|
||||
@@ -15,11 +15,11 @@ SOURCE_CONCURRENCY = 3
|
||||
|
||||
|
||||
def assert_single_writer(run_count: int) -> None:
|
||||
"""同预检最多一个执行 Run。
|
||||
"""同匹配最多一个执行 Run。
|
||||
|
||||
Args:
|
||||
run_count: 已存在的执行 Run 数。
|
||||
Raises:
|
||||
AssertionError: run_count > 1(一期硬约束)。
|
||||
"""
|
||||
assert run_count <= 1, "External write concurrency must stay 1 for the same precheck"
|
||||
assert run_count <= 1, "External write concurrency must stay 1 for the same matching"
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨 DTO 与稳定错误码契约。
|
||||
|
||||
用途:冻结前后端契约(预检摘要、明细项、外部系统 单据聚合结果)与一期错误码,
|
||||
用途:冻结前后端契约(匹配摘要、明细项、外部系统 单据聚合结果)与一期错误码,
|
||||
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
|
||||
依赖:标准库 dataclasses / decimal。
|
||||
逻辑:DTO 全部 frozen;aggregate_external_documents 按 外部系统 单号聚合最终结果页
|
||||
@@ -21,7 +21,7 @@ TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
|
||||
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND = "TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND"
|
||||
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
|
||||
TRANSFER_MATCH_EXPIRED = "TRANSFER_MATCH_EXPIRED"
|
||||
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
|
||||
TRANSFER_RESULT_UNKNOWN = "TRANSFER_RESULT_UNKNOWN"
|
||||
@@ -38,7 +38,7 @@ KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
|
||||
TRANSFER_INVOICE_CONFLICT,
|
||||
TRANSFER_QUANTITY_MISMATCH,
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
TRANSFER_MATCH_EXPIRED,
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED,
|
||||
TRANSFER_RESULT_UNKNOWN,
|
||||
@@ -61,14 +61,14 @@ def require_known_error_code(code: str) -> None:
|
||||
raise ValueError(f"unknown transfer error code: {code}")
|
||||
|
||||
|
||||
# ---- 预检 DTO -------------------------------------------------------------
|
||||
# ---- 匹配 DTO -------------------------------------------------------------
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckCountsDTO:
|
||||
"""预检计数。"""
|
||||
class MatchingCountsDTO:
|
||||
"""匹配计数。"""
|
||||
|
||||
file_invoice_count: int = 0
|
||||
not_matured_count: int = 0
|
||||
prechecked_count: int = 0
|
||||
matched_count: int = 0
|
||||
executable_count: int = 0
|
||||
blocked_count: int = 0
|
||||
|
||||
@@ -83,8 +83,8 @@ class RawLineRefDTO:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckInvoiceItemDTO:
|
||||
"""预检明细项(决策 6 十列 + 2026-09-21 增批号:拨出批号/拨入批号由 lot_no 转换派生,lot_no 存原值)。"""
|
||||
class MatchingItemDTO:
|
||||
"""匹配明细项(决策 6 十列 + 2026-09-21 增批号:拨出批号/拨入批号由 lot_no 转换派生,lot_no 存原值)。"""
|
||||
|
||||
source_code: str
|
||||
material_no: str
|
||||
@@ -103,21 +103,28 @@ class PrecheckInvoiceItemDTO:
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||
receipt_warehouse_code: str = ""
|
||||
# 行装饰字段(restore 按 scope 实时视图时填齐;run_matching 快照路径保持缺省):
|
||||
# item_id=行主键(批量操作/待处理池回链);checked_at=行评估时间(updated_at);
|
||||
# stale=评估时间距今超过确认 TTL;file_current=行评估版本戳仍是该来源当前可用文件。
|
||||
item_id: int = 0
|
||||
checked_at: str | None = None
|
||||
stale: bool = False
|
||||
file_current: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckSummaryDTO:
|
||||
"""预检摘要(含预计调拨数量、预计 外部系统 写入数与预检 Hash)。"""
|
||||
class MatchingSummaryDTO:
|
||||
"""匹配摘要(含预计调拨数量、预计 外部系统 写入数与匹配 Hash)。"""
|
||||
|
||||
precheck_id: str
|
||||
matching_id: str
|
||||
status: str
|
||||
business_date: str
|
||||
eligible_receipt_date_to: str
|
||||
expires_at: str
|
||||
counts: PrecheckCountsDTO
|
||||
counts: MatchingCountsDTO
|
||||
estimated_transfer_quantity: str
|
||||
estimated_external_write_count: int
|
||||
precheck_hash: str
|
||||
matching_hash: str
|
||||
|
||||
|
||||
# ---- 结果页 DTO(决策 20)--------------------------------------------------
|
||||
@@ -166,15 +173,15 @@ class RunResultDTO:
|
||||
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def aggregate_external_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
|
||||
def aggregate_external_documents(items: Iterable[MatchingItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
|
||||
"""按 外部系统 单号聚合成功项,产出结果页文档视图。
|
||||
|
||||
Args:
|
||||
items: 预检明细项(含 external_document_no 与 result)。
|
||||
items: 匹配明细项(含 external_document_no 与 result)。
|
||||
Returns:
|
||||
按单号聚合的 ExternalDocumentDTO 元组(行按 Invoice 排序)。
|
||||
"""
|
||||
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
|
||||
grouped: dict[str, list[MatchingItemDTO]] = {}
|
||||
for item in items:
|
||||
if item.external_document_no and item.result in {"success", "duplicate_success"}:
|
||||
grouped.setdefault(item.external_document_no, []).append(item)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨业务日期与成熟度策略。
|
||||
|
||||
用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured,
|
||||
昨天及更早可预检,未来日期阻断)。
|
||||
昨天及更早可匹配,未来日期阻断)。
|
||||
依赖:标准库 zoneinfo / datetime。
|
||||
逻辑:所有日期判定集中在本模块,供 precheck_service / recovery_service 复用,
|
||||
逻辑:所有日期判定集中在本模块,供 matching_service / recovery_service 复用,
|
||||
避免各服务各自计算导致口径漂移。
|
||||
"""
|
||||
|
||||
@@ -105,7 +105,7 @@ def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
|
||||
|
||||
|
||||
def eligible_receipt_date_to(business_date: date | str) -> date:
|
||||
"""返回可进入预检的收料截止日期(业务日期 T - 1 天)。
|
||||
"""返回可进入匹配的收料截止日期(业务日期 T - 1 天)。
|
||||
|
||||
Args:
|
||||
business_date: 当前业务日期。
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""在途调拨依赖装配(Dependencies)。
|
||||
|
||||
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
|
||||
依赖:movement_file_repository / capability_client / precheck_service / models。
|
||||
依赖:movement_file_repository / capability_client / matching_service / models。
|
||||
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
|
||||
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
|
||||
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed)。
|
||||
"""
|
||||
|
||||
@@ -15,7 +15,7 @@ from typing import Any
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient
|
||||
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
RouteNotResolvedError,
|
||||
RouteResolver,
|
||||
@@ -120,7 +120,7 @@ class _DefaultRpaTrigger:
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
|
||||
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
|
||||
# 抓回的文件无法被 latest_ready_file 复用,预检会反复重抓。fail-closed 返回明确错误码。
|
||||
# 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
|
||||
@@ -52,7 +52,7 @@ def build_exceptions_workbook(run_no: str) -> bytes:
|
||||
workbook.remove(workbook.active)
|
||||
|
||||
_sheet_summary(workbook, run, items)
|
||||
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
|
||||
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "matching_expired"})
|
||||
_sheet_blocked(workbook, items, "外部系统无库存", {"blocked_inventory_not_found"})
|
||||
_sheet_blocked(workbook, items, "外部系统技术失败", {"business_failed", "technical_failed", "item_execution_error"})
|
||||
_sheet_unknown(workbook, items)
|
||||
@@ -71,7 +71,7 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
|
||||
sheet.append(["Run 状态", run.status])
|
||||
sheet.append(["通知状态", run.notification_status])
|
||||
sheet.append([])
|
||||
sheet.append(["Invoice", "来源", "料号", "预检结果", "外部系统 单号"])
|
||||
sheet.append(["Invoice", "来源", "料号", "匹配结果", "外部系统 单号"])
|
||||
for item in items:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""在途调拨执行服务(确认门禁 + 写前复查 + 外部系统 原子写入 + 结果投影)。
|
||||
"""在途调拨执行服务(按行执行三层门禁 + 写前复查 + 外部系统 原子写入 + 结果投影)。
|
||||
|
||||
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
|
||||
用途:按行执行调拨:三层门禁(①存在且可执行 ②行级新鲜度 ③文件版本对账,
|
||||
fail-closed 任一不过则 外部系统 写入为 0)→ 创建执行 Run →
|
||||
逐项写前复查 外部系统 库存 → 原子建单/审核/过账 → 按 外部系统 单号投影最终结果。
|
||||
依赖:orchestrator、capability_client、quantity、contracts、audit、status、models。
|
||||
逻辑:未确认/过期/快照变化/选择含不可执行项 → 外部系统 写调用为 0;
|
||||
依赖:orchestrator、capability_client、quantity、contracts、audit、status、
|
||||
source_file_status、matching_service(scope 圈行/_item_evaluated_sha)、models。
|
||||
逻辑:执行与匹配确认解耦(hash/expires 门禁退役,新鲜度由行 updated_at 承担);
|
||||
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
|
||||
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
|
||||
"""
|
||||
@@ -17,29 +19,31 @@ from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem, TransferMatching, TransferRun
|
||||
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_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
ExternalDocumentDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
MatchingItemDTO,
|
||||
RunResultDTO,
|
||||
TransferExceptionDTO,
|
||||
aggregate_external_documents,
|
||||
)
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
from app.services.in_transit_transfer.orchestrator import (
|
||||
create_execution_run_for_items,
|
||||
finalize_run,
|
||||
)
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_EXECUTABLE,
|
||||
RouteNotResolvedError,
|
||||
TransferDeps,
|
||||
_item_evaluated_sha,
|
||||
scope_item_query,
|
||||
)
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
PRECHECK_EXPIRED_RESULT = "precheck_expired"
|
||||
ITEM_EXECUTION_ERROR_RESULT = "item_execution_error"
|
||||
|
||||
|
||||
@@ -53,7 +57,7 @@ class ExecuteOutcome:
|
||||
|
||||
|
||||
def _item_result_of(item: TransferInvoiceItem) -> str:
|
||||
"""从持久化状态还原明细结果值(与预检快照口径一致)。"""
|
||||
"""从持久化状态还原明细结果值(与匹配快照口径一致)。"""
|
||||
if item.result_code:
|
||||
return item.result_code
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value:
|
||||
@@ -61,121 +65,97 @@ def _item_result_of(item: TransferInvoiceItem) -> str:
|
||||
return item.status
|
||||
|
||||
|
||||
def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
|
||||
"""由存储明细复算预检 Hash(写前快照校验口径)。"""
|
||||
from app.services.in_transit_transfer.audit import canonical_hash
|
||||
|
||||
counts = precheck.counts_json if isinstance(precheck.counts_json, dict) else {}
|
||||
items = [
|
||||
{
|
||||
"source_code": item.source_code,
|
||||
"invoice_no": item.invoice_no,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"receipt_quantity": item.receipt_quantity,
|
||||
"external_quantity": item.external_quantity,
|
||||
"result": _item_result_of(item),
|
||||
}
|
||||
for item in sorted(precheck.items, key=lambda row: row.id)
|
||||
]
|
||||
snapshot = {
|
||||
"scope": sorted(precheck.scope_json.get("source_codes") or []),
|
||||
"business_date": precheck.business_date,
|
||||
"file_snapshot": precheck.file_snapshot_json if isinstance(precheck.file_snapshot_json, dict) else {},
|
||||
"counts": {
|
||||
key: int(counts.get(key, 0))
|
||||
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
|
||||
"executable_count", "blocked_count")
|
||||
},
|
||||
"items": items,
|
||||
}
|
||||
# [调拨类型] 创建时快照含 transfer_type(2026-09-22 起 scope_json 恒写入);
|
||||
# 存量预检 scope_json 无该字段时保持旧快照形状,避免复算 Hash 不一致误判过期。
|
||||
scope_transfer_type = str(precheck.scope_json.get("transfer_type") or "").strip()
|
||||
if scope_transfer_type:
|
||||
snapshot["transfer_type"] = scope_transfer_type
|
||||
return f"sha256:{canonical_hash(snapshot)}"
|
||||
|
||||
|
||||
def _expire(precheck: TransferPrecheck) -> None:
|
||||
"""将预检置为过期(fail-closed 落位)。"""
|
||||
precheck.status = "expired"
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def execute_precheck(
|
||||
def execute_items(
|
||||
*,
|
||||
precheck_id: str,
|
||||
item_ids: list[int],
|
||||
deps: TransferDeps,
|
||||
selected_invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> ExecuteOutcome:
|
||||
"""执行一次已确认的预检(手工或自动触发共用)。
|
||||
"""按行执行调拨(三层门禁,手工执行与自动触发共用)。
|
||||
|
||||
【AI 触发时机】:用户/自动排程圈定待执行明细行(item_ids)后触发;
|
||||
任一门禁不过则 外部系统 写入为 0(fail-closed)。
|
||||
|
||||
三层门禁(顺序校验,命中即抛、后续不执行):
|
||||
① 存在且可执行:id 存在且 status == ready_to_execute,否则
|
||||
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID", details.invalid_item_ids)。
|
||||
② 行级新鲜度:updated_at 距 now 超过 deps.strategy.confirm_ttl_seconds →
|
||||
ValidationError(code="TRANSFER.ITEMS_STALE", details.stale_item_ids)。
|
||||
③ 文件版本对账:按去重来源调 resolve_source_file_status,行评估版本戳
|
||||
(_item_evaluated_sha)缺失或 ≠ 来源最新可用文件 sha(含来源无可用文件)→
|
||||
ValidationError(code="TRANSFER.FILE_CHANGED", details.changed_item_ids)。
|
||||
|
||||
Args:
|
||||
precheck_id: 预检编号。
|
||||
item_ids: 待执行明细行 id 列表(重复 id 自动去重,保持首现顺序)。
|
||||
deps: 注入依赖。
|
||||
selected_invoice_nos: 选择范围(仅可执行项);缺省执行全部可执行项。
|
||||
actor_id / request_id: 审计上下文。
|
||||
actor_id / request_id: 审计上下文(写入 run.created_by / 写入审计事件)。
|
||||
Returns:
|
||||
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
|
||||
Raises:
|
||||
NotFoundError / ValidationError / AppError: 门禁失败(外部系统 写入为 0)。
|
||||
ConflictError: 重复执行。
|
||||
ValidationError: 三层门禁任一不过(details 携带对应 id 列表)。
|
||||
"""
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(
|
||||
precheck_no=str(precheck_id).strip(),
|
||||
).first()
|
||||
if precheck is None:
|
||||
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
|
||||
if precheck.confirmed_at is not None:
|
||||
from app.core.errors import ConflictError
|
||||
# [STEP 1] 门禁①:加载并校验 id(存在 + ready_to_execute)。
|
||||
seen: set[int] = set()
|
||||
ordered_ids = [i for i in (int(x) for x in item_ids) if not (i in seen or seen.add(i))]
|
||||
if not ordered_ids:
|
||||
raise ValidationError(
|
||||
"item_ids is required", code="TRANSFER.EXECUTE_ITEMS_INVALID",
|
||||
details={"invalid_item_ids": []},
|
||||
)
|
||||
rows = db.session.query(TransferInvoiceItem).filter(
|
||||
TransferInvoiceItem.id.in_(ordered_ids),
|
||||
).all()
|
||||
by_id = {row.id: row for row in rows}
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
invalid = [
|
||||
i for i in ordered_ids
|
||||
if by_id.get(i) is None or by_id[i].status != ready_status
|
||||
]
|
||||
if invalid:
|
||||
raise ValidationError(
|
||||
"items not executable", code="TRANSFER.EXECUTE_ITEMS_INVALID",
|
||||
details={"invalid_item_ids": invalid},
|
||||
)
|
||||
items = [by_id[i] for i in ordered_ids]
|
||||
|
||||
raise ConflictError("precheck already executed", code="TRANSFER.PRECHECK_ALREADY_EXECUTED")
|
||||
if precheck.status != status_machine.TransferStatus.READY_TO_EXECUTE.value:
|
||||
raise AppError(
|
||||
code=TRANSFER_CONFIRMATION_REQUIRED,
|
||||
message="precheck is not confirmed for execution",
|
||||
http_status=400,
|
||||
)
|
||||
if precheck.expires_at is not None and precheck.expires_at <= datetime.utcnow():
|
||||
_expire(precheck)
|
||||
db.session.commit()
|
||||
raise AppError(
|
||||
code=TRANSFER_PRECHECK_EXPIRED, message="precheck confirmation expired",
|
||||
http_status=409,
|
||||
)
|
||||
if recompute_precheck_hash(precheck) != precheck.precheck_hash:
|
||||
_expire(precheck)
|
||||
db.session.commit()
|
||||
raise AppError(
|
||||
code=TRANSFER_PRECHECK_EXPIRED,
|
||||
message="precheck snapshot changed since confirmation",
|
||||
http_status=409,
|
||||
# [STEP 2] 门禁②:行级新鲜度(updated_at 距 now ≤ 确认 TTL)。
|
||||
now = datetime.utcnow()
|
||||
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
|
||||
stale = [
|
||||
item.id for item in items
|
||||
if item.updated_at is None
|
||||
or (now - item.updated_at).total_seconds() > ttl_seconds
|
||||
]
|
||||
if stale:
|
||||
raise ValidationError(
|
||||
"items stale since last evaluation", code="TRANSFER.ITEMS_STALE",
|
||||
details={"stale_item_ids": stale},
|
||||
)
|
||||
|
||||
executable = [item for item in precheck.items if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value]
|
||||
if selected_invoice_nos is not None:
|
||||
selected_set = {str(item).strip() for item in selected_invoice_nos}
|
||||
available = {item.invoice_no for item in executable}
|
||||
invalid = selected_set - available
|
||||
if invalid:
|
||||
raise ValidationError(
|
||||
f"invoices not executable: {sorted(invalid)}",
|
||||
code="TRANSFER.SELECTION_INVALID",
|
||||
)
|
||||
selected = [item for item in executable if item.invoice_no in selected_set]
|
||||
else:
|
||||
selected = list(executable)
|
||||
if not selected:
|
||||
raise ValidationError("no executable invoices selected", code=TRANSFER_CONFIRMATION_REQUIRED)
|
||||
# [STEP 3] 门禁③:文件版本对账(按去重来源投影最新可用文件,行评估 sha 必须一致;
|
||||
# 来源无可用文件或行无版本戳均视为不一致 → FILE_CHANGED)。
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({item.source_code for item in items})
|
||||
}
|
||||
changed = []
|
||||
for item in items:
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
latest = latest_files.get(item.source_code) or {}
|
||||
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
|
||||
changed.append(item.id)
|
||||
if changed:
|
||||
raise ValidationError(
|
||||
"source receipt file changed since evaluation", code="TRANSFER.FILE_CHANGED",
|
||||
details={"changed_item_ids": changed},
|
||||
)
|
||||
|
||||
run = create_execution_run(
|
||||
precheck, deps=deps, actor_id=actor_id,
|
||||
selected_invoice_nos={item.invoice_no for item in selected},
|
||||
# [STEP 4] 建执行 Run(不绑定匹配)+ 逐行写前复查与原子写入(单项失败不阻断)。
|
||||
run = create_execution_run_for_items(
|
||||
items, deps=deps, actor_id=actor_id, selected_item_ids=set(ordered_ids),
|
||||
)
|
||||
for item in selected:
|
||||
for item in items:
|
||||
try:
|
||||
_write_item(item, deps=deps, run_no=run.run_no, request_id=request_id)
|
||||
except Exception as exc: # noqa: BLE001 —— 单项失败不阻断其他项
|
||||
@@ -190,6 +170,61 @@ def execute_precheck(
|
||||
return ExecuteOutcome(run_no=run.run_no, status=run.status, result=_build_run_result(run))
|
||||
|
||||
|
||||
def execute_matching_items(
|
||||
*,
|
||||
matching_id: str,
|
||||
deps: TransferDeps,
|
||||
invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> ExecuteOutcome:
|
||||
"""按匹配 scope 圈定 ready 行并按行执行(chat action / 自动排程 / Run Job 共用入口)。
|
||||
|
||||
行归属与匹配解耦(原地刷新)后,"这份匹配覆盖哪些行"由 scope 重新圈定
|
||||
(scope_item_query:来源 + 收料日期区间 + 调拨类型前缀);本入口按 scope 取
|
||||
ready_to_execute 行(可选 invoice_nos 过滤)后委托 execute_items 执行,
|
||||
三层门禁由 execute_items 统一裁定。
|
||||
|
||||
Args:
|
||||
matching_id: 匹配编号(MTG-...),仅用于圈定 scope。
|
||||
deps: 注入依赖。
|
||||
invoice_nos: 选择范围(可选);含 scope 内不可执行票时整单拒绝(fail-closed)。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
|
||||
Raises:
|
||||
NotFoundError: 匹配不存在。
|
||||
ValidationError: 选择含不可执行票(TRANSFER.SELECTION_INVALID)或
|
||||
execute_items 三层门禁失败。
|
||||
"""
|
||||
matching = db.session.query(TransferMatching).filter_by(
|
||||
matching_no=str(matching_id).strip(),
|
||||
).first()
|
||||
if matching is None:
|
||||
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)
|
||||
.order_by(TransferInvoiceItem.id.asc())
|
||||
.all()
|
||||
)
|
||||
if invoice_nos is not None:
|
||||
selected_set = {str(invoice_no).strip() for invoice_no in invoice_nos}
|
||||
available = {row.invoice_no for row in ready_rows}
|
||||
invalid = selected_set - available
|
||||
if invalid:
|
||||
raise ValidationError(
|
||||
f"invoices not executable: {sorted(invalid)}",
|
||||
code="TRANSFER.SELECTION_INVALID",
|
||||
)
|
||||
ready_rows = [row for row in ready_rows if row.invoice_no in selected_set]
|
||||
return execute_items(
|
||||
item_ids=[row.id for row in ready_rows],
|
||||
deps=deps, actor_id=actor_id, request_id=request_id,
|
||||
)
|
||||
|
||||
|
||||
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
|
||||
"""写前复查 + 外部系统 原子写入单个 Invoice(创建新 Attempt)。"""
|
||||
route = deps.route_resolver.resolve(
|
||||
@@ -197,7 +232,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
|
||||
_mark_recheck_blocked(item, "matching_expired", "route mapping changed since matching")
|
||||
return
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
@@ -215,7 +250,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
|
||||
except RouteNotResolvedError:
|
||||
raise
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "external inventory changed since precheck")
|
||||
_mark_recheck_blocked(item, "matching_expired", "external inventory changed since matching")
|
||||
return
|
||||
|
||||
# [STEP 2] 记录写 Attempt 并调用外部系统原子建单/审核/过账。
|
||||
@@ -337,11 +372,11 @@ def get_run(run_no: str) -> dict[str, Any]:
|
||||
|
||||
def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
"""由 Run 明细构建结果投影。"""
|
||||
item_dtos: list[PrecheckInvoiceItemDTO] = []
|
||||
item_dtos: list[MatchingItemDTO] = []
|
||||
exceptions: list[TransferExceptionDTO] = []
|
||||
for item in sorted(run.items, key=lambda row: row.invoice_no):
|
||||
result = _item_result_of(item)
|
||||
item_dtos.append(PrecheckInvoiceItemDTO(
|
||||
item_dtos.append(MatchingItemDTO(
|
||||
source_code=item.source_code,
|
||||
material_no=item.material_no,
|
||||
material_name=item.material_name,
|
||||
|
||||
@@ -62,7 +62,7 @@ def _is_unreceived_row(date_value: Any) -> bool:
|
||||
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
|
||||
① 未收料在途 ASN(Date Received 空、Qty Received 0);
|
||||
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
|
||||
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与预检;
|
||||
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与匹配;
|
||||
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
|
||||
"""
|
||||
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
|
||||
|
||||
@@ -84,7 +84,7 @@ def ensure_receipt_file_ready(
|
||||
outcome = rpa_trigger.trigger(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
reason="precheck_missing_ready_file",
|
||||
reason="matching_missing_ready_file",
|
||||
)
|
||||
outcome = outcome if isinstance(outcome, dict) else {}
|
||||
if outcome.get("ok"):
|
||||
|
||||
@@ -64,3 +64,38 @@ def manual_close_item(*, item_id: int, reason: str, actor_id: int | None = None,
|
||||
))
|
||||
db.session.commit()
|
||||
return {"item_id": item.id, "status": item.status}
|
||||
|
||||
|
||||
def manual_close_items(
|
||||
*, item_ids: list[int], reason: str,
|
||||
actor_id: str | None = None, request_id: str | None = None,
|
||||
) -> dict:
|
||||
"""批量人工关闭异常项(待处理池批量「标记无需处理」入口)。
|
||||
|
||||
Args:
|
||||
item_ids: TransferInvoiceItem.id 列表(非空)。
|
||||
reason: 关闭原因(必填,整批共用)。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"total", "results": [{item_id, ok, status|error}]};单行失败不阻断其余行。
|
||||
Raises:
|
||||
ValidationError: 原因缺失或 item_ids 为空。
|
||||
"""
|
||||
reason_value = str(reason or "").strip()
|
||||
if not reason_value:
|
||||
raise ValidationError("manual close reason is required", code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED)
|
||||
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")
|
||||
results: list[dict] = []
|
||||
for item_id in ids:
|
||||
try:
|
||||
outcome = manual_close_item(item_id=item_id, reason=reason_value,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
results.append({"item_id": item_id, "ok": True, "status": outcome["status"]})
|
||||
except (ValidationError, NotFoundError) as exc:
|
||||
results.append({"item_id": item_id, "ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:单行异常不炸整批
|
||||
results.append({"item_id": item_id, "ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
return {"total": len(ids), "results": results}
|
||||
+365
-123
@@ -1,11 +1,16 @@
|
||||
"""在途调拨预检服务。
|
||||
"""在途调拨匹配服务。
|
||||
|
||||
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → 外部系统 库存查询 →
|
||||
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
|
||||
严格数量匹配 → 匹配快照与 Hash",并支持匹配进度恢复(restore)。
|
||||
依赖:file_preparation / file_parser / invoice_aggregator / capability_client /
|
||||
date_policy / quantity / contracts / audit / models。
|
||||
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 外部系统;
|
||||
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
|
||||
匹配 Hash 由冻结快照复算;create_matching 落库 Run + Matching + Items,
|
||||
重复匹配对既有行"原地刷新"(不迁移 matching_id),行携带文件版本戳
|
||||
file_sha256,文件新版本消失的可执行行标记 blocked_file_removed;
|
||||
restore 与可调拨明细队列按匹配 scope(scope_item_query)实时圈行;
|
||||
restore 匹配卡是 scope 的实时视图:按 scope 圈行并逐行装饰新鲜度
|
||||
(checked_at/stale)与文件对账(file_current),counts 亦为实时聚合。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,15 +21,17 @@ from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from sqlalchemy import case, func, false, or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import canonical_hash
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
PrecheckCountsDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
PrecheckSummaryDTO,
|
||||
MatchingCountsDTO,
|
||||
MatchingItemDTO,
|
||||
MatchingSummaryDTO,
|
||||
RawLineRefDTO,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
@@ -52,14 +59,17 @@ from app.services.in_transit_transfer.invoice_aggregator import (
|
||||
aggregate_invoices,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.strategy import (
|
||||
TransferStrategyPolicy,
|
||||
default_strategy,
|
||||
)
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES,
|
||||
TransferType,
|
||||
ensure_transfer_type_supported,
|
||||
filter_invoices_for_type,
|
||||
invoice_in_scope,
|
||||
normalize_transfer_type,
|
||||
transfer_type_scope_note,
|
||||
)
|
||||
@@ -74,6 +84,8 @@ RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
|
||||
RESULT_FUTURE_DATE = "blocked_future_date"
|
||||
RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
|
||||
# 文件新版本缺失该行(上一版本可执行、最新文件中消失)。
|
||||
RESULT_FILE_REMOVED = "blocked_file_removed"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -118,17 +130,17 @@ class SourceProgressDTO:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckRunResult:
|
||||
"""一次预检运行的完整结果。"""
|
||||
class MatchingRunResult:
|
||||
"""一次匹配运行的完整结果。"""
|
||||
|
||||
summary: PrecheckSummaryDTO
|
||||
items: tuple[PrecheckInvoiceItemDTO, ...]
|
||||
summary: MatchingSummaryDTO
|
||||
items: tuple[MatchingItemDTO, ...]
|
||||
sources: tuple[SourceProgressDTO, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferDeps:
|
||||
"""预检/执行依赖集合(测试注入 Fake 替身)。"""
|
||||
"""匹配/执行依赖集合(测试注入 Fake 替身)。"""
|
||||
|
||||
file_repository: ReceiptFileRepository
|
||||
rpa_trigger: RpaTrigger
|
||||
@@ -137,8 +149,8 @@ class TransferDeps:
|
||||
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
|
||||
|
||||
|
||||
def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCountsDTO) -> str:
|
||||
"""预检状态:存在未完成来源 → file_pending;否则按可执行数定。"""
|
||||
def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCountsDTO) -> str:
|
||||
"""匹配状态:存在未完成来源 → file_pending;否则按可执行数定。"""
|
||||
if any(source.stage not in {"file_ready"} for source in sources):
|
||||
return "file_pending"
|
||||
if counts.executable_count > 0:
|
||||
@@ -146,7 +158,7 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCoun
|
||||
return "success"
|
||||
|
||||
|
||||
def run_precheck(
|
||||
def run_matching(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
@@ -156,8 +168,8 @@ def run_precheck(
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> PrecheckRunResult:
|
||||
"""执行一次只读预检(不写 外部系统)。
|
||||
) -> MatchingRunResult:
|
||||
"""执行一次只读匹配(不写 外部系统)。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
|
||||
@@ -168,7 +180,7 @@ def run_precheck(
|
||||
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
|
||||
transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。
|
||||
Returns:
|
||||
PrecheckRunResult(摘要 + 明细 + 来源进度)。
|
||||
MatchingRunResult(摘要 + 明细 + 来源进度)。
|
||||
Raises:
|
||||
ValidationError: source_codes 为空、日期范围非法或调拨类型非法/未支持。
|
||||
"""
|
||||
@@ -190,7 +202,7 @@ def run_precheck(
|
||||
validate_strategy = deps.strategy
|
||||
|
||||
sources: list[SourceProgressDTO] = []
|
||||
items: list[PrecheckInvoiceItemDTO] = []
|
||||
items: list[MatchingItemDTO] = []
|
||||
file_snapshot: dict[str, Any] = {}
|
||||
for source_code in source_codes:
|
||||
source_stage: SourceProgressDTO
|
||||
@@ -227,7 +239,7 @@ def run_precheck(
|
||||
# [调拨类型] 类型决定收料数据范围(如类型1仅保留 INVOICE 前缀 HOM/HOX/WTP),
|
||||
# 范围外票与日期范围过滤同语义:静默排除、不入明细、不阻断来源。
|
||||
invoices = filter_invoices_for_type(invoices, resolved_transfer_type)
|
||||
source_items = _precheck_invoices(
|
||||
source_items = _matching_invoices(
|
||||
invoices=invoices,
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
@@ -256,16 +268,16 @@ def run_precheck(
|
||||
except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code="TRANSFER.SOURCE_PRECheck_ERROR",
|
||||
error_code="TRANSFER.SOURCE_MATCH_ERROR",
|
||||
error_message=str(exc),
|
||||
))
|
||||
|
||||
counts = PrecheckCountsDTO(
|
||||
counts = MatchingCountsDTO(
|
||||
file_invoice_count=sum(
|
||||
1 for item in items
|
||||
),
|
||||
not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED),
|
||||
prechecked_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED),
|
||||
matched_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED),
|
||||
executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE),
|
||||
blocked_count=sum(1 for item in items if item.result.startswith("blocked_")),
|
||||
)
|
||||
@@ -280,7 +292,7 @@ def run_precheck(
|
||||
"counts": {
|
||||
"file_invoice_count": counts.file_invoice_count,
|
||||
"not_matured_count": counts.not_matured_count,
|
||||
"prechecked_count": counts.prechecked_count,
|
||||
"matched_count": counts.matched_count,
|
||||
"executable_count": counts.executable_count,
|
||||
"blocked_count": counts.blocked_count,
|
||||
},
|
||||
@@ -297,10 +309,10 @@ def run_precheck(
|
||||
for item in items
|
||||
],
|
||||
}
|
||||
precheck_hash = f"sha256:{canonical_hash(snapshot)}"
|
||||
matching_hash = f"sha256:{canonical_hash(snapshot)}"
|
||||
sources_tuple = tuple(sources)
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id="", # 落库时回填
|
||||
summary = MatchingSummaryDTO(
|
||||
matching_id="", # 落库时回填
|
||||
status=_summary_status(sources_tuple, counts),
|
||||
business_date=business_date,
|
||||
eligible_receipt_date_to=str(
|
||||
@@ -310,12 +322,12 @@ def run_precheck(
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=str(estimated_quantity),
|
||||
estimated_external_write_count=counts.executable_count,
|
||||
precheck_hash=precheck_hash,
|
||||
matching_hash=matching_hash,
|
||||
)
|
||||
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||
return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||
|
||||
|
||||
def _precheck_invoices(
|
||||
def _matching_invoices(
|
||||
*,
|
||||
invoices: list,
|
||||
source_code: str,
|
||||
@@ -323,9 +335,9 @@ def _precheck_invoices(
|
||||
ready_file: ReadyReceiptFile,
|
||||
deps: TransferDeps,
|
||||
run_no: str,
|
||||
) -> list[PrecheckInvoiceItemDTO]:
|
||||
"""对单个来源的汇总 Invoice 预检(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
|
||||
output: list[PrecheckInvoiceItemDTO] = []
|
||||
) -> list[MatchingItemDTO]:
|
||||
"""对单个来源的汇总 Invoice 匹配(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
|
||||
output: list[MatchingItemDTO] = []
|
||||
|
||||
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位,
|
||||
# 成熟项按 external_org(仓库映射的外部组织)分组,每组合并为一次批量查询。
|
||||
@@ -338,7 +350,7 @@ def _precheck_invoices(
|
||||
)
|
||||
receipt_date_iso = invoice.receipt_date.isoformat()
|
||||
if maturity == MATURITY_NOT_MATURED:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
@@ -350,7 +362,7 @@ def _precheck_invoices(
|
||||
))
|
||||
continue
|
||||
if maturity == MATURITY_FUTURE:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
@@ -385,7 +397,7 @@ def _precheck_invoices(
|
||||
)
|
||||
except ExternalQueryTimeoutError:
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
@@ -399,10 +411,10 @@ def _precheck_invoices(
|
||||
continue
|
||||
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
|
||||
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
|
||||
# 组内逐票给 blocked_external_query_failed + 原因,预检列表保持可见可解释。
|
||||
# 组内逐票给 blocked_external_query_failed + 原因,匹配列表保持可见可解释。
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
@@ -419,7 +431,7 @@ def _precheck_invoices(
|
||||
material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no,
|
||||
)
|
||||
if stock_qty is None:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
@@ -434,7 +446,7 @@ def _precheck_invoices(
|
||||
))
|
||||
continue
|
||||
match = classify_quantity_match(invoice.receipt_quantity, stock_qty)
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
@@ -462,12 +474,34 @@ def _item_status(result: str) -> str:
|
||||
|
||||
|
||||
def _generate_no(prefix: str, business_date: str) -> str:
|
||||
"""生成稳定业务编号(TPC-YYYYMMDD-XXXX / RUN-...)。"""
|
||||
"""生成稳定业务编号(MTG-YYYYMMDD-XXXX / RUN-...)。"""
|
||||
compact = str(business_date).replace("-", "")
|
||||
return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}"
|
||||
|
||||
|
||||
def create_precheck(
|
||||
def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
||||
"""读取行的文件版本戳(评估该行时所用的收料文件 checksum)。
|
||||
|
||||
用途:消失行标记(create_matching)与文件对账(restore 展示 / execute_items
|
||||
执行门禁③)据此判断"行的评估版本是否仍是最新文件版本"。
|
||||
两个消费方对 None(未知版本)口径不同:
|
||||
- restore 展示:None → file_current=False(仅展示不可执行原因,不阻断);
|
||||
- execute_items 门禁③:None 按"评估版本缺失"fail-closed 拒绝执行
|
||||
(TRANSFER.FILE_CHANGED),宁可误拒也不按过期文件写 ERP。
|
||||
|
||||
Args:
|
||||
item: InvoiceItem 行(raw_lines_json 首条携带 file_sha256 版本戳)。
|
||||
Returns:
|
||||
版本戳字符串;行无 raw_lines 或存量数据缺 file_sha256 键时返回 None
|
||||
(None 表示评估版本未知,调用方按各自口径处理,见上)。
|
||||
"""
|
||||
lines = item.raw_lines_json or []
|
||||
if not lines:
|
||||
return None
|
||||
return lines[0].get("file_sha256")
|
||||
|
||||
|
||||
def create_matching(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
@@ -476,19 +510,23 @@ def create_precheck(
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> PrecheckSummaryDTO:
|
||||
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
|
||||
) -> MatchingSummaryDTO:
|
||||
"""运行匹配并落库 TransferRun + TransferMatching + InvoiceItems。
|
||||
|
||||
落库为行原地刷新语义:相同粒度的既有行只刷新业务值(不迁移 matching_id)、
|
||||
行携带本次评估所用文件的 file_sha256 版本戳;上一版本可执行而最新文件
|
||||
消失的 ready 行被标记 blocked_file_removed。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_precheck。
|
||||
receipt_date_from / receipt_date_to / transfer_type: 同 run_precheck。
|
||||
source_codes / business_date / deps: 同 run_matching。
|
||||
receipt_date_from / receipt_date_to / transfer_type: 同 run_matching。
|
||||
Returns:
|
||||
预检摘要(precheck_id 已回填)。
|
||||
匹配摘要(matching_id 已回填)。
|
||||
"""
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
run_no = _generate_no("RUN", business_date)
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
@@ -503,7 +541,7 @@ def create_precheck(
|
||||
run_no=run_no,
|
||||
trigger_type="manual",
|
||||
business_date=business_date,
|
||||
status="prechecking",
|
||||
status="matching",
|
||||
source_codes_json=list(source_codes),
|
||||
counts_json=asdict(result.summary.counts),
|
||||
transfer_type=resolved_transfer_type.value,
|
||||
@@ -517,7 +555,7 @@ def create_precheck(
|
||||
|
||||
_valid_job_statuses = {
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
}
|
||||
for job_source in result.sources:
|
||||
create_source_job(
|
||||
@@ -528,9 +566,9 @@ def create_precheck(
|
||||
error_message=job_source.error_message,
|
||||
)
|
||||
|
||||
precheck_no = _generate_no("TPC", business_date)
|
||||
precheck = TransferPrecheck(
|
||||
precheck_no=precheck_no,
|
||||
matching_no = _generate_no("MTG", business_date)
|
||||
matching = TransferMatching(
|
||||
matching_no=matching_no,
|
||||
run_id=run.id,
|
||||
business_date=business_date,
|
||||
status=result.summary.status,
|
||||
@@ -555,14 +593,16 @@ def create_precheck(
|
||||
counts_json=asdict(result.summary.counts),
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
matching_hash=result.summary.matching_hash,
|
||||
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
|
||||
)
|
||||
db.session.add(precheck)
|
||||
db.session.add(matching)
|
||||
db.session.flush()
|
||||
|
||||
# [幂等] 相同 (来源,单号,料号,收料日期) 的重复预检不得累加异常行:
|
||||
# 非终态行原地刷新并挂到最新预检;终态行(已执行/人工关闭等)保持既定事实不复活。
|
||||
# [幂等·原地刷新] 相同 (来源,单号,料号,收料日期) 的重复匹配不得累加异常行:
|
||||
# 非终态行在原地刷新业务值(不迁移 matching_id 归属),并显式续 updated_at
|
||||
# 新鲜度(同值写入不触发 onupdate);终态行(已执行/人工关闭等)保持既定事实
|
||||
# 不复活。行是否仍有效由文件版本戳 + 消失行标记判定(见循环后标记段)。
|
||||
_terminal_item_statuses = {
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
@@ -570,9 +610,14 @@ def create_precheck(
|
||||
status_machine.TransferStatus.CANCELLED.value,
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
}
|
||||
# 文件版本戳与 file_snapshot 同源:本次评估各行所用的收料文件 checksum。
|
||||
source_checksums = {
|
||||
stage.source_code: stage.checksum
|
||||
for stage in result.sources
|
||||
if stage.checksum
|
||||
}
|
||||
for item in result.items:
|
||||
fields = {
|
||||
"precheck_id": precheck.id,
|
||||
"status": _item_status(item.result),
|
||||
"result_code": item.result if item.result != RESULT_EXECUTABLE else None,
|
||||
"result_message": item.reason or None,
|
||||
@@ -583,7 +628,13 @@ def create_precheck(
|
||||
"lot_no": item.lot_no or "",
|
||||
"receipt_warehouse_code": item.receipt_warehouse_code or "",
|
||||
"raw_lines_json": [
|
||||
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
|
||||
{
|
||||
"sheet": line.sheet,
|
||||
"row_no": line.row_no,
|
||||
"file_version": line.file_version,
|
||||
# 文件版本戳:Task 2/3 文件对账与消失行标记的判定依据。
|
||||
"file_sha256": source_checksums.get(item.source_code),
|
||||
}
|
||||
for line in item.raw_lines
|
||||
],
|
||||
}
|
||||
@@ -603,9 +654,13 @@ def create_precheck(
|
||||
if existing.status not in _terminal_item_statuses:
|
||||
for attr, value in fields.items():
|
||||
setattr(existing, attr, value)
|
||||
# 行不迁移归属(matching_id 保持首次创建值);显式续新鲜度,
|
||||
# 否则"同值刷新"不触发 onupdate、行看似陈旧。
|
||||
existing.updated_at = now
|
||||
continue
|
||||
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
|
||||
# 匹配阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=matching.id,
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
@@ -614,85 +669,134 @@ def create_precheck(
|
||||
receipt_date=item.receipt_date,
|
||||
**fields,
|
||||
))
|
||||
|
||||
# [消失行标记] 对每个有文件的 source:上一版本评估为可执行、本次文件版本
|
||||
# 已变化且行消失(或内容变化导致版本不同)的 ready 行,停用为
|
||||
# blocked_file_removed——防止按过期文件数据执行。只标 ready 行(blocked 行
|
||||
# 已有终局解释,覆盖会丢失真实原因);无版本戳的存量行跳过(fail-safe)。
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
for stage in result.sources:
|
||||
checksum = source_checksums.get(stage.source_code)
|
||||
if not checksum:
|
||||
continue
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == stage.source_code,
|
||||
TransferInvoiceItem.status == ready_status,
|
||||
)
|
||||
# 仅标记本次匹配收料日期范围内的行(范围外行不属于本次评估口径)。
|
||||
if receipt_date_from:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date >= receipt_date_from)
|
||||
if receipt_date_to:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date <= receipt_date_to)
|
||||
with db.session.no_autoflush:
|
||||
candidates = query.all()
|
||||
for row in candidates:
|
||||
evaluated_sha = _item_evaluated_sha(row)
|
||||
if evaluated_sha is None or evaluated_sha == checksum:
|
||||
continue
|
||||
row.status = blocked_status
|
||||
row.result_code = RESULT_FILE_REMOVED
|
||||
row.result_message = "receipt row removed from latest file"
|
||||
db.session.commit()
|
||||
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id=precheck_no,
|
||||
status=precheck.status,
|
||||
business_date=precheck.business_date,
|
||||
summary = MatchingSummaryDTO(
|
||||
matching_id=matching_no,
|
||||
status=matching.status,
|
||||
business_date=matching.business_date,
|
||||
eligible_receipt_date_to=result.summary.eligible_receipt_date_to,
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
expires_at=matching.expires_at.isoformat() if matching.expires_at else "",
|
||||
counts=result.summary.counts,
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
matching_hash=result.summary.matching_hash,
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
"""按 precheck_no 恢复预检进度与明细(页面刷新/会话恢复)。
|
||||
def restore_matching(
|
||||
matching_id: str,
|
||||
*,
|
||||
deps: TransferDeps | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""按 matching_no 恢复匹配进度与明细(页面刷新/会话恢复)。
|
||||
|
||||
匹配卡是 scope 的实时视图:明细不读 matching.items 行归属关系(行归属与
|
||||
匹配解耦后,"这份匹配覆盖哪些行"由 scope 重新圈定),counts 亦按 scope 行
|
||||
实时聚合;estimated_* 与 expires_at / matching_hash 沿用匹配记录留痕展示。
|
||||
|
||||
Args:
|
||||
precheck_id: 预检编号(TPC-...)。
|
||||
matching_id: 匹配编号(MTG-...)。
|
||||
deps: 注入依赖(缺省内部取 deps.get_transfer_dependencies();restore
|
||||
只读 strategy.confirm_ttl_seconds,不产生外部调用)。
|
||||
now: 新鲜度判定基准时间(缺省 datetime.utcnow(),测试注入冻结时钟)。
|
||||
Returns:
|
||||
{"summary": {...}, "items": [...], "sources": [...]}。
|
||||
{"summary": {...}, "items": [...], "sources": [...]};items 每行额外装饰
|
||||
item_id / checked_at / stale / file_current 四字段。
|
||||
Raises:
|
||||
NotFoundError: 预检不存在。
|
||||
NotFoundError: 匹配不存在。
|
||||
"""
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(
|
||||
precheck_no=str(precheck_id).strip()
|
||||
# [依赖缺省] API/Chat 未显式传 deps 时取默认装配(局部导入避免装配模块反向依赖)。
|
||||
if deps is None:
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
moment = now or datetime.utcnow()
|
||||
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
|
||||
|
||||
matching = db.session.query(TransferMatching).filter_by(
|
||||
matching_no=str(matching_id).strip()
|
||||
).first()
|
||||
if precheck is None:
|
||||
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
|
||||
counts = PrecheckCountsDTO(**{
|
||||
key: int(precheck.counts_json.get(key, 0))
|
||||
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
|
||||
"executable_count", "blocked_count")
|
||||
})
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id=precheck.precheck_no,
|
||||
status=precheck.status,
|
||||
business_date=precheck.business_date,
|
||||
eligible_receipt_date_to=str(
|
||||
date.fromisoformat(precheck.business_date) - timedelta(days=1)
|
||||
),
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
|
||||
estimated_external_write_count=int(precheck.estimated_external_write_count or 0),
|
||||
precheck_hash=precheck.precheck_hash,
|
||||
if matching is None:
|
||||
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
|
||||
|
||||
# [STEP 1] 按 scope 实时圈行(来源 + 收料日期区间 + 调拨类型前缀),行归属
|
||||
# (matching_id)不参与——同一批行可被多份同 scope 匹配同时看到。
|
||||
rows = (
|
||||
scope_item_query(matching)
|
||||
.order_by(TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
# [STEP 2] 文件对账映射:scope 内去重来源逐个投影当前可用文件版本,
|
||||
# 行评估版本戳与之比对得 file_current(来源无可用文件 → False)。
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({row.source_code for row in rows})
|
||||
}
|
||||
|
||||
# [STEP 3] counts 按 scope 行实时聚合(行归属不参与)。
|
||||
# matched_count 为"未成熟以外"的可用总数(与 run_matching 语义一致)。
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
not_matured_status = status_machine.TransferStatus.NOT_MATURED.value
|
||||
not_matured_count = sum(1 for row in rows if row.status == not_matured_status)
|
||||
counts = MatchingCountsDTO(
|
||||
file_invoice_count=len(rows),
|
||||
not_matured_count=not_matured_count,
|
||||
matched_count=len(rows) - not_matured_count,
|
||||
executable_count=sum(1 for row in rows if row.status == ready_status),
|
||||
blocked_count=sum(1 for row in rows if row.status == blocked_status),
|
||||
)
|
||||
summary = MatchingSummaryDTO(
|
||||
matching_id=matching.matching_no,
|
||||
status=matching.status,
|
||||
business_date=matching.business_date,
|
||||
eligible_receipt_date_to=str(
|
||||
date.fromisoformat(matching.business_date) - timedelta(days=1)
|
||||
),
|
||||
expires_at=matching.expires_at.isoformat() if matching.expires_at else "",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=matching.estimated_transfer_quantity or "0",
|
||||
estimated_external_write_count=int(matching.estimated_external_write_count or 0),
|
||||
matching_hash=matching.matching_hash,
|
||||
)
|
||||
|
||||
items = []
|
||||
for item in sorted(precheck.items, key=lambda row: row.invoice_no):
|
||||
items.append(PrecheckInvoiceItemDTO(
|
||||
source_code=item.source_code,
|
||||
material_no=item.material_no,
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
lot_no=item.lot_no or "",
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=item.result_code or (
|
||||
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
|
||||
),
|
||||
# 失败原因落库于 result_message(预检/重查降级均写);restore 不回读则
|
||||
# 前端刷新后原因恒为空,呈现「安静阻断」无法排查。
|
||||
reason=item.result_message or "",
|
||||
raw_lines=tuple(
|
||||
RawLineRefDTO(
|
||||
sheet=line.get("sheet", ""),
|
||||
row_no=int(line.get("row_no", 0)),
|
||||
file_version=line.get("file_version", ""),
|
||||
)
|
||||
for line in (item.raw_lines_json or [])
|
||||
),
|
||||
))
|
||||
for item in rows:
|
||||
items.append(
|
||||
_item_dto(item, latest_files.get(item.source_code) or {}, moment, ttl_seconds)
|
||||
)
|
||||
sources = [
|
||||
SourceProgressDTO(
|
||||
source_code=job.source_code,
|
||||
@@ -703,13 +807,151 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
error_code=job.error_code,
|
||||
error_message=job.error_message,
|
||||
)
|
||||
for job in (precheck.run.source_jobs if precheck.run else [])
|
||||
for job in (matching.run.source_jobs if matching.run else [])
|
||||
] or [
|
||||
SourceProgressDTO(source_code=code, stage="file_ready")
|
||||
for code in (precheck.scope_json.get("source_codes") or [])
|
||||
for code in (matching.scope_json.get("source_codes") or [])
|
||||
]
|
||||
return {
|
||||
"summary": summary,
|
||||
"items": items,
|
||||
"sources": sources,
|
||||
}
|
||||
|
||||
|
||||
def scope_item_query(matching: TransferMatching):
|
||||
"""按匹配 scope_json 实时圈定其行集(不依赖行的 matching_id 归属)。
|
||||
|
||||
用途:行归属与匹配解耦(原地刷新)后,"这份匹配覆盖哪些行"只能由
|
||||
scope(来源 + 收料日期区间 + 调拨类型范围)重新计算;
|
||||
restore 实时视图与可调拨明细队列共用本查询。
|
||||
|
||||
Args:
|
||||
matching: 匹配记录(读取 scope_json 的 source_codes / receipt_date_from /
|
||||
receipt_date_to / transfer_type)。
|
||||
Returns:
|
||||
TransferInvoiceItem 的 BaseQuery;类型 Invoice 前缀过滤与
|
||||
invoice_in_scope 同一常量口径,占位类型恒空(无任何行)。
|
||||
"""
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
sources = [str(code) for code in (scope.get("source_codes") or [])]
|
||||
query = db.session.query(TransferInvoiceItem).filter(
|
||||
TransferInvoiceItem.source_code.in_(sources),
|
||||
)
|
||||
# 收料日期为 ISO 字符串列,直接用字符串区间比较(与 run_matching 的内存过滤同语义)。
|
||||
date_from = scope.get("receipt_date_from")
|
||||
date_to = scope.get("receipt_date_to")
|
||||
if date_from:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date >= str(date_from))
|
||||
if date_to:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date <= str(date_to))
|
||||
resolved_type = normalize_transfer_type(scope.get("transfer_type"))
|
||||
if resolved_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
|
||||
query = query.filter(or_(
|
||||
*(func.upper(TransferInvoiceItem.invoice_no).like(f"{prefix}%") for prefix in prefixes),
|
||||
))
|
||||
else:
|
||||
# 占位类型范围外无任何票(与 invoice_in_scope 恒 False 同口径)。
|
||||
query = query.filter(false())
|
||||
return query
|
||||
|
||||
|
||||
def _item_dto(
|
||||
item: TransferInvoiceItem,
|
||||
latest: dict,
|
||||
moment: datetime,
|
||||
ttl_seconds: int,
|
||||
) -> MatchingItemDTO:
|
||||
"""把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。
|
||||
|
||||
Args:
|
||||
item: 明细行。
|
||||
latest: 该行来源当前可用文件状态投影(resolve_source_file_status 结果)。
|
||||
moment: 新鲜度判定基准时间。
|
||||
ttl_seconds: 行级新鲜度 TTL(strategy.confirm_ttl_seconds)。
|
||||
Returns:
|
||||
MatchingItemDTO(含 item_id / checked_at / stale / file_current)。
|
||||
"""
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
updated_at = item.updated_at
|
||||
return MatchingItemDTO(
|
||||
source_code=item.source_code,
|
||||
material_no=item.material_no,
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
lot_no=item.lot_no or "",
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=item.result_code or (
|
||||
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
|
||||
),
|
||||
# 失败原因落库于 result_message(匹配/重查降级均写);restore 不回读则
|
||||
# 前端刷新后原因恒为空,呈现「安静阻断」无法排查。
|
||||
reason=item.result_message or "",
|
||||
raw_lines=tuple(
|
||||
RawLineRefDTO(
|
||||
sheet=line.get("sheet", ""),
|
||||
row_no=int(line.get("row_no", 0)),
|
||||
file_version=line.get("file_version", ""),
|
||||
)
|
||||
for line in (item.raw_lines_json or [])
|
||||
),
|
||||
# [行装饰] 行级新鲜度与文件对账(实时视图判定依据):
|
||||
# stale=距上次评估超过确认 TTL;file_current=行评估版本戳仍是该来源
|
||||
# 当前可用文件 sha(无版本戳或无可用文件均视为不一致 → False)。
|
||||
item_id=item.id,
|
||||
checked_at=updated_at.isoformat() if updated_at else None,
|
||||
stale=bool(updated_at) and (moment - updated_at).total_seconds() > ttl_seconds,
|
||||
file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"),
|
||||
)
|
||||
|
||||
|
||||
def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | None = None) -> dict[str, Any]:
|
||||
"""全局可执行明细队列(「可调拨明细」入口数据源)。
|
||||
|
||||
用途:行归属与匹配解耦后,可执行行不再依附任何匹配卡——本查询给出全部
|
||||
ready_to_execute 行(跨匹配范围,业务稳定排序),供前端勾选后按行
|
||||
执行生成调拨单;行装饰(item_id / checked_at / stale / file_current)
|
||||
与 restore 实时视图同一口径。
|
||||
|
||||
Args:
|
||||
deps: 注入依赖(缺省内部取 get_transfer_dependencies;只读 TTL 配置)。
|
||||
now: 新鲜度判定基准时间(缺省 datetime.utcnow())。
|
||||
Returns:
|
||||
{"items": [MatchingItemDTO...], "counts": {"executable_count": N}}。
|
||||
"""
|
||||
if deps is None:
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
moment = now or datetime.utcnow()
|
||||
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
|
||||
|
||||
# [稳定排序] 收料日期(空值最后)→ Invoice → 创建时间:与重查/恢复等操作
|
||||
# 无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位。
|
||||
rows = (
|
||||
TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.status == status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
)
|
||||
.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({row.source_code for row in rows})
|
||||
}
|
||||
items = [
|
||||
_item_dto(row, latest_files.get(row.source_code) or {}, moment, ttl_seconds)
|
||||
for row in rows
|
||||
]
|
||||
return {"items": items, "counts": {"executable_count": len(rows)}}
|
||||
@@ -42,7 +42,7 @@ class MovementField:
|
||||
|
||||
# 定死的 10 个通用异动字段(领域契约,不配置化)。
|
||||
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
|
||||
# 批号(lot_no)为展示维度——预检列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
|
||||
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
|
||||
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
|
||||
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
"""在途调拨执行编排(Run 生命周期辅助)。
|
||||
|
||||
用途:创建执行 Run(关联预检与可执行明细、置 executing、记录确认)、
|
||||
用途:按选中明细行创建执行 Run(置 executing、记录业务日/来源范围/行计数)、
|
||||
按明细终态收尾 Run(success / partial_failed)。
|
||||
依赖:models、status、precheck_service.TransferDeps。
|
||||
逻辑:同一预检只允许创建一个执行 Run(confirmed_at 防重复);重复创建 409。
|
||||
依赖:models、status、date_policy、matching_service(编号生成/TransferDeps)。
|
||||
逻辑:执行 Run 与匹配解耦(不回写 matching.run_id / confirmed_at);行归属
|
||||
由调用方按 scope 圈定(见 matching_service.scope_item_query)后显式传入,
|
||||
本模块只负责"建 Run + 关联选中行",已关联(run_id 非空)的行跳过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.precheck_service import TransferDeps
|
||||
|
||||
EXECUTION_CONFLICT_CODE = "TRANSFER.PRECHECK_ALREADY_EXECUTED"
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.matching_service import TransferDeps, _generate_no
|
||||
|
||||
|
||||
def create_execution_run(
|
||||
precheck: TransferPrecheck,
|
||||
def create_execution_run_for_items(
|
||||
items: list[TransferInvoiceItem],
|
||||
*,
|
||||
deps: TransferDeps, # noqa: ARG001 —— 预留并发/锁参数扩展
|
||||
actor_id: int | None = None,
|
||||
selected_invoice_nos: set[str] | None = None,
|
||||
selected_item_ids: set[int] | None = None,
|
||||
) -> TransferRun:
|
||||
"""为已就绪预检创建执行 Run 并关联选中的可执行明细。
|
||||
"""为选中可执行明细行创建执行 Run 并关联(行级执行,不绑定匹配)。
|
||||
|
||||
Args:
|
||||
precheck: 已预检(ready_to_execute)对象。
|
||||
items: 候选明细行(调用方已完成可执行校验,见 execution_service.execute_items)。
|
||||
deps: 依赖集合(预留)。
|
||||
actor_id: 确认操作者。
|
||||
selected_invoice_nos: 选择范围(缺省关联全部可执行项)。
|
||||
actor_id: 触发执行的用户(写入 run.created_by 留痕)。
|
||||
selected_item_ids: 关联范围(行 id 集;缺省关联 items 中全部可执行未关联行)。
|
||||
Returns:
|
||||
状态为 executing 的 TransferRun。
|
||||
Raises:
|
||||
ConflictError: 预检已确认(重复执行)。
|
||||
状态为 executing 的 TransferRun(run_no/business_date 取当前业务日)。
|
||||
"""
|
||||
if precheck.confirmed_at is not None:
|
||||
raise ConflictError(
|
||||
"precheck already executed", code=EXECUTION_CONFLICT_CODE,
|
||||
)
|
||||
run_no = f"RUN-{str(precheck.business_date).replace('-', '')}-{uuid.uuid4().hex[:6].upper()}"
|
||||
selected = selected_item_ids if selected_item_ids is not None else None
|
||||
business_date = str(business_date_now())
|
||||
# 行计数快照:按本次关联(选中)行聚合,供通知/运营展示(与匹配 counts 同形状)。
|
||||
candidates = [
|
||||
item for item in items
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
and item.run_id is None
|
||||
and (selected is None or item.id in selected)
|
||||
]
|
||||
run = TransferRun(
|
||||
run_no=run_no,
|
||||
run_no=_generate_no("RUN", business_date),
|
||||
trigger_type="manual",
|
||||
business_date=precheck.business_date,
|
||||
business_date=business_date,
|
||||
status=status_machine.TransferRunStatus.EXECUTING.value,
|
||||
source_codes_json=list(precheck.scope_json.get("source_codes") or []),
|
||||
counts_json=dict(precheck.counts_json or {}),
|
||||
source_codes_json=sorted({item.source_code for item in candidates}),
|
||||
counts_json={
|
||||
"file_invoice_count": len(candidates),
|
||||
"not_matured_count": 0,
|
||||
"matched_count": len(candidates),
|
||||
"executable_count": len(candidates),
|
||||
"blocked_count": 0,
|
||||
},
|
||||
created_by=actor_id,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
|
||||
precheck.run_id = run.id
|
||||
precheck.status = status_machine.TransferRunStatus.EXECUTING.value
|
||||
precheck.confirmed_at = datetime.utcnow()
|
||||
precheck.confirmed_by = actor_id
|
||||
|
||||
for item in precheck.items:
|
||||
if item.status != status_machine.TransferStatus.READY_TO_EXECUTE.value or item.run_id is not None:
|
||||
continue
|
||||
if selected_invoice_nos is not None and item.invoice_no not in selected_invoice_nos:
|
||||
continue
|
||||
# 关联选中行:置 executing 并递增 Attempt 序号(每次执行创建新 Attempt)。
|
||||
for item in candidates:
|
||||
item.run_id = run.id
|
||||
item.status = status_machine.TransferStatus.EXECUTING.value
|
||||
item.attempt_no += 1
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
|
||||
|
||||
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
|
||||
供来源状态投影(source_file_status)、预检取文件(movement_file_repository)、
|
||||
供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、
|
||||
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
|
||||
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
|
||||
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
|
||||
@@ -36,7 +36,7 @@ def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnEleme
|
||||
"""返回「当前可用的收料归档文件」SQL 条件。
|
||||
|
||||
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
|
||||
+ 未过保留期(archive_expires_at 为空视为长期有效)。预检复用与下载
|
||||
+ 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载
|
||||
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
|
||||
|
||||
Args:
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.execution_service import _write_item
|
||||
from app.services.in_transit_transfer.orchestrator import finalize_run
|
||||
from app.services.in_transit_transfer.precheck_service import TransferDeps
|
||||
from app.services.in_transit_transfer.matching_service import TransferDeps
|
||||
|
||||
STALE_EXECUTION_THRESHOLD_SECONDS = 3600
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨每日历史恢复(自动复核待处理池)。
|
||||
|
||||
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新预检并创建新 Attempt;
|
||||
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新匹配并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:models、retry_service._recheck_item、TransferDeps。
|
||||
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
@@ -13,7 +13,7 @@ from dataclasses import dataclass
|
||||
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.precheck_service import TransferDeps
|
||||
from app.services.in_transit_transfer.matching_service import TransferDeps
|
||||
from app.services.in_transit_transfer.retry_service import _recheck_item
|
||||
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
|
||||
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
|
||||
依赖:models、capability_client、quantity、status、audit、precheck_service.TransferDeps。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
|
||||
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断;
|
||||
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,7 +20,7 @@ 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.precheck_service import (
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_EXTERNAL_QUERY_FAILED,
|
||||
RESULT_EXECUTABLE,
|
||||
TransferDeps,
|
||||
@@ -30,7 +31,7 @@ RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
|
||||
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
|
||||
|
||||
# 可重查状态:可恢复阻断 + 可执行(已可执行的行也允许重查核对最新库存,
|
||||
# 避免预检后库存变化无法发现);终态(已执行/人工关闭等)仍不可重查。
|
||||
# 避免匹配后库存变化无法发现);终态(已执行/人工关闭等)仍不可重查。
|
||||
_RETRYABLE_STATUSES = {
|
||||
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
@@ -64,7 +65,7 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
# [降级] 与 precheck 逐票语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
|
||||
# [降级] 与 matching 逐票语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
|
||||
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
|
||||
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
|
||||
try:
|
||||
@@ -89,6 +90,9 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
item.result_message = f"external query failed: {detail}"
|
||||
attempt.status = "failed"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
# [行级 TTL 续期] 降级也是一次真实评估:显式刷新 updated_at(执行门禁
|
||||
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
|
||||
item.updated_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ITEM_RECHECKED",
|
||||
aggregate_type="transfer_item",
|
||||
@@ -121,6 +125,9 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
item.external_quantity = str(stock_qty)
|
||||
attempt.status = "success"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
# [行级 TTL 续期] 重查即续新鲜度:状态落定后显式刷新 updated_at(执行门禁
|
||||
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
|
||||
item.updated_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ITEM_RECHECKED",
|
||||
aggregate_type="transfer_item",
|
||||
@@ -173,26 +180,67 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTER
|
||||
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
|
||||
|
||||
|
||||
def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 外部系统 库存:对同一预检下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
|
||||
def requery_items_by_ids(
|
||||
*, item_ids: list[int], deps: TransferDeps,
|
||||
actor_id: str | None = None, request_id: str | None = None,
|
||||
) -> dict:
|
||||
"""按明细 id 批量重查外部系统库存(待处理池批量「重查」入口)。
|
||||
|
||||
与 requery_items(匹配号定位)的差异:待处理池的行可能分散在多份历史
|
||||
匹配,只能按 id 直取。单行失败(状态不允许/不存在/异常)不影响其余行,
|
||||
隔离语义与 requery_items 一致。
|
||||
|
||||
Args:
|
||||
precheck_no: 预检编号(定位明细集合)。
|
||||
item_ids: TransferInvoiceItem.id 列表(非空)。
|
||||
deps / actor_id / request_id: 同 retry_item。
|
||||
Returns:
|
||||
{"total", "results": [{item_id, invoice_no, ok, status|error}]}。
|
||||
Raises:
|
||||
ValidationError: item_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")
|
||||
results: list[dict] = []
|
||||
for item_id in ids:
|
||||
try:
|
||||
retry_item(item_id=item_id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
item = db.session.get(TransferInvoiceItem, item_id)
|
||||
results.append({"item_id": item_id, "invoice_no": item.invoice_no if item else "",
|
||||
"ok": True, "status": item.status if item else ""})
|
||||
except (ValidationError, NotFoundError) as exc:
|
||||
results.append({"item_id": item_id, "invoice_no": "", "ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:单行异常不炸整批
|
||||
logger.warning(
|
||||
"transfer batch requery row crashed (skipped): item=%s error=%s",
|
||||
item_id, str(exc).strip() or exc.__class__.__name__,
|
||||
)
|
||||
results.append({"item_id": item_id, "invoice_no": "", "ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
return {"total": len(ids), "results": results}
|
||||
|
||||
|
||||
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:
|
||||
"""批量重查 外部系统 库存:对同一匹配下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
|
||||
|
||||
Args:
|
||||
matching_no: 匹配编号(定位明细集合)。
|
||||
deps: 注入依赖(capabilities = 外部系统网关客户端)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该预检全部可重查行。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该匹配全部可重查行。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"precheck_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
{"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
单行失败(状态不允许/不存在)不影响其余行(来源级隔离同款语义)。
|
||||
"""
|
||||
from app.models import TransferPrecheck
|
||||
from app.models import TransferMatching
|
||||
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=precheck_no).first()
|
||||
if precheck is None:
|
||||
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
|
||||
matching = TransferMatching.query.filter_by(matching_no=matching_no).first()
|
||||
if matching is None:
|
||||
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.precheck_id == precheck.id,
|
||||
TransferInvoiceItem.matching_id == matching.id,
|
||||
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
|
||||
)
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
@@ -219,4 +267,4 @@ def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
return {"precheck_no": precheck_no, "total": len(items), "results": results}
|
||||
return {"matching_no": matching_no, "total": len(items), "results": results}
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。
|
||||
|
||||
用途:将领域 DTO 转为前端稳定 JSON(预检摘要/明细/来源进度/执行结果)。
|
||||
用途:将领域 DTO 转为前端稳定 JSON(匹配摘要/明细/来源进度/执行结果)。
|
||||
依赖:contracts、execution_service。
|
||||
逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移。
|
||||
"""
|
||||
@@ -13,9 +13,9 @@ from app.services.in_transit_transfer.execution_service import serialize_run_res
|
||||
|
||||
|
||||
def serialize_summary(summary) -> dict[str, Any]:
|
||||
"""预检摘要序列化。"""
|
||||
"""匹配摘要序列化。"""
|
||||
return {
|
||||
"precheck_id": summary.precheck_id,
|
||||
"matching_id": summary.matching_id,
|
||||
"status": summary.status,
|
||||
"business_date": summary.business_date,
|
||||
"eligible_receipt_date_to": summary.eligible_receipt_date_to,
|
||||
@@ -23,18 +23,23 @@ def serialize_summary(summary) -> dict[str, Any]:
|
||||
"counts": {
|
||||
"file_invoice_count": summary.counts.file_invoice_count,
|
||||
"not_matured_count": summary.counts.not_matured_count,
|
||||
"prechecked_count": summary.counts.prechecked_count,
|
||||
"matched_count": summary.counts.matched_count,
|
||||
"executable_count": summary.counts.executable_count,
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
},
|
||||
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
|
||||
"estimated_external_write_count": summary.estimated_external_write_count,
|
||||
"precheck_hash": summary.precheck_hash,
|
||||
"matching_hash": summary.matching_hash,
|
||||
}
|
||||
|
||||
|
||||
def serialize_item(item) -> dict[str, Any]:
|
||||
"""明细项序列化(决策 6 十列字段)。"""
|
||||
"""明细项序列化(决策 6 十列字段 + 行装饰字段)。
|
||||
|
||||
行装饰字段(item_id/checked_at/stale/file_current)由 restore 按 scope
|
||||
实时视图路径在 DTO 上填齐;匹配快照路径(run_matching)为缺省值
|
||||
(0/None/False/False),前端按存在性展示。
|
||||
"""
|
||||
return {
|
||||
"source_code": item.source_code,
|
||||
"material_no": item.material_no,
|
||||
@@ -53,6 +58,10 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
|
||||
for line in item.raw_lines
|
||||
],
|
||||
"item_id": item.item_id,
|
||||
"checked_at": item.checked_at,
|
||||
"stale": item.stale,
|
||||
"file_current": item.file_current,
|
||||
}
|
||||
|
||||
|
||||
@@ -69,8 +78,8 @@ def serialize_source(source) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def serialize_precheck_detail(detail: dict[str, Any]) -> dict[str, Any]:
|
||||
"""预检恢复详情(summary + items + sources)。"""
|
||||
def serialize_matching_detail(detail: dict[str, Any]) -> dict[str, Any]:
|
||||
"""匹配恢复详情(summary + items + sources)。"""
|
||||
return {
|
||||
"summary": serialize_summary(detail["summary"]),
|
||||
"items": [serialize_item(item) for item in detail["items"]],
|
||||
|
||||
@@ -25,7 +25,7 @@ FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
"""返回某来源的收料文件状态投影。
|
||||
|
||||
失效判定(不依赖保留期清理任务落位,与预检取文件/下载同口径,见
|
||||
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
|
||||
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
|
||||
|
||||
Returns:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨来源级状态服务(唯一推进入口)。
|
||||
|
||||
用途:统一创建/推进 TransferSourceJob(run 内来源级状态真相源),
|
||||
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
|
||||
让 create_matching / restore / 未来回调等调用方都经由本服务,不各自散落改表。
|
||||
依赖:models(TransferSourceJob)、status_machine。
|
||||
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
|
||||
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 外部系统/触发 RPA。
|
||||
@@ -17,7 +17,7 @@ from app.models import TransferSourceJob
|
||||
|
||||
SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ class TransferStatus(StrEnum):
|
||||
|
||||
FILE_PENDING = "file_pending"
|
||||
FILE_READY = "file_ready"
|
||||
PRECHECKING = "prechecking"
|
||||
MATCHING = "matching"
|
||||
READY_TO_EXECUTE = "ready_to_execute"
|
||||
EXECUTING = "executing"
|
||||
SUCCESS = "success"
|
||||
@@ -43,7 +43,7 @@ class TransferRunStatus(StrEnum):
|
||||
|
||||
QUEUED = "queued"
|
||||
PREPARING_FILES = "preparing_files"
|
||||
PRECHECKING = "prechecking"
|
||||
MATCHING = "matching"
|
||||
READY_TO_EXECUTE = "ready_to_execute"
|
||||
EXECUTING = "executing"
|
||||
SUCCESS = "success"
|
||||
@@ -78,17 +78,17 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
}),
|
||||
TransferStatus.FILE_READY.value: frozenset({
|
||||
TransferStatus.PRECHECKING.value,
|
||||
TransferStatus.MATCHING.value,
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
}),
|
||||
TransferStatus.PRECHECKING.value: frozenset({
|
||||
TransferStatus.MATCHING.value: frozenset({
|
||||
TransferStatus.READY_TO_EXECUTE.value,
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
TransferStatus.NOT_MATURED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.READY_TO_EXECUTE.value: frozenset({
|
||||
TransferStatus.PRECHECKING.value, # 确认失效/库存变化 → 新 Attempt 重新预检
|
||||
TransferStatus.MATCHING.value, # 确认失效/库存变化 → 新 Attempt 重新匹配
|
||||
TransferStatus.EXECUTING.value,
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
@@ -101,7 +101,7 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
|
||||
TransferStatus.PRECHECKING.value, # 仅 外部系统 重查/重新预检,创建新 Attempt
|
||||
TransferStatus.MATCHING.value, # 仅 外部系统 重查/重新匹配,创建新 Attempt
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
@@ -121,11 +121,11 @@ RUN_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferRunStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferRunStatus.PREPARING_FILES.value: frozenset({
|
||||
TransferRunStatus.PRECHECKING.value,
|
||||
TransferRunStatus.MATCHING.value,
|
||||
TransferRunStatus.FAILED.value,
|
||||
TransferRunStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferRunStatus.PRECHECKING.value: frozenset({
|
||||
TransferRunStatus.MATCHING.value: frozenset({
|
||||
TransferRunStatus.READY_TO_EXECUTE.value,
|
||||
TransferRunStatus.FAILED.value,
|
||||
TransferRunStatus.CANCELLED.value,
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"""在途调拨类型契约。
|
||||
|
||||
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
|
||||
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝预检,规则先冻结)。
|
||||
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝匹配,规则先冻结)。
|
||||
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
|
||||
逻辑:类型决定预检纳入哪些收料票——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
逻辑:类型决定匹配纳入哪些收料票——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
的票(大小写不敏感,范围外票与收料日期范围过滤同语义,静默排除不入明细);
|
||||
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
|
||||
类型 3 规则待业务定义。调用方必须先 ensure_transfer_type_supported 再过滤。
|
||||
类型 3 规则待业务定义。范围判断统一走 invoice_in_scope 谓词(匹配过滤与
|
||||
scope 行圈定共用);调用方必须先 ensure_transfer_type_supported 再过滤。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,7 +30,7 @@ class TransferType(StrEnum):
|
||||
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
|
||||
|
||||
|
||||
# 一期已实现预检/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
|
||||
# 一期已实现匹配/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
|
||||
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
|
||||
|
||||
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
|
||||
@@ -63,7 +64,7 @@ def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
|
||||
|
||||
|
||||
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
|
||||
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入预检。
|
||||
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入匹配。
|
||||
|
||||
Args:
|
||||
transfer_type: 已规范化的调拨类型。
|
||||
@@ -78,6 +79,27 @@ def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
@@ -88,20 +110,16 @@ def filter_invoices_for_type(
|
||||
invoices: 已汇总的收料票。
|
||||
transfer_type: 已规范化且已确认支持的调拨类型。
|
||||
Returns:
|
||||
类型范围内的票列表。
|
||||
类型范围内的票列表(判断口径统一走 invoice_in_scope)。
|
||||
"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
|
||||
return [
|
||||
invoice for invoice in invoices
|
||||
if str(invoice.invoice_no or "").strip().upper().startswith(prefixes)
|
||||
]
|
||||
# 类型 2/3 的过滤规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
|
||||
return list(invoices)
|
||||
return [
|
||||
invoice for invoice in invoices
|
||||
if invoice_in_scope(invoice.invoice_no, transfer_type)
|
||||
]
|
||||
|
||||
|
||||
def transfer_type_scope_note(transfer_type: TransferType) -> str:
|
||||
"""类型的范围规则说明(写入 TransferPrecheck.scope_json 供审计追溯)。"""
|
||||
"""类型的范围规则说明(写入 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:
|
||||
|
||||
@@ -68,7 +68,14 @@ def extract_path(obj: Any, path: str) -> Any:
|
||||
|
||||
|
||||
def _walk(cur: Any, tokens: list[str]) -> Any:
|
||||
"""按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。"""
|
||||
"""按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。
|
||||
|
||||
[缺陷修复 2026-09-23] 扇出收集的命中值本身可能是列表(更深层重复节点,如
|
||||
多 RecordSet 的 Master 列表、单 Master 多 Record 的 Field 列表)。若不拍平,
|
||||
嵌套 list 会让 each/pick 等消费方取不到任何字段 → 行被静默丢弃——后果是
|
||||
批量库存查询整批误判为查无库存(机制推演;该嵌套形态尚未在生产观测到)。
|
||||
收集结果统一拍平一层:语义仍是"路径在重复结构中的全部命中"。
|
||||
"""
|
||||
if not tokens:
|
||||
return cur
|
||||
tok, rest = tokens[0], tokens[1:]
|
||||
@@ -81,10 +88,23 @@ def _walk(cur: Any, tokens: list[str]) -> Any:
|
||||
return _walk(cur[tok], rest)
|
||||
if isinstance(cur, list):
|
||||
collected = [hit for item in cur if (hit := _walk(item, tokens)) is not MISSING]
|
||||
return collected if collected else MISSING
|
||||
if not collected:
|
||||
return MISSING
|
||||
return _flatten(collected)
|
||||
return MISSING
|
||||
|
||||
|
||||
def _flatten(items: list[Any]) -> list[Any]:
|
||||
"""把扇出收集结果拍平一层:列表命中拼接、标量/字典命中保留,顺序不变。"""
|
||||
flat: list[Any] = []
|
||||
for item in items:
|
||||
if isinstance(item, list):
|
||||
flat.extend(item)
|
||||
else:
|
||||
flat.append(item)
|
||||
return flat
|
||||
|
||||
|
||||
# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ----
|
||||
|
||||
def _default(value: Any, default: Any) -> Any:
|
||||
@@ -163,6 +183,39 @@ def _pick(value: Any, key_field: str | None = None, key_value: Any = None,
|
||||
return MISSING
|
||||
|
||||
|
||||
def _expand_repeated_child(item: Any, fields: dict) -> list[Any]:
|
||||
"""把"容器记录"沿 fields 表达式引用的重复子节点展开成逐子记录单元。
|
||||
|
||||
[缺陷修复 2026-09-23] 假说防御:若 ERP 返回"单 Master 容器挂多条库存 Record"
|
||||
的形态,fields 的 expr 都以同一首段(如 Record)开头时,扁平映射会让 pick 只
|
||||
取到首条记录,其余行(不同批号/料号的库存)被静默丢弃——批量查询整批误判为
|
||||
查无库存。本修复对该形态按首段逐元素拆开,保证"一条 Record 一行"。
|
||||
真实留档响应(IntegrationCall 审计)均为扁平形态(每 Master 单 Record),
|
||||
该嵌套形态尚未在生产观测到;此处按通用归一化语义防御。
|
||||
|
||||
Args:
|
||||
item: each 的单个元素(dict 容器记录;非 dict 原样返回)。
|
||||
fields: each 的子映射(expr 首段即候选重复子节点名)。
|
||||
Returns:
|
||||
展开后的单元列表(无可展开的重复子节点时为 [item])。
|
||||
仅当全部 expr 首段一致且该子节点是"非空 dict 列表"时才展开,
|
||||
其余形态维持原行为(fail-safe,不做有歧义的拆分)。
|
||||
"""
|
||||
if not isinstance(item, dict):
|
||||
return [item]
|
||||
roots = {
|
||||
str(spec.get("expr") or "").split(".", 1)[0].split("[", 1)[0]
|
||||
for spec in fields.values() if isinstance(spec, dict)
|
||||
}
|
||||
if "" in roots or len(roots) != 1:
|
||||
return [item]
|
||||
root = next(iter(roots))
|
||||
children = item.get(root)
|
||||
if not isinstance(children, list) or not children or not all(isinstance(c, dict) for c in children):
|
||||
return [item]
|
||||
return [{**item, root: child} for child in children]
|
||||
|
||||
|
||||
def _each(value: Any, fields: dict | None = None) -> Any:
|
||||
"""对列表逐元素套用子映射,产出 dict 列表(多条外部记录→多行结果的通用需求)。
|
||||
|
||||
@@ -170,6 +223,9 @@ def _each(value: Any, fields: dict | None = None) -> Any:
|
||||
value: 目标列表(每项为 dict,如归一化后的 Master 记录列表)。
|
||||
fields: 子映射 {输出字段: {expr/transform/args}},语义与 map_response 顶层一致:
|
||||
元素内缺字段按 MISSING 处理(跳过该键),转换函数复用 TRANSFORMS 白名单。
|
||||
Note:
|
||||
元素是"容器记录"(同一 Master 下挂多条 Record,见 _expand_repeated_child)
|
||||
时按子记录逐条展开成行——批量查询多条库存不得丢行(2026-09-23 缺陷修复)。
|
||||
"""
|
||||
if value is MISSING:
|
||||
# 目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 归一为空列表:
|
||||
@@ -184,27 +240,30 @@ def _each(value: Any, fields: dict | None = None) -> Any:
|
||||
raise MappingInvalidError(details={"reason": "each_target_not_list"})
|
||||
out: list[Any] = []
|
||||
for item in value:
|
||||
row: dict[str, Any] = {}
|
||||
for field, spec in (fields or {}).items():
|
||||
if not isinstance(spec, dict):
|
||||
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
|
||||
if "default" in spec:
|
||||
v: Any = spec["default"]
|
||||
else:
|
||||
expr = spec.get("expr")
|
||||
v = extract_path(item, expr) if expr is not None else MISSING
|
||||
transform = spec.get("transform")
|
||||
if transform:
|
||||
fn = TRANSFORMS.get(transform)
|
||||
if fn is None:
|
||||
raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"})
|
||||
v = fn(v, **(spec.get("args") or {}))
|
||||
if v is not MISSING:
|
||||
row[field] = v
|
||||
if row:
|
||||
# 全字段缺失的空行(如 Master 节点存在但无 Record 子节点)跳过,
|
||||
# 避免产出违反行 Schema 的 {} 行;部分缺失仍保留,由行 Schema fail-closed。
|
||||
out.append(row)
|
||||
# [缺陷修复 2026-09-23] 容器记录内挂多条子记录(重复节点)时逐条展开,
|
||||
# 保证"一条外部记录一行";单条 dict 子节点行为不变。
|
||||
for unit in _expand_repeated_child(item, fields or {}):
|
||||
row: dict[str, Any] = {}
|
||||
for field, spec in (fields or {}).items():
|
||||
if not isinstance(spec, dict):
|
||||
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
|
||||
if "default" in spec:
|
||||
v: Any = spec["default"]
|
||||
else:
|
||||
expr = spec.get("expr")
|
||||
v = extract_path(unit, expr) if expr is not None else MISSING
|
||||
transform = spec.get("transform")
|
||||
if transform:
|
||||
fn = TRANSFORMS.get(transform)
|
||||
if fn is None:
|
||||
raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"})
|
||||
v = fn(v, **(spec.get("args") or {}))
|
||||
if v is not MISSING:
|
||||
row[field] = v
|
||||
if row:
|
||||
# 全字段缺失的空行(如 Master 节点存在但无 Record 子节点)跳过,
|
||||
# 避免产出违反行 Schema 的 {} 行;部分缺失仍保留,由行 Schema fail-closed。
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -792,6 +792,24 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
|
||||
return None
|
||||
|
||||
|
||||
def _lock_process_gates_for_task(task: ShippingNotice) -> None:
|
||||
"""
|
||||
[锁序约定] 回调写库存候选数据前,先锁该任务活跃 Execution 的全部 Gate 行。
|
||||
|
||||
外部等待轮询(run_inventory_external_wait_poll)的顺序是先锁 Gate 再读候选行;
|
||||
本侧若先写候选、后经 Gate 同步更新 Gate 行,会以相反顺序与轮询形成死锁环,
|
||||
事务被毒化后以 InFailedSqlTransaction 收口且轮询链断裂
|
||||
(2026-09-23 test job 8818:库存 RPA 回调 × external-wait 轮询竞跑)。
|
||||
统一为两侧都先取 Gate 锁:后到方短暂阻塞后串行执行,不再产生错误。
|
||||
"""
|
||||
from app.models import ShippingProcessGate
|
||||
|
||||
execution_id = int(getattr(task, 'active_process_execution_id', 0) or 0)
|
||||
if not execution_id:
|
||||
return
|
||||
ShippingProcessGate.query.filter_by(execution_id=execution_id).with_for_update().all()
|
||||
|
||||
|
||||
def _validate_rpa_callback_gate(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""
|
||||
复核 RPA 触发后可能漂移的订单与路由门禁(skipped/failed/success 共用)。
|
||||
@@ -1813,6 +1831,8 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
|
||||
# [锁序约定] 写入前先锁 Gate 行,与 external-wait 轮询串行(见 _lock_process_gates_for_task)。
|
||||
_lock_process_gates_for_task(task)
|
||||
runtime = _save_last_inventory_rpa_runtime(task, payload)
|
||||
callback_status = _normalize_rpa_inventory_result_status(payload)
|
||||
|
||||
@@ -2486,6 +2506,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
"error": gate_resp.get("message") or "inventory_source_gate_blocked",
|
||||
})
|
||||
continue
|
||||
# [锁序约定] 写入前先锁 Gate 行,与 external-wait 轮询串行(见 _lock_process_gates_for_task)。
|
||||
_lock_process_gates_for_task(task)
|
||||
round_resp = _validate_rpa_callback_round(task, merged_item)
|
||||
if round_resp is not None:
|
||||
round_data = round_resp.get("data") if isinstance(round_resp.get("data"), dict) else {}
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
"""在途调拨术语重构:precheck → match(表/列/约束/状态值全量改名)
|
||||
|
||||
Revision ID: rn1a2b3c4d5e6
|
||||
Revises: 43a8179cdd88
|
||||
Create Date: 2026-09-23 22:30:00.000000
|
||||
|
||||
用途:与代码术语重构(precheck→match,中文「匹配」)配套的存储层改造——
|
||||
1) 表改名:transfer_prechecks → transfer_matchings。
|
||||
2) 列改名:transfer_matchings.precheck_no→matching_no、precheck_hash→matching_hash;
|
||||
transfer_invoice_items.precheck_id→matching_id;transfer_audit_events.precheck_no→matching_no;
|
||||
transfer_matchings.status server_default 'prechecking'→'matching'。
|
||||
3) 枚举值刷写:transfer_matchings / transfer_runs / transfer_source_jobs /
|
||||
transfer_invoice_items 四表 status 'prechecking'→'matching';
|
||||
transfer_attempts.kind 'precheck'→'match'。
|
||||
4) 约束/索引替换:uq/ck 旧名 drop 后按新名与新增值列表重建
|
||||
(uq_transfer_matchings_matching_no、ck_transfer_matchings_status、
|
||||
uq_transfer_invoice_items_matching_grain、各表 ck_*_status、ck_transfer_attempts_kind);
|
||||
索引 ix_transfer_prechecks_run_status/business_date 改名。
|
||||
依赖:43a8179cdd88 为上一 head(模块未上线,无历史数据兼容包袱,直改新值)。
|
||||
逻辑:先改表名 → drop 旧名约束 → 刷历史行数据(避免被旧 CHECK 拦截)→ 列改名 →
|
||||
建新名约束/索引;约束与列经 batch 兼容 SQLite(batch 在 PG 上渲染为原生 ALTER),
|
||||
索引用独立 DROP/CREATE(两种库均支持);downgrade 全量对称回滚。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = 'rn1a2b3c4d5e6'
|
||||
down_revision = '43a8179cdd88'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# 13 状态中仅 'prechecking'→'matching' 更名,其余 12 个值不动。
|
||||
_OLD_MATCH_STATUSES = (
|
||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'success', 'failed', 'cancelled', 'expired',
|
||||
)
|
||||
_NEW_MATCH_STATUSES = (
|
||||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'failed', 'cancelled', 'expired',
|
||||
)
|
||||
_OLD_ITEM_STATUSES = (
|
||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
|
||||
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
|
||||
)
|
||||
_NEW_ITEM_STATUSES = (
|
||||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
|
||||
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
|
||||
)
|
||||
_OLD_RUN_STATUSES = (
|
||||
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
_NEW_RUN_STATUSES = (
|
||||
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
_OLD_SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
_NEW_SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
_OLD_ATTEMPT_KINDS = ('precheck', 'rpa', 'external_query', 'external_write')
|
||||
_NEW_ATTEMPT_KINDS = ('match', 'rpa', 'external_query', 'external_write')
|
||||
|
||||
|
||||
def _repr_list(values) -> str:
|
||||
return ', '.join(repr(v) for v in values)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""表改名 → drop 旧约束 → 刷枚举值 → 列改名 → 建新约束/索引。"""
|
||||
# [STEP 1] 表改名(RENAME 保留旧索引与约束名,需后续逐一替换)。
|
||||
op.rename_table('transfer_prechecks', 'transfer_matchings')
|
||||
|
||||
# [STEP 2] drop 旧名索引(独立 DDL,PG/SQLite 均支持)。
|
||||
op.drop_index('ix_transfer_prechecks_run_status', table_name='transfer_matchings')
|
||||
op.drop_index('ix_transfer_prechecks_business_date', table_name='transfer_matchings')
|
||||
|
||||
# [STEP 3] drop 旧名约束(引用旧列名的约束必须先删,列改名后再按新名重建)。
|
||||
with op.batch_alter_table('transfer_matchings') as batch:
|
||||
batch.drop_constraint('uq_transfer_prechecks_precheck_no', type_='unique')
|
||||
batch.drop_constraint('ck_transfer_prechecks_status', type_='check')
|
||||
with op.batch_alter_table('transfer_invoice_items') as batch:
|
||||
batch.drop_constraint('uq_transfer_invoice_items_precheck_grain', type_='unique')
|
||||
batch.drop_constraint('ck_transfer_invoice_items_status', type_='check')
|
||||
with op.batch_alter_table('transfer_runs') as batch:
|
||||
batch.drop_constraint('ck_transfer_runs_status', type_='check')
|
||||
with op.batch_alter_table('transfer_source_jobs') as batch:
|
||||
batch.drop_constraint('ck_transfer_source_jobs_status', type_='check')
|
||||
with op.batch_alter_table('transfer_attempts') as batch:
|
||||
batch.drop_constraint('ck_transfer_attempts_kind', type_='check')
|
||||
|
||||
# [STEP 4] 历史行数据刷写(先 UPDATE 再建新 CHECK,避免刷写被旧值列表拦截)。
|
||||
op.execute("UPDATE transfer_matchings SET status = 'matching' WHERE status = 'prechecking'")
|
||||
op.execute("UPDATE transfer_runs SET status = 'matching' WHERE status = 'prechecking'")
|
||||
op.execute("UPDATE transfer_source_jobs SET status = 'matching' WHERE status = 'prechecking'")
|
||||
op.execute("UPDATE transfer_invoice_items SET status = 'matching' WHERE status = 'prechecking'")
|
||||
op.execute("UPDATE transfer_attempts SET kind = 'match' WHERE kind = 'precheck'")
|
||||
|
||||
# [STEP 5] 列改名与默认值(batch 兼容 SQLite;PG 渲染为 ALTER COLUMN RENAME/SET DEFAULT)。
|
||||
with op.batch_alter_table('transfer_matchings') as batch:
|
||||
batch.alter_column('precheck_no', new_column_name='matching_no', existing_type=sa.String(length=64))
|
||||
batch.alter_column('precheck_hash', new_column_name='matching_hash', existing_type=sa.String(length=128))
|
||||
batch.alter_column(
|
||||
'status', existing_type=sa.String(length=32),
|
||||
server_default='matching', existing_server_default='prechecking',
|
||||
)
|
||||
with op.batch_alter_table('transfer_invoice_items') as batch:
|
||||
batch.alter_column('precheck_id', new_column_name='matching_id', existing_type=sa.Integer())
|
||||
with op.batch_alter_table('transfer_audit_events') as batch:
|
||||
batch.alter_column('precheck_no', new_column_name='matching_no', existing_type=sa.String(length=64))
|
||||
|
||||
# [STEP 6] 按新名重建约束(值列表换 'matching'/'match')。
|
||||
with op.batch_alter_table('transfer_matchings') as batch:
|
||||
batch.create_unique_constraint(
|
||||
'uq_transfer_matchings_matching_no', ['matching_no'],
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_matchings_status',
|
||||
f"status IN ({_repr_list(_NEW_MATCH_STATUSES)})",
|
||||
)
|
||||
with op.batch_alter_table('transfer_invoice_items') as batch:
|
||||
batch.create_unique_constraint(
|
||||
'uq_transfer_invoice_items_matching_grain',
|
||||
['matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date'],
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_invoice_items_status',
|
||||
f"status IN ({_repr_list(_NEW_ITEM_STATUSES)})",
|
||||
)
|
||||
with op.batch_alter_table('transfer_runs') as batch:
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_runs_status',
|
||||
f"status IN ({_repr_list(_NEW_RUN_STATUSES)})",
|
||||
)
|
||||
with op.batch_alter_table('transfer_source_jobs') as batch:
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_source_jobs_status',
|
||||
f"status IN ({_repr_list(_NEW_SOURCE_JOB_STATUSES)})",
|
||||
)
|
||||
with op.batch_alter_table('transfer_attempts') as batch:
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_attempts_kind',
|
||||
f"kind IN ({_repr_list(_NEW_ATTEMPT_KINDS)})",
|
||||
)
|
||||
|
||||
# [STEP 7] 按新名重建索引。
|
||||
op.create_index(
|
||||
'ix_transfer_matchings_run_status', 'transfer_matchings', ['run_id', 'status'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_transfer_matchings_business_date', 'transfer_matchings', ['business_date'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""对称回滚:drop 新约束/索引 → 刷回旧枚举值 → 列改回 → 旧约束/索引回补 → 表名还原。"""
|
||||
# [STEP 1] drop 新名索引。
|
||||
op.drop_index('ix_transfer_matchings_run_status', table_name='transfer_matchings')
|
||||
op.drop_index('ix_transfer_matchings_business_date', table_name='transfer_matchings')
|
||||
|
||||
# [STEP 2] drop 新名约束。
|
||||
with op.batch_alter_table('transfer_matchings') as batch:
|
||||
batch.drop_constraint('uq_transfer_matchings_matching_no', type_='unique')
|
||||
batch.drop_constraint('ck_transfer_matchings_status', type_='check')
|
||||
with op.batch_alter_table('transfer_invoice_items') as batch:
|
||||
batch.drop_constraint('uq_transfer_invoice_items_matching_grain', type_='unique')
|
||||
batch.drop_constraint('ck_transfer_invoice_items_status', type_='check')
|
||||
with op.batch_alter_table('transfer_runs') as batch:
|
||||
batch.drop_constraint('ck_transfer_runs_status', type_='check')
|
||||
with op.batch_alter_table('transfer_source_jobs') as batch:
|
||||
batch.drop_constraint('ck_transfer_source_jobs_status', type_='check')
|
||||
with op.batch_alter_table('transfer_attempts') as batch:
|
||||
batch.drop_constraint('ck_transfer_attempts_kind', type_='check')
|
||||
|
||||
# [STEP 3] 枚举值还原(旧 CHECK 尚未重建,可安全刷写)。
|
||||
op.execute("UPDATE transfer_matchings SET status = 'prechecking' WHERE status = 'matching'")
|
||||
op.execute("UPDATE transfer_runs SET status = 'prechecking' WHERE status = 'matching'")
|
||||
op.execute("UPDATE transfer_source_jobs SET status = 'prechecking' WHERE status = 'matching'")
|
||||
op.execute("UPDATE transfer_invoice_items SET status = 'prechecking' WHERE status = 'matching'")
|
||||
op.execute("UPDATE transfer_attempts SET kind = 'precheck' WHERE kind = 'match'")
|
||||
|
||||
# [STEP 4] 列名与默认值还原。
|
||||
with op.batch_alter_table('transfer_matchings') as batch:
|
||||
batch.alter_column('matching_no', new_column_name='precheck_no', existing_type=sa.String(length=64))
|
||||
batch.alter_column('matching_hash', new_column_name='precheck_hash', existing_type=sa.String(length=128))
|
||||
batch.alter_column(
|
||||
'status', existing_type=sa.String(length=32),
|
||||
server_default='prechecking', existing_server_default='matching',
|
||||
)
|
||||
with op.batch_alter_table('transfer_invoice_items') as batch:
|
||||
batch.alter_column('matching_id', new_column_name='precheck_id', existing_type=sa.Integer())
|
||||
with op.batch_alter_table('transfer_audit_events') as batch:
|
||||
batch.alter_column('matching_no', new_column_name='precheck_no', existing_type=sa.String(length=64))
|
||||
|
||||
# [STEP 5] 旧名约束回补(旧值列表含 'prechecking'/'precheck')。
|
||||
with op.batch_alter_table('transfer_matchings') as batch:
|
||||
batch.create_unique_constraint(
|
||||
'uq_transfer_prechecks_precheck_no', ['precheck_no'],
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_prechecks_status',
|
||||
f"status IN ({_repr_list(_OLD_MATCH_STATUSES)})",
|
||||
)
|
||||
with op.batch_alter_table('transfer_invoice_items') as batch:
|
||||
batch.create_unique_constraint(
|
||||
'uq_transfer_invoice_items_precheck_grain',
|
||||
['precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date'],
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_invoice_items_status',
|
||||
f"status IN ({_repr_list(_OLD_ITEM_STATUSES)})",
|
||||
)
|
||||
with op.batch_alter_table('transfer_runs') as batch:
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_runs_status',
|
||||
f"status IN ({_repr_list(_OLD_RUN_STATUSES)})",
|
||||
)
|
||||
with op.batch_alter_table('transfer_source_jobs') as batch:
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_source_jobs_status',
|
||||
f"status IN ({_repr_list(_OLD_SOURCE_JOB_STATUSES)})",
|
||||
)
|
||||
with op.batch_alter_table('transfer_attempts') as batch:
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_attempts_kind',
|
||||
f"kind IN ({_repr_list(_OLD_ATTEMPT_KINDS)})",
|
||||
)
|
||||
|
||||
# [STEP 6] 旧名索引回补。
|
||||
op.create_index(
|
||||
'ix_transfer_prechecks_run_status', 'transfer_matchings', ['run_id', 'status'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_transfer_prechecks_business_date', 'transfer_matchings', ['business_date'],
|
||||
)
|
||||
|
||||
# [STEP 7] 表名还原。
|
||||
op.rename_table('transfer_matchings', 'transfer_prechecks')
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨预检 API 契约测试(L2,Flask test client)。
|
||||
"""在途调拨匹配 API 契约测试(L2,Flask test client)。
|
||||
|
||||
用途:验证 POST /prechecks 创建(含 envelope/权限/参数校验)与
|
||||
GET /prechecks/{id} 进度恢复;无权限 403、未认证 401。
|
||||
用途:验证 POST /matchings 创建(含 envelope/权限/参数校验)与
|
||||
GET /matchings/{id} 进度恢复;无权限 403、未认证 401。
|
||||
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。
|
||||
逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或
|
||||
in_transit_transfer Agent 授权校验。
|
||||
@@ -27,11 +27,19 @@ def _jwt_headers(user: User) -> dict:
|
||||
|
||||
@pytest.fixture
|
||||
def transfer_deps(monkeypatch, dbs_ready_file):
|
||||
"""注入 Fake 预检依赖,并预置可执行库存。"""
|
||||
"""注入 Fake 匹配依赖,预置可执行库存,并把执行文件对账投影替换为 ready(sha=夹具 checksum)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
def _resolve(*, source_code: str) -> dict:
|
||||
# 执行门禁③(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。
|
||||
return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.execution_service.resolve_source_file_status", _resolve,
|
||||
)
|
||||
return deps
|
||||
|
||||
|
||||
@@ -87,9 +95,9 @@ def unauthorized_headers(app):
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_headers, transfer_deps):
|
||||
"""POST /prechecks → 201 envelope,data 含 precheck_id/hash/计数。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
def test_create_matching_returns_envelope_with_matching_id(app, client, admin_headers, transfer_deps):
|
||||
"""POST /matchings → 201 envelope,data 含 matching_id/hash/计数。"""
|
||||
response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
})
|
||||
@@ -97,48 +105,48 @@ def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_he
|
||||
body = response.get_json()
|
||||
assert body["success"] is True
|
||||
data = body["data"]
|
||||
assert data["precheck_id"].startswith("TPC-")
|
||||
assert data["precheck_hash"].startswith("sha256:")
|
||||
assert data["matching_id"].startswith("MTG-")
|
||||
assert data["matching_hash"].startswith("sha256:")
|
||||
assert data["estimated_external_write_count"] == 2
|
||||
assert body.get("request_id")
|
||||
|
||||
|
||||
def test_create_precheck_requires_authentication(client):
|
||||
def test_create_matching_requires_authentication(client):
|
||||
"""未认证 → 401(envelope error)。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", json={"source_codes": ["DBS-AWSBI"]})
|
||||
response = client.post(f"{API_PREFIX}/matchings", json={"source_codes": ["DBS-AWSBI"]})
|
||||
assert response.status_code == 401
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_create_precheck_forbidden_without_agent_permission(client, unauthorized_headers):
|
||||
def test_create_matching_forbidden_without_agent_permission(client, unauthorized_headers):
|
||||
"""无 in_transit_transfer Agent 权限 → 403。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=unauthorized_headers, json={
|
||||
response = client.post(f"{API_PREFIX}/matchings", headers=unauthorized_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
})
|
||||
assert response.status_code == 403
|
||||
assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN"
|
||||
|
||||
|
||||
def test_create_precheck_warehouse_manager_allowed(app, client, warehouse_headers, transfer_deps):
|
||||
"""持有 Agent 权限的仓库管理员可创建预检。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=warehouse_headers, json={
|
||||
def test_create_matching_warehouse_manager_allowed(app, client, warehouse_headers, transfer_deps):
|
||||
"""持有 Agent 权限的仓库管理员可创建匹配。"""
|
||||
response = client.post(f"{API_PREFIX}/matchings", headers=warehouse_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
})
|
||||
assert response.status_code == 201
|
||||
assert response.get_json()["data"]["precheck_id"]
|
||||
assert response.get_json()["data"]["matching_id"]
|
||||
|
||||
|
||||
def test_create_precheck_validates_source_codes(app, client, admin_headers, transfer_deps):
|
||||
def test_create_matching_validates_source_codes(app, client, admin_headers, transfer_deps):
|
||||
"""缺少 source_codes → 400 参数错误。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={"business_date": "2026-08-06"})
|
||||
response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={"business_date": "2026-08-06"})
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_create_precheck_accepts_transfer_type_and_rejects_placeholder(app, client, admin_headers, transfer_deps):
|
||||
def test_create_matching_accepts_transfer_type_and_rejects_placeholder(app, client, admin_headers, transfer_deps):
|
||||
"""transfer_type 合法值放行;占位类型(类型2/3)与非法值 → 400 fail-closed。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
"transfer_type": "in_transit_to_hub",
|
||||
@@ -146,7 +154,7 @@ def test_create_precheck_accepts_transfer_type_and_rejects_placeholder(app, clie
|
||||
assert created.status_code == 201
|
||||
|
||||
for bad_type in ("hub_repair_out", "hub_to_hub", "bogus_type"):
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
"transfer_type": bad_type,
|
||||
@@ -155,36 +163,88 @@ def test_create_precheck_accepts_transfer_type_and_rejects_placeholder(app, clie
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_restore_precheck_progress(app, client, admin_headers, transfer_deps):
|
||||
"""GET /prechecks/{id} 恢复预检进度(Hash/明细一致)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
def test_restore_matching_progress(app, client, admin_headers, transfer_deps):
|
||||
"""GET /matchings/{id} 恢复匹配进度(Hash/明细一致)。"""
|
||||
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
restored = client.get(f"{API_PREFIX}/prechecks/{created['precheck_id']}", headers=admin_headers)
|
||||
restored = client.get(f"{API_PREFIX}/matchings/{created['matching_id']}", headers=admin_headers)
|
||||
assert restored.status_code == 200
|
||||
body = restored.get_json()["data"]
|
||||
assert body["summary"]["precheck_hash"] == created["precheck_hash"]
|
||||
assert body["summary"]["matching_hash"] == created["matching_hash"]
|
||||
assert {item["invoice_no"] for item in body["items"]} == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps):
|
||||
"""未知 precheck → 404。"""
|
||||
response = client.get(f"{API_PREFIX}/prechecks/TPC-NOT-EXIST", headers=admin_headers)
|
||||
def test_restore_unknown_matching_404(app, client, admin_headers, transfer_deps):
|
||||
"""未知 matching → 404。"""
|
||||
response = client.get(f"{API_PREFIX}/matchings/MTG-NOT-EXIST", headers=admin_headers)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps):
|
||||
"""执行预检 → 201 run_no;GET run 返回 外部系统 单号聚合结果。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
def test_executable_items_lists_ready_rows_with_decoration(
|
||||
app, client, admin_headers, transfer_deps, monkeypatch
|
||||
):
|
||||
"""可调拨明细:只返回全局 ready 行,行带 item_id/checked_at/stale/file_current。"""
|
||||
# 行装饰的文件对账在 matching_service 命名空间——与执行门禁③同口径替身。
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||
lambda *, source_code: {"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": "REC-TEST", "file_sha256": "d" * 64},
|
||||
)
|
||||
_create_matching(client, admin_headers)
|
||||
response = client.get(f"{API_PREFIX}/items/executable", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()["data"]
|
||||
assert body["counts"]["executable_count"] == 2
|
||||
assert {item["invoice_no"] for item in body["items"]} == {"HOM-001", "HOX-002"}
|
||||
for item in body["items"]:
|
||||
assert item["item_id"] > 0
|
||||
assert item["stale"] is False
|
||||
assert item["file_current"] is True
|
||||
assert item["checked_at"]
|
||||
|
||||
|
||||
def test_executable_items_requires_authentication(client):
|
||||
"""未认证 → 401(与模块其余端点同口径)。"""
|
||||
assert client.get(f"{API_PREFIX}/items/executable").status_code == 401
|
||||
|
||||
|
||||
def _create_matching(client, admin_headers) -> str:
|
||||
"""创建匹配并返回 matching_no。"""
|
||||
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
assert executed.status_code == 201
|
||||
})
|
||||
assert created.status_code == 201
|
||||
return created.get_json()["data"]["matching_id"]
|
||||
|
||||
|
||||
def _ready_item_ids(app) -> list[int]:
|
||||
"""按行执行入参:ready_to_execute 行的真实 item_id(restore 视图同源)。"""
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
rows = (
|
||||
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
|
||||
.order_by(TransferInvoiceItem.id)
|
||||
.all()
|
||||
)
|
||||
return [row.id for row in rows]
|
||||
|
||||
|
||||
def _execute_ready_items(app, client, admin_headers, item_ids=None):
|
||||
"""POST /items/execute 执行 ready 行(缺省全部)。"""
|
||||
ids = _ready_item_ids(app) if item_ids is None else item_ids
|
||||
return client.post(f"{API_PREFIX}/items/execute", headers=admin_headers, json={"item_ids": ids})
|
||||
|
||||
|
||||
def test_execute_items_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps):
|
||||
"""按行执行 → 200 run_no;GET run 返回 外部系统 单号聚合结果。"""
|
||||
_create_matching(client, admin_headers)
|
||||
executed = _execute_ready_items(app, client, admin_headers)
|
||||
assert executed.status_code == 200
|
||||
assert executed.get_json()["success"] is True
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
assert run_no.startswith("RUN-")
|
||||
|
||||
@@ -195,36 +255,27 @@ def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_
|
||||
assert result["exceptions"] == []
|
||||
|
||||
|
||||
def test_execute_unconfirmed_precheck_rejected(app, client, admin_headers, transfer_deps):
|
||||
"""预检未就绪时执行 → 400 领域错误,不产生 Run。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
with app.app_context():
|
||||
from app.models import TransferPrecheck
|
||||
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=created["precheck_id"]).first()
|
||||
precheck.status = "prechecking"
|
||||
db.session.commit()
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001"]},
|
||||
)
|
||||
def test_execute_items_rejects_invalid_ids(app, client, admin_headers, transfer_deps):
|
||||
"""门禁①:不存在/非可执行行 → 400 EXECUTE_ITEMS_INVALID(details 列出 id),不产生 Run。"""
|
||||
_create_matching(client, admin_headers)
|
||||
response = _execute_ready_items(app, client, admin_headers, item_ids=[99999])
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
body = response.get_json()
|
||||
assert body["error"]["code"] == "TRANSFER.EXECUTE_ITEMS_INVALID"
|
||||
assert body["error"]["details"]["invalid_item_ids"] == [99999]
|
||||
|
||||
|
||||
def test_execute_items_requires_item_ids(app, client, admin_headers, transfer_deps):
|
||||
"""缺少 item_ids → 400 参数错误(复用批量操作校验)。"""
|
||||
response = client.post(f"{API_PREFIX}/items/execute", headers=admin_headers, json={})
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_cancel_run_requires_reason(app, client, admin_headers, transfer_deps):
|
||||
"""取消缺少原因 → 400。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={},
|
||||
)
|
||||
_create_matching(client, admin_headers)
|
||||
executed = _execute_ready_items(app, client, admin_headers)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={"reason": ""})
|
||||
assert response.status_code == 400
|
||||
@@ -232,14 +283,8 @@ def test_cancel_run_requires_reason(app, client, admin_headers, transfer_deps):
|
||||
|
||||
def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transfer_deps):
|
||||
"""取消未开始项并保留成功单据。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
_create_matching(client, admin_headers)
|
||||
executed = _execute_ready_items(app, client, admin_headers)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
# 模拟执行中状态:Run 回退 executing,INV-002 尚未开始
|
||||
with app.app_context():
|
||||
@@ -260,7 +305,7 @@ def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transf
|
||||
|
||||
def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_deps):
|
||||
"""人工关闭缺少原因 → 400。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
@@ -278,7 +323,7 @@ def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_
|
||||
|
||||
def test_manual_close_item_success(app, client, admin_headers, transfer_deps):
|
||||
"""人工关闭成功 → 状态 manually_closed。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
@@ -299,14 +344,8 @@ def test_manual_close_item_success(app, client, admin_headers, transfer_deps):
|
||||
|
||||
def test_exceptions_excel_download(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载异常 Excel → 200 xlsx,且记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
_create_matching(client, admin_headers)
|
||||
executed = _execute_ready_items(app, client, admin_headers)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
@@ -321,14 +360,8 @@ def test_exceptions_excel_download(app, transfer_db, client, admin_headers, tran
|
||||
|
||||
def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载收料来源文件 → 200(zip),记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
_create_matching(client, admin_headers)
|
||||
executed = _execute_ready_items(app, client, admin_headers)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
@@ -341,15 +374,9 @@ def test_receipt_files_download_records_access_audit(app, transfer_db, client, a
|
||||
|
||||
|
||||
def test_erp_inventory_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载预检冻结的 外部系统 库存表 → 200(csv),记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
"""下载匹配冻结的 外部系统 库存表 → 200(csv),记录访问审计。"""
|
||||
_create_matching(client, admin_headers)
|
||||
executed = _execute_ready_items(app, client, admin_headers)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/external-inventory", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
@@ -364,14 +391,8 @@ def test_erp_inventory_download_records_access_audit(app, transfer_db, client, a
|
||||
|
||||
def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_headers, unauthorized_headers, transfer_deps):
|
||||
"""无权限下载 → 403(越权检查)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={},
|
||||
)
|
||||
_create_matching(client, admin_headers)
|
||||
executed = _execute_ready_items(app, client, admin_headers)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files",
|
||||
f"{API_PREFIX}/runs/{run_no}/external-inventory",
|
||||
@@ -380,34 +401,23 @@ def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_
|
||||
assert response.status_code == 403, path
|
||||
|
||||
|
||||
def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""前端伪造来源仓/目标仓/数量 → 服务端忽略,使用冻结快照值(防篡改)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={
|
||||
"invoice_nos": ["HOM-001"],
|
||||
"from_warehouse": "FAKE-TRANSIT",
|
||||
"to_warehouse": "FAKE-HUB",
|
||||
"quantity": "1",
|
||||
},
|
||||
)
|
||||
assert executed.status_code == 201
|
||||
def test_execute_items_uses_frozen_snapshot_values(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""按行执行只接受 item_ids:来源仓/目标仓/数量一律取服务端冻结快照值(防篡改)。"""
|
||||
_create_matching(client, admin_headers)
|
||||
executed = _execute_ready_items(app, client, admin_headers, item_ids=_ready_item_ids(app)[:1])
|
||||
assert executed.status_code == 200
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers).get_json()["data"]
|
||||
documents = run["result"]["external_documents"]
|
||||
assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非伪造值
|
||||
assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非前端可指定值
|
||||
assert documents[0]["to_warehouse"] == "HUB-CN01"
|
||||
assert documents[0]["total_quantity"] == "1200"
|
||||
|
||||
|
||||
def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""待处理异常列表/汇总 API:收纳 blocked 项、排除 success、含老化等级。"""
|
||||
# 预检含 1 个数量不一致(blocked)项
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
# 匹配含 1 个数量不一致(blocked)项
|
||||
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
@@ -468,7 +478,7 @@ def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps
|
||||
|
||||
|
||||
def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch, dbs_ready_file):
|
||||
"""POST /prechecks/{no}/items/requery → 200 envelope,逐票返回重查结果。
|
||||
"""POST /matchings/{no}/items/requery → 200 envelope,逐票返回重查结果。
|
||||
|
||||
[断言意图] 回归防线(2026-09-21):该端点曾引用未定义的 _actor_id 导致
|
||||
500/SYSTEM.INTERNAL_ERROR;本用例锁定端点在真实鉴权链路下可完整执行,
|
||||
@@ -479,14 +489,14 @@ def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch,
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
})
|
||||
precheck_no = created.get_json()["data"]["precheck_id"]
|
||||
matching_no = created.get_json()["data"]["matching_id"]
|
||||
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/prechecks/{precheck_no}/items/requery",
|
||||
f"{API_PREFIX}/matchings/{matching_no}/items/requery",
|
||||
headers=admin_headers,
|
||||
json={"invoice_nos": ["HOM-001"]},
|
||||
)
|
||||
@@ -494,7 +504,7 @@ def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch,
|
||||
body = response.get_json()
|
||||
assert body["success"] is True
|
||||
data = body["data"]
|
||||
assert data["precheck_no"] == precheck_no
|
||||
assert data["matching_no"] == matching_no
|
||||
assert data["total"] == 1
|
||||
result = data["results"][0]
|
||||
assert result["invoice_no"] == "HOM-001"
|
||||
|
||||
@@ -689,7 +689,7 @@ def dbs_ready_file() -> dict:
|
||||
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。
|
||||
|
||||
rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date),
|
||||
与真实仓库 movement_file_repository 产出一致(B5 接线后 run_precheck 按
|
||||
与真实仓库 movement_file_repository 产出一致(B5 接线后 run_matching 按
|
||||
parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。
|
||||
"""
|
||||
return {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨预检 Job Handler 测试(L1)。
|
||||
"""在途调拨匹配 Job Handler 测试(L1)。
|
||||
|
||||
用途:验证 in_transit_transfer_precheck JobType 已注册、handler 能驱动
|
||||
precheck_service 落库更新预检状态;缺失 precheck 时报错。
|
||||
用途:验证 in_transit_transfer_match JobType 已注册、handler 能驱动
|
||||
matching_service 落库更新匹配状态;缺失 matching 时报错。
|
||||
依赖:app fixture、transfer_db、fakes/repo_fakes、jobs.handlers。
|
||||
逻辑:直接调用 handler 函数(不经过 Worker 队列),payload 携带 precheck_id。
|
||||
逻辑:直接调用 handler 函数(不经过 Worker 队列),payload 携带 matching_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,47 +14,55 @@ import pytest
|
||||
from app import db
|
||||
from app.jobs.registry import get_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def transfer_deps(monkeypatch, dbs_ready_file):
|
||||
"""注入 Fake 依赖并预置库存。"""
|
||||
"""注入 Fake 依赖并预置库存;同时把执行文件对账投影替换为 ready(sha=夹具 checksum)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
def _resolve(*, source_code: str) -> dict:
|
||||
# 执行门禁③(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。
|
||||
return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.execution_service.resolve_source_file_status", _resolve,
|
||||
)
|
||||
return deps
|
||||
|
||||
|
||||
def test_precheck_job_type_registered():
|
||||
"""in_transit_transfer_precheck handler 必须注册于 JobType 注册表。"""
|
||||
handler = get_handler(JobType.TRANSFER_PRECHECK)
|
||||
def test_matching_job_type_registered():
|
||||
"""in_transit_transfer_match handler 必须注册于 JobType 注册表。"""
|
||||
handler = get_handler(JobType.TRANSFER_MATCH)
|
||||
assert handler is not None
|
||||
|
||||
|
||||
def test_precheck_job_handler_runs_and_updates_precheck(transfer_db, dbs_ready_file, transfer_deps):
|
||||
"""handler 执行后预检状态进入 ready_to_execute,明细落库。"""
|
||||
summary = create_precheck(
|
||||
def test_matching_job_handler_runs_and_updates_matching(transfer_db, dbs_ready_file, transfer_deps):
|
||||
"""handler 执行后匹配状态进入 ready_to_execute,明细落库。"""
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
|
||||
)
|
||||
handler = get_handler(JobType.TRANSFER_PRECHECK)
|
||||
handler(None, {"precheck_id": summary.precheck_id})
|
||||
handler = get_handler(JobType.TRANSFER_MATCH)
|
||||
handler(None, {"matching_id": summary.matching_id})
|
||||
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
assert precheck is not None
|
||||
assert precheck.status == "ready_to_execute"
|
||||
assert precheck.precheck_hash.startswith("sha256:")
|
||||
assert len(precheck.items) == 2
|
||||
matching = db.session.query(TransferMatching).filter_by(matching_no=summary.matching_id).first()
|
||||
assert matching is not None
|
||||
assert matching.status == "ready_to_execute"
|
||||
assert matching.matching_hash.startswith("sha256:")
|
||||
assert len(matching.items) == 2
|
||||
|
||||
|
||||
def test_precheck_job_handler_missing_precheck_raises(transfer_db):
|
||||
"""缺失 precheck_id → handler 抛 RuntimeError(fail-closed)。"""
|
||||
handler = get_handler(JobType.TRANSFER_PRECHECK)
|
||||
def test_matching_job_handler_missing_matching_raises(transfer_db):
|
||||
"""缺失 matching_id → handler 抛 RuntimeError(fail-closed)。"""
|
||||
handler = get_handler(JobType.TRANSFER_MATCH)
|
||||
with pytest.raises(RuntimeError):
|
||||
handler(None, {"precheck_id": "TPC-NOT-EXIST"})
|
||||
handler(None, {"matching_id": "MTG-NOT-EXIST"})
|
||||
|
||||
|
||||
def test_run_and_item_job_types_registered():
|
||||
@@ -63,18 +71,18 @@ def test_run_and_item_job_types_registered():
|
||||
assert get_handler(JobType.TRANSFER_ITEM) is not None
|
||||
|
||||
|
||||
def test_run_job_handler_executes_precheck(transfer_db, dbs_ready_file, transfer_deps):
|
||||
"""run handler 执行预检并创建成功 Run。"""
|
||||
summary = create_precheck(
|
||||
def test_run_job_handler_executes_matching(transfer_db, dbs_ready_file, transfer_deps):
|
||||
"""run handler 执行匹配并创建成功 Run。"""
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
|
||||
)
|
||||
handler = get_handler(JobType.TRANSFER_RUN)
|
||||
handler(None, {"precheck_id": summary.precheck_id})
|
||||
handler(None, {"matching_id": summary.matching_id})
|
||||
|
||||
from app.models import TransferRun as RunModel
|
||||
|
||||
run = db.session.query(RunModel).filter(
|
||||
RunModel.status != "prechecking",
|
||||
RunModel.status != "matching",
|
||||
).order_by(RunModel.id.desc()).first()
|
||||
assert run is not None
|
||||
assert run.status == "success"
|
||||
@@ -82,13 +90,17 @@ def test_run_job_handler_executes_precheck(transfer_db, dbs_ready_file, transfer
|
||||
|
||||
def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, transfer_deps):
|
||||
"""item handler 执行单个 Invoice 写入并置 success。"""
|
||||
summary = create_precheck(
|
||||
create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
|
||||
)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run_for_items
|
||||
|
||||
create_execution_run(precheck, deps=transfer_deps, actor_id=None)
|
||||
ready_items = (
|
||||
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
|
||||
.order_by(TransferInvoiceItem.id)
|
||||
.all()
|
||||
)
|
||||
create_execution_run_for_items(ready_items, deps=transfer_deps, actor_id=None)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(
|
||||
invoice_no="HOM-001",
|
||||
).first()
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""在途调拨性能与规模测试(Phase 4,L6 子集)。
|
||||
|
||||
用途:验证大批量 Invoice 预检可完成且不退化(O(n) 汇总),投影读取正常。
|
||||
依赖:transfer_db、precheck_service、repo_fakes。
|
||||
逻辑:300 行收料文件 → 预检 300 个 Invoice;仅断言正确性,耗时打印参考。
|
||||
用途:验证大批量 Invoice 匹配可完成且不退化(O(n) 汇总),投影读取正常。
|
||||
依赖:transfer_db、matching_service、repo_fakes。
|
||||
逻辑:300 行收料文件 → 匹配 300 个 Invoice;仅断言正确性,耗时打印参考。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,7 +11,7 @@ import time
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
|
||||
from app.services.in_transit_transfer.matching_service import create_matching, restore_matching
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
@@ -38,18 +38,18 @@ def _bulk_file(count: int) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def test_bulk_precheck_300_invoices(transfer_db):
|
||||
"""300 Invoice 预检完成且数量正确;耗时打印参考(不设脆断言)。"""
|
||||
def test_bulk_matching_300_invoices(transfer_db):
|
||||
"""300 Invoice 匹配完成且数量正确;耗时打印参考(不设脆断言)。"""
|
||||
deps, erp, _ = make_transfer_deps(_bulk_file(300))
|
||||
for index in range(1, 301):
|
||||
# 库存种子按 (料号, 拨出库位, 拨出批号) 三元组与文件行一一对应。
|
||||
erp.seed_stock(f"MAT-{index:04d}", "DBS-TRANSIT", f"LOT-BULK-{index:04d}", "100")
|
||||
|
||||
started = time.perf_counter()
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
elapsed = time.perf_counter() - started
|
||||
assert summary.counts.executable_count == 300
|
||||
assert summary.counts.file_invoice_count == 300
|
||||
restored = restore_precheck(summary.precheck_id)
|
||||
restored = restore_matching(summary.matching_id)
|
||||
assert len(restored["items"]) == 300
|
||||
print(f"\n[perf] bulk precheck 300 invoices: {elapsed:.3f}s")
|
||||
print(f"\n[perf] bulk matching 300 invoices: {elapsed:.3f}s")
|
||||
@@ -37,3 +37,36 @@ def rpa_fake() -> FakeRPA:
|
||||
def wecom_fake() -> FakeWeCom:
|
||||
"""FakeWeCom:记录投递事实,可注入附件失败。"""
|
||||
return FakeWeCom()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def patch_source_file_status(monkeypatch):
|
||||
"""执行文件对账门禁替身工厂:替换 execution_service 的来源文件状态投影。
|
||||
|
||||
用途:execute_items 门禁③按去重来源调 resolve_source_file_status(真实查询
|
||||
收料文件表);单元测试注入替身避免触碰表数据。缺省全部来源投影为
|
||||
ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file 行版本戳同源)。
|
||||
|
||||
Args:
|
||||
mapping: source_code → sha 映射;值为 None 表示该来源无可用文件
|
||||
(file_status=none,触发 FILE_CHANGED);未列出的来源回落 ready/"d"*64。
|
||||
"""
|
||||
READY_SHA = "d" * 64
|
||||
|
||||
def _patch(mapping: dict[str, str | None] | None = None) -> None:
|
||||
table = mapping or {}
|
||||
|
||||
def _resolve(*, source_code: str) -> dict:
|
||||
if source_code in table:
|
||||
sha = table[source_code]
|
||||
if sha is None:
|
||||
return {"file_status": "none", "has_ready_file": False, "file_no": None, "file_sha256": None}
|
||||
return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": sha}
|
||||
return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": READY_SHA}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.execution_service.resolve_source_file_status",
|
||||
_resolve,
|
||||
)
|
||||
|
||||
return _patch
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨测试的仓库/路由/依赖替身。
|
||||
|
||||
用途:为 file_preparation / precheck_service / API / Job 测试提供可注入的
|
||||
用途:为 file_preparation / matching_service / API / Job 测试提供可注入的
|
||||
ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps。
|
||||
依赖:app.services.in_transit_transfer(仅类型)、fakes。
|
||||
逻辑:所有替身只返回测试注入的值,不触碰真实存储;
|
||||
@@ -10,7 +10,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.precheck_service import RouteMapping, TransferDeps
|
||||
from app.services.in_transit_transfer.matching_service import RouteMapping, TransferDeps
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ class FakeRouteResolver:
|
||||
raise RuntimeError("route resolution failed")
|
||||
mapping = self.routes.get(source_code)
|
||||
if mapping is None:
|
||||
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError
|
||||
from app.services.in_transit_transfer.matching_service import RouteNotResolvedError
|
||||
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
return mapping
|
||||
@@ -51,7 +51,7 @@ def test_archive_snapshot_persists_index_and_audit(transfer_db):
|
||||
data = _sample_data()
|
||||
archive = archive_snapshot(
|
||||
object_type="external_inventory_snapshot",
|
||||
object_id="TPC-20260806-001",
|
||||
object_id="MTG-20260806-001",
|
||||
data=data,
|
||||
original_filename="external-inventory-20260806.csv",
|
||||
content_type="text/csv",
|
||||
@@ -64,7 +64,7 @@ def test_archive_snapshot_persists_index_and_audit(transfer_db):
|
||||
assert store.objects # 对象已写入存储
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ARCHIVED").first()
|
||||
assert audit is not None
|
||||
assert audit.aggregate_id == "TPC-20260806-001"
|
||||
assert audit.aggregate_id == "MTG-20260806-001"
|
||||
|
||||
|
||||
def test_verify_archive_hash_ok_and_corruption_detected(transfer_db):
|
||||
|
||||
@@ -80,7 +80,7 @@ def test_build_event_carries_actor_and_correlation_ids():
|
||||
aggregate_type="transfer_item",
|
||||
aggregate_id="item-1",
|
||||
run_no="RUN-20260806-001",
|
||||
precheck_no="TPC-20260806-001",
|
||||
matching_no="MTG-20260806-001",
|
||||
invoice_no="INV-001",
|
||||
actor_type="user",
|
||||
actor_id="u-42",
|
||||
@@ -89,7 +89,7 @@ def test_build_event_carries_actor_and_correlation_ids():
|
||||
request_id="req_001",
|
||||
operation_id="op_001",
|
||||
result="success",
|
||||
before={"status": "prechecking"},
|
||||
before={"status": "matching"},
|
||||
after={"status": "ready_to_execute"},
|
||||
)
|
||||
assert event.actor_id == "u-42"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨历史待处理池与老化测试(Phase 3,L1)。
|
||||
|
||||
用途:验证待处理池只收纳可恢复/已关闭/结果未知项,并正确计算 3/5/7 天老化等级。
|
||||
依赖:transfer_db、precheck_service、backlog_service、repo_fakes。
|
||||
依赖:transfer_db、matching_service、backlog_service、repo_fakes。
|
||||
逻辑:老化按最近一次 Attempt 或明细更新时间计算;result_unknown 单独高风险展示。
|
||||
"""
|
||||
|
||||
@@ -18,16 +18,16 @@ from app.services.in_transit_transfer.backlog_service import (
|
||||
backlog_summary,
|
||||
list_backlog,
|
||||
)
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _blocked_precheck(dbs_ready_file):
|
||||
"""构造含数量不一致(blocked)项的预检。"""
|
||||
def _blocked_matching(dbs_ready_file):
|
||||
"""构造含数量不一致(blocked)项的匹配。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # 1200 ≠ 1000 → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return summary
|
||||
|
||||
|
||||
@@ -44,16 +44,43 @@ def test_aging_level_thresholds():
|
||||
|
||||
def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file):
|
||||
"""待处理池收纳 blocked_recoverable,排除 success / not_matured。"""
|
||||
_blocked_precheck(dbs_ready_file)
|
||||
_blocked_matching(dbs_ready_file)
|
||||
items = list_backlog()
|
||||
invoice_set = {item.invoice_no for item in items}
|
||||
assert "HOM-001" in invoice_set
|
||||
assert "HOX-002" not in invoice_set
|
||||
|
||||
|
||||
def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file):
|
||||
"""排序=收料日期→Invoice→created_at,与重查触碰(updated_at 刷新)无关。
|
||||
|
||||
[断言意图] 恢复处理/重查会刷新 updated_at(行级新鲜度续期);排序键若用
|
||||
updated_at 会让正在处理的行跳位(用户实测:恢复后被处理的行跳到列表末尾)。
|
||||
业务稳定键下,触碰前后列表顺序完全一致。
|
||||
"""
|
||||
_blocked_matching(dbs_ready_file) # HOM-001(receipt 2026-08-05)与 HOX-002 不进池,构造两笔 blocked
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
# 手工造第二笔 blocked:不同收料日期、更晚创建
|
||||
second = TransferInvoiceItem(
|
||||
matching_id=item.matching_id, source_code=item.source_code,
|
||||
invoice_no="HOM-002", material_no="MAT-003", material_name="垫片",
|
||||
receipt_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found",
|
||||
)
|
||||
db.session.add(second)
|
||||
db.session.commit()
|
||||
# 用户操作模拟:重查刷新 HOM-002 的 updated_at(变得更"新")
|
||||
second.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
invoices = [dto.invoice_no for dto in list_backlog()]
|
||||
# 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-05),尽管它刚被触碰过
|
||||
assert invoices == ["HOM-002", "HOM-001"]
|
||||
|
||||
|
||||
def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file):
|
||||
"""老化等级按明细更新日期计算。"""
|
||||
_blocked_precheck(dbs_ready_file)
|
||||
_blocked_matching(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.updated_at = datetime.utcnow() - timedelta(days=6)
|
||||
db.session.commit()
|
||||
@@ -65,7 +92,7 @@ def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_backlog_summary_counts_and_aging(transfer_db, dbs_ready_file):
|
||||
"""汇总包含可恢复/已关闭/未知计数与老化分级。"""
|
||||
_blocked_precheck(dbs_ready_file)
|
||||
_blocked_matching(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "manually_closed"
|
||||
item.manually_closed_reason = "线下处理"
|
||||
@@ -73,3 +100,20 @@ def test_backlog_summary_counts_and_aging(transfer_db, dbs_ready_file):
|
||||
summary = backlog_summary()
|
||||
assert summary.closed_count == 1
|
||||
assert summary.recoverable_count == 0
|
||||
|
||||
|
||||
def test_list_backlog_exposes_result_code(transfer_db, dbs_ready_file):
|
||||
"""[断言意图] F1(2026-09-23 评审修复):backlog 行透出 result_code,
|
||||
前端待处理池才能区分 blocked_file_removed(收料行已从最新文件移除)
|
||||
并展示「文件已移除」徽标,否则与普通数量阻断无法区分。"""
|
||||
_blocked_matching(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.result_code = "blocked_file_removed"
|
||||
db.session.commit()
|
||||
items = list_backlog()
|
||||
target = next(entry for entry in items if entry.invoice_no == "HOM-001")
|
||||
assert target.result_code == "blocked_file_removed"
|
||||
assert target.status == "blocked_recoverable"
|
||||
# 未打标的结果码为 None(普通阻断行不受影响)。
|
||||
others = [entry for entry in items if entry.invoice_no != "HOM-001"]
|
||||
assert all(entry.result_code is None for entry in others)
|
||||
@@ -0,0 +1,120 @@
|
||||
"""在途调拨批量操作测试(批量重查 / 批量人工关闭,L1)。
|
||||
|
||||
用途:验证待处理池多选批量操作的按 id 直取、单行隔离、参数门禁与
|
||||
「重查即续新鲜度」(行级 updated_at 续期,执行 TTL 门禁的续期机制)。
|
||||
依赖:transfer_db、matching_service、retry_service、manual_close_service、repo_fakes。
|
||||
逻辑:批量语义 = 逐行调用既有单行服务,任何单行失败(状态不允许/不存在/异常)
|
||||
不影响其余行;id/原因缺失直接拒绝;重查后行 updated_at 必须恢复当前时刻。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_items
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from app.services.in_transit_transfer.retry_service import requery_items_by_ids
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _seed(dbs_ready_file):
|
||||
"""构造 1 阻断 + 1 可执行的匹配,返回 (deps, erp, blocked_row)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
return deps, erp, blocked
|
||||
|
||||
|
||||
def test_batch_requery_requires_item_ids():
|
||||
"""空 id 列表直接拒绝。"""
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
requery_items_by_ids(item_ids=[], deps=None)
|
||||
assert exc_info.value.code == "TRANSFER.BATCH_ITEMS_REQUIRED"
|
||||
|
||||
|
||||
def test_batch_requery_recovers_fixed_stock_and_isolates_missing(transfer_db, dbs_ready_file):
|
||||
"""库存补齐后重查转可执行;不存在的 id 单行报错不阻断。"""
|
||||
deps, erp, blocked = _seed(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # ERP 已补齐
|
||||
|
||||
result = requery_items_by_ids(item_ids=[blocked.id, 999999], deps=deps)
|
||||
|
||||
assert result["total"] == 2
|
||||
first, second = result["results"]
|
||||
assert first["ok"] is True and first["status"] == "ready_to_execute"
|
||||
assert second["ok"] is False and "not found" in second["error"]
|
||||
|
||||
|
||||
def test_batch_requery_refreshes_freshness(transfer_db, dbs_ready_file):
|
||||
"""重查即续新鲜度:updated_at 被拨回 11 分钟前(超执行 TTL)的阻断行,重查后恢复到当前时刻。"""
|
||||
deps, erp, blocked = _seed(dbs_ready_file)
|
||||
stale_at = datetime.utcnow() - timedelta(minutes=11)
|
||||
blocked.updated_at = stale_at
|
||||
db.session.commit()
|
||||
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # ERP 已补齐 → 重查
|
||||
result = requery_items_by_ids(item_ids=[blocked.id], deps=deps)
|
||||
|
||||
assert result["results"][0]["ok"] is True
|
||||
db.session.expire(blocked)
|
||||
# [断言意图] 行级 TTL 门禁的续期机制:重查后行 updated_at 必须恢复到当前
|
||||
# 时刻(大于拨回值且距 now < 1 分钟),执行门禁据此放行。
|
||||
assert blocked.updated_at > stale_at
|
||||
assert (datetime.utcnow() - blocked.updated_at).total_seconds() < 60
|
||||
|
||||
|
||||
def test_batch_requery_degrade_path_refreshes_freshness(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""降级路径(外部查询失败落 blocked)同样续新鲜度:updated_at 恢复到当前时刻。"""
|
||||
deps, erp, blocked = _seed(dbs_ready_file)
|
||||
stale_at = datetime.utcnow() - timedelta(minutes=11)
|
||||
blocked.updated_at = stale_at
|
||||
db.session.commit()
|
||||
|
||||
def _raise(**kwargs):
|
||||
raise RuntimeError("external gateway down")
|
||||
|
||||
monkeypatch.setattr(erp, "query_stock", _raise)
|
||||
result = requery_items_by_ids(item_ids=[blocked.id], deps=deps)
|
||||
|
||||
assert result["results"][0]["ok"] is True
|
||||
assert result["results"][0]["status"] == "blocked_recoverable"
|
||||
db.session.expire(blocked)
|
||||
# [断言意图] 降级也是一次真实评估:外部查询失败落回阻断时同样续期行新鲜度,
|
||||
# 保证两条重查路径(成功/降级)对执行 TTL 门禁的续期语义一致。
|
||||
assert blocked.updated_at > stale_at
|
||||
assert (datetime.utcnow() - blocked.updated_at).total_seconds() < 60
|
||||
|
||||
|
||||
def test_batch_manual_close_requires_reason(transfer_db, dbs_ready_file):
|
||||
"""原因缺失整批拒绝(沿用单行关闭的 TRANSFER_MANUAL_CLOSE_REASON_REQUIRED)。"""
|
||||
with pytest.raises(ValidationError):
|
||||
manual_close_items(item_ids=[1], reason=" ")
|
||||
|
||||
|
||||
def test_batch_manual_close_requires_item_ids(transfer_db, dbs_ready_file):
|
||||
"""空 id 列表直接拒绝。"""
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
manual_close_items(item_ids=[], reason="线下处理")
|
||||
assert exc_info.value.code == "TRANSFER.BATCH_ITEMS_REQUIRED"
|
||||
|
||||
|
||||
def test_batch_manual_close_closes_and_isolates(transfer_db, dbs_ready_file):
|
||||
"""可关闭行成功关闭;终态行(已执行)单行报错不阻断。"""
|
||||
deps, _erp, blocked = _seed(dbs_ready_file)
|
||||
success_row = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
|
||||
success_row.status = "success" # 终态:不可关闭
|
||||
db.session.commit()
|
||||
|
||||
result = manual_close_items(item_ids=[blocked.id, success_row.id], reason="线下处理")
|
||||
|
||||
assert result["total"] == 2
|
||||
by_id = {entry["item_id"]: entry for entry in result["results"]}
|
||||
assert by_id[blocked.id]["ok"] is True and by_id[blocked.id]["status"] == "manually_closed"
|
||||
assert by_id[success_row.id]["ok"] is False and "not closeable" in by_id[success_row.id]["error"]
|
||||
@@ -13,35 +13,42 @@ from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.cancellation import cancel_run
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.execution_service import execute_items
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(dbs_ready_file):
|
||||
def _ready_matching(dbs_ready_file):
|
||||
erp = __import__("tests.services.in_transit_transfer.fakes", fromlist=["FakeCapabilityClient"]).FakeCapabilityClient()
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, summary
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
items = (
|
||||
db.session.query(TransferInvoiceItem)
|
||||
.filter_by(status="ready_to_execute")
|
||||
.order_by(TransferInvoiceItem.id)
|
||||
.all()
|
||||
)
|
||||
return deps, items
|
||||
|
||||
|
||||
def test_cancel_requires_reason(transfer_db, dbs_ready_file):
|
||||
"""取消原因必填;无副作用(不创建执行 Run)。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
deps, _ = _ready_matching(dbs_ready_file)
|
||||
with pytest.raises(ValidationError):
|
||||
cancel_run(run_no="RUN-X", reason="")
|
||||
# 仅存在预检关联 Run(prechecking),无执行 Run
|
||||
# 仅存在匹配关联 Run(matching),无执行 Run
|
||||
runs = db.session.query(TransferRun).all()
|
||||
assert len(runs) == 1
|
||||
assert runs[0].status != "executing"
|
||||
|
||||
|
||||
def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file):
|
||||
def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""取消只作用于未开始项;已成功单据保留。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
patch_source_file_status()
|
||||
deps, items = _ready_matching(dbs_ready_file)
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first()
|
||||
# 模拟执行中状态:Run 回退到 executing,INV-002 尚未开始,INV-001 保持 success
|
||||
run.status = "executing"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨 Chat Action 测试(L2 契约,SQLite 内存库)。
|
||||
|
||||
用途:验证 transfer.precheck / transfer.execute 已注册、agent 权限映射正确、
|
||||
stream 产出结构化卡片事件(transfer-precheck / transfer-result)。
|
||||
用途:验证 transfer.match / transfer.execute 已注册、agent 权限映射正确、
|
||||
stream 产出结构化卡片事件(transfer-match / transfer-result)。
|
||||
依赖:app fixture、transfer_db、repo_fakes、action_registry、chat_actions、turn_context。
|
||||
逻辑:直接构造 TurnContext 调用 handler.stream,断言事件载荷与卡片契约。
|
||||
"""
|
||||
@@ -16,9 +16,9 @@ from app.services.chat.action_schema import TurnInput
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.in_transit_transfer.chat_actions import (
|
||||
ACTION_TRANSFER_EXECUTE,
|
||||
ACTION_TRANSFER_PRECHECK,
|
||||
ACTION_TRANSFER_MATCH,
|
||||
TransferExecuteAction,
|
||||
TransferPrecheckAction,
|
||||
TransferMatchAction,
|
||||
)
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
@@ -44,7 +44,7 @@ def _ctx(agent_code: str, action_type: str, payload: dict) -> TurnContext:
|
||||
request_id="req-1",
|
||||
user=_User(),
|
||||
agent=_Agent(agent_code),
|
||||
input=TurnInput(type="action", display_text="调拨预检", action_type=action_type, payload=payload),
|
||||
input=TurnInput(type="action", display_text="调拨匹配", action_type=action_type, payload=payload),
|
||||
refs={},
|
||||
)
|
||||
|
||||
@@ -54,58 +54,59 @@ def test_transfer_actions_registered():
|
||||
ensure_handlers_loaded()
|
||||
assert "transfer." in ACTION_AGENT_CODES
|
||||
assert ACTION_AGENT_CODES["transfer."] == ("in_transit_transfer",)
|
||||
assert TransferPrecheckAction.action_type == ACTION_TRANSFER_PRECHECK
|
||||
assert TransferMatchAction.action_type == ACTION_TRANSFER_MATCH
|
||||
assert TransferExecuteAction.action_type == ACTION_TRANSFER_EXECUTE
|
||||
|
||||
|
||||
def test_transfer_action_agent_permission_enforced():
|
||||
"""transfer.* 仅允许 in_transit_transfer agent;其他 agent 拒绝。"""
|
||||
ensure_handlers_loaded()
|
||||
ctx = _ctx("generic", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]})
|
||||
ctx = _ctx("generic", ACTION_TRANSFER_MATCH, {"source_codes": ["DBS-AWSBI"]})
|
||||
with pytest.raises(ForbiddenError):
|
||||
resolve_action_handler(ctx)
|
||||
allowed = _ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]})
|
||||
assert resolve_action_handler(allowed).action_type == ACTION_TRANSFER_PRECHECK
|
||||
allowed = _ctx("in_transit_transfer", ACTION_TRANSFER_MATCH, {"source_codes": ["DBS-AWSBI"]})
|
||||
assert resolve_action_handler(allowed).action_type == ACTION_TRANSFER_MATCH
|
||||
|
||||
|
||||
def test_precheck_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""transfer.precheck 流式产出 transfer-precheck 卡片(含明细与来源进度)。"""
|
||||
def test_matching_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""transfer.match 流式产出 transfer-match 卡片(含明细与来源进度)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
events = list(TransferPrecheckAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {
|
||||
events = list(TransferMatchAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_MATCH, {
|
||||
"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06",
|
||||
})))
|
||||
assert len(events) == 1
|
||||
event = events[0]
|
||||
assert event.event == "message.completed"
|
||||
assert event.data["message_type"] == "transfer-precheck"
|
||||
assert event.data["message_type"] == "transfer-match"
|
||||
payload = event.data["payload"]
|
||||
assert payload["kind"] == "precheck"
|
||||
assert payload["kind"] == "match"
|
||||
assert payload["summary"]["estimated_external_write_count"] == 2
|
||||
assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-002"}
|
||||
assert payload["sources"][0]["source_code"] == "DBS-AWSBI"
|
||||
|
||||
|
||||
def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeypatch, patch_source_file_status):
|
||||
"""transfer.execute 流式产出 transfer-result 卡片(按 外部系统 单号聚合)。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
# 先跑预检拿 precheck_id
|
||||
precheck_events = list(TransferPrecheckAction().stream(_ctx(
|
||||
"in_transit_transfer", ACTION_TRANSFER_PRECHECK,
|
||||
# 先跑匹配拿 matching_id
|
||||
matching_events = list(TransferMatchAction().stream(_ctx(
|
||||
"in_transit_transfer", ACTION_TRANSFER_MATCH,
|
||||
{"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06"},
|
||||
)))
|
||||
precheck_id = precheck_events[0].data["payload"]["summary"]["precheck_id"]
|
||||
matching_id = matching_events[0].data["payload"]["summary"]["matching_id"]
|
||||
|
||||
execute_events = list(TransferExecuteAction().stream(_ctx(
|
||||
"in_transit_transfer", ACTION_TRANSFER_EXECUTE,
|
||||
{"precheck_id": precheck_id, "invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
{"matching_id": matching_id, "invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)))
|
||||
assert len(execute_events) == 1
|
||||
payload = execute_events[0].data["payload"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨 DTO 与错误码契约测试(L0 纯单元)。
|
||||
|
||||
用途:验证预检 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、
|
||||
用途:验证匹配 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、
|
||||
外部系统 单据按单号聚合投影,以及一期冻结错误码完整且唯一。
|
||||
依赖:app.services.in_transit_transfer.contracts。
|
||||
逻辑:DTO 为 frozen dataclass,聚合函数按 外部系统 单号分组并统计物料数/总数量。
|
||||
@@ -15,12 +15,12 @@ import pytest
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
KNOWN_TRANSFER_ERROR_CODES,
|
||||
TRANSFER_PERMISSION_DENIED,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
TRANSFER_MATCH_EXPIRED,
|
||||
TRANSFER_QUANTITY_MISMATCH,
|
||||
TRANSFER_RESULT_UNKNOWN,
|
||||
PrecheckCountsDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
PrecheckSummaryDTO,
|
||||
MatchingCountsDTO,
|
||||
MatchingItemDTO,
|
||||
MatchingSummaryDTO,
|
||||
aggregate_external_documents,
|
||||
require_known_error_code,
|
||||
)
|
||||
@@ -35,7 +35,7 @@ EXPECTED_ERROR_CODES = {
|
||||
"TRANSFER_INVOICE_CONFLICT",
|
||||
"TRANSFER_QUANTITY_MISMATCH",
|
||||
"TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND",
|
||||
"TRANSFER_PRECHECK_EXPIRED",
|
||||
"TRANSFER_MATCH_EXPIRED",
|
||||
"TRANSFER_CONFIRMATION_REQUIRED",
|
||||
"TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
"TRANSFER_RESULT_UNKNOWN",
|
||||
@@ -55,7 +55,7 @@ def test_error_codes_match_tdd_frozen_list():
|
||||
def test_require_known_error_code_accepts_frozen_codes():
|
||||
"""冻结错误码可被契约校验接受。"""
|
||||
require_known_error_code(TRANSFER_QUANTITY_MISMATCH)
|
||||
require_known_error_code(TRANSFER_PRECHECK_EXPIRED)
|
||||
require_known_error_code(TRANSFER_MATCH_EXPIRED)
|
||||
require_known_error_code(TRANSFER_RESULT_UNKNOWN)
|
||||
require_known_error_code(TRANSFER_PERMISSION_DENIED)
|
||||
|
||||
@@ -66,37 +66,37 @@ def test_require_known_error_code_rejects_unknown():
|
||||
require_known_error_code("TRANSFER_NO_SUCH_CODE")
|
||||
|
||||
|
||||
def test_precheck_counts_dto_fields():
|
||||
"""预检计数 DTO 包含文件内/未成熟/已预检/可执行/阻断五类计数。"""
|
||||
counts = PrecheckCountsDTO(
|
||||
file_invoice_count=40, not_matured_count=8, prechecked_count=32,
|
||||
def test_matching_counts_dto_fields():
|
||||
"""匹配计数 DTO 包含文件内/未成熟/已匹配/可执行/阻断五类计数。"""
|
||||
counts = MatchingCountsDTO(
|
||||
file_invoice_count=40, not_matured_count=8, matched_count=32,
|
||||
executable_count=27, blocked_count=5,
|
||||
)
|
||||
assert counts.executable_count == 27
|
||||
assert counts.not_matured_count == 8
|
||||
|
||||
|
||||
def test_precheck_summary_dto_carries_estimate_and_hash():
|
||||
"""预检摘要 DTO 必须携带预计调拨数量、预计 外部系统 写入数与预检 Hash。"""
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id="TPC-20260806-001",
|
||||
def test_matching_summary_dto_carries_estimate_and_hash():
|
||||
"""匹配摘要 DTO 必须携带预计调拨数量、预计 外部系统 写入数与匹配 Hash。"""
|
||||
summary = MatchingSummaryDTO(
|
||||
matching_id="MTG-20260806-001",
|
||||
status="ready_to_execute",
|
||||
business_date="2026-08-06",
|
||||
eligible_receipt_date_to="2026-08-05",
|
||||
expires_at="2026-08-06T09:20:00+08:00",
|
||||
counts=PrecheckCountsDTO(40, 8, 32, 27, 5),
|
||||
counts=MatchingCountsDTO(40, 8, 32, 27, 5),
|
||||
estimated_transfer_quantity="18460",
|
||||
estimated_external_write_count=27,
|
||||
precheck_hash="sha256:abc",
|
||||
matching_hash="sha256:abc",
|
||||
)
|
||||
assert summary.estimated_transfer_quantity == "18460"
|
||||
assert summary.estimated_external_write_count == 27
|
||||
assert summary.precheck_hash.startswith("sha256:")
|
||||
assert summary.matching_hash.startswith("sha256:")
|
||||
|
||||
|
||||
def test_invoice_item_dto_carries_warehouse_and_quantity_pairs():
|
||||
"""预检明细 DTO 必须包含拨出/拨入仓库与数量对(决策 6/7)。"""
|
||||
item = PrecheckInvoiceItemDTO(
|
||||
"""匹配明细 DTO 必须包含拨出/拨入仓库与数量对(决策 6/7)。"""
|
||||
item = MatchingItemDTO(
|
||||
source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件",
|
||||
specification="A 型 / 24PIN", invoice_no="INV-001",
|
||||
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"),
|
||||
@@ -111,21 +111,21 @@ def test_invoice_item_dto_carries_warehouse_and_quantity_pairs():
|
||||
def test_aggregate_external_documents_groups_by_document_no():
|
||||
"""结果页按 外部系统 单号聚合:物料数、调拨总数量、拨出/拨入仓。"""
|
||||
items = [
|
||||
PrecheckInvoiceItemDTO(
|
||||
MatchingItemDTO(
|
||||
source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件",
|
||||
specification="A 型 / 24PIN", invoice_no="INV-001",
|
||||
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("500"),
|
||||
to_warehouse="HUB-CN01", to_quantity=Decimal("500"),
|
||||
result="success", external_document_no="TRF-10001",
|
||||
),
|
||||
PrecheckInvoiceItemDTO(
|
||||
MatchingItemDTO(
|
||||
source_code="DBS-AWSBI", material_no="MAT-002", material_name="控制器组件",
|
||||
specification="标准型 / 48V", invoice_no="INV-002",
|
||||
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"),
|
||||
to_warehouse="HUB-CN01", to_quantity=Decimal("1200"),
|
||||
result="success", external_document_no="TRF-10001",
|
||||
),
|
||||
PrecheckInvoiceItemDTO(
|
||||
MatchingItemDTO(
|
||||
source_code="CRANE-SZ", material_no="MAT-200", material_name="传感器模组",
|
||||
specification="SZ-8 / IP67", invoice_no="INV-008",
|
||||
from_warehouse="CRANE-TRANSIT", from_quantity=Decimal("600"),
|
||||
|
||||
@@ -16,33 +16,40 @@ from openpyxl import load_workbook
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.excel_export import EXCEL_SHEET_NAMES, build_exceptions_workbook
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.execution_service import execute_items
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _executed_run(dbs_ready_file):
|
||||
def _executed_run(dbs_ready_file, patch_source_file_status):
|
||||
"""构造含 1 成功 + 1 业务失败(未生成单据)的 Run。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
items = (
|
||||
db.session.query(TransferInvoiceItem)
|
||||
.filter_by(status="ready_to_execute")
|
||||
.order_by(TransferInvoiceItem.id)
|
||||
.all()
|
||||
)
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
return outcome.run_no, deps
|
||||
|
||||
|
||||
def test_workbook_has_seven_sheets(transfer_db, dbs_ready_file):
|
||||
def test_workbook_has_seven_sheets(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""异常 Excel 必须包含规格定义的 7 个 Sheet。"""
|
||||
run_no, _ = _executed_run(dbs_ready_file)
|
||||
run_no, _ = _executed_run(dbs_ready_file, patch_source_file_status)
|
||||
data = build_exceptions_workbook(run_no)
|
||||
workbook = load_workbook(io.BytesIO(data))
|
||||
assert workbook.sheetnames == EXCEL_SHEET_NAMES
|
||||
|
||||
|
||||
def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file):
|
||||
def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""业务失败项进入失败 Sheet,成功项出现在汇总 Sheet。"""
|
||||
run_no, _ = _executed_run(dbs_ready_file)
|
||||
run_no, _ = _executed_run(dbs_ready_file, patch_source_file_status)
|
||||
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
|
||||
summary_sheet = workbook["执行汇总"]
|
||||
summary_text = _sheet_text(summary_sheet)
|
||||
@@ -52,18 +59,18 @@ def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file):
|
||||
assert "HOM-001" in failed_text
|
||||
|
||||
|
||||
def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file):
|
||||
def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""原始文件追溯 Sheet 保留 Sheet/行号(决策 11)。"""
|
||||
run_no, _ = _executed_run(dbs_ready_file)
|
||||
run_no, _ = _executed_run(dbs_ready_file, patch_source_file_status)
|
||||
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
|
||||
trace_sheet = workbook["原始文件追溯"]
|
||||
text = _sheet_text(trace_sheet)
|
||||
assert "Receipt" in text and "10" in text
|
||||
|
||||
|
||||
def test_workbook_never_contains_secrets(transfer_db, dbs_ready_file):
|
||||
def test_workbook_never_contains_secrets(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""Secret 明文不得出现在 Excel(密码/Token/密文片段)。"""
|
||||
run_no, _ = _executed_run(dbs_ready_file)
|
||||
run_no, _ = _executed_run(dbs_ready_file, patch_source_file_status)
|
||||
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
|
||||
for sheet in workbook.worksheets:
|
||||
text = _sheet_text(sheet).lower()
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
"""在途调拨按行执行测试(execute_items 三层门禁,L1,SQLite 内存库)。
|
||||
|
||||
用途:验证按行执行入口的三层门禁(①存在且可执行 ②行级新鲜度 ③文件版本对账,
|
||||
失败路径均携带 details 列表且外部系统 写入为 0)、写前复查(库存变化阻断)、
|
||||
Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、
|
||||
匹配 scope 执行入口(execute_matching_items:chat/自动排程/Run Job 共用)与
|
||||
按 外部系统 单号投影最终结果。
|
||||
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
|
||||
逻辑:建 ready 行后取 item_ids 直接执行(不再经过匹配确认/hash/expires 门禁);
|
||||
文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem, TransferMatching, TransferRun
|
||||
from app.services.in_transit_transfer.execution_service import (
|
||||
execute_items,
|
||||
execute_matching_items,
|
||||
get_run,
|
||||
)
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
# dbs_ready_file 夹具 checksum(行 file_sha256 版本戳与文件对账 ready 投影同源)。
|
||||
READY_SHA = "d" * 64
|
||||
|
||||
# Invoice 号 → 夹具行 (料号, 拨出库位, 拨出批号),用于按票预置账面库存。
|
||||
_INVOICE_TUPLES = {
|
||||
"HOM-001": ("MAT-001", "DBS-TRANSIT", "LOT-10"),
|
||||
"HOX-002": ("MAT-002", "DBS-TRANSIT", "LOT-20"),
|
||||
}
|
||||
|
||||
|
||||
def _ready_items(dbs_ready_file, *seeds) -> tuple:
|
||||
"""建匹配(原地落 ready 行)并返回 (deps, erp_fake, ready 行列表)。"""
|
||||
erp = FakeCapabilityClient()
|
||||
for invoice_no, quantity in seeds:
|
||||
erp.seed_stock(*_INVOICE_TUPLES[invoice_no], quantity)
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
items = (
|
||||
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
|
||||
.order_by(TransferInvoiceItem.id)
|
||||
.all()
|
||||
)
|
||||
return deps, erp, items
|
||||
|
||||
|
||||
def _execution_runs() -> list[TransferRun]:
|
||||
"""查询全部非匹配(执行)Run。"""
|
||||
return db.session.query(TransferRun).filter(TransferRun.status != "matching").all()
|
||||
|
||||
|
||||
def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]:
|
||||
"""按 run_no 加载关联明细(invoice_no → 行)。"""
|
||||
run = db.session.query(TransferRun).filter_by(run_no=run_no).first()
|
||||
return {
|
||||
item.invoice_no: item
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
}
|
||||
|
||||
|
||||
def test_execute_items_writes_and_aggregates(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""ready 行执行 → run_no 生成、ERP 写 Attempt、状态 success、结果按 ERP 单号聚合。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first()
|
||||
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# Run 终态与单据聚合:两张成功单据(每 Invoice 一张),无未生成单据异常。
|
||||
assert outcome.status == "success"
|
||||
assert outcome.run_no.startswith("RUN-")
|
||||
assert len(outcome.result.external_documents) == 2
|
||||
assert outcome.result.exceptions == ()
|
||||
|
||||
# 行落位:全部 success 且携带 ERP 单号;每行恰一次 external_write Attempt。
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in linked.values())
|
||||
assert all(item.external_document_no for item in linked.values())
|
||||
run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first()
|
||||
attempts = db.session.query(TransferAttempt).join(TransferInvoiceItem).filter(
|
||||
TransferInvoiceItem.run_id == run.id,
|
||||
).all()
|
||||
assert len([a for a in attempts if a.kind == "external_write"]) == 2
|
||||
|
||||
# 执行 Run 不绑定匹配:run 无 matching 归属,matching 确认痕迹保持不动。
|
||||
assert run.matchings == []
|
||||
assert matching.confirmed_at is None
|
||||
|
||||
|
||||
def test_execute_items_duplicate_invoice_maps_duplicate_success(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""重复 Invoice(原单已过账)→ item duplicate_success + 原单号,不重复建单。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
erp.seed_document("HOX-002", "TRF-OLD-002", posted=True)
|
||||
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert outcome.status == "success"
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert linked["HOX-002"].status == "duplicate_success"
|
||||
assert linked["HOX-002"].external_document_no == "TRF-OLD-002"
|
||||
# 同 Invoice 不重复建单:每 Invoice 恰 1 次写调用。
|
||||
assert len(erp.write_calls()) == 2
|
||||
|
||||
|
||||
def test_execute_items_business_failure_does_not_block_others(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""单项明确业务失败 → 该项阻断,其余项成功,Run partial_failed。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert outcome.status == "partial_failed"
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert linked["HOM-001"].status == "blocked_recoverable"
|
||||
assert linked["HOX-002"].status == "success"
|
||||
# 异常项进入结果页"未生成单据"区。
|
||||
assert any(exc.invoice_no == "HOM-001" for exc in outcome.result.exceptions)
|
||||
|
||||
|
||||
def test_execute_items_result_unknown_no_auto_retry(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""result_unknown:状态终态、每 Invoice 写调用仅 1 次(禁止自动重试)。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
erp.set_write_scenario("timeout_after_commit")
|
||||
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert outcome.status == "partial_failed"
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "result_unknown" for item in linked.values())
|
||||
assert len(erp.write_calls()) == 2
|
||||
|
||||
|
||||
def test_execute_items_write_before_recheck_inventory_change_blocks(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""写前复查发现 ERP 库存变化 → 该项阻断不写,其余项正常。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "999") # 匹配后库存变化
|
||||
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert linked["HOM-001"].status == "blocked_recoverable"
|
||||
assert linked["HOX-002"].status == "success"
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["HOX-002"]
|
||||
|
||||
|
||||
def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁①:不存在/非 ready_to_execute 的 id → EXECUTE_ITEMS_INVALID(details 列出 id),零写入。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
# 把一行拨为阻断:该 id 与不存在的 id 都属于"不可执行"。
|
||||
blocked = items[0]
|
||||
blocked.status = "blocked_recoverable"
|
||||
db.session.commit()
|
||||
bad_ids = [99999, blocked.id]
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=bad_ids, deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.EXECUTE_ITEMS_INVALID"
|
||||
assert sorted(excinfo.value.details["invalid_item_ids"]) == sorted(bad_ids)
|
||||
assert erp.write_calls() == []
|
||||
assert _execution_runs() == []
|
||||
|
||||
|
||||
def test_execute_items_rejects_stale_rows(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁②:行 updated_at 距 now 超过确认 TTL → ITEMS_STALE(details 列出 id),不创建 Run。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
stale_at = datetime.utcnow() - timedelta(minutes=11) # TTL 默认 600s
|
||||
for item in items:
|
||||
item.updated_at = stale_at
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.ITEMS_STALE"
|
||||
assert sorted(excinfo.value.details["stale_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
assert _execution_runs() == []
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁③:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。"""
|
||||
# monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配",
|
||||
# (重跑匹配会把行原地刷成新版本,无法构造本场景)。
|
||||
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
assert _execution_runs() == []
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁③:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。"""
|
||||
patch_source_file_status({"DBS-AWSBI": None})
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""scope 执行入口:invoice_nos 过滤 ready 行 → 只写入选中 Invoice(chat/自动排程共用语义)。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, _ = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first()
|
||||
|
||||
outcome = execute_matching_items(
|
||||
matching_id=matching.matching_no, deps=deps, invoice_nos=["HOM-001"],
|
||||
)
|
||||
assert outcome.status == "success"
|
||||
assert len(outcome.result.external_documents) == 1
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["HOM-001"]
|
||||
|
||||
|
||||
def test_execute_matching_items_unknown_matching_404(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""scope 执行入口:匹配不存在 → NotFoundError(TRANSFER.MATCH_NOT_FOUND)。"""
|
||||
patch_source_file_status()
|
||||
deps, _, _ = _ready_items(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
with pytest.raises(NotFoundError) as excinfo:
|
||||
execute_matching_items(matching_id="MTG-NOT-EXIST", deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.MATCH_NOT_FOUND"
|
||||
|
||||
|
||||
def test_get_run_restores_document_projection(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""GET run → 按 ERP 单号聚合单据 + 未生成单据异常分开展示。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
|
||||
restored = get_run(outcome.run_no)
|
||||
assert restored["run_no"] == outcome.run_no
|
||||
assert len(restored["result"]["external_documents"]) == 1
|
||||
assert any(exc["invoice_no"] == "HOM-001" for exc in restored["result"]["exceptions"])
|
||||
@@ -1,232 +0,0 @@
|
||||
"""在途调拨执行服务测试(Phase 2 核心,L1,SQLite 内存库)。
|
||||
|
||||
用途:验证确认门禁(未确认/过期/快照变化均写入 0)、写前复查(库存变化阻断)、
|
||||
Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、
|
||||
选择子集执行、重复点击防重与按 外部系统 单号投影最终结果。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service、execution_service。
|
||||
逻辑:全部经真实 ORM 落库;外部依赖注入 Fake 替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
)
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck, get_run
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(*files: dict, capabilities=None, source_codes=None) -> tuple:
|
||||
"""创建已预检(ready_to_execute)的 precheck 并返回 (deps, erp_fake, summary)。"""
|
||||
deps, erp_fake, _ = make_transfer_deps(*files, capabilities=capabilities)
|
||||
source_codes = source_codes or [files[0]["source_code"]]
|
||||
summary = create_precheck(source_codes=source_codes, business_date="2026-08-06", deps=deps)
|
||||
return deps, erp_fake, summary
|
||||
|
||||
|
||||
_INVOICE_TUPLES = {
|
||||
# dbs_ready_file 汇总键 (料号, 拨出库位, 拨出批号) —— 与夹具行一致。
|
||||
"HOM-001": ("MAT-001", "DBS-TRANSIT", "LOT-10"),
|
||||
"HOX-002": ("MAT-002", "DBS-TRANSIT", "LOT-20"),
|
||||
}
|
||||
|
||||
|
||||
def _erp_with_stock(dbs_ready_file, *seeds) -> FakeCapabilityClient:
|
||||
"""按 Invoice 预置账面库存的 FakeCapabilityClient(发票号映射到夹具三元组)。"""
|
||||
erp = FakeCapabilityClient()
|
||||
for invoice_no, quantity in seeds:
|
||||
material_no, from_warehouse, lot_no = _INVOICE_TUPLES[invoice_no]
|
||||
erp.seed_stock(material_no, from_warehouse, lot_no, quantity)
|
||||
return erp
|
||||
|
||||
|
||||
def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]:
|
||||
run = db.session.query(TransferRun).filter_by(run_no=run_no).first()
|
||||
return {
|
||||
item.invoice_no: item
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
}
|
||||
|
||||
|
||||
def test_execute_happy_path(transfer_db, dbs_ready_file):
|
||||
"""两个可执行 Invoice → Run 成功,按 外部系统 单号投影两张单据,Attempt 落库。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "success"
|
||||
assert outcome.run_no.startswith("RUN-")
|
||||
assert len(outcome.result.external_documents) == 2
|
||||
assert outcome.result.exceptions == ()
|
||||
|
||||
items = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in items.values())
|
||||
assert all(item.external_document_no for item in items.values())
|
||||
run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first()
|
||||
attempts = db.session.query(TransferAttempt).join(TransferInvoiceItem).filter(
|
||||
TransferInvoiceItem.run_id == run.id,
|
||||
).all()
|
||||
assert len([a for a in attempts if a.kind == "external_write"]) == 2
|
||||
|
||||
|
||||
def test_execute_duplicate_invoice_maps_duplicate_success(transfer_db, dbs_ready_file):
|
||||
"""重复 Invoice(原单已过账)→ item duplicate_success + 原单号。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.seed_document("HOX-002", "TRF-OLD-002", posted=True)
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "success"
|
||||
items = _load_items(outcome.run_no)
|
||||
assert items["HOX-002"].status == "duplicate_success"
|
||||
assert items["HOX-002"].external_document_no == "TRF-OLD-002"
|
||||
# 同 Invoice 不重复建单:每 Invoice 恰 1 次写调用
|
||||
assert len(erp.write_calls()) == 2
|
||||
|
||||
|
||||
def test_execute_business_failure_does_not_block_others(transfer_db, dbs_ready_file):
|
||||
"""单项明确业务失败 → 该项阻断,其余项成功,Run partial_failed。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "partial_failed"
|
||||
items = _load_items(outcome.run_no)
|
||||
assert items["HOM-001"].status == "blocked_recoverable"
|
||||
assert items["HOX-002"].status == "success"
|
||||
# 异常项进入结果页"未生成单据"区
|
||||
assert any(exc.invoice_no == "HOM-001" for exc in outcome.result.exceptions)
|
||||
|
||||
|
||||
def test_execute_result_unknown_no_auto_retry(transfer_db, dbs_ready_file):
|
||||
"""result_unknown:状态终态、每 Invoice 写调用仅 1 次。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.set_write_scenario("timeout_after_commit")
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "partial_failed"
|
||||
items = _load_items(outcome.run_no)
|
||||
assert all(item.status == "result_unknown" for item in items.values())
|
||||
# 禁止自动重试:每个 Invoice 写调用恰 1 次
|
||||
assert len(erp.write_calls()) == 2
|
||||
|
||||
|
||||
def test_execute_unconfirmed_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
"""预检未就绪(prechecking)→ 拒绝执行,外部系统 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
precheck.status = "prechecking"
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert excinfo.value.code == TRANSFER_CONFIRMATION_REQUIRED
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_execute_expired_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
"""确认过期(超过 10 分钟)→ 拒绝执行,外部系统 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
precheck.expires_at = datetime.utcnow() - timedelta(seconds=1)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_execute_snapshot_change_blocks_write(transfer_db, dbs_ready_file):
|
||||
"""预检快照(数量)变化 → fail-closed,外部系统 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(precheck_id=precheck.id).first()
|
||||
item.receipt_quantity = "999"
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_execute_selected_subset_only(transfer_db, dbs_ready_file):
|
||||
"""仅选择 INV-001 → 只写入该 Invoice。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(
|
||||
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["HOM-001"],
|
||||
)
|
||||
assert outcome.status == "success"
|
||||
assert len(outcome.result.external_documents) == 1
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["HOM-001"]
|
||||
|
||||
|
||||
def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_file):
|
||||
"""勾选当天收料项 → 拒绝,外部系统 写入为 0。"""
|
||||
deps, erp_fake, summary = _ready_precheck(same_day_receipt_file, source_codes=["DBS-AWSSG"])
|
||||
with pytest.raises(AppError):
|
||||
execute_precheck(
|
||||
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-041"],
|
||||
)
|
||||
assert erp_fake.write_calls() == []
|
||||
|
||||
|
||||
def test_execute_double_click_rejected(transfer_db, dbs_ready_file):
|
||||
"""重复点击执行 → 第二次 409,不创建重复 Run。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
first = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert excinfo.value.http_status == 409
|
||||
# 只存在一个执行 Run(其余为预检关联 Run)
|
||||
execution_runs = db.session.query(TransferRun).filter(
|
||||
TransferRun.status != "prechecking",
|
||||
).count()
|
||||
assert execution_runs == 1
|
||||
assert first.run_no
|
||||
|
||||
|
||||
def test_execute_write_before_recheck_inventory_change_blocks(transfer_db, dbs_ready_file):
|
||||
"""写前复查发现 外部系统 库存变化 → 该项阻断不写,其余项正常。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "999") # 预检后库存变化
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
items = _load_items(outcome.run_no)
|
||||
assert items["HOM-001"].status == "blocked_recoverable"
|
||||
assert items["HOX-002"].status == "success"
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["HOX-002"]
|
||||
|
||||
|
||||
def test_get_run_restores_document_projection(transfer_db, dbs_ready_file):
|
||||
"""GET run → 按 外部系统 单号聚合单据 + 未生成单据异常分开展示。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
|
||||
restored = get_run(outcome.run_no)
|
||||
assert restored["run_no"] == outcome.run_no
|
||||
assert len(restored["result"]["external_documents"]) == 1
|
||||
assert any(exc["invoice_no"] == "HOM-001" for exc in restored["result"]["exceptions"])
|
||||
@@ -0,0 +1,192 @@
|
||||
"""行原地刷新与文件版本戳测试(L1,SQLite 内存库)。
|
||||
|
||||
用途:验证重复匹配对既有 InvoiceItem 行为"原地刷新"(不迁移 matching_id、显式续
|
||||
updated_at)、行携带本次评估所用文件的 file_sha256 版本戳,以及文件新版本
|
||||
缺失行时 ready 行被打 blocked_file_removed(blocked 行与无版本戳行不受影响)、
|
||||
最近匹配计数按匹配 scope 实时聚合(不再按行归属)。
|
||||
依赖:transfer_db、matching_service、transfer_type、repo_fakes。
|
||||
逻辑:经 create_matching 真实落库构造行状态;用"改 checksum/裁剪 rows"模拟文件
|
||||
新版本;版本戳缺失用手工清空 raw_lines_json 的 file_sha256 模拟存量数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
_item_evaluated_sha,
|
||||
create_matching,
|
||||
scope_item_query,
|
||||
)
|
||||
from app.services.in_transit_transfer.transfer_type import invoice_in_scope
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _file_without(dbs_ready_file: dict, doc_no: str, *, checksum: str) -> dict:
|
||||
"""构造"新版本文件":剔除指定单号后剩余行,并更换 checksum。"""
|
||||
return {
|
||||
**dbs_ready_file,
|
||||
"checksum": checksum,
|
||||
"rows": [row for row in dbs_ready_file["rows"] if row["doc_no"] != doc_no],
|
||||
}
|
||||
|
||||
|
||||
def test_rematching_refreshes_rows_in_place(transfer_db, dbs_ready_file):
|
||||
"""第二次匹配:同一物理行原地刷新(id 不变、matching_id 不变、值更新)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 executable
|
||||
first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
row = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
old_id, old_matching_id, old_updated = row.id, row.matching_id, row.updated_at
|
||||
|
||||
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
|
||||
db.session.refresh(row)
|
||||
# [断言意图] 行不换归属:重复匹配复用同一物理行,matching_id 保持首次创建值,
|
||||
# 仅业务值与新鲜度(updated_at)被刷新——计数错乱与壳匹配的根源即"迁移行"。
|
||||
assert row.id == old_id
|
||||
assert row.matching_id == old_matching_id
|
||||
assert row.updated_at > old_updated
|
||||
# 两份匹配记录都存在(评估留痕)。
|
||||
assert first.matching_id != second.matching_id
|
||||
|
||||
|
||||
def test_rows_carry_file_sha256_stamp(transfer_db, dbs_ready_file):
|
||||
"""行 raw_lines_json 携带本次评估所用文件的 file_sha256(新建行写入)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
|
||||
# [断言意图] 版本戳与 file_snapshot 同源(checksum):Task 2/3 文件对账读取
|
||||
# item.raw_lines_json[0].file_sha256,缺失即无法判定行新鲜度。
|
||||
for invoice_no in ("HOM-001", "HOX-002"):
|
||||
row = db.session.query(TransferInvoiceItem).filter_by(invoice_no=invoice_no).first()
|
||||
assert row.raw_lines_json, f"{invoice_no} 应有 raw_lines"
|
||||
assert row.raw_lines_json[0]["file_sha256"] == dbs_ready_file["checksum"]
|
||||
assert _item_evaluated_sha(row) == dbs_ready_file["checksum"]
|
||||
|
||||
|
||||
def test_scope_item_query_follows_matching_scope(transfer_db, dbs_ready_file):
|
||||
"""scope_item_query 按 scope_json(来源+日期区间+类型前缀)圈行,不依赖行归属。"""
|
||||
from app.models import TransferMatching
|
||||
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-05", receipt_date_to="2026-08-05",
|
||||
)
|
||||
matching = db.session.query(TransferMatching).filter_by(matching_no=summary.matching_id).first()
|
||||
|
||||
rows = scope_item_query(matching).all()
|
||||
|
||||
# [断言意图] 行的 matching_id 即使不指向本匹配,scope 命中的行也必须被圈入
|
||||
# (Task 2 restore 与最近匹配计数共用该口径)。
|
||||
assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_scope_query_sees_same_rows_for_overlapping_matchings(transfer_db, dbs_ready_file):
|
||||
"""重匹配不迁移行:两份匹配按各自 scope 实时圈行,命中同一批行(实时视图语义)。"""
|
||||
from app.models import TransferMatching
|
||||
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable
|
||||
first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
|
||||
# [断言意图] 行不迁移后两份匹配的 scope 都命中同一批活跃行(总数 2、
|
||||
# 可执行 1、阻断 1)——匹配卡=范围实时视图,不再出现"旧匹配被掏空"。
|
||||
for matching_no in (first.matching_id, second.matching_id):
|
||||
matching = db.session.query(TransferMatching).filter_by(matching_no=matching_no).one()
|
||||
rows = scope_item_query(matching).all()
|
||||
assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"}
|
||||
assert sum(1 for r in rows if r.status == "ready_to_execute") == 1
|
||||
assert sum(1 for r in rows if r.status == "blocked_recoverable") == 1
|
||||
|
||||
|
||||
def test_file_removed_marks_ready_rows_blocked(transfer_db, dbs_ready_file):
|
||||
"""文件新版本缺失该行:ready 行打 blocked_file_removed;blocked 行不动。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # HOM-001 → executable
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
|
||||
assert hom.status == "ready_to_execute"
|
||||
|
||||
# 新文件版本:内容只剩 HOX-002(HOM-001 消失),checksum 变化。
|
||||
new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64)
|
||||
deps2, erp2, _ = make_transfer_deps(new_file)
|
||||
erp2.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 仍可执行
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2)
|
||||
|
||||
db.session.refresh(hom)
|
||||
db.session.refresh(hox)
|
||||
# [断言意图] 上一版本可执行、新版本消失的行必须停用(否则会按过期数据执行);
|
||||
# 仍在文件中的行原地刷新后保持可执行,且版本戳更新为本次评估文件。
|
||||
assert hom.status == "blocked_recoverable"
|
||||
assert hom.result_code == "blocked_file_removed"
|
||||
assert hom.result_message == "receipt row removed from latest file"
|
||||
assert hox.status == "ready_to_execute"
|
||||
assert _item_evaluated_sha(hox) == "e" * 64
|
||||
|
||||
|
||||
def test_file_removed_skips_unknown_evaluated_version(transfer_db, dbs_ready_file):
|
||||
"""行上无 file_sha256(历史数据)时不误标 file_removed。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
assert hom.status == "ready_to_execute"
|
||||
# 模拟存量行:清空 raw_lines_json 的 file_sha256 版本戳。
|
||||
hom.raw_lines_json = [
|
||||
{key: value for key, value in line.items() if key != "file_sha256"}
|
||||
for line in (hom.raw_lines_json or [])
|
||||
]
|
||||
db.session.commit()
|
||||
|
||||
new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64)
|
||||
deps2, _, _ = make_transfer_deps(new_file)
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2)
|
||||
|
||||
db.session.refresh(hom)
|
||||
# [断言意图] 无法判定行评估自哪个文件版本时宁可不标(fail-safe):
|
||||
# 误标会把存量可执行行全部打散成阻断。
|
||||
assert hom.status == "ready_to_execute"
|
||||
assert hom.result_code is None
|
||||
|
||||
|
||||
def test_file_removed_skips_blocked_and_out_of_range_rows(transfer_db, dbs_ready_file):
|
||||
"""消失行标记只作用于 ready 行:blocked 行保持原结果;范围外行不受影响。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 → 数量不一致 blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
assert hom.status == "blocked_recoverable"
|
||||
|
||||
new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64)
|
||||
deps2, _, _ = make_transfer_deps(new_file)
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2)
|
||||
|
||||
db.session.refresh(hom)
|
||||
# [断言意图] blocked 行已是终局解释(数量不一致),覆盖成 file_removed 会丢失
|
||||
# 真实原因——只补 ready 行的"消失"语义。
|
||||
assert hom.status == "blocked_recoverable"
|
||||
assert hom.result_code == "blocked_quantity_mismatch"
|
||||
|
||||
|
||||
def test_invoice_in_scope_predicate():
|
||||
"""invoice_in_scope:类型 1 按 HOM/HOX/WTP 前缀(大小写不敏感),占位类型恒 False。"""
|
||||
assert invoice_in_scope("HOM-001", "in_transit_to_hub") is True
|
||||
assert invoice_in_scope("hox-002", "in_transit_to_hub") is True
|
||||
assert invoice_in_scope("WTP-008", None) is True # 缺省回落类型 1
|
||||
assert invoice_in_scope("INV-9", "in_transit_to_hub") is False
|
||||
assert invoice_in_scope("", "in_transit_to_hub") is False
|
||||
# [断言意图] 占位类型(规则未启用)必须返回 False:scope 查询不得圈入任何行。
|
||||
assert invoice_in_scope("HOM-001", "hub_repair_out") is False
|
||||
+72
-67
@@ -1,9 +1,9 @@
|
||||
"""在途调拨预检服务测试(L1,SQLite 内存库)。
|
||||
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
|
||||
|
||||
用途:验证 D+1 过滤(当天收料 外部系统 调用=0)、严格数量匹配、来源隔离、
|
||||
预检快照 Hash 稳定、缺文件等待与进度恢复。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service。
|
||||
逻辑:全部经真实 ORM 落库(create_precheck/restore_precheck),
|
||||
匹配快照 Hash 稳定、缺文件等待与进度恢复。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
|
||||
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
|
||||
外部依赖注入 Fake 替身。
|
||||
"""
|
||||
|
||||
@@ -12,12 +12,12 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
create_precheck,
|
||||
restore_precheck,
|
||||
run_precheck,
|
||||
create_matching,
|
||||
restore_matching,
|
||||
run_matching,
|
||||
)
|
||||
from tests.services.in_transit_transfer.assertions import assert_erp_calls
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA
|
||||
@@ -38,7 +38,7 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
]:
|
||||
erp.seed_stock(material, warehouse, lot, qty)
|
||||
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
summary = result.summary
|
||||
@@ -46,7 +46,7 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
assert summary.counts.not_matured_count == 0
|
||||
assert summary.counts.blocked_count == 0
|
||||
assert summary.status == "ready_to_execute"
|
||||
assert summary.precheck_hash.startswith("sha256:")
|
||||
assert summary.matching_hash.startswith("sha256:")
|
||||
assert summary.estimated_external_write_count == 3
|
||||
# 明细 DTO 决策 6/7:拨出/拨入仓库与数量对
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
@@ -59,7 +59,7 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
|
||||
"""当天收料 → not_matured,外部系统 调用次数为 0。"""
|
||||
deps, erp, _ = _deps(same_day_receipt_file)
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert result.summary.counts.not_matured_count == 1
|
||||
@@ -73,7 +73,7 @@ def test_quantity_mismatch_blocked_no_write(dbs_ready_file):
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
@@ -87,7 +87,7 @@ def test_erp_inventory_not_found_blocked(dbs_ready_file):
|
||||
"""外部系统 无库存 → blocked_inventory_not_found。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # INV-002 无库存
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
@@ -98,11 +98,11 @@ def test_external_query_failure_degrades_to_blocked_item(dbs_ready_file):
|
||||
"""外部系统 网关故障(绑定缺失/连接失败等非超时异常)→ 单据级阻断,不得炸掉整个来源。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.query_scenario = "error"
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
# [断言意图] 外部系统 基础设施故障必须降级为逐票 blocked_external_query_failed:
|
||||
# 来源保持 file_ready,发票全部带原因出现在列表里,而不是来源消失、预检全 0。
|
||||
# 来源保持 file_ready,发票全部带原因出现在列表里,而不是来源消失、匹配全 0。
|
||||
assert result.sources[0].stage == "file_ready"
|
||||
assert result.items and all(item.result == "blocked_external_query_failed" for item in result.items)
|
||||
assert all("query_inventory" in item.reason for item in result.items)
|
||||
@@ -112,7 +112,7 @@ def test_external_query_failure_degrades_to_blocked_item(dbs_ready_file):
|
||||
def test_missing_file_waits_without_erp():
|
||||
"""缺文件 → 来源阶段 waiting_rpa_callback,无 外部系统 调用。"""
|
||||
deps, erp, _ = _deps()
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert result.sources[0].stage == "waiting_rpa_callback"
|
||||
@@ -121,11 +121,11 @@ def test_missing_file_waits_without_erp():
|
||||
|
||||
|
||||
def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file):
|
||||
"""DBS 缺文件且 RPA 触发失败不阻断 CRANE-SZ 预检(来源隔离)。"""
|
||||
"""DBS 缺文件且 RPA 触发失败不阻断 CRANE-SZ 匹配(来源隔离)。"""
|
||||
deps, erp, rpa = _deps(crane_ready_file)
|
||||
rpa.fail_on.add("DBS-AWSBI")
|
||||
erp.seed_stock("MAT-200", "CRANE-SZ-TRANSIT", "LOT-8", "600")
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
by_source = {stage.source_code: stage for stage in result.sources}
|
||||
@@ -136,27 +136,27 @@ def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file):
|
||||
|
||||
|
||||
def test_snapshot_hash_is_stable(dbs_ready_file):
|
||||
"""相同输入两次预检 → 预检 Hash 一致(可审计复算)。"""
|
||||
"""相同输入两次匹配 → 匹配 Hash 一致(可审计复算)。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
first = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
second = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
assert first.summary.precheck_hash == second.summary.precheck_hash
|
||||
first = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
second = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
assert first.summary.matching_hash == second.summary.matching_hash
|
||||
|
||||
|
||||
def test_create_and_restore_precheck(transfer_db, dbs_ready_file):
|
||||
"""create_precheck 落库后 restore_precheck 可完整恢复进度与明细。"""
|
||||
def test_create_and_restore_matching(transfer_db, dbs_ready_file):
|
||||
"""create_matching 落库后 restore_matching 可完整恢复进度与明细。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
|
||||
summary = create_precheck(
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert summary.precheck_id.startswith("TPC-")
|
||||
restored = restore_precheck(summary.precheck_id)
|
||||
assert restored["summary"].precheck_hash == summary.precheck_hash
|
||||
assert summary.matching_id.startswith("MTG-")
|
||||
restored = restore_matching(summary.matching_id)
|
||||
assert restored["summary"].matching_hash == summary.matching_hash
|
||||
assert restored["summary"].status == summary.status
|
||||
restored_items = {item.invoice_no: item for item in restored["items"]}
|
||||
assert set(restored_items) == {"HOM-001", "HOX-002"}
|
||||
@@ -170,7 +170,7 @@ def test_create_and_restore_precheck(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
def test_parse_failure_persists_source_error_visible_on_restore(transfer_db):
|
||||
"""解析失败 → 来源级 error 落库并经 restore 透出(预检全 0 复发防线)。
|
||||
"""解析失败 → 来源级 error 落库并经 restore 透出(匹配全 0 复发防线)。
|
||||
|
||||
[断言意图] CRANE 实况回归(2026-09-21):行缺 doc_no(别名覆盖症状)时
|
||||
整文件 ReceiptFileSchemaError;失败事实必须持久化到 source_job,恢复后
|
||||
@@ -189,11 +189,11 @@ def test_parse_failure_persists_source_error_visible_on_restore(transfer_db):
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
assert summary.status == "file_pending"
|
||||
assert summary.counts.file_invoice_count == 0
|
||||
|
||||
restored = restore_precheck(summary.precheck_id)
|
||||
restored = restore_matching(summary.matching_id)
|
||||
source = next(s for s in restored["sources"] if s.source_code == "DSV360_AWSDU")
|
||||
# [断言意图] 失败原因跨刷新可见:stage=failed + error_code/message 非空。
|
||||
assert source.stage == "failed"
|
||||
@@ -201,25 +201,30 @@ def test_parse_failure_persists_source_error_visible_on_restore(transfer_db):
|
||||
assert source.error_message
|
||||
|
||||
|
||||
def test_repeated_precheck_refreshes_instead_of_accumulating(transfer_db, dbs_ready_file):
|
||||
"""同一数据重复预检 → 不新增异常行,原地刷新并挂到最新预检(累加缺陷回归防线)。"""
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck
|
||||
def test_repeated_matching_refreshes_instead_of_accumulating(transfer_db, dbs_ready_file):
|
||||
"""同一数据重复匹配 → 不新增行,既有行原地刷新且归属不变(累加缺陷回归防线)。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.query_scenario = "error" # 全部阻断:正是此前不断累加"可恢复异常"的场景
|
||||
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
first_count = TransferInvoiceItem.query.count()
|
||||
assert first_count == 2
|
||||
first_matching = TransferMatching.query.order_by(TransferMatching.id.asc()).first()
|
||||
old_updated = {row.id: row.updated_at for row in TransferInvoiceItem.query.all()}
|
||||
|
||||
# [断言意图] 第二次相同预检必须复用既有行(不出现 2×116 式累加),并挂到最新预检。
|
||||
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
# [断言意图] 第二次相同匹配必须复用既有行(不出现 2×116 式累加),且行归属
|
||||
# 不变(原地刷新语义,matching_id 不改写到最新匹配)、新鲜度被显式续期。
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
assert TransferInvoiceItem.query.count() == first_count
|
||||
latest_precheck_id = TransferPrecheck.query.order_by(TransferPrecheck.id.desc()).first().id
|
||||
assert all(row.precheck_id == latest_precheck_id for row in TransferInvoiceItem.query.all())
|
||||
assert TransferMatching.query.count() == 2 # 匹配记录照常逐次留痕
|
||||
for row in TransferInvoiceItem.query.all():
|
||||
assert row.matching_id == first_matching.id
|
||||
assert row.updated_at > old_updated[row.id]
|
||||
|
||||
|
||||
def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
|
||||
"""同一批号(ASN)跨料号 → 按新聚合粒度拆分多行落库,不再撞 (预检,单号) 唯一约束。"""
|
||||
"""同一批号(ASN)跨料号 → 按新聚合粒度拆分多行落库,不再撞 (匹配,单号) 唯一约束。"""
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
@@ -236,23 +241,23 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.query_scenario = "error"
|
||||
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
# [断言意图] 新唯一粒度 = (预检,来源,单号,料号,日期):同批号多料号必须共存于同一预检。
|
||||
summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
# [断言意图] 新唯一粒度 = (匹配,来源,单号,料号,日期):同批号多料号必须共存于同一匹配。
|
||||
assert summary.counts.file_invoice_count == 2
|
||||
|
||||
|
||||
def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file):
|
||||
"""收料日期范围作为预检查询范围:范围外发票不进入明细。"""
|
||||
"""收料日期范围作为匹配查询范围:范围外发票不进入明细。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-05", receipt_date_to="2026-08-05",
|
||||
)
|
||||
assert summary.counts.file_invoice_count == 2
|
||||
|
||||
empty = create_precheck(
|
||||
empty = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-01", receipt_date_to="2026-08-04",
|
||||
)
|
||||
@@ -265,7 +270,7 @@ def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file):
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_precheck(
|
||||
create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-04", receipt_date_to="2026-08-06",
|
||||
)
|
||||
@@ -282,7 +287,7 @@ def test_route_not_resolved_marks_source_failed(dbs_ready_file):
|
||||
route_resolver=FakeRouteResolver(routes={}),
|
||||
capabilities=erp,
|
||||
)
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
by_source = {stage.source_code: stage for stage in result.sources}
|
||||
@@ -290,10 +295,10 @@ def test_route_not_resolved_marks_source_failed(dbs_ready_file):
|
||||
assert by_source["CRANE-SZ"].stage == "waiting_rpa_callback" # 无文件 → 等待,不阻断
|
||||
|
||||
|
||||
def test_run_precheck_consumes_movement_field_rows(app):
|
||||
"""run_precheck 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。"""
|
||||
def test_run_matching_consumes_movement_field_rows(app):
|
||||
"""run_matching 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。"""
|
||||
# [断言意图] 真实仓库 rows 以 doc_no/material_code/quantity/movement_date 为键;
|
||||
# 预检应正确产出 executable 明细而非 ReceiptFileSchemaError
|
||||
# 匹配应正确产出 executable 明细而非 ReceiptFileSchemaError
|
||||
# 注:sheet/row_no 为解析校验必带的溯源字段(与 parse_movement_rows 契约一致,同校验)。
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
@@ -308,7 +313,7 @@ def test_run_precheck_consumes_movement_field_rows(app):
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) # 按 (料号, 拨出库位, 拨出批号) 维护账面库存
|
||||
result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
item = next(i for i in result.items if i.invoice_no == "WTP-1")
|
||||
assert item.result == "executable"
|
||||
|
||||
@@ -318,7 +323,7 @@ def test_run_precheck_consumes_movement_field_rows(app):
|
||||
def test_type1_filters_invoices_by_prefix(app):
|
||||
"""类型 1(在途仓至HUB仓)只纳入 INVOICE 前缀 HOM/HOX/WTP 的票,范围外静默排除。"""
|
||||
# [断言意图] INV-9 不匹配任何前缀 → 不入明细、不产生 blocked 行;
|
||||
# HOM/HOX/WTP 前缀票正常走完整预检(成熟 + 外部系统 匹配)。
|
||||
# HOM/HOX/WTP 前缀票正常走完整匹配(成熟 + 外部系统 匹配)。
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
@@ -339,15 +344,15 @@ def test_type1_filters_invoices_by_prefix(app):
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5)
|
||||
erp_fake.seed_stock("M3", "WH1", "LOT-3", 7)
|
||||
result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
invoice_nos = {item.invoice_no for item in result.items}
|
||||
assert invoice_nos == {"HOM-100", "WTP-300"}
|
||||
assert all(item.result == "executable" for item in result.items)
|
||||
assert result.summary.counts.executable_count == 2
|
||||
|
||||
|
||||
def test_create_precheck_persists_transfer_type_on_run_and_scope(transfer_db):
|
||||
"""create_precheck 落库 Run.transfer_type 与 Precheck.scope_json 类型口径。"""
|
||||
def test_create_matching_persists_transfer_type_on_run_and_scope(transfer_db):
|
||||
"""create_matching 落库 Run.transfer_type 与 Matching.scope_json 类型口径。"""
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
@@ -361,21 +366,21 @@ def test_create_precheck_persists_transfer_type_on_run_and_scope(transfer_db):
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5)
|
||||
summary = create_precheck(
|
||||
summary = create_matching(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
)
|
||||
from app.models import TransferPrecheck, TransferRun
|
||||
from app.models import TransferMatching, TransferRun
|
||||
|
||||
run = TransferRun.query.filter_by(run_no=summary.precheck_id and TransferRun.query.first().run_no).first()
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first()
|
||||
run = TransferRun.query.filter_by(run_no=summary.matching_id and TransferRun.query.first().run_no).first()
|
||||
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).first()
|
||||
assert run is not None and run.transfer_type == "in_transit_to_hub"
|
||||
scope = precheck.scope_json
|
||||
scope = matching.scope_json
|
||||
assert scope["transfer_type"] == "in_transit_to_hub"
|
||||
assert scope["transfer_type_scope"] == "invoice_prefix:hom+hox+wtp"
|
||||
|
||||
|
||||
def test_create_precheck_defaults_transfer_type_when_omitted(transfer_db):
|
||||
def test_create_matching_defaults_transfer_type_when_omitted(transfer_db):
|
||||
"""缺省 transfer_type → 类型 1(存量调用方/排程行为不变但纳入前缀过滤)。"""
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
@@ -390,13 +395,13 @@ def test_create_precheck_defaults_transfer_type_when_omitted(transfer_db):
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5)
|
||||
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
from app.models import TransferPrecheck, TransferRun
|
||||
summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
from app.models import TransferMatching, TransferRun
|
||||
|
||||
run = TransferRun.query.first()
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first()
|
||||
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).first()
|
||||
assert run.transfer_type == "in_transit_to_hub"
|
||||
assert precheck.scope_json["transfer_type"] == "in_transit_to_hub"
|
||||
assert matching.scope_json["transfer_type"] == "in_transit_to_hub"
|
||||
|
||||
|
||||
def test_placeholder_transfer_types_fail_closed():
|
||||
@@ -411,13 +416,13 @@ def test_placeholder_transfer_types_fail_closed():
|
||||
},
|
||||
)
|
||||
with pytest.raises(ValidationError) as not_supported:
|
||||
create_precheck(
|
||||
create_matching(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="hub_repair_out",
|
||||
)
|
||||
assert not_supported.value.code == "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
|
||||
with pytest.raises(ValidationError) as invalid:
|
||||
create_precheck(
|
||||
create_matching(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="bogus_type",
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨运营指标测试(Phase 4,L1)。
|
||||
|
||||
用途:验证指标聚合(Run/明细状态分布、待处理老化、通知失败数)正确。
|
||||
依赖:transfer_db、precheck/execution/metrics、repo_fakes。
|
||||
依赖:transfer_db、matching/execution/metrics、repo_fakes。
|
||||
逻辑:指标由数据库现状投影,便于上线观察板使用。
|
||||
"""
|
||||
|
||||
@@ -10,20 +10,25 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.execution_service import execute_items
|
||||
from app.services.in_transit_transfer.metrics import collect_metrics
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file):
|
||||
def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""指标包含 Run 状态分布与明细状态分布。"""
|
||||
patch_source_file_status()
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
item_ids = [
|
||||
item.id for item in db.session.query(TransferInvoiceItem)
|
||||
.filter_by(status="ready_to_execute").all()
|
||||
]
|
||||
execute_items(item_ids=item_ids, deps=deps)
|
||||
|
||||
metrics = collect_metrics()
|
||||
assert metrics["runs"]["success"] >= 1
|
||||
@@ -35,7 +40,7 @@ def test_collect_metrics_backlog_and_notification_failure(transfer_db, dbs_ready
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.updated_at = item.updated_at # 保持默认年龄
|
||||
db.session.commit()
|
||||
|
||||
@@ -21,6 +21,7 @@ pytestmark = pytest.mark.pure_unit
|
||||
EXPECTED_TABLES = {
|
||||
"transfer_runs",
|
||||
"transfer_source_jobs",
|
||||
# 历史迁移 it1a2b3c4d5e 建的旧表名(旧 revision 不可改;后续 rn* 迁移再改名)。
|
||||
"transfer_prechecks",
|
||||
"transfer_invoice_items",
|
||||
"transfer_attempts",
|
||||
|
||||
@@ -18,13 +18,13 @@ from app.models import (
|
||||
TransferAttempt,
|
||||
TransferAuditEvent,
|
||||
TransferInvoiceItem,
|
||||
TransferPrecheck,
|
||||
TransferMatching,
|
||||
TransferRun,
|
||||
TransferSourceJob,
|
||||
)
|
||||
|
||||
TRANSFER_TABLES = {
|
||||
"transfer_runs", "transfer_source_jobs", "transfer_prechecks",
|
||||
"transfer_runs", "transfer_source_jobs", "transfer_matchings",
|
||||
"transfer_invoice_items", "transfer_attempts", "transfer_audit_events",
|
||||
"transfer_archives",
|
||||
}
|
||||
@@ -43,7 +43,7 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
run_no="RUN-20260806-001",
|
||||
trigger_type="manual",
|
||||
business_date="2026-08-06",
|
||||
status="prechecking",
|
||||
status="matching",
|
||||
source_codes_json=["DBS-AWSBI"],
|
||||
counts_json={"file_invoice_count": 3, "executable_count": 2},
|
||||
)
|
||||
@@ -56,17 +56,17 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
source_config_version=5,
|
||||
status="checking_file",
|
||||
)
|
||||
precheck = TransferPrecheck(
|
||||
precheck_no="TPC-20260806-001",
|
||||
matching = TransferMatching(
|
||||
matching_no="MTG-20260806-001",
|
||||
run_id=run.id,
|
||||
business_date="2026-08-06",
|
||||
status="ready_to_execute",
|
||||
scope_json={"source_codes": ["DBS-AWSBI"]},
|
||||
counts_json={"executable_count": 1},
|
||||
precheck_hash="sha256:test",
|
||||
matching_hash="sha256:test",
|
||||
)
|
||||
item = TransferInvoiceItem(
|
||||
precheck=precheck,
|
||||
matching=matching,
|
||||
run_id=run.id,
|
||||
source_code="DBS-AWSBI",
|
||||
invoice_no="INV-001",
|
||||
@@ -81,7 +81,7 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
status="ready_to_execute",
|
||||
raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}],
|
||||
)
|
||||
transfer_db.session.add_all([source_job, precheck, item])
|
||||
transfer_db.session.add_all([source_job, matching, item])
|
||||
transfer_db.session.flush()
|
||||
|
||||
attempt = TransferAttempt(
|
||||
@@ -104,22 +104,22 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
assert loaded_attempt.attempt_no == 1
|
||||
|
||||
|
||||
def test_invoice_item_unique_per_precheck(transfer_db):
|
||||
"""同一预检内同一 Invoice 只能出现一次(防重复建单底座)。"""
|
||||
precheck = TransferPrecheck(
|
||||
precheck_no="TPC-20260806-002",
|
||||
def test_invoice_item_unique_per_matching(transfer_db):
|
||||
"""同一匹配内同一 Invoice 只能出现一次(防重复建单底座)。"""
|
||||
matching = TransferMatching(
|
||||
matching_no="MTG-20260806-002",
|
||||
business_date="2026-08-06",
|
||||
status="prechecking",
|
||||
status="matching",
|
||||
scope_json={},
|
||||
counts_json={},
|
||||
precheck_hash="sha256:test2",
|
||||
matching_hash="sha256:test2",
|
||||
)
|
||||
transfer_db.session.add(precheck)
|
||||
transfer_db.session.add(matching)
|
||||
transfer_db.session.flush()
|
||||
|
||||
def _item(invoice_no: str) -> TransferInvoiceItem:
|
||||
return TransferInvoiceItem(
|
||||
precheck_id=precheck.id,
|
||||
matching_id=matching.id,
|
||||
source_code="DBS-AWSBI",
|
||||
invoice_no=invoice_no,
|
||||
material_no="MAT-001",
|
||||
@@ -154,14 +154,14 @@ def test_run_no_unique(transfer_db):
|
||||
|
||||
def test_invoice_item_status_check_constraint(transfer_db):
|
||||
"""Invoice 状态必须属于冻结枚举(数据库级门禁兜底)。"""
|
||||
precheck = TransferPrecheck(
|
||||
precheck_no="TPC-20260806-003", business_date="2026-08-06",
|
||||
status="prechecking", scope_json={}, counts_json={}, precheck_hash="x",
|
||||
matching = TransferMatching(
|
||||
matching_no="MTG-20260806-003", business_date="2026-08-06",
|
||||
status="matching", scope_json={}, counts_json={}, matching_hash="x",
|
||||
)
|
||||
transfer_db.session.add(precheck)
|
||||
transfer_db.session.add(matching)
|
||||
transfer_db.session.flush()
|
||||
transfer_db.session.add(TransferInvoiceItem(
|
||||
precheck_id=precheck.id, source_code="DBS-AWSBI", invoice_no="INV-999",
|
||||
matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="INV-999",
|
||||
material_no="MAT-9", receipt_date="2026-08-05",
|
||||
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1", external_quantity="1",
|
||||
@@ -198,7 +198,7 @@ def test_archive_roundtrip(transfer_db):
|
||||
archive = TransferArchive(
|
||||
archive_no="ARC-20260806-001",
|
||||
object_type="external_inventory_snapshot",
|
||||
object_id="TPC-20260806-001",
|
||||
object_id="MTG-20260806-001",
|
||||
storage_provider="minio",
|
||||
storage_bucket="hxops-transfer",
|
||||
storage_key="transfer/20260806/snapshot.xlsx",
|
||||
|
||||
@@ -11,26 +11,31 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferRun
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.execution_service import execute_items
|
||||
from app.services.in_transit_transfer.notification import notify_run_summary
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from tests.services.in_transit_transfer.fakes import FakeWeCom
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _executed_run(dbs_ready_file):
|
||||
def _executed_run(dbs_ready_file, patch_source_file_status):
|
||||
patch_source_file_status()
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
item_ids = [
|
||||
item.id for item in db.session.query(TransferInvoiceItem)
|
||||
.filter_by(status="ready_to_execute").all()
|
||||
]
|
||||
outcome = execute_items(item_ids=item_ids, deps=deps)
|
||||
return outcome.run_no
|
||||
|
||||
|
||||
def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file):
|
||||
def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""非空 Run → 恰好一条汇总通知;重复调用幂等。"""
|
||||
run_no = _executed_run(dbs_ready_file)
|
||||
run_no = _executed_run(dbs_ready_file, patch_source_file_status)
|
||||
wecom = FakeWeCom()
|
||||
first = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1", "u-2"])
|
||||
assert first["notification_status"] == "success"
|
||||
@@ -42,9 +47,9 @@ def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file):
|
||||
assert run.status == "success" # 外部系统 结果不受影响
|
||||
|
||||
|
||||
def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_file):
|
||||
def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""通知失败 → notification_status=failed,run.status 保持 success。"""
|
||||
run_no = _executed_run(dbs_ready_file)
|
||||
run_no = _executed_run(dbs_ready_file, patch_source_file_status)
|
||||
wecom = FakeWeCom()
|
||||
wecom.attach_fail = True
|
||||
result = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1"], excel_path="x.xlsx")
|
||||
|
||||
@@ -1,69 +1,96 @@
|
||||
"""在途调拨 Run 编排测试(Phase 2,L1)。
|
||||
|
||||
用途:验证执行 Run 创建(执行中状态、关联预检与明细)、终态收尾与
|
||||
重复创建防护。
|
||||
依赖:transfer_db、precheck_service、orchestrator、repo_fakes。
|
||||
逻辑:编排层复用 execution_service 落库流程,本文件聚焦 Run 生命周期辅助函数。
|
||||
用途:验证按行创建执行 Run(executing 状态、关联选中行、不绑定匹配)、
|
||||
终态收尾与重复关联防护(已关联行跳过)。
|
||||
依赖:transfer_db、matching_service、orchestrator、repo_fakes。
|
||||
逻辑:编排层接收调用方(execution_service)按 scope 圈定并校验后的行,
|
||||
本文件聚焦 Run 生命周期辅助函数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.orchestrator import (
|
||||
create_execution_run_for_items,
|
||||
finalize_run,
|
||||
)
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from app.services.in_transit_transfer.status import TransferRunStatus
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(dbs_ready_file):
|
||||
"""创建已预检 precheck 并返回 (deps, summary)。"""
|
||||
def _ready_items(dbs_ready_file):
|
||||
"""建匹配(原地落 ready 行)并返回 (deps, ready 行列表)。"""
|
||||
erp = FakeCapabilityClient()
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, summary
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
items = (
|
||||
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
|
||||
.order_by(TransferInvoiceItem.id)
|
||||
.all()
|
||||
)
|
||||
return deps, items
|
||||
|
||||
|
||||
def test_create_execution_run_links_items_and_sets_executing(transfer_db, dbs_ready_file):
|
||||
"""create_execution_run 创建 executing Run 并关联可执行明细。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
def test_create_execution_run_for_items_links_items_and_sets_executing(transfer_db, dbs_ready_file):
|
||||
"""create_execution_run_for_items 创建 executing Run 并关联选中明细(不绑定匹配)。"""
|
||||
deps, items = _ready_items(dbs_ready_file)
|
||||
|
||||
run = create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
run = create_execution_run_for_items(items, deps=deps, actor_id=None)
|
||||
assert run.status == TransferRunStatus.EXECUTING.value
|
||||
items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
assert len(items) == 2
|
||||
assert all(item.status == "executing" for item in items)
|
||||
assert run.matchings == [] # 执行 Run 与匹配解耦(matching.run_id 不回写执行 Run)
|
||||
linked = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
assert len(linked) == 2
|
||||
assert all(item.status == "executing" for item in linked)
|
||||
# Run 来源范围与行计数按选中行聚合。
|
||||
assert run.source_codes_json == ["DBS-AWSBI"]
|
||||
assert run.counts_json["executable_count"] == 2
|
||||
|
||||
|
||||
def test_finalize_run_sets_terminal_status(transfer_db, dbs_ready_file):
|
||||
"""finalize_run 按明细终态汇总 Run 状态。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
run = create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
deps, items = _ready_items(dbs_ready_file)
|
||||
run = create_execution_run_for_items(items, deps=deps, actor_id=None)
|
||||
|
||||
items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
for item in items:
|
||||
linked = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
for item in linked:
|
||||
item.status = "success"
|
||||
finalize_run(run, items)
|
||||
finalize_run(run, linked)
|
||||
assert run.status == TransferRunStatus.SUCCESS.value
|
||||
|
||||
for item in items:
|
||||
for item in linked:
|
||||
item.status = "blocked_recoverable"
|
||||
finalize_run(run, items)
|
||||
finalize_run(run, linked)
|
||||
assert run.status == TransferRunStatus.PARTIAL_FAILED.value
|
||||
|
||||
|
||||
def test_create_execution_run_rejects_duplicate(transfer_db, dbs_ready_file):
|
||||
"""已确认的 precheck 不允许重复创建执行 Run。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
with pytest.raises(ConflictError):
|
||||
create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
def test_create_execution_run_for_items_skips_already_linked(transfer_db, dbs_ready_file):
|
||||
"""已关联执行 Run(run_id 非空)的行被跳过:重复调用不重复关联/递增 Attempt 序号。"""
|
||||
deps, items = _ready_items(dbs_ready_file)
|
||||
first = create_execution_run_for_items(items, deps=deps, actor_id=None)
|
||||
attempt_no_before = {item.id: item.attempt_no for item in items}
|
||||
|
||||
second = create_execution_run_for_items(items, deps=deps, actor_id=None)
|
||||
linked_second = db.session.query(TransferInvoiceItem).filter_by(run_id=second.id).all()
|
||||
assert linked_second == [] # 全部行已归属首个执行 Run
|
||||
for item in items:
|
||||
assert item.run_id == first.id
|
||||
assert item.attempt_no == attempt_no_before[item.id]
|
||||
assert second.run_no != first.run_no
|
||||
|
||||
|
||||
def test_create_execution_run_for_items_selected_subset(transfer_db, dbs_ready_file):
|
||||
"""selected_item_ids 限定关联范围:仅选中行被置 executing 并计入 Run 计数。"""
|
||||
deps, items = _ready_items(dbs_ready_file)
|
||||
selected = {items[0].id}
|
||||
|
||||
run = create_execution_run_for_items(items, deps=deps, actor_id=None, selected_item_ids=selected)
|
||||
linked = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
assert [item.id for item in linked] == [items[0].id]
|
||||
assert linked[0].status == "executing"
|
||||
assert items[1].status == "ready_to_execute"
|
||||
assert items[1].run_id is None
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:验证调拨 query_inventory 经 CapabilityGateway 接线——网关被调用且入参为
|
||||
(external_org, targets) 契约、成熟过滤(当天收料不查)、fail-closed
|
||||
(无绑定来源逐票降级但不阻断其他来源)。
|
||||
依赖:run_precheck、CapabilityClient、repo_fakes.make_transfer_deps、transports.base。
|
||||
依赖:run_matching、CapabilityClient、repo_fakes.make_transfer_deps、transports.base。
|
||||
逻辑:领域规则(严格数量匹配/D+1/来源隔离)仍在领域层;接口选择与调用由连接器框架承担。
|
||||
"""
|
||||
|
||||
@@ -14,7 +14,7 @@ from decimal import Decimal
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient
|
||||
from app.services.in_transit_transfer.precheck_service import run_precheck
|
||||
from app.services.in_transit_transfer.matching_service import run_matching
|
||||
from app.services.integration_connector.errors import BindingNotFoundError
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
@@ -53,7 +53,7 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
|
||||
("MAT-001", "DBS-TRANSIT", "LOT-10"): "1200",
|
||||
("MAT-002", "DBS-TRANSIT", "LOT-20"): "1200",
|
||||
})
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06",
|
||||
deps=_cap_deps(dbs_ready_file, gw), run_no="RUN-T",
|
||||
)
|
||||
@@ -71,7 +71,7 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
|
||||
def test_not_matured_not_queried(app, same_day_receipt_file):
|
||||
"""当天收料(not_matured)不查外部系统——网关零调用。"""
|
||||
gw = FakeGateway(inventory={})
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06",
|
||||
deps=_cap_deps(same_day_receipt_file, gw), run_no="RUN-T",
|
||||
)
|
||||
@@ -101,7 +101,7 @@ def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready
|
||||
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, crane_ready_file)
|
||||
deps = replace(deps, capabilities=CapabilityClient(gateway=_SplitGateway()))
|
||||
result = run_precheck(
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06",
|
||||
deps=deps, run_no="RUN-T",
|
||||
)
|
||||
|
||||
@@ -133,7 +133,7 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
# [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger
|
||||
@@ -146,7 +146,7 @@ def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
|
||||
)
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
|
||||
assert outcome["ok"] is False
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨每日恢复(待处理池自动复核)测试(Phase 3,L1)。
|
||||
|
||||
用途:验证历史可恢复项下一排程重新预检并创建新 Attempt;
|
||||
用途:验证历史可恢复项下一排程重新匹配并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:transfer_db、precheck_service、recovery_service、repo_fakes。
|
||||
逻辑:恢复 = 重新预检(仅查询/匹配),不写 外部系统;每次恢复新 Attempt。
|
||||
依赖:transfer_db、matching_service、recovery_service、repo_fakes。
|
||||
逻辑:恢复 = 重新匹配(仅查询/匹配),不写 外部系统;每次恢复新 Attempt。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,23 +12,23 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from app.services.in_transit_transfer.recovery_service import run_daily_recovery
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _mixed_precheck(dbs_ready_file):
|
||||
"""构造 1 个数量不一致 + 1 个可执行的预检。"""
|
||||
def _mixed_matching(dbs_ready_file):
|
||||
"""构造 1 个数量不一致 + 1 个可执行的匹配。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, erp, summary
|
||||
|
||||
|
||||
def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_file):
|
||||
def test_recovery_rematchings_and_creates_new_attempt(transfer_db, dbs_ready_file):
|
||||
"""外部系统 修正后恢复 → 项转 ready_to_execute,新 Attempt 落库。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mixed_matching(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
assert item.status == "blocked_recoverable"
|
||||
old_attempt_no = item.attempt_no
|
||||
@@ -43,13 +43,13 @@ def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_fil
|
||||
assert refreshed.attempt_no == old_attempt_no + 1
|
||||
attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all()
|
||||
assert len(attempts) == 1 and attempts[0].kind == "external_query"
|
||||
# 恢复仅预检,不写 外部系统
|
||||
# 恢复仅匹配,不写 外部系统
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 不自动恢复,也不产生 外部系统 调用。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mixed_matching(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
@@ -62,7 +62,7 @@ def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_recovery_skips_manually_closed_and_success(transfer_db, dbs_ready_file):
|
||||
"""manually_closed / success 永久排除,不生成 Attempt。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mixed_matching(dbs_ready_file)
|
||||
blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
blocked.status = "manually_closed"
|
||||
blocked.manually_closed_reason = "线下处理"
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""匹配卡 scope 实时视图测试(restore 按 scope 查行 + 行装饰字段,L1)。
|
||||
|
||||
用途:验证 restore_matching 不再读 matching.items 行归属,而按匹配 scope
|
||||
(scope_item_query)实时圈定行集,并逐行装饰 item_id / checked_at /
|
||||
stale / file_current;counts 为 scope 行实时聚合(不读 counts_json 快照)。
|
||||
依赖:transfer_db、matching_service、repo_fakes。
|
||||
逻辑:经 create_matching 真实落库构造行状态;行归属(matching_id)保持首次
|
||||
创建值(原地刷新语义),重复匹配的 restore 仍能看到同一批活跃行;
|
||||
收料文件状态投影按同款 monkeypatch 替身注入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import matching_service
|
||||
from app.services.in_transit_transfer.matching_service import create_matching, restore_matching
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _file_ready(monkeypatch, dbs_ready_file: dict) -> None:
|
||||
"""让来源文件状态投影返回 ready(sha 与 fixture 文件一致,不触碰真实文件表)。"""
|
||||
monkeypatch.setattr(
|
||||
matching_service, "resolve_source_file_status",
|
||||
lambda *, source_code: {"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": dbs_ready_file["file_no"],
|
||||
"file_sha256": dbs_ready_file["checksum"]},
|
||||
)
|
||||
|
||||
|
||||
def test_restore_returns_scope_rows_not_owned_rows(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""restore 按范围返回实时行:行属于首份匹配,但第二份匹配的 restore 也能看到(实时状态)。"""
|
||||
_file_ready(monkeypatch, dbs_ready_file)
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) # 行建在此匹配
|
||||
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
|
||||
detail = restore_matching(second.matching_id, deps=deps)
|
||||
|
||||
assert {i.invoice_no for i in detail["items"]} == {"HOM-001", "HOX-002"}
|
||||
row = next(i for i in detail["items"] if i.invoice_no == "HOX-002")
|
||||
# [断言意图] 行装饰三要素:行 id 可追溯(item_id)、刚刷新不陈旧(stale)、
|
||||
# 行评估版本戳仍是该来源当前可用文件(file_current)。
|
||||
assert row.item_id > 0 and row.stale is False and row.file_current is True
|
||||
# [断言意图] counts 为 scope 行实时聚合(不读 counts_json 快照):
|
||||
# 2 行 = 1 可执行 + 1 阻断;summary 其余字段沿用匹配记录留痕。
|
||||
counts = detail["summary"].counts
|
||||
assert counts.file_invoice_count == 2
|
||||
assert counts.executable_count == 1
|
||||
assert counts.blocked_count == 1
|
||||
assert counts.matched_count == 2
|
||||
assert detail["summary"].matching_hash == second.matching_hash
|
||||
assert detail["summary"].expires_at
|
||||
|
||||
|
||||
def test_restore_marks_stale_beyond_ttl(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""行 updated_at 早于 TTL → stale=True(TTL 取 deps.strategy.confirm_ttl_seconds)。"""
|
||||
_file_ready(monkeypatch, dbs_ready_file)
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
# 手工把 HOX-002 行的评估时间拨回 11 分钟前(TTL 默认 600 秒 = 10 分钟)。
|
||||
stale_at = datetime.utcnow() - timedelta(minutes=11)
|
||||
hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
|
||||
hox.updated_at = stale_at
|
||||
db.session.commit()
|
||||
|
||||
detail = restore_matching(summary.matching_id, deps=deps)
|
||||
|
||||
row = next(i for i in detail["items"] if i.invoice_no == "HOX-002")
|
||||
fresh = next(i for i in detail["items"] if i.invoice_no == "HOM-001")
|
||||
# [断言意图] 超过确认 TTL 未刷新的行必须标记 stale(提示用户重查后再执行),
|
||||
# 未拨回的行保持新鲜;checked_at 携带行评估时间(updated_at isoformat)。
|
||||
assert row.stale is True
|
||||
assert fresh.stale is False
|
||||
assert row.checked_at == hox.updated_at.isoformat()
|
||||
assert row.file_current is True
|
||||
|
||||
|
||||
def test_restore_marks_file_current_false_without_ready_file(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""来源当前无可用文件 → 行 file_current=False(fail-safe,不得当作新鲜)。"""
|
||||
monkeypatch.setattr(
|
||||
matching_service, "resolve_source_file_status",
|
||||
lambda *, source_code: {"file_status": "none", "has_ready_file": False,
|
||||
"file_no": None, "file_sha256": None},
|
||||
)
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
|
||||
detail = restore_matching(summary.matching_id, deps=deps)
|
||||
|
||||
# [断言意图] 对账依据缺失(无可用文件 sha)时宁可不放行:行版本戳无法与
|
||||
# 当前文件比对,file_current 必须为 False,避免按过期数据执行的幻觉。
|
||||
assert detail["items"]
|
||||
assert all(i.file_current is False for i in detail["items"])
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
用途:验证人工重试只创建新 Attempt(重新查询 外部系统,不重新抓 RPA、不写 外部系统),
|
||||
result_unknown 拒绝重试;人工关闭原因必填且永久排除。
|
||||
依赖:transfer_db、precheck_service、retry_service、manual_close_service、repo_fakes。
|
||||
依赖:transfer_db、matching_service、retry_service、manual_close_service、repo_fakes。
|
||||
逻辑:重试前冻结文件不变;每次重试 attempt_no 递增且旧 Attempt 保留。
|
||||
"""
|
||||
|
||||
@@ -14,17 +14,17 @@ from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from app.services.in_transit_transfer.retry_service import requery_items, retry_item
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _mismatch_precheck(dbs_ready_file):
|
||||
"""构造 INV-001 数量不一致的预检。"""
|
||||
def _mismatch_matching(dbs_ready_file):
|
||||
"""构造 INV-001 数量不一致的匹配。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, erp, summary
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ def _item_by_invoice(invoice_no: str) -> TransferInvoiceItem:
|
||||
|
||||
def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file):
|
||||
"""外部系统 修正后重试 → 新 Attempt,状态进入 ready_to_execute。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
assert item.status == "blocked_recoverable"
|
||||
old_attempt_count = item.attempt_no
|
||||
@@ -56,7 +56,7 @@ def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_retry_still_mismatch_keeps_blocked(transfer_db, dbs_ready_file):
|
||||
"""重试后仍不匹配 → 保持 blocked_recoverable,attempt_no 递增。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
old = item.attempt_no
|
||||
result = retry_item(item_id=item.id, deps=deps)
|
||||
@@ -71,7 +71,7 @@ def test_retry_still_mismatch_keeps_blocked(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_retry_not_found_shows_zero_stock(transfer_db, dbs_ready_file):
|
||||
"""重查后外部系统查无记录 → 库存数按 0 落库展示,不显示"-"误导为查询失败。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
retry_item(item_id=item.id, deps=deps) # 先产生 external_quantity=1000
|
||||
assert _item_by_invoice("HOM-001").external_quantity == "1000"
|
||||
@@ -86,8 +86,8 @@ def test_retry_not_found_shows_zero_stock(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
def test_retry_ready_row_allowed(transfer_db, dbs_ready_file):
|
||||
"""可执行(ready_to_execute)行也允许重查:预检后库存变化需可复核。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
"""可执行(ready_to_execute)行也允许重查:匹配后库存变化需可复核。"""
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "ready_to_execute"
|
||||
db.session.commit()
|
||||
@@ -102,13 +102,13 @@ def test_retry_ready_row_allowed(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_requery_includes_ready_rows(transfer_db, dbs_ready_file):
|
||||
"""批量重查范围含可执行行:可执行行也会被逐票刷新,而非只刷阻断行。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "ready_to_execute"
|
||||
db.session.commit()
|
||||
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "500") # 库存被挪用
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
|
||||
result = requery_items(matching_no=summary.matching_id, deps=deps)
|
||||
|
||||
# [断言意图] 可执行行不再被重查排除;库存变化后被重查回阻断态并保留 外部系统 数。
|
||||
assert result["total"] == 2
|
||||
@@ -120,7 +120,7 @@ def test_requery_includes_ready_rows(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 只读:拒绝重试(禁止猜测性二次写入)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "result_unknown"
|
||||
item.result_code = "result_unknown"
|
||||
@@ -132,7 +132,7 @@ def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file):
|
||||
"""Run 创建后禁止重新抓取 RPA(文件冻结)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
with pytest.raises(ValidationError):
|
||||
retry_item(item_id=item.id, deps=deps, kind="rpa_refetch")
|
||||
@@ -140,7 +140,7 @@ def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_manual_close_requires_reason(transfer_db, dbs_ready_file):
|
||||
"""人工关闭原因必填。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
with pytest.raises(ValidationError):
|
||||
manual_close_item(item_id=item.id, reason="")
|
||||
@@ -148,7 +148,7 @@ def test_manual_close_requires_reason(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_manual_close_marks_terminal(transfer_db, dbs_ready_file):
|
||||
"""人工关闭 → manually_closed(永久排除,后续排程不再处理)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
result = manual_close_item(item_id=item.id, reason="货代确认无需调拨")
|
||||
assert result["status"] == "manually_closed"
|
||||
@@ -163,7 +163,7 @@ def test_manual_close_marks_terminal(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 只读:禁止人工关闭(需按 SOP 核实)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
@@ -172,10 +172,10 @@ def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
def test_requery_items_refreshes_blocked_rows(transfer_db, dbs_ready_file):
|
||||
"""批量重查:同预检全部可重查行(阻断 + 可执行)逐票刷新,结果按行回报。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
"""批量重查:同匹配全部可重查行(阻断 + 可执行)逐票刷新,结果按行回报。"""
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # 人工在 外部系统 修正库存
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
|
||||
result = requery_items(matching_no=summary.matching_id, deps=deps)
|
||||
# [断言意图] 阻断行(HOM-001)与可执行行(HOX-002)都在重查范围内。
|
||||
assert result["total"] == 2
|
||||
rows = {row["invoice_no"]: row for row in result["results"]}
|
||||
@@ -187,11 +187,11 @@ def test_requery_items_refreshes_blocked_rows(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_requery_items_invoice_filter_targets_only_given_rows(transfer_db, dbs_ready_file):
|
||||
"""invoice_nos 限定范围:不在清单的阻断行不被触碰。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
blocked = db.session.query(TransferInvoiceItem).filter_by(status="blocked_recoverable").all()
|
||||
assert [i.invoice_no for i in blocked] == ["HOM-001"]
|
||||
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps, invoice_nos=["INV-XXX"])
|
||||
result = requery_items(matching_no=summary.matching_id, deps=deps, invoice_nos=["INV-XXX"])
|
||||
assert result["total"] == 0
|
||||
assert _item_by_invoice("HOM-001").status == "blocked_recoverable"
|
||||
|
||||
@@ -201,9 +201,9 @@ def test_retry_erp_binding_failure_degrades_instead_of_raising(transfer_db, dbs_
|
||||
blocked_external_query_failed + 原因,不向调用方抛异常。
|
||||
|
||||
此前该场景抛 BindingNotFoundError('no binding for capability'),
|
||||
与 precheck 的逐票降级语义不一致,用户侧表现为全局错误弹窗。
|
||||
与 matching 的逐票降级语义不一致,用户侧表现为全局错误弹窗。
|
||||
"""
|
||||
deps, erp, _summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, _summary = _mismatch_matching(dbs_ready_file)
|
||||
erp.set_query_scenario("error") # RuntimeError: binding not found for capability query_inventory
|
||||
item = _item_by_invoice("HOM-001")
|
||||
old_attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).count()
|
||||
@@ -223,9 +223,9 @@ def test_retry_erp_binding_failure_degrades_instead_of_raising(transfer_db, dbs_
|
||||
|
||||
def test_requery_with_erp_gateway_failure_stays_batched(transfer_db, dbs_ready_file):
|
||||
"""批量重查遇 外部系统 故障:逐票降级、批次正常完成,不炸整批。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
deps, erp, summary = _mismatch_matching(dbs_ready_file)
|
||||
erp.set_query_scenario("error")
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
|
||||
result = requery_items(matching_no=summary.matching_id, deps=deps)
|
||||
assert result["total"] == 2
|
||||
assert all(row["ok"] for row in result["results"])
|
||||
assert _item_by_invoice("HOM-001").result_code == "blocked_external_query_failed"
|
||||
@@ -15,7 +15,7 @@ import pytest
|
||||
from app.extensions import db
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.deps import DefaultRouteResolver
|
||||
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError
|
||||
from app.services.in_transit_transfer.matching_service import RouteNotResolvedError
|
||||
|
||||
|
||||
def _seed_mapping(
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.services.in_transit_transfer.source_job_service import (
|
||||
def _run() -> TransferRun:
|
||||
from app import db
|
||||
|
||||
run = TransferRun(run_no='RUN-SJOB', trigger_type='manual', business_date='2026-08-06', status='prechecking')
|
||||
run = TransferRun(run_no='RUN-SJOB', trigger_type='manual', business_date='2026-08-06', status='matching')
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
return run
|
||||
|
||||
@@ -25,7 +25,7 @@ from app.services.in_transit_transfer.status import (
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
PROMPT_STATUSES = {
|
||||
"file_pending", "file_ready", "prechecking", "ready_to_execute", "executing",
|
||||
"file_pending", "file_ready", "matching", "ready_to_execute", "executing",
|
||||
"success", "duplicate_success", "blocked_recoverable", "not_matured",
|
||||
"result_unknown", "manually_closed", "cancelled", "notification_failed",
|
||||
}
|
||||
@@ -62,8 +62,8 @@ def test_illegal_transition_rejected():
|
||||
|
||||
|
||||
def test_legal_transition_accepted():
|
||||
"""file_ready → prechecking 是合法迁移。"""
|
||||
assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.PRECHECKING.value)
|
||||
"""file_ready → matching 是合法迁移。"""
|
||||
assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.MATCHING.value)
|
||||
|
||||
|
||||
def test_executing_to_success_accepted():
|
||||
@@ -81,9 +81,9 @@ def test_executing_to_result_unknown_accepted_but_no_auto_retry():
|
||||
|
||||
|
||||
def test_blocked_recoverable_to_manual_close_and_recheck():
|
||||
"""blocked_recoverable 可人工关闭或重新预检(新 Attempt)。"""
|
||||
"""blocked_recoverable 可人工关闭或重新匹配(新 Attempt)。"""
|
||||
assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.MANUALLY_CLOSED.value)
|
||||
assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.PRECHECKING.value)
|
||||
assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.MATCHING.value)
|
||||
|
||||
|
||||
def test_unknown_status_rejected():
|
||||
@@ -98,10 +98,10 @@ def test_not_matured_has_no_outgoing_edges():
|
||||
|
||||
|
||||
def test_run_transition_queued_to_executing_path():
|
||||
"""Run 生命周期:queued → preparing_files → prechecking → ready_to_execute → executing。"""
|
||||
"""Run 生命周期:queued → preparing_files → matching → ready_to_execute → executing。"""
|
||||
assert_transition_allowed(TransferRunStatus.QUEUED.value, TransferRunStatus.PREPARING_FILES.value, transitions=RUN_TRANSITIONS)
|
||||
assert_transition_allowed(TransferRunStatus.PREPARING_FILES.value, TransferRunStatus.PRECHECKING.value, transitions=RUN_TRANSITIONS)
|
||||
assert_transition_allowed(TransferRunStatus.PRECHECKING.value, TransferRunStatus.READY_TO_EXECUTE.value, transitions=RUN_TRANSITIONS)
|
||||
assert_transition_allowed(TransferRunStatus.PREPARING_FILES.value, TransferRunStatus.MATCHING.value, transitions=RUN_TRANSITIONS)
|
||||
assert_transition_allowed(TransferRunStatus.MATCHING.value, TransferRunStatus.READY_TO_EXECUTE.value, transitions=RUN_TRANSITIONS)
|
||||
assert_transition_allowed(TransferRunStatus.READY_TO_EXECUTE.value, TransferRunStatus.EXECUTING.value, transitions=RUN_TRANSITIONS)
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
用途:验证执行中(executing)且租约过期的项可恢复(依赖 Invoice 幂等,不重复建单)、
|
||||
停滞 Run 可终态收尾、result_unknown 不被自动重试。
|
||||
依赖:transfer_db、precheck/execution/recovery、repo_fakes。
|
||||
依赖:transfer_db、matching/execution/recovery、repo_fakes。
|
||||
逻辑:恢复 = 重新写前复查 + 幂等写入;已落单场景由 外部系统 返回 duplicate_success。
|
||||
"""
|
||||
|
||||
@@ -14,8 +14,7 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from app.services.in_transit_transfer.recovery import (
|
||||
finalize_stale_runs,
|
||||
recover_stale_execution_items,
|
||||
@@ -24,12 +23,12 @@ from app.services.in_transit_transfer.status import TransferStatus
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _executing_precheck(dbs_ready_file):
|
||||
"""构造已预检 precheck(不执行),并手动把明细置为 executing。"""
|
||||
def _executing_matching(dbs_ready_file):
|
||||
"""构造已匹配 matching(不执行),并手动把明细置为 executing。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
for item in db.session.query(TransferInvoiceItem).all():
|
||||
item.status = "executing"
|
||||
item.updated_at = datetime.utcnow() - timedelta(hours=2) # 租约已过期
|
||||
@@ -39,7 +38,7 @@ def _executing_precheck(dbs_ready_file):
|
||||
|
||||
def test_recover_stale_execution_items_completes_writes(transfer_db, dbs_ready_file):
|
||||
"""租约过期的 executing 项恢复后完成写入(幂等,无重复建单)。"""
|
||||
deps, erp = _executing_precheck(dbs_ready_file)
|
||||
deps, erp = _executing_matching(dbs_ready_file)
|
||||
result = recover_stale_execution_items(deps=deps)
|
||||
assert result["recovered"] == 2
|
||||
items = db.session.query(TransferInvoiceItem).all()
|
||||
@@ -51,7 +50,7 @@ def test_recover_stale_execution_items_completes_writes(transfer_db, dbs_ready_f
|
||||
|
||||
def test_recover_skips_result_unknown(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 不自动重试(不触碰、不写 外部系统)。"""
|
||||
deps, erp = _executing_precheck(dbs_ready_file)
|
||||
deps, erp = _executing_matching(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).first()
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
@@ -64,15 +63,18 @@ def test_recover_skips_result_unknown(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_finalize_stale_runs_marks_terminal(transfer_db, dbs_ready_file):
|
||||
"""停滞 Run(全部明细已终态但 Run 仍 executing)→ 收尾为 success。"""
|
||||
from app.models import TransferPrecheck
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run_for_items
|
||||
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first()
|
||||
run = create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
ready_items = (
|
||||
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
|
||||
.order_by(TransferInvoiceItem.id)
|
||||
.all()
|
||||
)
|
||||
run = create_execution_run_for_items(ready_items, deps=deps, actor_id=None)
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
|
||||
item.status = "success"
|
||||
item.external_document_no = "TRF-DONE"
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""tests/services/integration_connector/test_mapping_repeated_record_batch.py
|
||||
|
||||
用途:复现并回归"批量库存查询结果装配丢行"缺陷(Task 6 独立排查,2026-09-23)。
|
||||
生产实测矛盾:同一批 Invoice 预检批量查询全部 blocked_inventory_not_found(0),
|
||||
逐行单查却能查得库存——两条路径的差异只在一次查询携带的 targets 数量。
|
||||
依赖:mapping.py / transports.soap(纯函数);capability_client.CapabilityClient。
|
||||
逻辑:TIPTOP GetItemStockList 响应中 Record/Master/RecordSet 都是可重复节点,
|
||||
XML 归一化后"单条 dict、多条 list"。批量查询返回多 Record(/多 Master)时,
|
||||
extract_path 扇出收集会产出嵌套 list,pick 无法消费 → 字段全 MISSING →
|
||||
行被静默丢弃 → 领域层 lookup 未命中 → 整批 0 库存。
|
||||
用例覆盖:同料号不同批号、同批号不同料号、单 Master 多 Record、
|
||||
多 RecordSet 混合多 Record,以及批量 vs 单查的 lookup 对账。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient, StockTarget
|
||||
from app.services.integration_connector.mapping import extract_path, map_response
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
from app.services.integration_connector.transports.soap import _parse_soap_payload
|
||||
|
||||
# 生产绑定同构的 rows 映射(expr/each/pick 与 2026-09-22 回归用例一致,
|
||||
# from_warehouse 按 img02、批号 img04、库存数 img10)。
|
||||
_ROWS_MAPPING = {"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master",
|
||||
"transform": "each", "args": {"fields": {
|
||||
"material_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img01", "value_field": "@value"}},
|
||||
"from_warehouse": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img02", "value_field": "@value"}},
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}},
|
||||
"quantity": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img10", "value_field": "@value",
|
||||
"cast": "decimal"}}}}}}
|
||||
_ROWS_OUTPUT_SCHEMA = {"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array", "items": {
|
||||
"type": "object", "required": ["material_no", "from_warehouse", "lot_no", "quantity"]}}}}
|
||||
|
||||
|
||||
def _field(name: str, value: str) -> dict:
|
||||
return {"@name": name, "@value": value}
|
||||
|
||||
|
||||
def _record(material: str, warehouse: str, lot: str, qty: str) -> dict:
|
||||
return {"Field": [_field("img01", material), _field("img02", warehouse),
|
||||
_field("img04", lot), _field("img10", qty)]}
|
||||
|
||||
|
||||
def _stock_response(record_sets: list[dict]) -> dict:
|
||||
"""构造 GetItemStockListResponse 归一化后形态(与 _parse_soap_payload 产出同构)。"""
|
||||
return {"GetItemStockListResponse": {"response": {"Response": {
|
||||
"ResponseContent": {"Document": {"RecordSet": record_sets}}}}}}
|
||||
|
||||
|
||||
def _client_with_rows(rows: list[dict]) -> CapabilityClient:
|
||||
"""以映射产物为应答的 CapabilityClient 替身网关(模拟引擎 data 透传)。"""
|
||||
|
||||
class _Gateway:
|
||||
def call(self, **kwargs):
|
||||
return IntegrationCallResult(status="success", data={"rows": rows})
|
||||
|
||||
return CapabilityClient(gateway=_Gateway())
|
||||
|
||||
|
||||
def test_single_target_single_record_maps_one_row():
|
||||
"""单查形态(1 RecordSet × 1 Master × 1 Record)→ 一行(重查路径现状正确的基线)。"""
|
||||
raw = _stock_response([
|
||||
{"@id": "1", "Master": {"@name": "img_file", "Record": _record("M-1", "W-1", "L-1", "30")}},
|
||||
])
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
assert rows == [{"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("30")}]
|
||||
|
||||
|
||||
def test_multi_record_master_maps_every_record_row():
|
||||
"""[缺陷复现] 一个 Master 容器携带多条 Record(不同批号/料号)→ 每条 Record 一行。
|
||||
|
||||
[断言意图] 修复前:扇出嵌套 list 使 pick 全 MISSING → 行静默消失(rows=[]),
|
||||
批量查询整批 0 库存;修复后:每条 Record 产出独立行,同料号不同批号 /
|
||||
同批号不同料号互不覆盖、互不丢失。
|
||||
"""
|
||||
raw = _stock_response([
|
||||
{"@id": "1", "Master": {"@name": "img_file", "Record": [
|
||||
_record("M-1", "W-1", "L-1", "30"),
|
||||
_record("M-1", "W-1", "L-2", "40"),
|
||||
_record("M-2", "W-1", "L-1", "36"),
|
||||
]}},
|
||||
])
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
# [断言意图] 同料号不同批号(L-1/L-2)与同批号不同料号(M-1/M-2)全部保留。
|
||||
assert rows == [
|
||||
{"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("30")},
|
||||
{"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-2", "quantity": Decimal("40")},
|
||||
{"material_no": "M-2", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("36")},
|
||||
]
|
||||
|
||||
|
||||
def test_multi_recordset_with_multi_record_master_keeps_all_rows():
|
||||
"""[缺陷复现] 多 RecordSet(按条件拆分)且部分 Master 多 Record → 行数完整。"""
|
||||
raw = _stock_response([
|
||||
{"@id": "1", "Master": {"@name": "img_file", "Record": [
|
||||
_record("M-1", "W-1", "L-1", "30"),
|
||||
_record("M-1", "W-1", "L-1", "10"),
|
||||
]}},
|
||||
{"@id": "2", "Master": {"@name": "img_file", "Record": _record("M-2", "W-2", "L-9", "40")}},
|
||||
])
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
# [断言意图] RecordSet 逐元素扇出 + 重复 Record 展开叠加时行数完整(2+1=3 行)。
|
||||
assert len(rows) == 3
|
||||
assert rows[0]["quantity"] == Decimal("30")
|
||||
assert rows[2] == {"material_no": "M-2", "from_warehouse": "W-2", "lot_no": "L-9", "quantity": Decimal("40")}
|
||||
|
||||
|
||||
def test_batch_vs_single_lookup_parity_on_multi_record_response():
|
||||
"""[事故链路] 批量查询(多 targets)与逐 target 单查的 lookup 结果必须一一对应。
|
||||
|
||||
映射切片走生产同构配置:批量响应为"单 Master 多 Record"形态时,修复前批量
|
||||
lookup 全 None(=0 库存)而单查正常——正是预检 0 / 重查 30 的矛盾来源。
|
||||
"""
|
||||
raw_batch = _stock_response([
|
||||
{"@id": "1", "Master": {"@name": "img_file", "Record": [
|
||||
_record("M-1", "W-1", "L-1", "30"),
|
||||
_record("M-1", "W-1", "L-2", "40"),
|
||||
_record("M-2", "W-1", "L-1", "36"),
|
||||
]}},
|
||||
])
|
||||
raw_single = _stock_response([
|
||||
{"@id": "1", "Master": {"@name": "img_file", "Record": _record("M-1", "W-1", "L-1", "30")}},
|
||||
])
|
||||
batch_rows = map_response(_ROWS_MAPPING, raw_batch, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
single_rows = map_response(_ROWS_MAPPING, raw_single, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
|
||||
targets = [StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-1"),
|
||||
StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-2"),
|
||||
StockTarget(material_no="M-2", from_warehouse="W-1", lot_no="L-1")]
|
||||
batch_result = _client_with_rows(batch_rows).query_stock(
|
||||
operation_id="op-batch", external_org="HX-CN01", targets=targets)
|
||||
single_result = _client_with_rows(single_rows).query_stock(
|
||||
operation_id="op-single", external_org="HX-CN01", targets=[targets[0]])
|
||||
|
||||
# [断言意图] 批量与单查逐 target 对账一致:批量不再整批 0(inventory_not_found)。
|
||||
assert single_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") == Decimal("30")
|
||||
assert batch_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") == Decimal("30")
|
||||
assert batch_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-2") == Decimal("40")
|
||||
assert batch_result.lookup(material_no="M-2", from_warehouse="W-1", lot_no="L-1") == Decimal("36")
|
||||
|
||||
|
||||
def test_soap_multi_record_payload_end_to_end_mapping():
|
||||
"""端到端真实 XML:转义内嵌报文 → SOAP 解析归一化 → 多 Record 全部映射成行。"""
|
||||
xml = (
|
||||
"<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'>"
|
||||
"<SOAP-ENV:Body><ns0:GetItemStockListResponse xmlns:ns0='urn:tiptop'>"
|
||||
"<ns0:response><Response><ResponseContent><Document>"
|
||||
"<RecordSet id='1'><Master name='img_file'>"
|
||||
"<Record><Field name='img01' value='M-1'/><Field name='img02' value='W-1'/>"
|
||||
"<Field name='img04' value='L-1'/><Field name='img10' value='30'/></Record>"
|
||||
"<Record><Field name='img01' value='M-1'/><Field name='img02' value='W-1'/>"
|
||||
"<Field name='img04' value='L-2'/><Field name='img10' value='40'/></Record>"
|
||||
"</Master></RecordSet>"
|
||||
"</Document></ResponseContent></Response>"
|
||||
"</ns0:response></ns0:GetItemStockListResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>"
|
||||
)
|
||||
raw = _parse_soap_payload(xml)
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
# [断言意图] 转义内嵌报文同样走归一化+映射:两条 Record(不同批号)都成行。
|
||||
assert [(r["lot_no"], str(r["quantity"])) for r in rows] == [("L-1", "30"), ("L-2", "40")]
|
||||
|
||||
|
||||
def test_extract_path_fanout_nested_list_flattened():
|
||||
"""extract_path 扇出命中本身是列表(更深层重复节点)→ 拍平而非嵌套。"""
|
||||
raw = {"Masters": [
|
||||
{"Record": [{"Field": [{"@name": "img01", "@value": "M-1"}]},
|
||||
{"Field": [{"@name": "img01", "@value": "M-2"}]}]},
|
||||
{"Record": {"Field": [{"@name": "img01", "@value": "M-3"}]}},
|
||||
]}
|
||||
# [断言意图] 逐元素收集跨两层重复节点后是"所有 Field dict"的扁平列表,
|
||||
# pick 等消费方不再见到 list-in-list。
|
||||
assert extract_path(raw, "Masters.Record.Field") == [
|
||||
{"@name": "img01", "@value": "M-1"}, {"@name": "img01", "@value": "M-2"},
|
||||
{"@name": "img01", "@value": "M-3"},
|
||||
]
|
||||
|
||||
|
||||
def test_case_and_space_variants_pass_through_exact_match():
|
||||
"""[怀疑矩阵:大小写/尾空格] ERP 回显值原样透传,lookup 按三元组精确匹配。
|
||||
|
||||
[断言意图] 归一化/映射层不做任何大小写或去空格改写(回显 'm-1 '/'l-1' 原样
|
||||
成行);若外部回显与请求键存在大小写/空格差异,lookup 未命中返回 None——
|
||||
该语义对批量/单查两侧对称,不是本次"批量 0/单查有值"矛盾的原因,故不改匹配语义。
|
||||
"""
|
||||
raw = _stock_response([
|
||||
{"@id": "1", "Master": {"@name": "img_file", "Record": _record("m-1 ", "W-1", "l-1", "30")}},
|
||||
])
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
# [断言意图] 行值原样保留(未改写大小写、未截断空格)。
|
||||
assert rows == [{"material_no": "m-1 ", "from_warehouse": "W-1", "lot_no": "l-1",
|
||||
"quantity": Decimal("30")}]
|
||||
result = _client_with_rows(rows).query_stock(
|
||||
operation_id="op-case", external_org="HX-CN01",
|
||||
targets=[StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-1")])
|
||||
# [断言意图] 精确匹配下大小写/空格不同的键不命中(两侧路径同语义)。
|
||||
assert result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") is None
|
||||
assert result.lookup(material_no="m-1 ", from_warehouse="W-1", lot_no="l-1") == Decimal("30")
|
||||
@@ -0,0 +1,145 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_poll_resilience.py
|
||||
|
||||
用途:锁定 external-wait 轮询 Job 的异常韧性契约与库存回调的 Gate 锁序约定。
|
||||
依赖:pytest、shipping_process_gate handler、inventory_rpa_workflow、monkeypatch。
|
||||
逻辑:不依赖 DB。轮询异常时回滚并按 Gate 现状分流(waiting_external 延迟重排保持轮询链不断 /
|
||||
已收口则安静结束),绝不终态失败;回调侧 `_lock_process_gates_for_task` 必须锁活跃
|
||||
Execution 的全部 Gate 行且无 Execution 时不查询。
|
||||
背景:2026-09-23 test job 8818——轮询与库存 RPA 回调以相反顺序争抢 Gate/候选行,事务被
|
||||
毒化后以 InFailedSqlTransaction 终态失败,轮询链断裂(本次回调早到 400ms 自愈,
|
||||
若回调迟到则 run 将永久停在 external-wait)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def gate_job_env(monkeypatch):
|
||||
"""构造轮询 Job + Gate 的最小 handler 环境;返回各类捕获器。"""
|
||||
import app.jobs.handlers.shipping_process_gate as handler
|
||||
|
||||
job = SimpleNamespace(id=8818, attempts=1)
|
||||
gate = SimpleNamespace(id=10313, status='waiting_external', latest_attempt_id=7)
|
||||
finished: list[dict] = []
|
||||
failed: list[dict] = []
|
||||
scheduled: list[dict] = []
|
||||
|
||||
def _fake_get(model, _id):
|
||||
if model is handler.Job:
|
||||
return job
|
||||
if model is handler.ShippingProcessGate:
|
||||
return gate
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', _fake_get)
|
||||
monkeypatch.setattr(handler.db.session, 'rollback', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'current_app',
|
||||
SimpleNamespace(config={'SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS': 30}),
|
||||
)
|
||||
|
||||
def _finish(job_id, *, result, owned_attempt):
|
||||
finished.append({'job_id': job_id, 'result': result})
|
||||
|
||||
def _fail(job_id, *, error, result=None, retryable, owned_attempt):
|
||||
failed.append({'job_id': job_id, 'error': error, 'retryable': retryable})
|
||||
|
||||
def _schedule(*, attempt_id):
|
||||
scheduled.append({'attempt_id': attempt_id})
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', _finish)
|
||||
monkeypatch.setattr(handler, 'fail_job', _fail)
|
||||
monkeypatch.setattr(handler, 'schedule_waiting_external_poll', _schedule)
|
||||
return {
|
||||
'handler': handler,
|
||||
'job': job,
|
||||
'gate': gate,
|
||||
'finished': finished,
|
||||
'failed': failed,
|
||||
'scheduled': scheduled,
|
||||
}
|
||||
|
||||
|
||||
def _raise_poll(*_args, **_kwargs):
|
||||
raise RuntimeError('poisoned transaction: InFailedSqlTransaction')
|
||||
|
||||
|
||||
def test_poll_failure_while_waiting_external_requeues_chain(monkeypatch, gate_job_env):
|
||||
"""轮询异常且 Gate 仍在等待外部:回滚后延迟重排,轮询链不断,且不得终态失败。"""
|
||||
handler = gate_job_env['handler']
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_job_service.run_inventory_external_wait_poll',
|
||||
_raise_poll,
|
||||
)
|
||||
|
||||
handler.run_shipping_process_gate(
|
||||
SimpleNamespace(),
|
||||
{'external_wait_poll_gate_id': 10313, 'job_id': 8818},
|
||||
)
|
||||
|
||||
# 断言:以 waiting_external_requeued 成功收口并重排轮询链;绝不走 fail_job。
|
||||
assert len(gate_job_env['finished']) == 1
|
||||
result = gate_job_env['finished'][0]['result']
|
||||
assert result['status'] == 'waiting_external_requeued'
|
||||
assert 'InFailedSqlTransaction' in (result.get('poll_error') or '')
|
||||
assert gate_job_env['scheduled'] == [{'attempt_id': 7}]
|
||||
assert gate_job_env['failed'] == []
|
||||
|
||||
|
||||
def test_poll_failure_after_gate_resolved_ends_quietly(monkeypatch, gate_job_env):
|
||||
"""Gate 已被回调等其他路径收口(status=passed):安静结束,不再重排。"""
|
||||
handler = gate_job_env['handler']
|
||||
gate_job_env['gate'].status = 'passed'
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_job_service.run_inventory_external_wait_poll',
|
||||
_raise_poll,
|
||||
)
|
||||
|
||||
handler.run_shipping_process_gate(
|
||||
SimpleNamespace(),
|
||||
{'external_wait_poll_gate_id': 10313, 'job_id': 8818},
|
||||
)
|
||||
|
||||
# 断言:竞态输给回调时安静退出(poll_superseded),不重排、不失败。
|
||||
assert len(gate_job_env['finished']) == 1
|
||||
result = gate_job_env['finished'][0]['result']
|
||||
assert result['status'] == 'poll_superseded'
|
||||
assert result['gate_status'] == 'passed'
|
||||
assert gate_job_env['scheduled'] == []
|
||||
assert gate_job_env['failed'] == []
|
||||
|
||||
|
||||
def test_lock_process_gates_for_task_locks_active_execution_gates(monkeypatch):
|
||||
"""[锁序约定] 回调写候选前必须锁活跃 Execution 的全部 Gate 行;无 Execution 不查询。"""
|
||||
from app.services.shipping_notice import inventory_rpa_workflow as wf
|
||||
|
||||
calls: list[dict] = []
|
||||
|
||||
class _FakeQuery:
|
||||
def filter_by(self, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return self
|
||||
|
||||
def with_for_update(self):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return [SimpleNamespace(id=1), SimpleNamespace(id=2)]
|
||||
|
||||
monkeypatch.setattr('app.models.ShippingProcessGate', SimpleNamespace(query=_FakeQuery()))
|
||||
|
||||
task = SimpleNamespace(active_process_execution_id=516)
|
||||
wf._lock_process_gates_for_task(task)
|
||||
# 断言:按活跃 Execution 过滤并加锁。
|
||||
assert calls == [{'execution_id': 516}]
|
||||
|
||||
# 断言:无活跃 Execution(历史/已归档任务)直接跳过,不查询。
|
||||
calls.clear()
|
||||
wf._lock_process_gates_for_task(SimpleNamespace(active_process_execution_id=None))
|
||||
assert calls == []
|
||||
Reference in new issue
Block a user