Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-09-24 16:54:10 +08:00
commit 59b37422ab
113 files changed
+6036 -1759

No files matched your search

+114 -49
View File
@@ -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,
}
+1 -1
View File
@@ -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)
+3 -3
View File
@@ -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',
}),
}
+2 -2
View File
@@ -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',
+31 -31
View File
@@ -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}
@@ -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')
+141 -131
View File
@@ -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"
+1 -1
View File
@@ -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
@@ -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>&lt;Response&gt;&lt;ResponseContent&gt;&lt;Document&gt;"
"&lt;RecordSet id='1'&gt;&lt;Master name='img_file'&gt;"
"&lt;Record&gt;&lt;Field name='img01' value='M-1'/&gt;&lt;Field name='img02' value='W-1'/&gt;"
"&lt;Field name='img04' value='L-1'/&gt;&lt;Field name='img10' value='30'/&gt;&lt;/Record&gt;"
"&lt;Record&gt;&lt;Field name='img01' value='M-1'/&gt;&lt;Field name='img02' value='W-1'/&gt;"
"&lt;Field name='img04' value='L-2'/&gt;&lt;Field name='img10' value='40'/&gt;&lt;/Record&gt;"
"&lt;/Master&gt;&lt;/RecordSet&gt;"
"&lt;/Document&gt;&lt;/ResponseContent&gt;&lt;/Response&gt;"
"</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 == []
+53 -14
View File
@@ -1,24 +1,24 @@
# 在途仓自动调拨 Agent — 运行维护手册
> 状态:后端 Phase 0-4 已交付(领域/文件/预检/执行/排程/恢复/通知/归档/指标),前端实施中。
> 状态:后端 Phase 0-4 已交付(领域/文件/匹配/执行/排程/恢复/通知/归档/指标),前端实施中。2026-09-23 术语重构:precheck(预检)→ match(匹配),表/列/API/状态值全量更名,未上线无兼容层。
> 关联规格:[minimum-implementation-spec.md](./minimum-implementation-spec.md) · [TDD](./in-transit-transfer-tdd.md) · [PRD](./prd.md) · [路线图](./roadmap.md)
## 1. 架构概览
- **业务域**:`backend/app/services/in_transit_transfer/`(独立领域模块,不混入 shipping_notice 订单解析)。
- **执行边界**:收料来源实例(如 DBS-AWSBI / DBS-AWSSG / CRANE-SZ);DBS/Crane 仅分组。
- **真相源**:`TransferRun` / `TransferPrecheck` / `TransferInvoiceItem` / `TransferAttempt`(表:`transfer_*`,迁移 `it1a2b3c4d5e`)。
- **真相源**:`TransferRun` / `TransferMatching` / `TransferInvoiceItem` / `TransferAttempt`(表:`transfer_*`,迁移 `it1a2b3c4d5e`;术语重构迁移 `rn1a2b3c4d5e6`)。
- **外部系统访问唯一出口**:`capability_client.py`(`CapabilityClient.query_stock / create_transfer / verify_duplicate`);查询经集成连接器 CapabilityGateway 按 `in_transit_transfer.query_inventory` 能力批量调用(按 external_org 分组、targets = 料号+拨出库位+拨出批号 元组,`external_org` 取自仓库映射 `external_organization_code`);写路径在外部契约冻结前 fail-closed(`ExternalNotFrozenError`,Phase 2 接线)。
- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 收料文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。收料文件仓库列原值随明细落库于 `transfer_invoice_items.receipt_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / precheck_expired)。运维注意:来源的 movement 解析方案须把收料文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。
- **调拨业务类型(2026-09-22)**:`transfer_type.py` 定义三类——`in_transit_to_hub`(在途仓至HUB仓,一期唯一开放)、`hub_repair_out`(HUB仓维修出,占位)、`hub_to_hub`(HUB仓间调拨,占位)。类型决定预检收料数据范围:类型 1 仅纳入 INVOICE 前缀 `HOM/HOX/WTP`(大小写不敏感)的票,范围外票与收料日期过滤同语义静默排除;类型 2 规则已冻结(ODM ID=`HoxinRMA`)待收料文件解析层支持 `odm_id` 字段后启用,类型 3 规则待业务定义;占位类型被调用时 fail-closed(`TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED`)。类型随 Run 落库(`transfer_runs.transfer_type`,迁移 `tt3d4e5f6a7b`)并写入 `TransferPrecheck.scope_json`(含范围规则说明)参与预检 Hash;前端来源选择卡顶部选择(类型 2/3 禁用展示「即将上线」),异步预检 Job 从 scope_json 回读类型保证口径一致。
- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费预检/执行 Run/执行 Item 三类 Job。
- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 收料文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。收料文件仓库列原值随明细落库于 `transfer_invoice_items.receipt_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / `matching_expired`)。运维注意:来源的 movement 解析方案须把收料文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。
- **调拨业务类型(2026-09-22)**:`transfer_type.py` 定义三类——`in_transit_to_hub`(在途仓至HUB仓,一期唯一开放)、`hub_repair_out`(HUB仓维修出,占位)、`hub_to_hub`(HUB仓间调拨,占位)。类型决定匹配收料数据范围:类型 1 仅纳入 INVOICE 前缀 `HOM/HOX/WTP`(大小写不敏感)的票,范围外票与收料日期过滤同语义静默排除;类型 2 规则已冻结(ODM ID=`HoxinRMA`)待收料文件解析层支持 `odm_id` 字段后启用,类型 3 规则待业务定义;占位类型被调用时 fail-closed(`TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED`)。类型随 Run 落库(`transfer_runs.transfer_type`,迁移 `tt3d4e5f6a7b`)并写入 `TransferMatching.scope_json`(含范围规则说明)参与匹配 Hash;前端来源选择卡顶部选择(类型 2/3 禁用展示「即将上线」),异步匹配 Job 从 scope_json 回读类型保证口径一致。
- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费匹配/执行 Run/执行 Item 三类 Job。
- **排程**:`in-transit-receipt-file`(08:00)与 `in-transit-transfer`(09:00)platform job(`schedule/job_registry.py`)。
## 2. 数据库
- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`);后续 `it2c3d4e5f6a7_add_in_transit_warehouse_code.py` 为 `transfer_invoice_items` 追加 `receipt_warehouse_code`(收料仓库匹配键);`tt3d4e5f6a7b_add_transfer_runs_transfer_type.py` 为 `transfer_runs` 追加 `transfer_type`(调拨业务类型,带检查约束)。
- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`);后续 `it2c3d4e5f6a7_add_in_transit_warehouse_code.py` 为 `transfer_invoice_items` 追加 `receipt_warehouse_code`(收料仓库匹配键);`tt3d4e5f6a7b_add_transfer_runs_transfer_type.py` 为 `transfer_runs` 追加 `transfer_type`(调拨业务类型,带检查约束);`rn1a2b3c4d5e6_rename_transfer_precheck_to_match.py`(down_revision=`43a8179cdd88`)为术语重构迁移——表 `transfer_prechecks`→`transfer_matchings`、列 `precheck_no/precheck_hash/precheck_id`→`matching_no/matching_hash/matching_id`、状态值 `prechecking`→`matching`(13 状态中仅此一个更名)、约束/索引同步改名,未上线直改无兼容层。
- 部署:`cd backend && flask db upgrade`(PostgreSQL)。回滚:`flask db downgrade <上一revision>`。
- 表:transfer_runs / transfer_source_jobs / transfer_prechecks / transfer_invoice_items / transfer_attempts / transfer_audit_events / transfer_archives。
- 表:transfer_runs / transfer_source_jobs / transfer_matchings / transfer_invoice_items / transfer_attempts / transfer_audit_events / transfer_archives。
- 审计表只追加(ORM 门禁 + 前端禁止删除);大对象归档 MinIO(transfer_archives 记录 provider/bucket/key/sha256)。
## 3. 环境变量(⑨业务模块区;凭据只由环境/Secret 注入)
@@ -26,7 +26,7 @@
| 变量 | 默认 | 说明 |
| --- | --- | --- |
| `IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY` | 2 | 来源并发 |
| `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` | 600 | 确认有效期(10 分钟) |
| `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` | 600 | 行级新鲜度 TTL(10 分钟;按行执行门禁②:行 `updated_at` 距 now 超时拒绝执行) |
| `IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS` | 3 | 老化预警阈值 |
| `IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS` | 5 | 老化升级阈值 |
| `IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS` | 7 | 老化严重阈值 |
@@ -43,19 +43,47 @@
| Method | Path | 说明 |
| --- | --- | --- |
| POST | `/prechecks` | 创建预检(只读;可选 `transfer_type`,缺省 `in_transit_to_hub`) |
| GET | `/prechecks/{id}` | 预检进度恢复 |
| POST | `/prechecks/{id}/execute` | 确认范围并直接生成执行 Run |
| POST | `/matchings` | 创建/复用一次调拨匹配(只读,不写 ERP;body `source_codes` 必填,可选 `business_date`/`receipt_date_from`/`receipt_date_to`/`transfer_type`,缺省 `in_transit_to_hub`;响应含 matching_id/hash/计数/来源进度) |
| GET | `/items/executable` | 可调拨明细:全局 ready_to_execute 行队列(业务稳定排序=收料日期→Invoice→created_at;行含 item_id/checked_at/stale/file_current),勾选后 POST `/items/execute` 按行生成调拨单 |
| GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`,counts 实时聚合) |
| POST | `/matchings/{no}/items/requery` | 按 matching_no 批量重查 ERP 库存(可恢复阻断行;body 可选 `invoice_nos` 限定范围) |
| POST | `/sources/receipt-files` | 按选中来源打包下载各自最新归档收料文件 zip(下载留审计) |
| GET | `/runs/{run_no}` | Run 结果(按 ERP 单号聚合 + 未生成单据异常) |
| POST | `/runs/{run_no}/cancel` | 请求停止剩余任务(原因必填) |
| POST | `/items/{id}/retry` | 人工重试(external_recheck,新 Attempt) |
| POST | `/items/{id}/manual-close` | 人工关闭(原因必填) |
| POST | `/items/execute` | 按行执行调拨(body `{"item_ids":[..]}`;三层门禁:行级新鲜度 TTL / 文件版本对账 / 写前复查;错误码 `TRANSFER.EXECUTE_ITEMS_INVALID` / `TRANSFER.ITEMS_STALE` / `TRANSFER.FILE_CHANGED`;Run 留痕不绑匹配) |
| POST | `/items/batch-requery` | 批量重查库存=恢复处理(body `item_ids`;单行隔离,逐行 external_recheck) |
| POST | `/items/batch-manual-close` | 批量人工关闭(body `item_ids` + `reason`;单行隔离) |
| GET | `/runs/{run_no}/exceptions.xlsx` | 七 Sheet 异常 Excel(下载留审计) |
| GET | `/runs/{run_no}/receipt-files` | 收料来源文件 zip(下载留审计) |
| GET | `/runs/{run_no}/external-inventory` | 预检冻结外部系统库存表 csv(下载留审计) |
| GET | `/runs/{run_no}/external-inventory` | 匹配冻结 ERP 库存表 csv(下载留审计) |
| GET | `/metrics` | 调拨运营指标(成功率/失败类型/待处理老化/通知失败) |
| GET | `/sources` | 来源实例列表(附收料文件状态 ready/fetching/failed/expired/none + has_ready_file,供前端门禁) |
| POST | `/sources/{source_code}/retry-rpa` | 对指定来源重新触发一次收料 RPA 抓取(配置缺失 fail-closed ok=False) |
| GET | `/backlog` | 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级;查看留审计) |
| GET | `/backlog/summary` | 待处理异常汇总(含 3/5/7 天老化分级) |
> 已删除路由:`/prechecks`、`/prechecks/{id}` 等 precheck 路由全量下线,`/items/batch-resume` 随恢复处理改版删除,均无兼容层。
权限:admin 或持有 `in_transit_transfer` Agent 权限;无权限 403。
### 4.1 行归属与执行语义(2026-09-23 修订:行不迁移;术语 precheck→match 全量更名)
- **主叙事**:库存匹配(动作,首页「库存匹配」卡发起)→ 可调拨清单(匹配结果的实时视图,勾选)→ 生成调拨单(按行执行);匹配不上的行进入待恢复异常(恢复处理=行级重查)。
- **行不迁移(行归属与匹配解耦)**:`TransferInvoiceItem.matching_id` 仅记录首次评估建行时的匹配。后续对同一 scope 的重复匹配/重查对既有行**原地刷新**(不迁移 `matching_id`),并刷新 `updated_at` 续行级新鲜度;终态行(success / duplicate_success / manually_closed / cancelled / executing)不迁移、不复活。同一批行可同时被多份同 scope 匹配看到,不存在"行被掏空/迁走",也不依赖两份匹配的执行集合互斥来防重(防重由三层门禁 + ERP Invoice 幂等键承担)。
- **匹配 = 评估留痕**:匹配记录(表 `transfer_matchings`,单号 `matching_no` 前缀 `MTG-` 由 `_generate_no` 生成)固化 scope(来源 / 收料日期区间 / 调拨类型)、counts、收料文件快照与 `matching_hash` 作为**评估留痕**;hash 与 `expires_at` **不拦截执行**(仅展示)。匹配卡与 `GET /matchings/{id}` 是 scope 的**实时视图**:按 scope 重新圈行并逐行装饰 `checked_at`(库存查询时刻)/ `stale`(新鲜度)/ `file_current`(文件版本对账),counts 亦为 scope 实时聚合(不读 counts_json 快照)。
- **执行 = 按行 + 三层门禁**:`POST /items/execute` 按 `item_ids` 执行,Run 留痕不绑匹配;手工执行与自动排程共用同一入口。三层门禁任一不过 fail-closed(ERP 写入为 0):
| 门禁 | 防什么 | 机制 | 失败表现 |
| --- | --- | --- | --- |
| ① 行级新鲜度 TTL | 时间漂移 | 行 `updated_at` 距 now 超过 `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` 拒绝 | `TRANSFER.ITEMS_STALE`(`details.stale_item_ids`) |
| ② 文件版本对账 | 文件漂移 | 行评估版本戳(file_sha256)≠ 来源最新可用文件 sha(含来源无可用文件 / 行无版本戳)即拒绝;评估后被更新版本文件取代而**消失的 ready 行**在匹配/重查时标 `blocked_file_removed` 入异常池(fail-closed,宁可误拒也不按过期文件写 ERP) | `TRANSFER.FILE_CHANGED`(`details.changed_item_ids`) |
| ③ 写前复查 | ERP 漂移 | 逐行重查库存 + 按收料仓库列重解析路由;库存变化/路由失败标记该行 `matching_expired` 阻断(单项失败不阻断其他行) | 行级 `matching_expired`(不整批失败) |
门禁前置校验:id 不存在或非 `ready_to_execute` → `TRANSFER.EXECUTE_ITEMS_INVALID`(`details.invalid_item_ids`)。
- **恢复处理 = 行级重查**:待处理池「恢复处理」= 对选中行逐行 external_recheck(`POST /items/batch-requery`)**原地刷新 + 续新鲜度**,不创建匹配、不迁移行,单行隔离;ERP 事实修正后重查通过即回到可执行。按组重建范围匹配的 `POST /items/batch-resume` 与 `resume_service` 已删除,无兼容层。
## 5. 部署
```bash
@@ -65,7 +93,7 @@ cd backend && flask db upgrade
# command: python workers/worker_in_transit_transfer.py,环境同后端)
```
上线灰度顺序(路线图 §8.6):ERP 测试组织 UAT → 生产只读观察(预检、写=0)→ 小范围对话写入试点 → 正式对话写入 → 单来源自动排程 → 全部来源自动排程;每步留启用人/时间/配置版本/门禁结果/回退条件审计。
上线灰度顺序(路线图 §8.6):ERP 测试组织 UAT → 生产只读观察(匹配、写=0)→ 小范围对话写入试点 → 正式对话写入 → 单来源自动排程 → 全部来源自动排程;每步留启用人/时间/配置版本/门禁结果/回退条件审计。
## 6. 告警与运维关注点
@@ -75,6 +103,17 @@ cd backend && flask db upgrade
- 外部系统查询超时率与 `ExternalNotFrozenError` 出现(说明契约/配置未冻结或 endpoint 缺失)。
- 归档 Hash 复核(`verify_archive_hash`)与 MinIO 容量。
### 6.1 批量库存查询对账结论(2026-09-23)
- **现象**:对话侧库存答复为 0,与 ERP 账套内真实库存(30/40/36)不一致,触发批量查询对账排查。
- **根因**:收料仓库映射行曾指向**错误的 ERP 组织账套 TGHX**;2026-09-23 00:52 修正为 TGHX1 后重查得到真实库存 30/40/36。关键证据来自 `integration_calls` 落库:call_id 12/13(TGHX 账套)仅返回 2 条 Record 且 `img10=0`;call_id 163(TGHX1 账套)返回 30/40/36——查询链路本身无丢数/改数,差异完全由账套路由错误造成。
- **WTP26060612**:在 TGHX1 亦真实查无,属真实业务答复,非缺陷。
- **顺带修复**:`integration_connector/mapping.py` 记录扇出(fan-out)在嵌套形态下丢行的潜在缺陷已修复(该嵌套形态尚未在生产数据中观测到,属防御性修复)。
- **待确认清单(移交 ERP/业务)**:
- `img10` vs `img11` 字段语义(在库 vs 可用):当前取 `img10`;若业务口径应为 `img11`(可用量),仅需管理端调整映射配置,无需改代码。
- 批量 targets 跨 Invoice 未去重的双计风险:同一料号+库位+批号被多张 Invoice 共用时 targets 重复,建议在 `matching_service` 侧去重。
- 组织账套白名单与变更审计:仓库映射的 `external_organization_code` 建议增加账套白名单校验与变更审计,避免再次静默指向错误账套。
## 7. 归档与数据保留
- 大型快照/Excel/报文经 `archive.py` 归档 MinIO,`transfer_archives` 索引+Hash 留库;归档必须重算 Hash 并写审计。
@@ -82,7 +121,7 @@ cd backend && flask db upgrade
## 8. 回退策略
- 停用 `in-transit-transfer` 自动排程(不删除历史 Run);保留对话只读预检与手工执行。
- 停用 `in-transit-transfer` 自动排程(不删除历史 Run);保留对话只读匹配与手工执行。
- `result_unknown` 继续进入人工核实池;已成功 ERP 单据不自动撤销。
- 回退配置走新发布版本 + Diff 审计,不直接改数据库。
@@ -76,6 +76,7 @@
- “保存订单并校验”是唯一确认入口。后端先保存 Draft,再在同一业务链路重新计算必填、证据、冲突、重复、客户确认和自动建单策略门禁;只有 `auto_create_enabled=true` 且全部自动建单门禁通过时,才返回 `can_auto_create=true` 并进入建单,否则返回稳定阻断原因及可执行的 Review 动作。
- **显式校验幂等短路 + STP Job 串行化(2026-09-22)**:STP 自动建单持有草稿(等待入队/排队/执行)且内容相对最近一次校验未变(`validation_result_json.content_checksum` 比对)时,重复“保存并校验”幂等短路——不递增 `draft_version`、不写 `draft_validated` 事件、不重复入队。背景:连点保存曾产生版本/Job 风暴,同文档两个 STP Job 并发在建单 advisory 锁上死锁且 `max_attempts=1` 一次判死(case 永久停在 ready)。配套修复:`ensure_stp_auto_create_for_case` 入队前作废同文档旧版本 queued Job(running 由执行期“新版替代”检查收口);STP Job `max_attempts` 1→3,死锁类瞬时失败在 attempts 耗尽前自动重排,业务阻断仍 `retryable=false` 收口为“等待用户选择下一步动作”。自动化持有期间前端复核表单只读,与后端 `_locked_case` 的 `SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION` 同义。
- **抽取交接不变量:STP 只由最后一个抽取 Job 入队(2026-09-22 第二轮)**:多附件 EML 版面分批就绪时,交接 Job 与续抽 Job 同 commit 入队并被双 worker 并发执行,抽取链(持 run 锁→锁 intake)与 STP 确认链(持 intake→进度写锁 run)以相反顺序形成**结构性死锁**(`SNER-20260922-6466EB53` 整 run 卡死、附件滞留识别;同日 `879785D1` 的 STP 死锁同族)。修复:①`submit_order_extraction_unit_result` 增加 `defer_stp_enqueue`——Worker 开工快照仍有待排版附件(`pending_layout_ids` 非空、必交接)时跳过本 Unit 的 STP 入队,Candidate/Review Case 仍即时物化,STP 统一由最后一个抽取 Job 的 run 收口(`submit_order_extraction_run_result`)与 run 状态同事务入队,时序上消除抽取∥STP 并发;②收口前重放推送失败必须冒泡(原 try/except 吞错不回滚,会把真实死锁伪装成 `InFailedSqlTransaction` 并静默丢单),删除吞错让异常走外层收口;③外层收口对瞬时锁错(SQLSTATE 40P01 死锁 / 55P03 锁超时)标记 `retryable=true`,队列在 attempts 耗尽前自动重排(requeue 状态为 queued,`sync_order_extraction_run_after_job_failure` 的终态守卫保证不会误收口 run),attempts 耗尽仍终态失败等人工。残余概率性锁对(版面收尾×抽取、复核编辑×后台确认)由③兜底为秒级自愈。
- **库存回调×external-wait 轮询锁序约定(2026-09-23,test job 8818)**:库存 RPA 回调与 external-wait 轮询曾以相反顺序争抢 Gate 行与库存候选行(回调=先写候选后更 Gate;轮询=先锁 Gate 后读候选),轮询事务被毒化后以 `InFailedSqlTransaction` 终态失败、轮询链断裂(本次回调早 400ms 自愈,否则 run 永久停在 external-wait)。根治:回调侧写候选前先锁活跃 Execution 的全部 Gate 行(`_lock_process_gates_for_task`,批量与单任务两个入口统一),两侧在 Gate 锁上串行、环消失;防御:`shipping_process_gate` 轮询分支增加异常韧性——异常回滚后按 Gate 现状分流(仍 `waiting_external` 则以 `waiting_external_requeued` 收口并延迟重排保持轮询链不断;已被收口则 `poll_superseded` 安静结束),错误文本留在 `result_json.poll_error` 供排查,轮询 Job 永不终态失败。
- Review Gate 或字段冲突发生变化时,即使生命周期 `stage/status` 不变,也必须递增 `progress_version` 并写入对应审计事件。Review 工作台、聊天投影和任务详情均按该版本刷新,禁止以前端旧 Projection 推导按钮。
- 上传成功(人工确认或 RPA 回调)必须统一清除历史上传阻断原因并收口正式 Execution 的履约 Gate;Notice 面成功词唯一为 `uploaded`(经 `project_notice_upload_status`;Attempt 库内仍写 `succeeded`)。业务完成用 `has_verified_upload_success`;`facts.upload_state` 成功词为 `succeeded`(`project_facts_upload_state`)。禁止调用方再读 Attempt 原词或扩同义词集合。
- `resolve_field_conflicts` 仅在当前 Case 仍存在开放字段冲突时展示;Case 已无开放冲突时,旧 Projection 中残留的该动作必须被前端隐藏,同时以后端 `ui_state.actions` 为最终动作契约。
+9 -5
View File
@@ -757,13 +757,17 @@
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | ackend/app/models/in_transit_transfer.py(Run/SourceJob/Precheck/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e;13 状态服务端门禁(services/in_transit_transfer/status.py) |
| 收料文件准备与只读预检 | 后端已实现 | ready 复用/缺文件按来源触发收料 RPA/来源隔离/字段校验/D+1/Invoice 多行汇总+原始行追溯/ERP 库存查询/严格数量匹配/预检快照 Hash/进度恢复 |
| 确认与 ERP 原子调拨 | 后端已实现 | 直接生成执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按 ERP 单号聚合结果(ERP SOAP 实现在 WSDL 冻结前 fail-closed) |
| 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | backend/app/models/in_transit_transfer.py(Run/SourceJob/Matching/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e / rn1a2b3c4d5e6(precheck→match 术语改名);13 状态服务端门禁(services/in_transit_transfer/status.py) |
| 收料文件准备与只读匹配(原"预检") | 后端已实现 | ready 复用/缺文件按来源触发收料 RPA/来源隔离/字段校验/D+1/Invoice 多行汇总+原始行追溯/ERP 库存查询/严格数量匹配/匹配快照 Hash/进度恢复 |
| 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行生成执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按 ERP 单号聚合结果(ERP SOAP 实现在 WSDL 冻结前 fail-closed) |
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) |
| 调拨业务类型 | 后端已实现(类型2/3占位) | 三类型:在途仓至HUB仓(一期开放,仅纳入 INVOICE 前缀 HOM/HOX/WTP 的票)/HUB仓维修出(占位,规则 ODM ID=HoxinRMA 待文件层支持 odm_id)/HUB仓间调拨(占位);类型随 Run 落库并入预检 Hash,占位类型 fail-closed;前端来源选择卡选择(占位类型禁用) |
| 调拨业务类型 | 后端已实现(类型2/3占位) | 三类型:在途仓至HUB仓(一期开放,仅纳入 INVOICE 前缀 HOM/HOX/WTP 的票)/HUB仓维修出(占位,规则 ODM ID=HoxinRMA 待文件层支持 odm_id)/HUB仓间调拨(占位);类型随 Run 落库并入匹配 Hash,占位类型 fail-closed;前端来源选择卡选择(占位类型禁用) |
| 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md |
| 前端 Chat 卡片/结果页与四语言 | 实施中 | `frontend/src/features/chat/` 卡片(文件进度/预检/结果/待处理)与 admin 模块按计划实施 |
| 可调拨明细与待办看板首页 | 已实现 | 首页上区「库存匹配」动作卡 + 待办看板四队列:可调拨明细(GET /items/executable 全局可执行行,勾选按行生成调拨单)/待恢复异常/已人工关闭/结果未知;「最近匹配」(原"最近预检")已移除(行不迁移后匹配卡=范围实时视图,多份同 scope 匹配属重复窗口) |
| 待处理池批量操作与恢复处理 | 已实现 | 批量重查(恢复处理=行级重查原地刷新+续新鲜度)/批量关闭;blocked_file_removed 消失行 fail-closed 入异常池;匹配=评估留痕,行不迁移 |
| 按行执行与三层执行门禁 | 已实现 | execute(item_ids):行级新鲜度 TTL + 文件版本对账 + 写前复查;Run 留痕不绑匹配;确认 TTL/hash 拦截退役(hash 留痕) |
| 收料日期默认与输入期限制 | 已实现 | 来源选择卡收料日期默认 D+1 规则日期(上海业务日 T-1);日期输入 max/min 即时限制 + 起止非法行内提示禁用确认(后端 RECEIPT_DATE_RANGE_INVALID 卡控保留双保险);「直接生成调拨单」改名「生成调拨单」 |
| 前端 Chat 卡片/结果页与四语言 | 实施中 | `frontend/src/features/chat/` 卡片(文件进度/匹配/结果/待处理)与 admin 模块按计划实施 |
---
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,297 @@
# 在途调拨「行归属解耦」实施计划(预检降级为评估留痕 + 按行执行 + 三层执行门禁)
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 把在途调拨的核心真相源从"预检容器"迁移到"发票行"——行永不迁移、预检降级为评估留痕与范围视图、执行按行发起并带三层门禁(行级新鲜度 / 文件版本对账 / 写前复查)、恢复处理收敛为行级重查;前端三区结构(首页待办入口 / 预检卡 / 待处理异常)保持不变只换接线。
**Architecture:** 发票行(TransferInvoiceItem,业务键 = 来源+Invoice+料号+收料日期)是唯一真相源,预检/重查只原地刷新行并留痕;预检记录(TransferPrecheck)保留为评估日志(scope/counts/文件快照/expires_at 仅展示,hash 照算留痕不再拦执行);预检卡 = 按预检 scope 的行实时视图;执行从"绑定预检"改为"按行执行"(Execute items),由行级新鲜度、文件版本对账、写前复查三层门禁兜底;恢复处理 = 批量行级重查(不建预检、不迁移)。
**Tech Stack:** Flask + SQLAlchemy 2.0(后端)、Vue 3 + TS + Vitest(前端)、pytest(后端)。零数据库迁移(复用既有列与 JSON 字段)。
**Spec:** 本计划实现 2026-09-23 与用户确认的设计(对话定稿):前端三区保留;行不迁移;预检=评估留痕+范围视图;执行=按行+三层门禁(TTL 保留、hash 留痕不拦执行、文件版本对账新增);恢复=行级重查;「文件已移除」fail-closed 规则;库存列带查询时刻。权威文档落点:`docs/features/in-transit-transfer/technical.md` §4.1(完成后更新)。
## Global Constraints
- 🚫 禁止自动 `git commit`:所有任务以 `git add`(stage)结束,提交须用户明确批准。
- 🧬 零数据库迁移:不得新增/修改列与约束;行级文件版本戳写入既有 `raw_lines_json`(JSON 列)条目内;行新鲜度复用 `updated_at`。
- 🔒 不得改动 ERP 写路径语义:`_write_item` 的写前复查 + 原子建单 + 幂等逻辑保持原样。
- 🌍 前端新增/改动文案必须同步四语言(zh-CN / zh-TW / en / th 的 `chat.json` 与 `errors.json`);i18n 占位符只用 `{name}` 形式。
- 📡 JSON POST 必须带 `Content-Type: application/json`(`transfer.api.ts` 的 `jsonHeaders` 模式)。
- ✅ 每个任务结束必须通过:`cd backend && python -m pytest tests/services/in_transit_transfer -q` 全绿;前端任务另须 `npm run build` + 相关 vitest 全绿。
- 后端测试命令统一:`cd D:/Workspace/HxProjects/hxops/backend && (source venv/Scripts/activate 2>/dev/null || source venv/bin/activate 2>/dev/null); python -m pytest ...`。
- 术语:`blocked_recoverable`=可恢复异常;`ready_to_execute`=可执行;TTL=`deps.strategy.confirm_ttl_seconds`(默认 600s);"评估"=预检或行级重查。
---
## File Structure(改动全景)
```
backend/app/services/in_transit_transfer/
precheck_service.py # 改:create_precheck 行原地刷新(不迁移)+ 文件版本戳 + 消失行标记;
# restore_precheck 改按 scope 查行 + 计数实时聚合 + 行装饰字段;
# list_recent_prechecks 改按 scope 实时聚合
transfer_type.py # 改:导出 invoice_in_scope(invoice_no, transfer_type)(复用既有前缀常量)
execution_service.py # 改:删除 execute_precheck;新增 execute_items(三层门禁)+ 按行建 Run
retry_service.py # 改:_recheck_item 显式刷新 updated_at(续新鲜度)
resume_service.py # 删除(恢复处理收敛为 batch-requery)
serializers.py # 改:serialize_item 增 item_id/checked_at/stale/file_current
backend/app/api/in_transit_transfer.py
# 改:+POST /items/execute;-POST /items/batch-resume;
# execute 路由改调 execute_items;restore 传 deps
backend/app/services/in_transit_transfer/chat_actions.py
# 改:TransferExecuteAction 改调 execute_items
backend/tests/services/in_transit_transfer/
test_precheck_inplace.py # 新建(Task 1)
test_restore_scope.py # 新建(Task 2)
test_execute_items.py # 新建(Task 3,承接原 test_execution_service 用例)
test_resume_service.py # 删除(Task 4)
test_recent_prechecks.py # 改(Task 1,scope 语义)
test_execution_service.py# 删除/迁移(Task 3)
test_batch_actions.py # 改(Task 4,新鲜度断言)
backend/tmp/diag_stock_batch.py # 新建(Task 6 探针,仿 diag_precheck_empty.py)
frontend/src/features/chat/
api/transfer.api.ts # 改:+executeTransferItems;-batchResumeTransferItems
types/transfer.types.ts # 改:TransferPrecheckItem +item_id/checked_at/stale/file_current
composables/useChatTransfer.ts # 改:execute 按 item_ids;selected 改 Set<number>;resume=requery
components/messages/TransferMessageView.vue # 改:execute/resume 接线
components/messages/TransferPrecheckCard.vue # 改:勾选/执行按 item_id;库存列查询时刻+过期置灰
components/messages/TransferBacklogSummaryCard.vue # 改:blocked_file_removed 结果徽标
frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json + errors.json # 改(新增/删除键,见 Task 5)
docs/features/in-transit-transfer/technical.md + docs/funclist.md # 改(Task 7)
```
---
### Task 1: 行原地刷新(预检不再迁移行)+ 文件版本戳 + 消失行标记
**Files:**
- Modify: `backend/app/services/in_transit_transfer/precheck_service.py`(create_precheck 的 upsert 段,约 562-616 行;list_recent_prechecks 的归属聚合)
- Modify: `backend/app/services/in_transit_transfer/transfer_type.py`(导出范围谓词)
- Create: `backend/tests/services/in_transit_transfer/test_precheck_inplace.py`
- Modify: `backend/tests/services/in_transit_transfer/test_recent_prechecks.py`
**Interfaces:**
- Produces: `transfer_type.invoice_in_scope(invoice_no: str, transfer_type: str) -> bool`(Task 2 的 scope 查询复用)
- Produces: 行 `raw_lines_json` 条目新增键 `file_sha256: str`(Task 2/3 的文件对账读取:`item.raw_lines_json[0].file_sha256`,帮助函数 `_item_evaluated_sha(item) -> str | None` 定义在 precheck_service)
- Produces: `scope_item_query(precheck) -> BaseQuery`(按 precheck.scope_json 查行:source_codes + receipt_date 区间 + transfer_type 前缀过滤;Task 2 restore 复用)
- [ ] **Step 1: 写失败测试**(新建 `test_precheck_inplace.py`,复用 `tests/services/in_transit_transfer/repo_fakes.make_transfer_deps` 与根 conftest 的 `dbs_ready_file`/`transfer_db` 夹具,写法参照现有 `test_backlog_service.py`):
```python
def test_reprecheck_refreshes_rows_in_place(transfer_db, dbs_ready_file):
"""第二次预检:同一物理行原地刷新(id 不变、precheck_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_precheck(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_precheck_id, old_updated = row.id, row.precheck_id, row.updated_at
second = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
db.session.refresh(row)
assert row.id == old_id # 不新建行
assert row.precheck_id == old_precheck_id # 不迁移归属
assert row.updated_at > old_updated # 显式续新鲜度
# 两份预检记录都存在(评估留痕),且最近预检按 scope 聚合都看到同一行
assert first.precheck_id != second.precheck_id
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")
create_precheck(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"
# 新文件版本:内容只剩 HOX-002(HOM-001 消失),checksum 变化
new_file = {**dbs_ready_file, "file_version": "v4", "checksum": "e" * 64,
"rows": [r for r in dbs_ready_file["rows"] if r["doc_no"] != "HOM-001"]}
deps2, _, _ = make_transfer_deps(new_file)
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2)
db.session.refresh(hom)
assert hom.status == "blocked_recoverable"
assert hom.result_code == "blocked_file_removed"
# blocked 行(本例无)与未知评估版本的行不被误标——由其余用例覆盖
def test_file_removed_skips_unknown_evaluated_version(transfer_db, dbs_ready_file):
"""行上无 file_sha256(历史数据)时不误标 file_removed。"""
# 先造 ready 行,再手工清空 raw_lines_json 的 file_sha256 模拟存量,重跑新版本预检
```
- [ ] **Step 2: 运行确认失败**:`python -m pytest tests/services/in_transit_transfer/test_precheck_inplace.py -q` → FAIL(现状会迁移行/不标 file_removed)。
- [ ] **Step 3: 实现**(precheck_service.py):
1. `transfer_type.py`:把类型 1 的 Invoice 前缀判断抽成 `def invoice_in_scope(invoice_no, transfer_type) -> bool`(复用模块内既有前缀常量 HOM/HOX/WTP;占位类型恒 False)。
2. `create_precheck` upsert 循环改为原地刷新:`fields` 字典**删除** `"precheck_id"` 键;对 `existing` 刷新业务字段后**显式** `existing.updated_at = now`;`raw_lines_json` 每条 line 追加 `"file_sha256": stage.checksum`(stage 来自 `result.sources` 中该 source 的阶段对象,checksum 与 file_snapshot 同源);新建行同样带 `file_sha256`。
3. 循环后新增"消失行标记":对每个有文件的 source,查该 source 下 `status == ready_to_execute`、`receipt_date` 在本次范围(from/to 有值时)内、且 `_item_evaluated_sha(item)` 非空并不等于本次 checksum 的行 → `status=blocked_recoverable, result_code="blocked_file_removed", result_message="receipt row removed from latest file"`(帮助函数 `_item_evaluated_sha(item)`:`item.raw_lines_json[0].get("file_sha256")`,空列表/缺键返回 None)。
4. `list_recent_prechecks` 的 `item_agg` 从"按 precheck_id 分组"改为"按 scope 聚合":新增模块级 `scope_item_query(precheck)`(`TransferInvoiceItem.source_code.in_(scope sources)` + receipt_date 字符串区间过滤 + `invoice_in_scope(invoice_no, transfer_type)`);recent 对最近 N 条记录逐条用 `scope_item_query` 实时计数(N≤50,性能可接受),过滤条件改为"实时 executable_count > 0 或 status='prechecking'"(删除 confirmed_at/expires 过滤——执行不再绑定预检)。
- [ ] **Step 4: 跑测试**:`test_precheck_inplace.py` PASS。
- [ ] **Step 5: 修复受迁移语义影响的既有用例**:`test_recent_prechecks.py::test_recent_excludes_emptied_precheck_after_reprecheck` 改为 scope 语义(行不迁移后两份预检的 scope 计数相同 → 用"第二份预检记录有可执行行、列表仍只列可执行>0"断言替代"掏空"断言);全量跑 `tests/services/in_transit_transfer -q`,凡断言"行迁移/旧卡掏空"的用例按新语义改写(预期涉及 test_precheck_service 幂等段若干用例)。
- [ ] **Step 6: 全绿后 stage**:`git add backend/app/services/in_transit_transfer/precheck_service.py backend/app/services/in_transit_transfer/transfer_type.py backend/tests/services/in_transit_transfer/`
---
### Task 2: 预检卡改范围实时视图(restore 按 scope 查行 + 行装饰字段)
**Files:**
- Modify: `backend/app/services/in_transit_transfer/precheck_service.py`(restore_precheck)
- Modify: `backend/app/services/in_transit_transfer/serializers.py`(serialize_item 增字段)
- Create: `backend/tests/services/in_transit_transfer/test_restore_scope.py`
**Interfaces:**
- Consumes: Task 1 的 `scope_item_query(precheck)`、`_item_evaluated_sha`
- Produces: `restore_precheck(precheck_id, *, deps=None, now=None)`(deps 缺省时内部取 `deps.get_transfer_dependencies()`);返回 items 的每行新增:`item_id: int`、`checked_at: str|None`(updated_at isoformat)、`stale: bool`(now - updated_at > TTL)、`file_current: bool`(行评估 sha == 该来源当前最新可用文件 sha;来源无可用文件 → False)。`PrecheckInvoiceItemDTO` 同步加这四个字段;`serialize_item` 输出同步。
- [ ] **Step 1: 写失败测试**(`test_restore_scope.py`):
```python
def test_restore_returns_scope_rows_not_owned_rows(transfer_db, dbs_ready_file):
"""restore 按范围返回实时行:行属于首份预检,但第二份预检的 restore 也能看到(实时状态)。"""
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_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) # 行建在此预检
second = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
detail = restore_precheck(second.precheck_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")
assert row.item_id > 0 and row.stale is False and row.file_current is True
def test_restore_marks_stale_beyond_ttl(transfer_db, dbs_ready_file):
"""行 updated_at 早于 TTL → stale=True(TTL 取 deps.strategy.confirm_ttl_seconds)。"""
# 建预检后手工把 item.updated_at 拨回 11 分钟前,restore 断言 stale is True
```
- [ ] **Step 2: 确认失败**(现状 restore 读 `precheck.items` 关系,第二份预检 items 为空 → FAIL)。
- [ ] **Step 3: 实现**:restore_precheck 加 `deps/now` 参数;items 改为 `scope_item_query(precheck).order_by(...).all()`;按 scope 内去重后的 source 逐个调 `resolve_source_file_status(source_code=...)` 建映射,逐行装饰四字段(`file_current = bool(evaluated_sha) and evaluated_sha == latest_sha`;来源无可用文件 → False;`stale = (now - item.updated_at).total_seconds() > deps.strategy.confirm_ttl_seconds`);counts 用 scope 行实时聚合(executable/blocked/not_matured/total→file_invoice_count),`estimated_*` 与 `expires_at` 沿用预检记录(留痕展示);`serialize_item` 增加 `item_id/checked_at/stale/file_current`。注意 API 层 `get_precheck_api` 调用处传 `deps=transfer_deps.get_transfer_dependencies()`。
- [ ] **Step 4: 跑测试** PASS;全目录回归(chat_actions 里 `restore_precheck(summary.precheck_id)` 调用需同步传 deps 或用缺省)。
- [ ] **Step 5: stage**。
---
### Task 3: 按行执行 execute_items(三层门禁)+ 路由 + chat action;hash/expires 门禁退役
**Files:**
- Modify: `backend/app/services/in_transit_transfer/execution_service.py`
- Modify: `backend/app/api/in_transit_transfer.py`(路由替换)
- Modify: `backend/app/services/in_transit_transfer/chat_actions.py`
- Delete: `backend/tests/services/in_transit_transfer/test_execution_service.py`(用例迁移)
- Create: `backend/tests/services/in_transit_transfer/test_execute_items.py`
**Interfaces:**
- Consumes: Task 1 `_item_evaluated_sha`;既有 `_write_item(item, *, deps, run_no, request_id)`、`finalize_run(run, run_items)`、`ExecuteOutcome(run_no, status, result)`、`_build_run_result(run)`
- Produces: `execute_items(*, item_ids: list[int], deps, actor_id=None, request_id=None) -> ExecuteOutcome`;错误码:`TRANSFER.EXECUTE_ITEMS_INVALID`(不存在/非可执行)、`TRANSFER.ITEMS_STALE`(details.stale_item_ids)、`TRANSFER.FILE_CHANGED`(details.changed_item_ids,含"来源无可用文件"情形)
- Produces: 路由 `POST /items/execute` body `{"item_ids": [int]}` → 200 envelope `{run_no, status, result}`
- [ ] **Step 1: 写失败测试**(承接 `test_execution_service.py` 的成功/重复/业务失败/部分失败用例改写到 execute_items——把"建预检后 execute_precheck"改为"取 scope 内 ready 行的 item_ids 直接执行";新增三个门禁用例):
```python
def test_execute_items_rejects_stale_rows(transfer_db, dbs_ready_file):
# 建 ready 行后把 updated_at 拨回 11 分钟前 → execute_items 抛 ValidationError
# code == "TRANSFER.ITEMS_STALE",details 含该 item_id;不创建 Run
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file):
# 建 ready 行后,用"新 checksum 的文件"刷新来源最新可用文件状态
# (monkeypatch resolve_source_file_status 返回不同 file_sha256,或按 Task 1 方式重跑新文件预检
# —— 注意重跑会把行刷成新版本,所以本用例用 monkeypatch 模拟"文件更新但未重新预检")
# → ValidationError code == "TRANSFER.FILE_CHANGED"
def test_execute_items_writes_and_aggregates(transfer_db, dbs_ready_file):
# ready 行执行 → run_no 生成、ERP 写 Attempt、状态 success、结果按 ERP 单号聚合
```
- [ ] **Step 2: 确认失败**(execute_items 未定义)。
- [ ] **Step 3: 实现**(execution_service.py):
1. `execute_items`:加载并校验 `item_ids`(存在 + `status == ready_to_execute`,否则 `ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID", details={"invalid_item_ids": [...]})`)。
2. 新鲜度门禁:`stale = [i.id for i in items if (now - i.updated_at) > ttl]`(ttl=`deps.strategy.confirm_ttl_seconds`,now=utcnow)→ 非空抛 `TRANSFER.ITEMS_STALE`。
3. 文件版本对账门禁:按去重 source 调 `resolve_source_file_status`,行评估 sha(`_item_evaluated_sha`)缺失或 ≠ 最新可用 sha(或来源无可用文件)→ 抛 `TRANSFER.FILE_CHANGED`(details 列出 changed_item_ids)。
4. 建 Run:改造 `create_execution_run` 为 `create_execution_run_for_items(items, *, deps, actor_id, selected_item_ids)`(阅读原函数后平移:`run_no=_generate_no("RUN", business_date_now())`、`business_date=business_date_now()`、`source_codes_json=sorted({i.source_code})`、`trigger_type="manual"`、counts 按行聚合;**不绑定 precheck**,`precheck.run_id` 保持空)。逐行 `_write_item(item, deps=deps, run_no=..., request_id=...)`(保持原样:写前复查+原子写+单项失败不阻断),`finalize_run` + `commit`,返回 `ExecuteOutcome`。
5. **删除 `execute_precheck` 函数与 `POST /prechecks/{id}/execute` 路由**(hash/expires 门禁随之退役;`create_precheck` 仍照算 `precheck_hash` 留痕,`expires_at` 仍写仅作展示)。同步删除 `_expire`/`recompute_precheck_hash` 的调用点(函数若仅剩此处引用一并删除)。
6. `chat_actions.TransferExecuteAction.stream`:payload 仍为 `{precheck_id, invoice_nos}` → 用 `scope_item_query(restore 用的预检)` + `invoice_nos` 过滤出 ready 行的 item_ids → 调 `execute_items`;输出卡片不变。
7. API:`POST /items/execute`(`_require_user` + body item_ids 校验复用 `_require_item_ids`)。
- [ ] **Step 4: 跑测试** PASS;全目录回归。
- [ ] **Step 5: stage**。
---
### Task 4: 恢复处理收敛为行级重查(删 batch-resume 与 resume_service)
**Files:**
- Delete: `backend/app/services/in_transit_transfer/resume_service.py`、`backend/tests/services/in_transit_transfer/test_resume_service.py`
- Modify: `backend/app/api/in_transit_transfer.py`(删 `POST /items/batch-resume` 路由与 import)
- Modify: `backend/app/services/in_transit_transfer/retry_service.py`(_recheck_item 续新鲜度)
- Modify: `backend/tests/services/in_transit_transfer/test_batch_actions.py`
**Interfaces:**
- Produces: `requery_items_by_ids`(既有)成为"恢复处理"唯一后端语义;`_recheck_item` 成功/失败路径均显式 `item.updated_at = datetime.utcnow()`(重查即续新鲜度)。
- Note: 本任务后前端 `batchResumeTransferItems` 调用会 404,由 Task 5 同一计划内修复(计划整体一次性交付)。
- [ ] **Step 1: 写失败测试**(test_batch_actions.py 追加):
```python
def test_batch_requery_refreshes_freshness(transfer_db, dbs_ready_file):
# ready 前置:把行 updated_at 拨回 11 分钟前 → blocked(先 seed 不匹配库存造 blocked)
# 再 seed 正确库存 → requery_items_by_ids → 行 updated_at 恢复到当前时刻附近(断言 > 拨回值)
```
- [ ] **Step 2: 确认失败**(现状同值刷新不触发 onupdate,updated_at 不变)。
- [ ] **Step 3: 实现**:`_recheck_item` 在每次状态落定后 `item.updated_at = datetime.utcnow()`(成功与降级两条路径都加)。
- [ ] **Step 4:** 删除 resume_service.py、test_resume_service.py、batch-resume 路由与 import;跑全目录回归(chat/e2e 若引用 resume 端点一并清理)。
- [ ] **Step 5: stage**。
---
### Task 5: 前端换接线(界面结构不变)+ 四语言
**Files:**
- Modify: `frontend/src/features/chat/api/transfer.api.ts`、`types/transfer.types.ts`、`composables/useChatTransfer.ts`
- Modify: `frontend/src/features/chat/components/messages/TransferMessageView.vue`、`TransferPrecheckCard.vue`、`TransferBacklogSummaryCard.vue`
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`、`errors.json`
- Modify: 相关 spec(`transferCards.spec.ts`、`TransferMessageView.spec.ts`、`transfer.api.spec.ts`)
**Interfaces:**
- `executeTransferItems(itemIds: number[]) => POST /items/execute`;`TransferPrecheckItem` 增 `item_id: number; checked_at?: string|null; stale?: boolean; file_current?: boolean`
- `useChatTransfer.selected: Set<number>`(勾选键从 invoice_no 改 item_id);`resume(itemIds)` = `batchRequery` 的语义别名(返回 results,由视图统计 recovered/still_blocked)
- 删除:`batchResumeTransferItems`、恢复跳预检卡导航逻辑、`toastResumeOpened/Refetching/Skipped/StillBlocked` 键
- [ ] **Step 1: 类型与 API**:`transfer.types.ts` 的 `TransferPrecheckItem` 加四字段;`transfer.api.ts` 新增 `executeTransferItems`(jsonHeaders POST `/items/execute`,body `{item_ids}`),删除 `batchResumeTransferItems`。更新 `transfer.api.spec.ts` 的 jsonHeaders 契约用例(新端点带 Content-Type)。
- [ ] **Step 2: composable**:`selected` 改 `Set<number>`(`executableInvoices`→`executableItemIds`;`applyDetail/applyPayload` 的默认勾选按 `item_id`);`execute()` 改 `executeTransferItems([...selected])`;删除 `batchResume`,新增 `resume(itemIds)` 直调 `batchRequeryTransferItems`(别名导出,视图统一走它)。
- [ ] **Step 3: TransferPrecheckCard**:checkbox `:checked="selected.has(item.item_id)"`、emit toggle/execute 均带 `item_id`;库存数量单元格渲染 `{{ item.external_quantity ?? '—' }}` + 小字查询时刻(`checked_at` 的 HH:mm,`title` 用 `stockCheckedAtTitle`);`stale===true` 行加置灰 class + 「数据已过期,请重查」小标;`file_current===false` 加「文件已更新,请重新预检」小标;结果徽标映射加 `blocked_file_removed → resultFileRemoved`。对应更新 `transferCards.spec.ts`(勾选键、execute 参数为数组 item_id)。
- [ ] **Step 4: TransferMessageView**:`onExecute(invoiceNos)` 改 `onExecute(itemIds)`;`onBacklogResume` 改为调 `transfer.resume(itemIds)` → `loadBacklog()` → 由 results 统计 `recovered`(status==='ready_to_execute')与 `still` → 提示 `toastRequeryRecovered({recovered, blocked})`;删除跳预检卡导航与 file_fetching/skipped 分支;恢复单行按钮走同一 handler。`TransferBacklogSummaryCard` 结果徽标映射补 `blocked_file_removed`。
- [ ] **Step 5: 四语言**:新增键(chat.json):`stockCheckedAtTitle`("库存查询时刻:{time}")、`staleRow`("数据已过期,请重查")、`fileChangedRow`("文件已更新,请重新预检")、`resultFileRemoved`("文件已移除")、`toastExecuteStale`("{count} 笔数据已过期,请重查后生成")、`toastExecuteFileChanged`("{count} 笔文件已更新,请重新预检")、`toastRequeryRecovered`("恢复完成:{recovered} 笔已可执行 · {blocked} 笔仍阻断");errors.json 新增 `TRANSFER.ITEMS_STALE`/`TRANSFER.FILE_CHANGED`/`TRANSFER.EXECUTE_ITEMS_INVALID`;删除 `toastResumeOpened/toastResumeRefetching/toastResumeSkipped/toastResumeStillBlocked`。zh-TW/en/th 给出对应译文(en: "Stock checked at {time}" / "Stale — requery" / "File updated — re-precheck" / "Removed from file" / "{count} stale rows — requery before generating" / "{count} rows with file updated — re-precheck" / "Resume done: {recovered} executable · {blocked} still blocked")。
- [ ] **Step 6: 验证**:`npm run build` 通过;`npx vitest run src/features/chat/` 全绿;`grep -rn "batchResume\|toastResume" frontend/src` 无残留。
- [ ] **Step 7: stage**。
---
### Task 6: 批量库存查询对账排查(独立缺陷,探针 + 修复)
**Files:**
- Create: `backend/tmp/diag_stock_batch.py`(仿 `backend/tmp/diag_precheck_empty.py` 的真实环境探针模式)
- Modify(若证实 bug): `backend/app/services/in_transit_transfer/capability_client.py` 或连接器查询映射层
**背景(实测矛盾)**:同一行(如 HOX260824001/002/007,CRANE 来源)预检批量查询得库存 0,单行重查得 30/40/36——两条路径必有一条错。
- [ ] **Step 1: 单元层复现尝试**:写 pytest 用 `FakeCapabilityClient` 构造"同 external_org 多 targets(≥3 个、含同料号不同批号/同批号不同料号)"场景,断言 `query_stock(...).lookup(material, warehouse, lot)` 与 seed 一一对应;若映射键冲突/覆盖可复现,即定位 `capability_client` 的结果装配逻辑缺陷并修复 + 回归(参考既有 `test_capability_client.py`、`test_query_inventory_gateway.py`)。
- [ ] **Step 2: 真实数据探针**:`backend/tmp/diag_stock_batch.py`——对用户环境的三笔 Invoice(WTP26060612/HOX260824001/HOX260824007),分别走"批量 targets 一次查询"与"逐 target 单查询",打印两侧逐 target 结果与差异(只读,不写 ERP;复用 `transfer_deps.get_transfer_dependencies()`;真实连接器凭据由环境注入,脚本不得硬编码)。
- [ ] **Step 3: 结论落档**:探针输出与根因写入 `docs/features/in-transit-transfer/technical.md` §6(运维关注点)新增小节;若修复,附回归测试;若需 ERP 侧核对,列出待确认清单交给用户。
- [ ] **Step 4: stage**。
---
### Task 7: 全量回归 + 文档同步
**Files:**
- Modify: `docs/features/in-transit-transfer/technical.md`(§4 API 表:+execute、-batch-resume/-prechecks/{id}/execute;§4.1 重写为"行不迁移/三层门禁/恢复=行级重查/预检=评估留痕";§6 补对账结论)
- Modify: `docs/funclist.md`(在途调拨表:改"最近预检恢复入口/待处理池批量操作"两行描述为最终语义;新增"按行执行与三层门禁"一行)
- [ ] **Step 1:** `cd backend && python -m pytest tests/services/in_transit_transfer -q` 全绿(记录用例数)。
- [ ] **Step 2:** `cd frontend && npm run build && npx vitest run` 全绿(记录用例数)。
- [ ] **Step 3:** 更新两个文档(内容按本计划 Architecture 与 Task 3/4 的最终 API 面)。
- [ ] **Step 4:** `git add` 全部改动文件;向用户汇报各步验证结果,等待提交批准。
---
## Self-Review 记录
- 规格覆盖:前端三区保留(Task 5 仅接线)✓;行不迁移(Task 1)✓;预检卡=范围视图(Task 2)✓;按行执行+TTL(Task 3)✓;hash 留痕不拦执行(Task 3 删执行链校验、create 保留计算)✓;文件版本对账+消失行(Task 1/3)✓;恢复=行级重查(Task 4+5)✓;库存查询时刻(Task 2 序列化 + Task 5 展示)✓;批量查询对账(Task 6)✓;文档(Task 7)✓。
- 类型一致性:`item_id` 贯穿 serialize_item→DTO→前端类型→selected Set<number>→execute(item_ids);`_item_evaluated_sha`/`scope_item_query` 定义于 Task 1、消费于 Task 2/3;错误码三处(service 抛/api envelope/errors.json)已对齐。
- 已知取舍(已在对话向用户说明):restore 的 scope 视图会显示范围内所有行(含非本次评估新增行)——这是"实时视图"的既定语义;行新鲜度用 `updated_at` 近似(评估时显式赋值,关闭等操作也会刷新但那些状态本就不可执行)。
@@ -23,10 +23,10 @@ vi.mock('@/shared/utils/auth', () => ({
import {
cancelTransferRun,
createTransferPrecheck,
executeTransferPrecheck,
createTransferMatching,
executeTransferItems,
getTransferBacklogSummary,
getTransferPrecheck,
getTransferMatching,
getTransferRun,
listTransferSources,
manualCloseTransferItem,
@@ -39,21 +39,24 @@ describe('transfer.api JSON request contract', () => {
requestBlob.mockReset();
});
it('创建预检 POST 带 Content-Type: application/json 与序列化 source_codes', () => {
createTransferPrecheck({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' });
it('创建匹配 POST 带 Content-Type: application/json 与序列化 source_codes', () => {
createTransferMatching({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' });
const [url, init] = requestJson.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/in-transit-transfer/prechecks');
expect(url).toBe('/api/in-transit-transfer/matchings');
expect(init.method).toBe('POST');
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' }));
});
it('直接生成调拨单 POST 带 application/json', () => {
executeTransferPrecheck('TPC-1', ['INV-001']);
const [, init] = requestJson.mock.calls[0] as [string, RequestInit];
it('按明细行执行调拨 POST /items/execute 带 application/json 与 item_ids 契约', () => {
// [断言意图] 行式执行(2026-09-23 item-centric 重构):执行不再挂在旧匹配详情端点下,
// 改为独立 items/execute,body 键从 invoice_nos 改为 item_ids;JSON 头契约不变。
executeTransferItems([101, 102]);
const [url, init] = requestJson.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/in-transit-transfer/items/execute');
expect(init.method).toBe('POST');
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
expect(init.body).toBe(JSON.stringify({ invoice_nos: ['INV-001'] }));
expect(init.body).toBe(JSON.stringify({ item_ids: [101, 102] }));
});
it('重试/关闭/取消 POST 带 application/json', () => {
@@ -67,7 +70,7 @@ describe('transfer.api JSON request contract', () => {
});
it('GET 端点只需鉴权头,不需要强制 Content-Type', () => {
getTransferPrecheck('TPC-1');
getTransferMatching('MTG-1');
getTransferRun('RUN-1');
getTransferBacklogSummary();
listTransferSources();
+42 -17
View File
@@ -10,9 +10,11 @@ import type {
TransferActionResult,
TransferBacklogItem,
TransferBacklogSummary,
TransferBatchResult,
TransferExecuteResponse,
TransferPrecheckDetail,
TransferPrecheckSummary,
TransferMatchingDetail,
TransferMatchingItem,
TransferMatchingSummary,
TransferRunResult,
TransferSourceFileStatus,
TransferSourceOption,
@@ -24,7 +26,7 @@ const BASE = '/api/in-transit-transfer';
/** JSON 请求头:除鉴权外必须带 Content-Type: application/json,否则 Flask request.get_json 解析不到 body。 */
const jsonHeaders = () => ({ 'Content-Type': 'application/json', ...getAuthHeaders() });
export interface CreatePrecheckPayload {
export interface CreateMatchingPayload {
source_codes: string[];
business_date?: string;
receipt_date_from?: string;
@@ -33,26 +35,33 @@ export interface CreatePrecheckPayload {
transfer_type?: TransferType;
}
/** 创建预检(只读) */
export const createTransferPrecheck = (payload: CreatePrecheckPayload) =>
requestJson<TransferPrecheckSummary>(BASE + '/prechecks', {
/** 创建匹配(只读) */
export const createTransferMatching = (payload: CreateMatchingPayload) =>
requestJson<TransferMatchingSummary>(BASE + '/matchings', {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify(payload),
});
/** 恢复预检进度与明细 */
export const getTransferPrecheck = (precheckId: string) =>
requestJson<TransferPrecheckDetail>(`${BASE}/prechecks/${precheckId}`, {
/** 恢复匹配进度与明细 */
export const getTransferMatching = (matchingId: string) =>
requestJson<TransferMatchingDetail>(`${BASE}/matchings/${matchingId}`, {
headers: getAuthHeaders(),
});
/** 确认选择范围并直接生成执行 Run */
export const executeTransferPrecheck = (precheckId: string, invoiceNos: string[]) =>
requestJson<TransferExecuteResponse>(`${BASE}/prechecks/${precheckId}/execute`, {
/** 可调拨明细:全局可执行行队列(勾选后 executeTransferItems 按行生成调拨单) */
export const listExecutableTransferItems = () =>
requestJson<{ items: TransferMatchingItem[]; counts: { executable_count: number } }>(
`${BASE}/items/executable`,
{ headers: getAuthHeaders() },
);
/** 按明细行执行调拨(item-centric:body {item_ids};三层门禁在后端,失败抛 BusinessError) */
export const executeTransferItems = (itemIds: number[]) =>
requestJson<TransferExecuteResponse>(`${BASE}/items/execute`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ invoice_nos: invoiceNos }),
body: JSON.stringify({ item_ids: itemIds }),
});
/** 恢复 Run 最终结果 */
@@ -89,7 +98,7 @@ export const manualCloseTransferItem = (itemId: number, reason: string) =>
export const downloadTransferReceiptFiles = (runNo: string) =>
requestBlob(`${BASE}/runs/${runNo}/receipt-files`, { headers: getAuthHeaders() });
/** 下载预检冻结的 ERP 库存表(csv) */
/** 下载匹配冻结的 ERP 库存表(csv) */
export const downloadTransferErpInventory = (runNo: string) =>
requestBlob(`${BASE}/runs/${runNo}/external-inventory`, { headers: getAuthHeaders() });
@@ -97,10 +106,26 @@ export const downloadTransferErpInventory = (runNo: string) =>
export const downloadTransferExceptions = (runNo: string) =>
requestBlob(`${BASE}/runs/${runNo}/exceptions.xlsx`, { headers: getAuthHeaders() });
/** 批量重查库存(待处理池多选;单行隔离,按明细 id 直取;恢复处理=重查的唯一后端) */
export const batchRequeryTransferItems = (itemIds: number[]) =>
requestJson<TransferBatchResult>(`${BASE}/items/batch-requery`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ item_ids: itemIds }),
});
/** 批量人工关闭异常项(原因整批共用;单行隔离) */
export const batchManualCloseTransferItems = (itemIds: number[], reason: string) =>
requestJson<TransferBatchResult>(`${BASE}/items/batch-manual-close`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ item_ids: itemIds, reason }),
});
/** 批量重查 ERP 库存(可恢复阻断行;invoice_nos 缺省 = 全部阻断行) */
export const requeryTransferItems = (precheckNo: string, invoiceNos?: string[]) =>
requestJson<{ precheck_no: string; total: number; results: Array<Record<string, unknown>> }>(
`${BASE}/prechecks/${precheckNo}/items/requery`,
export const requeryTransferMatchingItems = (matchingNo: string, invoiceNos?: string[]) =>
requestJson<{ matching_no: string; total: number; results: Array<Record<string, unknown>> }>(
`${BASE}/matchings/${matchingNo}/items/requery`,
{ method: 'POST', body: JSON.stringify(invoiceNos ? { invoice_nos: invoiceNos } : {}), headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' } },
);
@@ -99,11 +99,11 @@ const RESTRICTED_INLINE_DOWNLOAD_FILE_NAME = '资产明细全量导出表.csv';
const isContractReviewMessage = computed(() => message.type === 'procurement-contract-review');
const isTransferMessage = computed(
() =>
message.type === 'transfer-precheck'
message.type === 'transfer-match'
|| message.type === 'transfer-progress'
|| message.type === 'transfer-result',
);
/** 调拨消息带宽表格(预检明细 10+ 列),放宽气泡宽度上限避免横向挤压成局部布局。 */
/** 调拨消息带宽表格(匹配明细 10+ 列),放宽气泡宽度上限避免横向挤压成局部布局。 */
const wideMessage = computed(() => isTransferMessage.value || isContractReviewMessage.value);
const isLeaveMessage = computed(() =>
@@ -1,22 +1,93 @@
<!--
features/chat/components/messages/TransferBacklogSummaryCard.vue
用途:待处理异常卡(可恢复/已关闭/结果未知三组)+ 人工重试/人工关闭入口。
依赖:props.items、i18n chat.transfer.*。
逻辑:result_unknown 只读(无重试/关闭按钮);人工关闭由父组件弹窗处理。
用途:待处理异常卡(可恢复/已关闭/结果未知三组)——列与匹配窗口一致,
支持关键字/结果筛选、多选批量操作(重查/恢复处理/标记无需处理)与行级快捷操作。
依赖:props.items、i18n chat.transfer.*、transferBatch.deriveBatchNo。
逻辑:仅 blocked_recoverable 可勾选与操作;result_unknown / manually_closed 只读;
可恢复行按 result_code 细分徽标(blocked_file_removed=文件已移除);
勾选集合为卡片本地态,操作经 emit 交父组件调用批量端点并刷新。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { deriveBatchNo } from './transferBatch';
import type { TransferBacklogItem } from '../../types/transfer.types';
defineProps<{
const props = defineProps<{
items: TransferBacklogItem[];
busy?: boolean;
/** 初始结果筛选(首页计数卡切片进入:closed 卡落「已关闭」切片等)。 */
initialFilter?: 'all' | 'recoverable' | 'closed' | 'unknown';
}>();
const emit = defineEmits<{
retry: [itemId: number];
close: [item: TransferBacklogItem];
refresh: [];
retry: [itemId: number];
resume: [itemIds: number[]];
requery: [itemIds: number[]];
close: [item: TransferBacklogItem];
batchClose: [itemIds: number[]];
}>();
/** 勾选集合(本地视图态;仅可恢复行可勾选)。 */
const selectedIds = ref<Set<number>>(new Set());
const keyword = ref('');
const resultFilter = ref<'all' | 'recoverable' | 'closed' | 'unknown'>(props.initialFilter ?? 'all');
function isActionable(item: TransferBacklogItem): boolean {
return item.status === 'blocked_recoverable';
}
const filtered = computed(() =>
props.items.filter((item) => {
const kw = keyword.value.trim().toLowerCase();
if (kw) {
const haystack = [item.invoice_no, item.material_no, item.material_name, item.source_code]
.map((value) => String(value ?? '').toLowerCase());
if (!haystack.some((value) => value.includes(kw))) return false;
}
if (resultFilter.value === 'recoverable' && item.status !== 'blocked_recoverable') return false;
if (resultFilter.value === 'closed' && item.status !== 'manually_closed') return false;
if (resultFilter.value === 'unknown' && item.status !== 'result_unknown') return false;
return true;
}),
);
const selectedActionableIds = computed(() =>
filtered.value.filter((item) => isActionable(item) && selectedIds.value.has(item.item_id)).map((item) => item.item_id),
);
const allFilteredSelected = computed(() => {
const actionable = filtered.value.filter(isActionable);
return actionable.length > 0 && actionable.every((item) => selectedIds.value.has(item.item_id));
});
function toggleRow(item: TransferBacklogItem, checked: boolean) {
const next = new Set(selectedIds.value);
if (checked) next.add(item.item_id);
else next.delete(item.item_id);
selectedIds.value = next;
}
function toggleAll(checked: boolean) {
const next = new Set(selectedIds.value);
for (const item of filtered.value.filter(isActionable)) {
if (checked) next.add(item.item_id);
else next.delete(item.item_id);
}
selectedIds.value = next;
}
function clearSelection() {
selectedIds.value = new Set();
}
/** 行操作后/刷新后清理已消失行的勾选残留。 */
function pruneSelection() {
const alive = new Set(props.items.map((item) => item.item_id));
selectedIds.value = new Set([...selectedIds.value].filter((id) => alive.has(id)));
}
defineExpose({ pruneSelection });
function agingLabel(level: string): string {
const map: Record<string, string> = {
warn_3d: 'chat.transfer.agingWarn',
@@ -27,6 +98,19 @@ function agingLabel(level: string): string {
};
return map[level] ?? 'chat.transfer.agingNormal';
}
function rowKey(item: TransferBacklogItem): string {
return `${item.item_id}|${item.invoice_no}`;
}
/** 结果徽标文案键:可恢复行按 result_code 细分(blocked_file_removed=文件已移除),其余按状态。 */
function resultLabelKey(item: TransferBacklogItem): string {
if (item.status === 'result_unknown') return 'chat.transfer.resultUnknown';
if (item.status === 'manually_closed') return 'chat.transfer.statusClosed';
return item.result_code === 'blocked_file_removed'
? 'chat.transfer.resultFileRemoved'
: 'chat.transfer.resultBlocked';
}
</script>
<template>
@@ -42,47 +126,177 @@ function agingLabel(level: string): string {
{{ $t('chat.transfer.refreshProgress') }}
</button>
</div>
<ul v-if="items.length" class="flex flex-col gap-1.5">
<li
v-for="item in items"
:key="item.item_id"
class="flex items-center justify-between gap-2 rounded-lg border border-subtle px-3 py-2 text-xs"
:data-testid="`transfer-backlog-${item.invoice_no}`"
<!-- 批量操作条:勾选 ≥1 行时原位替换筛选区 -->
<div v-if="selectedActionableIds.length" class="mb-2 flex flex-wrap items-center gap-2">
<span class="text-xs font-bold text-secondary" data-testid="transfer-backlog-selected-count">
{{ $t('chat.transfer.selectedRows', { count: selectedActionableIds.length }) }}
</span>
<button
type="button"
class="rounded-lg border border-brand-200 bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-40"
data-testid="transfer-backlog-batch-requery"
:disabled="busy"
@click="emit('requery', selectedActionableIds)"
>
<div class="min-w-0">
<div class="font-semibold text-secondary">
{{ item.invoice_no }}
<span class="ml-1 text-muted">{{ item.source_code }}</span>
</div>
<div class="text-[11px] text-muted">
{{ item.reason }} · {{ $t(agingLabel(item.aging_level)) }}
</div>
</div>
<div class="flex shrink-0 gap-1.5">
<template v-if="item.status === 'blocked_recoverable'">
<button
type="button"
class="rounded-lg border border-brand-200 px-2 py-1 font-bold text-brand-700 hover:bg-brand-50"
data-testid="transfer-backlog-retry"
@click="emit('retry', item.item_id)"
>
{{ $t('chat.transfer.retryErp') }}
</button>
<button
type="button"
class="rounded-lg border border-red-200 px-2 py-1 font-bold text-red-600 hover:bg-red-50"
data-testid="transfer-backlog-close"
@click="emit('close', item)"
>
{{ $t('chat.transfer.manualClose') }}
</button>
</template>
<span v-else-if="item.status === 'result_unknown'" class="text-[11px] text-muted">
{{ $t('chat.transfer.resultUnknownReadonly') }}
</span>
</div>
</li>
</ul>
{{ $t('chat.transfer.requeryRow') }}({{ selectedActionableIds.length }})
</button>
<button
type="button"
class="rounded-lg border border-brand-200 bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-40"
data-testid="transfer-backlog-batch-resume"
:disabled="busy"
@click="emit('resume', selectedActionableIds)"
>
{{ $t('chat.transfer.resumeAction') }}({{ selectedActionableIds.length }})
</button>
<button
type="button"
class="rounded-lg border border-red-200 bg-red-50 px-3 py-1 text-xs font-bold text-red-600 transition hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-40"
data-testid="transfer-backlog-batch-close"
:disabled="busy"
@click="emit('batchClose', selectedActionableIds)"
>
{{ $t('chat.transfer.manualClose') }}({{ selectedActionableIds.length }})
</button>
<button
type="button"
class="rounded-lg border border-default px-2 py-1 text-xs text-secondary hover-surface-soft"
data-testid="transfer-backlog-clear-selection"
@click="clearSelection"
>
{{ $t('chat.transfer.clearSelection') }}
</button>
</div>
<div v-else class="mb-2 flex flex-wrap items-center gap-2">
<input
v-model="keyword"
type="text"
class="w-56 rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
:placeholder="$t('chat.transfer.filterPlaceholder')"
data-testid="transfer-backlog-filter"
/>
<select
v-model="resultFilter"
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
data-testid="transfer-backlog-result-filter"
>
<option value="all">{{ $t('chat.transfer.filterAll') }}</option>
<option value="recoverable">{{ $t('chat.transfer.homeRecoverable') }}</option>
<option value="closed">{{ $t('chat.transfer.homeClosed') }}</option>
<option value="unknown">{{ $t('chat.transfer.homeUnknown') }}</option>
</select>
</div>
<div v-if="filtered.length" class="overflow-x-auto">
<table class="w-full min-w-[1180px] text-xs" data-testid="transfer-backlog-table">
<thead>
<tr class="border-b border-default bg-surface-soft text-left text-[11px] text-muted">
<th class="p-2">
<input
type="checkbox"
:checked="allFilteredSelected"
data-testid="transfer-backlog-select-all"
@change="toggleAll(($event.target as HTMLInputElement).checked)"
/>
</th>
<th class="p-2">{{ $t('chat.transfer.colSource') }}</th>
<th class="p-2">{{ $t('chat.transfer.colInvoice') }}</th>
<th class="p-2">{{ $t('chat.transfer.colReceiptDate') }}</th>
<th class="p-2">{{ $t('chat.transfer.colMaterial') }}</th>
<th class="p-2">{{ $t('chat.transfer.colName') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromWarehouse') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromBatch') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromQty') }}</th>
<th class="p-2">{{ $t('chat.transfer.colToWarehouse') }}</th>
<th class="p-2">{{ $t('chat.transfer.colToQty') }}</th>
<th class="p-2">{{ $t('chat.transfer.colResult') }}</th>
<th class="p-2">{{ $t('chat.transfer.colAging') }}</th>
<th class="p-2">{{ $t('chat.transfer.colAction') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in filtered"
:key="rowKey(item)"
class="border-b border-subtle"
:class="{ 'bg-surface-soft text-muted': !isActionable(item) }"
:data-testid="`transfer-backlog-${item.invoice_no}`"
>
<td class="p-2">
<input
type="checkbox"
:checked="selectedIds.has(item.item_id)"
:disabled="!isActionable(item) || busy"
:data-testid="`transfer-backlog-check-${item.invoice_no}`"
@change="toggleRow(item, ($event.target as HTMLInputElement).checked)"
/>
</td>
<td class="p-2">{{ item.source_code }}</td>
<td class="p-2 font-semibold">{{ item.invoice_no }}</td>
<td class="p-2">{{ item.receipt_date || '—' }}</td>
<td class="p-2">{{ item.material_no }}</td>
<td class="p-2">{{ item.material_name || '—' }}</td>
<td class="p-2">{{ item.from_warehouse || '—' }}</td>
<td class="p-2">{{ deriveBatchNo(item.lot_no ?? '') || '—' }}</td>
<td class="p-2">{{ item.external_quantity ?? '—' }}</td>
<td class="p-2">{{ item.to_warehouse || '—' }}</td>
<td class="p-2">{{ item.receipt_quantity ?? '—' }}</td>
<td class="p-2">
<span
class="rounded-full px-2 py-0.5 font-bold"
:class="{
'bg-red-50 text-red-700': item.status === 'blocked_recoverable',
'bg-amber-50 text-amber-700': item.status === 'result_unknown',
'bg-surface-soft text-muted': item.status === 'manually_closed',
}"
:title="item.reason || undefined"
data-testid="transfer-backlog-result"
>
{{
$t(resultLabelKey(item))
}}
</span>
</td>
<td class="p-2">{{ $t(agingLabel(item.aging_level)) }}</td>
<td class="p-2">
<template v-if="isActionable(item)">
<button
type="button"
class="mr-1 rounded border border-brand-200 px-1 py-0.5 text-[10px] font-bold text-brand-700 transition hover:bg-brand-50 disabled:opacity-40"
:data-testid="`transfer-backlog-requery-${item.invoice_no}`"
:disabled="busy"
@click="emit('retry', item.item_id)"
>
{{ $t('chat.transfer.requeryRow') }}
</button>
<button
type="button"
class="mr-1 rounded border border-brand-200 px-1 py-0.5 text-[10px] font-bold text-brand-700 transition hover:bg-brand-50 disabled:opacity-40"
:data-testid="`transfer-backlog-resume-${item.invoice_no}`"
:disabled="busy"
@click="emit('resume', [item.item_id])"
>
{{ $t('chat.transfer.resumeAction') }}
</button>
<button
type="button"
class="rounded border border-red-200 px-1 py-0.5 text-[10px] font-bold text-red-600 transition hover:bg-red-50 disabled:opacity-40"
:data-testid="`transfer-backlog-close-${item.invoice_no}`"
:disabled="busy"
@click="emit('close', item)"
>
{{ $t('chat.transfer.manualClose') }}
</button>
</template>
<span v-else-if="item.status === 'result_unknown'" class="text-[11px] text-muted">
{{ $t('chat.transfer.resultUnknownReadonly') }}
</span>
</td>
</tr>
</tbody>
</table>
</div>
<div v-else class="rounded-lg bg-surface-soft p-3 text-xs text-muted">
{{ $t('chat.transfer.noBacklog') }}
</div>
@@ -0,0 +1,212 @@
<!--
features/chat/components/messages/TransferExecutableCard.vue
用途:可调拨明细卡——全局可执行行队列(跨匹配范围):勾选明细行后按行生成调拨单。
依赖:props.items、i18n chat.transfer.*、transferBatch.deriveBatchNo。
逻辑:行由后端按业务稳定键排序(收料日期→Invoice→创建时间);勾选为卡片本地态;
stale/file_current 行置灰提示(执行门禁在后端,失败经 BusinessError 展示);
无 item_id 的历史回放行禁选。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { deriveBatchNo } from './transferBatch';
import type { TransferMatchingItem } from '../../types/transfer.types';
const props = defineProps<{
items: TransferMatchingItem[];
busy?: boolean;
}>();
const emit = defineEmits<{
refresh: [];
execute: [itemIds: number[]];
requery: [itemIds: number[]];
}>();
/** 勾选集合(本地视图态,按明细行 item_id)。 */
const selectedIds = ref<Set<number>>(new Set());
const keyword = ref('');
const filtered = computed(() =>
props.items.filter((item) => {
const kw = keyword.value.trim().toLowerCase();
if (!kw) return true;
const haystack = [item.invoice_no, item.material_no, item.material_name, item.source_code, item.lot_no]
.map((value) => String(value ?? '').toLowerCase());
return haystack.some((value) => value.includes(kw));
}),
);
const checked = computed(() =>
filtered.value.filter((item) => item.item_id != null && selectedIds.value.has(item.item_id)),
);
const allFilteredSelected = computed(() =>
filtered.value.length > 0 && filtered.value.every((item) => item.item_id != null && selectedIds.value.has(item.item_id)),
);
function toggleRow(item: TransferMatchingItem, checkedBox: boolean) {
if (item.item_id == null) return;
const next = new Set(selectedIds.value);
if (checkedBox) next.add(item.item_id);
else next.delete(item.item_id);
selectedIds.value = next;
}
function toggleAll(checkedBox: boolean) {
const next = new Set(selectedIds.value);
for (const item of filtered.value) {
if (item.item_id == null) continue;
if (checkedBox) next.add(item.item_id);
else next.delete(item.item_id);
}
selectedIds.value = next;
}
function clearSelection() {
selectedIds.value = new Set();
}
function rowKey(item: TransferMatchingItem): string {
return `${item.item_id ?? 'na'}|${item.invoice_no}`;
}
/** 查询时刻展示(HH:mm);无 checked_at 不渲染。 */
function checkedTime(item: TransferMatchingItem): string {
if (!item.checked_at) return '';
const date = new Date(item.checked_at);
return Number.isNaN(date.getTime()) ? '' : date.toTimeString().slice(0, 5);
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-executable-card">
<div class="mb-2 flex items-center justify-between">
<h3 class="text-sm font-bold text-primary">{{ $t('chat.transfer.executableTitle') }}</h3>
<button
type="button"
class="rounded-lg border border-default px-2 py-1 text-xs text-secondary hover-surface-soft"
data-testid="transfer-executable-refresh"
@click="emit('refresh')"
>
{{ $t('chat.transfer.refreshProgress') }}
</button>
</div>
<div class="mb-2 flex flex-wrap items-center gap-2">
<input
v-model="keyword"
type="text"
class="w-56 rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
:placeholder="$t('chat.transfer.filterPlaceholder')"
data-testid="transfer-executable-filter"
/>
<span v-if="checked.length" class="text-xs font-bold text-secondary" data-testid="transfer-executable-selected-count">
{{ $t('chat.transfer.selectedRows', { count: checked.length }) }}
</span>
<button
v-if="checked.length"
type="button"
class="rounded-lg border border-default px-2 py-1 text-xs text-secondary hover-surface-soft"
data-testid="transfer-executable-clear-selection"
@click="clearSelection"
>
{{ $t('chat.transfer.clearSelection') }}
</button>
</div>
<div v-if="filtered.length" class="overflow-x-auto">
<table class="w-full min-w-[1100px] text-xs" data-testid="transfer-executable-table">
<thead>
<tr class="border-b border-default bg-surface-soft text-left text-[11px] text-muted">
<th class="p-2">
<input
type="checkbox"
:checked="allFilteredSelected"
data-testid="transfer-executable-select-all"
@change="toggleAll(($event.target as HTMLInputElement).checked)"
/>
</th>
<th class="p-2">{{ $t('chat.transfer.colSource') }}</th>
<th class="p-2">{{ $t('chat.transfer.colInvoice') }}</th>
<th class="p-2">{{ $t('chat.transfer.colReceiptDate') }}</th>
<th class="p-2">{{ $t('chat.transfer.colMaterial') }}</th>
<th class="p-2">{{ $t('chat.transfer.colName') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromWarehouse') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromBatch') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromQty') }}</th>
<th class="p-2">{{ $t('chat.transfer.colToWarehouse') }}</th>
<th class="p-2">{{ $t('chat.transfer.colToQty') }}</th>
<th class="p-2">{{ $t('chat.transfer.colResult') }}</th>
<th class="p-2">{{ $t('chat.transfer.colAction') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in filtered"
:key="rowKey(item)"
class="border-b border-subtle"
:class="{ 'bg-surface-soft text-muted': item.stale || item.file_current === false }"
:data-testid="`transfer-executable-${item.invoice_no}`"
>
<td class="p-2">
<input
type="checkbox"
:checked="item.item_id != null && selectedIds.has(item.item_id)"
:disabled="item.item_id == null || busy"
:data-testid="`transfer-executable-check-${item.invoice_no}`"
@change="toggleRow(item, ($event.target as HTMLInputElement).checked)"
/>
</td>
<td class="p-2">{{ item.source_code }}</td>
<td class="p-2 font-semibold">{{ item.invoice_no }}</td>
<td class="p-2">{{ item.receipt_date || '—' }}</td>
<td class="p-2">{{ item.material_no }}</td>
<td class="p-2">{{ item.material_name }}</td>
<td class="p-2">{{ item.from_warehouse }}</td>
<td class="p-2">{{ deriveBatchNo(item.lot_no ?? '') || '—' }}</td>
<td class="p-2">
{{ item.from_quantity ?? '—' }}
<div v-if="checkedTime(item)" class="text-[10px] text-muted">{{ checkedTime(item) }}</div>
</td>
<td class="p-2">{{ item.to_warehouse }}</td>
<td class="p-2">{{ item.to_quantity }}</td>
<td class="p-2">
<span class="rounded-full bg-emerald-50 px-2 py-0.5 font-bold text-emerald-700" data-testid="transfer-executable-result">
{{ $t('chat.transfer.resultExecutable') }}
</span>
<div v-if="item.stale" class="mt-0.5 text-[10px] text-amber-600">{{ $t('chat.transfer.staleRow') }}</div>
<div v-else-if="item.file_current === false" class="mt-0.5 text-[10px] text-amber-600">{{ $t('chat.transfer.fileChangedRow') }}</div>
</td>
<td class="p-2">
<button
type="button"
class="rounded border border-brand-200 px-1 py-0.5 text-[10px] font-bold text-brand-700 transition hover:bg-brand-50 disabled:opacity-40"
:data-testid="`transfer-executable-requery-${item.invoice_no}`"
:disabled="busy || item.item_id == null"
@click="item.item_id != null && emit('requery', [item.item_id])"
>
{{ $t('chat.transfer.requeryRow') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-else class="rounded-lg bg-surface-soft p-3 text-xs text-muted" data-testid="transfer-executable-empty">
{{ $t('chat.transfer.executableEmpty') }}
</div>
<div class="mt-3 flex items-center justify-end gap-3 border-t border-subtle pt-3">
<span class="text-xs text-muted">{{ $t('chat.transfer.executableSelectedCount', { count: checked.length }) }}</span>
<button
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="busy || checked.length === 0"
data-testid="transfer-executable-generate"
@click="emit('execute', checked.map((item) => item.item_id as number))"
>
{{ $t('chat.transfer.generateTransfer') }}
</button>
</div>
</div>
</template>
@@ -11,9 +11,9 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';
import i18n from '@/i18n';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
createTransferMatching: vi.fn(),
getTransferMatching: vi.fn(),
executeTransferItems: vi.fn(),
getTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
@@ -23,6 +23,7 @@ const api = vi.hoisted(() => ({
listTransferBacklog: vi.fn(),
getTransferBacklogSummary: vi.fn(),
listTransferSources: vi.fn(),
listExecutableTransferItems: vi.fn(),
}));
vi.mock('@/features/chat/api/transfer.api', () => api);
@@ -43,6 +44,7 @@ describe('TransferHomePanel chat home entry', () => {
recoverable: 6, closed: 2, unknown: 1, aging: { warn_3d: 3, escalate_5d: 2, critical_7d: 1 },
});
api.listTransferBacklog.mockResolvedValue([]);
api.listExecutableTransferItems.mockResolvedValue({ items: [], counts: { executable_count: 0 } });
api.listTransferSources.mockResolvedValue([
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
]);
@@ -59,19 +61,19 @@ describe('TransferHomePanel chat home entry', () => {
expect(api.getTransferBacklogSummary).toHaveBeenCalled();
});
it('点击“发起今日调拨预检”独立触发来源选择卡(复用 TransferMessageView)', async () => {
api.createTransferPrecheck.mockResolvedValue({
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
it('点击“匹配可调拨库存”今日待办入口独立触发来源选择卡(复用 TransferMessageView)', async () => {
api.createTransferMatching.mockResolvedValue({
matching_id: 'MTG-1', status: 'ready_to_execute', business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05', expires_at: '',
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200', estimated_external_write_count: 1, precheck_hash: 'sha256:x',
counts: { file_invoice_count: 1, not_matured_count: 0, matched_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200', estimated_external_write_count: 1, matching_hash: 'sha256:x',
});
api.getTransferPrecheck.mockResolvedValue({
api.getTransferMatching.mockResolvedValue({
summary: {
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
matching_id: 'MTG-1', status: 'ready_to_execute', business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05', expires_at: '',
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200', estimated_external_write_count: 1, precheck_hash: 'sha256:x',
counts: { file_invoice_count: 1, not_matured_count: 0, matched_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200', estimated_external_write_count: 1, matching_hash: 'sha256:x',
},
items: [{
source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
@@ -89,18 +91,44 @@ describe('TransferHomePanel chat home entry', () => {
expect(api.listTransferSources).toHaveBeenCalled();
});
it('点击历史待办计数卡独立触发 backlog 卡片', async () => {
it('点击历史待办计数卡独立触发 backlog 卡片,并按计数卡切片初始筛选', async () => {
// [断言意图] 三张计数卡不再落入同一份全量列表:可恢复/已关闭/结果未知
// 各自带对应 resultFilter 打开待处理池(否则 0 行的已关闭/结果未知被 50 行可恢复淹没)。
api.listTransferBacklog.mockResolvedValue([
{ item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1',
status: 'blocked_recoverable', reason: '收料 1200 / ERP 1000', age_days: 1, aging_level: 'normal' },
{ item_id: 8, source_code: 'DBS-AWSBI', invoice_no: 'INV-002', material_no: 'MAT-2',
status: 'manually_closed', reason: '线下处理', age_days: 2, aging_level: 'closed' },
{ item_id: 9, source_code: 'DBS-AWSBI', invoice_no: 'INV-003', material_no: 'MAT-3',
status: 'result_unknown', reason: '待人工核实', age_days: 3, aging_level: 'result_unknown' },
]);
const wrapper = mountHome();
await flushPromises();
await wrapper.find('[data-testid="transfer-home-recoverable"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
expect(api.listTransferBacklog).toHaveBeenCalled();
expect((wrapper.find('[data-testid="transfer-backlog-result-filter"]').element as HTMLSelectElement).value).toBe('recoverable');
// 切片后仅可见对应状态行。
expect(wrapper.text()).toContain('INV-001');
expect(wrapper.text()).not.toContain('INV-002');
await wrapper.find('[data-testid="transfer-home-back"]').trigger('click');
await flushPromises();
await wrapper.find('[data-testid="transfer-home-closed"]').trigger('click');
await flushPromises();
expect((wrapper.find('[data-testid="transfer-backlog-result-filter"]').element as HTMLSelectElement).value).toBe('closed');
expect(wrapper.text()).toContain('INV-002');
expect(wrapper.text()).not.toContain('INV-001');
await wrapper.find('[data-testid="transfer-home-back"]').trigger('click');
await flushPromises();
await wrapper.find('[data-testid="transfer-home-unknown"]').trigger('click');
await flushPromises();
expect((wrapper.find('[data-testid="transfer-backlog-result-filter"]').element as HTMLSelectElement).value).toBe('unknown');
expect(wrapper.text()).toContain('INV-003');
});
it('子视图提供“返回首页”并切回 home', async () => {
@@ -1,10 +1,11 @@
<!--
features/chat/components/messages/TransferHomePanel.vue
用途:在途仓自动调拨 Agent 的 Chat 首页入口区——home 视图展示标题、今日待办
入口与三张历史待办计数卡;点击入口独立触发 source-select / backlog 卡片。
用途:在途仓自动调拨 Agent 的 Chat 首页入口区——上区「库存匹配」动作入口,
下区「待办看板」四队列(可调拨明细/待恢复异常/已人工关闭/结果未知),
点击进入对应处理视图(复用自驱动的 TransferMessageView)。
依赖:TransferMessageView(复用自驱动卡片)、useChatTransfer、i18n chat.transfer.*。
逻辑:home 时只消费 backlogSummary 计数;非 home 时渲染 TransferMessageView。
卡片不注入消息流,因此无需后端 ChatLog 消息(决策:补首页入口 A 方案)。
逻辑:home 时拉取待办汇总与可调拨明细计数;非 home 时渲染 TransferMessageView。
卡片不注入消息流,因此无需后端 ChatLog 消息。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
@@ -20,31 +21,44 @@ const emit = defineEmits<{
'flow-active': [active: boolean];
}>();
type HomeView = 'home' | 'source-select' | 'backlog';
type HomeView = 'home' | 'source-select' | 'backlog' | 'executable';
/** 待处理池结果筛选(与 TransferBacklogSummaryCard 的筛选选项一致)。 */
type BacklogFilter = 'all' | 'recoverable' | 'closed' | 'unknown';
const transfer = useChatTransfer();
const view = ref<HomeView>('home');
/** 历史待办计数卡对应的初始筛选:点击哪张卡就落到哪个切片。 */
const backlogFilter = ref<BacklogFilter>('all');
/** 进入非 home 时通知父级隐藏聊天输入框(决策:来源选择为业务页,无对话输入区)。 */
watch(view, (value) => emit('flow-active', value !== 'home'), { immediate: true });
/** 打开待处理池并按计数卡切片(recoverable/closed/unknown)。 */
function openBacklog(filter: BacklogFilter) {
backlogFilter.value = filter;
view.value = 'backlog';
}
/** home 视图仅需要待办汇总;进入时拉取计数。 */
/** home 视图需要待办汇总与可调拨明细计数;进入时拉取。 */
async function loadHomeSummary() {
if (view.value !== 'home') return;
await transfer.loadBacklog();
await Promise.all([
transfer.loadBacklog().catch(() => undefined),
transfer.loadExecutableItems().catch(() => undefined),
]);
}
onMounted(() => { void loadHomeSummary(); });
watch(view, () => { void loadHomeSummary(); });
/** 进入非 home 时通知父级隐藏聊天输入框(来源选择/待办为业务页,无对话输入区)。 */
watch(view, (value) => emit('flow-active', value !== 'home'), { immediate: true });
const displayAgentName = computed(() => props.agentName || '在途仓自动调拨');
/** 非 home 视图把当前入口透传给自驱动的 TransferMessageView(决定 source-select 或 backlog)。 */
const childPayload = computed(() => (
view.value === 'source-select'
? { kind: 'source-select' }
: { kind: 'backlog' }
));
/** 非 home 视图把当前入口透传给自驱动的 TransferMessageView。 */
const childPayload = computed(() => {
if (view.value === 'source-select') return { kind: 'source-select' };
if (view.value === 'executable') return { kind: 'executable' };
return { kind: 'backlog', filter: backlogFilter.value };
});
function goBack() {
view.value = 'home';
@@ -53,7 +67,7 @@ function goBack() {
<template>
<div class="flex w-full flex-col items-center px-4 pb-2 pt-6 md:pb-4">
<!-- home:标题 + 今日/历史待办入口 -->
<!-- home:库存匹配 + 待办看板 -->
<template v-if="view === 'home'">
<h2 data-testid="transfer-home" class="mb-8 mt-6 shrink-0 text-center text-2xl font-bold text-primary md:mt-10 md:text-3xl">
{{ $t('chat.transfer.homeWelcome') }}
@@ -61,9 +75,9 @@ function goBack() {
</h2>
<div class="w-full max-w-3xl space-y-4">
<!-- 今日待办 -->
<section aria-label="今日待办">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeTodayLabel') }}</p>
<!-- 库存匹配 -->
<section aria-label="库存匹配">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeMatchLabel') }}</p>
<button
type="button"
data-testid="transfer-home-today"
@@ -79,15 +93,25 @@ function goBack() {
</button>
</section>
<!-- 历史待办 -->
<section aria-label="历史待办">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeHistoryLabel') }}</p>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
<!-- 待办看板 -->
<section aria-label="待办看板">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeBoardLabel') }}</p>
<div class="grid grid-cols-2 gap-3 lg:grid-cols-4">
<button
type="button"
data-testid="transfer-home-executable"
class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-left transition-colors hover:bg-emerald-100"
@click="view = 'executable'"
>
<b class="block text-2xl leading-none text-emerald-600">{{ transfer.executableItems.value.length }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeExecutable') }}</b>
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeExecutableHint') }}</span>
</button>
<button
type="button"
data-testid="transfer-home-recoverable"
class="rounded-2xl border border-brand-200 bg-brand-50 p-4 text-left transition-colors hover:bg-brand-100"
@click="view = 'backlog'"
@click="openBacklog('recoverable')"
>
<b class="block text-2xl leading-none text-brand-600">{{ transfer.backlogSummary.value?.recoverable ?? 0 }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeRecoverable') }}</b>
@@ -97,7 +121,7 @@ function goBack() {
type="button"
data-testid="transfer-home-closed"
class="rounded-2xl border border-default bg-surface p-4 text-left transition-colors hover:border-brand-200 hover:bg-brand-50"
@click="view = 'backlog'"
@click="openBacklog('closed')"
>
<b class="block text-2xl leading-none text-secondary">{{ transfer.backlogSummary.value?.closed ?? 0 }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeClosed') }}</b>
@@ -107,7 +131,7 @@ function goBack() {
type="button"
data-testid="transfer-home-unknown"
class="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-left transition-colors hover:bg-amber-100"
@click="view = 'backlog'"
@click="openBacklog('unknown')"
>
<b class="block text-2xl leading-none text-amber-600">{{ transfer.backlogSummary.value?.unknown ?? 0 }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeUnknown') }}</b>
@@ -118,7 +142,7 @@ function goBack() {
</div>
</template>
<!-- 子流程:复用自驱动的 TransferMessageView(预检宽表格需要全宽,上限对齐消息气泡宽布局) -->
<!-- 子流程:复用自驱动的 TransferMessageView(宽表格需要全宽,上限对齐消息气泡宽布局) -->
<div v-else class="w-full max-w-[min(96vw,1500px)] pr-2">
<button
type="button"
@@ -1,7 +1,7 @@
<!--
features/chat/components/messages/TransferManualCloseDialog.vue
用途:人工关闭弹窗(原因必填;关闭后永久排除,历史保留)。
依赖:props(open/invoiceNo)、i18n chat.transfer.*。
用途:人工关闭弹窗(原因必填;关闭后永久排除,历史保留);count>1 时按批量文案展示。
依赖:props(open/invoiceNo/count)、i18n chat.transfer.*。
逻辑:原因为空时确认按钮禁用;确认时 emit confirm(reason)。
-->
<script setup lang="ts">
@@ -10,6 +10,8 @@ import { ref, watch } from 'vue';
const props = defineProps<{
open: boolean;
invoiceNo: string;
/** 批量关闭的行数;>1 时忽略 invoiceNo,标题/提示切换为批量文案。 */
count?: number;
}>();
const emit = defineEmits<{
@@ -34,8 +36,13 @@ watch(
data-testid="transfer-manual-close-dialog"
>
<div class="w-full max-w-md rounded-2xl bg-surface p-5 shadow-xl">
<h3 class="text-base font-bold text-primary">{{ $t('chat.transfer.manualCloseTitle') }}</h3>
<p class="mt-1 text-xs text-muted">{{ invoiceNo }} · {{ $t('chat.transfer.manualCloseHint') }}</p>
<h3 class="text-base font-bold text-primary">
{{ $t(count && count > 1 ? 'chat.transfer.batchCloseTitle' : 'chat.transfer.manualCloseTitle', count && count > 1 ? { count } : {}) }}
</h3>
<p class="mt-1 text-xs text-muted">
<template v-if="count && count > 1">{{ $t('chat.transfer.manualCloseHint') }}</template>
<template v-else>{{ invoiceNo }} · {{ $t('chat.transfer.manualCloseHint') }}</template>
</p>
<textarea
v-model="reason"
rows="3"
@@ -1,38 +1,47 @@
<!--
features/chat/components/messages/TransferPrecheckCard.vue
用途:预检卡——计数 + 来源失败提示 + 调拨明细表(含筛选)+ 勾选 + “直接生成调拨单”按钮。
features/chat/components/messages/TransferMatchCard.vue
用途:匹配卡——计数 + 来源失败提示 + 调拨明细表(含筛选)+ 勾选 + “直接生成调拨单”按钮。
依赖:props(summary/items/sources/selected/busy)、i18n chat.transfer.*。
逻辑:明细表渲染 filtered(关键字/结果筛选生效);阻断/未成熟项 checkbox 禁用;
重查范围含可恢复阻断与可执行行;阻断原因经结果徽标 title 悬浮透出不占行高;
无选择或 busy 时生成按钮禁用;emit execute(invoiceNos)(决策 4/5:无独立确认页);
勾选键 = 明细行 item_id(历史回放行无 item_id 禁用防误选);
库存数量下方小字透出查询时刻(checked_at);stale 行置灰 + 重查提示;
file_current=false 行提示文件已更新;blocked_file_removed 徽标独立文案;
重查范围含可恢复阻断与可执行行(重查仍按 invoice_no 提交);阻断原因经结果徽标
title 悬浮透出不占行高;无选择或 busy 时生成按钮禁用;emit execute(itemIds);
来源级解析/文件失败经 sources.error_code 透出(防"安静全 0")。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { deriveBatchNo } from './transferBatch';
import type { TransferPrecheckItem, TransferPrecheckSummary, TransferSourceProgress } from '../../types/transfer.types';
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
const { t } = useI18n();
const props = defineProps<{
summary: TransferPrecheckSummary;
items: TransferPrecheckItem[];
summary: TransferMatchingSummary;
items: TransferMatchingItem[];
sources?: TransferSourceProgress[];
selected: Set<string>;
/** 勾选集合(明细行 item_id);历史回放行无 item_id 不可选 */
selected: Set<number>;
busy?: boolean;
requeryBusy?: boolean;
}>();
const emit = defineEmits<{
toggle: [invoiceNo: string, checked: boolean];
'toggle-all': [invoiceNos: string[], checked: boolean];
execute: [invoiceNos: string[]];
toggle: [itemId: number, checked: boolean];
'toggle-all': [itemIds: number[], checked: boolean];
execute: [itemIds: number[]];
requery: [invoiceNos: string[]];
}>();
/** 勾选可用范围:有 item_id 且(可执行或可恢复阻断);无 item_id 的历史行禁用防误选。 */
function hasSelectionKey(item: TransferMatchingItem): boolean {
return item.item_id != null;
}
const selectedCount = computed(() =>
props.items.filter((item) => item.result === 'executable' && props.selected.has(item.invoice_no)).length,
props.items.filter((item) => item.result === 'executable' && isChecked(item)).length,
);
const executeDisabled = computed(() => props.busy || selectedCount.value === 0);
@@ -45,21 +54,21 @@ const failedSources = computed(() =>
const keyword = ref('');
const resultFilter = ref<'all' | 'executable' | 'blocked' | 'not_matured'>('all');
function isBlocked(item: TransferPrecheckItem): boolean {
function isBlocked(item: TransferMatchingItem): boolean {
return String(item.result).startsWith('blocked_');
}
/** 勾选可用范围:可执行(可生成调拨)或可恢复阻断(可重查 ERP)。 */
function isSelectable(item: TransferPrecheckItem): boolean {
function isSelectable(item: TransferMatchingItem): boolean {
return item.result === 'executable';
}
function isCheckable(item: TransferPrecheckItem): boolean {
return isSelectable(item) || isBlocked(item);
function isCheckable(item: TransferMatchingItem): boolean {
return hasSelectionKey(item) && (isSelectable(item) || isBlocked(item));
}
/** 可重查行:可恢复阻断 + 可执行(已可执行也允许重查核对最新库存)。 */
function isRequeryable(item: TransferPrecheckItem): boolean {
function isRequeryable(item: TransferMatchingItem): boolean {
return isBlocked(item) || item.result === 'executable';
}
@@ -78,27 +87,48 @@ const filtered = computed(() =>
}),
);
const filteredInvoiceNos = computed(() => filtered.value.map((item) => item.invoice_no));
/** 全选/批量提交范围:仅含拥有 item_id 的行(历史回放行无键不可参与)。 */
const filteredItemIds = computed(() =>
filtered.value.filter(hasSelectionKey).map((item) => item.item_id as number),
);
const allFilteredSelected = computed(() =>
filteredInvoiceNos.value.length > 0 && filteredInvoiceNos.value.every((no) => props.selected.has(no)),
filteredItemIds.value.length > 0 && filteredItemIds.value.every((id) => props.selected.has(id)),
);
const selectedRequeryableCount = computed(() =>
filtered.value.filter((item) => isRequeryable(item) && props.selected.has(item.invoice_no)).length,
filtered.value.filter((item) => isRequeryable(item) && isChecked(item)).length,
);
function toggleAll(): void {
emit('toggle-all', filteredInvoiceNos.value, !allFilteredSelected.value);
emit('toggle-all', filteredItemIds.value, !allFilteredSelected.value);
}
function requerySelected(): void {
const nos = filtered.value
.filter((item) => isRequeryable(item) && props.selected.has(item.invoice_no))
.filter((item) => isRequeryable(item) && isChecked(item))
.map((item) => item.invoice_no);
if (nos.length) emit('requery', nos);
}
function isChecked(item: TransferPrecheckItem): boolean {
return props.selected.has(item.invoice_no);
function isChecked(item: TransferMatchingItem): boolean {
return item.item_id != null && props.selected.has(item.item_id);
}
/** 生成调拨单提交范围:可执行且被勾选的明细行 id。 */
const executableCheckedItemIds = computed(() =>
props.items.filter((item) => isSelectable(item) && isChecked(item)).map((item) => item.item_id as number),
);
/**
* 库存查询时刻小字(HH:mm);无效/缺省 checked_at 返回 null 不渲染。
* @param item 匹配明细行;checked_at 为后端 ISO 时间
*/
function checkedAtLabel(item: TransferMatchingItem): string | null {
if (!item.checked_at) return null;
const date = new Date(item.checked_at);
if (Number.isNaN(date.getTime())) return null;
const hh = String(date.getHours()).padStart(2, '0');
const mm = String(date.getMinutes()).padStart(2, '0');
return `${hh}:${mm}`;
}
function resultLabel(result: string): string {
@@ -108,6 +138,7 @@ function resultLabel(result: string): string {
blocked_quantity_mismatch: 'chat.transfer.resultBlocked',
blocked_inventory_not_found: 'chat.transfer.resultBlocked',
blocked_future_date: 'chat.transfer.resultBlocked',
blocked_file_removed: 'chat.transfer.resultFileRemoved',
external_query_timeout: 'chat.transfer.resultUnknown',
result_unknown: 'chat.transfer.resultUnknown',
};
@@ -122,7 +153,7 @@ const REASON_I18N_KEYS: Record<string, string> = {
blocked_future_date: 'chat.transfer.reasonFutureDate',
};
function reasonTitle(item: TransferPrecheckItem): string | undefined {
function reasonTitle(item: TransferMatchingItem): string | undefined {
if (!isBlocked(item) || !item.reason) return undefined;
const key = REASON_I18N_KEYS[item.result];
if (!key) return item.reason;
@@ -136,13 +167,13 @@ function reasonTitle(item: TransferPrecheckItem): string | undefined {
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-precheck-card">
<div class="my-2 rounded-2xl border border-brand-100 bg-surface p-4 shadow-sm" data-testid="transfer-match-card">
<div class="mb-3 flex flex-wrap items-center justify-between gap-3">
<h3 class="text-sm font-bold text-primary">{{ $t('chat.transfer.precheckTitle') }}</h3>
<h3 class="text-sm font-bold text-primary">{{ $t('chat.transfer.matchTitle') }}</h3>
<span class="text-xs text-muted">{{ $t('chat.transfer.businessDate') }}:{{ summary.business_date }}</span>
</div>
<div class="mb-3 grid grid-cols-2 gap-2 sm:grid-cols-5" data-testid="transfer-precheck-counts">
<div class="mb-3 grid grid-cols-2 gap-2 sm:grid-cols-5" data-testid="transfer-match-counts">
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.counts.executable_count }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.executableCount') }}</div>
@@ -168,7 +199,7 @@ function reasonTitle(item: TransferPrecheckItem): string | undefined {
<div
v-if="failedSources.length"
class="mb-3 rounded-lg border border-red-200 bg-red-50 p-3 text-xs text-red-700"
data-testid="transfer-precheck-source-errors"
data-testid="transfer-match-source-errors"
>
<div class="mb-1 font-bold">{{ $t('chat.transfer.sourceErrorTitle') }}</div>
<div v-for="source in failedSources" :key="source.source_code" class="leading-5">
@@ -182,9 +213,9 @@ function reasonTitle(item: TransferPrecheckItem): string | undefined {
type="text"
class="w-56 rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
:placeholder="$t('chat.transfer.filterPlaceholder')"
data-testid="transfer-precheck-filter"
data-testid="transfer-match-filter"
/>
<select v-model="resultFilter" class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary" data-testid="transfer-precheck-result-filter">
<select v-model="resultFilter" class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary" data-testid="transfer-match-result-filter">
<option value="all">{{ $t('chat.transfer.filterAll') }}</option>
<option value="executable">{{ $t('chat.transfer.resultExecutable') }}</option>
<option value="blocked">{{ $t('chat.transfer.resultBlocked') }}</option>
@@ -194,21 +225,21 @@ function reasonTitle(item: TransferPrecheckItem): string | undefined {
type="button"
class="rounded-lg border border-brand-200 bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="props.requeryBusy || selectedRequeryableCount === 0"
data-testid="transfer-precheck-requery-selected"
data-testid="transfer-match-requery-selected"
@click="requerySelected"
>
{{ $t('chat.transfer.requerySelected') }}{{ selectedRequeryableCount ? `(${selectedRequeryableCount})` : '' }}
</button>
</div>
<div class="overflow-x-auto">
<table class="w-full min-w-[1100px] text-xs" data-testid="transfer-precheck-table">
<table class="w-full min-w-[1100px] text-xs" data-testid="transfer-match-table">
<thead>
<tr class="border-b border-default bg-surface-soft text-left text-[11px] text-muted">
<th class="p-2">
<input
type="checkbox"
:checked="allFilteredSelected"
data-testid="transfer-precheck-select-all"
data-testid="transfer-match-select-all"
@change="toggleAll"
/>
</th>
@@ -230,7 +261,7 @@ function reasonTitle(item: TransferPrecheckItem): string | undefined {
v-for="item in filtered"
:key="`${item.source_code}|${item.invoice_no}|${item.material_no}|${item.receipt_date ?? ''}`"
class="border-b border-subtle"
:class="{ 'bg-surface-soft text-muted': !isSelectable(item) }"
:class="{ 'bg-surface-soft text-muted': !isSelectable(item), 'opacity-60': item.stale === true }"
:data-testid="`transfer-item-${item.invoice_no}`"
>
<td class="p-2">
@@ -239,7 +270,7 @@ function reasonTitle(item: TransferPrecheckItem): string | undefined {
:checked="isChecked(item)"
:disabled="!isCheckable(item) || busy"
:data-testid="`transfer-check-${item.invoice_no}`"
@change="emit('toggle', item.invoice_no, ($event.target as HTMLInputElement).checked)"
@change="emit('toggle', item.item_id as number, ($event.target as HTMLInputElement).checked)"
/>
</td>
<td class="p-2">{{ item.source_code }}</td>
@@ -249,11 +280,22 @@ function reasonTitle(item: TransferPrecheckItem): string | undefined {
<td class="p-2">{{ item.material_name }}</td>
<td class="p-2">{{ item.from_warehouse }}</td>
<td class="p-2">{{ deriveBatchNo(item.lot_no) }}</td>
<td class="p-2">{{ item.from_quantity ?? '—' }}</td>
<td class="p-2">
<div>{{ item.from_quantity ?? '—' }}</div>
<!-- 库存查询时刻小字:数据新鲜度溯源(stale 门禁的可见依据) -->
<div
v-if="checkedAtLabel(item)"
class="text-[10px] text-muted"
:title="$t('chat.transfer.stockCheckedAtTitle', { time: checkedAtLabel(item) })"
:data-testid="`transfer-checked-at-${item.invoice_no}`"
>
{{ checkedAtLabel(item) }}
</div>
</td>
<td class="p-2">{{ item.to_warehouse }}</td>
<td class="p-2">{{ item.to_quantity }}</td>
<td class="p-2">
<div class="flex items-center gap-1">
<div class="flex flex-wrap items-center gap-1">
<!-- 阻断原因经悬浮提示(title)透出:不占行高;可执行行也提供重查入口 -->
<span
class="rounded-full px-2 py-0.5 font-bold"
@@ -267,6 +309,21 @@ function reasonTitle(item: TransferPrecheckItem): string | undefined {
>
{{ $t(resultLabel(item.result)) }}
</span>
<!-- 行级警示小标:stale(超 TTL 执行会被拦截)/ 文件版本已过期 -->
<span
v-if="item.stale === true"
class="rounded border border-amber-300 px-1 py-0.5 text-[10px] text-amber-700"
data-testid="transfer-item-stale"
>
{{ $t('chat.transfer.staleRow') }}
</span>
<span
v-if="item.file_current === false"
class="rounded border border-amber-300 px-1 py-0.5 text-[10px] text-amber-700"
data-testid="transfer-item-file-changed"
>
{{ $t('chat.transfer.fileChangedRow') }}
</span>
<button
v-if="isRequeryable(item)"
type="button"
@@ -294,7 +351,7 @@ function reasonTitle(item: TransferPrecheckItem): string | undefined {
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="executeDisabled"
:data-testid="'transfer-generate-button'"
@click="emit('execute', items.filter(isSelectable).filter(isChecked).map((item) => item.invoice_no))"
@click="emit('execute', executableCheckedItemIds)"
>
{{ $t('chat.transfer.generateTransfer') }}
</button>
@@ -1,8 +1,9 @@
/**
* features/chat/components/messages/TransferMessageView.spec.ts
* 用途:验证卡片自驱动接线——预检卡渲染、点“直接生成调拨单”真实调 API 并切换结果卡、
* 用途:验证卡片自驱动接线——匹配卡渲染(勾选键 = 明细 item_id)、点“生成调拨单”
* 真实调 /items/execute 并切换结果卡、恢复处理 = 批量重查(不跳匹配卡)、
* 下载按钮调 requestBlob 封装、结果页无审计入口。
* 依赖:vi.mock(transfer.api)、@vue/test-utils、i18n。
* 依赖:vi.mock(transfer.api)、vi.mock(useMessage)、@vue/test-utils、i18n。
* 逻辑:Mock API 断言调用参数与状态切换(对应后端 197 项测试的契约面)。
*/
import { mount, flushPromises } from '@vue/test-utils';
@@ -10,12 +11,15 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';
import i18n from '@/i18n';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
createTransferMatching: vi.fn(),
getTransferMatching: vi.fn(),
listExecutableTransferItems: vi.fn(),
executeTransferItems: vi.fn(),
getTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
batchRequeryTransferItems: vi.fn(),
batchManualCloseTransferItems: vi.fn(),
downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(),
@@ -26,22 +30,35 @@ const api = vi.hoisted(() => ({
vi.mock('@/features/chat/api/transfer.api', () => api);
const messageMocks = vi.hoisted(() => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => messageMocks,
}));
import TransferMessageView from './TransferMessageView.vue';
import { eligibleReceiptDateTo } from './transferDate';
const payload = {
kind: 'precheck',
kind: 'match',
summary: {
precheck_id: 'TPC-1',
matching_id: 'MTG-1',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
counts: { file_invoice_count: 1, not_matured_count: 0, matched_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200',
estimated_external_write_count: 1,
precheck_hash: 'sha256:x',
matching_hash: 'sha256:x',
},
items: [{
item_id: 101,
source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200',
to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable',
@@ -70,29 +87,29 @@ const runPayload = {
describe('TransferMessageView self-driving wiring', () => {
beforeEach(() => {
vi.clearAllMocks();
api.executeTransferPrecheck.mockResolvedValue({ run_no: 'RUN-1', status: 'success' });
api.executeTransferItems.mockResolvedValue({ run_no: 'RUN-1', status: 'success' });
api.getTransferRun.mockResolvedValue(runPayload.run);
api.downloadTransferReceiptFiles.mockResolvedValue({ blob: new Blob(['z']), filename: 'r.zip' });
api.downloadTransferErpInventory.mockResolvedValue({ blob: new Blob(['c']), filename: 'e.csv' });
});
it('预检 payload 渲染预检卡,且默认勾选可执行项', () => {
it('匹配 payload 渲染匹配卡,且默认按 item_id 勾选可执行行', () => {
const wrapper = mount(TransferMessageView, {
props: { payload },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="transfer-match-card"]').exists()).toBe(true);
expect((wrapper.find('[data-testid="transfer-check-INV-001"]').element as HTMLInputElement).checked).toBe(true);
});
it('点击“直接生成调拨单”调用 execute API 并切换为结果卡', async () => {
it('点击“生成调拨单”按明细行 id 调 /items/execute 并切换为结果卡', async () => {
const wrapper = mount(TransferMessageView, {
props: { payload },
global: { plugins: [i18n] },
});
await wrapper.find('[data-testid="transfer-generate-button"]').trigger('click');
await flushPromises();
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-1', ['INV-001']);
expect(api.executeTransferItems).toHaveBeenCalledWith([101]);
expect(wrapper.find('[data-testid="transfer-result-card"]').exists()).toBe(true);
});
@@ -116,10 +133,12 @@ describe('TransferMessageView self-driving wiring', () => {
expect(wrapper.text()).not.toContain('审计');
});
it('backlog 视图拉取待处理列表,重试/关闭调用对应 API', async () => {
it('backlog 视图拉取待处理列表,行级重查/关闭调用对应 API', async () => {
api.listTransferBacklog.mockResolvedValue([{
item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1',
status: 'blocked_recoverable', reason: '收料 1200 / ERP 1000', age_days: 1, aging_level: 'normal',
receipt_date: '2026-08-05', material_name: '连接器组件', from_warehouse: 'DBS-TRANSIT',
to_warehouse: 'HUB-CN01', lot_no: 'LOT-10', receipt_quantity: '1200', external_quantity: '1000',
}]);
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 1, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
@@ -135,23 +154,156 @@ describe('TransferMessageView self-driving wiring', () => {
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
expect(wrapper.text()).toContain('INV-001');
await wrapper.find('[data-testid="transfer-backlog-retry"]').trigger('click');
// 行级重查(原「重新查询 ERP」改名「重查」,复用单行端点)。
await wrapper.find('[data-testid="transfer-backlog-requery-INV-001"]').trigger('click');
await flushPromises();
expect(api.retryTransferItem).toHaveBeenCalledWith(7);
await wrapper.find('[data-testid="transfer-backlog-close"]').trigger('click');
// 行级关闭:弹窗原因必填后提交。
await wrapper.find('[data-testid="transfer-backlog-close-INV-001"]').trigger('click');
await wrapper.find('[data-testid="transfer-close-reason"]').setValue('线下已处理');
await wrapper.find('[data-testid="transfer-close-confirm"]').trigger('click');
await flushPromises();
expect(api.manualCloseTransferItem).toHaveBeenCalledWith(7, '线下已处理');
});
it('来源实例选择:加载列表 → 确认范围 → 创建预检并切换预检卡', async () => {
it('backlog 批量:勾选后操作条出现,重查/恢复/批量关闭调用对应端点', async () => {
api.listTransferBacklog.mockResolvedValue([
{ item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1', status: 'blocked_recoverable', reason: '', age_days: 0, aging_level: 'normal' },
{ item_id: 8, source_code: 'DBS-AWSBI', invoice_no: 'INV-002', material_no: 'MAT-2', status: 'result_unknown', reason: '', age_days: 2, aging_level: 'result_unknown' },
]);
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 1, closed: 0, unknown: 1, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
});
api.batchRequeryTransferItems.mockResolvedValue({ total: 1, results: [{ item_id: 7, ok: true, status: 'ready_to_execute' }] });
api.batchManualCloseTransferItems.mockResolvedValue({ total: 1, results: [{ item_id: 7, ok: true, status: 'manually_closed' }] });
const wrapper = mount(TransferMessageView, {
props: { payload: { kind: 'backlog' } },
global: { plugins: [i18n] },
});
await flushPromises();
// result_unknown 行 checkbox 禁用(只读隔离)。
expect((wrapper.find('[data-testid="transfer-backlog-check-INV-002"]').element as HTMLInputElement).disabled).toBe(true);
// 未勾选时批量操作条不存在。
expect(wrapper.find('[data-testid="transfer-backlog-batch-requery"]').exists()).toBe(false);
await wrapper.find('[data-testid="transfer-backlog-check-INV-001"]').setValue(true);
expect(wrapper.find('[data-testid="transfer-backlog-batch-requery"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-backlog-batch-requery"]').trigger('click');
await flushPromises();
expect(api.batchRequeryTransferItems).toHaveBeenCalledWith([7]);
// 恢复处理(批量)= 同一批量重查端点(恢复的唯一后端)。
await wrapper.find('[data-testid="transfer-backlog-check-INV-001"]').setValue(true);
await wrapper.find('[data-testid="transfer-backlog-batch-resume"]').trigger('click');
await flushPromises();
expect(api.batchRequeryTransferItems).toHaveBeenCalledWith([7]);
await wrapper.find('[data-testid="transfer-backlog-check-INV-001"]').setValue(true);
await wrapper.find('[data-testid="transfer-backlog-batch-close"]').trigger('click');
await wrapper.find('[data-testid="transfer-close-reason"]').setValue('整批线下处理');
await wrapper.find('[data-testid="transfer-close-confirm"]').trigger('click');
await flushPromises();
expect(api.batchManualCloseTransferItems).toHaveBeenCalledWith([7], '整批线下处理');
});
it('backlog 结果徽标:blocked_file_removed 行显示「文件已移除」,普通阻断仍为「已阻断」', async () => {
// [断言意图] F1(2026-09-23 评审修复):backlog 行带 result_code 后,
// 收料行已从最新文件移除(blocked_file_removed)的行必须与普通数量阻断区分展示。
api.listTransferBacklog.mockResolvedValue([
{ item_id: 9, source_code: 'DBS-AWSBI', invoice_no: 'INV-009', material_no: 'MAT-9', status: 'blocked_recoverable', result_code: 'blocked_file_removed', reason: '收料行已从最新文件移除', age_days: 0, aging_level: 'normal' },
{ item_id: 10, source_code: 'DBS-AWSBI', invoice_no: 'INV-010', material_no: 'MAT-10', status: 'blocked_recoverable', result_code: 'blocked_quantity_mismatch', reason: '收料 300 / ERP 280', age_days: 0, aging_level: 'normal' },
]);
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 2, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
});
const wrapper = mount(TransferMessageView, {
props: { payload: { kind: 'backlog' } },
global: { plugins: [i18n] },
});
await flushPromises();
const removedBadge = wrapper.find('[data-testid="transfer-backlog-INV-009"] [data-testid="transfer-backlog-result"]');
const normalBadge = wrapper.find('[data-testid="transfer-backlog-INV-010"] [data-testid="transfer-backlog-result"]');
expect(removedBadge.text()).toContain('文件已移除');
expect(normalBadge.text()).toContain('已阻断');
expect(normalBadge.text()).not.toContain('文件已移除');
});
it('可调拨明细视图:加载全局可执行行,勾选后按行生成调拨单', async () => {
// [断言意图] 行归属解耦后的执行入口:executable 视图聚合全部可执行行,
// 勾选(item_id)→ /items/execute → 结果卡,恢复后的行在此闭环。
api.listExecutableTransferItems.mockResolvedValue({ items: [{
item_id: 77, source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200',
to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable',
checked_at: '2026-09-23T10:21:00', stale: false, file_current: true,
}], counts: { executable_count: 1 } });
api.executeTransferItems.mockResolvedValue({ run_no: 'RUN-9', status: 'success' });
api.getTransferRun.mockResolvedValue(runPayload.run);
const wrapper = mount(TransferMessageView, {
props: { payload: { kind: 'executable' } },
global: { plugins: [i18n] },
});
await flushPromises();
expect(api.listExecutableTransferItems).toHaveBeenCalled();
expect(wrapper.find('[data-testid="transfer-executable-card"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-executable-check-INV-001"]').setValue(true);
await wrapper.find('[data-testid="transfer-executable-generate"]').trigger('click');
await flushPromises();
expect(api.executeTransferItems).toHaveBeenCalledWith([77]);
expect(wrapper.find('[data-testid="transfer-result-card"]').exists()).toBe(true);
});
it('恢复处理(恢复=重查):按明细 id 调 batch-requery,留在待处理池并统计提示', async () => {
// [断言意图] 行式执行重构(2026-09-23):恢复处理不再重建/打开匹配卡,
// 语义收敛为按明细 id 重查库存;结果按 status 统计(ready_to_execute=已恢复),
// 完成后留在待处理池(fail-closed),toast 汇总 recovered/blocked。
api.listTransferBacklog.mockResolvedValue([
{ item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1', status: 'blocked_recoverable', reason: '', age_days: 0, aging_level: 'normal' },
{ item_id: 8, source_code: 'DBS-AWSBI', invoice_no: 'INV-002', material_no: 'MAT-2', status: 'blocked_recoverable', reason: '', age_days: 1, aging_level: 'normal' },
]);
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 2, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
});
api.batchRequeryTransferItems.mockResolvedValue({
total: 2,
results: [
{ item_id: 7, invoice_no: 'INV-001', ok: true, status: 'ready_to_execute' },
{ item_id: 8, invoice_no: 'INV-002', ok: true, status: 'blocked_recoverable' },
],
});
const wrapper = mount(TransferMessageView, {
props: { payload: { kind: 'backlog' } },
global: { plugins: [i18n] },
});
await flushPromises();
await wrapper.find('[data-testid="transfer-backlog-check-INV-001"]').setValue(true);
await wrapper.find('[data-testid="transfer-backlog-batch-resume"]').trigger('click');
await flushPromises();
expect(api.batchRequeryTransferItems).toHaveBeenCalledWith([7]);
expect(api.getTransferMatching).not.toHaveBeenCalled();
expect(wrapper.find('[data-testid="transfer-match-card"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
// 恢复统计 toast:1 笔已可执行 · 1 笔仍阻断。
expect(messageMocks.success).toHaveBeenCalledTimes(1);
const toastText = String(messageMocks.success.mock.calls[0][0]);
expect(toastText).toContain('可执行');
expect(toastText).toContain('仍阻断');
});
it('来源实例选择:加载列表 → 确认范围 → 创建匹配并切换匹配卡(默认携带 D+1 日期范围)', async () => {
api.listTransferSources.mockResolvedValue([
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
]);
api.createTransferPrecheck.mockResolvedValue(payload.summary);
api.getTransferPrecheck.mockResolvedValue({
api.createTransferMatching.mockResolvedValue(payload.summary);
api.getTransferMatching.mockResolvedValue({
summary: payload.summary,
items: payload.items,
sources: payload.sources,
@@ -167,7 +319,12 @@ describe('TransferMessageView self-driving wiring', () => {
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
await flushPromises();
expect(api.createTransferPrecheck).toHaveBeenCalledWith({ source_codes: ['DBS-AWSBI'], transfer_type: 'in_transit_to_hub' });
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
const cutoff = eligibleReceiptDateTo();
expect(api.createTransferMatching).toHaveBeenCalledWith({
source_codes: ['DBS-AWSBI'], business_date: undefined,
receipt_date_from: cutoff, receipt_date_to: cutoff,
transfer_type: 'in_transit_to_hub',
});
expect(wrapper.find('[data-testid="transfer-match-card"]').exists()).toBe(true);
});
});
@@ -1,28 +1,33 @@
<!--
features/chat/components/messages/TransferMessageView.vue
用途:在途调拨消息卡片的自驱动挂载视图——按 payload 形态渲染卡片,并把卡片按钮
(直接生成调拨单 / 下载 / 重试 / 关闭)经 useChatTransfer 真实调用 API。
(生成调拨单 / 下载 / 重查 / 恢复处理 / 关闭)经 useChatTransfer 真实调用 API。
依赖:Transfer*Card、useChatTransfer、i18n chat.transfer.*。
逻辑:payload 作为初始状态(ChatLog 回放);执行后切换为结果卡;下载走 requestBlob;
逻辑:payload 作为初始状态(ChatLog 回放;历史行无 item_id 仅展示不可选);仅携带
matching_id 时按 ID 恢复匹配卡(最近匹配入口);勾选/执行按明细 item_id;
恢复处理 = 按明细 id 重查库存(batch-requery 唯一后端),完成后刷新待处理池并
统计提示,不再跳转匹配卡;执行后切换为结果卡;下载走 requestBlob;
不展示执行审计入口(决策 19)。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import TransferPrecheckCard from './TransferPrecheckCard.vue';
import { useI18n } from 'vue-i18n';
import TransferMatchCard from './TransferMatchCard.vue';
import TransferFileProgressCard from './TransferFileProgressCard.vue';
import TransferProgressCard from './TransferProgressCard.vue';
import TransferResultCard from './TransferResultCard.vue';
import TransferBacklogSummaryCard from './TransferBacklogSummaryCard.vue';
import TransferExecutableCard from './TransferExecutableCard.vue';
import TransferManualCloseDialog from './TransferManualCloseDialog.vue';
import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
import { useChatTransfer } from '../../composables/useChatTransfer';
import { downloadTransferSourceFiles, getTransferPrecheck, requeryTransferItems } from '../../api/transfer.api';
import { downloadTransferSourceFiles, getTransferMatching, requeryTransferMatchingItems } from '../../api/transfer.api';
import { triggerBlobDownload } from '@/shared/utils/download';
import { useMessage } from '@/shared/composables/useMessage';
import type {
TransferBacklogItem,
TransferPrecheckItem,
TransferPrecheckSummary,
TransferMatchingItem,
TransferMatchingSummary,
TransferRunResult,
TransferSourceProgress,
TransferType,
@@ -32,22 +37,31 @@ const props = defineProps<{
payload?: Record<string, unknown> | null;
}>();
const { error: notifyError } = useMessage();
const { t } = useI18n();
const { error: notifyError, success: notifySuccess } = useMessage();
/** 统一错误提示:BusinessError 带本地化 message,其余回退到 String(e)。 */
function reportError(e: unknown) {
notifyError(e instanceof Error ? e.message : String(e));
}
const kind = computed(() => String(props.payload?.kind ?? 'precheck'));
const kind = computed(() => String(props.payload?.kind ?? 'match'));
const mode = ref(kind.value);
const summaryRef = ref<TransferPrecheckSummary | null>((props.payload?.summary as TransferPrecheckSummary) ?? null);
const items = ref<TransferPrecheckItem[]>((props.payload?.items as TransferPrecheckItem[]) ?? []);
/** backlog 初始筛选(首页计数卡切片进入:recoverable/closed/unknown;白名单外回落 all)。 */
const backlogInitialFilter = computed<'all' | 'recoverable' | 'closed' | 'unknown'>(() => {
const value = String(props.payload?.filter ?? 'all');
const allowed = ['all', 'recoverable', 'closed', 'unknown'] as const;
return (allowed as readonly string[]).includes(value) ? (value as (typeof allowed)[number]) : 'all';
});
const summaryRef = ref<TransferMatchingSummary | null>((props.payload?.summary as TransferMatchingSummary) ?? null);
const items = ref<TransferMatchingItem[]>((props.payload?.items as TransferMatchingItem[]) ?? []);
const runNo = ref(String(props.payload?.run_no ?? ''));
const status = ref(String(props.payload?.status ?? 'executing'));
const run = ref<TransferRunResult | null>((props.payload?.run as TransferRunResult) ?? null);
const busy = ref(false);
const closeTarget = ref<TransferBacklogItem | null>(null);
/** 批量标记无需处理的明细 id 集合(与单行关闭共用同一弹窗)。 */
const batchCloseIds = ref<number[]>([]);
/** 正在重试收料 RPA 的来源编码集合(按来源独立展示重试中)。 */
const retryingSource = ref<Set<string>>(new Set());
@@ -61,24 +75,28 @@ onMounted(() => {
if (kind.value === 'source-select') {
void transfer.loadSources();
}
if (kind.value === 'executable') {
void transfer.loadExecutableItems();
}
});
/** payload 更新时重置本地状态(历史回放/刷新);初始化组合式函数上下文 */
function applyPayload(payload?: Record<string, unknown> | null) {
if (!payload) return;
mode.value = String(payload.kind ?? 'precheck');
summaryRef.value = (payload.summary as TransferPrecheckSummary) ?? null;
items.value = (payload.items as TransferPrecheckItem[]) ?? [];
mode.value = String(payload.kind ?? 'match');
summaryRef.value = (payload.summary as TransferMatchingSummary) ?? null;
items.value = (payload.items as TransferMatchingItem[]) ?? [];
runNo.value = String(payload.run_no ?? '');
status.value = String(payload.status ?? 'executing');
run.value = (payload.run as TransferRunResult) ?? null;
const summaryValue = (payload.summary as TransferPrecheckSummary) ?? null;
const summaryValue = (payload.summary as TransferMatchingSummary) ?? null;
if (summaryValue) {
transfer.precheckId.value = summaryValue.precheck_id;
transfer.matchingId.value = summaryValue.matching_id;
// 默认勾选可执行明细行(按 item_id);历史回放行无 item_id 不参与勾选
transfer.selected.value = new Set(
(payload.items as TransferPrecheckItem[] ?? [])
.filter((item) => item.result === 'executable')
.map((item) => item.invoice_no),
((payload.items as TransferMatchingItem[]) ?? [])
.filter((item) => item.result === 'executable' && item.item_id != null)
.map((item) => item.item_id as number),
);
}
if (runNo.value) {
@@ -105,17 +123,21 @@ async function onDownloadSources(sourceCodes: string[]) {
/** 重新获取 ERP 库存:批量重查后用服务端明细原位刷新(保留勾选中仍阻断的行) */
async function onRequery(invoiceNos: string[]) {
if (!invoiceNos.length || !transfer.precheckId.value) return;
if (!invoiceNos.length || !transfer.matchingId.value) return;
busy.value = true;
try {
await requeryTransferItems(transfer.precheckId.value, invoiceNos);
const detail = await getTransferPrecheck(transfer.precheckId.value);
await requeryTransferMatchingItems(transfer.matchingId.value, invoiceNos);
const detail = await getTransferMatching(transfer.matchingId.value);
items.value = detail.items;
if (detail.summary) summaryRef.value = detail.summary;
const stillBlocked = new Set(
items.value.filter((item) => String(item.result).startsWith('blocked_')).map((item) => item.invoice_no),
const stillBlockedIds = new Set(
items.value
.filter((item) => String(item.result).startsWith('blocked_') && item.item_id != null)
.map((item) => item.item_id as number),
);
transfer.selected.value = new Set(
[...transfer.selected.value].filter((id) => stillBlockedIds.has(id)),
);
transfer.selected.value = new Set([...transfer.selected.value].filter((no) => stillBlocked.has(no)));
} catch (e) {
reportError(e);
} finally {
@@ -123,11 +145,26 @@ async function onRequery(invoiceNos: string[]) {
}
}
/** 直接生成调拨单(决策 4/5:无独立确认页) */
async function onExecute(invoiceNos: string[]) {
/** 可调拨明细行重查:逐行核对最新库存后刷新队列(行级 retry 不依赖匹配) */
async function onExecutableRequery(itemIds: number[]) {
busy.value = true;
try {
transfer.selected.value = new Set(invoiceNos);
for (const itemId of itemIds) {
await transfer.retry(itemId);
}
await transfer.loadExecutableItems();
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
/** 按勾选明细行直接生成调拨单(item-centric:门禁在后端,失败经 reportError 展示) */
async function onExecute(itemIds: number[]) {
busy.value = true;
try {
transfer.selected.value = new Set(itemIds);
const outcome = await transfer.execute();
if (outcome) {
mode.value = 'result';
@@ -178,16 +215,13 @@ async function onBacklogRetry(itemId: number) {
}
}
function onBacklogClose(item: TransferBacklogItem) {
closeTarget.value = item;
}
async function onCloseConfirm(reason: string) {
if (!closeTarget.value) return;
/** 批量重查(待处理池多选):逐行隔离,完成后刷新列表并弹汇总。 */
async function onBacklogRequery(itemIds: number[]) {
busy.value = true;
try {
await transfer.manualClose(closeTarget.value.item_id, reason);
closeTarget.value = null;
const result = await transfer.batchRequery(itemIds);
const ok = result.results.filter((entry) => entry.ok).length;
notifySuccess(t('chat.transfer.toastRequeryDone', { ok, failed: result.total - ok }));
await transfer.loadBacklog();
} catch (e) {
reportError(e);
@@ -196,7 +230,59 @@ async function onCloseConfirm(reason: string) {
}
}
/** 来源实例选择确认 → 创建预检并切换预检卡(决策 4:两步第一步;收料日期范围为查询范围;调拨类型决定数据范围) */
/** 恢复处理(行级/多选):恢复语义 = 按明细 id 重查库存(batch-requery 唯一后端);
* 完成后刷新待处理池,并按结果统计提示(ready_to_execute 计为已可执行,其余仍阻断);
* 不再跳转匹配卡(行式执行重构后恢复与匹配卡解耦)。 */
async function onBacklogResume(itemIds: number[]) {
busy.value = true;
try {
const result = await transfer.resume(itemIds);
await transfer.loadBacklog();
const recovered = result.results.filter((entry) => entry.status === 'ready_to_execute').length;
const still = result.total - recovered;
notifySuccess(t('chat.transfer.toastRequeryRecovered', { recovered, blocked: still }));
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
function onBacklogClose(item: TransferBacklogItem) {
closeTarget.value = item;
}
/** 批量标记无需处理:复用关闭弹窗(批量文案)。 */
function onBacklogBatchClose(itemIds: number[]) {
batchCloseIds.value = itemIds;
}
function onCancelClose() {
closeTarget.value = null;
batchCloseIds.value = [];
}
async function onCloseConfirm(reason: string) {
busy.value = true;
try {
if (batchCloseIds.value.length) {
const result = await transfer.batchManualClose(batchCloseIds.value, reason);
const ok = result.results.filter((entry) => entry.ok).length;
notifySuccess(t('chat.transfer.toastCloseDone', { ok, failed: result.total - ok }));
batchCloseIds.value = [];
} else if (closeTarget.value) {
await transfer.manualClose(closeTarget.value.item_id, reason);
closeTarget.value = null;
}
await transfer.loadBacklog();
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
/** 来源实例选择确认 → 创建匹配并切换匹配卡(决策 4:两步第一步;收料日期范围为查询范围;调拨类型决定数据范围) */
async function onSourceConfirm(
sourceCodes: string[],
dateRange?: { from?: string; to?: string },
@@ -204,9 +290,9 @@ async function onSourceConfirm(
) {
busy.value = true;
try {
await transfer.createPrecheck(sourceCodes, undefined, dateRange, transferType);
mode.value = 'precheck';
summaryRef.value = transfer.precheck.value;
await transfer.createMatching(sourceCodes, undefined, dateRange, transferType);
mode.value = 'match';
summaryRef.value = transfer.matching.value;
items.value = transfer.items.value;
run.value = null;
} catch (e) {
@@ -250,19 +336,27 @@ async function onSourceRetry(sourceCodes: string[]) {
@download="onDownloadSources"
@retry="onSourceRetry"
/>
<TransferPrecheckCard
v-else-if="mode === 'precheck' && summaryRef"
<TransferMatchCard
v-else-if="mode === 'match' && summaryRef"
:summary="summaryRef"
:items="items"
:sources="transfer.sources.value"
:selected="transfer.selected.value"
:requery-busy="busy"
:busy="busy"
@toggle="(invoiceNo, checked) => transfer.toggleSelect(invoiceNo, checked)"
@toggle-all="(invoiceNos, checked) => invoiceNos.forEach((no) => transfer.toggleSelect(no, checked))"
@toggle="(itemId, checked) => transfer.toggleSelect(itemId, checked)"
@toggle-all="(itemIds, checked) => itemIds.forEach((id) => transfer.toggleSelect(id, checked))"
@requery="onRequery"
@execute="onExecute"
/>
<TransferExecutableCard
v-else-if="mode === 'executable'"
:items="transfer.executableItems.value"
:busy="busy"
@refresh="() => transfer.loadExecutableItems()"
@requery="onExecutableRequery"
@execute="onExecute"
/>
<TransferProgressCard v-else-if="mode === 'progress'" :run-no="runNo" :status="status" :busy="busy" />
<TransferResultCard
v-else-if="mode === 'result' && run"
@@ -274,16 +368,22 @@ async function onSourceRetry(sourceCodes: string[]) {
<TransferBacklogSummaryCard
v-else-if="mode === 'backlog'"
:items="transfer.backlog.value"
:busy="busy"
:initial-filter="backlogInitialFilter"
@retry="onBacklogRetry"
@requery="onBacklogRequery"
@resume="onBacklogResume"
@close="onBacklogClose"
@batch-close="onBacklogBatchClose"
@refresh="() => transfer.loadBacklog()"
/>
<TransferManualCloseDialog
v-if="closeTarget"
:open="Boolean(closeTarget)"
:invoice-no="closeTarget.invoice_no"
v-if="closeTarget || batchCloseIds.length"
:open="Boolean(closeTarget || batchCloseIds.length)"
:invoice-no="closeTarget?.invoice_no ?? ''"
:count="batchCloseIds.length"
@confirm="onCloseConfirm"
@cancel="closeTarget = null"
@cancel="onCancelClose"
/>
</div>
</template>
@@ -25,7 +25,7 @@ function reasonLabel(reason: string): string {
business_failed: 'chat.transfer.exceptionBusinessFailed',
technical_failed: 'chat.transfer.exceptionTechnicalFailed',
result_unknown: 'chat.transfer.resultUnknown',
precheck_expired: 'chat.transfer.exceptionPrecheckExpired',
matching_expired: 'chat.transfer.exceptionMatchExpired',
};
return map[reason] ?? 'chat.transfer.resultBlocked';
}
@@ -4,12 +4,13 @@
* 确认提交、重试收料 RPA。
* 依赖:@vue/test-utils、i18n。
* 逻辑:平台 DBS/Crane 仅分组;实例为选择与执行边界(决策 2/3/4);
* 所选来源需至少一个 has_ready_file 才能确认预检(决策:无 ready 文件禁止确认)。
* 所选来源需至少一个 has_ready_file 才能确认匹配(决策:无 ready 文件禁止确认)。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
import { eligibleReceiptDateTo } from './transferDate';
const readySources = [
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI 在途仓', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
@@ -85,7 +86,33 @@ describe('TransferSourceSelectCard', () => {
it('D+1 规则提示收进 ⓘ 悬浮(title),不再平铺占宽', () => {
// [断言意图] 长规则文案通过原生 title 渐进披露,紧凑日期行不换行错位。
const wrapper = mountCard();
expect(wrapper.find('[data-testid="transfer-source-date-hint"]').attributes('title')).toBe('截止不超出 D+1 规则(业务日期前一天)');
const title = wrapper.find('[data-testid="transfer-source-date-hint"]').attributes('title') ?? '';
expect(title).toContain('D+1 规则');
expect(title).toContain('业务日期前一天');
});
it('收料日期默认为 D+1 规则日期(T-1)且上限锁定(输入期限制)', () => {
// [断言意图] 默认值与 max 均为上海口径 T-1,未来日期在选择器层面不可选。
const wrapper = mountCard();
const from = wrapper.find('[data-testid="transfer-source-date-from"]').element as HTMLInputElement;
const to = wrapper.find('[data-testid="transfer-source-date-to"]').element as HTMLInputElement;
const cutoff = eligibleReceiptDateTo();
expect(from.value).toBe(cutoff);
expect(to.value).toBe(cutoff);
expect(from.max).toBe(cutoff);
expect(to.max).toBe(cutoff);
});
it('起始晚于截止时行内提示并禁用确认(不等提交报错)', async () => {
// [断言意图] 日期维护期即时卡控:非法区间直接禁用确认并显示行内红字。
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-date-from"]').setValue('2026-09-20');
await wrapper.find('[data-testid="transfer-source-date-to"]').setValue('2026-09-10');
expect(wrapper.find('[data-testid="transfer-source-date-invalid"]').exists()).toBe(true);
expect((wrapper.find('[data-testid="transfer-source-confirm"]').element as HTMLButtonElement).disabled).toBe(true);
await wrapper.find('[data-testid="transfer-source-date-to"]').setValue('2026-09-22');
expect(wrapper.find('[data-testid="transfer-source-date-invalid"]').exists()).toBe(false);
});
it('“只选可重试”勾选无文件/失败来源', async () => {
@@ -1,11 +1,11 @@
<!--
features/chat/components/messages/TransferSourceSelectCard.vue
用途:来源实例选择卡(决策 2/3/4:手工两步第一步)——按平台 DBS/Crane 分组勾选实例,
选择调拨类型后“确认范围并预检”发起预检。
选择调拨类型后“确认范围并匹配”发起匹配。
依赖:props.sources、i18n chat.transfer.*。
逻辑:预检参数区(调拨类型 + 收料日期,确认时一并提交)→ 选择辅助/上下文操作条
逻辑:匹配参数区(调拨类型 + 收料日期,确认时一并提交)→ 选择辅助/上下文操作条
(有选中时原位替换辅助区,承载批量重试/下载/清空选择)→ 平台分组来源列表
(平台仅分组不可直接执行)→ 底部唯一实心主按钮「确认范围并预检」(未选禁用);
(平台仅分组不可直接执行)→ 底部唯一实心主按钮「确认范围并匹配」(未选禁用);
调拨类型决定收料数据范围(类型 1 仅纳入 INVOICE 前缀 HOM/HOX/WTP),
类型 2/3 一期占位(禁用,后端同样 fail-closed)。
-->
@@ -13,6 +13,7 @@
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import { eligibleReceiptDateTo } from './transferDate';
import type { TransferSourceOption, TransferType } from '../../types/transfer.types';
const props = defineProps<{
@@ -33,10 +34,19 @@ const { warning: notifyWarning } = useMessage();
const { t } = useI18n();
const selected = ref<Set<string>>(new Set());
/** 收料日期范围(预检查询范围);截止不得超出 D+1 规则(后端卡控)。 */
const dateFrom = ref('');
const dateTo = ref('');
/** 调拨业务类型:决定本次预检纳入哪些收料数据;一期仅类型 1 开放。 */
/** 收料日期范围(匹配查询范围):默认 D+1 规则日期(T-1),上限同(输入期限制,
* 不等提交报错);后端 RECEIPT_DATE_RANGE_INVALID 卡控保留为双保险。 */
const maxReceiptDate = eligibleReceiptDateTo();
const dateFrom = ref(maxReceiptDate);
const dateTo = ref(maxReceiptDate);
/** 起始不得晚于截止(清空视为不限,提交 undefined)。 */
const dateRangeInvalid = computed(() => {
const from = dateFrom.value || null;
const to = dateTo.value || null;
return from !== null && to !== null && from > to;
});
/** 调拨业务类型:决定本次匹配纳入哪些收料数据;一期仅类型 1 开放。 */
const transferType = ref<TransferType>('in_transit_to_hub');
/** 类型选项元数据;enabled=false 为占位类型(UI 禁用 + 后端 fail-closed 双保险)。 */
@@ -66,11 +76,13 @@ const selectedRetryableCount = computed(() =>
);
const batchRetryDisabled = computed(() => props.busy || selectedRetryableCount.value === 0);
/** 已选来源中是否有具备 ready 文件的(门禁:都无 ready 文件则禁止确认预检)。 */
/** 已选来源中是否有具备 ready 文件的(门禁:都无 ready 文件则禁止确认匹配)。 */
const selectedHasReadyFile = computed(() =>
[...selected.value].some((code) => props.sources.find((s) => s.source_code === code)?.has_ready_file),
);
const confirmDisabled = computed(() => props.busy || selectedCount.value === 0 || !selectedHasReadyFile.value);
const confirmDisabled = computed(() =>
props.busy || selectedCount.value === 0 || !selectedHasReadyFile.value || dateRangeInvalid.value,
);
const downloadDisabled = computed(() => props.busy || !selectedHasReadyFile.value);
function toggle(sourceCode: string, checked: boolean) {
@@ -143,9 +155,9 @@ function confirm() {
<h3 class="mb-1 text-sm font-bold text-primary">{{ $t('chat.transfer.sourceSelectTitle') }}</h3>
<p class="mb-3 text-xs text-muted">{{ $t('chat.transfer.sourceSelectHint') }}</p>
<!-- [ZONE 1] 预检参数区:调拨类型 + 收料日期同组(确认预检时一并提交,参数先行定范围)。 -->
<!-- [ZONE 1] 匹配参数区:调拨类型 + 收料日期同组(确认匹配时一并提交,参数先行定范围)。 -->
<div class="mb-3 rounded-lg border border-subtle p-3" data-testid="transfer-source-params">
<p class="mb-2 text-[11px] font-bold text-muted">{{ $t('chat.transfer.precheckParams') }}</p>
<p class="mb-2 text-[11px] font-bold text-muted">{{ $t('chat.transfer.matchParams') }}</p>
<div class="flex flex-wrap items-center gap-2">
<span class="text-xs font-bold text-secondary">{{ $t('chat.transfer.transferTypeLabel') }}</span>
<button
@@ -170,6 +182,7 @@ function confirm() {
<input
v-model="dateFrom"
type="date"
:max="maxReceiptDate"
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
data-testid="transfer-source-date-from"
/>
@@ -177,6 +190,8 @@ function confirm() {
<input
v-model="dateTo"
type="date"
:max="maxReceiptDate"
:min="dateFrom || undefined"
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
data-testid="transfer-source-date-to"
/>
@@ -186,6 +201,10 @@ function confirm() {
:title="$t('chat.transfer.receiptDateHint')"
data-testid="transfer-source-date-hint"
>ⓘ</span>
<!-- 输入期校验:起始晚于截止时行内提示并禁用确认(不等提交报错)。 -->
<span v-if="dateRangeInvalid" class="text-xs font-bold text-red-600" data-testid="transfer-source-date-invalid">
{{ $t('chat.transfer.receiptDateInvalid') }}
</span>
</div>
</div>
@@ -338,7 +357,7 @@ function confirm() {
data-testid="transfer-source-confirm"
@click="confirm"
>
{{ $t('chat.transfer.confirmScopeAndPrecheck') }}
{{ $t('chat.transfer.confirmScopeAndMatch') }}
</button>
</div>
</div>
@@ -1,6 +1,6 @@
/**
* features/chat/components/messages/transferCards.spec.ts
* 用途:验证在途调拨三张核心卡片(文件进度/预检/结果)+ 关闭弹窗的交互与禁用语义。
* 用途:验证在途调拨三张核心卡片(文件进度/匹配/结果)+ 关闭弹窗的交互与禁用语义。
* 依赖:@vue/test-utils、i18n、transfer.types。
* 逻辑:断言按钮禁用、勾选禁用、ERP 单号展开/收起、异常展示、下载按钮与
* 结果页不出现“查看执行审计”入口(决策 19)。
@@ -9,27 +9,27 @@ import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import TransferFileProgressCard from './TransferFileProgressCard.vue';
import TransferPrecheckCard from './TransferPrecheckCard.vue';
import TransferMatchCard from './TransferMatchCard.vue';
import TransferResultCard from './TransferResultCard.vue';
import TransferManualCloseDialog from './TransferManualCloseDialog.vue';
const mountOptions = { global: { plugins: [i18n] } };
const summary = {
precheck_id: 'TPC-1',
matching_id: 'MTG-1',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 3, not_matured_count: 1, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
counts: { file_invoice_count: 3, not_matured_count: 1, matched_count: 2, executable_count: 2, blocked_count: 0 },
estimated_transfer_quantity: '2400',
estimated_external_write_count: 2,
precheck_hash: 'sha256:x',
matching_hash: 'sha256:x',
};
const items = [
{ source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器', specification: 'A', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: '控制器', specification: 'B', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
{ item_id: 101, source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器', specification: 'A', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable', checked_at: '2026-09-23T09:05:00+08:00' },
{ item_id: 102, source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: '控制器', specification: 'B', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
];
describe('TransferFileProgressCard', () => {
@@ -46,41 +46,88 @@ describe('TransferFileProgressCard', () => {
});
});
describe('TransferPrecheckCard', () => {
it('阻断/未成熟项 checkbox 禁用;可执行项可选', () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set(['INV-001']) },
describe('TransferMatchCard', () => {
it('勾选键为明细行 item_id:阻断/未成熟项 checkbox 禁用,可执行项可选', () => {
const wrapper = mount(TransferMatchCard, {
props: { summary, items, selected: new Set<number>([101]) },
...mountOptions,
});
const executableCheck = wrapper.find('[data-testid="transfer-check-INV-001"]');
const maturedCheck = wrapper.find('[data-testid="transfer-check-INV-041"]');
expect((executableCheck.element as HTMLInputElement).disabled).toBe(false);
expect((executableCheck.element as HTMLInputElement).checked).toBe(true);
expect((maturedCheck.element as HTMLInputElement).disabled).toBe(true);
});
it('历史回放行(无 item_id)checkbox 禁用,防误选', () => {
// [断言意图] 行式执行重构(2026-09-23):chat 消息流回放的旧 payload 行没有
// item_id,不能作为执行勾选键;这类行必须禁选(防误选后 400)。
const legacyItems = [{ ...items[0], item_id: undefined }];
const wrapper = mount(TransferMatchCard, {
props: { summary, items: legacyItems, selected: new Set<number>() },
...mountOptions,
});
expect((wrapper.find('[data-testid="transfer-check-INV-001"]').element as HTMLInputElement).disabled).toBe(true);
expect((wrapper.find('[data-testid="transfer-generate-button"]').element as HTMLButtonElement).disabled).toBe(true);
});
it('未选择任何项时生成按钮禁用', () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set() },
const wrapper = mount(TransferMatchCard, {
props: { summary, items, selected: new Set<number>() },
...mountOptions,
});
expect((wrapper.find('[data-testid="transfer-generate-button"]').element as HTMLButtonElement).disabled).toBe(true);
});
it('busy 时生成按钮禁用', () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set(['INV-001']), busy: true },
const wrapper = mount(TransferMatchCard, {
props: { summary, items, selected: new Set<number>([101]), busy: true },
...mountOptions,
});
expect((wrapper.find('[data-testid="transfer-generate-button"]').element as HTMLButtonElement).disabled).toBe(true);
});
it('点击生成按钮仅提交可执行勾选项', async () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set(['INV-001']) },
it('点击生成按钮提交可执行勾选行的 item_id 数组', async () => {
const wrapper = mount(TransferMatchCard, {
props: { summary, items, selected: new Set<number>([101]) },
...mountOptions,
});
await wrapper.find('[data-testid="transfer-generate-button"]').trigger('click');
expect(wrapper.emitted('execute')?.[0][0]).toEqual(['INV-001']);
expect(wrapper.emitted('execute')?.[0][0]).toEqual([101]);
});
it('库存数量下方小字展示查询时刻(HH:mm)', () => {
const wrapper = mount(TransferMatchCard, {
props: { summary, items, selected: new Set<number>() },
...mountOptions,
});
const cell = wrapper.find('[data-testid="transfer-checked-at-INV-001"]');
expect(cell.exists()).toBe(true);
expect(cell.text()).toMatch(/^\d{2}:\d{2}$/);
expect(wrapper.find('[data-testid="transfer-checked-at-INV-041"]').exists()).toBe(false);
});
it('stale 行置灰 + 重查小标;file_current=false 行展示文件更新小标', () => {
const flaggedItems = [
{ ...items[0], stale: true, file_current: false },
];
const wrapper = mount(TransferMatchCard, {
props: { summary, items: flaggedItems, selected: new Set<number>() },
...mountOptions,
});
const row = wrapper.find('[data-testid="transfer-item-INV-001"]');
expect(row.classes()).toContain('opacity-60');
expect(wrapper.find('[data-testid="transfer-item-stale"]').text()).toContain('重查');
expect(wrapper.find('[data-testid="transfer-item-file-changed"]').text()).toContain('重新匹配');
});
it('blocked_file_removed 结果行展示「文件已移除」独立徽标', () => {
const removedItems = [{ ...items[0], result: 'blocked_file_removed' }];
const wrapper = mount(TransferMatchCard, {
props: { summary, items: removedItems, selected: new Set<number>() },
...mountOptions,
});
expect(wrapper.find('[data-testid="transfer-item-result"]').text()).toContain('文件已移除');
});
it('同 Invoice 跨收料日期拆票(重复 invoice_no)时,筛选后仅渲染匹配行', async () => {
@@ -89,16 +136,16 @@ describe('TransferPrecheckCard', () => {
// 筛选后不匹配行残留/克隆(用户输入 HOX 仍见 SLC2PHX 行)。
// 行身份 = (来源, Invoice, 料号, 收料日期),key 必须用同一粒度。
const dupItems = [
{ source_code: 'CRANE', material_no: 'M-1', material_name: '机框', specification: '', invoice_no: 'HOX-1', receipt_date: '2026-09-11', from_warehouse: 'HTP-D43', from_quantity: null, to_warehouse: 'HTP-D49', to_quantity: '36', result: 'blocked_quantity_mismatch' },
{ source_code: 'CRANE', material_no: 'M-2', material_name: '护罩', specification: '', invoice_no: 'DUP-1', receipt_date: '2026-09-03', from_warehouse: 'HTP-D43', from_quantity: null, to_warehouse: 'HTP-D49', to_quantity: '36', result: 'blocked_quantity_mismatch' },
{ source_code: 'CRANE', material_no: 'M-2', material_name: '护罩', specification: '', invoice_no: 'DUP-1', receipt_date: '2026-09-04', from_warehouse: 'HTP-D43', from_quantity: null, to_warehouse: 'HTP-D49', to_quantity: '36', result: 'blocked_quantity_mismatch' },
{ item_id: 201, source_code: 'CRANE', material_no: 'M-1', material_name: '机框', specification: '', invoice_no: 'HOX-1', receipt_date: '2026-09-11', from_warehouse: 'HTP-D43', from_quantity: null, to_warehouse: 'HTP-D49', to_quantity: '36', result: 'blocked_quantity_mismatch' },
{ item_id: 202, source_code: 'CRANE', material_no: 'M-2', material_name: '护罩', specification: '', invoice_no: 'DUP-1', receipt_date: '2026-09-03', from_warehouse: 'HTP-D43', from_quantity: null, to_warehouse: 'HTP-D49', to_quantity: '36', result: 'blocked_quantity_mismatch' },
{ item_id: 203, source_code: 'CRANE', material_no: 'M-2', material_name: '护罩', specification: '', invoice_no: 'DUP-1', receipt_date: '2026-09-04', from_warehouse: 'HTP-D43', from_quantity: null, to_warehouse: 'HTP-D49', to_quantity: '36', result: 'blocked_quantity_mismatch' },
];
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items: dupItems, selected: new Set() },
const wrapper = mount(TransferMatchCard, {
props: { summary, items: dupItems, selected: new Set<number>() },
...mountOptions,
});
expect(wrapper.findAll('tbody tr').length).toBe(3);
await wrapper.find('[data-testid="transfer-precheck-filter"]').setValue('HOX');
await wrapper.find('[data-testid="transfer-match-filter"]').setValue('HOX');
const rows = wrapper.findAll('tbody tr');
expect(rows.length).toBe(1);
expect(rows[0].text()).toContain('HOX-1');
@@ -0,0 +1,26 @@
/**
* features/chat/components/messages/transferDate.ts
* 用途:在途调拨业务日期工具——按 Asia/Shanghai 计算业务日期(T)与
* D+1 成熟规则的可匹配截止日(T-1),与后端 date_policy 完全同口径。
* 依赖:无(纯函数,便于单测)。
* 逻辑:浏览器本地时区不可靠(部署/用户时区任意),必须固定上海时区口径,
* 否则前端日期上限与后端 TRANSFER.RECEIPT_DATE_RANGE_INVALID 卡控会漂移。
*/
/** Asia/Shanghai 当前业务日期(YYYY-MM-DD)。 */
export function shanghaiBusinessDate(now: Date = new Date()): string {
// en-CA 输出恰为 ISO YYYY-MM-DD(locale 无关的稳定格式技巧)。
return new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(now);
}
/** D+1 规则可匹配截止日(业务日期 T - 1 天,YYYY-MM-DD)。 */
export function eligibleReceiptDateTo(now: Date = new Date()): string {
const business = new Date(`${shanghaiBusinessDate(now)}T00:00:00Z`);
business.setUTCDate(business.getUTCDate() - 1);
return business.toISOString().slice(0, 10);
}
@@ -1,19 +1,20 @@
/**
* features/chat/composables/useChatTransfer.spec.ts
* 用途:验证预检创建/恢复、选择范围、直接生成执行 Run、结果恢复与防重复。
* 用途:验证匹配创建/恢复、选择范围、直接生成执行 Run、结果恢复与防重复。
* 依赖:vi.mock(transfer.api)、useChatTransfer。
* 逻辑:用 Mock API 驱动组合式函数,断言状态流转与调用参数。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
createTransferMatching: vi.fn(),
getTransferMatching: vi.fn(),
executeTransferItems: vi.fn(),
getTransferRun: vi.fn(),
cancelTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
batchRequeryTransferItems: vi.fn(),
downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(),
@@ -24,33 +25,33 @@ vi.mock('../api/transfer.api', () => api);
import { useChatTransfer } from './useChatTransfer';
const summary = {
precheck_id: 'TPC-20260806-001',
matching_id: 'MTG-20260806-001',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 2, not_matured_count: 0, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
counts: { file_invoice_count: 2, not_matured_count: 0, matched_count: 2, executable_count: 2, blocked_count: 0 },
estimated_transfer_quantity: '2400',
estimated_external_write_count: 2,
precheck_hash: 'sha256:abc',
matching_hash: 'sha256:abc',
};
const detail = {
summary,
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1' }],
items: [
{ source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: 'x', specification: 'y', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: 'x', specification: 'y', invoice_no: 'INV-002', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-3', material_name: 'x', specification: 'y', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
{ item_id: 11, source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: 'x', specification: 'y', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ item_id: 12, source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: 'x', specification: 'y', invoice_no: 'INV-002', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ item_id: 13, source_code: 'DBS-AWSBI', material_no: 'MAT-3', material_name: 'x', specification: 'y', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
],
};
describe('useChatTransfer', () => {
beforeEach(() => {
vi.clearAllMocks();
api.createTransferPrecheck.mockResolvedValue(summary);
api.getTransferPrecheck.mockResolvedValue(detail);
api.executeTransferPrecheck.mockResolvedValue({ run_no: 'RUN-20260806-1', status: 'success' });
api.createTransferMatching.mockResolvedValue(summary);
api.getTransferMatching.mockResolvedValue(detail);
api.executeTransferItems.mockResolvedValue({ run_no: 'RUN-20260806-1', status: 'success' });
api.getTransferRun.mockResolvedValue({
run_no: 'RUN-20260806-1',
status: 'success',
@@ -58,55 +59,71 @@ describe('useChatTransfer', () => {
});
});
it('创建预检后默认勾选全部可执行项,未成熟项不可勾选', async () => {
it('创建匹配后默认按 item_id 勾选全部可执行行,未成熟项不可勾选', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI'], '2026-08-06');
expect(transfer.precheckId.value).toBe('TPC-20260806-001');
expect(transfer.executableInvoices.value).toEqual(['INV-001', 'INV-002']);
expect(transfer.selected.value.has('INV-001')).toBe(true);
expect(transfer.selected.value.has('INV-041')).toBe(false);
await transfer.createMatching(['DBS-AWSBI'], '2026-08-06');
expect(transfer.matchingId.value).toBe('MTG-20260806-001');
expect(transfer.executableItemIds.value).toEqual([11, 12]);
expect(transfer.selected.value.has(11)).toBe(true);
expect(transfer.selected.value.has(13)).toBe(false);
});
it('执行时提交勾选范围并恢复 Run', async () => {
it('执行时按明细行 id 提交勾选范围并恢复 Run', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI']);
transfer.toggleSelect('INV-001', false);
await transfer.createMatching(['DBS-AWSBI']);
transfer.toggleSelect(11, false);
await transfer.execute();
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-20260806-001', ['INV-002']);
expect(api.executeTransferItems).toHaveBeenCalledWith([12]);
expect(transfer.runNo.value).toBe('RUN-20260806-1');
expect(api.getTransferRun).toHaveBeenCalledWith('RUN-20260806-1');
});
it('无选择时执行被拦截(不调用 API)', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI']);
await transfer.createMatching(['DBS-AWSBI']);
transfer.selected.value = new Set();
const result = await transfer.execute().catch(() => null);
expect(result).toBeNull();
expect(api.executeTransferPrecheck).not.toHaveBeenCalled();
expect(api.executeTransferItems).not.toHaveBeenCalled();
});
it('resume 是批量重查的语义别名:按明细 id 直调 batch-requery', async () => {
// [断言意图] 行式执行重构(2026-09-23):恢复处理不再重建匹配,
// 前端 resume 与 batchRequery 同源(batch-requery 是恢复的唯一后端)。
api.batchRequeryTransferItems.mockResolvedValue({
total: 2,
results: [
{ item_id: 7, ok: true, status: 'ready_to_execute' },
{ item_id: 8, ok: false, error: 'blocked' },
],
});
const transfer = useChatTransfer();
const result = await transfer.resume([7, 8]);
expect(api.batchRequeryTransferItems).toHaveBeenCalledWith([7, 8]);
expect(result.results.filter((entry) => entry.status === 'ready_to_execute')).toHaveLength(1);
});
it('busy 在请求期间置位,完成后复位(防重复点击)', async () => {
let resolvePrecheck!: (value: unknown) => void;
api.getTransferPrecheck.mockImplementation(
() => new Promise((resolve) => { resolvePrecheck = resolve; }),
let resolveMatching!: (value: unknown) => void;
api.getTransferMatching.mockImplementation(
() => new Promise((resolve) => { resolveMatching = resolve; }),
);
const transfer = useChatTransfer();
const promise = transfer.createPrecheck(['DBS-AWSBI']);
// 推进微任务链:createTransferPrecheck → getTransferPrecheck(mock 已执行)
const promise = transfer.createMatching(['DBS-AWSBI']);
// 推进微任务链:createTransferMatching → getTransferMatching(mock 已执行)
await Promise.resolve();
await Promise.resolve();
expect(transfer.busy.value).toBe(true);
resolvePrecheck(detail);
resolveMatching(detail);
await promise;
expect(transfer.busy.value).toBe(false);
});
it('reset 清空全部状态', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI']);
await transfer.createMatching(['DBS-AWSBI']);
transfer.reset();
expect(transfer.precheckId.value).toBeNull();
expect(transfer.matchingId.value).toBeNull();
expect(transfer.items.value).toHaveLength(0);
expect(transfer.run.value).toBeNull();
});
@@ -1,23 +1,28 @@
/**
* features/chat/composables/useChatTransfer.ts
* 用途:在途仓自动调拨聊天编排入口——预检创建/恢复、选择范围、直接生成执行 Run、
* Run 进度与结果恢复、人工重试/关闭、下载。
* 用途:在途仓自动调拨聊天编排入口——匹配创建/恢复、选择范围(按明细 item_id)、
* 按行直接生成执行 Run、Run 进度与结果恢复、人工重试/关闭、恢复处理(重查)、下载。
* 依赖:transfer.api、transfer.types、useMessage、Vue refs/computed。
* 逻辑:前端只消费稳定 DTO;Run 是异步真相源,刷新/重进由 GET 恢复;
* 勾选集合以明细行 item_id 为键(历史回放行无 item_id 不可选);
* 恢复处理 = 按明细 id 重查库存(batch-requery 是唯一后端);
* 防重复点击(busy);错误统一 useMessage 展示 BusinessError。
*/
import { computed, ref, type Ref } from 'vue';
import { useMessage } from '@/shared/composables/useMessage';
import {
batchManualCloseTransferItems,
batchRequeryTransferItems,
cancelTransferRun,
createTransferPrecheck,
createTransferMatching,
downloadTransferErpInventory,
downloadTransferExceptions,
downloadTransferReceiptFiles,
executeTransferPrecheck,
executeTransferItems,
getTransferBacklogSummary,
getTransferPrecheck,
getTransferMatching,
getTransferRun,
listExecutableTransferItems,
listTransferBacklog,
listTransferSources,
manualCloseTransferItem,
@@ -27,9 +32,10 @@ import {
import type {
TransferBacklogItem,
TransferBacklogSummary,
TransferPrecheckDetail,
TransferPrecheckItem,
TransferPrecheckSummary,
TransferBatchResult,
TransferMatchingDetail,
TransferMatchingItem,
TransferMatchingSummary,
TransferRunResult,
TransferSourceOption,
TransferSourceProgress,
@@ -39,29 +45,32 @@ import type {
export function useChatTransfer() {
const { error: notifyError } = useMessage();
const precheckId = ref<string | null>(null);
const precheck = ref<TransferPrecheckSummary | null>(null);
const items = ref<TransferPrecheckItem[]>([]);
const matchingId = ref<string | null>(null);
const matching = ref<TransferMatchingSummary | null>(null);
const items = ref<TransferMatchingItem[]>([]);
const sources = ref<TransferSourceProgress[]>([]);
const runNo = ref<string | null>(null);
const run = ref<TransferRunResult | null>(null);
const backlog = ref<TransferBacklogItem[]>([]);
const backlogSummary = ref<TransferBacklogSummary | null>(null);
const executableItems = ref<TransferMatchingItem[]>([]);
const sourceOptions = ref<TransferSourceOption[]>([]);
const selected = ref<Set<string>>(new Set());
const selected = ref<Set<number>>(new Set());
const busy = ref(false);
const error = ref('');
/** 全部可执行 Invoice(阻断/未成熟不可勾选) */
const executableInvoices = computed(() =>
items.value.filter((item) => item.result === 'executable').map((item) => item.invoice_no),
/** 全部可执行明细行 id(阻断/未成熟/无 item_id 的历史行不可勾选) */
const executableItemIds = computed(() =>
items.value
.filter((item) => item.result === 'executable' && item.item_id != null)
.map((item) => item.item_id as number),
);
const selectedCount = computed(() => selected.value.size);
const estimatedQuantity = computed(() => precheck.value?.estimated_transfer_quantity ?? '0');
const estimatedQuantity = computed(() => matching.value?.estimated_transfer_quantity ?? '0');
/** 创建预检(缺文件时来源级阶段展示等待/失败);transferType 决定收料数据范围,缺省在途仓至HUB仓 */
async function createPrecheck(
/** 创建匹配(缺文件时来源级阶段展示等待/失败);transferType 决定收料数据范围,缺省在途仓至HUB仓 */
async function createMatching(
sourceCodes: string[],
businessDate?: string,
dateRange?: { from?: string; to?: string },
@@ -70,15 +79,15 @@ export function useChatTransfer() {
busy.value = true;
error.value = '';
try {
const summary = await createTransferPrecheck({
const summary = await createTransferMatching({
source_codes: sourceCodes,
business_date: businessDate,
receipt_date_from: dateRange?.from,
receipt_date_to: dateRange?.to,
transfer_type: transferType,
});
precheckId.value = summary.precheck_id;
await refreshPrecheck();
matchingId.value = summary.matching_id;
await refreshMatching();
return summary;
} catch (e) {
error.value = String(e);
@@ -88,42 +97,43 @@ export function useChatTransfer() {
}
}
/** 恢复预检进度(页面刷新/会话恢复) */
async function refreshPrecheck() {
if (!precheckId.value) return null;
const detail = await getTransferPrecheck(precheckId.value);
/** 恢复匹配进度(页面刷新/会话恢复) */
async function refreshMatching() {
if (!matchingId.value) return null;
const detail = await getTransferMatching(matchingId.value);
applyDetail(detail);
return detail;
}
function applyDetail(detail: TransferPrecheckDetail) {
precheck.value = detail.summary;
function applyDetail(detail: TransferMatchingDetail) {
matching.value = detail.summary;
items.value = detail.items;
sources.value = detail.sources;
// 默认勾选全部可执行项;阻断/未成熟不可选
// 默认勾选全部可执行明细行(按 item_id);阻断/未成熟/无 item_id 不可选
selected.value = new Set(
detail.items.filter((item) => item.result === 'executable').map((item) => item.invoice_no),
detail.items
.filter((item) => item.result === 'executable' && item.item_id != null)
.map((item) => item.item_id as number),
);
}
function toggleSelect(invoiceNo: string, checked: boolean) {
function toggleSelect(itemId: number, checked: boolean) {
const next = new Set(selected.value);
if (checked) next.add(invoiceNo);
else next.delete(invoiceNo);
if (checked) next.add(itemId);
else next.delete(itemId);
selected.value = next;
}
/** 直接生成调拨单(决策 4/5:无独立确认页) */
/** 按勾选明细行直接生成调拨单(item-centric:门禁在后端,失败抛 BusinessError) */
async function execute() {
if (!precheckId.value) throw new Error('precheck not created');
if (selected.value.size === 0) {
notifyError('请至少选择一个可执行 Invoice');
notifyError('请至少选择一个可执行明细行');
return null;
}
busy.value = true;
error.value = '';
try {
const result = await executeTransferPrecheck(precheckId.value, [...selected.value]);
const result = await executeTransferItems([...selected.value]);
runNo.value = result.run_no;
await refreshRun();
return result;
@@ -154,14 +164,14 @@ export function useChatTransfer() {
/** 人工重试异常项 */
async function retry(itemId: number) {
const result = await retryTransferItem(itemId);
await refreshPrecheck();
await refreshMatching();
return result;
}
/** 人工关闭异常项 */
async function manualClose(itemId: number, reason: string) {
const result = await manualCloseTransferItem(itemId, reason);
await refreshPrecheck();
await refreshMatching();
return result;
}
@@ -173,7 +183,7 @@ export function useChatTransfer() {
return result;
}
/** 下载预检冻结的 ERP 库存表(csv) */
/** 下载匹配冻结的 ERP 库存表(csv) */
async function downloadErpInventory() {
if (!runNo.value) return null;
const result = await downloadTransferErpInventory(runNo.value);
@@ -210,6 +220,29 @@ export function useChatTransfer() {
return { items, summary };
}
/** 加载可调拨明细(全局可执行行队列;恢复后的行会出现在这里) */
async function loadExecutableItems() {
const payload = await listExecutableTransferItems();
executableItems.value = payload.items;
return executableItems.value;
}
/** 批量重查库存(单行隔离,结果由调用方刷新列表后展示) */
async function batchRequery(itemIds: number[]): Promise<TransferBatchResult> {
return batchRequeryTransferItems(itemIds);
}
/** 恢复处理(行级/多选):恢复语义 = 按明细 id 重查库存(batch-requery 唯一后端);
* 返回批量结果,由视图统计 recovered(status=ready_to_execute)与仍阻断数。 */
async function resume(itemIds: number[]): Promise<TransferBatchResult> {
return batchRequeryTransferItems(itemIds);
}
/** 批量人工关闭(原因整批共用;单行隔离) */
async function batchManualClose(itemIds: number[], reason: string): Promise<TransferBatchResult> {
return batchManualCloseTransferItems(itemIds, reason);
}
function saveBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
@@ -220,37 +253,39 @@ export function useChatTransfer() {
}
function reset() {
precheckId.value = null;
precheck.value = null;
matchingId.value = null;
matching.value = null;
items.value = [];
sources.value = [];
runNo.value = null;
run.value = null;
backlog.value = [];
backlogSummary.value = null;
executableItems.value = [];
sourceOptions.value = [];
selected.value = new Set();
error.value = '';
}
return {
precheckId,
precheck,
matchingId,
matching,
items,
sources,
runNo,
run,
backlog,
backlogSummary,
executableItems,
sourceOptions,
selected,
selectedCount,
executableInvoices,
executableItemIds,
estimatedQuantity,
busy,
error,
createPrecheck,
refreshPrecheck,
createMatching,
refreshMatching,
toggleSelect,
execute,
refreshRun,
@@ -260,6 +295,10 @@ export function useChatTransfer() {
loadSources,
retrySourceRpa,
loadBacklog,
loadExecutableItems,
batchRequery,
resume,
batchManualClose,
downloadReceiptFiles,
downloadErpInventory,
downloadExceptions,
@@ -1,7 +1,7 @@
/**
* features/chat/e2e/in-transit-transfer.spec.ts
* 用途:在途仓自动调拨全链路契约冒烟(对应 TDD §10 主路径)——
* 预检 → 选择子集 → 直接生成调拨单 → Run 恢复 → 下载留底。
* 匹配 → 选择子集 → 生成调拨单 → Run 恢复 → 下载留底。
* 依赖:Vitest、vi.mock(transfer.api)、useChatTransfer。
* 逻辑:不启浏览器;用组合式函数 + Mock API 断言产品契约,避免 e2e 环境依赖
* (与仓库 shipping e2e 约定一致)。
@@ -9,9 +9,9 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
createTransferMatching: vi.fn(),
getTransferMatching: vi.fn(),
executeTransferItems: vi.fn(),
getTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
@@ -23,25 +23,25 @@ const api = vi.hoisted(() => ({
vi.mock('@/features/chat/api/transfer.api', () => api);
import { useChatTransfer } from '@/features/chat/composables/useChatTransfer';
import type { TransferPrecheckDetail } from '@/features/chat/types/transfer.types';
import type { TransferMatchingDetail } from '@/features/chat/types/transfer.types';
const detail: TransferPrecheckDetail = {
const detail: TransferMatchingDetail = {
summary: {
precheck_id: 'TPC-20260806-001',
matching_id: 'MTG-20260806-001',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 3, not_matured_count: 1, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
counts: { file_invoice_count: 3, not_matured_count: 1, matched_count: 2, executable_count: 2, blocked_count: 0 },
estimated_transfer_quantity: '2400',
estimated_external_write_count: 2,
precheck_hash: 'sha256:abc',
matching_hash: 'sha256:abc',
},
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1', file_version: 'v3' }],
items: [
{ source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: '控制器组件', specification: 'B', invoice_no: 'INV-002', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSSG', material_no: 'MAT-41', material_name: '连接器', specification: 'C', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
{ item_id: 11, source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ item_id: 12, source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: '控制器组件', specification: 'B', invoice_no: 'INV-002', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ item_id: 13, source_code: 'DBS-AWSSG', material_no: 'MAT-41', material_name: '连接器', specification: 'C', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
],
};
@@ -68,23 +68,23 @@ const runResult = {
describe('in-transit-transfer e2e contract', () => {
beforeEach(() => {
vi.clearAllMocks();
api.createTransferPrecheck.mockResolvedValue(detail.summary);
api.getTransferPrecheck.mockResolvedValue(detail);
api.executeTransferPrecheck.mockResolvedValue({ run_no: 'RUN-20260806-001', status: 'success' });
api.createTransferMatching.mockResolvedValue(detail.summary);
api.getTransferMatching.mockResolvedValue(detail);
api.executeTransferItems.mockResolvedValue({ run_no: 'RUN-20260806-001', status: 'success' });
api.getTransferRun.mockResolvedValue(runResult);
api.downloadTransferReceiptFiles.mockResolvedValue({ blob: new Blob(['zip']), filename: 'receipt-files.zip' });
api.downloadTransferErpInventory.mockResolvedValue({ blob: new Blob(['csv']), filename: 'erp.csv' });
});
it('主路径:预检 → 只选 INV-001 → 生成调拨单 → 结果按 ERP 单号聚合', async () => {
it('主路径:匹配 → 只选 item 11 → 按明细行生成调拨单 → 结果按 ERP 单号聚合', async () => {
const transfer = useChatTransfer();
await transfer.createPrecheck(['DBS-AWSBI', 'DBS-AWSSG'], '2026-08-06');
await transfer.createMatching(['DBS-AWSBI', 'DBS-AWSSG'], '2026-08-06');
// 未成熟项默认不勾选
expect(transfer.selected.value.has('INV-041')).toBe(false);
// 取消 INV-002,只执行 INV-001
transfer.toggleSelect('INV-002', false);
expect(transfer.selected.value.has(13)).toBe(false);
// 取消 item 12,只执行 item 11
transfer.toggleSelect(12, false);
await transfer.execute();
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-20260806-001', ['INV-001']);
expect(api.executeTransferItems).toHaveBeenCalledWith([11]);
expect(transfer.run.value?.result.external_documents[0].document_no).toBe('TRF-10001');
});
@@ -234,7 +234,7 @@ export interface ChatMessage {
content: string;
/** 用户提交时固化的附件展示快照;助手消息不使用此字段。 */
attachments?: ChatMessageAttachment[];
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result' | 'procurement-contract-review' | 'transfer-precheck' | 'transfer-progress' | 'transfer-result';
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result' | 'procurement-contract-review' | 'transfer-match' | 'transfer-progress' | 'transfer-result';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more