feat(invoice-check): 从erp查询PO订单数据来源

This commit is contained in:
sophie committed 2026-09-14 19:09:42 +08:00
1 parent b15dd6808f
commit 1c34ab962f
40 files changed
+2682 -395

No files matched your search

@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/dms_client.py
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、复制;不移动原件)。
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
依赖:requests、Flask 配置;登录接口与合同库相同。
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。归档复制策略为同名跳过。
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
"""
from __future__ import annotations
@@ -11,6 +11,7 @@ from __future__ import annotations
import threading
import time
from datetime import date
from pathlib import Path
from typing import Any
import requests
@@ -178,9 +179,44 @@ class SalesDmsClient:
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]]:
"""
@@ -400,3 +436,144 @@ class SalesDmsClient:
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},
)