Files
syops/backend/app/services/voucher_check/filename_match.py
T
2026-09-07 11:13:33 +08:00

90 lines
2.8 KiB
Python

"""
backend/app/services/voucher_check/filename_match.py
用途:按 Profile 命名模板匹配文档库文件名,并校验文件名中的 invoice。
依赖:标准库 re。
逻辑:{invoice} 替换为当前票号;其余 {token} 视为一段非路径字符;禁止路径穿越。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
_PLACEHOLDER_RE = re.compile(r"\{([^{}]+)\}")
_UNSAFE_RE = re.compile(r"[/\\\x00]|(\.\.)")
@dataclass(frozen=True)
class FilenameMatch:
"""单次文件名命中。"""
filename: str
groups: dict[str, str]
def compile_filename_pattern(template: str, *, invoice_no: str) -> re.Pattern[str]:
"""
把命名模板编译为整名匹配正则。
核心逻辑:先替换 invoice,再把剩余占位符变成捕获组,字面量全部转义。
Args:
template: 如 `{invoice}-{order_no}.pdf`。
invoice_no: 当前发票号,禁止含路径字符。
Returns:
锚定的正则。
Raises:
ValueError: 模板或发票号非法。
"""
invoice = str(invoice_no or "").strip()
if not invoice or _UNSAFE_RE.search(invoice):
raise ValueError("invoice_no 非法")
text = str(template or "").strip()
if not text or _UNSAFE_RE.search(_PLACEHOLDER_RE.sub("", text)):
raise ValueError("filename_template 非法")
parts: list[str] = []
cursor = 0
for match in _PLACEHOLDER_RE.finditer(text):
parts.append(re.escape(text[cursor : match.start()]))
name = match.group(1)
if name in {"invoice", "invoice号"}:
parts.append(re.escape(invoice))
else:
parts.append(rf"(?P<{re.escape(name)}>[^/\\]+)")
cursor = match.end()
parts.append(re.escape(text[cursor:]))
return re.compile(r"^" + "".join(parts) + r"$")
def match_filename(filename: str, *, template: str, invoice_no: str) -> FilenameMatch | None:
"""
判断文件名是否属于该 invoice 的规则。
核心逻辑:整名匹配;命中后要求文件名包含 invoice 原文。
"""
name = str(filename or "").strip()
if not name:
return None
try:
pattern = compile_filename_pattern(template, invoice_no=invoice_no)
except ValueError:
return None
matched = pattern.match(name)
if not matched:
return None
invoice = str(invoice_no).strip()
if invoice not in name:
return None
return FilenameMatch(filename=name, groups=matched.groupdict())
def first_match(filenames: list[str], *, template: str, invoice_no: str) -> FilenameMatch | None:
"""在文件名列表中返回第一条命中,保持目录返回顺序。"""
for name in filenames:
hit = match_filename(name, template=template, invoice_no=invoice_no)
if hit is not None:
return hit
return None