1
This commit is contained in:
1 parent
78576f5745
commit
63b997a7e4
68 files changed
+3680
-1413
No files matched your search
@@ -0,0 +1,388 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/dms_client.py
|
||||
|
||||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、复制;不移动原件)。
|
||||
依赖:requests、Flask 配置;登录接口与合同库相同。
|
||||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。归档复制策略为同名跳过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from datetime import date
|
||||
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:
|
||||
"""配置缺失时在批次开始前失败,避免空扫被当成业务缺件。"""
|
||||
if not cls.is_configured():
|
||||
raise ValidationError(
|
||||
"未配置销售开票附件文档库根目录",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"missing": "VOUCHER_CHECK_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()
|
||||
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,
|
||||
)
|
||||
return data
|
||||
|
||||
@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
|
||||
Reference in new issue
Block a user