206 lines
9.7 KiB
Python
206 lines
9.7 KiB
Python
"""
|
|
backend/app/services/contract_payment/dms_client.py
|
|
|
|
用途:访问采购合同文档管理系统,作为 OA 附件缺失时的延迟补充来源。
|
|
依赖:requests、Flask 配置;接口模式复用固定资产图片服务的登录、目录查询和附件代理。
|
|
逻辑:使用配置的根 FolderID 逐级定位年份目录,按合同编号检索文件,再按创建日期窗口筛选并下载附件。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
from datetime import date, datetime, timedelta
|
|
from typing import Any
|
|
from urllib.parse import urlencode
|
|
|
|
import requests
|
|
from flask import current_app
|
|
|
|
|
|
_LOCK = threading.Lock()
|
|
_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0}
|
|
|
|
|
|
class ContractDmsClient:
|
|
"""采购合同文档库轻量客户端;不会把账号或密码返回给 API。"""
|
|
|
|
@classmethod
|
|
def _base(cls) -> str:
|
|
return str(current_app.config.get("CONTRACT_DMS_BASE_URL") or "").rstrip("/")
|
|
|
|
@classmethod
|
|
def is_configured(cls) -> bool:
|
|
"""判断 DMS 地址、账号、密码和文档库 ID 是否齐全。"""
|
|
return bool(
|
|
cls._base()
|
|
and current_app.config.get("CONTRACT_DMS_USERNAME")
|
|
and current_app.config.get("CONTRACT_DMS_PASSWORD")
|
|
and current_app.config.get("CONTRACT_DMS_LIBRARY_ID")
|
|
and current_app.config.get("CONTRACT_DMS_ROOT_FOLDER_ID")
|
|
)
|
|
|
|
@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()
|
|
response = session.post(
|
|
f"{cls._base()}/Login/_api/Login",
|
|
json={"LoginName": current_app.config.get("CONTRACT_DMS_USERNAME"), "Pwd": current_app.config.get("CONTRACT_DMS_PASSWORD")},
|
|
timeout=20,
|
|
)
|
|
response.raise_for_status()
|
|
payload = response.json()
|
|
if int(payload.get("Code") or 0) != 0:
|
|
raise RuntimeError(payload.get("Msg") or "文档管理系统登录失败")
|
|
_CACHE.update({"session": session, "created_at": time.time()})
|
|
return session
|
|
|
|
@classmethod
|
|
def _page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]:
|
|
"""查询一个父目录下的条目;目录解析使用非递归,合同文件检索使用递归。"""
|
|
payload = {
|
|
"LibraryID": str(current_app.config.get("CONTRACT_DMS_LIBRARY_ID")),
|
|
"ParentFolderID": parent_folder_id,
|
|
"Keywords": "",
|
|
"Page": {"Size": 200, "Index": 1},
|
|
"Total": 0,
|
|
"Recursion": recursion,
|
|
"OrderBy": [],
|
|
"FieldQuery": [],
|
|
"LeafName": leaf_name,
|
|
}
|
|
session = cls._session()
|
|
response = session.post(f"{cls._base()}/Api/_api/APS/Public/Item/Page", json=payload, timeout=30)
|
|
if response.status_code in {401, 403}:
|
|
session = cls._session(refresh=True)
|
|
response = session.post(f"{cls._base()}/Api/_api/APS/Public/Item/Page", json=payload, timeout=30)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
if int(data.get("Code") or 0) != 0:
|
|
raise RuntimeError(data.get("Msg") or "文档管理系统查询失败")
|
|
section = data.get("Data") or {}
|
|
return section.get("Rows") or section.get("Items") or (section.get("Page") or {}).get("Items") or []
|
|
|
|
@classmethod
|
|
def resolve_folder(cls, *, archive_date: date | None = None, folder_id: str | None = None) -> str:
|
|
"""
|
|
根据归档年份解析合同目录 FolderID。
|
|
|
|
AI 触发时机:OA 附件缺失,需要在 DMS 补查合同时调用。
|
|
逻辑:传入 folder_id 时直接使用;否则从根目录查找“{year}年设备合同书”,查不到时回退根目录。
|
|
"""
|
|
explicit = str(folder_id or "").strip()
|
|
if explicit:
|
|
return explicit
|
|
root = str(current_app.config.get("CONTRACT_DMS_ROOT_FOLDER_ID") or "").strip()
|
|
if not root or not archive_date:
|
|
return root
|
|
if archive_date.year == 2026:
|
|
configured_2026 = str(current_app.config.get("CONTRACT_DMS_2026_FOLDER_ID") or "").strip()
|
|
if configured_2026:
|
|
return configured_2026
|
|
template = str(current_app.config.get("CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE") or "{year}年设备合同书")
|
|
wanted = template.format(year=archive_date.year)
|
|
rows = cls._page(parent_folder_id=root, recursion=False)
|
|
for row in rows:
|
|
if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == wanted:
|
|
return str(row.get("ID") or root)
|
|
return root
|
|
|
|
@classmethod
|
|
def _created_at(cls, row: dict[str, Any]) -> datetime | None:
|
|
"""读取 DMS 条目的创建时间,无法解析时返回 None。"""
|
|
raw = row.get("CreatedDate") or row.get("CreatedAt") or row.get("CreateDate")
|
|
if isinstance(raw, datetime):
|
|
return raw.replace(tzinfo=None)
|
|
text = str(raw or "").strip()
|
|
if not text:
|
|
return None
|
|
try:
|
|
return datetime.fromisoformat(text.replace("Z", "+00:00")).replace(tzinfo=None)
|
|
except ValueError:
|
|
return None
|
|
|
|
@classmethod
|
|
def search(cls, *, contract_no: str, folder_id: str | None = None, archive_date: date | None = None) -> list[dict[str, Any]]:
|
|
"""
|
|
按合同编号查询 DMS 文件并按 OA 归档日期过滤。
|
|
|
|
AI 触发时机:OA 附件下载失败或延迟到达时调用。
|
|
约束:只返回文件元数据;不创建合同主记录、不生成采购单号。首选年份目录,最后查询暂存目录。
|
|
"""
|
|
if not cls.is_configured():
|
|
return []
|
|
normalized = str(contract_no or "").strip()
|
|
if not normalized:
|
|
return []
|
|
root = str(current_app.config.get("CONTRACT_DMS_ROOT_FOLDER_ID") or "").strip()
|
|
primary = cls.resolve_folder(archive_date=archive_date, folder_id=folder_id)
|
|
folder_ids = [primary]
|
|
temp_name = str(current_app.config.get("CONTRACT_DMS_TEMP_FOLDER_NAME") or "暂存").strip()
|
|
if primary == root and root:
|
|
rows = cls._page(parent_folder_id=root, recursion=False)
|
|
else:
|
|
rows = cls._page(parent_folder_id=root, recursion=False) if root else []
|
|
for row in rows:
|
|
if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == temp_name:
|
|
temp_id = str(row.get("ID") or "")
|
|
if temp_id and temp_id not in folder_ids:
|
|
folder_ids.append(temp_id)
|
|
window = max(int(current_app.config.get("CONTRACT_DMS_LOOKUP_WINDOW_DAYS") or 30), 0)
|
|
start = datetime.combine(archive_date - timedelta(days=window), datetime.min.time()) if archive_date else None
|
|
end = datetime.combine(archive_date + timedelta(days=window), datetime.max.time()) if archive_date else None
|
|
matches: list[dict[str, Any]] = []
|
|
for current_folder in folder_ids:
|
|
for row in cls._page(parent_folder_id=current_folder, leaf_name=normalized, recursion=True):
|
|
if row.get("IsFolder"):
|
|
continue
|
|
if normalized.lower() not in str(row.get("LeafName") or "").lower():
|
|
continue
|
|
created = cls._created_at(row)
|
|
if start and end and created and not (start <= created <= end):
|
|
continue
|
|
row = dict(row)
|
|
row["DmsFolderID"] = current_folder
|
|
matches.append(row)
|
|
matches.sort(key=lambda row: cls._created_at(row) or datetime.min, reverse=True)
|
|
return matches
|
|
|
|
@classmethod
|
|
def download_attachment(cls, attachment_id: str, *, max_size: int | None = None) -> tuple[bytes, str, str | None]:
|
|
"""
|
|
下载 DMS 附件二进制,供 FileAsset 私有存储和合同解析使用。
|
|
|
|
参数约束:attachment_id 必须来自 DMS Item/Page 返回的 MainFileAttachment.ID。
|
|
返回:文件字节、MIME 类型、Content-Disposition 推断的文件名。
|
|
"""
|
|
attachment = str(attachment_id or "").strip()
|
|
if not attachment:
|
|
raise ValueError("DMS attachment ID is required")
|
|
session = cls._session()
|
|
response = session.get(cls.attachment_url(attachment), timeout=60, allow_redirects=True)
|
|
if response.status_code in {401, 403}:
|
|
session = cls._session(refresh=True)
|
|
response = session.get(cls.attachment_url(attachment), timeout=60, allow_redirects=True)
|
|
response.raise_for_status()
|
|
data = response.content
|
|
limit = max_size or 30 * 1024 * 1024
|
|
if len(data) > limit:
|
|
raise RuntimeError("DMS 附件超过文件大小限制")
|
|
content_type = (response.headers.get("content-type") or "application/octet-stream").split(";", 1)[0].strip().lower()
|
|
disposition = response.headers.get("content-disposition") or ""
|
|
filename = None
|
|
if "filename=" in disposition:
|
|
filename = disposition.split("filename=", 1)[1].strip().strip('"')
|
|
return data, content_type, filename
|
|
|
|
@classmethod
|
|
def attachment_url(cls, attachment_id: str) -> str:
|
|
"""生成同源附件 Embed URL;不把登录 Cookie 暴露给前端。"""
|
|
return f"{cls._base()}/Api/_api/DMS/Public/Attachment/Embed?{urlencode({'attachmentID': attachment_id})}"
|