""" backend/app/services/voucher_check/share_scanner.py 用途:共享盘健康检查、路径构造、目录枚举与精确文件名匹配。 依赖:config、fingerprint、core.errors.ServiceUnavailableError / ValidationError。 逻辑:runner 阶段 A 调用;健康失败整批失败;单票目录缺失记业务缺资料。 """ from __future__ import annotations import os from dataclasses import dataclass, field from datetime import date from pathlib import Path from app.core.errors import ServiceUnavailableError, ValidationError from app.services.voucher_check.config import ( RequiredFileRule, VoucherCheckConfig, resolve_share_root, ) from app.services.voucher_check.fingerprint import build_material_fingerprint @dataclass class FileMeta: """直接子文件元数据。""" name: str size: int mtime_ns: int @dataclass class InvoiceScanResult: """单票扫描结果。""" invoice_no: str folder_path: str absolute_path: str folder_exists: bool material_fingerprint: str | None matched_files: dict[str, str] = field(default_factory=dict) missing_materials: list[dict[str, str]] = field(default_factory=list) result: str = "missing" # complete / missing / technical_error error_code: str | None = None error_message: str | None = None def ensure_share_healthy(config: VoucherCheckConfig) -> str: """ 校验共享盘根目录可用。 核心逻辑:根存在、可 scandir、健康标记文件存在;失败抛 SHARE_UNAVAILABLE。 Returns: 解析后的绝对根路径。 """ root = resolve_share_root(config) root_path = Path(root) try: if not root_path.exists() or not root_path.is_dir(): raise ServiceUnavailableError( "共享盘根目录不可用", code="VOUCHER_CHECK.SHARE_UNAVAILABLE", ) # [STEP 1] 轻量枚举证明 I/O 可用 with os.scandir(root_path) as it: _ = next(it, None) root_path.stat() # [STEP 2] 健康标记:避免挂载丢失后空目录被误判为业务缺件 marker = (root_path / config.healthcheck_relative_path).resolve() if not str(marker).startswith(str(root_path.resolve())): raise ServiceUnavailableError( "共享盘健康标记路径非法", code="VOUCHER_CHECK.SHARE_UNAVAILABLE", ) if not marker.is_file(): raise ServiceUnavailableError( "共享盘健康标记文件缺失", code="VOUCHER_CHECK.SHARE_UNAVAILABLE", ) except ServiceUnavailableError: raise except OSError as exc: raise ServiceUnavailableError( "共享盘健康检查失败", code="VOUCHER_CHECK.SHARE_UNAVAILABLE", details={"error_type": type(exc).__name__}, ) from exc return str(root_path) def _render_invoice_relative_path( template: str, *, year: str, month: str, invoice_no: str, ) -> str: """渲染相对业务路径(不含 root 实际值,报告用)。""" rendered = ( template.replace("{root}", "vouche") .replace("{YYYY}", year) .replace("{MM}", month) .replace("{invoice_no}", invoice_no) ) return rendered.strip("/").replace("\\", "/") def build_invoice_absolute_path( config: VoucherCheckConfig, *, root: str, period_month: date, invoice_no: str, ) -> tuple[str, str]: """ 构造单票绝对路径与相对业务路径。 核心逻辑:invoice_no 仅 trim;含路径分隔符则视为非法(调用方记 technical_error)。 """ year = f"{period_month.year:04d}" month = f"{period_month.month:02d}" invoice = str(invoice_no or "").strip() if not invoice or "/" in invoice or "\\" in invoice or "\x00" in invoice or ".." in invoice: raise ValidationError( "发票号含非法路径字符", code="VOUCHER_CHECK.INVOICE_PATH_INVALID", details={"invoice_no": invoice_no}, ) relative = _render_invoice_relative_path( config.directory_template, year=year, month=month, invoice_no=invoice, ) # 实际落盘:用真实 root 替换模板中的 {root} absolute_template = ( config.directory_template.replace("{root}", root.rstrip("/\\")) .replace("{YYYY}", year) .replace("{MM}", month) .replace("{invoice_no}", invoice) ) absolute = str(Path(absolute_template)) resolved_root = Path(root).resolve() resolved_abs = Path(absolute).resolve() try: resolved_abs.relative_to(resolved_root) except ValueError as exc: raise ValidationError( "发票目录逃逸共享根", code="VOUCHER_CHECK.INVOICE_PATH_INVALID", details={"invoice_no": invoice}, ) from exc return absolute, relative def list_direct_files(folder: Path) -> list[FileMeta]: """枚举发票目录直接子文件(忽略子目录与非普通文件)。""" files: list[FileMeta] = [] if not folder.is_dir(): return files with os.scandir(folder) as it: for entry in it: try: if not entry.is_file(follow_symlinks=False): continue stat = entry.stat(follow_symlinks=False) files.append( FileMeta( name=entry.name, size=int(stat.st_size), mtime_ns=int(getattr(stat, "st_mtime_ns", int(stat.st_mtime * 1_000_000_000))), ) ) except OSError: continue return files def match_required_files( files: list[FileMeta], rules: tuple[RequiredFileRule, ...], *, case_sensitive: bool, ) -> tuple[dict[str, str], list[dict[str, str]]]: """ 按完整文件名精确匹配必检材料。 核心逻辑:任一候选命中即算该材料存在;不支持模糊/前缀匹配。 """ if case_sensitive: available = {f.name: f.name for f in files} else: available = {f.name.lower(): f.name for f in files} matched: dict[str, str] = {} missing: list[dict[str, str]] = [] for rule in rules: if not rule.required: continue hit: str | None = None for candidate in rule.accepted_filenames: key = candidate if case_sensitive else candidate.lower() if key in available: hit = available[key] break if hit: matched[rule.code] = hit else: missing.append({"code": rule.code, "name": rule.name}) return matched, missing def scan_invoice_folder( config: VoucherCheckConfig, *, root: str, period_month: date, invoice_no: str, ) -> InvoiceScanResult: """ 扫描单票目录并判定齐全/缺资料。 核心逻辑:目录不存在→missing;存在则精确匹配必检文件名并生成指纹。 """ try: absolute, relative = build_invoice_absolute_path( config, root=root, period_month=period_month, invoice_no=invoice_no, ) except ValidationError as exc: return InvoiceScanResult( invoice_no=str(invoice_no or "").strip(), folder_path="", absolute_path="", folder_exists=False, material_fingerprint=None, result="technical_error", error_code=exc.code, error_message=exc.message, ) folder = Path(absolute) if not folder.exists() or not folder.is_dir(): missing = [{"code": r.code, "name": r.name} for r in config.required_files if r.required] return InvoiceScanResult( invoice_no=str(invoice_no).strip(), folder_path=relative, absolute_path=absolute, folder_exists=False, material_fingerprint=None, missing_materials=missing, result="missing", ) files = list_direct_files(folder) fingerprint = build_material_fingerprint([(f.name, f.size, f.mtime_ns) for f in files]) matched, missing = match_required_files( files, config.required_files, case_sensitive=config.filename_case_sensitive, ) return InvoiceScanResult( invoice_no=str(invoice_no).strip(), folder_path=relative, absolute_path=absolute, folder_exists=True, material_fingerprint=fingerprint, matched_files=matched, missing_materials=missing, result="complete" if not missing else "missing", )