feat(invoice): 立账凭证检核复制文件加重命名后缀优化

This commit is contained in:
sophie committed 2026-10-28 15:00:49 +08:00
1 parent 02aa00e913
commit 3710aa4d81
10 files changed
+424 -23

No files matched your search

+3 -1
View File
@@ -4,6 +4,7 @@ backend/app/api/workspace/voucher_check.py
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
批次明细可按 result 与 invoice_no 筛选。
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
"""
@@ -149,12 +150,13 @@ def workspace_voucher_latest_run():
def workspace_voucher_run_items(run_id: int):
"""
分页查看批次明细。
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
核心逻辑:委托 query_service.list_run_items,可按 result 与 invoice_no 过滤,并返回 by_file_type。
"""
_require_voucher_check_access()
data = query_service.list_run_items(
run_id=run_id,
result=request.args.get("result"),
invoice_no=request.args.get("invoice_no"),
page=request.args.get("page", default=1, type=int) or 1,
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
@@ -44,7 +44,7 @@ class DmsArchiveAdapter:
"""
确保所有归档/{invoice}/ 存在,并把命中文件复制进去(不移动类型目录原件)。
【AI 触发时机】扫描命中且 invoice 关联校验通过后调用。
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有同 LeafName 则跳过覆盖。
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有原名则跳过。带「(重命名)」的副本改回原名,同一目录多出来的该后缀文件删除。
"""
yyyy = f"{period_month.year:04d}"
mm = f"{period_month.month:02d}"
@@ -4,10 +4,12 @@ backend/app/services/voucher_check/dms_client.py
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
依赖:requests、Flask 配置;登录接口与合同库相同。
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
文档库复制后若把文件名写成「原名(重命名).扩展名」,用 Item/Rename 改回原文件名;同一目录多出来的该后缀副本用 Item/Recycle 删除。
"""
from __future__ import annotations
import re
import threading
import time
from datetime import date
@@ -23,6 +25,36 @@ _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 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:
@@ -265,14 +297,21 @@ class SalesDmsClient:
@classmethod
def find_child_file(cls, *, parent_folder_id: str, leaf_name: str) -> dict[str, Any] | None:
"""在父目录下按 LeafName 找非文件夹条目,找不到返回 None。"""
"""
在父目录下按 LeafName 找非文件夹条目,找不到返回 None。
核心逻辑:优先完全同名;否则返回文档库改成「原名(重命名).扩展名」的那一份,供归档改回原名,避免再次复制。
"""
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):
if str(row.get("LeafName") or "").strip() == wanted:
leaf = str(row.get("LeafName") or "").strip()
if leaf == wanted:
return row
return None
if renamed is None and leaf_names_match(leaf, wanted):
renamed = row
return renamed
@classmethod
def resolve_period_folder(cls, *, period_month: date) -> tuple[str | None, str | None]:
@@ -387,6 +426,119 @@ class SalesDmsClient:
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]:
"""
所有归档要求文件名不带「(重命名)」。
核心逻辑:当前条目只是原名加上文档库后缀时,改回原名后再按完全同名回查。多余副本由归档收尾删除。
"""
leaf = str(row.get("LeafName") or "").strip()
if leaf == wanted:
return row
if canonical_leaf_name(leaf) != 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=wanted)
for item in cls.list_files(folder_id=parent_folder_id):
if str(item.get("LeafName") or "").strip() == 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()
if not item_id or item_id == keep or "重命名" not in leaf:
continue
if canonical_leaf_name(leaf) == 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]:
"""
归档落盘后收成一个不带后缀的原名。
核心逻辑:必要时先改回原名,再删除同目录其余「(重命名)」副本。
"""
if str(row.get("LeafName") or "").strip() != wanted:
row = cls._restore_exact_leaf(parent_folder_id=parent_folder_id, wanted=wanted, row=row)
cls._drop_extra_renamed_copies(
parent_folder_id=parent_folder_id,
wanted=wanted,
keep_item_id=str(row.get("ID") or "").strip(),
)
return row
@classmethod
def copy_file_skip_same_name(
cls,
@@ -397,10 +549,10 @@ class SalesDmsClient:
) -> tuple[dict[str, Any], bool]:
"""
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
核心逻辑:先按 LeafName 查目标;没有再 Copy。Copy 报同名或复制后已能查到,一律视为跳过成功。
核心逻辑:先按 LeafName 查目标。已有原名则跳过复制;只有「(重命名)」副本时改回原名。没有再 Copy。收尾时同一目录多出来的该后缀副本删除。
Returns:
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有同名文件。
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有文件(必要时已去掉重命名后缀并删除多余副本)。
"""
wanted = str(leaf_name or "").strip()
source = str(source_item_id or "").strip()
@@ -414,18 +566,21 @@ class SalesDmsClient:
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
if existing:
return existing, True
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 existing, True
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 existing, True
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)
@@ -435,7 +590,7 @@ class SalesDmsClient:
code="VOUCHER_CHECK.ARCHIVE_FAILED",
details={"leaf_name": wanted},
)
return dest_row, False
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:
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/query_service.py
用途:查询检核批次列表、最近一次检核、批次明细、企微发送记录,以及工作台强制重检入队。
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service、schedule_seed。
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细可按状态和 invoice 号筛选行,by_file_type 仍是整批;强制重检写入 run_options.mode=force_all。
"""
from __future__ import annotations
@@ -545,10 +545,14 @@ def list_run_items(
*,
run_id: int,
result: str | None = None,
invoice_no: str | None = None,
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。"""
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。
核心逻辑:result 精确匹配状态;invoice_no 按包含、忽略大小写筛行。文件类型汇总不跟着这两个条件缩。
"""
run = ScheduleRun.query.get(run_id)
if not run:
raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
@@ -574,6 +578,12 @@ def list_run_items(
result_filter = str(result).strip() if result else ""
if result_filter:
items = [row for row in items if row.get("result") == result_filter]
invoice_filter = str(invoice_no).strip().casefold() if invoice_no else ""
if invoice_filter:
items = [
row for row in items
if invoice_filter in str(row.get("invoice_no") or "").casefold()
]
total = len(items)
sliced = items[(page - 1) * page_size : page * page_size]
return {