fix(shipping-notice): 修复调拨预检全 0 及筛选重查系列缺陷

- movement 表头反查改一列对多字段,doc_no/lot_no 共用 External ASN # 列不再互相覆盖,修复 CRANE 预检全 0
- 来源级失败事实落库 source_job 并经 restore 回读,预检卡片透出失败横幅(四语言)
- 明细表渲染切 filtered 并将行键升为拆票四元组(来源|Invoice|料号|收料日期),筛选真正生效且无重复 key 残影
- 移除规格/拨入批号列,拨出数量更名库存数量,清理孤儿 i18n 键 colToBatch
- requery 端点补用户上下文修复 NameError 500;ERP 网关/绑定故障逐票降级,不再抛全局错误弹窗
- 回归测试:同列双字段提取、失败落库可见、requery 冒烟、同票多行筛选、ERP 绑定缺失降级
This commit is contained in:
hugo committed 2026-09-21 21:23:20 +08:00
1 parent 1ba38e1685
commit 881863478e
16 files changed
+279 -40

No files matched your search

@@ -114,7 +114,11 @@ def _extract_movement_rows(
headers = [str(c or '').strip() for c in raw_rows[header_idx]]
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
header_to_code: dict[str, list[str]] = {}
for code, alias in field_mapping.items():
# 一个表头别名可被多个领域字段共用(如 CRANE 单号/批号同源 ASN 列);
# 反查必须是 一别名→多字段,不得互相覆盖。
header_to_code.setdefault(str(alias).strip(), []).append(str(code).strip())
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
@@ -126,11 +130,16 @@ def _extract_movement_rows(
]
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。"""
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, list[str]]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。
header_to_code 为 一别名→多字段 列表:共用同一表头别名的字段
(如 doc_no 与 lot_no 同源一列)各自都写入该单元格值,互不覆盖。
"""
output: dict[str, Any] = {}
for index, header in enumerate(headers):
code = header_to_code.get(header)
if code and index < len(row):
output[code] = row[index]
codes = header_to_code.get(header)
if codes and index < len(row):
for code in codes:
output[code] = row[index]
return output
@@ -475,6 +475,8 @@ def create_precheck(
run_id=run.id,
source_code=job_source.source_code,
status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending',
error_code=job_source.error_code,
error_message=job_source.error_message,
)
precheck_no = _generate_no("TPC", business_date)
@@ -638,6 +640,8 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
file_no=job.file_no,
file_version=None,
checksum=job.file_sha256,
error_code=job.error_code,
error_message=job.error_message,
)
for job in (precheck.run.source_jobs if precheck.run else [])
] or [
@@ -17,7 +17,11 @@ from app.core.errors import NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.precheck_service import RESULT_EXECUTABLE, TransferDeps
from app.services.in_transit_transfer.precheck_service import (
RESULT_ERP_QUERY_FAILED,
RESULT_EXECUTABLE,
TransferDeps,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
RETRY_KIND_ERP_RECHECK = "erp_recheck"
@@ -33,16 +37,6 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
receipt_qty = Decimal(item.receipt_quantity)
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=item.run.run_no if item.run else "RUN-PENDING",
attempt_no=item.attempt_no + 1,
invoice_no=item.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
item.attempt_no += 1
before_status = item.status
attempt = TransferAttempt(
@@ -56,6 +50,44 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
)
db.session.add(attempt)
db.session.flush()
# [降级] 与 precheck 逐票语义一致:ERP 网关/绑定故障(如集成连接器缺绑定
# BindingNotFoundError)记为该行 blocked_erp_query_failed + 原因,
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
try:
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=item.run.run_no if item.run else "RUN-PENDING",
attempt_no=item.attempt_no,
invoice_no=item.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
except Exception as exc: # noqa: BLE001
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = RESULT_ERP_QUERY_FAILED
item.result_message = f"erp query failed: {detail}"
attempt.status = "failed"
attempt.completed_at = datetime.utcnow()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_RECHECKED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="failure",
before={"status": before_status},
after={"status": item.status, "attempt_no": item.attempt_no, "error": detail},
))
db.session.flush()
return item.status
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch"
@@ -156,4 +188,8 @@ def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str
except (ValidationError, NotFoundError) as exc:
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": False, "error": exc.message})
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:任何单行异常不炸整批
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": False,
"error": str(exc).strip() or exc.__class__.__name__})
return {"precheck_no": precheck_no, "total": len(items), "results": results}
@@ -21,13 +21,22 @@ SOURCE_JOB_STATUSES = (
)
def create_source_job(*, run_id: int, source_code: str, status: str = 'pending') -> TransferSourceJob:
def create_source_job(
*,
run_id: int,
source_code: str,
status: str = 'pending',
error_code: str | None = None,
error_message: str | None = None,
) -> TransferSourceJob:
"""为一次 run 创建一条来源级 job;(run_id, source_code) 唯一由模型约束。
Args:
run_id: 所属 TransferRun.id。
source_code: 来源实例编码。
status: 初始状态。
error_code / error_message: 来源级失败事实(如解析失败 error_code),
随创建落库,保证刷新/恢复后失败原因仍可见(不静默丢成全 0)。
Returns:
新建(或复用已存在同 run 同来源)的 TransferSourceJob。
"""
@@ -36,7 +45,13 @@ def create_source_job(*, run_id: int, source_code: str, status: str = 'pending')
)
if existing is not None:
return existing
job = TransferSourceJob(run_id=run_id, source_code=source_code, status=status)
job = TransferSourceJob(
run_id=run_id,
source_code=source_code,
status=status,
error_code=error_code,
error_message=error_message,
)
db.session.add(job)
db.session.flush()
return job