""" scripts/freight_rpa/receipt/receipt_excel_empty.py 用途:收料 Excel「有表头无明细」判空(真相源,对齐库存 Excel 判空)。 依赖:openpyxl(运行期可选;缺失时不强制 empty)。 逻辑:receipt_rpa_worker 落盘校验后调用;标题行(如 AWS Receipt Detail) 不得当成表头,否则真表头会被误判为明细导致假 success。 """ from __future__ import annotations from pathlib import Path class NoReceiptDataError(RuntimeError): """收料报表可打开且有表头,但无业务明细行(合法 empty / no_receipt_data)。""" def _normalize_row_joined(row: tuple | list) -> str: """ 将一行单元格规范为小写比较串。 核心逻辑:换行压成空格(SSRS 表头常为 External\\nASN #),去空白后用 | 拼接。 """ parts: list[str] = [] for cell in row: if cell is None: continue text = ' '.join(str(cell).replace('\n', ' ').replace('\r', ' ').split()).strip() if text: parts.append(text.lower()) return ' | '.join(parts) def is_receipt_excel_header_row(joined: str) -> bool: """ 判断是否为收料列标题行(非报表标题行)。 核心逻辑:要求 External ASN / WMS Receipt / Supplier ID+AWS Sku 等组合特征; 单独含 receipt(如「AWS Receipt Detail」)不得命中。 """ if not joined: return False if 'external asn' in joined and ( 'wms receipt' in joined or 'aws sku' in joined or 'supplier id' in joined or 'supplier' in joined ): return True if 'warehouse' in joined and 'external asn' in joined: return True if 'supplier id' in joined and 'aws sku' in joined: return True return False def receipt_excel_has_detail_rows(path: Path) -> bool | None: """ 判断收料 Excel 列标题之后是否有明细行。 核心逻辑:先定位严格表头行,再扫描其后非空行;无法识别表头时返回 None (不强制 empty,由结构校验兜底)。 Returns: True: 有明细;False: 有表头无明细;None: 未识别表头形态。 """ try: from openpyxl import load_workbook except ImportError: return None try: workbook = load_workbook(path, read_only=True, data_only=True) except Exception: return None try: worksheet = workbook.active if worksheet is None: return None header_idx: int | None = None for idx, row in enumerate(worksheet.iter_rows(max_row=120, values_only=True), start=1): joined = _normalize_row_joined(row or ()) if not joined: continue if header_idx is None: if is_receipt_excel_header_row(joined): header_idx = idx continue if idx > header_idx: return True if header_idx is None: return None return False finally: workbook.close() def enforce_receipt_excel_not_empty(path: Path) -> None: """ 有表头无明细时记为无收料(NoReceiptDataError → empty / no_receipt_data)。 Raises: NoReceiptDataError: 可识别表头但无业务行;message 固定为 no_receipt_data。 """ if receipt_excel_has_detail_rows(path) is False: raise NoReceiptDataError('no_receipt_data')