feat(in-transit-transfer): 异常恢复一键重建预检并支持按行批量处理

- 新增 resume_service:可恢复阻断行按(来源×收料日期)分组重建范围预检,收料文件不可用自动触发 RPA 重抓,单组失败不影响其余组
- precheck 新增 list_recent_prechecks 最近预检入口:未执行未过期可继续执行,解决预检卡关闭后无处恢复
- manual_close 支持按 item_ids 批量关闭并带审计,retry/backlog 配合按行口径调整
- 前端三区接线换新:首页待办/预检卡/待处理异常接恢复与批量动作,新增 transferDate 日期工具与 e2e 用例
- i18n chat/errors 四语言同步,technical.md 与 funclist 更新,落行归属解耦与 ERP 写路径两份实施计划
This commit is contained in:
hugo committed 2026-09-23 15:30:07 +08:00
1 parent 42b271f92b
commit 556d3fd3db
35 files changed
+2879 -105

No files matched your search

+85 -4
View File
@@ -26,9 +26,18 @@ from app.services.in_transit_transfer.execution_service import (
get_run, get_run,
serialize_run_result, serialize_run_result,
) )
from app.services.in_transit_transfer.manual_close_service import manual_close_item from app.services.in_transit_transfer.manual_close_service import manual_close_item, manual_close_items
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck from app.services.in_transit_transfer.precheck_service import (
from app.services.in_transit_transfer.retry_service import requery_items as retry_service_requery_items, retry_item create_precheck,
list_recent_prechecks,
restore_precheck,
)
from app.services.in_transit_transfer.resume_service import resume_items
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 ( from app.services.in_transit_transfer.serializers import (
serialize_item, serialize_item,
serialize_source, serialize_source,
@@ -98,6 +107,17 @@ def create_precheck_api():
return _ok(serialize_summary(summary), status=201) return _ok(serialize_summary(summary), status=201)
@in_transit_transfer_bp.route("/prechecks/recent", methods=["GET"])
@require_transfer_permission
def recent_prechecks_api():
"""最近预检列表(未执行、未过期、仍拥有归属行);供前端一键恢复预检卡。"""
try:
limit = int(request.args.get("limit", 10))
except (TypeError, ValueError):
limit = 10
return _ok(list_recent_prechecks(limit=limit))
@in_transit_transfer_bp.route("/prechecks/<precheck_id>", methods=["GET"]) @in_transit_transfer_bp.route("/prechecks/<precheck_id>", methods=["GET"])
@require_transfer_permission @require_transfer_permission
def get_precheck_api(precheck_id: str): def get_precheck_api(precheck_id: str):
@@ -255,6 +275,60 @@ def manual_close_item_api(item_id: int):
return _ok(manual_close_item(item_id=item_id, reason=reason)) 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/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-resume", methods=["POST"])
@require_transfer_permission
def batch_resume_items_api():
"""批量恢复异常项到预检流程(按来源+收料日期分组重建预检;单组隔离)。"""
user = _require_user()
body = request.get_json(silent=True) or {}
item_ids = _require_item_ids(body)
return _ok(resume_items(
item_ids=item_ids,
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"]) @in_transit_transfer_bp.route("/runs/<run_no>/exceptions.xlsx", methods=["GET"])
@require_transfer_permission @require_transfer_permission
def exceptions_excel_api(run_no: str): def exceptions_excel_api(run_no: str):
@@ -502,7 +576,7 @@ def backlog_summary_api():
def _serialize_backlog_item(item) -> dict[str, Any]: def _serialize_backlog_item(item) -> dict[str, Any]:
"""待处理池项序列化。""" """待处理池项序列化(明细字段与预检窗口列一致)。"""
return { return {
'item_id': item.item_id, 'item_id': item.item_id,
'source_code': item.source_code, 'source_code': item.source_code,
@@ -513,4 +587,11 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
'age_days': item.age_days, 'age_days': item.age_days,
'aging_level': item.aging_level, 'aging_level': item.aging_level,
'last_attempt_at': item.last_attempt_at, '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,
} }
@@ -28,7 +28,7 @@ _BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
@dataclass(frozen=True) @dataclass(frozen=True)
class BacklogItemDTO: class BacklogItemDTO:
"""待处理池单项。""" """待处理池单项(明细字段与预检窗口列一致,供异常表格直接渲染)。"""
item_id: int item_id: int
source_code: str source_code: str
@@ -39,6 +39,13 @@ class BacklogItemDTO:
age_days: int age_days: int
aging_level: str aging_level: str
last_attempt_at: Optional[str] = None 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
@dataclass @dataclass
@@ -117,6 +124,13 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
age_days=age, age_days=age,
aging_level=level, aging_level=level,
last_attempt_at=latest.created_at.isoformat() if latest is not None else None, 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,
)) ))
return output return output
@@ -64,3 +64,38 @@ def manual_close_item(*, item_id: int, reason: str, actor_id: int | None = None,
)) ))
db.session.commit() db.session.commit()
return {"item_id": item.id, "status": item.status} 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}
@@ -16,6 +16,8 @@ from datetime import date, datetime, timedelta
from decimal import Decimal from decimal import Decimal
from typing import Any, Protocol from typing import Any, Protocol
from sqlalchemy import case, func, or_
from app import db from app import db
from app.core.errors import AppError, NotFoundError, ValidationError from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
@@ -713,3 +715,79 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
"items": items, "items": items,
"sources": sources, "sources": sources,
} }
def list_recent_prechecks(*, limit: int = 10, now: datetime | None = None) -> list[dict[str, Any]]:
"""列出可继续执行的最近预检(最近预检入口数据源)。
用途:预检卡关闭/离开视图后无处恢复,本查询给出"未执行、未过期、
仍拥有归属行且至少一行可执行"的预检,供前端一键恢复到既有预检卡。
恢复处理遗留的全阻断壳预检(ERP 未修正,0 可执行)不入列——
其行仍在待处理池可见、可重查,入列只是噪音。
Args:
limit: 返回上限(1-50,缺省 10)。
now: 判定时刻(缺省当前 UTC 时间)。
Returns:
按 created_at 倒序的预检摘要列表(counts 为按归属行实时聚合,
不读 counts_json 快照——重复预检会把非终态行迁入最新预检,
快照数字会与恢复后的真实明细不一致)。
"""
current = now or datetime.utcnow()
# [归属聚合] 行单一归属(precheck_id 唯一外键):实时按状态聚合计数。
item_agg = (
db.session.query(
TransferInvoiceItem.precheck_id.label("precheck_id"),
func.count(TransferInvoiceItem.id).label("total"),
func.sum(case((TransferInvoiceItem.status == status_machine.TransferStatus.READY_TO_EXECUTE.value, 1), else_=0)).label("executable_count"),
func.sum(case((TransferInvoiceItem.status == status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, 1), else_=0)).label("blocked_count"),
func.sum(case((TransferInvoiceItem.status == status_machine.TransferStatus.NOT_MATURED.value, 1), else_=0)).label("not_matured_count"),
)
.group_by(TransferInvoiceItem.precheck_id)
.subquery()
)
rows = (
db.session.query(
TransferPrecheck,
func.coalesce(item_agg.c.total, 0).label("agg_total"),
func.coalesce(item_agg.c.executable_count, 0).label("agg_executable"),
func.coalesce(item_agg.c.blocked_count, 0).label("agg_blocked"),
func.coalesce(item_agg.c.not_matured_count, 0).label("agg_not_matured"),
)
.outerjoin(item_agg, item_agg.c.precheck_id == TransferPrecheck.id)
.filter(
TransferPrecheck.confirmed_at.is_(None),
TransferPrecheck.status != "expired",
or_(TransferPrecheck.expires_at.is_(None), TransferPrecheck.expires_at > current),
# 进行中(异步落明细前)必列;其余必须仍拥有归属行且至少一行可执行
# (被新预检掏空的旧预检、恢复遗留的全阻断壳均不可操作,列出只会误导)。
or_(
TransferPrecheck.status == "prechecking",
func.coalesce(item_agg.c.executable_count, 0) > 0,
),
)
.order_by(TransferPrecheck.created_at.desc())
.limit(max(1, min(int(limit), 50)))
.all()
)
output: list[dict[str, Any]] = []
for precheck, total, executable, blocked, not_matured in rows:
scope = precheck.scope_json if isinstance(precheck.scope_json, dict) else {}
output.append({
"precheck_no": precheck.precheck_no,
"business_date": precheck.business_date,
"status": precheck.status,
"transfer_type": scope.get("transfer_type"),
"source_codes": list(scope.get("source_codes") or []),
"counts": {
"total": int(total),
"executable_count": int(executable),
"blocked_count": int(blocked),
"not_matured_count": int(not_matured),
},
"estimated_transfer_quantity": precheck.estimated_transfer_quantity or "0",
"estimated_external_write_count": int(precheck.estimated_external_write_count or 0),
"created_at": precheck.created_at.isoformat() if precheck.created_at else None,
"expires_at": precheck.expires_at.isoformat() if precheck.expires_at else None,
})
return output
@@ -0,0 +1,138 @@
"""在途调拨异常恢复服务(待处理池一键回到预检流程)。
用途:对可恢复阻断行按(来源, 收料日期)分组重建范围预检,行随 create_precheck
幂等刷新迁入新预检并重查库存;收料文件不可用的来源自动触发一次 RPA 重抓。
依赖:models、precheck_service.create_precheck、source_file_status、
receipt_trigger_service、audit、date_policy。
逻辑:仅 blocked_recoverable 可恢复;本服务只查询/重建预检,不写外部系统
(ERP 写入仍走预检卡人工核对后的执行链路);单组失败不影响其余组。
"""
from __future__ import annotations
import logging
from app import db
from app.core.errors import ValidationError
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.precheck_service import TransferDeps, create_precheck
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
logger = logging.getLogger(__name__)
def resume_items(
*,
item_ids: list[int],
deps: TransferDeps | None = None,
actor_id: str | None = None,
request_id: str | None = None,
) -> dict:
"""批量恢复待处理异常项到预检流程。
Args:
item_ids: TransferInvoiceItem.id 列表(非空)。
deps: 注入依赖(缺省取真实依赖,便于测试覆写)。
actor_id / request_id: 审计上下文。
Returns:
{"prechecks": [{precheck_no, source_code, receipt_date, selected_item_count,
executable_count}],
"file_fetching": [{source_code, ok, callback_id?, error_code?}],
"skipped": [{item_id, invoice_no, 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")
resolved_deps = deps or transfer_deps.get_transfer_dependencies()
# [STEP 1] 门禁:逐行校验存在且为可恢复阻断;不合格进 skipped(单行隔离)。
skipped: list[dict] = []
valid: list[TransferInvoiceItem] = []
for item_id in ids:
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
skipped.append({"item_id": item_id, "invoice_no": "", "error": "item not found"})
elif item.status != "blocked_recoverable":
skipped.append({
"item_id": item_id, "invoice_no": item.invoice_no,
"error": f"item status {item.status} is not resumable",
})
else:
valid.append(item)
# [STEP 2] 按(来源, 收料日期)精确分组:同一组的行会随 create_precheck
# 幂等刷新迁入同一份新预检;不扩日期范围,避免多重查未勾选的行。
groups: dict[tuple[str, str], list[TransferInvoiceItem]] = {}
for item in valid:
groups.setdefault((item.source_code, item.receipt_date or ""), []).append(item)
# [STEP 3] 逐组恢复:收料文件可用 → 重建范围预检;不可用 → 触发 RPA 重抓
#(用户稍后再次恢复)。任一组异常降级进 skipped,不中断其余组。
prechecks: list[dict] = []
file_fetching: list[dict] = []
business_date = str(business_date_now())
for (source_code, receipt_date), group in groups.items():
try:
file_status = resolve_source_file_status(source_code=source_code)
if not file_status.get("has_ready_file"):
outcome = trigger_receipt_rpa(
source_code=source_code, business_date=business_date,
reason="transfer_resume_file_missing",
)
entry: dict = {"source_code": source_code, "ok": bool(outcome.get("ok"))}
if outcome.get("ok"):
entry["callback_id"] = outcome.get("callback_id")
else:
entry["error_code"] = outcome.get("error_code")
file_fetching.append(entry)
continue
summary = create_precheck(
source_codes=[source_code],
business_date=business_date,
deps=resolved_deps,
receipt_date_from=receipt_date or None,
receipt_date_to=receipt_date or None,
)
prechecks.append({
"precheck_no": summary.precheck_id,
"source_code": source_code,
"receipt_date": receipt_date,
"selected_item_count": len(group),
# 可执行行数供前端决策:0 可执行(ERP 未修正)不跳预检卡,
# 留在待处理池并提示"仍阻断",避免打开一张全阻断的壳卡。
"executable_count": int(summary.counts.executable_count),
})
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEMS_RESUMED",
aggregate_type="transfer_precheck",
aggregate_id=summary.precheck_id,
precheck_no=summary.precheck_id,
actor_type="user",
actor_id=str(actor_id) if actor_id is not None else None,
request_id=request_id,
result="success",
after={
"source_code": source_code,
"receipt_date": receipt_date,
"item_ids": [item.id for item in group],
},
))
db.session.commit()
except Exception as exc: # noqa: BLE001 —— 单组隔离:失败不影响其余组
db.session.rollback()
logger.warning(
"transfer resume group crashed (skipped): source=%s receipt_date=%s items=%s error=%s",
source_code, receipt_date, [item.id for item in group],
str(exc).strip() or exc.__class__.__name__,
)
skipped.append({
"item_id": group[0].id, "invoice_no": group[0].invoice_no,
"error": str(exc).strip() or exc.__class__.__name__,
})
return {"prechecks": prechecks, "file_fetching": file_fetching, "skipped": skipped}
@@ -173,6 +173,47 @@ 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} return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
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:
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(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None, 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: actor_id: int | None = None, request_id: str | None = None) -> dict:
"""批量重查 外部系统 库存:对同一预检下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。 """批量重查 外部系统 库存:对同一预检下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
@@ -0,0 +1,77 @@
"""在途调拨批量操作测试(批量重查 / 批量人工关闭,L1)。
用途:验证待处理池多选批量操作的按 id 直取、单行隔离与参数门禁。
依赖:transfer_db、precheck_service、retry_service、manual_close_service、repo_fakes。
逻辑:批量语义 = 逐行调用既有单行服务,任何单行失败(状态不允许/不存在/异常)
不影响其余行;id/原因缺失直接拒绝。
"""
from __future__ import annotations
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.precheck_service import create_precheck
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_precheck(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_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"]
@@ -0,0 +1,85 @@
"""最近预检列表测试(list_recent_prechecks,L1)。
用途:验证「最近预检」只列可继续执行的预检:未执行、未过期、仍拥有归属行;
counts 为按归属行实时聚合(非 counts_json 快照)。
依赖:transfer_db、precheck_service、repo_fakes。
逻辑:重复预检会迁走非终态行,被掏空的旧预检不得出现在列表;
已执行(confirmed_at)与已过期(expires_at)均排除。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from app import db
from app.models import TransferPrecheck
from app.services.in_transit_transfer.precheck_service import create_precheck, list_recent_prechecks
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
def _create(dbs_ready_file, *, mat1_stock="1000", mat2_stock="1200"):
"""创建一份 DBS-AWSBI 预检:默认 HOM-001 阻断、HOX-002 可执行。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", mat1_stock)
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", mat2_stock)
return create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
def test_recent_lists_live_precheck_with_live_counts(transfer_db, dbs_ready_file):
"""未执行未过期且拥有归属行的预检可见,counts 为实时聚合。"""
summary = _create(dbs_ready_file)
recent = list_recent_prechecks()
assert [row["precheck_no"] for row in recent] == [summary.precheck_id]
counts = recent[0]["counts"]
assert counts["total"] == 2
assert counts["executable_count"] == 1
assert counts["blocked_count"] == 1
assert recent[0]["source_codes"] == ["DBS-AWSBI"]
assert recent[0]["expires_at"]
def test_recent_excludes_executed_precheck(transfer_db, dbs_ready_file):
"""已确认执行(confirmed_at)的预检不再列出。"""
summary = _create(dbs_ready_file)
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
precheck.confirmed_at = datetime.utcnow()
db.session.commit()
assert list_recent_prechecks() == []
def test_recent_excludes_expired_precheck(transfer_db, dbs_ready_file):
"""确认窗口过期(expires_at 已过)的预检不再列出。"""
summary = _create(dbs_ready_file)
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
precheck.expires_at = datetime.utcnow() - timedelta(seconds=1)
db.session.commit()
assert list_recent_prechecks() == []
def test_recent_excludes_precheck_without_executable_rows(transfer_db, dbs_ready_file):
"""全阻断壳预检(0 可执行,如恢复遗留)不入列:其行仍在待处理池可见。"""
summary = _create(dbs_ready_file, mat1_stock="1000", mat2_stock="999") # 两行均阻断
assert list_recent_prechecks() == []
# 预检本身存在且拥有 2 行归属,只是不可继续执行。
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
assert precheck is not None
assert len(precheck.items) == 2
def test_recent_excludes_emptied_precheck_after_reprecheck(transfer_db, dbs_ready_file):
"""重复预检迁走全部归属行后,被掏空的旧预检不再列出(行单一归属)。"""
first = _create(dbs_ready_file)
second = _create(dbs_ready_file)
recent = list_recent_prechecks()
nos = [row["precheck_no"] for row in recent]
assert second.precheck_id in nos
assert first.precheck_id not in nos
# 新预检拥有全部 2 行(实时聚合而非快照)。
assert next(row for row in recent if row["precheck_no"] == second.precheck_id)["counts"]["total"] == 2
@@ -0,0 +1,131 @@
"""在途调拨异常恢复服务测试(resume_items,L1)。
用途:验证待处理池「恢复处理」的分组重建预检、行迁移、门禁与降级隔离。
依赖:transfer_db、precheck_service、resume_service、repo_fakes。
逻辑:恢复只重建预检不写外部系统;文件不可用触发 RPA 重抓不建预检;
非可恢复行进 skipped;空 id 列表直接拒绝。
"""
from __future__ import annotations
import pytest
from app import db
from app.core.errors import ValidationError
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import resume_service
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.precheck_service import create_precheck
from app.services.in_transit_transfer.resume_service import resume_items
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
def _file_ready(monkeypatch):
"""让收料文件可用性检查返回 ready(不触碰真实文件表)。"""
monkeypatch.setattr(
resume_service, "resolve_source_file_status",
lambda *, source_code: {"file_status": "ready", "has_ready_file": True,
"file_no": "REC-1", "file_sha256": "a" * 64},
)
def _seed_two_blocked(dbs_ready_file):
"""构造两行 blocked_recoverable(同来源同收料日期)的预检,返回 deps。
生产口径:恢复链路使用「当天业务日抓取的可用文件」(receipt_file_gate
只认当天),再按旧行的收料日期过滤范围。因此文件仓库必须按当天业务日
键入,行内容(movement_date=2026-08-05)保持历史收料日期。
"""
today = str(business_date_now())
file_today = {**dbs_ready_file, "business_date": today}
deps, erp, _ = make_transfer_deps(file_today)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # 1200 ≠ 1000 → blocked
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "999") # 1200 ≠ 999 → blocked
create_precheck(source_codes=["DBS-AWSBI"], business_date=today, deps=deps)
return deps
def test_resume_rebuilds_scoped_precheck_and_migrates_row(transfer_db, dbs_ready_file, monkeypatch):
"""恢复单行:按(来源,收料日期)重建预检,行迁移到新预检。"""
_file_ready(monkeypatch)
deps = _seed_two_blocked(dbs_ready_file)
blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
old_precheck_id = blocked.precheck_id
result = resume_items(item_ids=[blocked.id], deps=deps)
assert len(result["prechecks"]) == 1
created = result["prechecks"][0]
assert created["source_code"] == "DBS-AWSBI"
assert created["receipt_date"] == "2026-08-05"
assert created["selected_item_count"] == 1
# ERP 未修正:0 可执行,前端据此不跳预检卡。
assert created["executable_count"] == 0
assert created["precheck_no"] != old_precheck_id
# 幂等刷新:同一物理行迁入新预检(单一归属),状态仍为可恢复阻断。
assert blocked.precheck_id != old_precheck_id
assert blocked.status == "blocked_recoverable"
assert result["file_fetching"] == []
assert result["skipped"] == []
def test_resume_groups_same_source_and_date(transfer_db, dbs_ready_file, monkeypatch):
"""同来源同收料日期的多行合并进同一份新预检。"""
_file_ready(monkeypatch)
deps = _seed_two_blocked(dbs_ready_file)
hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
result = resume_items(item_ids=[hom.id, hox.id], deps=deps)
assert len(result["prechecks"]) == 1
assert result["prechecks"][0]["selected_item_count"] == 2
def test_resume_file_missing_triggers_rpa_refetch(transfer_db, dbs_ready_file, monkeypatch):
"""收料文件不可用:触发 RPA 重抓、不建预检。"""
monkeypatch.setattr(
resume_service, "resolve_source_file_status",
lambda *, source_code: {"file_status": "none", "has_ready_file": False},
)
calls: list[dict] = []
def _fake_trigger(**kwargs):
calls.append(kwargs)
return {"ok": True, "callback_id": "cb-1"}
monkeypatch.setattr(resume_service, "trigger_receipt_rpa", _fake_trigger)
deps = _seed_two_blocked(dbs_ready_file)
hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
result = resume_items(item_ids=[hom.id], deps=deps)
assert result["prechecks"] == []
assert result["file_fetching"] == [
{"source_code": "DBS-AWSBI", "ok": True, "callback_id": "cb-1"},
]
assert calls and calls[0]["source_code"] == "DBS-AWSBI"
assert calls[0]["reason"] == "transfer_resume_file_missing"
def test_resume_skips_non_recoverable_rows(transfer_db, dbs_ready_file, monkeypatch):
"""非可恢复行(可执行/不存在)进 skipped,不建预检。"""
_file_ready(monkeypatch)
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
executable = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
result = resume_items(item_ids=[executable.id, 999999], deps=deps)
assert result["prechecks"] == []
assert {entry["item_id"] for entry in result["skipped"]} == {executable.id, 999999}
assert any("not resumable" in entry["error"] for entry in result["skipped"])
assert any("not found" in entry["error"] for entry in result["skipped"])
def test_resume_requires_item_ids():
"""空 id 列表直接拒绝(TRANSFER.BATCH_ITEMS_REQUIRED)。"""
with pytest.raises(ValidationError) as exc_info:
resume_items(item_ids=[])
assert exc_info.value.code == "TRANSFER.BATCH_ITEMS_REQUIRED"
@@ -44,18 +44,28 @@
| Method | Path | 说明 | | Method | Path | 说明 |
| --- | --- | --- | | --- | --- | --- |
| POST | `/prechecks` | 创建预检(只读;可选 `transfer_type`,缺省 `in_transit_to_hub`) | | POST | `/prechecks` | 创建预检(只读;可选 `transfer_type`,缺省 `in_transit_to_hub`) |
| GET | `/prechecks/recent` | 最近预检列表(未执行 + 未过期 + 仍拥有归属行;counts 按归属行实时聚合,非 counts_json 快照) |
| GET | `/prechecks/{id}` | 预检进度恢复 | | GET | `/prechecks/{id}` | 预检进度恢复 |
| POST | `/prechecks/{id}/execute` | 确认范围并直接生成执行 Run | | POST | `/prechecks/{id}/execute` | 确认范围并直接生成执行 Run |
| GET | `/runs/{run_no}` | Run 结果(按 ERP 单号聚合 + 未生成单据异常) | | GET | `/runs/{run_no}` | Run 结果(按 ERP 单号聚合 + 未生成单据异常) |
| POST | `/runs/{run_no}/cancel` | 请求停止剩余任务(原因必填) | | POST | `/runs/{run_no}/cancel` | 请求停止剩余任务(原因必填) |
| POST | `/items/{id}/retry` | 人工重试(external_recheck,新 Attempt) | | POST | `/items/{id}/retry` | 人工重试(external_recheck,新 Attempt) |
| POST | `/items/{id}/manual-close` | 人工关闭(原因必填) | | POST | `/items/{id}/manual-close` | 人工关闭(原因必填) |
| POST | `/items/batch-requery` | 批量重查库存(body `item_ids`;单行隔离,逐行 external_recheck) |
| POST | `/items/batch-resume` | 批量恢复处理(body `item_ids`;按(来源,收料日期)分组重建范围预检,行随幂等刷新迁入新预检;收料文件不可用的来源自动触发 RPA 重抓并返回 `file_fetching`;单组隔离) |
| POST | `/items/batch-manual-close` | 批量人工关闭(body `item_ids` + `reason`;单行隔离) |
| GET | `/runs/{run_no}/exceptions.xlsx` | 七 Sheet 异常 Excel(下载留审计) | | GET | `/runs/{run_no}/exceptions.xlsx` | 七 Sheet 异常 Excel(下载留审计) |
| GET | `/runs/{run_no}/receipt-files` | 收料来源文件 zip(下载留审计) | | GET | `/runs/{run_no}/receipt-files` | 收料来源文件 zip(下载留审计) |
| GET | `/runs/{run_no}/external-inventory` | 预检冻结外部系统库存表 csv(下载留审计) | | GET | `/runs/{run_no}/external-inventory` | 预检冻结外部系统库存表 csv(下载留审计) |
权限:admin 或持有 `in_transit_transfer` Agent 权限;无权限 403。 权限:admin 或持有 `in_transit_transfer` Agent 权限;无权限 403。
### 4.1 行归属与恢复语义(2026-09-23 修订)
- **行单一归属**:`TransferInvoiceItem.precheck_id` 为唯一归属外键。重复预检时非终态行**原地迁移**到最新覆盖它的预检(幂等刷新);终态行(success / duplicate_success / manually_closed / cancelled / executing)不迁移、不复活。因此任意时刻一行只属于一份预检,两份并存预检的执行集合天然互斥,不存在重复写入(ERP 侧另有 Invoice 幂等键 + 写前复查双保险)。
- **恢复处理(resume)**:异常面板「恢复处理」= 按(来源, 收料日期)重建范围预检回到两步人工流程;`create_precheck` 的 `business_date` 用当天业务日(收料文件门禁只认当天抓取),`receipt_date_from/to` 用行的历史收料日期。恢复**不直接写 ERP**,可执行后仍走预检卡人工核对生成调拨单。**适用场景是 ERP 事实事后被修正**(补库存/上账/修批号):ERP 未修正时恢复的正确结果就是"仍阻断",响应按预检返回 `executable_count`,前端仅当存在可执行行才切预检卡,否则留在待处理池提示"仍阻断",且全阻断壳预检不入「最近预检」。
- **最近预检**:只列未执行、未过期、仍拥有归属行**且至少一行可执行**(`status='prechecking'` 除外)的预检;被新预检掏空的旧预检、恢复遗留的全阻断壳均不可见。
## 5. 部署 ## 5. 部署
```bash ```bash
+3
View File
@@ -762,6 +762,9 @@
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) | | 排程/恢复/异常/通知 | 后端已实现 | 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 | | 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md |
| 最近预检恢复入口 | 已实现 | GET /prechecks/recent 只列未执行+未过期+仍拥有归属行的预检(counts 按归属行实时聚合);Chat 首页「最近预检」一键恢复到既有预检卡继续勾选/执行,关闭窗口后无需重做预检 |
| 待处理池批量操作与恢复处理 | 已实现 | 异常表列与预检窗口一致(来源/单号/收料日期/料号/品名/库位/批号/数量/结果/老化);多选批量「重查 / 恢复处理 / 标记无需处理」(batch-requery / batch-resume / batch-manual-close,单行隔离);恢复处理按(来源,收料日期)分组重建范围预检回到两步人工流程(不直写 ERP),文件不可用自动触发 RPA 重抓;「重新查询 ERP」改名「重查」 |
| 收料日期默认与输入期限制 | 已实现 | 来源选择卡收料日期默认 D+1 规则日期(上海业务日 T-1);日期输入 max/min 即时限制 + 起止非法行内提示禁用确认(后端 RECEIPT_DATE_RANGE_INVALID 卡控保留双保险);「直接生成调拨单」改名「生成调拨单」 |
| 前端 Chat 卡片/结果页与四语言 | 实施中 | `frontend/src/features/chat/` 卡片(文件进度/预检/结果/待处理)与 admin 模块按计划实施 | | 前端 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` 近似(评估时显式赋值,关闭等操作也会刷新但那些状态本就不可执行)。
@@ -48,7 +48,7 @@ describe('transfer.api JSON request contract', () => {
expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' })); expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' }));
}); });
it('直接生成调拨单 POST 带 application/json', () => { it('生成调拨单 POST 带 application/json', () => {
executeTransferPrecheck('TPC-1', ['INV-001']); executeTransferPrecheck('TPC-1', ['INV-001']);
const [, init] = requestJson.mock.calls[0] as [string, RequestInit]; const [, init] = requestJson.mock.calls[0] as [string, RequestInit];
expect(init.method).toBe('POST'); expect(init.method).toBe('POST');
@@ -10,9 +10,12 @@ import type {
TransferActionResult, TransferActionResult,
TransferBacklogItem, TransferBacklogItem,
TransferBacklogSummary, TransferBacklogSummary,
TransferBatchResumeResponse,
TransferBatchResult,
TransferExecuteResponse, TransferExecuteResponse,
TransferPrecheckDetail, TransferPrecheckDetail,
TransferPrecheckSummary, TransferPrecheckSummary,
TransferRecentPrecheck,
TransferRunResult, TransferRunResult,
TransferSourceFileStatus, TransferSourceFileStatus,
TransferSourceOption, TransferSourceOption,
@@ -47,6 +50,10 @@ export const getTransferPrecheck = (precheckId: string) =>
headers: getAuthHeaders(), headers: getAuthHeaders(),
}); });
/** 最近预检列表(未执行、未过期、仍拥有归属行;供一键恢复预检卡) */
export const listRecentTransferPrechecks = () =>
requestJson<TransferRecentPrecheck[]>(`${BASE}/prechecks/recent`, { headers: getAuthHeaders() });
/** 确认选择范围并直接生成执行 Run */ /** 确认选择范围并直接生成执行 Run */
export const executeTransferPrecheck = (precheckId: string, invoiceNos: string[]) => export const executeTransferPrecheck = (precheckId: string, invoiceNos: string[]) =>
requestJson<TransferExecuteResponse>(`${BASE}/prechecks/${precheckId}/execute`, { requestJson<TransferExecuteResponse>(`${BASE}/prechecks/${precheckId}/execute`, {
@@ -97,6 +104,30 @@ export const downloadTransferErpInventory = (runNo: string) =>
export const downloadTransferExceptions = (runNo: string) => export const downloadTransferExceptions = (runNo: string) =>
requestBlob(`${BASE}/runs/${runNo}/exceptions.xlsx`, { headers: getAuthHeaders() }); 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 batchResumeTransferItems = (itemIds: number[]) =>
requestJson<TransferBatchResumeResponse>(`${BASE}/items/batch-resume`, {
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 缺省 = 全部阻断行) */ /** 批量重查 ERP 库存(可恢复阻断行;invoice_nos 缺省 = 全部阻断行) */
export const requeryTransferItems = (precheckNo: string, invoiceNos?: string[]) => export const requeryTransferItems = (precheckNo: string, invoiceNos?: string[]) =>
requestJson<{ precheck_no: string; total: number; results: Array<Record<string, unknown>> }>( requestJson<{ precheck_no: string; total: number; results: Array<Record<string, unknown>> }>(
@@ -1,22 +1,92 @@
<!-- <!--
features/chat/components/messages/TransferBacklogSummaryCard.vue 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 只读;
勾选集合为卡片本地态,操作经 emit 交父组件调用批量端点并刷新。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref } from 'vue';
import { deriveBatchNo } from './transferBatch';
import type { TransferBacklogItem } from '../../types/transfer.types'; import type { TransferBacklogItem } from '../../types/transfer.types';
defineProps<{ const props = defineProps<{
items: TransferBacklogItem[]; items: TransferBacklogItem[];
busy?: boolean;
/** 初始结果筛选(首页计数卡切片进入:closed 卡落「已关闭」切片等)。 */
initialFilter?: 'all' | 'recoverable' | 'closed' | 'unknown';
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
retry: [itemId: number];
close: [item: TransferBacklogItem];
refresh: []; 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 { function agingLabel(level: string): string {
const map: Record<string, string> = { const map: Record<string, string> = {
warn_3d: 'chat.transfer.agingWarn', warn_3d: 'chat.transfer.agingWarn',
@@ -27,6 +97,10 @@ function agingLabel(level: string): string {
}; };
return map[level] ?? 'chat.transfer.agingNormal'; return map[level] ?? 'chat.transfer.agingNormal';
} }
function rowKey(item: TransferBacklogItem): string {
return `${item.item_id}|${item.invoice_no}`;
}
</script> </script>
<template> <template>
@@ -42,36 +116,166 @@ function agingLabel(level: string): string {
{{ $t('chat.transfer.refreshProgress') }} {{ $t('chat.transfer.refreshProgress') }}
</button> </button>
</div> </div>
<ul v-if="items.length" class="flex flex-col gap-1.5">
<li <!-- 批量操作条:勾选 ≥1 行时原位替换筛选区 -->
v-for="item in items" <div v-if="selectedActionableIds.length" class="mb-2 flex flex-wrap items-center gap-2">
:key="item.item_id" <span class="text-xs font-bold text-secondary" data-testid="transfer-backlog-selected-count">
class="flex items-center justify-between gap-2 rounded-lg border border-subtle px-3 py-2 text-xs" {{ $t('chat.transfer.selectedRows', { count: selectedActionableIds.length }) }}
:data-testid="`transfer-backlog-${item.invoice_no}`" </span>
>
<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 <button
type="button" type="button"
class="rounded-lg border border-brand-200 px-2 py-1 font-bold text-brand-700 hover:bg-brand-50" 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-retry" data-testid="transfer-backlog-batch-requery"
@click="emit('retry', item.item_id)" :disabled="busy"
@click="emit('requery', selectedActionableIds)"
> >
{{ $t('chat.transfer.retryErp') }} {{ $t('chat.transfer.requeryRow') }}({{ selectedActionableIds.length }})
</button> </button>
<button <button
type="button" type="button"
class="rounded-lg border border-red-200 px-2 py-1 font-bold text-red-600 hover:bg-red-50" 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-close" 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"
>
{{
item.status === 'blocked_recoverable' ? $t('chat.transfer.resultBlocked')
: item.status === 'result_unknown' ? $t('chat.transfer.resultUnknown')
: $t('chat.transfer.statusClosed')
}}
</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)" @click="emit('close', item)"
> >
{{ $t('chat.transfer.manualClose') }} {{ $t('chat.transfer.manualClose') }}
@@ -80,9 +284,11 @@ function agingLabel(level: string): string {
<span v-else-if="item.status === 'result_unknown'" class="text-[11px] text-muted"> <span v-else-if="item.status === 'result_unknown'" class="text-[11px] text-muted">
{{ $t('chat.transfer.resultUnknownReadonly') }} {{ $t('chat.transfer.resultUnknownReadonly') }}
</span> </span>
</td>
</tr>
</tbody>
</table>
</div> </div>
</li>
</ul>
<div v-else class="rounded-lg bg-surface-soft p-3 text-xs text-muted"> <div v-else class="rounded-lg bg-surface-soft p-3 text-xs text-muted">
{{ $t('chat.transfer.noBacklog') }} {{ $t('chat.transfer.noBacklog') }}
</div> </div>
@@ -89,18 +89,44 @@ describe('TransferHomePanel chat home entry', () => {
expect(api.listTransferSources).toHaveBeenCalled(); expect(api.listTransferSources).toHaveBeenCalled();
}); });
it('点击历史待办计数卡独立触发 backlog 卡片', async () => { it('点击历史待办计数卡独立触发 backlog 卡片,并按计数卡切片初始筛选', async () => {
// [断言意图] 三张计数卡不再落入同一份全量列表:可恢复/已关闭/结果未知
// 各自带对应 resultFilter 打开待处理池(否则 0 行的已关闭/结果未知被 50 行可恢复淹没)。
api.listTransferBacklog.mockResolvedValue([ api.listTransferBacklog.mockResolvedValue([
{ item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1', { 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' }, 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(); const wrapper = mountHome();
await flushPromises(); await flushPromises();
await wrapper.find('[data-testid="transfer-home-recoverable"]').trigger('click'); await wrapper.find('[data-testid="transfer-home-recoverable"]').trigger('click');
await flushPromises(); await flushPromises();
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true); expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
expect(api.listTransferBacklog).toHaveBeenCalled(); 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 () => { it('子视图提供“返回首页”并切回 home', async () => {
@@ -1,10 +1,11 @@
<!-- <!--
features/chat/components/messages/TransferHomePanel.vue features/chat/components/messages/TransferHomePanel.vue
用途:在途仓自动调拨 Agent 的 Chat 首页入口区——home 视图展示标题、今日待办 用途:在途仓自动调拨 Agent 的 Chat 首页入口区——home 视图展示标题、今日待办
入口与三张历史待办计数卡;点击入口独立触发 source-select / backlog 卡片。 入口、最近预检(一键恢复)与三张历史待办计数卡;点击入口独立触发
source-select / backlog / 预检恢复卡片。
依赖:TransferMessageView(复用自驱动卡片)、useChatTransfer、i18n chat.transfer.*。 依赖:TransferMessageView(复用自驱动卡片)、useChatTransfer、i18n chat.transfer.*。
逻辑:home 时只消费 backlogSummary 计数;非 home 时渲染 TransferMessageView。 逻辑:home 时消费 backlogSummary 计数与 recentPrechecks 列表;非 home 时渲染
卡片不注入消息流,因此无需后端 ChatLog 消息(决策:补首页入口 A 方案)。 TransferMessageView。卡片不注入消息流,因此无需后端 ChatLog 消息。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'; import { computed, onMounted, ref, watch } from 'vue';
@@ -20,18 +21,33 @@ const emit = defineEmits<{
'flow-active': [active: boolean]; 'flow-active': [active: boolean];
}>(); }>();
type HomeView = 'home' | 'source-select' | 'backlog'; type HomeView = 'home' | 'source-select' | 'backlog' | 'precheck-restore';
/** 待处理池结果筛选(与 TransferBacklogSummaryCard 的筛选选项一致)。 */
type BacklogFilter = 'all' | 'recoverable' | 'closed' | 'unknown';
const transfer = useChatTransfer(); const transfer = useChatTransfer();
const view = ref<HomeView>('home'); const view = ref<HomeView>('home');
/** 最近预检入口选中的预检号(precheck-restore 视图传给 TransferMessageView 按ID恢复)。 */
const restorePrecheckId = ref('');
/** 历史待办计数卡对应的初始筛选:点击哪张卡就落到哪个切片,不再一律全量列表。 */
const backlogFilter = ref<BacklogFilter>('all');
/** 打开待处理池并按计数卡切片(recoverable/closed/unknown)。 */
function openBacklog(filter: BacklogFilter) {
backlogFilter.value = filter;
view.value = 'backlog';
}
/** 进入非 home 时通知父级隐藏聊天输入框(决策:来源选择为业务页,无对话输入区)。 */ /** 进入非 home 时通知父级隐藏聊天输入框(决策:来源选择为业务页,无对话输入区)。 */
watch(view, (value) => emit('flow-active', value !== 'home'), { immediate: true }); watch(view, (value) => emit('flow-active', value !== 'home'), { immediate: true });
/** home 视图仅需要待办汇总;进入时拉取计数。 */ /** home 视图需要待办汇总与最近预检;进入时拉取。 */
async function loadHomeSummary() { async function loadHomeSummary() {
if (view.value !== 'home') return; if (view.value !== 'home') return;
await transfer.loadBacklog(); await Promise.all([
transfer.loadBacklog().catch(() => undefined),
transfer.loadRecentPrechecks().catch(() => undefined),
]);
} }
onMounted(() => { void loadHomeSummary(); }); onMounted(() => { void loadHomeSummary(); });
@@ -39,12 +55,19 @@ watch(view, () => { void loadHomeSummary(); });
const displayAgentName = computed(() => props.agentName || '在途仓自动调拨'); const displayAgentName = computed(() => props.agentName || '在途仓自动调拨');
/** 非 home 视图把当前入口透传给自驱动的 TransferMessageView(决定 source-select 或 backlog)。 */ /** 确认窗口剩余分钟(前端按 expires_at 计算,用于最近预检行展示)。 */
const childPayload = computed(() => ( function remainingMinutes(expiresAt?: string | null): number {
view.value === 'source-select' if (!expiresAt) return 0;
? { kind: 'source-select' } const ms = new Date(expiresAt).getTime() - Date.now();
: { kind: 'backlog' } return Math.max(0, Math.ceil(ms / 60000));
)); }
/** 非 home 视图把当前入口透传给自驱动的 TransferMessageView。 */
const childPayload = computed(() => {
if (view.value === 'source-select') return { kind: 'source-select' };
if (view.value === 'precheck-restore') return { kind: 'precheck', precheck_id: restorePrecheckId.value };
return { kind: 'backlog', filter: backlogFilter.value };
});
function goBack() { function goBack() {
view.value = 'home'; view.value = 'home';
@@ -79,6 +102,35 @@ function goBack() {
</button> </button>
</section> </section>
<!-- 最近预检:关闭/离开视图后可一键恢复(后端只列未执行、未过期、仍拥有归属行) -->
<section v-if="transfer.recentPrechecks.value.length" aria-label="最近预检">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeRecentTitle') }}</p>
<div class="flex flex-col gap-2">
<button
v-for="recent in transfer.recentPrechecks.value"
:key="recent.precheck_no"
type="button"
data-testid="transfer-home-recent-precheck"
class="flex w-full items-center gap-3 rounded-2xl border border-default bg-surface p-3 text-left transition-colors hover:border-brand-200 hover:bg-brand-50"
@click="restorePrecheckId = recent.precheck_no; view = 'precheck-restore'"
>
<span class="min-w-0 flex-1">
<b class="block text-sm font-bold text-primary">{{ recent.precheck_no }}</b>
<span class="mt-0.5 block text-xs text-secondary">
{{ recent.business_date }}
· {{ $t('chat.transfer.executableCount') }} {{ recent.counts.executable_count }}
· {{ $t('chat.transfer.blockedCount') }} {{ recent.counts.blocked_count }}
<template v-if="recent.status === 'prechecking'"> · {{ $t('chat.transfer.recentPrechecking') }}</template>
<template v-else-if="remainingMinutes(recent.expires_at) > 0">
· {{ $t('chat.transfer.recentRemaining', { min: remainingMinutes(recent.expires_at) }) }}
</template>
</span>
</span>
<span class="shrink-0 text-xl text-brand-600">›</span>
</button>
</div>
</section>
<!-- 历史待办 --> <!-- 历史待办 -->
<section aria-label="历史待办"> <section aria-label="历史待办">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeHistoryLabel') }}</p> <p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeHistoryLabel') }}</p>
@@ -87,7 +139,7 @@ function goBack() {
type="button" type="button"
data-testid="transfer-home-recoverable" 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" 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="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> <b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeRecoverable') }}</b>
@@ -97,7 +149,7 @@ function goBack() {
type="button" type="button"
data-testid="transfer-home-closed" 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" 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="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> <b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeClosed') }}</b>
@@ -107,7 +159,7 @@ function goBack() {
type="button" type="button"
data-testid="transfer-home-unknown" 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" 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="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> <b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeUnknown') }}</b>
@@ -1,7 +1,7 @@
<!-- <!--
features/chat/components/messages/TransferManualCloseDialog.vue features/chat/components/messages/TransferManualCloseDialog.vue
用途:人工关闭弹窗(原因必填;关闭后永久排除,历史保留)。 用途:人工关闭弹窗(原因必填;关闭后永久排除,历史保留);count>1 时按批量文案展示。
依赖:props(open/invoiceNo)、i18n chat.transfer.*。 依赖:props(open/invoiceNo/count)、i18n chat.transfer.*。
逻辑:原因为空时确认按钮禁用;确认时 emit confirm(reason)。 逻辑:原因为空时确认按钮禁用;确认时 emit confirm(reason)。
--> -->
<script setup lang="ts"> <script setup lang="ts">
@@ -10,6 +10,8 @@ import { ref, watch } from 'vue';
const props = defineProps<{ const props = defineProps<{
open: boolean; open: boolean;
invoiceNo: string; invoiceNo: string;
/** 批量关闭的行数;>1 时忽略 invoiceNo,标题/提示切换为批量文案。 */
count?: number;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@@ -34,8 +36,13 @@ watch(
data-testid="transfer-manual-close-dialog" data-testid="transfer-manual-close-dialog"
> >
<div class="w-full max-w-md rounded-2xl bg-surface p-5 shadow-xl"> <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> <h3 class="text-base font-bold text-primary">
<p class="mt-1 text-xs text-muted">{{ invoiceNo }} · {{ $t('chat.transfer.manualCloseHint') }}</p> {{ $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 <textarea
v-model="reason" v-model="reason"
rows="3" rows="3"
@@ -12,10 +12,14 @@ import i18n from '@/i18n';
const api = vi.hoisted(() => ({ const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(), createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(), getTransferPrecheck: vi.fn(),
listRecentTransferPrechecks: vi.fn(),
executeTransferPrecheck: vi.fn(), executeTransferPrecheck: vi.fn(),
getTransferRun: vi.fn(), getTransferRun: vi.fn(),
retryTransferItem: vi.fn(), retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(), manualCloseTransferItem: vi.fn(),
batchRequeryTransferItems: vi.fn(),
batchResumeTransferItems: vi.fn(),
batchManualCloseTransferItems: vi.fn(),
downloadTransferReceiptFiles: vi.fn(), downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(), downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(), downloadTransferExceptions: vi.fn(),
@@ -27,6 +31,7 @@ const api = vi.hoisted(() => ({
vi.mock('@/features/chat/api/transfer.api', () => api); vi.mock('@/features/chat/api/transfer.api', () => api);
import TransferMessageView from './TransferMessageView.vue'; import TransferMessageView from './TransferMessageView.vue';
import { eligibleReceiptDateTo } from './transferDate';
const payload = { const payload = {
kind: 'precheck', kind: 'precheck',
@@ -85,7 +90,7 @@ describe('TransferMessageView self-driving wiring', () => {
expect((wrapper.find('[data-testid="transfer-check-INV-001"]').element as HTMLInputElement).checked).toBe(true); expect((wrapper.find('[data-testid="transfer-check-INV-001"]').element as HTMLInputElement).checked).toBe(true);
}); });
it('点击“直接生成调拨单”调用 execute API 并切换为结果卡', async () => { it('点击“生成调拨单”调用 execute API 并切换为结果卡', async () => {
const wrapper = mount(TransferMessageView, { const wrapper = mount(TransferMessageView, {
props: { payload }, props: { payload },
global: { plugins: [i18n] }, global: { plugins: [i18n] },
@@ -116,10 +121,12 @@ describe('TransferMessageView self-driving wiring', () => {
expect(wrapper.text()).not.toContain('审计'); expect(wrapper.text()).not.toContain('审计');
}); });
it('backlog 视图拉取待处理列表,重试/关闭调用对应 API', async () => { it('backlog 视图拉取待处理列表,行级重查/关闭调用对应 API', async () => {
api.listTransferBacklog.mockResolvedValue([{ api.listTransferBacklog.mockResolvedValue([{
item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1', 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', 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({ api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 1, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 }, recoverable: 1, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
@@ -135,18 +142,132 @@ describe('TransferMessageView self-driving wiring', () => {
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true); expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
expect(wrapper.text()).toContain('INV-001'); 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(); await flushPromises();
expect(api.retryTransferItem).toHaveBeenCalledWith(7); 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-reason"]').setValue('线下已处理');
await wrapper.find('[data-testid="transfer-close-confirm"]').trigger('click'); await wrapper.find('[data-testid="transfer-close-confirm"]').trigger('click');
await flushPromises(); await flushPromises();
expect(api.manualCloseTransferItem).toHaveBeenCalledWith(7, '线下已处理'); 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.batchResumeTransferItems.mockResolvedValue({ prechecks: [], file_fetching: [], skipped: [] });
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.batchResumeTransferItems).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('最近预检入口:仅携带 precheck_id 时按 ID 恢复预检卡', async () => {
api.getTransferPrecheck.mockResolvedValue({
summary: payload.summary,
items: payload.items,
sources: payload.sources,
});
const wrapper = mount(TransferMessageView, {
props: { payload: { kind: 'precheck', precheck_id: 'TPC-1' } },
global: { plugins: [i18n] },
});
await flushPromises();
expect(api.getTransferPrecheck).toHaveBeenCalledWith('TPC-1');
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
});
it('恢复处理成功返回预检时切换预检卡', 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' },
]);
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 1, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
});
api.batchResumeTransferItems.mockResolvedValue({
prechecks: [{ precheck_no: 'TPC-9', source_code: 'DBS-AWSBI', receipt_date: '2026-08-05', selected_item_count: 1, executable_count: 1 }],
file_fetching: [],
skipped: [],
});
api.getTransferPrecheck.mockResolvedValue({ summary: payload.summary, items: payload.items, sources: payload.sources });
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.getTransferPrecheck).toHaveBeenCalledWith('TPC-9');
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
});
it('恢复处理全部仍阻断(0 可执行)时不跳预检卡,留在待处理池', async () => {
// [断言意图] ERP 未修正时恢复的正确结果是"仍阻断":不打开全阻断的壳预检卡,
// 行留在待处理池(fail-closed),避免"恢复了个寂寞"的误导性跳转。
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' },
]);
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 1, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
});
api.batchResumeTransferItems.mockResolvedValue({
prechecks: [{ precheck_no: 'TPC-9', source_code: 'DBS-AWSBI', receipt_date: '2026-08-05', selected_item_count: 1, executable_count: 0 }],
file_fetching: [],
skipped: [],
});
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.getTransferPrecheck).not.toHaveBeenCalled();
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
});
it('来源实例选择:加载列表 → 确认范围 → 创建预检并切换预检卡(默认携带 D+1 日期范围)', async () => {
api.listTransferSources.mockResolvedValue([ api.listTransferSources.mockResolvedValue([
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' }, { source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
]); ]);
@@ -167,7 +288,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-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click'); await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
await flushPromises(); await flushPromises();
expect(api.createTransferPrecheck).toHaveBeenCalledWith({ source_codes: ['DBS-AWSBI'], transfer_type: 'in_transit_to_hub' }); const cutoff = eligibleReceiptDateTo();
expect(api.createTransferPrecheck).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-precheck-card"]').exists()).toBe(true); expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
}); });
}); });
@@ -1,13 +1,15 @@
<!-- <!--
features/chat/components/messages/TransferMessageView.vue features/chat/components/messages/TransferMessageView.vue
用途:在途调拨消息卡片的自驱动挂载视图——按 payload 形态渲染卡片,并把卡片按钮 用途:在途调拨消息卡片的自驱动挂载视图——按 payload 形态渲染卡片,并把卡片按钮
(直接生成调拨单 / 下载 / 重试 / 关闭)经 useChatTransfer 真实调用 API。 (生成调拨单 / 下载 / 重查 / 恢复 / 关闭)经 useChatTransfer 真实调用 API。
依赖:Transfer*Card、useChatTransfer、i18n chat.transfer.*。 依赖:Transfer*Card、useChatTransfer、i18n chat.transfer.*。
逻辑:payload 作为初始状态(ChatLog 回放);执行后切换为结果卡;下载走 requestBlob; 逻辑:payload 作为初始状态(ChatLog 回放);仅携带 precheck_id 时按 ID 恢复预检卡
(最近预检入口);执行后切换为结果卡;下载走 requestBlob;
不展示执行审计入口(决策 19)。 不展示执行审计入口(决策 19)。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'; import { computed, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import TransferPrecheckCard from './TransferPrecheckCard.vue'; import TransferPrecheckCard from './TransferPrecheckCard.vue';
import TransferFileProgressCard from './TransferFileProgressCard.vue'; import TransferFileProgressCard from './TransferFileProgressCard.vue';
import TransferProgressCard from './TransferProgressCard.vue'; import TransferProgressCard from './TransferProgressCard.vue';
@@ -32,7 +34,8 @@ const props = defineProps<{
payload?: Record<string, unknown> | null; payload?: Record<string, unknown> | null;
}>(); }>();
const { error: notifyError } = useMessage(); const { t } = useI18n();
const { error: notifyError, success: notifySuccess, warning: notifyWarning } = useMessage();
/** 统一错误提示:BusinessError 带本地化 message,其余回退到 String(e)。 */ /** 统一错误提示:BusinessError 带本地化 message,其余回退到 String(e)。 */
function reportError(e: unknown) { function reportError(e: unknown) {
@@ -41,6 +44,12 @@ function reportError(e: unknown) {
const kind = computed(() => String(props.payload?.kind ?? 'precheck')); const kind = computed(() => String(props.payload?.kind ?? 'precheck'));
const mode = ref(kind.value); const mode = ref(kind.value);
/** 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<TransferPrecheckSummary | null>((props.payload?.summary as TransferPrecheckSummary) ?? null); const summaryRef = ref<TransferPrecheckSummary | null>((props.payload?.summary as TransferPrecheckSummary) ?? null);
const items = ref<TransferPrecheckItem[]>((props.payload?.items as TransferPrecheckItem[]) ?? []); const items = ref<TransferPrecheckItem[]>((props.payload?.items as TransferPrecheckItem[]) ?? []);
const runNo = ref(String(props.payload?.run_no ?? '')); const runNo = ref(String(props.payload?.run_no ?? ''));
@@ -48,6 +57,8 @@ const status = ref(String(props.payload?.status ?? 'executing'));
const run = ref<TransferRunResult | null>((props.payload?.run as TransferRunResult) ?? null); const run = ref<TransferRunResult | null>((props.payload?.run as TransferRunResult) ?? null);
const busy = ref(false); const busy = ref(false);
const closeTarget = ref<TransferBacklogItem | null>(null); const closeTarget = ref<TransferBacklogItem | null>(null);
/** 批量标记无需处理的明细 id 集合(与单行关闭共用同一弹窗)。 */
const batchCloseIds = ref<number[]>([]);
/** 正在重试收料 RPA 的来源编码集合(按来源独立展示重试中)。 */ /** 正在重试收料 RPA 的来源编码集合(按来源独立展示重试中)。 */
const retryingSource = ref<Set<string>>(new Set()); const retryingSource = ref<Set<string>>(new Set());
@@ -61,8 +72,27 @@ onMounted(() => {
if (kind.value === 'source-select') { if (kind.value === 'source-select') {
void transfer.loadSources(); void transfer.loadSources();
} }
// 最近预检入口:仅携带 precheck_id 无 summary,按 ID 恢复预检进度与明细。
if (kind.value === 'precheck' && !summaryRef.value && props.payload?.precheck_id) {
void restoreById(String(props.payload.precheck_id));
}
}); });
/** 按预检号恢复预检卡(GET /prechecks/{id},页面刷新/最近预检入口共用)。 */
async function restoreById(precheckId: string) {
busy.value = true;
try {
const detail = await transfer.restorePrecheckById(precheckId);
mode.value = 'precheck';
summaryRef.value = detail.summary;
items.value = detail.items;
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
/** payload 更新时重置本地状态(历史回放/刷新);初始化组合式函数上下文 */ /** payload 更新时重置本地状态(历史回放/刷新);初始化组合式函数上下文 */
function applyPayload(payload?: Record<string, unknown> | null) { function applyPayload(payload?: Record<string, unknown> | null) {
if (!payload) return; if (!payload) return;
@@ -178,16 +208,87 @@ async function onBacklogRetry(itemId: number) {
} }
} }
/** 批量重查(待处理池多选):逐行隔离,完成后刷新列表并弹汇总。 */
async function onBacklogRequery(itemIds: number[]) {
busy.value = true;
try {
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);
} finally {
busy.value = false;
}
}
/** 恢复处理(行级/多选):按(来源, 收料日期)分组重建预检。仅当重建预检
* 含可执行行才切换预检卡(其余份数引导到「最近预检」);全部仍阻断(ERP
* 未修正)不跳转,留在待处理池并明确提示;文件不可用的来源已触发重抓。 */
async function onBacklogResume(itemIds: number[]) {
busy.value = true;
try {
const result = await transfer.batchResume(itemIds);
await transfer.loadBacklog();
const actionable = result.prechecks.filter((entry) => entry.executable_count > 0);
const firstActionable = actionable[0];
if (firstActionable) {
const detail = await transfer.restorePrecheckById(firstActionable.precheck_no);
mode.value = 'precheck';
summaryRef.value = detail.summary;
items.value = detail.items;
if (actionable.length > 1) {
notifySuccess(t('chat.transfer.toastResumeOpened', { count: actionable.length }));
}
}
const stillBlockedCount = result.prechecks
.filter((entry) => entry.executable_count === 0)
.reduce((sum, entry) => sum + entry.selected_item_count, 0);
if (stillBlockedCount) {
notifyWarning(t('chat.transfer.toastResumeStillBlocked', { count: stillBlockedCount }));
}
const refetching = result.file_fetching.filter((entry) => entry.ok).map((entry) => entry.source_code);
if (refetching.length) {
notifyWarning(t('chat.transfer.toastResumeRefetching', { sources: refetching.join('、') }));
}
const failedCount = result.file_fetching.filter((entry) => !entry.ok).length + result.skipped.length;
if (failedCount) {
notifyWarning(t('chat.transfer.toastResumeSkipped', { count: failedCount }));
}
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
function onBacklogClose(item: TransferBacklogItem) { function onBacklogClose(item: TransferBacklogItem) {
closeTarget.value = item; closeTarget.value = item;
} }
/** 批量标记无需处理:复用关闭弹窗(批量文案)。 */
function onBacklogBatchClose(itemIds: number[]) {
batchCloseIds.value = itemIds;
}
function onCancelClose() {
closeTarget.value = null;
batchCloseIds.value = [];
}
async function onCloseConfirm(reason: string) { async function onCloseConfirm(reason: string) {
if (!closeTarget.value) return;
busy.value = true; busy.value = true;
try { 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); await transfer.manualClose(closeTarget.value.item_id, reason);
closeTarget.value = null; closeTarget.value = null;
}
await transfer.loadBacklog(); await transfer.loadBacklog();
} catch (e) { } catch (e) {
reportError(e); reportError(e);
@@ -274,16 +375,22 @@ async function onSourceRetry(sourceCodes: string[]) {
<TransferBacklogSummaryCard <TransferBacklogSummaryCard
v-else-if="mode === 'backlog'" v-else-if="mode === 'backlog'"
:items="transfer.backlog.value" :items="transfer.backlog.value"
:busy="busy"
:initial-filter="backlogInitialFilter"
@retry="onBacklogRetry" @retry="onBacklogRetry"
@requery="onBacklogRequery"
@resume="onBacklogResume"
@close="onBacklogClose" @close="onBacklogClose"
@batch-close="onBacklogBatchClose"
@refresh="() => transfer.loadBacklog()" @refresh="() => transfer.loadBacklog()"
/> />
<TransferManualCloseDialog <TransferManualCloseDialog
v-if="closeTarget" v-if="closeTarget || batchCloseIds.length"
:open="Boolean(closeTarget)" :open="Boolean(closeTarget || batchCloseIds.length)"
:invoice-no="closeTarget.invoice_no" :invoice-no="closeTarget?.invoice_no ?? ''"
:count="batchCloseIds.length"
@confirm="onCloseConfirm" @confirm="onCloseConfirm"
@cancel="closeTarget = null" @cancel="onCancelClose"
/> />
</div> </div>
</template> </template>
@@ -10,6 +10,7 @@ import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import i18n from '@/i18n'; import i18n from '@/i18n';
import TransferSourceSelectCard from './TransferSourceSelectCard.vue'; import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
import { eligibleReceiptDateTo } from './transferDate';
const readySources = [ const readySources = [
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI 在途仓', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' }, { 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),不再平铺占宽', () => { it('D+1 规则提示收进 ⓘ 悬浮(title),不再平铺占宽', () => {
// [断言意图] 长规则文案通过原生 title 渐进披露,紧凑日期行不换行错位。 // [断言意图] 长规则文案通过原生 title 渐进披露,紧凑日期行不换行错位。
const wrapper = mountCard(); 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 () => { it('“只选可重试”勾选无文件/失败来源', async () => {
@@ -13,6 +13,7 @@
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage'; import { useMessage } from '@/shared/composables/useMessage';
import { eligibleReceiptDateTo } from './transferDate';
import type { TransferSourceOption, TransferType } from '../../types/transfer.types'; import type { TransferSourceOption, TransferType } from '../../types/transfer.types';
const props = defineProps<{ const props = defineProps<{
@@ -33,9 +34,18 @@ const { warning: notifyWarning } = useMessage();
const { t } = useI18n(); const { t } = useI18n();
const selected = ref<Set<string>>(new Set()); const selected = ref<Set<string>>(new Set());
/** 收料日期范围(预检查询范围);截止不得超出 D+1 规则(后端卡控)。 */ /** 收料日期范围(预检查询范围):默认 D+1 规则日期(T-1),上限同(输入期限制,
const dateFrom = ref(''); * 不等提交报错);后端 RECEIPT_DATE_RANGE_INVALID 卡控保留为双保险。 */
const dateTo = ref(''); 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 开放。 */ /** 调拨业务类型:决定本次预检纳入哪些收料数据;一期仅类型 1 开放。 */
const transferType = ref<TransferType>('in_transit_to_hub'); const transferType = ref<TransferType>('in_transit_to_hub');
@@ -70,7 +80,9 @@ const batchRetryDisabled = computed(() => props.busy || selectedRetryableCount.v
const selectedHasReadyFile = computed(() => const selectedHasReadyFile = computed(() =>
[...selected.value].some((code) => props.sources.find((s) => s.source_code === code)?.has_ready_file), [...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); const downloadDisabled = computed(() => props.busy || !selectedHasReadyFile.value);
function toggle(sourceCode: string, checked: boolean) { function toggle(sourceCode: string, checked: boolean) {
@@ -170,6 +182,7 @@ function confirm() {
<input <input
v-model="dateFrom" v-model="dateFrom"
type="date" type="date"
:max="maxReceiptDate"
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary" class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
data-testid="transfer-source-date-from" data-testid="transfer-source-date-from"
/> />
@@ -177,6 +190,8 @@ function confirm() {
<input <input
v-model="dateTo" v-model="dateTo"
type="date" type="date"
:max="maxReceiptDate"
:min="dateFrom || undefined"
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary" class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
data-testid="transfer-source-date-to" data-testid="transfer-source-date-to"
/> />
@@ -186,6 +201,10 @@ function confirm() {
:title="$t('chat.transfer.receiptDateHint')" :title="$t('chat.transfer.receiptDateHint')"
data-testid="transfer-source-date-hint" data-testid="transfer-source-date-hint"
>ⓘ</span> >ⓘ</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>
</div> </div>
@@ -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);
}
@@ -9,6 +9,9 @@
import { computed, ref, type Ref } from 'vue'; import { computed, ref, type Ref } from 'vue';
import { useMessage } from '@/shared/composables/useMessage'; import { useMessage } from '@/shared/composables/useMessage';
import { import {
batchManualCloseTransferItems,
batchResumeTransferItems,
batchRequeryTransferItems,
cancelTransferRun, cancelTransferRun,
createTransferPrecheck, createTransferPrecheck,
downloadTransferErpInventory, downloadTransferErpInventory,
@@ -18,6 +21,7 @@ import {
getTransferBacklogSummary, getTransferBacklogSummary,
getTransferPrecheck, getTransferPrecheck,
getTransferRun, getTransferRun,
listRecentTransferPrechecks,
listTransferBacklog, listTransferBacklog,
listTransferSources, listTransferSources,
manualCloseTransferItem, manualCloseTransferItem,
@@ -27,9 +31,12 @@ import {
import type { import type {
TransferBacklogItem, TransferBacklogItem,
TransferBacklogSummary, TransferBacklogSummary,
TransferBatchResumeResponse,
TransferBatchResult,
TransferPrecheckDetail, TransferPrecheckDetail,
TransferPrecheckItem, TransferPrecheckItem,
TransferPrecheckSummary, TransferPrecheckSummary,
TransferRecentPrecheck,
TransferRunResult, TransferRunResult,
TransferSourceOption, TransferSourceOption,
TransferSourceProgress, TransferSourceProgress,
@@ -47,6 +54,7 @@ export function useChatTransfer() {
const run = ref<TransferRunResult | null>(null); const run = ref<TransferRunResult | null>(null);
const backlog = ref<TransferBacklogItem[]>([]); const backlog = ref<TransferBacklogItem[]>([]);
const backlogSummary = ref<TransferBacklogSummary | null>(null); const backlogSummary = ref<TransferBacklogSummary | null>(null);
const recentPrechecks = ref<TransferRecentPrecheck[]>([]);
const sourceOptions = ref<TransferSourceOption[]>([]); const sourceOptions = ref<TransferSourceOption[]>([]);
const selected = ref<Set<string>>(new Set()); const selected = ref<Set<string>>(new Set());
const busy = ref(false); const busy = ref(false);
@@ -210,6 +218,35 @@ export function useChatTransfer() {
return { items, summary }; return { items, summary };
} }
/** 加载最近预检(未执行、未过期、仍拥有归属行;供一键恢复预检卡) */
async function loadRecentPrechecks() {
recentPrechecks.value = await listRecentTransferPrechecks();
return recentPrechecks.value;
}
/** 按预检号恢复预检进度(最近预检入口 → 预检卡) */
async function restorePrecheckById(id: string) {
const detail = await getTransferPrecheck(id);
precheckId.value = detail.summary.precheck_id;
applyDetail(detail);
return detail;
}
/** 批量重查库存(单行隔离,结果由调用方刷新列表后展示) */
async function batchRequery(itemIds: number[]): Promise<TransferBatchResult> {
return batchRequeryTransferItems(itemIds);
}
/** 批量恢复处理:按(来源, 收料日期)分组重建预检,返回预检/重抓/跳过明细 */
async function batchResume(itemIds: number[]): Promise<TransferBatchResumeResponse> {
return batchResumeTransferItems(itemIds);
}
/** 批量人工关闭(原因整批共用;单行隔离) */
async function batchManualClose(itemIds: number[], reason: string): Promise<TransferBatchResult> {
return batchManualCloseTransferItems(itemIds, reason);
}
function saveBlob(blob: Blob, filename: string) { function saveBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const link = document.createElement('a'); const link = document.createElement('a');
@@ -228,6 +265,7 @@ export function useChatTransfer() {
run.value = null; run.value = null;
backlog.value = []; backlog.value = [];
backlogSummary.value = null; backlogSummary.value = null;
recentPrechecks.value = [];
sourceOptions.value = []; sourceOptions.value = [];
selected.value = new Set(); selected.value = new Set();
error.value = ''; error.value = '';
@@ -242,6 +280,7 @@ export function useChatTransfer() {
run, run,
backlog, backlog,
backlogSummary, backlogSummary,
recentPrechecks,
sourceOptions, sourceOptions,
selected, selected,
selectedCount, selectedCount,
@@ -260,6 +299,11 @@ export function useChatTransfer() {
loadSources, loadSources,
retrySourceRpa, retrySourceRpa,
loadBacklog, loadBacklog,
loadRecentPrechecks,
restorePrecheckById,
batchRequery,
batchResume,
batchManualClose,
downloadReceiptFiles, downloadReceiptFiles,
downloadErpInventory, downloadErpInventory,
downloadExceptions, downloadExceptions,
@@ -1,7 +1,7 @@
/** /**
* features/chat/e2e/in-transit-transfer.spec.ts * features/chat/e2e/in-transit-transfer.spec.ts
* 用途:在途仓自动调拨全链路契约冒烟(对应 TDD §10 主路径)—— * 用途:在途仓自动调拨全链路契约冒烟(对应 TDD §10 主路径)——
* 预检 → 选择子集 → 直接生成调拨单 → Run 恢复 → 下载留底。 * 预检 → 选择子集 → 生成调拨单 → Run 恢复 → 下载留底。
* 依赖:Vitest、vi.mock(transfer.api)、useChatTransfer。 * 依赖:Vitest、vi.mock(transfer.api)、useChatTransfer。
* 逻辑:不启浏览器;用组合式函数 + Mock API 断言产品契约,避免 e2e 环境依赖 * 逻辑:不启浏览器;用组合式函数 + Mock API 断言产品契约,避免 e2e 环境依赖
* (与仓库 shipping e2e 约定一致)。 * (与仓库 shipping e2e 约定一致)。
@@ -120,7 +120,7 @@ export interface TransferExecuteResponse {
result?: TransferRunResult['result']; result?: TransferRunResult['result'];
} }
/** 待处理池项 */ /** 待处理池项(明细字段与预检窗口列一致) */
export interface TransferBacklogItem { export interface TransferBacklogItem {
item_id: number; item_id: number;
source_code: string; source_code: string;
@@ -131,6 +131,52 @@ export interface TransferBacklogItem {
age_days: number; age_days: number;
aging_level: string; aging_level: string;
last_attempt_at?: string | null; last_attempt_at?: string | null;
receipt_date?: string | null;
material_name?: string | null;
from_warehouse?: string | null;
to_warehouse?: string | null;
lot_no?: string | null;
receipt_quantity?: string | null;
external_quantity?: string | null;
}
/** 最近预检(未执行、未过期、仍拥有归属行;counts 为归属行实时聚合) */
export interface TransferRecentPrecheck {
precheck_no: string;
business_date: string;
status: string;
transfer_type?: string | null;
source_codes: string[];
counts: {
total: number;
executable_count: number;
blocked_count: number;
not_matured_count: number;
};
estimated_transfer_quantity: string;
estimated_external_write_count: number;
created_at?: string | null;
expires_at?: string | null;
}
/** 批量操作结果(单行隔离:ok 行带 status,失败行带 error) */
export interface TransferBatchResult {
total: number;
results: Array<{ item_id: number; invoice_no?: string; ok: boolean; status?: string; error?: string }>;
}
/** 批量恢复响应(按来源+收料日期分组重建的预检 / 触发重抓的来源 / 跳过行) */
export interface TransferBatchResumeResponse {
prechecks: Array<{
precheck_no: string;
source_code: string;
receipt_date: string;
selected_item_count: number;
/** 重建预检后的可执行行数;0 表示 ERP 未修正(不跳预检卡) */
executable_count: number;
}>;
file_fetching: Array<{ source_code: string; ok: boolean; callback_id?: string; error_code?: string }>;
skipped: Array<{ item_id: number; invoice_no: string; error: string }>;
} }
/** 操作结果(重试/关闭/取消) */ /** 操作结果(重试/关闭/取消) */
+21 -6
View File
@@ -3715,7 +3715,7 @@
"reasonExternalQueryFailed": "External system query failed", "reasonExternalQueryFailed": "External system query failed",
"reasonFutureDate": "Receipt date is after the business date", "reasonFutureDate": "Receipt date is after the business date",
"selectedCount": "{count} selected", "selectedCount": "{count} selected",
"generateTransfer": "Generate transfer order", "generateTransfer": "Generate transfer orders",
"colSource": "Source", "colSource": "Source",
"colMaterial": "Material", "colMaterial": "Material",
"colName": "Name", "colName": "Name",
@@ -3728,10 +3728,10 @@
"colFromBatch": "Outbound Batch", "colFromBatch": "Outbound Batch",
"filterPlaceholder": "Filter by material / name / Invoice / batch", "filterPlaceholder": "Filter by material / name / Invoice / batch",
"filterAll": "All results", "filterAll": "All results",
"requerySelected": "Requery selected ERP stock", "requerySelected": "Requery selected",
"receiptDateLabel": "Receipt date", "receiptDateLabel": "Receipt date",
"receiptDateTo": "Receipt date to", "receiptDateTo": "Receipt date end",
"receiptDateHint": "End cannot exceed the D+1 rule (day before business date)", "receiptDateHint": "Defaults to the D+1 rule date (day before business date, the precheck cutoff); end cannot exceed it and start cannot be after end",
"requeryRow": "Requery", "requeryRow": "Requery",
"colToQty": "To qty", "colToQty": "To qty",
"colResult": "Result", "colResult": "Result",
@@ -3758,7 +3758,22 @@
"downloadErpInventory": "Download ERP inventory", "downloadErpInventory": "Download ERP inventory",
"downloadExceptions": "Download exceptions Excel", "downloadExceptions": "Download exceptions Excel",
"backlogTitle": "Backlog exceptions", "backlogTitle": "Backlog exceptions",
"retryErp": "Re-query ERP", "resumeAction": "Resume",
"colAging": "Aging",
"colAction": "Actions",
"selectedRows": "{count} selected",
"clearSelection": "Clear selection",
"receiptDateInvalid": "Start date cannot be after end date",
"homeRecentTitle": "Recent prechecks",
"recentRemaining": "{min} min left",
"recentPrechecking": "Prechecking…",
"toastRequeryDone": "Requery done: {ok} rows updated, {failed} failed",
"toastResumeOpened": "{count} prechecks created; the first is opened, continue the rest under Recent prechecks",
"toastResumeRefetching": "Receipt file unavailable for {sources}; a refetch has been triggered, resume again once ready",
"toastResumeSkipped": "{count} rows could not be resumed",
"toastResumeStillBlocked": "Resume finished: {count} rows still blocked (ERP stock not matched); resume again after stock is corrected",
"toastCloseDone": "Closed: {ok} succeeded, {failed} failed",
"batchCloseTitle": "Mark as no further action ({count} items)",
"manualClose": "Mark as no further action", "manualClose": "Mark as no further action",
"manualCloseTitle": "Mark as no further action", "manualCloseTitle": "Mark as no further action",
"manualCloseHint": "Auto schedule will skip it; history and audit are kept permanently.", "manualCloseHint": "Auto schedule will skip it; history and audit are kept permanently.",
@@ -3794,7 +3809,7 @@
"homeTodayHint": "After selecting source instances, the system uses yesterday as the business date by default.", "homeTodayHint": "After selecting source instances, the system uses yesterday as the business date by default.",
"homeHistoryLabel": "Pending tasks", "homeHistoryLabel": "Pending tasks",
"homeRecoverable": "Recoverable exceptions", "homeRecoverable": "Recoverable exceptions",
"homeRecoverableHint": "Re-query ERP stock before continuing", "homeRecoverableHint": "Requery stock or resume processing in one click",
"homeClosed": "Manually closed", "homeClosed": "Manually closed",
"homeClosedHint": "View reason and restore processing", "homeClosedHint": "View reason and restore processing",
"homeUnknown": "Unknown result", "homeUnknown": "Unknown result",
+2 -1
View File
@@ -552,6 +552,7 @@
"TRANSFER.EXTERNAL_QUERY_TIMEOUT": "External system query timed out; retry.", "TRANSFER.EXTERNAL_QUERY_TIMEOUT": "External system query timed out; retry.",
"TRANSFER.PRECHECK_ALREADY_EXECUTED": "This precheck was already executed.", "TRANSFER.PRECHECK_ALREADY_EXECUTED": "This precheck was already executed.",
"TRANSFER.SELECTION_INVALID": "Selection contains non-executable invoices.", "TRANSFER.SELECTION_INVALID": "Selection contains non-executable invoices.",
"TRANSFER.INVALID_STATE_TRANSITION": "Invalid state transition." "TRANSFER.INVALID_STATE_TRANSITION": "Invalid state transition.",
"TRANSFER.BATCH_ITEMS_REQUIRED": "Item ids are required."
} }
} }
+21 -6
View File
@@ -3715,7 +3715,7 @@
"reasonExternalQueryFailed": "การสอบถามระบบภายนอกล้มเหลว", "reasonExternalQueryFailed": "การสอบถามระบบภายนอกล้มเหลว",
"reasonFutureDate": "วันที่รับสินค้าหลังวันที่ทำธุรกรรม", "reasonFutureDate": "วันที่รับสินค้าหลังวันที่ทำธุรกรรม",
"selectedCount": "เลือก {count} รายการ", "selectedCount": "เลือก {count} รายการ",
"generateTransfer": "สร้างใบโอนทันที", "generateTransfer": "สร้างใบโอน",
"colSource": "แหล่งรับของ", "colSource": "แหล่งรับของ",
"colMaterial": "รหัสวัสดุ", "colMaterial": "รหัสวัสดุ",
"colName": "ชื่อ", "colName": "ชื่อ",
@@ -3728,10 +3728,10 @@
"colFromBatch": "ล็อตต้นทาง", "colFromBatch": "ล็อตต้นทาง",
"filterPlaceholder": "กรองตามรหัสวัสดุ / ชื่อ / Invoice / ล็อต", "filterPlaceholder": "กรองตามรหัสวัสดุ / ชื่อ / Invoice / ล็อต",
"filterAll": "ทุกผลลัพธ์", "filterAll": "ทุกผลลัพธ์",
"requerySelected": "ตรวจซ้ำ ERP ที่เลือก", "requerySelected": "ตรวจซ้ำที่เลือก",
"receiptDateLabel": "วันที่รับสินค้า", "receiptDateLabel": "วันที่รับสินค้า",
"receiptDateTo": "วันที่รับสินค้าถึง", "receiptDateTo": "วันที่รับสินค้าสิ้นสุด",
"receiptDateHint": "วันสิ้นสุดต้องไม่เกินกฎ D+1 (วันก่อนวันทำการ)", "receiptDateHint": "ค่าเริ่มต้นเป็นวันตามกฎ D+1 (วันก่อนวันทำการ ซึ่งเป็นเส้นตายการตรวจสอบ); วันสิ้นสุดต้องไม่เกินวันนี้และวันเริ่มต้นต้องไม่ช้ากว่าวันสิ้นสุด",
"requeryRow": "ตรวจซ้ำ", "requeryRow": "ตรวจซ้ำ",
"colToQty": "จำนวนปลายทาง", "colToQty": "จำนวนปลายทาง",
"colResult": "ผลตรวจ", "colResult": "ผลตรวจ",
@@ -3758,7 +3758,22 @@
"downloadErpInventory": "ดาวน์โหลดสต็อก ERP", "downloadErpInventory": "ดาวน์โหลดสต็อก ERP",
"downloadExceptions": "ดาวน์โหลด Excel ข้อผิดพลาด", "downloadExceptions": "ดาวน์โหลด Excel ข้อผิดพลาด",
"backlogTitle": "รายการค้างดำเนินการ", "backlogTitle": "รายการค้างดำเนินการ",
"retryErp": "สอบถาม ERP อีกครั้ง", "resumeAction": "ดำเนินการต่อ",
"colAging": "ความเก่า",
"colAction": "การดำเนินการ",
"selectedRows": "เลือกแล้ว {count} แถว",
"clearSelection": "ล้างการเลือก",
"receiptDateInvalid": "วันเริ่มต้นต้องไม่ช้ากว่าวันสิ้นสุด",
"homeRecentTitle": "การตรวจสอบก่อนโอนล่าสุด",
"recentRemaining": "เหลือ {min} นาที",
"recentPrechecking": "กำลังตรวจสอบ…",
"toastRequeryDone": "ตรวจซ้ำเสร็จ: อัปเดตแล้ว {ok} แถว ล้มเหลว {failed} แถว",
"toastResumeOpened": "สร้างการตรวจสอบก่อนโอน {count} รายการ เปิดรายการแรกแล้ว ที่เหลือดำเนินการต่อในหัวข้อการตรวจสอบก่อนโอนล่าสุด",
"toastResumeRefetching": "ไฟล์รับสินค้าไม่พร้อมใช้สำหรับ {sources} ทริกเกอร์การดึงข้อมูลใหม่แล้ว โปรดดำเนินการต่ออีกครั้งเมื่อพร้อม",
"toastResumeSkipped": "{count} แถวไม่สามารถดำเนินการต่อได้",
"toastResumeStillBlocked": "ดำเนินการต่อเสร็จ: {count} แถวยังถูกบล็อก (สต็อก ERP ยังไม่ตรง) สามารถดำเนินการต่ออีกครั้งหลังแก้ไขสต็อก",
"toastCloseDone": "ปิดแล้ว: สำเร็จ {ok} รายการ ล้มเหลว {failed} รายการ",
"batchCloseTitle": "ทำเครื่องหมายไม่ต้องดำเนินการต่อ ({count} รายการ)",
"manualClose": "ทำเครื่องหมายไม่ต้องดำเนินการ", "manualClose": "ทำเครื่องหมายไม่ต้องดำเนินการ",
"manualCloseTitle": "ทำเครื่องหมายไม่ต้องดำเนินการ", "manualCloseTitle": "ทำเครื่องหมายไม่ต้องดำเนินการ",
"manualCloseHint": "หลังปิดระบบอัตโนมัติจะไม่ประมวลผลอีก ประวัติและการตรวจสอบคงอยู่ถาวร", "manualCloseHint": "หลังปิดระบบอัตโนมัติจะไม่ประมวลผลอีก ประวัติและการตรวจสอบคงอยู่ถาวร",
@@ -3794,7 +3809,7 @@
"homeTodayHint": "หลังจากเลือกแหล่งรับ ระบบจะใช้เมื่อวานเป็นวันที่ทำรายการโดยค่าเริ่มต้น", "homeTodayHint": "หลังจากเลือกแหล่งรับ ระบบจะใช้เมื่อวานเป็นวันที่ทำรายการโดยค่าเริ่มต้น",
"homeHistoryLabel": "งานค้าง", "homeHistoryLabel": "งานค้าง",
"homeRecoverable": "รายการผิดปกติที่กู้คืนได้", "homeRecoverable": "รายการผิดปกติที่กู้คืนได้",
"homeRecoverableHint": "สามารถสอบถามสต็อก ERP ใหม่ก่อนดำเนินการต่อ", "homeRecoverableHint": "ตรวจซ้ำสต็อกหรือดำเนินการต่อได้ทันที",
"homeClosed": "ปิดด้วยตนเองแล้ว", "homeClosed": "ปิดด้วยตนเองแล้ว",
"homeClosedHint": "สามารถดูสาเหตุและกู้คืนการดำเนินการได้", "homeClosedHint": "สามารถดูสาเหตุและกู้คืนการดำเนินการได้",
"homeUnknown": "ผลลัพธ์ไม่ทราบ", "homeUnknown": "ผลลัพธ์ไม่ทราบ",
+2 -1
View File
@@ -552,6 +552,7 @@
"TRANSFER.EXTERNAL_QUERY_TIMEOUT": "สอบถามระบบภายนอกหมดเวลา กรุณาลองใหม่", "TRANSFER.EXTERNAL_QUERY_TIMEOUT": "สอบถามระบบภายนอกหมดเวลา กรุณาลองใหม่",
"TRANSFER.PRECHECK_ALREADY_EXECUTED": "การตรวจสอบนี้ดำเนินการแล้ว", "TRANSFER.PRECHECK_ALREADY_EXECUTED": "การตรวจสอบนี้ดำเนินการแล้ว",
"TRANSFER.SELECTION_INVALID": "รายการที่เลือกมี Invoice ที่ดำเนินการไม่ได้", "TRANSFER.SELECTION_INVALID": "รายการที่เลือกมี Invoice ที่ดำเนินการไม่ได้",
"TRANSFER.INVALID_STATE_TRANSITION": "การเปลี่ยนสถานะไม่ถูกต้อง" "TRANSFER.INVALID_STATE_TRANSITION": "การเปลี่ยนสถานะไม่ถูกต้อง",
"TRANSFER.BATCH_ITEMS_REQUIRED": "กรุณาระบุรายการที่ต้องการดำเนินการ"
} }
} }
+20 -5
View File
@@ -3788,7 +3788,7 @@
"reasonExternalQueryFailed": "外部系统查询失败", "reasonExternalQueryFailed": "外部系统查询失败",
"reasonFutureDate": "收料日期晚于业务日期", "reasonFutureDate": "收料日期晚于业务日期",
"selectedCount": "已选 {count} 张", "selectedCount": "已选 {count} 张",
"generateTransfer": "直接生成调拨单", "generateTransfer": "生成调拨单",
"colSource": "收料来源", "colSource": "收料来源",
"colMaterial": "料号", "colMaterial": "料号",
"colName": "品名", "colName": "品名",
@@ -3801,10 +3801,10 @@
"colFromBatch": "拨出批号", "colFromBatch": "拨出批号",
"filterPlaceholder": "按料号 / 品名 / Invoice / 批号筛选", "filterPlaceholder": "按料号 / 品名 / Invoice / 批号筛选",
"filterAll": "全部结果", "filterAll": "全部结果",
"requerySelected": "重查选中 ERP 库存", "requerySelected": "重查选中",
"receiptDateLabel": "收料日期", "receiptDateLabel": "收料日期",
"receiptDateTo": "收料日期止", "receiptDateTo": "收料日期止",
"receiptDateHint": "截止不超出 D+1 规则(业务日期前一天)", "receiptDateHint": "默认为 D+1 规则日期(业务日期前一天,即可预检截止日);截止不超出该日,起始不得晚于截止",
"requeryRow": "重查", "requeryRow": "重查",
"colToQty": "拨入数量", "colToQty": "拨入数量",
"colResult": "预检结果", "colResult": "预检结果",
@@ -3831,7 +3831,22 @@
"downloadErpInventory": "下载 ERP 库存表", "downloadErpInventory": "下载 ERP 库存表",
"downloadExceptions": "下载异常 Excel", "downloadExceptions": "下载异常 Excel",
"backlogTitle": "待处理异常", "backlogTitle": "待处理异常",
"retryErp": "重新查询 ERP", "resumeAction": "恢复处理",
"colAging": "老化",
"colAction": "操作",
"selectedRows": "已选 {count} 行",
"clearSelection": "取消选择",
"receiptDateInvalid": "起始日期不得晚于截止日期",
"homeRecentTitle": "最近预检",
"recentRemaining": "剩余 {min} 分钟",
"recentPrechecking": "预检中…",
"toastRequeryDone": "重查完成:{ok} 行已更新,{failed} 行失败",
"toastResumeOpened": "已创建 {count} 份预检,已打开第 1 份,其余可在「最近预检」中继续",
"toastResumeRefetching": "来源 {sources} 收料文件不可用,已触发重新抓取,完成后请再次恢复",
"toastResumeSkipped": "{count} 行未能恢复",
"toastResumeStillBlocked": "恢复完成:{count} 行仍阻断(ERP 库存尚未匹配),补录库存后可再次恢复",
"toastCloseDone": "关闭完成:{ok} 行成功,{failed} 行失败",
"batchCloseTitle": "标记无需继续处理({count} 项)",
"manualClose": "标记无需继续处理", "manualClose": "标记无需继续处理",
"manualCloseTitle": "标记无需继续处理", "manualCloseTitle": "标记无需继续处理",
"manualCloseHint": "关闭后自动排程不再处理;历史与审计永久保留。", "manualCloseHint": "关闭后自动排程不再处理;历史与审计永久保留。",
@@ -3867,7 +3882,7 @@
"homeTodayHint": "选择来源实例后,系统默认以昨天为业务日期处理可成熟收料。", "homeTodayHint": "选择来源实例后,系统默认以昨天为业务日期处理可成熟收料。",
"homeHistoryLabel": "历史待办", "homeHistoryLabel": "历史待办",
"homeRecoverable": "可恢复异常", "homeRecoverable": "可恢复异常",
"homeRecoverableHint": "可重新查询 ERP 库存后继续处理", "homeRecoverableHint": "可重查库存或一键恢复处理",
"homeClosed": "已人工关闭", "homeClosed": "已人工关闭",
"homeClosedHint": "可查看原因并恢复处理", "homeClosedHint": "可查看原因并恢复处理",
"homeUnknown": "结果未知", "homeUnknown": "结果未知",
+2 -1
View File
@@ -552,6 +552,7 @@
"TRANSFER.EXTERNAL_QUERY_TIMEOUT": "外部系统查询超时,请重试。", "TRANSFER.EXTERNAL_QUERY_TIMEOUT": "外部系统查询超时,请重试。",
"TRANSFER.PRECHECK_ALREADY_EXECUTED": "该预检已执行,请勿重复提交。", "TRANSFER.PRECHECK_ALREADY_EXECUTED": "该预检已执行,请勿重复提交。",
"TRANSFER.SELECTION_INVALID": "选择范围包含不可执行 Invoice。", "TRANSFER.SELECTION_INVALID": "选择范围包含不可执行 Invoice。",
"TRANSFER.INVALID_STATE_TRANSITION": "非法状态转换。" "TRANSFER.INVALID_STATE_TRANSITION": "非法状态转换。",
"TRANSFER.BATCH_ITEMS_REQUIRED": "请提供要操作的明细行。"
} }
} }
+20 -5
View File
@@ -3715,7 +3715,7 @@
"reasonExternalQueryFailed": "外部系統查詢失敗", "reasonExternalQueryFailed": "外部系統查詢失敗",
"reasonFutureDate": "收料日期晚於業務日期", "reasonFutureDate": "收料日期晚於業務日期",
"selectedCount": "已選 {count} 張", "selectedCount": "已選 {count} 張",
"generateTransfer": "直接產生調撥單", "generateTransfer": "產生調撥單",
"colSource": "收料來源", "colSource": "收料來源",
"colMaterial": "料號", "colMaterial": "料號",
"colName": "品名", "colName": "品名",
@@ -3728,10 +3728,10 @@
"colFromBatch": "撥出批號", "colFromBatch": "撥出批號",
"filterPlaceholder": "按料號 / 品名 / Invoice / 批號篩選", "filterPlaceholder": "按料號 / 品名 / Invoice / 批號篩選",
"filterAll": "全部結果", "filterAll": "全部結果",
"requerySelected": "重查選中 ERP 庫存", "requerySelected": "重查選中",
"receiptDateLabel": "收料日期", "receiptDateLabel": "收料日期",
"receiptDateTo": "收料日期止", "receiptDateTo": "收料日期止",
"receiptDateHint": "截止不超出 D+1 規則(業務日期前一天)", "receiptDateHint": "預設為 D+1 規則日期(業務日期前一天,即可預檢截止日);截止不超出該日,起始不得晚於截止",
"requeryRow": "重查", "requeryRow": "重查",
"colToQty": "撥入數量", "colToQty": "撥入數量",
"colResult": "預檢結果", "colResult": "預檢結果",
@@ -3758,7 +3758,22 @@
"downloadErpInventory": "下載 ERP 庫存表", "downloadErpInventory": "下載 ERP 庫存表",
"downloadExceptions": "下載異常 Excel", "downloadExceptions": "下載異常 Excel",
"backlogTitle": "待處理異常", "backlogTitle": "待處理異常",
"retryErp": "重新查詢 ERP", "resumeAction": "恢復處理",
"colAging": "老化",
"colAction": "操作",
"selectedRows": "已選 {count} 行",
"clearSelection": "取消選擇",
"receiptDateInvalid": "起始日期不得晚於截止日期",
"homeRecentTitle": "最近預檢",
"recentRemaining": "剩餘 {min} 分鐘",
"recentPrechecking": "預檢中…",
"toastRequeryDone": "重查完成:{ok} 行已更新,{failed} 行失敗",
"toastResumeOpened": "已建立 {count} 份預檢,已開啟第 1 份,其餘可在「最近預檢」中繼續",
"toastResumeRefetching": "來源 {sources} 收料檔案不可用,已觸發重新擷取,完成後請再次恢復",
"toastResumeSkipped": "{count} 行未能恢復",
"toastResumeStillBlocked": "恢復完成:{count} 行仍阻斷(ERP 庫存尚未匹配),補錄庫存後可再次恢復",
"toastCloseDone": "關閉完成:{ok} 行成功,{failed} 行失敗",
"batchCloseTitle": "標記無需繼續處理({count} 項)",
"manualClose": "標記無需繼續處理", "manualClose": "標記無需繼續處理",
"manualCloseTitle": "標記無需繼續處理", "manualCloseTitle": "標記無需繼續處理",
"manualCloseHint": "關閉後自動排程不再處理;歷史與稽核永久保留。", "manualCloseHint": "關閉後自動排程不再處理;歷史與稽核永久保留。",
@@ -3794,7 +3809,7 @@
"homeTodayHint": "選擇來源實例後,系統預設以昨天為業務日期處理可成熟收料。", "homeTodayHint": "選擇來源實例後,系統預設以昨天為業務日期處理可成熟收料。",
"homeHistoryLabel": "歷史待辦", "homeHistoryLabel": "歷史待辦",
"homeRecoverable": "可恢復異常", "homeRecoverable": "可恢復異常",
"homeRecoverableHint": "可重新查詢 ERP 庫存後繼續處理", "homeRecoverableHint": "可重查庫存或一鍵恢復處理",
"homeClosed": "已人工關閉", "homeClosed": "已人工關閉",
"homeClosedHint": "可查看原因並恢復處理", "homeClosedHint": "可查看原因並恢復處理",
"homeUnknown": "結果未知", "homeUnknown": "結果未知",
+2 -1
View File
@@ -552,6 +552,7 @@
"TRANSFER.EXTERNAL_QUERY_TIMEOUT": "外部系統查詢逾時,請重試。", "TRANSFER.EXTERNAL_QUERY_TIMEOUT": "外部系統查詢逾時,請重試。",
"TRANSFER.PRECHECK_ALREADY_EXECUTED": "該預檢已執行,請勿重複提交。", "TRANSFER.PRECHECK_ALREADY_EXECUTED": "該預檢已執行,請勿重複提交。",
"TRANSFER.SELECTION_INVALID": "選擇範圍包含不可執行 Invoice。", "TRANSFER.SELECTION_INVALID": "選擇範圍包含不可執行 Invoice。",
"TRANSFER.INVALID_STATE_TRANSITION": "非法狀態轉換。" "TRANSFER.INVALID_STATE_TRANSITION": "非法狀態轉換。",
"TRANSFER.BATCH_ITEMS_REQUIRED": "請提供要操作的明細行。"
} }
} }