""" backend/app/services/voucher_check/dms_client.py 用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。 依赖:requests、Flask 配置;登录接口与合同库相同。 逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。 文档库复制后 LeafName 写成「原名.pdf(重命名)」,扩展名另存。改回「原名.pdf」会被判同名,必须改成不含扩展名的「原名」;多余副本用 Item/Recycle 删除。 """ from __future__ import annotations import re import threading import time from datetime import date from pathlib import Path from typing import Any import requests from flask import current_app from app.core.errors import ServiceUnavailableError, ValidationError _LOCK = threading.Lock() _CACHE: dict[str, Any] = {"session": None, "created_at": 0.0} ARCHIVE_ROOT_LEAF = "所有归档" # 文档库同名冲突或复制后自动改名。标记前后可能有空格,后面有时还有 (1)。 _DMS_RENAME_RE = re.compile( r"\s*[((]\s*重命名\s*[))]\s*(?:\(\s*\d+\s*\)|(\s*\d+\s*))?" ) def canonical_leaf_name(name: str) -> str: """ 去掉文档库自动加上的「重命名」标记,还原业务文件名。 核心逻辑:`发票.pdf(重命名).pdf` 或带空格的 `发票.pdf (重命名) .pdf` 去掉标记后会多出一个扩展名,再折成 `发票.pdf`。 """ text = str(name or "").strip() cleaned = _DMS_RENAME_RE.sub("", text) if cleaned == text: return text return re.sub(r"(\.[A-Za-z0-9]{1,8})\s*\1$", r"\1", cleaned).strip() def dms_stored_leaf_name(filename: str) -> str: """ 算出文档库改名接口要写入的 LeafName。 核心逻辑:库里真实名字是「发票.pdf(重命名)」,扩展名在附件上。改成「发票.pdf」会和自己判成同名;改成「发票」后界面仍显示「发票.pdf」。 """ name = str(filename or "").strip() suffix = Path(name).suffix if suffix and name.lower().endswith(suffix.lower()) and len(name) > len(suffix): return name[: -len(suffix)] return name def row_display_name(row: dict[str, Any]) -> str: """ 还原文档库界面上的文件名。 核心逻辑:LeafName 没有以附件扩展名结尾时,界面会把扩展名补在后面。 """ leaf = str((row or {}).get("LeafName") or "").strip() attachment = (row or {}).get("MainFileAttachment") or {} if not isinstance(attachment, dict): attachment = {} ext = str(attachment.get("Extension") or "").strip() if ext and not ext.startswith("."): ext = f".{ext}" if ext and leaf and not leaf.lower().endswith(ext.lower()): return f"{leaf}{ext}" return leaf def leaf_names_match(actual: str, wanted: str) -> bool: """ 判断目录里的文件名是否就是要找的那一份。 核心逻辑:完全一致,或实际名字只是想要的名字加上了文档库「重命名」。 """ left = str(actual or "").strip() right = str(wanted or "").strip() if not left or not right: return False if left == right: return True return canonical_leaf_name(left) == right def _extract_item_id(payload: dict[str, Any]) -> str: """ 从 DMS SaveFolder / Copy 响应中取出条目 ID。 核心逻辑:现网 Data 可能是对象或字符串;缺字段时返回空串,由调用方再 Page 回查。 """ data = payload.get("Data") if isinstance(data, str) and data.strip(): return data.strip() if not isinstance(data, dict): return "" for key in ("ID", "ItemID", "FolderID"): value = str(data.get(key) or "").strip() if value: return value nested = data.get("Item") or data.get("Folder") or {} if isinstance(nested, dict): return str(nested.get("ID") or "").strip() return "" def _is_name_conflict(message: str) -> bool: """判断 DMS 返回是否为同名/已存在冲突,便于按「同名跳过」回收。""" text = str(message or "").strip() if not text: return False lowered = text.lower() return any( needle in text for needle in ("已存在", "同名", "重复名称", "名称重复") ) or any( needle in lowered for needle in ("already exist", "already exists", "duplicate name") ) class SalesDmsClient: """销售开票附件 DMS 客户端;不把账号密码返回给 API。""" @classmethod def _cfg(cls, key: str, fallback: str = "") -> str: value = current_app.config.get(key) or fallback return str(value or "").strip() @classmethod def base_url(cls) -> str: return (cls._cfg("VOUCHER_CHECK_DMS_BASE_URL") or cls._cfg("CONTRACT_DMS_BASE_URL")).rstrip("/") @classmethod def library_id(cls) -> str: return cls._cfg("VOUCHER_CHECK_DMS_LIBRARY_ID") or cls._cfg("CONTRACT_DMS_LIBRARY_ID") @classmethod def root_folder_id(cls) -> str: return cls._cfg("VOUCHER_CHECK_DMS_ROOT_FOLDER_ID") @classmethod def username(cls) -> str: return cls._cfg("VOUCHER_CHECK_DMS_USERNAME") or cls._cfg("CONTRACT_DMS_USERNAME") @classmethod def password(cls) -> str: return str( current_app.config.get("VOUCHER_CHECK_DMS_PASSWORD") or current_app.config.get("CONTRACT_DMS_PASSWORD") or "" ) @classmethod def is_configured(cls) -> bool: """判断销售 DMS 基址、账号、文档库 ID 和销售根目录是否齐全。""" return bool(cls.base_url() and cls.username() and cls.password() and cls.library_id() and cls.root_folder_id()) @classmethod def ensure_configured(cls) -> None: """ 配置缺失时在批次开始前失败,并返回可操作的缺失项。 核心逻辑:避免把空扫当成业务缺件;同时不能将任意凭据值写入错误响应。 """ missing = [ key for key, value in ( ("VOUCHER_CHECK_DMS_BASE_URL", cls.base_url()), ("VOUCHER_CHECK_DMS_LIBRARY_ID", cls.library_id()), ("VOUCHER_CHECK_DMS_ROOT_FOLDER_ID", cls.root_folder_id()), ("VOUCHER_CHECK_DMS_USERNAME", cls.username()), ("VOUCHER_CHECK_DMS_PASSWORD", cls.password()), ) if not value ] if missing: raise ValidationError( "销售开票附件文档库配置不完整", code="VOUCHER_CHECK.CONFIG_INVALID", details={"missing": missing}, ) @classmethod def _session(cls, *, refresh: bool = False) -> requests.Session: """登录 DMS 并缓存会话。""" with _LOCK: session = _CACHE.get("session") if not refresh and isinstance(session, requests.Session) and time.time() - float(_CACHE.get("created_at") or 0) < 1200: return session session = requests.Session() try: response = session.post( f"{cls.base_url()}/Login/_api/Login", json={"LoginName": cls.username(), "Pwd": cls.password()}, timeout=20, ) response.raise_for_status() payload = response.json() except requests.RequestException as exc: raise ServiceUnavailableError( "文档库登录失败", code="VOUCHER_CHECK.DMS_UNAVAILABLE", ) from exc if int(payload.get("Code") or 0) != 0: raise ServiceUnavailableError( payload.get("Msg") or "文档库登录失败", code="VOUCHER_CHECK.DMS_UNAVAILABLE", ) _CACHE.update({"session": session, "created_at": time.time()}) return session @classmethod def _post_json( cls, path: str, payload: dict[str, Any], *, timeout: int = 30, failure_code: str = "VOUCHER_CHECK.DMS_UNAVAILABLE", failure_message: str = "文档库请求失败", ) -> dict[str, Any]: """ POST JSON 到现网 DMS,并统一处理 401 刷新与 Code!=0。 核心逻辑:路径相对基址;失败抛 ServiceUnavailableError,不把凭据写入异常。 """ url = f"{cls.base_url()}{path}" try: session = cls._session() response = session.post(url, json=payload, timeout=timeout) if response.status_code in {401, 403}: session = cls._session(refresh=True) response = session.post(url, json=payload, timeout=timeout) response.raise_for_status() data = response.json() except (requests.RequestException, ValueError) as exc: raise ServiceUnavailableError(failure_message, code=failure_code) from exc if int(data.get("Code") or 0) != 0: raise ServiceUnavailableError( data.get("Msg") or failure_message, code=failure_code, details={"dms_data": data.get("Data")} if data.get("Data") not in (None, "", {}) else {}, ) return data @classmethod def _post_multipart( cls, path: str, *, files: dict[str, Any], data: dict[str, Any] | None = None, timeout: int = 60, failure_code: str = "VOUCHER_CHECK.DMS_UNAVAILABLE", failure_message: str = "文档库上传失败", ) -> dict[str, Any]: """ POST multipart 到现网 DMS(用于附件 Upload)。 核心逻辑:不手工设 Content-Type,交给 requests 带 boundary;401/403 刷新会话后重试。 """ url = f"{cls.base_url()}{path}" try: session = cls._session() response = session.post(url, files=files, data=data or {}, timeout=timeout) if response.status_code in {401, 403}: session = cls._session(refresh=True) response = session.post(url, files=files, data=data or {}, timeout=timeout) response.raise_for_status() payload = response.json() except (requests.RequestException, ValueError) as exc: raise ServiceUnavailableError(failure_message, code=failure_code) from exc if int(payload.get("Code") or 0) != 0: raise ServiceUnavailableError( payload.get("Msg") or failure_message, code=failure_code, details={"dms_data": payload.get("Data")} if payload.get("Data") not in (None, "", {}) else {}, ) return payload @classmethod def page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]: """ 查询一个父目录下的条目。 核心逻辑:POST Item/Page,按页累加直到本页不足 Size 或达到 Total;避免「所有归档」超过 200 个子目录时漏建/漏跳过。 """ items: list[dict[str, Any]] = [] page_size = 200 index = 1 while index <= 50: payload = { "LibraryID": cls.library_id(), "ParentFolderID": parent_folder_id, "Keywords": "", "Page": {"Size": page_size, "Index": index}, "Total": 0, "Recursion": recursion, "OrderBy": [], "FieldQuery": [], "LeafName": leaf_name, } data = cls._post_json("/Api/_api/APS/Public/Item/Page", payload, timeout=30) section = data.get("Data") or {} batch = section.get("Rows") or section.get("Items") or (section.get("Page") or {}).get("Items") or [] items.extend(batch) total = int(section.get("Total") or 0) if len(batch) < page_size: break if total and len(items) >= total: break index += 1 return items @classmethod def find_child_folder(cls, *, parent_folder_id: str, leaf_name: str) -> str | None: """在父目录下按 LeafName 找文件夹 ID,找不到返回 None。""" wanted = str(leaf_name or "").strip() if not wanted: return None for row in cls.page(parent_folder_id=parent_folder_id, recursion=False): if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == wanted: folder_id = str(row.get("ID") or "").strip() if folder_id: return folder_id return None @classmethod def find_child_file(cls, *, parent_folder_id: str, leaf_name: str) -> dict[str, Any] | None: """ 在父目录下按 LeafName 找非文件夹条目,找不到返回 None。 核心逻辑:优先完全同名。库内名字可能是「原名.pdf(重命名)」或已改回的「原名」,都按界面显示名认成同一份。 """ wanted = str(leaf_name or "").strip() if not wanted: return None renamed: dict[str, Any] | None = None for row in cls.list_files(folder_id=parent_folder_id): leaf = str(row.get("LeafName") or "").strip() shown = row_display_name(row) if leaf == wanted or shown == wanted: return row if renamed is None and (leaf_names_match(leaf, wanted) or leaf_names_match(shown, wanted)): renamed = row return renamed @classmethod def resolve_period_folder(cls, *, period_month: date) -> tuple[str | None, str | None]: """ 解析销售开票附件/{yyyy}/{MM} 的 FolderID。 核心逻辑:从销售根逐级找年、月目录;缺层返回 (None, None),由扫描记缺件而非技术失败。 """ root = cls.root_folder_id() year_name = f"{period_month.year:04d}" month_name = f"{period_month.month:02d}" year_id = cls.find_child_folder(parent_folder_id=root, leaf_name=year_name) if not year_id: return None, None month_id = cls.find_child_folder(parent_folder_id=year_id, leaf_name=month_name) return year_id, month_id @classmethod def list_files(cls, *, folder_id: str) -> list[dict[str, Any]]: """列出目录下的非文件夹条目。""" rows = cls.page(parent_folder_id=folder_id, recursion=False) return [row for row in rows if not row.get("IsFolder")] @classmethod def ensure_folder(cls, *, parent_folder_id: str, leaf_name: str) -> str: """ 确保父目录下存在指定 LeafName 的文件夹;没有则 SaveFolder。 核心逻辑:先 Page 查找;已存在直接返回。创建时若接口报同名,再查一次当作成功。 """ wanted = str(leaf_name or "").strip() if not wanted: raise ValidationError("文件夹名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted) if existing: return existing try: payload = cls._post_json( "/Api/_api/APS/Public/Item/SaveFolder", { "ID": "", "LibraryID": cls.library_id(), "ParentFolderID": parent_folder_id, "LeafName": wanted, "FieldValues": [], }, failure_code="VOUCHER_CHECK.ARCHIVE_FAILED", failure_message="文档库创建文件夹失败", ) except ServiceUnavailableError as exc: existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted) if existing: return existing if _is_name_conflict(exc.message): existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted) if existing: return existing raise created_id = _extract_item_id(payload) if created_id: return created_id existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted) if existing: return existing raise ServiceUnavailableError( "创建文件夹后未能解析 FolderID", code="VOUCHER_CHECK.ARCHIVE_FAILED", details={"leaf_name": wanted}, ) @classmethod def ensure_month_archive_root(cls, *, period_month: date) -> str: """ 确保销售开票附件/{yyyy}/{MM}/所有归档 存在并返回 FolderID。 核心逻辑:月目录必须已存在(扫描命中才归档);缺月目录视为技术失败,不降级为缺件。 """ _year_id, month_id = cls.resolve_period_folder(period_month=period_month) if not month_id: raise ServiceUnavailableError( "销售开票附件年/月目录不存在,无法创建归档文件夹", code="VOUCHER_CHECK.ARCHIVE_FAILED", ) return cls.ensure_folder(parent_folder_id=month_id, leaf_name=ARCHIVE_ROOT_LEAF) @classmethod def ensure_invoice_archive_folder(cls, *, period_month: date, invoice_no: str) -> str: """ 确保所有归档/{invoice}/ 存在并返回 FolderID。 核心逻辑:先保证「所有归档」,再按发票号建子目录。 """ invoice = str(invoice_no or "").strip() if not invoice: raise ValidationError("归档发票号不能为空", code="VOUCHER_CHECK.INVOICE_REQUIRED") archive_root_id = cls.ensure_month_archive_root(period_month=period_month) return cls.ensure_folder(parent_folder_id=archive_root_id, leaf_name=invoice) @classmethod def copy_items(cls, *, item_ids: list[str], dest_folder_id: str) -> dict[str, Any]: """ 把文档库条目复制到目标文件夹(不移动原件)。 核心逻辑:POST Item/Copy;ItemID 为数组,与现网前端 CopyFileFolder 一致。 """ ids = [str(item_id).strip() for item_id in item_ids if str(item_id).strip()] dest = str(dest_folder_id or "").strip() if not ids: raise ValidationError("复制源条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") if not dest: raise ValidationError("复制目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") return cls._post_json( "/Api/_api/APS/Public/Item/Copy", {"ItemID": ids, "ParentFolderID": dest}, timeout=60, failure_code="VOUCHER_CHECK.ARCHIVE_FAILED", failure_message="文档库复制文件失败", ) @classmethod def rename_item(cls, *, item_id: str, leaf_name: str) -> dict[str, Any]: """ 把文档库条目改成指定文件名。 核心逻辑:POST Item/Rename,与文档库列表「重命名」一致,只改 LeafName、不另存一份。 """ item = str(item_id or "").strip() wanted = str(leaf_name or "").strip() if not item: raise ValidationError("重命名条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") if not wanted: raise ValidationError("重命名文件名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") return cls._post_json( "/Api/_api/APS/Public/Item/Rename", {"ItemID": item, "LeafName": wanted}, timeout=30, failure_code="VOUCHER_CHECK.ARCHIVE_FAILED", failure_message="文档库去掉重命名后缀失败", ) @classmethod def _restore_exact_leaf( cls, *, parent_folder_id: str, wanted: str, row: dict[str, Any], ) -> dict[str, Any]: """ 所有归档要求界面上不带「(重命名)」。 核心逻辑:先确认这份就是目标文件。改名只写不含扩展名的 LeafName;写成「原名.pdf」会和「原名.pdf(重命名)」判成同名。 """ leaf = str(row.get("LeafName") or "").strip() shown = row_display_name(row) target = dms_stored_leaf_name(wanted) if leaf in {wanted, target} or shown == wanted: return row if canonical_leaf_name(leaf) != wanted and canonical_leaf_name(shown) != wanted: raise ServiceUnavailableError( "目标目录文件名与归档文件名不一致", code="VOUCHER_CHECK.ARCHIVE_FAILED", details={"leaf_name": wanted, "actual_name": leaf}, ) cls.rename_item(item_id=str(row.get("ID") or ""), leaf_name=target) for item in cls.list_files(folder_id=parent_folder_id): item_leaf = str(item.get("LeafName") or "").strip() if item_leaf in {wanted, target} or row_display_name(item) == wanted: return item raise ServiceUnavailableError( "去掉重命名后缀后未找到原文件名", code="VOUCHER_CHECK.ARCHIVE_FAILED", details={"leaf_name": wanted}, ) @classmethod def recycle_items(cls, *, item_ids: list[str]) -> dict[str, Any]: """ 按文档库列表「删除」把条目放进回收站。 核心逻辑:POST Item/Recycle,ItemID 为数组;不调用彻底删除,误删可从回收站恢复。 """ ids = [str(item_id).strip() for item_id in item_ids if str(item_id).strip()] if not ids: raise ValidationError("删除条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") return cls._post_json( "/Api/_api/APS/Public/Item/Recycle", {"ItemID": ids}, timeout=30, failure_code="VOUCHER_CHECK.ARCHIVE_FAILED", failure_message="文档库删除多余重命名文件失败", ) @classmethod def _drop_extra_renamed_copies( cls, *, parent_folder_id: str, wanted: str, keep_item_id: str, ) -> None: """ 删掉同一目录里多出来的「(重命名)」副本。 核心逻辑:只删文件名还原后等于目标原名、且仍带重命名标记的条目;原名和其他文件不动。 """ keep = str(keep_item_id or "").strip() extras: list[str] = [] for row in cls.list_files(folder_id=parent_folder_id): item_id = str(row.get("ID") or "").strip() leaf = str(row.get("LeafName") or "").strip() shown = row_display_name(row) if not item_id or item_id == keep or ("重命名" not in leaf and "重命名" not in shown): continue if canonical_leaf_name(leaf) == wanted or canonical_leaf_name(shown) == wanted: extras.append(item_id) if extras: cls.recycle_items(item_ids=extras) @classmethod def _settle_archived_file( cls, *, parent_folder_id: str, wanted: str, row: dict[str, Any], ) -> dict[str, Any]: """ 归档落盘后收成一个界面上不带后缀的原名。 核心逻辑:先删掉其余「(重命名)」副本,再把留下的那份改成不含扩展名的 LeafName。先改名会被文档库判成同名。 """ cls._drop_extra_renamed_copies( parent_folder_id=parent_folder_id, wanted=wanted, keep_item_id=str(row.get("ID") or "").strip(), ) return cls._restore_exact_leaf(parent_folder_id=parent_folder_id, wanted=wanted, row=row) @classmethod def copy_file_skip_same_name( cls, *, source_item_id: str, dest_folder_id: str, leaf_name: str, ) -> tuple[dict[str, Any], bool]: """ 复制文件到目标目录;目标已有同名文件则跳过、不覆盖。 核心逻辑:先按 LeafName 查目标。已有原名则跳过复制;只有「(重命名)」副本时改回原名。没有再 Copy。收尾时同一目录多出来的该后缀副本删除。 Returns: (目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有文件(必要时已去掉重命名后缀并删除多余副本)。 """ wanted = str(leaf_name or "").strip() source = str(source_item_id or "").strip() dest = str(dest_folder_id or "").strip() if not source: raise ValidationError("复制源条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") if not dest: raise ValidationError("复制目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") if not wanted: raise ValidationError("复制文件名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) if existing: return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True try: cls.copy_items(item_ids=[source], dest_folder_id=dest) except ServiceUnavailableError as exc: existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) if existing: return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True if _is_name_conflict(exc.message): existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) if existing: return ( cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True, ) raise dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) if not dest_row: raise ServiceUnavailableError( "复制成功但目标目录未找到同名文件", code="VOUCHER_CHECK.ARCHIVE_FAILED", details={"leaf_name": wanted}, ) return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=dest_row), False @classmethod def ensure_period_type_folder(cls, *, period_month: date, type_folder: str) -> str: """ 确保销售开票附件/{yyyy}/{MM}/{类型目录} 存在并返回 FolderID。 【AI 触发时机】要把新生成的 PO PDF 写入类型目录时调用;年/月/类型目录没有就建。 Args: period_month: 检核月份(用年、月两位目录名)。 type_folder: 类型目录名,销售 PO 固定为「PO订单」。 """ wanted = str(type_folder or "").strip() if not wanted: raise ValidationError("类型目录名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") cls.ensure_configured() root = cls.root_folder_id() year_id = cls.ensure_folder(parent_folder_id=root, leaf_name=f"{period_month.year:04d}") month_id = cls.ensure_folder(parent_folder_id=year_id, leaf_name=f"{period_month.month:02d}") return cls.ensure_folder(parent_folder_id=month_id, leaf_name=wanted) @classmethod def upload_attachment(cls, *, filename: str, content: bytes) -> dict[str, Any]: """ 把文件二进制上传为未入目录的附件,返回 Data(须含 ID)。 核心逻辑:现网「新建文件」先 Upload 附件,再 CreateFiles 挂到文件夹。 """ name = str(filename or "").strip() if not name: raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID") if not content: raise ValidationError("上传文件内容不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID") payload = cls._post_multipart( "/Api/_api/DMS/Public/Attachment/Upload", files={"file": (name, content, "application/pdf")}, timeout=120, failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED", failure_message="文档库上传附件失败", ) data = payload.get("Data") if not isinstance(data, dict) or not str(data.get("ID") or "").strip(): raise ServiceUnavailableError( "文档库上传附件后未返回 AttachmentID", code="VOUCHER_CHECK.PO_UPLOAD_FAILED", ) return data @classmethod def create_files( cls, *, parent_folder_id: str, files: list[dict[str, Any]], ) -> dict[str, Any]: """ 把已上传附件登记到指定文件夹(现网 functionCreationFile)。 核心逻辑:POST Item/CreateFiles;Files[].AttachmentID 来自 Attachment/Upload。 """ dest = str(parent_folder_id or "").strip() if not dest: raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") if not files: raise ValidationError("上传文件列表不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") return cls._post_json( "/Api/_api/APS/Public/Item/CreateFiles", { "LibraryID": cls.library_id(), "CategoryID": "", "ParentFolderID": dest, "Files": files, "TermID": [], "CheckedOutState": 0, "CheckedOutMemo": "", }, timeout=60, failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED", failure_message="文档库创建文件失败", ) @classmethod def upload_file_skip_same_name( cls, *, parent_folder_id: str, leaf_name: str, content: bytes, ) -> tuple[dict[str, Any], bool]: """ 上传文件到类型目录;目标已有同名则跳过、不覆盖。 核心逻辑:先 Page 查 LeafName;没有则 Upload 附件再 CreateFiles。CreateFiles 报同名视为跳过。 """ wanted = str(leaf_name or "").strip() dest = str(parent_folder_id or "").strip() if not dest: raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") if not wanted: raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID") existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) if existing: return existing, True attachment = cls.upload_attachment(filename=wanted, content=content) extension = str(attachment.get("Extension") or Path(wanted).suffix or ".pdf").strip() if extension and not extension.startswith("."): extension = f".{extension}" file_row = { "LeafName": wanted, "AttachmentID": str(attachment.get("ID") or "").strip(), "CheckedOutState": 0, "CheckedOutMemo": "", "Extension": extension, "FieldValues": [], } try: cls.create_files(parent_folder_id=dest, files=[file_row]) except ServiceUnavailableError as exc: existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) if existing: return existing, True same_names = ((exc.details or {}).get("dms_data") or {}).get("SameLeafNames") or [] if same_names or _is_name_conflict(exc.message): existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) if existing: return existing, True raise dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) if dest_row: return dest_row, False # 部分现网 CreateFiles 后 LeafName 不含扩展名,再按无后缀查一次。 stem = Path(wanted).stem dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=stem) if dest_row: return dest_row, False raise ServiceUnavailableError( "上传成功但类型目录未找到同名文件", code="VOUCHER_CHECK.PO_UPLOAD_FAILED", details={"leaf_name": wanted}, )