feat(shipping-notice): 调拨预检解析增强与批号列交互完善

- 异动解析跳过无异动日期的在途/执行中行,兼容 datetime 日期单元格
- ERP 网关故障降级为逐票阻断并带原因,不再炸整来源
- 预检明细唯一约束升粒度:(预检,来源,单号,料号,收料日期)
- Invoice 恢复单号锚定并移至料号前;批号 lot_no 全链贯通,
  拨出/拨入批号按 WTP→HOW 转换展示;新增收料日期列
- 预检表格筛选/全选;单行与批量重查 ERP 库存
- 收料日期范围作为预检查询范围,截止卡控不超出 D+1 规则
- 来源多选打包下载收料文件;调拨消息与子流程容器放宽宽度
- 预检恢复明细补齐收料日期与批号字段(修复卡片三列空值)
This commit is contained in:
hugo committed 2026-09-21 19:29:52 +08:00
1 parent a06ff79d7c
commit 1ba38e1685
44 files changed
+963 -121

No files matched your search

+79 -1
View File
@@ -28,7 +28,7 @@ from app.services.in_transit_transfer.execution_service import (
)
from app.services.in_transit_transfer.manual_close_service import manual_close_item
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
from app.services.in_transit_transfer.retry_service import retry_item
from app.services.in_transit_transfer.retry_service import requery_items as retry_service_requery_items, retry_item
from app.services.in_transit_transfer.serializers import (
serialize_item,
serialize_source,
@@ -89,6 +89,8 @@ def create_precheck_api():
source_codes=[str(item).strip() for item in source_codes],
business_date=business_date,
deps=deps,
receipt_date_from=str(body.get("receipt_date_from")) if body.get("receipt_date_from") else None,
receipt_date_to=str(body.get("receipt_date_to")) if body.get("receipt_date_to") else None,
)
return _ok(serialize_summary(summary), status=201)
@@ -130,6 +132,82 @@ def execute_precheck_api(precheck_id: str):
}, status=201)
@in_transit_transfer_bp.route("/prechecks/<precheck_no>/items/requery", methods=["POST"])
@require_transfer_permission
def requery_items_api(precheck_no: str):
"""批量重查 ERP 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
body = request.get_json(silent=True) or {}
invoice_nos = body.get("invoice_nos") if isinstance(body.get("invoice_nos"), list) else None
deps = transfer_deps.get_transfer_dependencies()
return _ok(retry_service_requery_items(
precheck_no=precheck_no, deps=deps, invoice_nos=invoice_nos, actor_id=_actor_id(),
))
@in_transit_transfer_bp.route("/sources/receipt-files", methods=["POST"])
@require_transfer_permission
def download_source_receipt_files_api():
"""按选中来源打包下载各自最新归档收料文件(zip);记录访问审计。"""
import io
import zipfile
from pathlib import Path as _Path
from app import db
from app.models import ShippingReceiptReportFile
from app.services.file_assets.storage import file_asset_storage
body = request.get_json(silent=True) or {}
source_codes = body.get("source_codes")
if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]:
raise ValidationError("source_codes is required")
buffer = io.BytesIO()
included: list[str] = []
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
for code in source_codes:
code = str(code or "").strip()
if not code:
continue
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is None:
continue
data = file_asset_storage.get_bytes(report.storage_key)
safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name
archive.writestr(f"{code}-{safe_name}", data)
included.append(code)
if not included:
raise NotFoundError("no archived receipt files", code="SHIPPING.RECEIPT_FILE_NOT_FOUND")
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
aggregate_type="in_transit_source",
aggregate_id=",".join(included),
actor_type="user",
actor_id=str(user.id) if user.id else None,
actor_display=str(getattr(user, "name", "") or ""),
request_id=getattr(g, "request_id", None),
result="success",
))
db.session.commit()
buffer.seek(0)
return send_file(
buffer,
mimetype="application/zip",
as_attachment=True,
download_name=f"receipt-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip",
)
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
@require_transfer_permission
def get_run_api(run_no: str):
+10 -2
View File
@@ -184,11 +184,17 @@ class TransferPrecheck(Base):
class TransferInvoiceItem(Base):
"""预检明细项;同一预检内 Invoice 唯一,保留原始行追溯。"""
"""预检明细项;同一预检内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
"""
__tablename__ = 'transfer_invoice_items'
__table_args__ = (
UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'),
UniqueConstraint(
'precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
name='uq_transfer_invoice_items_precheck_grain',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})",
name='ck_transfer_invoice_items_status',
@@ -203,6 +209,8 @@ class TransferInvoiceItem(Base):
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
@@ -362,7 +362,12 @@ class ShippingInventoryRoutingRuleVersion(Base):
class ShippingInventoryExternalMapping(Base):
"""货代库存身份到外部系统仓库的单向映射;不承载调拨规则。"""
"""货代仓库到外部系统仓库的映射。
freight_warehouse_id(货代仓库)是必维护的业务维度,同时是调拨拨出仓库的
来源(in_transit_transfer DefaultRouteResolver);历史遗留的 NULL"默认映射"
行不再允许新建(保存端必填校验),仅存量数据兼容。
"""
__tablename__ = 'shipping_inventory_external_mappings'
__table_args__ = (
@@ -1208,8 +1208,9 @@ def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping
raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
record.inventory_source_id = source_id
# Freight warehouse is a business identity token; normalize it to match runtime inventory rows.
record.freight_warehouse_id = (_text(data, 'freight_warehouse_id') or '').upper() or None
# 货代仓库是映射必要维度(调拨拨出仓库来源),不再支持"库存源默认映射";
# 归一化为大写以与库存行 Warehouse 身份精确匹配。
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id', required=True)).upper()
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
record.external_organization_code = _text(data, 'external_organization_code')
record.external_site_code = _text(data, 'external_site_code')
@@ -84,7 +84,7 @@ class RawLineRefDTO:
@dataclass(frozen=True)
class PrecheckInvoiceItemDTO:
"""预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。"""
"""预检明细项(决策 6 十列 + 2026-09-21 增批号:拨出批号/拨入批号由 lot_no 转换派生,lot_no 存原值)。"""
source_code: str
material_no: str
@@ -100,6 +100,7 @@ class PrecheckInvoiceItemDTO:
reason: str = ""
erp_document_no: str | None = None
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
lot_no: str = ""
@dataclass(frozen=True)
@@ -20,19 +20,30 @@ MATURITY_NOT_MATURED = "not_matured"
MATURITY_FUTURE = "future"
def parse_date(value: date | str) -> date:
"""将 date 或 'YYYY-MM-DD' 字符串归一化为 date。
def parse_date(value: date | datetime | str) -> date:
"""将 date/datetime 或日期字符串归一化为 date。
Args:
value: date 对象或 ISO 日期字符串。
value: date/datetime 对象,或日期字符串(允许携带时间部分,如
Excel 日期单元格经字符串化的 '2026-08-26 17:38:38')。
Returns:
归一化后的 date。
Raises:
ValueError: 字符串不是合法 ISO 日期。
ValueError: 字符串不是可识别的日期/日期时间。
"""
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
return date.fromisoformat(str(value).strip())
text = str(value).strip()
try:
return date.fromisoformat(text)
except ValueError:
pass
try:
return datetime.fromisoformat(text).date()
except ValueError as exc:
raise ValueError(f"Invalid date value: {value!r}") from exc
def business_date_now(moment: datetime | None = None) -> date:
@@ -24,9 +24,10 @@ from app.services.in_transit_transfer.precheck_service import (
class DefaultRouteResolver:
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
"""默认路由解析:仓库映射的货代仓库 + 外部系统仓库。
路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。
拨出仓库 = 映射行的货代仓库(货现在所在的 WMS 仓);拨入仓库 = 映射的
目标仓库代码。不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
@@ -39,9 +40,13 @@ class DefaultRouteResolver:
).first()
if mapping is None or not mapping.external_organization_code:
raise RouteNotResolvedError(source_code=source_code)
from_warehouse = str(mapping.freight_warehouse_id or "").strip()
if not from_warehouse:
# 拨出仓库无来源(映射未维护货代仓库)——fail-closed,不猜测。
raise RouteNotResolvedError(source_code=source_code)
return RouteMapping(
erp_org=mapping.external_organization_code,
from_warehouse=source.fixed_warehouse_id or "",
from_warehouse=from_warehouse,
to_warehouse=mapping.external_warehouse_code,
)
@@ -9,7 +9,7 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Iterable, Mapping
@@ -34,6 +34,7 @@ class ParsedReceiptRow:
specification: str
receipt_date: date
receipt_quantity: Decimal
lot_no: str = ""
class ReceiptFileSchemaError(AppError):
@@ -53,6 +54,18 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
rows.append({"row_no": row_no, "reason": reason})
def _is_unreceived_row(date_value: Any) -> bool:
"""判断是否为"无收料事实的在途行":无异动日期即跳过。
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
① 未收料在途 ASN(Date Received 空、Qty Received 0);
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与预检;
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
"""
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
@@ -61,7 +74,7 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
quantity → receipt_quantity(严格数量匹配)
movement_date → receipt_date(成熟过滤)
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
doc_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
@@ -120,7 +133,7 @@ def _parse_rows(
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
到原始行字段名的映射(如 {invoice_no: doc_no})。
Returns:
已校验的 ParsedReceiptRow 列表。
已校验的 ParsedReceiptRow 列表("无异动日期"的在途/执行中行已跳过)。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
@@ -137,7 +150,7 @@ def _parse_rows(
invoice_no = str(row.get(invoice_key) or "").strip()
material_no = str(row.get(material_key) or "").strip()
sheet = str(row.get("sheet") or "").strip()
receipt_date_raw = str(row.get(date_key) or "").strip()
receipt_date_value = row.get(date_key)
quantity_raw = row.get(quantity_key)
if not sheet or not row_no:
@@ -153,10 +166,12 @@ def _parse_rows(
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
if _is_unreceived_row(receipt_date_value):
continue
try:
receipt_date = parse_date(receipt_date_raw)
receipt_date = parse_date(receipt_date_value)
except ValueError:
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}")
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_value!r}")
continue
try:
quantity = validate_receipt_quantity(quantity_raw)
@@ -173,6 +188,7 @@ def _parse_rows(
specification=str(row.get("specification") or "").strip(),
receipt_date=receipt_date,
receipt_quantity=quantity,
lot_no=str(row.get("lot_no") or "").strip(),
))
if errors:
raise ReceiptFileSchemaError(rows=errors)
@@ -1,9 +1,9 @@
"""在途调拨 Invoice 多行汇总与冲突阻断。
"""在途调拨 Invoice 多行汇总。
用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本;
同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。
用途:相同 Invoice+料号+收料日期 的多行只汇总收料数量,并永久保留原始
Sheet/行号/文件版本;同 Invoice 跨料号或跨日期自然拆分为多张发票。
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。
逻辑:汇总键 (source_code, invoice_no, material_no, receipt_date)。
"""
from __future__ import annotations
@@ -30,6 +30,7 @@ class AggregatedInvoice:
receipt_date: date
receipt_quantity: Decimal
raw_lines: tuple[RawLineRefDTO, ...]
lot_no: str = ""
class InvoiceConflictError(AppError):
@@ -45,34 +46,25 @@ class InvoiceConflictError(AppError):
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice 汇总收料数量并保留原始行证据。
"""按 Invoice+料号+收料日期 汇总收料数量并保留原始行证据。
汇总键 (source_code, invoice_no, material_no, receipt_date):Invoice 语义为
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨收料日期时
自然拆分为多张发票(部分交付场景),不做整单阻断。
Args:
rows: 已校验的解析行。
file_version: 当前文件版本(写入原始行追溯)。
Returns:
汇总后的 Invoice 列表(按 Invoice 排序)。
Raises:
InvoiceConflictError: 同一 Invoice 多料号或多收料日期。
汇总后的 Invoice 列表(按汇总键排序)。
"""
grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {}
grouped: dict[tuple[str, str, str, date], list[ParsedReceiptRow]] = {}
for row in rows:
grouped.setdefault((row.source_code, row.invoice_no), []).append(row)
grouped.setdefault(
(row.source_code, row.invoice_no, row.material_no, row.receipt_date), [],
).append(row)
invoices: list[AggregatedInvoice] = []
for (source_code, invoice_no), group in sorted(grouped.items()):
material_nos = {row.material_no for row in group}
dates = {row.receipt_date for row in group}
if len(material_nos) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_material_no: {sorted(material_nos)}",
)
if len(dates) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}",
)
for (source_code, invoice_no, material_no, receipt_date), group in sorted(grouped.items()):
first = group[0]
raw_lines = tuple(
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
@@ -81,11 +73,12 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
invoices.append(AggregatedInvoice(
source_code=source_code,
invoice_no=invoice_no,
material_no=first.material_no,
material_no=material_no,
material_name=first.material_name,
specification=first.specification,
receipt_date=first.receipt_date,
receipt_date=receipt_date,
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
raw_lines=raw_lines,
lot_no=first.lot_no,
))
return invoices
@@ -41,6 +41,8 @@ class MovementField:
# 定死的 10 个通用异动字段(领域契约,不配置化)。
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
# 批号(lot_no)为展示维度——预检列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
@@ -29,9 +29,11 @@ from app.services.in_transit_transfer.contracts import (
)
from app.services.in_transit_transfer.date_policy import (
MATURITY_ELIGIBLE,
eligible_receipt_date_to,
MATURITY_FUTURE,
MATURITY_NOT_MATURED,
maturity_status,
parse_date,
)
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
from app.services.in_transit_transfer.file_parser import (
@@ -47,7 +49,6 @@ from app.services.in_transit_transfer.file_preparation import (
ensure_receipt_file_ready,
)
from app.services.in_transit_transfer.invoice_aggregator import (
InvoiceConflictError,
aggregate_invoices,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
@@ -64,6 +65,7 @@ RESULT_NOT_MATURED = "not_matured"
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
RESULT_FUTURE_DATE = "blocked_future_date"
RESULT_ERP_QUERY_FAILED = "blocked_erp_query_failed"
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
@@ -144,6 +146,8 @@ def run_precheck(
deps: TransferDeps,
active_source_job_key: str | None = None,
run_no: str = "RUN-PENDING",
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
) -> PrecheckRunResult:
"""执行一次只读预检(不写 ERP)。
@@ -160,6 +164,17 @@ def run_precheck(
"""
if not source_codes:
raise ValidationError("source_codes is required")
# [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。
range_from = parse_date(receipt_date_from) if receipt_date_from else None
range_to = parse_date(receipt_date_to) if receipt_date_to else None
if range_from and range_to and range_from > range_to:
raise ValidationError(
"receipt date range is invalid", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
)
if range_to and range_to > eligible_receipt_date_to(business_date):
raise ValidationError(
"receipt date range end exceeds D+1 maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
)
validate_strategy = deps.strategy
sources: list[SourceProgressDTO] = []
@@ -193,6 +208,10 @@ def run_precheck(
# (doc_no/material_code/quantity/movement_date),按异动解析规则映射校验。
parsed = parse_movement_rows(source_code=source_code, rows=ready_file.rows)
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
if range_from is not None:
invoices = [invoice for invoice in invoices if invoice.receipt_date >= range_from]
if range_to is not None:
invoices = [invoice for invoice in invoices if invoice.receipt_date <= range_to]
source_items = _precheck_invoices(
invoices=invoices,
source_code=source_code,
@@ -209,7 +228,7 @@ def run_precheck(
file_version=ready_file.file_version,
checksum=ready_file.checksum,
))
except (ReceiptFileSchemaError, InvoiceConflictError) as exc:
except ReceiptFileSchemaError as exc:
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=exc.code, error_message=exc.message,
@@ -302,7 +321,7 @@ def _precheck_invoices(
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
@@ -313,7 +332,7 @@ def _precheck_invoices(
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_FUTURE_DATE, reason="future receipt date",
@@ -337,7 +356,7 @@ def _precheck_invoices(
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
@@ -345,11 +364,26 @@ def _precheck_invoices(
raw_lines=raw,
))
continue
except Exception as exc: # noqa: BLE001 —— ERP 网关/绑定层故障降级为单据阻断,不炸整来源
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
# 逐票给 blocked_erp_query_failed + 原因,预检列表保持可见可解释。
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_ERP_QUERY_FAILED, reason=f"erp query failed: {detail}",
raw_lines=raw,
))
continue
if not query.found:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
@@ -361,7 +395,7 @@ def _precheck_invoices(
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=query.quantity, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
@@ -396,6 +430,8 @@ def create_precheck(
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
) -> PrecheckSummaryDTO:
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
@@ -410,6 +446,8 @@ def create_precheck(
business_date=business_date,
deps=deps,
active_source_job_key=active_source_job_key,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
run_no=run_no,
)
now = datetime.utcnow()
@@ -445,7 +483,7 @@ def create_precheck(
run_id=run.id,
business_date=business_date,
status=result.summary.status,
scope_json={"source_codes": list(source_codes)},
scope_json={"source_codes": list(source_codes), "receipt_date_from": receipt_date_from, "receipt_date_to": receipt_date_to},
file_snapshot_json={
stage.source_code: {
"file_no": stage.file_no,
@@ -466,27 +504,57 @@ def create_precheck(
db.session.add(precheck)
db.session.flush()
# [幂等] 相同 (来源,单号,料号,收料日期) 的重复预检不得累加异常行:
# 非终态行原地刷新并挂到最新预检;终态行(已执行/人工关闭等)保持既定事实不复活。
_terminal_item_statuses = {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
status_machine.TransferStatus.CANCELLED.value,
status_machine.TransferStatus.EXECUTING.value,
}
for item in result.items:
fields = {
"precheck_id": precheck.id,
"status": _item_status(item.result),
"result_code": item.result if item.result != RESULT_EXECUTABLE else None,
"result_message": item.reason or None,
"from_warehouse": item.from_warehouse or "",
"to_warehouse": item.to_warehouse or "",
"receipt_quantity": str(item.to_quantity),
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"lot_no": item.lot_no or "",
"raw_lines_json": [
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
}
# 禁 autoflush:避免本批 pending 插入在查询时提前落库(应随循环末统一 commit)。
with db.session.no_autoflush:
existing = (
TransferInvoiceItem.query.filter_by(
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
receipt_date=item.receipt_date,
)
.order_by(TransferInvoiceItem.id.desc())
.first()
)
if existing is not None:
if existing.status not in _terminal_item_statuses:
for attr, value in fields.items():
setattr(existing, attr, value)
continue
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
db.session.add(TransferInvoiceItem(
precheck_id=precheck.id,
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse or "",
to_warehouse=item.to_warehouse or "",
receipt_quantity=str(item.to_quantity),
erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None,
status=_item_status(item.result),
result_code=item.result if item.result != RESULT_EXECUTABLE else None,
result_message=item.reason or None,
raw_lines_json=[
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
**fields,
))
db.session.commit()
@@ -545,6 +613,8 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
lot_no=item.lot_no or "",
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
to_warehouse=item.to_warehouse,
@@ -118,3 +118,42 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_R
status = _recheck_item(item, deps=deps, request_id=request_id)
db.session.commit()
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""批量重查 ERP 库存:对同一预检下全部/指定的可恢复阻断行逐票重查并刷新。
Args:
precheck_no: 预检编号(定位明细集合)。
deps: 注入依赖(erp = 网关适配器)。
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该预检全部可恢复阻断行。
actor_id / request_id: 审计上下文。
Returns:
{"precheck_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
单行失败(状态不允许/不存在)不影响其余行(来源级隔离同款语义)。
"""
from app.models import TransferPrecheck
precheck = TransferPrecheck.query.filter_by(precheck_no=precheck_no).first()
if precheck is None:
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
query = TransferInvoiceItem.query.filter_by(
precheck_id=precheck.id, status=status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
)
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
if wanted:
query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted))
items = query.order_by(TransferInvoiceItem.id).all()
results: list[dict] = []
for item in items:
try:
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_ERP_RECHECK,
actor_id=actor_id, request_id=request_id)
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": True, "status": item.status})
except (ValidationError, NotFoundError) as exc:
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": False, "error": exc.message})
return {"precheck_no": precheck_no, "total": len(items), "results": results}
@@ -41,6 +41,7 @@ def serialize_item(item) -> dict[str, Any]:
"material_name": item.material_name,
"specification": item.specification,
"invoice_no": item.invoice_no,
"lot_no": item.lot_no,
"receipt_date": item.receipt_date,
"from_warehouse": item.from_warehouse,
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
@@ -0,0 +1,44 @@
"""
backend/migrations/versions/rc4d5e6f7a8b_widen_transfer_invoice_item_unique_grain.py
用途:预检明细唯一约束从 (预检,Invoice) 升粒度为 (预检,来源,Invoice,料号,收料日期)。
依赖:Alembic revision sd9e8f7a6b5c;transfer_invoice_items 已存在。
逻辑:调拨 Invoice 自 2026-09-21 锚定批号(External ASN),同一批号按料号/收料日期
拆分为多行;旧约束 (precheck_id, invoice_no) 与新粒度矛盾导致预检 500。
降级前必须确认不存在同批号多料号/多日期的明细行。
Revision ID: rc4d5e6f7a8b
Revises: sd9e8f7a6b5c
Create Date: 2026-09-21 17:20:00.000000
"""
from __future__ import annotations
from alembic import op
revision = "rc4d5e6f7a8b"
down_revision = "sd9e8f7a6b5c"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除 (预检,Invoice) 唯一约束,改为含料号与收料日期的完整业务粒度。"""
op.drop_constraint(
'uq_transfer_invoice_items_precheck_invoice', 'transfer_invoice_items', type_='unique',
)
op.create_unique_constraint(
'uq_transfer_invoice_items_precheck_grain', 'transfer_invoice_items',
['precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date'],
)
def downgrade() -> None:
"""恢复旧约束;执行前必须清理同批号多料号/多日期产生的拆分明细行。"""
op.drop_constraint(
'uq_transfer_invoice_items_precheck_grain', 'transfer_invoice_items', type_='unique',
)
op.create_unique_constraint(
'uq_transfer_invoice_items_precheck_invoice', 'transfer_invoice_items',
['precheck_id', 'invoice_no'],
)
@@ -0,0 +1,31 @@
"""
backend/migrations/versions/rc5e6f7a8b9c_add_transfer_invoice_item_lot_no.py
用途:预检明细增加批号 lot_no 列(拨出/拨入批号展示与追溯的数据来源)。
依赖:Alembic revision rc4d5e6f7a8b;transfer_invoice_items 已存在。
逻辑:批号为收料行的 External ASN 等批号原值;拨入批号展示由 WTP→HOW 转换派生,不落库。
Revision ID: rc5e6f7a8b9c
Revises: rc4d5e6f7a8b
Create Date: 2026-09-21 18:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "rc5e6f7a8b9c"
down_revision = "rc4d5e6f7a8b"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""transfer_invoice_items 增加 lot_no 可空列。"""
op.add_column('transfer_invoice_items', sa.Column('lot_no', sa.String(length=64), nullable=True))
def downgrade() -> None:
"""删除 lot_no 列(展示数据派生自收料文件,可随时重算)。"""
op.drop_column('transfer_invoice_items', 'lot_no')
+5 -5
View File
@@ -701,13 +701,13 @@ def dbs_ready_file() -> dict:
"checksum": "d" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 10, "doc_no": "INV-001", "material_code": "MAT-001",
{"sheet": "Receipt", "row_no": 10, "doc_no": "INV-001", "lot_no": "LOT-10", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "500", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 11, "doc_no": "INV-001", "material_code": "MAT-001",
{"sheet": "Receipt", "row_no": 11, "doc_no": "INV-001", "lot_no": "LOT-11", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "700", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 20, "doc_no": "INV-002", "material_code": "MAT-002",
{"sheet": "Receipt", "row_no": 20, "doc_no": "INV-002", "lot_no": "LOT-20", "material_code": "MAT-002",
"material_name": "控制器组件", "specification": "标准型 / 48V",
"movement_date": "2026-08-05", "quantity": "1200", "source_code": "DBS-AWSBI"},
],
@@ -729,7 +729,7 @@ def crane_ready_file() -> dict:
"checksum": "c" * 64,
"status": "ready",
"rows": [
{"sheet": "Inbound", "row_no": 5, "doc_no": "INV-008", "material_code": "MAT-200",
{"sheet": "Inbound", "row_no": 5, "doc_no": "INV-008", "lot_no": "LOT-8", "material_code": "MAT-200",
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
"movement_date": "2026-08-05", "quantity": "600", "source_code": "CRANE-SZ"},
],
@@ -751,7 +751,7 @@ def same_day_receipt_file() -> dict:
"checksum": "s" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 3, "doc_no": "INV-041", "material_code": "MAT-041",
{"sheet": "Receipt", "row_no": 3, "doc_no": "RCP-3", "lot_no": "INV-041", "material_code": "MAT-041",
"material_name": "连接器组件", "specification": "C 型",
"movement_date": "2026-08-06", "quantity": "400", "source_code": "DBS-AWSSG"},
],
@@ -540,14 +540,29 @@ def test_active_default_external_mapping_is_unique_per_source(app):
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
payload = {
'inventory_source_id': source['id'], 'external_system_code': 'TOPGP', 'external_organization_code': None,
'external_site_code': 'EU01', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
'external_organization_code': None, 'external_site_code': 'EU01',
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
}
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
with pytest.raises(ConflictError):
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
def test_external_mapping_requires_freight_warehouse(app):
"""货代仓库是映射必要维度(调拨拨出仓库来源)——缺省必须拒绝,不再支持默认映射。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
# [断言意图] 缺货代仓库的映射会让调拨拨出仓库无来源,保存端必须 fail-closed。
with pytest.raises(ValidationError):
shipping_inventory_service.save_external_mapping({
'inventory_source_id': source['id'], 'external_system_code': 'TOPGP',
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
}, actor_id=None)
def test_external_mapping_normalizes_freight_warehouse_identity(app):
"""配置端小写货代仓应与库存行大写 Warehouse 使用同一精确映射身份。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
@@ -97,6 +97,11 @@ class FakeERP:
key = str(invoice_no).strip()
if self.query_scenario == "timeout":
raise TimeoutError(f"query timeout operation_id={operation_id}")
if self.query_scenario == "error":
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "error", "query_inventory")
self.call_log.append(record)
raise RuntimeError("binding not found for capability query_inventory")
if self.query_scenario == "inventory_not_found" or key not in self.inventory:
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "inventory_not_found", "query_inventory")
@@ -16,7 +16,6 @@ import pytest
from app.services.in_transit_transfer.file_parser import parse_receipt_rows
from app.services.in_transit_transfer.invoice_aggregator import (
AggregatedInvoice,
InvoiceConflictError,
aggregate_invoices,
)
@@ -66,25 +65,29 @@ def test_distinct_invoices_stay_separate_and_sorted():
assert [item.invoice_no for item in invoices] == ["INV-001", "INV-002"]
def test_multiple_material_no_conflict_blocks_invoice():
"""同一 Invoice 出现多个料号 → 整单阻断。"""
def test_same_invoice_multiple_materials_split_into_separate_invoices():
"""同一 Invoice(ASN)跨料号 → 按料号拆分为多张调拨发票,不再整单阻断。"""
rows = [
_row("INV-001", material_no="MAT-001", row_no=1),
_row("INV-001", material_no="MAT-002", row_no=2),
_row("ASN-001", material_no="MAT-001", row_no=1, quantity="100"),
_row("ASN-001", material_no="MAT-002", row_no=2, quantity="200"),
]
with pytest.raises(InvoiceConflictError) as excinfo:
aggregate_invoices(_parsed(rows))
assert excinfo.value.details.get("invoice_no") == "INV-001"
invoices = aggregate_invoices(_parsed(rows))
# [断言意图] Invoice 语义 = 调拨拨出单据号;料号维度自然拆分,保留各自数量与原始行。
assert [(i.material_no, i.receipt_quantity) for i in invoices] == [
("MAT-001", Decimal("100")), ("MAT-002", Decimal("200")),
]
assert all(i.invoice_no == "ASN-001" for i in invoices)
def test_multiple_receipt_date_conflict_blocks_invoice():
"""同一 Invoice 出现多个收料日期 → 整单阻断。"""
def test_same_invoice_material_multiple_dates_split_by_date():
"""同 Invoice 同料号跨收料日期(部分交付)→ 按日期拆分,不再整单阻断。"""
rows = [
_row("INV-001", receipt_date="2026-08-05", row_no=1),
_row("INV-001", receipt_date="2026-08-06", row_no=2),
_row("ASN-001", receipt_date="2026-08-05", row_no=1, quantity="100"),
_row("ASN-001", receipt_date="2026-08-06", row_no=2, quantity="50"),
]
with pytest.raises(InvoiceConflictError):
aggregate_invoices(_parsed(rows))
invoices = aggregate_invoices(_parsed(rows))
assert [str(i.receipt_date) for i in invoices] == ["2026-08-05", "2026-08-06"]
assert [i.receipt_quantity for i in invoices] == [Decimal("100"), Decimal("50")]
def test_aggregated_invoice_keeps_material_identity():
@@ -71,6 +71,8 @@ def test_extract_movement_rows_maps_columns_to_domain_fields():
parsed = parse_movement_rows(source_code='DBS-AWSBI', rows=rows)
assert [row.row_no for row in parsed] == [2, 3]
assert [row.invoice_no for row in parsed] == ['MOV-001', 'MOV-001']
# [断言意图] 批号透传进解析行(预检拨出/拨入批号展示的数据来源)。
assert [row.lot_no for row in parsed] == ['LOT-9', 'LOT-9']
def test_extract_movement_rows_skips_missing_alias_columns():
@@ -92,3 +92,46 @@ def test_optional_fields_default_empty():
)
row = parsed[0]
assert row.material_name == ""
def test_pending_intransit_rows_are_skipped():
"""未收料在途行(无异动日期且数量为空/0)是 WMS 报告常态——必须跳过而不是整文件报错。"""
pending_zero_qty = {"sheet": "Movement", "row_no": 2, "doc_no": "MOV-100", "material_code": "MAT-X",
"quantity": 0, "movement_date": None, "source_code": "DBS-AWSBI"}
pending_blank_qty = {"sheet": "Movement", "row_no": 3, "doc_no": "MOV-101", "material_code": "MAT-X",
"quantity": None, "movement_date": "", "source_code": "DBS-AWSBI"}
received = dict(VALID_MOVEMENT_ROW)
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[pending_zero_qty, pending_blank_qty, received])
# [断言意图] 只有真实收料行进入解析结果,在途行静默跳过且不阻断整文件。
assert [row.invoice_no for row in parsed] == ["MOV-001"]
def test_receiving_in_progress_rows_are_skipped():
"""收料执行中(Qty 已计数但日期未盖章)与未收料在途行同属无收料事实——一并跳过。"""
executing = {"sheet": "Movement", "row_no": 4, "doc_no": "MOV-200", "material_code": "MAT-X",
"quantity": "1", "movement_date": None, "source_code": "DBS-AWSBI"}
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[executing, dict(VALID_MOVEMENT_ROW)])
# [断言意图] 无日期行不参与预检也不阻断文件;ASN 完成后由下次抓取补齐。
assert [row.invoice_no for row in parsed] == ["MOV-001"]
def test_unparseable_date_still_fails():
"""日期有值但不可解析仍是数据损坏——跳过守卫不得吞掉真正的脏数据。"""
corrupted = dict(VALID_MOVEMENT_ROW, row_no=5, doc_no="MOV-300", movement_date="not-a-date")
with pytest.raises(ReceiptFileSchemaError) as exc_info:
parse_movement_rows(source_code="DBS-AWSBI", rows=[corrupted])
assert any("invalid_receipt_date" in error.get("reason", "")
for error in exc_info.value.details["rows"])
def test_datetime_cell_and_timed_string_dates_are_accepted():
"""Excel 日期单元格抽出 datetime 对象、字符串型日期常带时间部分——都必须取日期部分解析。"""
from datetime import datetime
datetime_cell = dict(VALID_MOVEMENT_ROW, row_no=8, doc_no="MOV-002",
movement_date=datetime(2026, 8, 26, 17, 38, 38))
timed_string = dict(VALID_MOVEMENT_ROW, row_no=9, doc_no="MOV-003",
movement_date="2026-09-08 00:00:00")
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[datetime_cell, timed_string])
# [断言意图] WMS 报表真实日期形态不能被 ISO 纯日期校验误杀。
assert [row.receipt_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)]
@@ -91,6 +91,21 @@ def test_erp_inventory_not_found_blocked(dbs_ready_file):
assert items["INV-002"].result == "blocked_inventory_not_found"
def test_erp_query_failure_degrades_to_blocked_item(dbs_ready_file):
"""ERP 网关故障(绑定缺失/连接失败等非超时异常)→ 单据级阻断,不得炸掉整个来源。"""
deps, erp, _ = _deps(dbs_ready_file)
erp.query_scenario = "error"
result = run_precheck(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
)
# [断言意图] ERP 基础设施故障必须降级为逐票 blocked_erp_query_failed:
# 来源保持 file_ready,发票全部带原因出现在列表里,而不是来源消失、预检全 0。
assert result.sources[0].stage == "file_ready"
assert result.items and all(item.result == "blocked_erp_query_failed" for item in result.items)
assert all("query_inventory" in item.reason for item in result.items)
assert result.summary.counts.blocked_count == len(result.items)
def test_missing_file_waits_without_erp():
"""缺文件 → 来源阶段 waiting_rpa_callback,无 ERP 调用。"""
deps, erp, _ = _deps()
@@ -145,6 +160,81 @@ def test_create_and_restore_precheck(transfer_db, dbs_ready_file):
assert restored_items["INV-001"].result == "executable"
# 落库数量与 DTO 一致(Decimal 文本持久化)
assert str(restored_items["INV-001"].to_quantity) == "1200"
# [断言意图] 收料日期与批号必须随明细恢复——聊天卡片收料日期/拨出批号/拨入批号列的数据来源。
assert restored_items["INV-001"].receipt_date == "2026-08-05"
assert restored_items["INV-001"].lot_no == "LOT-10"
assert restored_items["INV-002"].lot_no == "LOT-20"
def test_repeated_precheck_refreshes_instead_of_accumulating(transfer_db, dbs_ready_file):
"""同一数据重复预检 → 不新增异常行,原地刷新并挂到最新预检(累加缺陷回归防线)。"""
from app.models import TransferInvoiceItem, TransferPrecheck
deps, erp, _ = _deps(dbs_ready_file)
erp.query_scenario = "error" # 全部阻断:正是此前不断累加"可恢复异常"的场景
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
first_count = TransferInvoiceItem.query.count()
assert first_count == 2
# [断言意图] 第二次相同预检必须复用既有行(不出现 2×116 式累加),并挂到最新预检。
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
assert TransferInvoiceItem.query.count() == first_count
latest_precheck_id = TransferPrecheck.query.order_by(TransferPrecheck.id.desc()).first().id
assert all(row.precheck_id == latest_precheck_id for row in TransferInvoiceItem.query.all())
def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
"""同一批号(ASN)跨料号 → 按新聚合粒度拆分多行落库,不再撞 (预检,单号) 唯一约束。"""
deps, erp_fake, _rpa = make_transfer_deps(
{
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
"rows": [
{"sheet": "Movement", "row_no": 1, "doc_no": "RCP-1", "lot_no": "ASN-1",
"material_code": "M1", "material_name": "物料1",
"quantity": 5, "movement_date": "2026-09-16"},
{"sheet": "Movement", "row_no": 2, "doc_no": "RCP-2", "lot_no": "ASN-1",
"material_code": "M2", "material_name": "物料2",
"quantity": 7, "movement_date": "2026-09-16"},
],
},
routes={"DSV360_AWSDU": RouteMapping(erp_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
)
erp_fake.query_scenario = "error"
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
# [断言意图] 新唯一粒度 = (预检,来源,单号,料号,日期):同批号多料号必须共存于同一预检。
assert summary.counts.file_invoice_count == 2
def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file):
"""收料日期范围作为预检查询范围:范围外发票不进入明细。"""
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_inventory("INV-001", "1200")
erp.seed_inventory("INV-002", "1200")
summary = create_precheck(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
receipt_date_from="2026-08-05", receipt_date_to="2026-08-05",
)
assert summary.counts.file_invoice_count == 2
empty = create_precheck(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
receipt_date_from="2026-08-01", receipt_date_to="2026-08-04",
)
assert empty.counts.file_invoice_count == 0
def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file):
"""卡控:截止日期超出 D+1 规则(业务日期-1)必须拒绝。"""
from app.core.errors import ValidationError
deps, erp, _ = _deps(dbs_ready_file)
with pytest.raises(ValidationError) as exc_info:
create_precheck(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
receipt_date_from="2026-08-04", receipt_date_to="2026-08-06",
)
assert exc_info.value.code == "TRANSFER.RECEIPT_DATE_RANGE_INVALID"
def test_route_not_resolved_marks_source_failed(dbs_ready_file):
@@ -176,7 +266,7 @@ def test_run_precheck_consumes_movement_field_rows(app):
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
"rows": [{
"sheet": "Movement", "row_no": 1,
"doc_no": "INV-1", "material_code": "M1", "material_name": "物料1",
"doc_no": "INV-1", "lot_no": "LOT-1", "material_code": "M1", "material_name": "物料1",
"quantity": 5, "movement_date": "2026-09-16",
}],
},
@@ -70,7 +70,7 @@ def test_not_matured_not_queried(app, same_day_receipt_file):
def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file):
"""无绑定的来源(网关抛错)标记来源失败,不阻断整个预检。"""
"""无绑定(网关抛错)→ 该来源发票逐票阻断并带原因,其余来源照常执行。"""
class _SplitGateway:
"""按 Invoice 区分失败来源:DBS(INV-001/002)失败,CRANE(INV-008)成功。"""
@@ -90,7 +90,12 @@ def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06",
deps=deps, run_no="RUN-T",
)
# [断言意图] ERP 基础设施故障降级为逐票 blocked_erp_query_failed:
# 来源保持 file_ready,发票带原因可见,其余来源(CRANE)不受影响。
dbs_source = next(s for s in result.sources if s.source_code == "DBS-AWSBI")
assert dbs_source.stage == "failed"
assert dbs_source.stage == "file_ready"
dbs_items = [i for i in result.items if i.source_code == "DBS-AWSBI"]
assert dbs_items and all(i.result == "blocked_erp_query_failed" for i in dbs_items)
assert all("no binding for capability" in i.reason for i in dbs_items)
# CRANE 正常执行 → 出可执行项
assert any(i.invoice_no == "INV-008" and i.result == "executable" for i in result.items)
@@ -15,7 +15,7 @@ from app.core.errors import ValidationError
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer.manual_close_service import manual_close_item
from app.services.in_transit_transfer.precheck_service import create_precheck
from app.services.in_transit_transfer.retry_service import retry_item
from app.services.in_transit_transfer.retry_service import requery_items, retry_item
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
@@ -115,3 +115,26 @@ def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file):
db.session.commit()
with pytest.raises(ValidationError):
manual_close_item(item_id=item.id, reason="尝试关闭未知项")
def test_requery_items_refreshes_blocked_rows(transfer_db, dbs_ready_file):
"""批量重查:同预检全部可恢复阻断行逐票刷新,结果按行回报。"""
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
erp.seed_inventory("INV-001", "1200") # 人工在 ERP 修正库存
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
assert result["total"] == 1
row = result["results"][0]
assert row["ok"] is True
assert row["invoice_no"] == "INV-001"
assert row["status"] == "ready_to_execute"
def test_requery_items_invoice_filter_targets_only_given_rows(transfer_db, dbs_ready_file):
"""invoice_nos 限定范围:不在清单的阻断行不被触碰。"""
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
blocked = db.session.query(TransferInvoiceItem).filter_by(status="blocked_recoverable").all()
assert [i.invoice_no for i in blocked] == ["INV-001"]
result = requery_items(precheck_no=summary.precheck_id, deps=deps, invoice_nos=["INV-XXX"])
assert result["total"] == 0
assert _item_by_invoice("INV-001").status == "blocked_recoverable"
@@ -0,0 +1,54 @@
"""调拨路由解析器测试。
用途:验证 DefaultRouteResolver 的拨出/拨入仓库来源契约——
拨出仓库 = 仓库映射的货代仓库(必填),拨入仓库 = 映射的目标仓库代码。
依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。
逻辑:不再借用站点固定仓库(那是货代发货/库存导出链路的字段);
映射缺货代仓库时 fail-closed,拨出仓库无来源不得放行。
"""
from __future__ import annotations
import pytest
from app.extensions import db
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.deps import DefaultRouteResolver
def _seed_mapping(source: ShippingInventorySource, *, freight_warehouse_id: str | None) -> ShippingInventoryExternalMapping:
"""在既有种子站点上挂一条启用映射。"""
mapping = ShippingInventoryExternalMapping(
inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id,
external_system_code='TOPGP', external_organization_code='TGHX',
external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓', enabled=True,
)
db.session.add(mapping)
db.session.commit()
return mapping
def test_route_resolver_uses_mapping_freight_warehouse_as_from_warehouse(app):
"""拨出仓库必须取映射的货代仓库,而不是站点固定仓库。"""
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
# 种子站点 fixed_warehouse_id='AWSDU';断言取映射货代仓 'TZR2',证明不再借用固定仓。
_seed_mapping(source, freight_warehouse_id='TZR2')
route = DefaultRouteResolver().resolve(source_code='DSV360_AWSDU', invoice_no='INV-1')
assert route.from_warehouse == 'TZR2'
assert route.to_warehouse == 'HUB-CN01'
assert route.erp_org == 'TGHX'
def test_route_resolver_fails_closed_without_freight_warehouse(app):
"""映射未维护货代仓库 → 拨出仓库无来源,fail-closed。"""
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
_seed_mapping(source, freight_warehouse_id=None)
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError
with pytest.raises(RouteNotResolvedError):
DefaultRouteResolver().resolve(source_code='DSV360_AWSDU', invoice_no='INV-1')
@@ -346,7 +346,7 @@
<template v-else-if="activeTab === 'mappings'">
<label><span>{{ t('admin.shippingInventory.source') }}</span><select v-model.number="mapping.inventory_source_id" class="select-field" required><option :value="0">{{ t('admin.shippingInventory.chooseSource') }}</option><option v-for="item in sources" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.source_code }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.freightWarehouse') }}</span><input v-model="mapping.freight_warehouse_id" class="input-field" :placeholder="t('admin.shippingInventory.defaultMapping')"></label>
<label><span>{{ t('admin.shippingInventory.freightWarehouse') }}</span><input v-model="mapping.freight_warehouse_id" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.externalSystem') }}</span><input v-model="mapping.external_system_code" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.externalOrganization') }}</span><input v-model="mapping.external_organization_code" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.externalSite') }}</span><input v-model="mapping.external_site_code" class="input-field"></label>
@@ -746,7 +746,9 @@ const currentItems = computed<Item[]>(() => {
});
const compatibleProfiles = computed(() => profiles.value.filter((item) => item.connector_type === source.connector_type));
const selectedRuleStatus = computed(() => rules.value.find((item) => Number(item.id) === selectedId.value)?.status || 'draft');
const ruleReadOnly = computed(() => ['published', 'retired'].includes(selectedRuleStatus.value));
// 只读判定必须限定在规则页签:selectedId 是各页签共享的,站点 id 可能与规则 id 相同,
// 不加页签限定时已发布规则会让站点页签的保存按钮被误禁用(点击无任何请求)。
const ruleReadOnly = computed(() => activeTab.value === 'rules' && ['published', 'retired'].includes(selectedRuleStatus.value));
const selectedTemplateStatus = computed(() => excelTemplates.value.find((item) => Number(item.id) === selectedId.value)?.status || 'draft');
const selectedParsingStatus = computed(() => parsingProfiles.value.find((item) => Number(item.id) === selectedId.value)?.status || 'draft');
const parsingReadOnly = computed(() => activeTab.value === 'parsing' && ['published', 'retired'].includes(selectedParsingStatus.value));
@@ -1627,11 +1629,13 @@ function serialiseSourceInput(): string {
});
}
/** 将收料配置表单稳定序列化,作为统一保存与启用守卫的收料脏检查基线。 */
/** 将收料配置表单稳定序列化(含异动解析规则绑定),作为统一保存与启用守卫的收料脏检查基线。 */
function serialiseReceiptInput(): string {
return JSON.stringify({
report_path_json: receiptConfig.report_path_json,
query_parameters_json: receiptConfig.query_parameters_json,
// 异动解析绑定必须参与脏检查:否则只改绑定时统一保存会跳过收料配置提交,改动被静默丢弃。
parsing_profile_id: receiptConfig.parsing_profile_id ? Number(receiptConfig.parsing_profile_id) : null,
});
}
@@ -26,6 +26,8 @@ const jsonHeaders = () => ({ 'Content-Type': 'application/json', ...getAuthHeade
export interface CreatePrecheckPayload {
source_codes: string[];
business_date?: string;
receipt_date_from?: string;
receipt_date_to?: string;
}
/** 创建预检(只读) */
@@ -92,6 +94,21 @@ export const downloadTransferErpInventory = (runNo: string) =>
export const downloadTransferExceptions = (runNo: string) =>
requestBlob(`${BASE}/runs/${runNo}/exceptions.xlsx`, { headers: getAuthHeaders() });
/** 批量重查 ERP 库存(可恢复阻断行;invoice_nos 缺省 = 全部阻断行) */
export const requeryTransferItems = (precheckNo: string, invoiceNos?: string[]) =>
requestJson<{ precheck_no: string; total: number; results: Array<Record<string, unknown>> }>(
`${BASE}/prechecks/${precheckNo}/items/requery`,
{ method: 'POST', body: JSON.stringify(invoiceNos ? { invoice_nos: invoiceNos } : {}), headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' } },
);
/** 按选中来源打包下载各自最新归档收料文件(zip) */
export const downloadTransferSourceFiles = (sourceCodes: string[]) =>
requestBlob(`${BASE}/sources/receipt-files`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ source_codes: sourceCodes }),
});
/** 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级) */
export const listTransferBacklog = () =>
requestJson<TransferBacklogItem[]>(`${BASE}/backlog`, { headers: getAuthHeaders() });
@@ -103,6 +103,8 @@ const isTransferMessage = computed(
|| message.type === 'transfer-progress'
|| message.type === 'transfer-result',
);
/** 调拨消息带宽表格(预检明细 10+ 列),放宽气泡宽度上限避免横向挤压成局部布局。 */
const wideMessage = computed(() => isTransferMessage.value || isContractReviewMessage.value);
const isLeaveMessage = computed(() =>
message.type === 'leave-form'
@@ -709,8 +711,8 @@ function handleInlineDownload(file: InlineDownloadFile): void {
<template>
<div
:data-msg-index="index"
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
:class="message.role === 'user' ? 'justify-end' : 'justify-start'"
class="group mx-auto mb-6 flex w-full animate-slide-up"
:class="message.role === 'user' ? 'justify-end' : wideMessage ? 'max-w-[min(96vw,1500px)]' : 'max-w-4xl justify-start'"
>
<div
class="flex flex-col"
@@ -721,7 +723,7 @@ function handleInlineDownload(file: InlineDownloadFile): void {
class="text-[15px] leading-relaxed"
:class="message.role === 'user'
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
: isContractReviewMessage
: isContractReviewMessage || isTransferMessage
? 'w-full'
: shippingOrderExtractionState
? 'w-full'
@@ -118,8 +118,8 @@ function goBack() {
</div>
</template>
<!-- 子流程:复用自驱动的 TransferMessageView -->
<div v-else class="w-full max-w-4xl pr-2">
<!-- 子流程:复用自驱动的 TransferMessageView(预检宽表格需要全宽,上限对齐消息气泡宽布局) -->
<div v-else class="w-full max-w-[min(96vw,1500px)] pr-2">
<button
type="button"
data-testid="transfer-home-back"
@@ -16,6 +16,8 @@ import TransferBacklogSummaryCard from './TransferBacklogSummaryCard.vue';
import TransferManualCloseDialog from './TransferManualCloseDialog.vue';
import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
import { useChatTransfer } from '../../composables/useChatTransfer';
import { downloadTransferSourceFiles, getTransferPrecheck, requeryTransferItems } from '../../api/transfer.api';
import { triggerBlobDownload } from '@/shared/utils/download';
import { useMessage } from '@/shared/composables/useMessage';
import type {
TransferBacklogItem,
@@ -86,6 +88,40 @@ function applyPayload(payload?: Record<string, unknown> | null) {
applyPayload(props.payload);
watch(() => props.payload, applyPayload);
/** 打包下载选中来源的最新归档收料文件 */
async function onDownloadSources(sourceCodes: string[]) {
if (!sourceCodes.length) return;
busy.value = true;
try {
const result = await downloadTransferSourceFiles(sourceCodes);
triggerBlobDownload(result.blob, result.filename ?? `receipt-files-${sourceCodes.length}.zip`);
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
/** 重新获取 ERP 库存:批量重查后用服务端明细原位刷新(保留勾选中仍阻断的行) */
async function onRequery(invoiceNos: string[]) {
if (!invoiceNos.length || !transfer.precheckId.value) return;
busy.value = true;
try {
await requeryTransferItems(transfer.precheckId.value, invoiceNos);
const detail = await getTransferPrecheck(transfer.precheckId.value);
items.value = detail.items;
if (detail.summary) summaryRef.value = detail.summary;
const stillBlocked = new Set(
items.value.filter((item) => String(item.result).startsWith('blocked_')).map((item) => item.invoice_no),
);
transfer.selected.value = new Set([...transfer.selected.value].filter((no) => stillBlocked.has(no)));
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
/** 直接生成调拨单(决策 4/5:无独立确认页) */
async function onExecute(invoiceNos: string[]) {
busy.value = true;
@@ -159,11 +195,14 @@ async function onCloseConfirm(reason: string) {
}
}
/** 来源实例选择确认 → 创建预检并切换预检卡(决策 4:两步第一步) */
async function onSourceConfirm(sourceCodes: string[]) {
/** 来源实例选择确认 → 创建预检并切换预检卡(决策 4:两步第一步;收料日期范围为查询范围) */
async function onSourceConfirm(
sourceCodes: string[],
dateRange?: { from?: string; to?: string },
) {
busy.value = true;
try {
await transfer.createPrecheck(sourceCodes);
await transfer.createPrecheck(sourceCodes, undefined, dateRange);
mode.value = 'precheck';
summaryRef.value = transfer.precheck.value;
items.value = transfer.items.value;
@@ -206,6 +245,7 @@ async function onSourceRetry(sourceCodes: string[]) {
:busy="busy"
:retrying="retryingSource"
@confirm="onSourceConfirm"
@download="onDownloadSources"
@retry="onSourceRetry"
/>
<TransferPrecheckCard
@@ -213,8 +253,11 @@ async function onSourceRetry(sourceCodes: string[]) {
:summary="summaryRef"
:items="items"
:selected="transfer.selected.value"
:requery-busy="busy"
:busy="busy"
@toggle="(invoiceNo, checked) => transfer.toggleSelect(invoiceNo, checked)"
@toggle-all="(invoiceNos, checked) => invoiceNos.forEach((no) => transfer.toggleSelect(no, checked))"
@requery="onRequery"
@execute="onExecute"
/>
<TransferProgressCard v-else-if="mode === 'progress'" :run-no="runNo" :status="status" :busy="busy" />
@@ -6,7 +6,8 @@
emit execute(invoiceNos)(决策 4/5:无独立确认页)。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { computed, ref } from 'vue';
import { deriveBatchNo } from './transferBatch';
import type { TransferPrecheckItem, TransferPrecheckSummary } from '../../types/transfer.types';
const props = defineProps<{
@@ -14,11 +15,14 @@ const props = defineProps<{
items: TransferPrecheckItem[];
selected: Set<string>;
busy?: boolean;
requeryBusy?: boolean;
}>();
const emit = defineEmits<{
toggle: [invoiceNo: string, checked: boolean];
'toggle-all': [invoiceNos: string[], checked: boolean];
execute: [invoiceNos: string[]];
requery: [invoiceNos: string[]];
}>();
const selectedCount = computed(() =>
@@ -26,10 +30,57 @@ const selectedCount = computed(() =>
);
const executeDisabled = computed(() => props.busy || selectedCount.value === 0);
/** 筛选与全选状态(表格交互本地态,勾选集合仍由父级持有)。 */
const keyword = ref('');
const resultFilter = ref<'all' | 'executable' | 'blocked' | 'not_matured'>('all');
function isBlocked(item: TransferPrecheckItem): boolean {
return String(item.result).startsWith('blocked_');
}
/** 勾选可用范围:可执行(可生成调拨)或可恢复阻断(可重查 ERP)。 */
function isSelectable(item: TransferPrecheckItem): boolean {
return item.result === 'executable';
}
function isCheckable(item: TransferPrecheckItem): boolean {
return isSelectable(item) || isBlocked(item);
}
const filtered = computed(() =>
props.items.filter((item) => {
const kw = keyword.value.trim().toLowerCase();
if (kw) {
const haystack = [item.material_no, item.material_name, item.invoice_no, item.lot_no]
.map((value) => String(value ?? '').toLowerCase());
if (!haystack.some((value) => value.includes(kw))) return false;
}
if (resultFilter.value === 'executable' && item.result !== 'executable') return false;
if (resultFilter.value === 'blocked' && !isBlocked(item)) return false;
if (resultFilter.value === 'not_matured' && item.result !== 'not_matured') return false;
return true;
}),
);
const filteredInvoiceNos = computed(() => filtered.value.map((item) => item.invoice_no));
const allFilteredSelected = computed(() =>
filteredInvoiceNos.value.length > 0 && filteredInvoiceNos.value.every((no) => props.selected.has(no)),
);
const selectedBlockedCount = computed(() =>
filtered.value.filter((item) => isBlocked(item) && props.selected.has(item.invoice_no)).length,
);
function toggleAll(): void {
emit('toggle-all', filteredInvoiceNos.value, !allFilteredSelected.value);
}
function requerySelected(): void {
const nos = filtered.value
.filter((item) => isBlocked(item) && props.selected.has(item.invoice_no))
.map((item) => item.invoice_no);
if (nos.length) emit('requery', nos);
}
function isChecked(item: TransferPrecheckItem): boolean {
return props.selected.has(item.invoice_no);
}
@@ -78,19 +129,53 @@ function resultLabel(result: string): string {
</div>
</div>
<div class="overflow-x-auto">
<div class="mb-2 flex flex-wrap items-center gap-2">
<input
v-model="keyword"
type="text"
class="w-56 rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
:placeholder="$t('chat.transfer.filterPlaceholder')"
data-testid="transfer-precheck-filter"
/>
<select v-model="resultFilter" class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary" data-testid="transfer-precheck-result-filter">
<option value="all">{{ $t('chat.transfer.filterAll') }}</option>
<option value="executable">{{ $t('chat.transfer.resultExecutable') }}</option>
<option value="blocked">{{ $t('chat.transfer.resultBlocked') }}</option>
<option value="not_matured">{{ $t('chat.transfer.resultNotMatured') }}</option>
</select>
<button
type="button"
class="rounded-lg border border-brand-200 bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="props.requeryBusy || selectedBlockedCount === 0"
data-testid="transfer-precheck-requery-selected"
@click="requerySelected"
>
{{ $t('chat.transfer.requerySelected') }}{{ selectedBlockedCount ? `(${selectedBlockedCount})` : '' }}
</button>
</div>
<div class="overflow-x-auto">
<table class="w-full min-w-[1100px] text-xs" data-testid="transfer-precheck-table">
<thead>
<tr class="border-b border-default bg-surface-soft text-left text-[11px] text-muted">
<th class="p-2"></th>
<th class="p-2">
<input
type="checkbox"
:checked="allFilteredSelected"
data-testid="transfer-precheck-select-all"
@change="toggleAll"
/>
</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.colSpec') }}</th>
<th class="p-2">{{ $t('chat.transfer.colInvoice') }}</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.colToBatch') }}</th>
<th class="p-2">{{ $t('chat.transfer.colToQty') }}</th>
<th class="p-2">{{ $t('chat.transfer.colResult') }}</th>
</tr>
@@ -107,19 +192,22 @@ function resultLabel(result: string): string {
<input
type="checkbox"
:checked="isChecked(item)"
:disabled="!isSelectable(item) || busy"
:disabled="!isCheckable(item) || busy"
:data-testid="`transfer-check-${item.invoice_no}`"
@change="emit('toggle', item.invoice_no, ($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.specification }}</td>
<td class="p-2 font-semibold">{{ item.invoice_no }}</td>
<td class="p-2">{{ item.from_warehouse }}</td>
<td class="p-2">{{ deriveBatchNo(item.lot_no) }}</td>
<td class="p-2">{{ item.from_quantity ?? '—' }}</td>
<td class="p-2">{{ item.to_warehouse }}</td>
<td class="p-2">{{ deriveBatchNo(item.lot_no) }}</td>
<td class="p-2">{{ item.to_quantity }}</td>
<td class="p-2">
<span
@@ -132,6 +220,16 @@ function resultLabel(result: string): string {
>
{{ $t(resultLabel(item.result)) }}
</span>
<button
v-if="isBlocked(item)"
type="button"
class="ml-1 rounded border border-brand-200 px-1 text-[10px] font-bold text-brand-700 transition hover:bg-brand-50 disabled:opacity-40"
:disabled="props.requeryBusy"
:data-testid="`transfer-requery-${item.invoice_no}`"
@click="emit('requery', [item.invoice_no])"
>
{{ $t('chat.transfer.requeryRow') }}
</button>
</td>
</tr>
</tbody>
@@ -19,15 +19,19 @@ const props = defineProps<{
}>();
const emit = defineEmits<{
confirm: [sourceCodes: string[]];
confirm: [sourceCodes: string[], dateRange?: { from?: string; to?: string }];
/** 批量重试收料 RPA:传来源编码列表 */
retry: [sourceCodes: string[]];
download: [sourceCodes: string[]];
}>();
const { warning: notifyWarning } = useMessage();
const { t } = useI18n();
const selected = ref<Set<string>>(new Set());
/** 收料日期范围(预检查询范围);截止不得超出 D+1 规则(后端卡控)。 */
const dateFrom = ref('');
const dateTo = ref('');
const platforms = computed(() => [...new Set(props.sources.map((source) => source.platform))]);
const selectedCount = computed(() => selected.value.size);
@@ -50,6 +54,7 @@ const selectedHasReadyFile = computed(() =>
[...selected.value].some((code) => props.sources.find((s) => s.source_code === code)?.has_ready_file),
);
const confirmDisabled = computed(() => props.busy || selectedCount.value === 0 || !selectedHasReadyFile.value);
const downloadDisabled = computed(() => props.busy || !selectedHasReadyFile.value);
function toggle(sourceCode: string, checked: boolean) {
const next = new Set(selected.value);
@@ -96,6 +101,13 @@ function batchRetry() {
emit('retry', codes);
}
function downloadSelected(): void {
const codes = [...selected.value].filter(
(code) => props.sources.find((s) => s.source_code === code)?.has_ready_file,
);
if (codes.length) emit('download', codes);
}
function confirm() {
if (selectedCount.value === 0) {
notifyWarning(t('chat.transfer.needSelectSource'), t('chat.transfer.sourceSelectTitle'));
@@ -105,7 +117,7 @@ function confirm() {
notifyWarning(t('chat.transfer.needReadyFile'), t('chat.transfer.sourceSelectTitle'));
return;
}
emit('confirm', [...selected.value]);
emit('confirm', [...selected.value], { from: dateFrom.value || undefined, to: dateTo.value || undefined });
}
</script>
@@ -142,6 +154,36 @@ function confirm() {
>
{{ $t('chat.transfer.batchRetry') }}
</button>
<button
type="button"
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft disabled:opacity-50"
:disabled="busy || downloadDisabled"
data-testid="transfer-source-download"
@click="downloadSelected"
>
{{ $t('chat.transfer.downloadFiles') }}
</button>
<div class="ml-auto flex flex-wrap items-center gap-2">
<label class="flex items-center gap-1 text-xs text-secondary">
<span>{{ $t('chat.transfer.receiptDateFrom') }}</span>
<input
v-model="dateFrom"
type="date"
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
data-testid="transfer-source-date-from"
/>
</label>
<label class="flex items-center gap-1 text-xs text-secondary">
<span>~</span>
<input
v-model="dateTo"
type="date"
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
data-testid="transfer-source-date-to"
/>
</label>
<span class="text-xs text-muted">{{ $t('chat.transfer.receiptDateHint') }}</span>
</div>
<button
type="button"
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft disabled:opacity-50"
@@ -0,0 +1,27 @@
/**
* features/chat/components/messages/transferBatch.spec.ts
* 用途:覆盖批号转换规则。
* 依赖:transferBatch、vitest。
* 逻辑:WTP 前缀替换为 HOW;其余原样;空值安全。
*/
import { describe, expect, it } from 'vitest';
import { deriveBatchNo } from './transferBatch';
describe('transferBatch', () => {
it('replaces WTP prefix with HOW and keeps the rest', () => {
expect(deriveBatchNo('WTP26082728')).toBe('HOW26082728');
expect(deriveBatchNo('wtp26082728')).toBe('HOW26082728');
});
it('returns non-WTP values unchanged', () => {
expect(deriveBatchNo('HS000131')).toBe('HS000131');
expect(deriveBatchNo('4294235')).toBe('4294235');
});
it('returns empty string for empty input', () => {
expect(deriveBatchNo('')).toBe('');
expect(deriveBatchNo(null)).toBe('');
expect(deriveBatchNo(undefined)).toBe('');
});
});
@@ -0,0 +1,14 @@
/**
* features/chat/components/messages/transferBatch.ts
* 用途:在途调拨批号转换规则(拨出/拨入批号展示)。
* 依赖:无。
* 逻辑:原批号以 WTP 开头时替换前缀为 HOW 获得真实批号;其余规则不变、原样展示。
*/
/** 原批号(如 WMS 的 WTP26082728)→ 真实批号(HOW26082728);空值/非 WTP 原样返回。 */
export function deriveBatchNo(lotNo: string | null | undefined): string {
const value = String(lotNo ?? '').trim();
if (!value) return '';
if (value.toUpperCase().startsWith('WTP')) return `HOW${value.slice(3)}`;
return value;
}
@@ -60,11 +60,20 @@ export function useChatTransfer() {
const estimatedQuantity = computed(() => precheck.value?.estimated_transfer_quantity ?? '0');
/** 创建预检(缺文件时来源级阶段展示等待/失败) */
async function createPrecheck(sourceCodes: string[], businessDate?: string) {
async function createPrecheck(
sourceCodes: string[],
businessDate?: string,
dateRange?: { from?: string; to?: string },
) {
busy.value = true;
error.value = '';
try {
const summary = await createTransferPrecheck({ source_codes: sourceCodes, business_date: businessDate });
const summary = await createTransferPrecheck({
source_codes: sourceCodes,
business_date: businessDate,
receipt_date_from: dateRange?.from,
receipt_date_to: dateRange?.to,
});
precheckId.value = summary.precheck_id;
await refreshPrecheck();
return summary;
@@ -50,6 +50,7 @@ export interface TransferPrecheckItem {
reason?: string;
erp_document_no?: string | null;
raw_lines?: TransferRawLine[];
lot_no?: string;
}
/** 来源实例级进度(决策 18:来源隔离展示) */
+1 -2
View File
@@ -844,7 +844,6 @@
"exportsHelp": "Read-only inventory export results. Retries and manual exports are not initiated here.",
"externalMappings": "Warehouse Mapping",
"mappingsHelp": "Map a freight warehouse, or a source default, to an external system warehouse code.",
"defaultMapping": "Source Default Mapping",
"loadFailed": "Failed to load shipping inventory configuration",
"createNew": "New",
"saving": "Saving...",
@@ -1053,7 +1052,7 @@
"publishedImmutable": "Published rules are retained as immutable audit definitions. Create and publish a new rule instead.",
"source": "Inventory Source",
"chooseSource": "Select an inventory source",
"freightWarehouse": "Freight Warehouse (optional)",
"freightWarehouse": "Freight Warehouse",
"externalSystem": "Target system",
"externalOrganization": "Target organization (optional)",
"externalSite": "Target site (optional)",
+11
View File
@@ -3716,9 +3716,19 @@
"colName": "Name",
"colSpec": "Spec",
"colInvoice": "Invoice",
"colReceiptDate": "Receipt Date",
"colFromWarehouse": "From warehouse",
"colFromQty": "From qty",
"colToWarehouse": "To warehouse",
"colFromBatch": "Outbound Batch",
"colToBatch": "Inbound Batch",
"filterPlaceholder": "Filter by material / name / Invoice / batch",
"filterAll": "All results",
"requerySelected": "Requery selected ERP stock",
"receiptDateFrom": "Receipt date from",
"receiptDateTo": "Receipt date to",
"receiptDateHint": "End cannot exceed the D+1 rule (day before business date)",
"requeryRow": "Requery",
"colToQty": "To qty",
"colResult": "Result",
"resultExecutable": "Executable",
@@ -3788,6 +3798,7 @@
"selectVisible": "Select visible",
"selectRetryable": "Select retryable",
"batchRetry": "Batch retry RPA",
"downloadFiles": "Download receipt files",
"selectedRetryableCount": "{count} retryable",
"noRetryable": "No selected source needs retry (already ready or fetching)"
}
+1 -2
View File
@@ -844,7 +844,6 @@
"exportsHelp": "ดูผลการส่งออกสต็อกแบบอ่านอย่างเดียว ไม่สั่งส่งออกหรือทดลองใหม่ที่นี่",
"externalMappings": "การแมปคลัง",
"mappingsHelp": "แมปคลังของผู้ให้บริการขนส่ง หรือคลังเริ่มต้นของแหล่งข้อมูล ไปยังรหัสคลังของระบบภายนอก",
"defaultMapping": "การแมปเริ่มต้นของแหล่งข้อมูล",
"loadFailed": "โหลดการตั้งค่าสินค้าคงคลังขนส่งไม่สำเร็จ",
"createNew": "สร้างใหม่",
"saving": "กำลังบันทึก...",
@@ -1053,7 +1052,7 @@
"publishedImmutable": "กฎที่เผยแพร่จะถูกเก็บเป็นคำนิยามตรวจสอบที่แก้ไขไม่ได้ โปรดสร้างและเผยแพร่กฎใหม่แทน",
"source": "แหล่งสต็อก",
"chooseSource": "เลือกแหล่งสต็อก",
"freightWarehouse": "คลังผู้ให้บริการ (ไม่บังคับ)",
"freightWarehouse": "คลังผู้ให้บริการ",
"externalSystem": "ระบบปลายทาง",
"externalOrganization": "องค์กรปลายทาง (ไม่บังคับ)",
"externalSite": "สถานที่ปลายทาง (ไม่บังคับ)",
+11
View File
@@ -3716,9 +3716,19 @@
"colName": "ชื่อ",
"colSpec": "สเปก",
"colInvoice": "Invoice",
"colReceiptDate": "วันที่รับสินค้า",
"colFromWarehouse": "คลังต้นทาง",
"colFromQty": "จำนวนต้นทาง",
"colToWarehouse": "คลังปลายทาง",
"colFromBatch": "ล็อตต้นทาง",
"colToBatch": "ล็อตปลายทาง",
"filterPlaceholder": "กรองตามรหัสวัสดุ / ชื่อ / Invoice / ล็อต",
"filterAll": "ทุกผลลัพธ์",
"requerySelected": "ตรวจซ้ำ ERP ที่เลือก",
"receiptDateFrom": "วันที่รับสินค้าจาก",
"receiptDateTo": "วันที่รับสินค้าถึง",
"receiptDateHint": "วันสิ้นสุดต้องไม่เกินกฎ D+1 (วันก่อนวันทำการ)",
"requeryRow": "ตรวจซ้ำ",
"colToQty": "จำนวนปลายทาง",
"colResult": "ผลตรวจ",
"resultExecutable": "ดำเนินการได้",
@@ -3788,6 +3798,7 @@
"selectVisible": "เลือกที่เห็นทั้งหมด",
"selectRetryable": "เลือกที่ลองใหม่ได้",
"batchRetry": "ลองใหม่เป็นชุด",
"downloadFiles": "ดาวน์โหลดไฟล์การรับสินค้า",
"selectedRetryableCount": "ลองใหม่ได้ {count} รายการ",
"noRetryable": "ไม่มีแหล่งที่เลือกต้องลองใหม่ (พร้อมแล้วหรือกำลังดึง)"
}
+1 -2
View File
@@ -973,7 +973,6 @@
"exportsHelp": "只读查看库存导出的执行结果;不在此处重试或触发导出。",
"externalMappings": "仓库映射",
"mappingsHelp": "将货代仓库或库存源默认仓库映射到外部系统仓库编码。",
"defaultMapping": "库存源默认映射",
"loadFailed": "加载货代库存配置失败",
"createNew": "新建",
"saving": "保存中...",
@@ -1182,7 +1181,7 @@
"publishedImmutable": "已发布规则作为审计定义保留,不能修改。请新建规则后重新发布。",
"source": "库存源",
"chooseSource": "请选择库存源",
"freightWarehouse": "货代仓库(可选)",
"freightWarehouse": "货代仓库",
"externalSystem": "目标系统",
"externalOrganization": "目标组织(可选)",
"externalSite": "目标地点(可选)",
+11
View File
@@ -3790,9 +3790,19 @@
"colName": "品名",
"colSpec": "规格",
"colInvoice": "Invoice",
"colReceiptDate": "收料日期",
"colFromWarehouse": "拨出仓库",
"colFromQty": "拨出数量",
"colToWarehouse": "拨入仓库",
"colFromBatch": "拨出批号",
"colToBatch": "拨入批号",
"filterPlaceholder": "按料号 / 品名 / Invoice / 批号筛选",
"filterAll": "全部结果",
"requerySelected": "重查选中 ERP 库存",
"receiptDateFrom": "收料日期起",
"receiptDateTo": "收料日期止",
"receiptDateHint": "截止不超出 D+1 规则(业务日期前一天)",
"requeryRow": "重查",
"colToQty": "拨入数量",
"colResult": "预检结果",
"resultExecutable": "可执行",
@@ -3862,6 +3872,7 @@
"selectVisible": "全选可见",
"selectRetryable": "只选可重试",
"batchRetry": "批量重试 RPA",
"downloadFiles": "下载收料文件",
"selectedRetryableCount": "其中 {count} 个可重试",
"noRetryable": "所选来源均无需重试(已就绪或抓取中)"
}
+1 -2
View File
@@ -844,7 +844,6 @@
"exportsHelp": "唯讀查看庫存匯出的執行結果;此處不重試或觸發匯出。",
"externalMappings": "倉庫映射",
"mappingsHelp": "將貨代倉庫或庫存來源預設倉庫對應至外部系統倉庫編碼。",
"defaultMapping": "庫存來源預設對應",
"loadFailed": "載入貨代庫存設定失敗",
"createNew": "新增",
"saving": "儲存中...",
@@ -1053,7 +1052,7 @@
"publishedImmutable": "已發布規則作為稽核定義保留,不能修改。請新增規則後重新發布。",
"source": "庫存來源",
"chooseSource": "請選擇庫存來源",
"freightWarehouse": "貨代倉庫(可選)",
"freightWarehouse": "貨代倉庫",
"externalSystem": "目標系統",
"externalOrganization": "目標組織(可選)",
"externalSite": "目標地點(可選)",
+11
View File
@@ -3716,9 +3716,19 @@
"colName": "品名",
"colSpec": "規格",
"colInvoice": "Invoice",
"colReceiptDate": "收料日期",
"colFromWarehouse": "撥出倉庫",
"colFromQty": "撥出數量",
"colToWarehouse": "撥入倉庫",
"colFromBatch": "撥出批號",
"colToBatch": "撥入批號",
"filterPlaceholder": "按料號 / 品名 / Invoice / 批號篩選",
"filterAll": "全部結果",
"requerySelected": "重查選中 ERP 庫存",
"receiptDateFrom": "收料日期起",
"receiptDateTo": "收料日期止",
"receiptDateHint": "截止不超出 D+1 規則(業務日期前一天)",
"requeryRow": "重查",
"colToQty": "撥入數量",
"colResult": "預檢結果",
"resultExecutable": "可執行",
@@ -3788,6 +3798,7 @@
"selectVisible": "全選可見",
"selectRetryable": "只選可重試",
"batchRetry": "批次重試 RPA",
"downloadFiles": "下載收料文件",
"selectedRetryableCount": "其中 {count} 個可重試",
"noRetryable": "所選來源均無需重試(已就緒或抓取中)"
}