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