""" backend/app/services/voucher_check/config.py 用途:解析立账凭证检核环境变量与 ScheduleTask.job_params,校验目录模板与文件名规则。 依赖:Flask current_app.config、core.errors.ValidationError。 逻辑:runner / share_scanner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID。 """ from __future__ import annotations import json import os import re from dataclasses import dataclass from typing import Any from flask import has_app_context, current_app from app.core.errors import ValidationError _ALLOWED_TEMPLATE_KEYS = {"root", "YYYY", "MM", "invoice_no"} _TEMPLATE_TOKEN_RE = re.compile(r"\{([^{}]+)\}") _UNSAFE_FILENAME_RE = re.compile(r"[/\\\x00]|(\.\.)") DEFAULT_REQUIRED_FILES: list[dict[str, Any]] = [ { "code": "price_check_sheet", "name": "核价单", "required": True, "accepted_filenames": ["核价单.pdf"], }, { "code": "purchase_order", "name": "采购单", "required": True, "accepted_filenames": ["采购单.pdf"], }, ] DEFAULT_JOB_PARAMS: dict[str, Any] = { "scope_code": "HXJM", "directory_template": "{root}/{YYYY}/{MM}/{invoice_no}", "required_files": DEFAULT_REQUIRED_FILES, "filename_case_sensitive": True, "notify_missing_enabled": True, "notify_failure_enabled": True, "same_day_dedup_enabled": True, } @dataclass(frozen=True) class RequiredFileRule: """单条必检材料规则。""" code: str name: str required: bool accepted_filenames: tuple[str, ...] @dataclass(frozen=True) class VoucherCheckConfig: """运行期检核配置快照。""" scope_code: str directory_template: str required_files: tuple[RequiredFileRule, ...] filename_case_sensitive: bool notify_missing_enabled: bool notify_failure_enabled: bool same_day_dedup_enabled: bool local_root: str share_unc: str healthcheck_relative_path: str erp_dsn: str erp_username: str erp_password: str erp_timeout_seconds: int = 30 def _config_invalid(message: str, *, details: dict[str, Any] | None = None) -> ValidationError: return ValidationError( message, code="VOUCHER_CHECK.CONFIG_INVALID", details=details or {}, ) def _as_bool(value: Any, default: bool) -> bool: if value is None: return default if isinstance(value, bool): return value text = str(value).strip().lower() if text in {"1", "true", "yes", "on"}: return True if text in {"0", "false", "no", "off"}: return False return default def _parse_required_files(raw: Any) -> list[RequiredFileRule]: if raw is None: raw = DEFAULT_REQUIRED_FILES if isinstance(raw, str): try: raw = json.loads(raw) except json.JSONDecodeError as exc: raise _config_invalid("required_files JSON 非法", details={"error": str(exc)}) from exc if not isinstance(raw, list) or not raw: raise _config_invalid("required_files 至少包含一个必检项") rules: list[RequiredFileRule] = [] for idx, item in enumerate(raw): if not isinstance(item, dict): raise _config_invalid(f"required_files[{idx}] 必须为对象") code = str(item.get("code") or "").strip() name = str(item.get("name") or code).strip() accepted = item.get("accepted_filenames") or [] if not code: raise _config_invalid(f"required_files[{idx}].code 不能为空") if not isinstance(accepted, list) or not accepted: raise _config_invalid(f"required_files[{idx}].accepted_filenames 不能为空") filenames: list[str] = [] for fname in accepted: text = str(fname or "").strip() if not text: raise _config_invalid(f"required_files[{idx}] 存在空文件名") if "*" in text or "?" in text or _UNSAFE_FILENAME_RE.search(text): raise _config_invalid( f"required_files[{idx}] 文件名禁止通配/路径字符: {text}", ) filenames.append(text) rules.append( RequiredFileRule( code=code, name=name or code, required=_as_bool(item.get("required"), True), accepted_filenames=tuple(filenames), ) ) if not any(r.required for r in rules): raise _config_invalid("required_files 至少包含一个 required=true 项") return rules def validate_directory_template(template: str) -> str: """ 校验目录模板占位符。 核心逻辑:仅允许 {root}/{YYYY}/{MM}/{invoice_no} 四类占位符,且四者皆须出现。 """ text = str(template or "").strip().replace("\\", "/") if not text: raise _config_invalid("directory_template 不能为空") tokens = _TEMPLATE_TOKEN_RE.findall(text) unknown = sorted({t for t in tokens if t not in _ALLOWED_TEMPLATE_KEYS}) if unknown: raise _config_invalid( "directory_template 含非法占位符", details={"unknown": unknown}, ) missing = sorted(_ALLOWED_TEMPLATE_KEYS - set(tokens)) if missing: raise _config_invalid( "directory_template 缺少必要占位符", details={"missing": missing}, ) return text def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> VoucherCheckConfig: """ 合并 env 与 job_params,返回校验后的检核配置。 核心逻辑:敏感凭据只读环境变量;业务规则以 job_params 为准,缺省用 DEFAULT_JOB_PARAMS。 """ params = dict(DEFAULT_JOB_PARAMS) if isinstance(job_params, dict): params.update({k: v for k, v in job_params.items() if v is not None}) scope_code = str(params.get("scope_code") or "HXJM").strip().upper() or "HXJM" if scope_code != "HXJM": raise _config_invalid("一期仅支持 scope_code=HXJM", details={"scope_code": scope_code}) template = validate_directory_template( str(params.get("directory_template") or DEFAULT_JOB_PARAMS["directory_template"]) ) required_files = _parse_required_files(params.get("required_files")) cfg = current_app.config if has_app_context() else {} local_root = str( cfg.get("VOUCHER_CHECK_LOCAL_ROOT") or os.getenv("VOUCHER_CHECK_LOCAL_ROOT") or "" ).strip() share_unc = str( cfg.get("VOUCHER_CHECK_SHARE_UNC") or os.getenv("VOUCHER_CHECK_SHARE_UNC") or "" ).strip() healthcheck = str( cfg.get("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH") or os.getenv("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH") or ".hxops-share-ready" ).strip() or ".hxops-share-ready" # 开发机可临时用 UNC;Linux/容器必须 LOCAL_ROOT if not local_root and not share_unc: raise _config_invalid("未配置 VOUCHER_CHECK_LOCAL_ROOT 或 VOUCHER_CHECK_SHARE_UNC") erp_dsn = str( cfg.get("VOUCHER_CHECK_ERP_DSN") or os.getenv("VOUCHER_CHECK_ERP_DSN") or cfg.get("ERP_DB_DSN") or os.getenv("ERP_DB_DSN") or "" ).strip() erp_username = str( cfg.get("VOUCHER_CHECK_ERP_USERNAME") or os.getenv("VOUCHER_CHECK_ERP_USERNAME") or "" ).strip() erp_password = str( cfg.get("VOUCHER_CHECK_ERP_PASSWORD") or os.getenv("VOUCHER_CHECK_ERP_PASSWORD") or "" ) if not erp_dsn or not erp_username: raise _config_invalid("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME") timeout = int( cfg.get("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS") or os.getenv("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS") or 30 ) return VoucherCheckConfig( scope_code=scope_code, directory_template=template, required_files=tuple(required_files), filename_case_sensitive=_as_bool(params.get("filename_case_sensitive"), True), notify_missing_enabled=_as_bool(params.get("notify_missing_enabled"), True), notify_failure_enabled=_as_bool(params.get("notify_failure_enabled"), True), same_day_dedup_enabled=_as_bool(params.get("same_day_dedup_enabled"), True), local_root=local_root, share_unc=share_unc, healthcheck_relative_path=healthcheck, erp_dsn=erp_dsn, erp_username=erp_username, erp_password=erp_password, erp_timeout_seconds=max(1, timeout), ) def resolve_share_root(config: VoucherCheckConfig) -> str: """ 解析实际扫描根路径。 核心逻辑:优先 LOCAL_ROOT(容器/Linux);无则回退 share_unc(开发机)。 """ root = (config.local_root or config.share_unc or "").strip() if not root: raise _config_invalid("共享盘根路径为空") return root