580 lines
24 KiB
Python
580 lines
24 KiB
Python
"""
|
||
backend/app/services/voucher_check/dms_client.py
|
||
|
||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
|
||
依赖:requests、Flask 配置;登录接口与合同库相同。
|
||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
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 = "所有归档"
|
||
|
||
|
||
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。"""
|
||
wanted = str(leaf_name or "").strip()
|
||
if not wanted:
|
||
return None
|
||
for row in cls.list_files(folder_id=parent_folder_id):
|
||
if str(row.get("LeafName") or "").strip() == wanted:
|
||
return row
|
||
return None
|
||
|
||
@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 copy_file_skip_same_name(
|
||
cls,
|
||
*,
|
||
source_item_id: str,
|
||
dest_folder_id: str,
|
||
leaf_name: str,
|
||
) -> tuple[dict[str, Any], bool]:
|
||
"""
|
||
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
|
||
核心逻辑:先按 LeafName 查目标;没有再 Copy。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 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 existing, True
|
||
if _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 not dest_row:
|
||
raise ServiceUnavailableError(
|
||
"复制成功但目标目录未找到同名文件",
|
||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||
details={"leaf_name": wanted},
|
||
)
|
||
return 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},
|
||
)
|
||
|