feat(in-transit-transfer): 实现匹配静默顶替并完善单号与明细表体验

This commit is contained in:
hugo committed 2026-10-27 16:35:56 +08:00
1 parent f5611d6783
commit 79050d02ba
25 files changed
+806 -178

No files matched your search

@@ -1478,6 +1478,7 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
'item_id': item.item_id,
'source_code': item.source_code,
'invoice_no': item.invoice_no,
'external_doc_no': item.external_doc_no,
'material_no': item.material_no,
'status': item.status,
'reason': item.reason,
@@ -36,6 +36,7 @@ from app.models import TransferAttempt, TransferInvoiceItem, TransferMovementLed
from app.services.in_transit_transfer.matching_service import (
circle_ledger_record_ids_scope_union,
pending_ledger_query,
ledger_external_doc_no,
transfer_type_code_of,
)
from app.services.in_transit_transfer.status import TransferStatus
@@ -100,6 +101,8 @@ class BacklogItemDTO:
result_code: Optional[str] = None
# 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。
transfer_type: str = ""
# 档上的外部单号。空串表示这行没有外部单号。
external_doc_no: str = ""
@dataclass(frozen=True)
@@ -207,7 +210,7 @@ def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None):
"""待处理池基础查询(状态集合 + 可选来源/关键字过滤)。
keyword 与前端池内筛选同字段集(Invoice/料号/品名/来源,2026-10-16 随
keyword 与前端池内筛选同字段集(单号/外部单号/料号/品名/来源,2026-10-16 随
服务端分页下推),大小写不敏感子串匹配(ilike)。
Args:
@@ -222,12 +225,19 @@ def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: st
query = query.filter_by(source_code=source_code)
if keyword:
like = f"%{keyword}%"
query = query.filter(or_(
TransferInvoiceItem.invoice_no.ilike(like),
TransferInvoiceItem.material_no.ilike(like),
TransferInvoiceItem.material_name.ilike(like),
TransferInvoiceItem.source_code.ilike(like),
))
query = (
query.outerjoin(
TransferMovementLedger,
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
)
.filter(or_(
TransferInvoiceItem.invoice_no.ilike(like),
TransferMovementLedger.external_doc_no.ilike(like),
TransferInvoiceItem.material_no.ilike(like),
TransferInvoiceItem.material_name.ilike(like),
TransferInvoiceItem.source_code.ilike(like),
))
)
return query
@@ -266,6 +276,7 @@ def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[Ba
item_id=item.id,
source_code=item.source_code,
invoice_no=item.invoice_no,
external_doc_no=ledger_external_doc_no(item),
material_no=item.material_no,
status=item.status,
reason=item.result_message or item.result_code or "",
@@ -303,7 +314,10 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
current = now or datetime.utcnow()
rows = (
_backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code)
.options(joinedload(TransferInvoiceItem.matching))
.options(
joinedload(TransferInvoiceItem.matching),
joinedload(TransferInvoiceItem.ledger_record),
)
.order_by(*_BACKLOG_ORDER_BY)
.all()
)
@@ -330,7 +344,7 @@ def list_backlog_page(
Args:
now: 判定时刻(默认当前时间)。
source_code: 可选来源过滤。
keyword: 可选关键字(Invoice/料号/品名/来源,子串大小写不敏感)。
keyword: 可选关键字(单号/外部单号/料号/品名/来源,子串大小写不敏感)。
result_filter: 结果切片(all/recoverable/closed/unknown)。
page: 页码(1 起)。
page_size: 每页行数(1..100)。
@@ -345,7 +359,10 @@ def list_backlog_page(
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
total = base.count()
rows = (
base.options(joinedload(TransferInvoiceItem.matching))
base.options(
joinedload(TransferInvoiceItem.matching),
joinedload(TransferInvoiceItem.ledger_record),
)
.order_by(*_BACKLOG_ORDER_BY)
.offset((page - 1) * page_size)
.limit(page_size)
@@ -124,6 +124,8 @@ class MatchingItemDTO:
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
# 无匹配或快照未写类型时为空串。
transfer_type: str = ""
# 档上的外部单号(WMS Order #)。空串表示这行没有外部单号。
external_doc_no: str = ""
@dataclass(frozen=True)
@@ -63,6 +63,7 @@ from app.services.in_transit_transfer.matching_service import (
RouteMapping,
TransferDeps,
item_external_lot_no,
ledger_external_doc_no,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.orchestrator import (
@@ -805,12 +806,12 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
ERP 行粒度 = 物料+批号:同单同料号同批号跨 Invoice 聚合为一行,数量按
Decimal 精确相加后取 6 位小数;客户端行数量为数值型(能力 Schema number,
且须可 JSON 序列化进引擎审计),快照文本(6 位小数字符串)随 D14 留档。
行内附带 invoice_no 溯源(逗号连接,供测试替身/排障;ERP 契约无此字段,
真实绑定未映射即透传为惰性键)。
行内附带 invoice_no 与 external_doc_no 溯源(各自逗号连接,供清单展示与排障;
ERP 契约无这两字段,真实绑定未映射即透传为惰性键)。
Returns:
行 dict 列表:line_no/material_no/from_warehouse/to_warehouse/lot_no/
quantity/unit/invoice_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
quantity/unit/invoice_no/external_doc_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
"""
grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {}
for item in items:
@@ -831,6 +832,9 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
quantity = total.quantize(_QUANTITY_QUANT)
unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "")
invoices = ",".join(sorted({item.invoice_no for item in group}))
external_docs = ",".join(sorted({
doc for item in group if (doc := ledger_external_doc_no(item))
}))
lines.append({
"line_no": index,
"material_no": key[0],
@@ -840,6 +844,7 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
"quantity": float(quantity),
"unit": unit,
"invoice_no": invoices,
"external_doc_no": external_docs,
"quantity_text": f"{quantity:.6f}",
})
return lines
@@ -1273,6 +1278,7 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
external_doc_no=ledger_external_doc_no(item),
movement_date=item.movement_date,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
@@ -18,7 +18,7 @@
movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+
未被有效 items 占用(D17:ledger_record_id 引用或同匹配 grain
(source, invoice/doc_no, material, movement_date) 已被有效 item 占用;
取消匹配即释放)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
取消匹配即释放;ADR 0007 匹配顶替在圈档前取消被新范围盖住、尚未写 ERP 的旧匹配)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
空→有值的重解析双行);出生前按 grain 择一建 item(不累加数量,防翻倍),
占用亦按 grain 互斥。业务字段=档原值;仓库经 resolve_warehouse;库存评估
链以 items 为工作单元。create_matching 先落 Run + Matching 再驱动管道。
@@ -295,11 +295,12 @@ def _dedupe_ledger_records_for_item_birth(
def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
"""构造「未被有效 items 占用」(D17)的 NOT EXISTS 过滤(圈档互斥单一口径)。
占用定义(规格 §9 + grain 互斥):存在有效 item(所属匹配未取消、行非
blocked_file_removed)且满足其一——(a) ledger_record_id 直指本档;
(b) 与本档同匹配 grain(source/invoice=doc_no/material/movement_date)。
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档,避免待匹配桶与二次
匹配仍圈到兄弟档。取消匹配即释放;人工关闭/成功终态不释放。
占用定义(规格 §9 + grain 互斥 + ADR 0007):存在已挂上匹配的有效 item
(所属匹配未取消,或该行是人工关闭;行非 blocked_file_removed)且满足其一
——(a) ledger_record_id 直指本档;(b) 与本档同匹配 grain
(source/invoice=doc_no/material/movement_date)。没有挂上匹配的明细不占用。
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档。取消匹配即释放,
人工关闭除外;成功终态不释放。
Args:
exclude_matching_id: 重查对账场景传入本匹配 id——本匹配自有 items 不构成
@@ -308,9 +309,8 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
SQLAlchemy NOT EXISTS 子句(作用于 TransferMovementLedger 查询)。
"""
# material_code 可空:COALESCE 与出生侧 ``material_code or ""`` 对齐。
# grain 互斥只认「已绑定未取消匹配」的行——出生翻转前 matching_id=NULL 的
# 历史孤儿行不得按 grain 封死整票待匹配(本地曾因此从 ~2k 掉到 5)。
# ledger_record_id 直指占用仍含 NULL 归属行(保持 D17 原口径)。
# 【ADR 0007】没有挂上匹配的明细不占货(直指与 grain 都不算)。
# 人工关闭在所属匹配被顶替之后仍然占用。
grain_match = and_(
TransferInvoiceItem.matching_id.isnot(None),
TransferInvoiceItem.source_code == TransferMovementLedger.source_code,
@@ -328,17 +328,21 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
]
if exclude_matching_id is None:
# 匹配创建:任何未取消匹配(含无归属的历史行)的有效引用都算占用。
# 匹配创建:必须已挂上匹配。未取消的匹配占用;人工关闭在匹配被顶替后仍占用。
item_conditions.append(TransferInvoiceItem.matching_id.isnot(None))
item_conditions.append(or_(
TransferInvoiceItem.matching_id.is_(None),
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
))
else:
# 重查对账:仅「其他匹配」的有效引用算占用(本匹配自有 items 允许刷新)。
item_conditions.append(and_(
TransferInvoiceItem.matching_id.isnot(None),
TransferInvoiceItem.matching_id != exclude_matching_id,
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
or_(
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
),
))
occupancy = (
db.session.query(TransferInvoiceItem.id)
@@ -611,6 +615,23 @@ def matching_transform_rules(matching: TransferMatching) -> tuple[TransformRule,
return parse_transform_rules(scope.get("transform_rules"))
def ledger_external_doc_no(item: TransferInvoiceItem) -> str:
"""读取明细行对应异动档上的外部单号。
核心逻辑:外部单号只在档上(WMS Order #),明细行经 ledger_record_id 指向档。
没有档、或档上为空时返回空串,列表显示占位。
Args:
item: 明细行。ledger_record 可已预加载;未预加载时按外键懒加载。
Returns:
外部单号;没有则空串。
"""
record = item.ledger_record
if record is None:
return ""
return str(record.external_doc_no or "").strip()
def item_external_lot_no(item: TransferInvoiceItem) -> str:
"""行批号的外部形态派生(按行所属匹配快照的转换规则;无规则=恒等)。
@@ -1242,6 +1263,116 @@ def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
return lines[0].get("file_sha256")
def _source_set(codes: list[str] | None) -> tuple[str, ...]:
"""把来源编码收成可比较的集合。
核心逻辑:去掉空白后排序,使 [B, A] 与 [A, B] 视为同一组来源。
Args:
codes: 来源编码列表;None 当空。
Returns:
排序后的来源编码元组。
"""
return tuple(sorted(str(code).strip() for code in (codes or []) if str(code).strip()))
def _date_range_covers(new_from: str | None, new_to: str | None, old_from: str | None, old_to: str | None) -> bool:
"""新异动日期范围是否把旧范围整个盖住。
核心逻辑:任一侧缺少起或止,都视为没盖住(无日期范围的旧匹配不被顶替)。
日期是 YYYY-MM-DD,字符串序与日历序一致。
Args:
new_from / new_to: 本次匹配的异动日期起止。
old_from / old_to: 旧匹配快照上的异动日期起止。
Returns:
新范围包含旧范围时为 True。
"""
if not new_from or not new_to or not old_from or not old_to:
return False
return str(new_from) <= str(old_from) and str(new_to) >= str(old_to)
def _matching_has_erp_activity(items: list[TransferInvoiceItem]) -> bool:
"""匹配是否已经写出单据,或有行正在写、结果未知。
核心逻辑:有外部单号,或行状态为执行中、结果未知、成功,就不顶替,
避免把在途 ERP 写入拆成两张单。
Args:
items: 该匹配名下的明细。
Returns:
存在上述活动时为 True。
"""
active = {
status_machine.TransferStatus.EXECUTING.value,
status_machine.TransferStatus.RESULT_UNKNOWN.value,
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
}
return any(
(item.external_document_no or "").strip() or item.status in active
for item in items
)
def _supersede_covered_matchings(
*,
transfer_type: str,
source_codes: list[str],
movement_date_from: str | None,
movement_date_to: str | None,
exclude_matching_id: int,
) -> None:
"""圈档前顶替被新范围盖住、尚未写 ERP 的旧匹配(ADR 0007)。
核心逻辑:同一调拨类型、同一组来源、旧日期范围被新范围整个盖住,且名下没有
ERP 单据、没有正在写或结果未知的行,则匹配改为 cancelled,名下明细一并取消。
盖不住或已在写 ERP 的旧匹配保持原样,清单不列举它们的编号。
Args:
transfer_type: 本次匹配的调拨类型编码。
source_codes: 本次来源集合。
movement_date_from / movement_date_to: 本次异动日期范围;缺一则不顶替任何人。
exclude_matching_id: 刚落库、尚未圈档的本次匹配,不能把自己顶掉。
"""
new_sources = _source_set(source_codes)
if not new_sources:
return
candidates = (
TransferMatching.query
.filter(TransferMatching.id != exclude_matching_id)
.filter(TransferMatching.status != _MATCHING_STATUS_CANCELLED)
.all()
)
for matching in candidates:
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
if str(scope.get("transfer_type") or "") != transfer_type:
continue
if _source_set(scope.get("source_codes")) != new_sources:
continue
items = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
covered = _date_range_covers(
movement_date_from,
movement_date_to,
scope.get("movement_date_from"),
scope.get("movement_date_to"),
)
# 匹配状态 success 只表示没有可执行行(全阻断也会落成 success),
# 不能当成已经写出 ERP。是否写过只看行上的单据号和执行状态。
if (
not covered
or matching.status == status_machine.TransferStatus.EXECUTING.value
or _matching_has_erp_activity(items)
):
continue
matching.status = _MATCHING_STATUS_CANCELLED
for item in items:
# 人工关闭是仓库人员的裁定,顶替不把它改回可圈状态。
if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value:
continue
item.status = status_machine.TransferStatus.CANCELLED.value
item.result_code = "cancelled"
item.result_message = "superseded by a new matching"
def create_matching(
*,
source_codes: list[str],
@@ -1259,6 +1390,7 @@ def create_matching(
管道回写 status/counts/estimated/hash 后随主事务统一提交。类型必填且配置
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。圈档记录类型由
run_matching 对已加载的 scope_rules 调用 record_kinds_of,不再写死入站。
【ADR 0007】圈档前顶替被本次日期范围盖住、尚未写 ERP 的同类型同来源旧匹配。
Args:
source_codes / business_date / deps: 同 run_matching。
@@ -1299,6 +1431,14 @@ def create_matching(
)
db.session.add(matching)
db.session.flush()
# [ADR 0007] 先释放被盖住的旧匹配,本次圈档才能看到那批货。
_supersede_covered_matchings(
transfer_type=config.code,
source_codes=list(source_codes),
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
exclude_matching_id=matching.id,
)
result = run_matching(
source_codes=source_codes,
@@ -1404,6 +1544,7 @@ def restore_matching(
# 同口径(2026-09-29 统一),同一批行在匹配卡/可调拨明细/待处理池顺序一致。
rows_all = (
TransferInvoiceItem.query
.options(joinedload(TransferInvoiceItem.ledger_record))
.filter(TransferInvoiceItem.matching_id == matching.id)
.order_by(
TransferInvoiceItem.movement_date.asc().nulls_last(),
@@ -1531,6 +1672,7 @@ def _item_dto(
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
external_doc_no=ledger_external_doc_no(item),
movement_date=item.movement_date,
lot_no=item.lot_no or "",
movement_warehouse_code=item.movement_warehouse_code or "",
@@ -1600,7 +1742,10 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
rows = (
TransferInvoiceItem.query
.options(joinedload(TransferInvoiceItem.matching))
.options(
joinedload(TransferInvoiceItem.matching),
joinedload(TransferInvoiceItem.ledger_record),
)
# [防御性双保险] 所属匹配已取消的行不入队:取消路径已把匹配名下 ready
# 行退役为 cancelled(cancellation.py),此处按匹配状态再拒一次——
# 防绕过取消路径的状态组合(如手工改库/历史数据)产生可执行行。
@@ -12,7 +12,10 @@ from __future__ import annotations
from typing import Any
from app.services.in_transit_transfer.matching_service import item_external_lot_no
from app.services.in_transit_transfer.matching_service import (
item_external_lot_no,
ledger_external_doc_no,
)
# ---------------------------------------------------------------------------
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
@@ -71,6 +74,7 @@ def serialize_item(item) -> dict[str, Any]:
"material_name": item.material_name,
"specification": item.specification,
"invoice_no": item.invoice_no,
"external_doc_no": getattr(item, "external_doc_no", "") or "",
"lot_no": item.lot_no,
"movement_date": item.movement_date,
"from_warehouse": item.from_warehouse,
@@ -177,6 +181,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
# 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
"invoice_no": line["invoice_no"],
"external_doc_no": line.get("external_doc_no") or "",
"material_no": line["material_no"],
"material_name": name_by_key.get(
(line["material_no"], line["lot_no"],
@@ -222,6 +227,7 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
"items": [
{
"invoice_no": item.invoice_no,
"external_doc_no": ledger_external_doc_no(item),
"material_no": item.material_no,
"material_name": item.material_name,
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
@@ -1,7 +1,7 @@
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
匹配快照 Hash 稳定、缺文件等待与进度恢复、匹配顶替;专项用例锁生产默认 lag=2。
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行,
@@ -1152,3 +1152,182 @@ def test_cancel_matching_releases_ledger_occupancy(transfer_db, dbs_ready_file):
born = TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
assert len(born) == 2
assert all(row.status == "ready_to_execute" for row in born)
def test_create_matching_supersedes_covered_unwritten_matching(transfer_db, dbs_ready_file):
"""新匹配盖住同一类型、同一来源、尚未写 ERP 的旧匹配时,旧匹配取消,货出现在新匹配上。
夹具两行异动日都是 2026-08-04。第一次与第二次都用 08-01~08-04,新范围盖住旧范围。
"""
from app.models import TransferInvoiceItem, TransferMatching
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
covered = dict(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
first = create_matching(deps=deps, **covered)
# [断言意图] 顶替前旧匹配自己先圈到夹具的两张单,证明后面的 2 不是「本来就没占上」。
assert first.counts.executable_count == 2
second = create_matching(deps=deps, **covered)
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
# [断言意图] 被盖住且未写 ERP 的旧匹配不再有效,其可执行行不能留在队列里二次写 ERP。
assert first_matching.status == "cancelled"
retired = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id).all()
assert retired
assert all(row.status == "cancelled" for row in retired)
# [断言意图] 同一批货(HOM-001、HOX-002)出现在新匹配上,且仍可执行。
assert second.counts.executable_count == 2
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
reborn = {
row.invoice_no
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
}
assert reborn == {"HOM-001", "HOX-002"}
def test_create_matching_supersedes_covered_matching_with_only_blocked_rows(transfer_db, dbs_ready_file):
"""全阻断的旧匹配状态虽是 success,只要还没写 ERP,新范围盖住时仍要顶替。"""
from app.models import TransferInvoiceItem, TransferMatching
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
covered = dict(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
first = create_matching(deps=deps, **covered)
# [断言意图] 数量对不上时匹配状态是 success,不能因此被当成「已经写出单据」。
assert first.status == "success"
assert first.counts.executable_count == 0
second = create_matching(deps=deps, **covered)
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
assert first_matching.status == "cancelled"
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
reborn = {
row.invoice_no
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
}
assert reborn == {"HOM-001", "HOX-002"}
def test_create_matching_keeps_previous_when_new_range_does_not_cover(transfer_db, dbs_ready_file):
"""新范围盖不住旧范围时,旧匹配保持有效,货仍留在旧匹配上。"""
from app.models import TransferMatching
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
first = create_matching(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
deps=deps,
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
second = create_matching(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
deps=deps,
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-04",
movement_date_to="2026-08-04",
)
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
# [断言意图] 08-04~08-04 盖不住 08-01~08-04,旧匹配不能被取消。
assert first_matching.status == "ready_to_execute"
# [断言意图] 货仍被旧匹配占用,新匹配圈不到,清单不另列历史匹配编号。
assert second.counts.executable_count == 0
def test_supersede_keeps_manually_closed_goods_out_of_the_new_matching(transfer_db, dbs_ready_file):
"""顶替后,人工关闭的单号不回到新匹配。"""
from app.models import TransferInvoiceItem, TransferMatching
from app.services.in_transit_transfer.manual_close_service import manual_close_item
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
covered = dict(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
first = create_matching(deps=deps, **covered)
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
closed = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id, invoice_no="HOX-002").one()
manual_close_item(item_id=closed.id, reason="这批不再调拨")
second = create_matching(deps=deps, **covered)
# [断言意图] 人工关闭跨过顶替仍然有效,新匹配不能把 HOX-002 再圈成可执行。
assert db.session.get(TransferInvoiceItem, closed.id).status == "manually_closed"
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
reborn = {
row.invoice_no
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
}
assert reborn == {"HOM-001"}
def test_unattached_item_does_not_block_a_new_matching(transfer_db, dbs_ready_file):
"""没有挂上任何匹配的明细不占货,新匹配仍能圈到那张单。"""
from app.models import TransferInvoiceItem, TransferMatching, TransferMovementLedger
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
ledger = TransferMovementLedger.query.filter_by(source_code="DBS-AWSBI", doc_no="HOM-001").first()
db.session.add(TransferInvoiceItem(
matching_id=None,
ledger_record_id=ledger.id,
source_code="DBS-AWSBI",
invoice_no="HOM-001",
material_no="MAT-001",
movement_date="2026-08-04",
from_warehouse="DBS-TRANSIT",
to_warehouse="HUB-CN01",
movement_quantity="1200",
status="matching",
result_code="pending_stock_check",
))
db.session.commit()
summary = create_matching(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
deps=deps,
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
# [断言意图] 悬挂行没有匹配编号,不能挡住 HOM-001;两张夹具单都进新匹配。
invoices = {
row.invoice_no
for row in TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
}
assert invoices == {"HOM-001", "HOX-002"}
+18
View File
@@ -0,0 +1,18 @@
# 新匹配顶替尚未写 ERP 的旧匹配
状态:accepted。
2026-10-27 决定:提交一次新匹配时,取消所有被它盖住、且还没有任何 ERP 单据的旧匹配,再按新的日期范围重新圈档。同一批货不能同时留在两张未取消的匹配上,否则可执行行会各写一次 ERP。画面上不再为这件事单加取消按钮。
顶替只发生在同一调拨类型、同一组来源,且新的日期范围把旧范围整个盖住的时候。旧匹配没有日期范围、正在写 ERP、结果未知,或已经写出单据,都保持有效,货留在原匹配里。清单不列举这些匹配的编号。人工关闭的货不回到新匹配。没有挂上任何匹配的明细不占货。
## Considered Options
- **只加取消按钮**:被否——仓库人员的下一步就是再匹配一次,按钮多一次确认,不解决「提交新匹配时期望直接看到货」。
- **允许重复匹配**:被否——两张未取消的匹配会把同一批可执行货各写一次 ERP。
## Consequences
- 圈档仍互斥。顶替是取消的自动出口,不是第二套占用规则。
- 日期没盖住或已经在写 ERP 时,这些货留在原匹配里。新清单只显示这次圈出来的行。
- 人工关闭跨过顶替继续有效。未归属匹配的明细不再挡住圈档。
+11 -3
View File
@@ -56,7 +56,7 @@ _Avoid_: 仓库映射(专指映射档本身)
### 在途调拨 · 平台侧概念
**匹配明细 (Matching Item)**:
一次匹配从异动档圈定并永久绑定的执行明细行,承载库存核对结果、执行状态与 ERP 单据关联;自创建起归属唯一匹配。
一次匹配从异动档圈定并永久绑定的执行明细行,承载库存核对结果、执行状态与 ERP 单据关联;自创建起归属唯一匹配。尚未归属任何匹配的行不占货。
_Avoid_: 待办行、入站明细
**记录类型 (Record Kind)**:
@@ -80,8 +80,16 @@ _Avoid_: 来源状态、部分就绪
_Avoid_: 把已人工关闭的记录重新打开
**人工关闭 (Manual Close)**:
仓库人员判定某条明细不再继续调拨,并留下原因之后的状态。该状态只保留原因供查看。
_Avoid_: 删除、恢复处理
仓库人员判定某条明细不再继续调拨,并留下原因之后的状态。该状态只保留原因供查看。匹配顶替不把这些货放回新匹配。
_Avoid_: 删除、恢复处理、匹配顶替
**占用 (Occupancy)**:
一批货已被某次仍有效的匹配圈住,因而不能再进一次新匹配。人工关闭的货也算占用。没有挂上任何匹配的明细不构成占用。
_Avoid_: 锁定、文件占用
**匹配顶替 (Matching Supersede)**:
新匹配成立时对既有匹配的取代:同一调拨类型、同一组来源、日期范围被新范围完全盖住、且还没有任何 ERP 单据的旧匹配全部不再有效,其中的货按新匹配重新圈定。盖不住、正在写 ERP、或结果未知的旧匹配保持有效。
_Avoid_: 重复匹配、再匹配一次
**结果未知 (Result Unknown)**:
一次调拨写入之后,ERP 是否已经生成单据仍不能确定的状态。
@@ -386,7 +386,7 @@ cd backend && flask db upgrade
### 11.6 items 出生翻转与 D17 圈档互斥(迁移 `tt12c3d4e5f6a7`)
- **出生翻转(ADR 0001)**:`transfer_invoice_items` 退化为纯匹配执行记录——匹配创建时从档按类型范围规则圈定生成(`matching_id`/`ledger_record_id` 出生即绑定,业务字段取档原值、路由解析落 from/to);证据落地只写档不写行;重查 `requery_items` 弃 items SQL 圈行(`scope_item_query` 退役),改**对档对账**(同一编译器、同一快照规则):档有行无→补建、档证据变→刷新证据并重置待查、档记录被新版本替换→items 失效隔离(`blocked_file_removed` 语义)。
- **D17 圈档互斥**:一条档记录一生只生成一次 items 绑定——匹配创建圈档排除「已被有效 items 占用」的档记录(存在所属匹配未取消、行未被失效隔离的 item 引用即占用)。取消匹配(items→cancelled)释放占用,记录可被后续匹配重圈;人工关闭/成功终态不释放(前者=业务裁定不拨,后者=档级封存)。重查只对账本匹配自有 items,不受此规则影响。取消按 `matching_id` 圈定名下 ready 未建单行退役(出生行 `run_id=None`,按 run_id 圈行恒不命中)。
- **D17 圈档互斥**:一条档记录一生只生成一次 items 绑定——匹配创建圈档排除「已被有效 items 占用」的档记录(存在所属匹配未取消、行未被失效隔离的 item 引用即占用)。取消匹配(items→cancelled)释放占用,记录可被后续匹配重圈;人工关闭/成功终态不释放(前者=业务裁定不拨,后者=档级封存)。【ADR 0007】提交新匹配时,同一调拨类型、同一组来源、日期范围被新范围整个盖住、且还没有任何 ERP 单据的旧匹配自动取消后再圈档;盖不住或已在写 ERP 的旧匹配保持有效,货留在原匹配里,清单不列举编号。没有挂上匹配的明细不占用。重查只对账本匹配自有 items,不受此规则影响。取消按 `matching_id` 圈定名下 ready 未建单行退役(出生行 `run_id=None`,按 run_id 圈行恒不命中)。
### 11.7 首页待办看板「待匹配」桶(D16)
+1 -1
View File
@@ -819,7 +819,7 @@
| 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行提交执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按票聚合结果(写路径已接线,见下行「ERP 建单写路径」) |
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 入站文件与 09:00 自动调拨(现注册表单列 `in-transit-transfer` platform job,缺当日入站文件自动触发收料 RPA);任务参数=来源实例/历史可恢复异常复核/可选异动日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部成熟积压;非法偏移快速失败,偏移终点落在 T−1/当天或更晚由匹配层卡控截止≤T−2);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) |
| 调拨类型配置化(2026-10-14) | 已实现 | 类型来自平台配置表 `transfer_type_configs`(ADR 0002,代码枚举/CHECK 约束/前端 union/「即将上线」占位全退役):管理端「在途调拨类型」页四块配置(基本信息/范围规则/仓库定义/字段转换),admin CRUD API + chat enabled 最小暴露 API;`transfer_type` 匹配创建必填(未配置/停用 fail-closed),配置为空前端空态;范围规则引擎(18 字段白名单、规则间 AND 值间 OR、内存谓词+SQL 编译双形态)、仓库定义(mapped/fixed+法人覆盖)、字段转换(批号前缀替换,六个系统边界生效,行/档保原值);规则随匹配快照进 scope_json;管理页见 `features/admin/modules/transfer-types/`,运维手册 technical.md §11 |
| 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放);2026-10-21 外部单据身份扩维:自然键 8→10 成分(+外部单号/外部项次=WMS Order #/行号,迁移 tt21c8d9e0f1a2)作档幂等主键管控,movement 契约字段目录扩至 20 字段(解析 Profile 可映射),解析层料号空行静默跳过(不管控、不进异动表) |
| 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放;ADR 0007:新匹配自动顶替同一类型、同一来源、日期被盖住且尚未写 ERP 的旧匹配,人工关闭仍排除,未挂匹配的明细不占用,清单不列举历史匹配编号);2026-10-21 外部单据身份扩维:自然键 8→10 成分(+外部单号/外部项次=WMS Order #/行号,迁移 tt21c8d9e0f1a2)作档幂等主键管控,movement 契约字段目录扩至 20 字段(解析 Profile 可映射),解析层料号空行静默跳过(不管控、不进异动表) |
| 入站/出站统一改版与幂等修复(2026-10-15) | 已实现 | record_kind 枚举值改版 inbound/outbound(迁移 tt14 值迁移);明细/单据列异动口径 `movement_*`(异动日期/数量/仓库列与匹配创建参数 `movement_date_from/to`、序列化键、Excel 表头随行更名,无兼容层);异动档自然键扩为 8 成分(+箱号/批号,三份真实 WMS 文件实测塌缩归零)+「异动日期非空才落档」过滤(`date_skipped`,未完成/已取消行不入档);解析规则 purpose 三枚举 onhand/inbound/outbound(迁移 tt15 值迁移);入站配置绑定校验 inbound 专用(`SHIPPING.INBOUND_PROFILE_INVALID`),出站绑定 `SHIPPING.OUTBOUND_PROFILE_INVALID`(2026-10-19 出站全栈);解析规则退役守卫补查入站/出站配置绑定;API 路由 `/sources/inbound-files`、`/runs/{run_no}/inbound-files` 与错误码/审计事件 inbound 化;出站 RPA 与调拨 sink 见 [superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md](superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md);2026-10-15 设计见 [superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md](superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md),运维手册 technical.md §12 |
| 待匹配桶清空并重新解析(2026-10-15) | 已下线(2026-10-22) | 原入口会重放该来源保留期内全部归档,一次执行可把历史行整批灌进待匹配。界面与 `GET/POST /backlog/pending-match/reparse*` 已移除。重解析只保留来源卡「重新解析」(当天最新一份,不删行)。 |
| 首页待匹配桶与 file_current 改锚(2026-10-14) | 已实现 | 待办看板新增「待匹配」桶(已落档但从未匹配的外部记录只读可见+去匹配引导,不可勾选执行),四队列卡数据源改档+最近执行状态联查;file_current 门禁改锚档记录 file_version(==来源最新可用文件 sha 即当前) |
@@ -320,7 +320,7 @@ function resultLabelKey(item: TransferBacklogItem): string {
</div>
</div>
<!-- EP 表格壳:数据=服务端返回的当前页切片;横向滚动由 el-table 内建(列 min-width 撑开) -->
<!-- EP 表格:show-overflow-tooltip;左固定勾选,右固定结果+操作;单号/老化可滚 -->
<el-table
v-if="items.length"
:data="items"
@@ -330,7 +330,7 @@ function resultLabelKey(item: TransferBacklogItem): string {
class="text-xs"
data-testid="transfer-backlog-table"
>
<el-table-column width="48" class-name="whitespace-nowrap">
<el-table-column fixed width="48">
<template #header>
<el-checkbox
size="small"
@@ -349,40 +349,61 @@ function resultLabelKey(item: TransferBacklogItem): string {
/>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="110" class-name="whitespace-nowrap" />
<el-table-column :label="$t('chat.transfer.transferTypeLabel')" min-width="140" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="120" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.transferTypeLabel')" min-width="140" show-overflow-tooltip>
<template #default="{ row }">
<span :data-testid="`transfer-backlog-type-${row.invoice_no}`">{{ typeLabel(row.transfer_type) }}</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colInvoice')" prop="invoice_no" min-width="130" class-name="whitespace-nowrap">
<el-table-column
:label="$t('chat.transfer.transferPendingMatchColDocNo')"
prop="invoice_no"
min-width="130"
show-overflow-tooltip
>
<template #default="{ row }">
<span class="font-semibold">{{ row.invoice_no }}</span>
<span class="font-semibold">{{ row.invoice_no || '—' }}</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="100" class-name="whitespace-nowrap">
<el-table-column
:label="$t('chat.transfer.transferPendingMatchColExternalDoc')"
min-width="130"
show-overflow-tooltip
>
<template #default="{ row }">
<span data-testid="transfer-backlog-external-doc">{{ row.external_doc_no || '—' }}</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.movement_date || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" class-name="whitespace-nowrap" />
<el-table-column :label="$t('chat.transfer.colName')" min-width="140">
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="140" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="160" show-overflow-tooltip>
<template #default="{ row }">{{ row.material_name || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" min-width="110" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.from_warehouse || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="110" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="120" show-overflow-tooltip>
<template #default="{ row }">{{ deriveBatchNo(row.lot_no ?? '') || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="90" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="90" show-overflow-tooltip>
<template #default="{ row }">{{ formatQuantity(row.external_quantity) }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colToWarehouse')" min-width="110" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colToWarehouse')" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.to_warehouse || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" show-overflow-tooltip>
<template #default="{ row }">{{ formatQuantity(row.movement_quantity) }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colResult')" min-width="110">
<el-table-column :label="$t('chat.transfer.colAging')" min-width="90" show-overflow-tooltip>
<template #default="{ row }">{{ $t(agingLabel(row.aging_level)) }}</template>
</el-table-column>
<el-table-column
fixed="right"
:label="$t('chat.transfer.colResult')"
width="100"
>
<template #default="{ row }">
<el-tag
size="small"
@@ -395,10 +416,11 @@ function resultLabelKey(item: TransferBacklogItem): string {
</el-tag>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colAging')" min-width="90" class-name="whitespace-nowrap">
<template #default="{ row }">{{ $t(agingLabel(row.aging_level)) }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colAction')" min-width="150" class-name="whitespace-nowrap">
<el-table-column
fixed="right"
:label="$t('chat.transfer.colAction')"
width="150"
>
<template #default="{ row }">
<template v-if="isActionable(row as TransferBacklogItem)">
<!-- 失效行(文件已移除)只留关闭:重查会被后端拒绝(TRANSFER.RETRY_NOT_ALLOWED)。 -->
@@ -2,20 +2,18 @@
features/chat/components/messages/TransferExecutableCard.vue
用途:可调拨明细卡——全局可执行行队列(跨匹配范围):勾选明细行后按行生成调拨单。
依赖:Element Plus ElTable/ElTableColumn/ElInput/ElButton/ElTag/ElPagination/
ElCheckbox(2026-10-20:勾选列一并 EP;testid 挂 el-checkbox,规格经内层
input 读写)、props.items、i18n chat.transfer.*、transferBatch.deriveBatchNo。
逻辑:行由后端按业务稳定键排序(异动日期→Invoice→创建时间);勾选为卡片本地态;
stale/file_current 行置灰提示(执行门禁在后端,失败经 BusinessError 展示);
无 item_id 的历史回放行禁选。
客户端分页(2026-10-16):集合天然有界(仅当日成熟可执行行)但为防增长后
DOM 失控,50/页切片渲染;关键字筛选变更回第 1 页,勾选集合跨页保留。
行定位:el-table 经 row-class-name 注入 transfer-executable-<invoice_no>。
调拨类型列取行上 transfer_type,按启用类型配置显示当前语言名称。
ElCheckbox/ElAlert、props.items、i18n chat.transfer.*、transferBatch /
transferItemTable(明细表密度约定)。
逻辑:行由后端按业务稳定键排序;勾选本地态;无 item_id 历史行禁选;50/页分页。
表格遵循 transferItemTable:show-overflow-tooltip、左固定勾选、右固定结果+操作、
单号可滚、库存数量与查询时刻同行、过期用顶栏 el-alert 汇总批量重查。
行定位:row-class-name 注入 transfer-executable-<invoice_no>。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import {
ElAlert,
ElButton,
ElCheckbox,
ElInput,
@@ -27,8 +25,11 @@ import {
import type { CheckboxValueType } from 'element-plus';
import { deriveBatchNo } from './transferBatch';
import { formatQuantity } from './transferFormat';
import {
formatStockQuantityCell,
freshnessHint,
} from './transferItemTable';
import { transferTypeDisplay } from './transferTypeLabel';
import { parseApiUtcDate } from '@/shared/utils/dateTime';
import type { TransferMatchingItem, TransferTypeOption } from '../../types/transfer.types';
const props = withDefaults(defineProps<{
@@ -40,7 +41,7 @@ const props = withDefaults(defineProps<{
transferTypes: () => [],
});
const { locale } = useI18n();
const { locale, t } = useI18n();
/**
* 把可执行行的调拨类型 code 显示成名称。
@@ -70,7 +71,7 @@ const filtered = computed(() =>
props.items.filter((item) => {
const kw = keyword.value.trim().toLowerCase();
if (!kw) return true;
const haystack = [item.invoice_no, item.material_no, item.material_name, item.source_code, item.lot_no]
const haystack = [item.invoice_no, item.external_doc_no, item.material_no, item.material_name, item.source_code, item.lot_no]
.map((value) => String(value ?? '').toLowerCase());
return haystack.some((value) => value.includes(kw));
}),
@@ -80,7 +81,6 @@ const pagedItems = computed(() =>
filtered.value.slice((currentPage.value - 1) * PAGE_SIZE, currentPage.value * PAGE_SIZE),
);
// 筛选变更回第 1 页;刷新后行数减少时收拢当前页防空白页
watch(keyword, () => {
currentPage.value = 1;
});
@@ -97,6 +97,13 @@ const allFilteredSelected = computed(() =>
filtered.value.length > 0 && filtered.value.every((item) => item.item_id != null && selectedIds.value.has(item.item_id)),
);
/** 当前筛选下库存已过期且可重查的行 id。 */
const staleItemIds = computed(() =>
filtered.value
.filter((item) => item.stale === true && item.item_id != null)
.map((item) => item.item_id as number),
);
function toggleRow(item: TransferMatchingItem, checkedBox: boolean) {
if (item.item_id == null) return;
const next = new Set(selectedIds.value);
@@ -126,7 +133,7 @@ function rowKey(item: TransferMatchingItem): string {
/**
* el-table 行类:注入行定位类 + stale/文件过期置灰。
* @param row 可执行明细行
* @returns 空格分隔的 class 串(含 transfer-executable-<invoice_no>)
* @returns 空格分隔的 class 串
*/
function rowClassName({ row }: { row: TransferMatchingItem }): string {
return [
@@ -135,12 +142,21 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
].filter(Boolean).join(' ');
}
/** 查询时刻展示(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);无 checked_at 不渲染。 */
function checkedTime(item: TransferMatchingItem): string {
if (!item.checked_at) return '';
const date = parseApiUtcDate(item.checked_at);
return Number.isNaN(date.getTime()) ? '' : date.toTimeString().slice(0, 5);
/**
* 库存数量单元格:数量与完整查询时刻同一行。
* @param item 可执行明细行
*/
function stockCell(item: TransferMatchingItem): string {
return formatStockQuantityCell(formatQuantity(item.from_quantity), item.checked_at);
}
/**
* 批量重查当前筛选下全部过期行。
* 核心逻辑:顶栏汇总入口,避免结果列刷长文案。
*/
function requeryStaleRows() {
if (!staleItemIds.value.length) return;
emit('requery', [...staleItemIds.value]);
}
</script>
@@ -157,6 +173,30 @@ function checkedTime(item: TransferMatchingItem): string {
</el-button>
</div>
<el-alert
v-if="staleItemIds.length"
type="warning"
:closable="false"
class="mb-2"
data-testid="transfer-executable-stale-banner"
>
<template #title>
<div class="flex flex-wrap items-center gap-2">
<span>{{ $t('chat.transfer.staleBanner', { count: staleItemIds.length }) }}</span>
<el-button
link
type="primary"
size="small"
:disabled="busy"
data-testid="transfer-executable-requery-stale"
@click="requeryStaleRows"
>
{{ $t('chat.transfer.staleBannerRequery') }}
</el-button>
</div>
</template>
</el-alert>
<div class="mb-2 flex flex-wrap items-center gap-2">
<div class="w-56 shrink-0">
<el-input
@@ -189,7 +229,7 @@ function checkedTime(item: TransferMatchingItem): string {
class="text-xs"
data-testid="transfer-executable-table"
>
<el-table-column width="48" class-name="whitespace-nowrap">
<el-table-column fixed width="48">
<template #header>
<el-checkbox
size="small"
@@ -208,52 +248,77 @@ function checkedTime(item: TransferMatchingItem): string {
/>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="110" class-name="whitespace-nowrap" />
<el-table-column :label="$t('chat.transfer.transferTypeLabel')" min-width="140" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="120" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.transferTypeLabel')" min-width="140" show-overflow-tooltip>
<template #default="{ row }">
<span :data-testid="`transfer-executable-type-${row.invoice_no}`">{{ typeLabel(row.transfer_type) }}</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colInvoice')" prop="invoice_no" min-width="130" class-name="whitespace-nowrap">
<el-table-column
:label="$t('chat.transfer.transferPendingMatchColDocNo')"
prop="invoice_no"
min-width="130"
show-overflow-tooltip
>
<template #default="{ row }">
<span class="font-semibold">{{ row.invoice_no }}</span>
<span class="font-semibold">{{ row.invoice_no || '—' }}</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="100" class-name="whitespace-nowrap">
<el-table-column
:label="$t('chat.transfer.transferPendingMatchColExternalDoc')"
min-width="130"
show-overflow-tooltip
>
<template #default="{ row }">
<span data-testid="transfer-executable-external-doc">{{ row.external_doc_no || '—' }}</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.movement_date || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" class-name="whitespace-nowrap" />
<el-table-column :label="$t('chat.transfer.colName')" min-width="140">
<template #default="{ row }">{{ row.material_name }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" min-width="110" class-name="whitespace-nowrap">
<template #default="{ row }">{{ row.from_warehouse }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="110" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="140" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="160" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" prop="from_warehouse" min-width="110" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="120" show-overflow-tooltip>
<template #default="{ row }">{{ deriveBatchNo(row.lot_no ?? '') || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="90" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="168" show-overflow-tooltip>
<template #default="{ row }">
{{ formatQuantity(row.from_quantity) }}
<div v-if="checkedTime(row as TransferMatchingItem)" class="text-[10px] text-muted">{{ checkedTime(row as TransferMatchingItem) }}</div>
<span
:class="row.stale ? 'text-amber-700' : undefined"
:title="freshnessHint(row as TransferMatchingItem, t) || undefined"
:data-testid="`transfer-executable-stock-${row.invoice_no}`"
>
{{ stockCell(row as TransferMatchingItem) }}
</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colToWarehouse')" min-width="110" class-name="whitespace-nowrap">
<template #default="{ row }">{{ row.to_warehouse }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colToWarehouse')" prop="to_warehouse" min-width="110" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" show-overflow-tooltip>
<template #default="{ row }">{{ formatQuantity(row.to_quantity) }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colResult')" min-width="120">
<el-table-column
fixed="right"
:label="$t('chat.transfer.colResult')"
width="88"
>
<template #default="{ row }">
<el-tag size="small" type="success" effect="light" data-testid="transfer-executable-result">
<el-tag
size="small"
type="success"
effect="light"
:title="freshnessHint(row as TransferMatchingItem, t) || undefined"
data-testid="transfer-executable-result"
>
{{ $t('chat.transfer.resultExecutable') }}
</el-tag>
<div v-if="row.stale" class="mt-0.5 text-[10px] text-amber-600">{{ $t('chat.transfer.staleRow') }}</div>
<div v-else-if="row.file_current === false" class="mt-0.5 text-[10px] text-amber-600">{{ $t('chat.transfer.fileChangedRow') }}</div>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colAction')" min-width="90" class-name="whitespace-nowrap">
<el-table-column
fixed="right"
:label="$t('chat.transfer.colAction')"
width="72"
>
<template #default="{ row }">
<el-button
link
@@ -268,7 +333,6 @@ function checkedTime(item: TransferMatchingItem): string {
</template>
</el-table-column>
</el-table>
<!-- 客户端分页(单页时隐藏):文案走全局 ElConfigProvider 四语言 locale -->
<el-pagination
v-if="filtered.length > PAGE_SIZE"
v-model:current-page="currentPage"
@@ -362,7 +362,10 @@ onMounted(async () => {
:data-testid="`transfer-executed-items-${order.doc_no}`"
>
<el-table :data="order.items" size="small" class="text-xs">
<el-table-column :label="$t('chat.transfer.colInvoice')" prop="invoice_no" min-width="120" class-name="whitespace-nowrap" />
<el-table-column :label="$t('chat.transfer.transferPendingMatchColDocNo')" prop="invoice_no" min-width="120" class-name="whitespace-nowrap" />
<el-table-column :label="$t('chat.transfer.transferPendingMatchColExternalDoc')" min-width="120" class-name="whitespace-nowrap">
<template #default="{ row }">{{ row.external_doc_no || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" class-name="whitespace-nowrap" />
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="140" />
<!-- 拨出批号展示外部形态(WTP→HOW 镜像转换,与匹配卡/可调拨明细/待办池同规则;
@@ -2,7 +2,7 @@
* features/chat/components/messages/TransferMatchCard.spec.ts
* 用途:匹配卡顶栏「来源失败」横幅过滤——路由未解析失败只行内展示,不进顶栏。
* 依赖:@vue/test-utils、i18n。
* 逻辑:来源失败顶栏(sources[].error_code/error_message)防止“安静全 0”;
* 逻辑:来源失败顶栏(sources[].error_code/error_message)防止“安静全 0”。
* 后端分层后路由失败保持行级(result=blocked_route_not_resolved),
* 顶栏需按 error_code 客户端排除(历史卡片回放同样生效)。
*/
@@ -7,20 +7,11 @@
busy)、i18n chat.transfer.*。
逻辑:明细表渲染 pagedItems(filtered 经客户端分页切片);阻断项 checkbox 禁用;
勾选键 = 明细行 item_id(历史回放行无 item_id 禁用防误选);
库存数量下方小字透出查询时刻(checked_at);stale 行置灰 + 重查提示;
file_current=false 行提示文件已更新(自动对齐语义);blocked_file_removed
徽标独立文案;pending_stock_check 行徽标「待查库存」(el-tag warning);
计数卡透出待查库存(pending_stock_check_count)/已失效(invalid_count),
历史回放缺省按 0 展示;blocked_file_removed 行退出主视图(表格不渲染),
表格下方折叠提示去待处理异常池处理——重查救不了已消失的行,主清单只留
可行动项;重查范围含可恢复阻断与可执行行(重查仍按 invoice_no 提交);
阻断原因经结果徽标 title 悬浮透出不占行高;无选择或 busy 时生成按钮禁用;
emit execute(itemIds);来源级解析/文件失败经 sources.error_code 透出
(防"安静全 0"),但路由未解析失败(TRANSFER.ROUTE_NOT_RESOLVED)不进顶栏
——路由失败保持行级(result=blocked_route_not_resolved 行内展示),
顶栏按 error_code 客户端排除,历史卡片回放同样生效;
行定位:el-table 行不支持逐行 attr,经 row-class-name 注入
transfer-item-<invoice_no>(spec/e2e 用类选择器等价定位);
明细表遵循 transferItemTable(EP show-overflow-tooltip、左固定勾选、
右固定结果/重查、单号可滚、库存数量与查询时刻同行、过期顶栏 el-alert 汇总);
blocked_file_removed 退出主视图;重查仍按 invoice_no;emit execute(itemIds);
来源失败顶栏排除 TRANSFER.ROUTE_NOT_RESOLVED;行定位经 row-class-name
注入 transfer-item-<invoice_no>;
[2026-10-12 单据数口径修正] 预计 ERP 单据数(计数卡=全部可执行行、
生成按钮旁=勾选可执行行)按执行建单五元组 (external_org, source_code,
movement_date, from_warehouse, to_warehouse) 去重实时计算(与后端
@@ -49,7 +40,10 @@ import {
import type { CheckboxValueType } from 'element-plus';
import { deriveBatchNo } from './transferBatch';
import { formatQuantity } from './transferFormat';
import { parseApiUtcDate } from '@/shared/utils/dateTime';
import {
formatStockQuantityCell,
freshnessHint,
} from './transferItemTable';
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
const { t } = useI18n();
@@ -129,7 +123,7 @@ const filtered = computed(() =>
if (isFileRemoved(item)) return false;
const kw = keyword.value.trim().toLowerCase();
if (kw) {
const haystack = [item.material_no, item.material_name, item.invoice_no, item.lot_no]
const haystack = [item.material_no, item.material_name, item.invoice_no, item.external_doc_no, item.lot_no]
.map((value) => String(value ?? '').toLowerCase());
if (!haystack.some((value) => value.includes(kw))) return false;
}
@@ -179,6 +173,22 @@ function requerySelected(): void {
if (nos.length) emit('requery', nos);
}
/** 当前筛选下库存已过期且可重查的单号。 */
const staleInvoiceNos = computed(() =>
filtered.value
.filter((item) => item.stale === true && isRequeryable(item))
.map((item) => item.invoice_no),
);
/**
* 批量重查当前筛选下全部过期行。
* 核心逻辑:顶栏汇总入口,避免结果列刷长文案。
*/
function requeryStaleRows(): void {
if (!staleInvoiceNos.value.length) return;
emit('requery', [...staleInvoiceNos.value]);
}
function isChecked(item: TransferMatchingItem): boolean {
return item.item_id != null && props.selected.has(item.item_id);
}
@@ -217,18 +227,11 @@ const estimatedDocumentCountSelected = computed(
);
/**
* 库存查询时刻小字(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);
* 无效/缺省 checked_at 返回 null 不渲染。
* @param item 匹配明细行;checked_at 为后端 ISO 时间
* 库存数量单元格:数量与完整查询时刻同一行。
* @param item 匹配明细行
*/
function checkedAtLabel(item: TransferMatchingItem): string | null {
if (!item.checked_at) return null;
const date = parseApiUtcDate(item.checked_at);
if (Number.isNaN(date.getTime())) return null;
const hh = String(date.getHours()).padStart(2, '0');
const mm = String(date.getMinutes()).padStart(2, '0');
return `${hh}:${mm}`;
function stockCell(item: TransferMatchingItem): string {
return formatStockQuantityCell(formatQuantity(item.from_quantity), item.checked_at);
}
function resultLabel(result: string): string {
@@ -348,6 +351,30 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
</div>
</el-alert>
<el-alert
v-if="staleInvoiceNos.length"
type="warning"
:closable="false"
class="mb-3"
data-testid="transfer-match-stale-banner"
>
<template #title>
<div class="flex flex-wrap items-center gap-2">
<span>{{ $t('chat.transfer.staleBanner', { count: staleInvoiceNos.length }) }}</span>
<el-button
link
type="primary"
size="small"
:disabled="props.requeryBusy"
data-testid="transfer-match-requery-stale"
@click="requeryStaleRows"
>
{{ $t('chat.transfer.staleBannerRequery') }}
</el-button>
</div>
</template>
</el-alert>
<div class="mb-2 flex flex-wrap items-center gap-2">
<div class="w-56 shrink-0">
<el-input
@@ -383,8 +410,7 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
</el-button>
</div>
<!-- EP 表格壳:横向滚动由 el-table 内建(列 min-width 撑开);无行动行时不挂表;
表体只挂当前页切片(pagedItems),全量集合仍在 filtered 供筛选/全选/计数 -->
<!-- EP 表格:show-overflow-tooltip + 左右固定列;表体仅当前页切片 -->
<el-table
v-if="filtered.length"
:data="pagedItems"
@@ -394,7 +420,7 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
class="text-xs"
data-testid="transfer-match-table"
>
<el-table-column width="48" class-name="whitespace-nowrap">
<el-table-column fixed width="48">
<template #header>
<el-checkbox
size="small"
@@ -413,49 +439,57 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
/>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="110" class-name="whitespace-nowrap" />
<el-table-column :label="$t('chat.transfer.colInvoice')" prop="invoice_no" min-width="130" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colSource')" prop="source_code" min-width="120" show-overflow-tooltip />
<el-table-column
:label="$t('chat.transfer.transferPendingMatchColDocNo')"
prop="invoice_no"
min-width="130"
show-overflow-tooltip
>
<template #default="{ row }">
<span class="font-semibold">{{ row.invoice_no }}</span>
<span class="font-semibold">{{ row.invoice_no || '—' }}</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="100" class-name="whitespace-nowrap">
<el-table-column
:label="$t('chat.transfer.transferPendingMatchColExternalDoc')"
min-width="130"
show-overflow-tooltip
>
<template #default="{ row }">
<span data-testid="transfer-match-external-doc">{{ row.external_doc_no || '—' }}</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMovementDate')" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.movement_date || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" class-name="whitespace-nowrap" />
<el-table-column :label="$t('chat.transfer.colName')" min-width="140">
<template #default="{ row }">{{ row.material_name }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" min-width="110" class-name="whitespace-nowrap">
<template #default="{ row }">{{ row.from_warehouse }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="110" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="140" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="160" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.colFromWarehouse')" prop="from_warehouse" min-width="110" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="120" show-overflow-tooltip>
<template #default="{ row }">{{ deriveBatchNo(row.lot_no) }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="90" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colFromQty')" min-width="168" show-overflow-tooltip>
<template #default="{ row }">
<div>{{ formatQuantity(row.from_quantity) }}</div>
<!-- 库存查询时刻小字:数据新鲜度溯源(stale 门禁的可见依据) -->
<div
v-if="checkedAtLabel(row as TransferMatchingItem)"
class="text-[10px] text-muted"
:title="$t('chat.transfer.stockCheckedAtTitle', { time: checkedAtLabel(row as TransferMatchingItem) })"
<span
:class="row.stale === true ? 'text-amber-700' : undefined"
:title="freshnessHint(row as TransferMatchingItem, t) || undefined"
:data-testid="`transfer-checked-at-${row.invoice_no}`"
>
{{ checkedAtLabel(row as TransferMatchingItem) }}
</div>
{{ stockCell(row as TransferMatchingItem) }}
</span>
</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colToWarehouse')" min-width="110" class-name="whitespace-nowrap">
<template #default="{ row }">{{ row.to_warehouse }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" class-name="whitespace-nowrap">
<el-table-column :label="$t('chat.transfer.colToWarehouse')" prop="to_warehouse" min-width="110" show-overflow-tooltip />
<el-table-column :label="$t('chat.transfer.colToQty')" min-width="90" show-overflow-tooltip>
<template #default="{ row }">{{ formatQuantity(row.to_quantity) }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colResult')" min-width="200">
<el-table-column
fixed="right"
:label="$t('chat.transfer.colResult')"
width="200"
>
<template #default="{ row }">
<div class="flex flex-wrap items-center gap-1">
<!-- 阻断原因经悬浮提示(title)透出:不占行高;可执行行也提供重查入口 -->
<div class="flex flex-nowrap items-center gap-1">
<el-tag
size="small"
effect="light"
@@ -465,24 +499,25 @@ function rowClassName({ row }: { row: TransferMatchingItem }): string {
>
{{ $t(resultLabel(row.result)) }}
</el-tag>
<!-- 行级警示小标:stale(仅展示提示,不拦截执行——2026-09-25 TTL 退役)/ 文件版本已过期 -->
<el-tag
v-if="row.stale === true"
size="small"
type="warning"
effect="plain"
:title="$t('chat.transfer.staleRow')"
data-testid="transfer-item-stale"
>
{{ $t('chat.transfer.staleRow') }}
{{ $t('chat.transfer.staleShort') }}
</el-tag>
<el-tag
v-if="row.file_current === false"
size="small"
type="warning"
effect="plain"
:title="$t('chat.transfer.fileChangedRow')"
data-testid="transfer-item-file-changed"
>
{{ $t('chat.transfer.fileChangedRow') }}
{{ $t('chat.transfer.fileChangedShort') }}
</el-tag>
<el-button
v-if="isRequeryable(row as TransferMatchingItem)"
@@ -403,9 +403,12 @@ async function confirmCloseOrder() {
<!-- 行明细常驻展开(物料 × 批号聚合行;Invoice 首列对齐可调拨明细列序) -->
<div class="border-t border-subtle px-3 py-2" :data-testid="`transfer-order-lines-${order.doc_no}`">
<el-table :data="order.lines" size="small" class="text-xs">
<el-table-column :label="$t('chat.transfer.colInvoice')" min-width="110">
<el-table-column :label="$t('chat.transfer.transferPendingMatchColDocNo')" min-width="110">
<template #default="{ row }">{{ row.invoice_no || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.transferPendingMatchColExternalDoc')" min-width="120">
<template #default="{ row }">{{ row.external_doc_no || '—' }}</template>
</el-table-column>
<el-table-column :label="$t('chat.transfer.colMaterial')" prop="material_no" min-width="110" />
<el-table-column :label="$t('chat.transfer.colName')" prop="material_name" min-width="120" />
<el-table-column :label="$t('chat.transfer.colFromBatch')" min-width="100">
@@ -108,15 +108,17 @@ describe('TransferMatchCard', () => {
expect(wrapper.find('.transfer-item-INV-001').text()).toContain('HOW26082728');
});
it('库存数量下方小字展示查询时刻(HH:mm)', async () => {
it('库存数量与完整查询时刻同一行(数量 · YYYY-MM-DD HH:mm)', async () => {
// [断言意图] 数量与时刻同行,避免第二行撑高整表;完整日期才能判断新旧。
const wrapper = await mountMatchCard({ summary, items, selected: new Set<number>() });
const cell = wrapper.find('[data-testid="transfer-checked-at-INV-001"]');
expect(cell.exists()).toBe(true);
expect(cell.text()).toMatch(/^\d{2}:\d{2}$/);
expect(wrapper.find('[data-testid="transfer-checked-at-INV-041"]').exists()).toBe(false);
expect(cell.text()).toBe('1200 · 2026-09-23 09:05');
// [断言意图] 无查询时刻时仍单行只显示数量,不拆第二行。
expect(wrapper.find('[data-testid="transfer-checked-at-INV-041"]').text()).not.toContain('·');
});
it('stale 行置灰 + 重查小标;file_current=false 行展示文件更新小标', async () => {
it('stale 行置灰 + 短徽标;file_current=false 行展示文件更新短徽标;顶栏汇总过期', async () => {
const flaggedItems = [
{ ...items[0], stale: true, file_current: false },
];
@@ -124,8 +126,12 @@ describe('TransferMatchCard', () => {
// [断言意图] el-table 行类经 row-class-name 注入 opacity-60。
const row = wrapper.find('.transfer-item-INV-001');
expect(row.classes()).toContain('opacity-60');
expect(wrapper.find('[data-testid="transfer-item-stale"]').text()).toContain('重查');
expect(wrapper.find('[data-testid="transfer-item-file-changed"]').text()).toContain('自动对齐');
// [断言意图] 长句只放悬停;行内只留短徽标;顶栏 el-alert 汇总可批量重查。
expect(wrapper.find('[data-testid="transfer-item-stale"]').text()).toContain('已过期');
expect(wrapper.find('[data-testid="transfer-item-stale"]').attributes('title')).toContain('重查');
expect(wrapper.find('[data-testid="transfer-item-file-changed"]').text()).toContain('文件更新');
expect(wrapper.find('[data-testid="transfer-item-file-changed"]').attributes('title')).toContain('自动对齐');
expect(wrapper.find('[data-testid="transfer-match-stale-banner"]').text()).toContain('1');
});
it('计数卡透出待查库存/已失效计数;历史 payload 缺省按 0 展示', async () => {
@@ -0,0 +1,32 @@
/**
* features/chat/components/messages/transferItemTable.spec.ts
* 用途:锁住明细表库存单元格与新鲜度提示的统一格式。
*/
import { describe, expect, it } from 'vitest';
import {
formatStockCheckedAt,
formatStockQuantityCell,
freshnessHint,
} from './transferItemTable';
describe('transferItemTable', () => {
it('完整查询时刻为上海时区 YYYY-MM-DD HH:mm', () => {
// [断言意图] +08:00 墙钟原样保留;无时区 naive 按 UTC 再转上海。
expect(formatStockCheckedAt('2026-09-23T09:05:00+08:00')).toBe('2026-09-23 09:05');
expect(formatStockCheckedAt('2026-10-22T02:57:00')).toBe('2026-10-22 10:57');
expect(formatStockCheckedAt('')).toBe('');
});
it('库存单元格数量与时刻同一行', () => {
// [断言意图] 禁止拆成两行撑高表格。
expect(formatStockQuantityCell('30', '2026-10-20T10:38:00+08:00')).toBe('30 · 2026-10-20 10:38');
expect(formatStockQuantityCell('30', null)).toBe('30');
});
it('新鲜度悬停过期优先于文件更新', () => {
const t = (key: string) => key;
expect(freshnessHint({ stale: true, file_current: false }, t)).toBe('chat.transfer.staleRow');
expect(freshnessHint({ stale: false, file_current: false }, t)).toBe('chat.transfer.fileChangedRow');
expect(freshnessHint({}, t)).toBe('');
});
});
@@ -0,0 +1,61 @@
/**
* features/chat/components/messages/transferItemTable.ts
* 用途:在途调拨明细表(可调拨 / 匹配 / 待恢复)的统一展示约定与单元格格式化。
* 依赖:transferDate.formatShanghaiDateTime、i18n chat.transfer.*。
* 逻辑:三卡共用 Element Plus 密度规则,禁止各卡各自叠第二行或放任折行。
*
* Element Plus 约定:
* 1. 长文本列 show-overflow-tooltip;不够宽就横向滚,不折行。
* 2. 左只固定勾选,右固定结果/操作;单号随表横滚(不钉死,避免挤窄中间区)。
* 3. 库存数量与查询时刻同一行:「数量 · YYYY-MM-DD HH:mm」。
* 4. 过期不占结果列长文;顶栏 el-alert 汇总 + 批量重查。
*/
import { formatShanghaiDateTime } from './transferDate';
const CHECKED_AT_RE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
/**
* 把后端库存查得时刻格式成上海时区完整墙钟。
* @param checkedAt - 后端 ISO(可空)
* @returns `YYYY-MM-DD HH:mm`;无法解析则空串
*/
export function formatStockCheckedAt(checkedAt: string | null | undefined): string {
if (!checkedAt) return '';
const label = formatShanghaiDateTime(checkedAt);
return CHECKED_AT_RE.test(label) ? label : '';
}
/**
* 库存数量单元格主文案:数量与查询时刻同一行。
* @param quantityLabel - 已格式化的数量文本
* @param checkedAt - 后端 ISO
* @returns 如 `30 · 2026-10-20 18:38`;无时刻则仅数量
*/
export function formatStockQuantityCell(
quantityLabel: string,
checkedAt: string | null | undefined,
): string {
const when = formatStockCheckedAt(checkedAt);
return when ? `${quantityLabel} · ${when}` : quantityLabel;
}
export interface TransferFreshnessRow {
stale?: boolean;
file_current?: boolean;
}
/**
* 行新鲜度悬停说明(过期优先于文件更新)。
* @param row - 带 stale / file_current 的明细行
* @param t - vue-i18n t
* @returns 悬停全文;无提示时空串
*/
export function freshnessHint(
row: TransferFreshnessRow,
t: (key: string) => string,
): string {
if (row.stale) return t('chat.transfer.staleRow');
if (row.file_current === false) return t('chat.transfer.fileChangedRow');
return '';
}
@@ -77,6 +77,8 @@ export interface TransferMatchingItem {
material_name: string;
specification: string;
invoice_no: string;
/** 档上的外部单号;没有则为空,列表显示占位 */
external_doc_no?: string;
/** 明细异动日期(Task 3 序列化键更名,明细 movement 语义;旧名见 git 历史) */
movement_date?: string | null;
from_warehouse: string;
@@ -164,8 +166,10 @@ export type TransferOrderStatus = 'pending' | 'executing' | 'success' | 'duplica
/** 单内行(ERP 写入行粒度聚合:物料+批号;quantity 为 6 位小数字符串,与 D14 快照口径一致) */
export interface TransferOrderLine {
/** 行级溯源入站通知号(2026-09-29 契约扩充;一行恒对应一张 invoice,旧 payload 缺省) */
/** 行级溯源单号(档 doc_no;旧 payload 缺省) */
invoice_no?: string;
/** 档上的外部单号;聚合行内多个单号以逗号连接,旧 payload 缺省 */
external_doc_no?: string;
material_no: string;
material_name: string;
lot_no: string;
@@ -218,6 +222,8 @@ export interface TransferBacklogItem {
item_id: number;
source_code: string;
invoice_no: string;
/** 档上的外部单号;没有则为空 */
external_doc_no?: string;
material_no: string;
status: string;
reason: string;
@@ -388,6 +394,8 @@ export interface TransferOrderGroups {
*/
export interface TransferExecutedOrderItem {
invoice_no: string;
/** 档上的外部单号;没有则为空 */
external_doc_no?: string;
material_no: string;
material_name: string;
lot_no: string;
+5 -2
View File
@@ -3807,14 +3807,13 @@
"colMaterial": "Material",
"colName": "Name",
"colSpec": "Spec",
"colInvoice": "Invoice",
"colMovementDate": "Movement Date",
"colFromWarehouse": "From warehouse",
"colFromQty": "Stock qty",
"stockCheckedAtTitle": "Stock checked at {time}",
"colToWarehouse": "To warehouse",
"colFromBatch": "Outbound Batch",
"filterPlaceholder": "Filter by material / name / Invoice / batch",
"filterPlaceholder": "Filter by material / name / doc no. / external doc / batch",
"filterAll": "All results",
"requerySelected": "Requery selected",
"movementDateLabel": "Movement date",
@@ -3830,7 +3829,11 @@
"resultFileRemoved": "Removed from file",
"resultPendingStockCheck": "Pending stock check",
"staleRow": "Stale — requery",
"staleShort": "Stale",
"staleBanner": "{count} rows have stale inventory",
"staleBannerRequery": "Requery stale rows",
"fileChangedRow": "File updated; data will realign",
"fileChangedShort": "File updated",
"fileRemovedQuarantined": "{count} more rows were invalidated (removed from the inbound file) and are hidden from this list; handle them under Pending Exceptions (mark as no further action).",
"runProgress": "Transfer run progress",
"runExecuting": "Executing",
+5 -2
View File
@@ -3807,14 +3807,13 @@
"colMaterial": "รหัสวัสดุ",
"colName": "ชื่อ",
"colSpec": "สเปก",
"colInvoice": "Invoice",
"colMovementDate": "วันที่เคลื่อนไหว",
"colFromWarehouse": "คลังต้นทาง",
"colFromQty": "จำนวนสต๊อก",
"stockCheckedAtTitle": "เวลาตรวจสอบสต๊อก: {time}",
"colToWarehouse": "คลังปลายทาง",
"colFromBatch": "ล็อตต้นทาง",
"filterPlaceholder": "กรองตามรหัสวัสดุ / ชื่อ / Invoice / ล็อต",
"filterPlaceholder": "กรองตามรหัสวัสดุ / ชื่อ / เลขที่เอกสาร / เลขที่เอกสารภายนอก / ล็อต",
"filterAll": "ทุกผลลัพธ์",
"requerySelected": "ตรวจซ้ำที่เลือก",
"movementDateLabel": "วันที่เคลื่อนไหว",
@@ -3830,7 +3829,11 @@
"resultFileRemoved": "ถูกลบออกจากไฟล์",
"resultPendingStockCheck": "รอตรวจสอบสต๊อก",
"staleRow": "ข้อมูลหมดอายุ กรุณาตรวจซ้ำ",
"staleShort": "หมดอายุ",
"staleBanner": "มี {count} แถวที่สต๊อกหมดอายุ",
"staleBannerRequery": "ตรวจซ้ำแถวที่หมดอายุ",
"fileChangedRow": "ไฟล์อัปเดตแล้ว ข้อมูลจะจัดตำแหน่งใหม่อัตโนมัติ",
"fileChangedShort": "ไฟล์อัปเดต",
"fileRemovedQuarantined": "อีก {count} รายการถือเป็นยกเลิกเนื่องจากถูกลบออกจากไฟล์รับเข้า และถูกซ่อนจากรายการนี้ โปรดดำเนินการใน「ข้อยกเว้นที่รอดำเนินการ」โดยสามารถทำเครื่องหมายว่าไม่จำเป็นต้องดำเนินการต่อ",
"runProgress": "ความคืบหน้าการโอน",
"runExecuting": "กำลังดำเนินการ",
+5 -2
View File
@@ -3807,14 +3807,13 @@
"colMaterial": "料号",
"colName": "品名",
"colSpec": "规格",
"colInvoice": "Invoice",
"colMovementDate": "异动日期",
"colFromWarehouse": "拨出仓库",
"colFromQty": "库存数量",
"stockCheckedAtTitle": "库存查询时刻:{time}",
"colToWarehouse": "拨入仓库",
"colFromBatch": "拨出批号",
"filterPlaceholder": "按料号 / 品名 / Invoice / 批号筛选",
"filterPlaceholder": "按料号 / 品名 / 单号 / 外部单号 / 批号筛选",
"filterAll": "全部结果",
"requerySelected": "重查选中",
"movementDateLabel": "异动日期",
@@ -3830,7 +3829,11 @@
"resultFileRemoved": "文件已移除",
"resultPendingStockCheck": "待查库存",
"staleRow": "数据已过期,请重查",
"staleShort": "已过期",
"staleBanner": "{count} 行库存已过期",
"staleBannerRequery": "重查过期行",
"fileChangedRow": "文件已更新,将自动对齐",
"fileChangedShort": "文件更新",
"fileRemovedQuarantined": "另有 {count} 行已随入站文件移除而失效,已移出本清单;请到「待处理异常」处理,可标记无需继续处理。",
"runProgress": "调拨执行进度",
"runExecuting": "执行中",
+5 -2
View File
@@ -3807,14 +3807,13 @@
"colMaterial": "料號",
"colName": "品名",
"colSpec": "規格",
"colInvoice": "Invoice",
"colMovementDate": "異動日期",
"colFromWarehouse": "撥出倉庫",
"colFromQty": "庫存數量",
"stockCheckedAtTitle": "庫存查詢時刻:{time}",
"colToWarehouse": "撥入倉庫",
"colFromBatch": "撥出批號",
"filterPlaceholder": "按料號 / 品名 / Invoice / 批號篩選",
"filterPlaceholder": "按料號 / 品名 / 單號 / 外部單號 / 批號篩選",
"filterAll": "全部結果",
"requerySelected": "重查選中",
"movementDateLabel": "異動日期",
@@ -3830,7 +3829,11 @@
"resultFileRemoved": "檔案已移除",
"resultPendingStockCheck": "待查庫存",
"staleRow": "資料已過期,請重查",
"staleShort": "已過期",
"staleBanner": "{count} 行庫存已過期",
"staleBannerRequery": "重查過期行",
"fileChangedRow": "檔案已更新,將自動對齊",
"fileChangedShort": "檔案更新",
"fileRemovedQuarantined": "另有 {count} 筆已隨入站檔案移除而失效,已移出本清單;請到「待處理異常」處理,可標記無需繼續處理。",
"runProgress": "調撥執行進度",
"runExecuting": "執行中",