Files
syops/backend/app/services/fixed_asset_history.py
T

326 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/fixed_asset_history.py
用途:为固资管理提供“资产履历”共享盘检索能力,按资产编号/资产名称匹配履历文件。
依赖:app.core.config.settings.Config、chat.py 里的预览代理会复用这里返回的共享盘文件路径。
逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索共享盘 -> 前端拿到候选履历文件后继续走既有预览弹窗。
"""
from __future__ import annotations
import os
import re
import subprocess
import threading
import time
from dataclasses import dataclass
from flask import current_app, has_app_context
from app.core.config.settings import Config
_CONNECT_LOCK = threading.Lock()
_LAST_CONNECT_AT = 0.0
_CONNECT_COOLDOWN_SECONDS = 30.0
@dataclass(slots=True)
class AssetHistoryCandidate:
"""资产履历候选文件。"""
path: str
relative_path: str
name: str
actual_ext: str
size_bytes: int
modified_at: str
score: int
match_reason: str
def to_dict(self) -> dict[str, object]:
return {
"name": self.name,
"path": self.path,
"relative_path": self.relative_path,
"actual_ext": self.actual_ext,
"size_bytes": self.size_bytes,
"modified_at": self.modified_at,
"match_reason": self.match_reason,
"url": self.path,
}
class FixedAssetHistoryService:
"""
固资履历检索服务。
AI 触发时机:
- 当聊天结果里已经拿到了具体资产编号,用户点击“资产编号”想看履历时调用;
- 输入必须至少包含资产编号或资产名称中的一个;
- 输出只返回共享盘上可预览的候选文件,不直接拼接文件内容。
"""
HISTORY_FILE_EXTENSIONS = {".xls", ".xlsx", ".pdf", ".doc", ".docx", ".txt"}
@classmethod
def _get_runtime_setting(cls, key: str, default: str = "") -> str:
if has_app_context():
try:
value = current_app.config.get(key)
if value is not None:
return str(value)
except Exception:
pass
return str(getattr(Config, key, default) or default)
@classmethod
def is_enabled(cls) -> bool:
return bool(cls.get_share_root())
@classmethod
def get_share_root(cls) -> str:
return cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_ROOT').strip()
@classmethod
def search_history_files(
cls,
*,
asset_id: str,
asset_name: str = "",
limit: int | None = None,
) -> list[dict[str, object]]:
"""
按资产编号/资产名称检索履历文件。
[STEP 1] 先尝试建立共享盘访问权限,避免 Windows 服务账号没有提前挂载网络盘。
[STEP 2] 优先用资产编号做全局文件名命中,确保定位到唯一设备履历。
[STEP 3] 再用资产名称命中同名文件夹/文件,补足部分历史文件只按设备名称归档的情况。
"""
asset_id_value = cls._normalize_keyword(asset_id)
asset_name_value = cls._normalize_keyword(asset_name)
if not asset_id_value and not asset_name_value:
return []
root = cls.get_share_root()
if not root:
return []
if not os.path.exists(root):
cls._ensure_share_connected(root)
if not os.path.isdir(root):
return []
max_results = max(
1,
min(int(limit or cls._get_runtime_setting('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or 20), 50),
)
candidates: dict[str, AssetHistoryCandidate] = {}
if asset_id_value:
for current_root, _dirs, files in os.walk(root):
for filename in files:
candidate = cls._build_candidate(
root=root,
file_path=os.path.join(current_root, filename),
asset_id=asset_id_value,
asset_name=asset_name_value,
match_reason="asset_id",
)
if candidate:
cls._merge_candidate(candidates, candidate)
folder_candidates = cls._find_matching_folders(root, asset_name_value)
for folder_path in folder_candidates:
for current_root, _dirs, files in os.walk(folder_path):
for filename in files:
candidate = cls._build_candidate(
root=root,
file_path=os.path.join(current_root, filename),
asset_id=asset_id_value,
asset_name=asset_name_value,
match_reason="asset_name_folder",
)
if candidate:
cls._merge_candidate(candidates, candidate)
if asset_name_value:
for entry in os.scandir(root):
if not entry.is_file():
continue
candidate = cls._build_candidate(
root=root,
file_path=entry.path,
asset_id=asset_id_value,
asset_name=asset_name_value,
match_reason="asset_name_file",
)
if candidate:
cls._merge_candidate(candidates, candidate)
ordered = sorted(
candidates.values(),
key=lambda item: (-item.score, item.relative_path.lower(), item.name.lower()),
)
return [item.to_dict() for item in ordered[:max_results]]
@classmethod
def _merge_candidate(
cls,
existing: dict[str, AssetHistoryCandidate],
candidate: AssetHistoryCandidate,
) -> None:
previous = existing.get(candidate.path)
if previous is None or candidate.score > previous.score:
existing[candidate.path] = candidate
@classmethod
def _find_matching_folders(cls, root: str, asset_name: str) -> list[str]:
if not asset_name:
return []
matches: list[str] = []
for entry in os.scandir(root):
if not entry.is_dir():
continue
normalized_folder = cls._normalize_keyword(entry.name)
if asset_name and asset_name in normalized_folder:
matches.append(entry.path)
return matches
@classmethod
def _build_candidate(
cls,
*,
root: str,
file_path: str,
asset_id: str,
asset_name: str,
match_reason: str,
) -> AssetHistoryCandidate | None:
if not os.path.isfile(file_path):
return None
ext = os.path.splitext(file_path)[1].strip().lower()
if ext and ext not in cls.HISTORY_FILE_EXTENSIONS:
return None
filename = os.path.basename(file_path)
searchable_parts = [
cls._normalize_keyword(filename),
cls._normalize_keyword(os.path.relpath(file_path, root)),
]
searchable_text = " ".join(part for part in searchable_parts if part)
if not searchable_text:
return None
if asset_id and asset_id not in searchable_text:
return None
if asset_name and asset_name not in searchable_text and match_reason != "asset_id":
return None
score = cls._score_candidate(
searchable_text=searchable_text,
filename=cls._normalize_keyword(filename),
asset_id=asset_id,
asset_name=asset_name,
match_reason=match_reason,
)
if score <= 0:
return None
stat = os.stat(file_path)
return AssetHistoryCandidate(
path=file_path,
relative_path=os.path.relpath(file_path, root).replace("/", "\\"),
name=filename,
actual_ext=ext.lstrip("."),
size_bytes=int(stat.st_size),
modified_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stat.st_mtime)),
score=score,
match_reason=match_reason,
)
@classmethod
def _score_candidate(
cls,
*,
searchable_text: str,
filename: str,
asset_id: str,
asset_name: str,
match_reason: str,
) -> int:
score = 0
if asset_id:
if asset_id in filename:
score += 120
elif asset_id in searchable_text:
score += 80
if asset_name:
if asset_name in filename:
score += 60
elif asset_name in searchable_text:
score += 40
if "履历" in filename:
score += 20
if match_reason == "asset_name_folder":
score += 10
return score
@classmethod
def _normalize_keyword(cls, value: str | None) -> str:
text = str(value or "").strip().lower()
if not text:
return ""
return re.sub(r"[\s\\/_\-()()【】\[\],。,;;::]+", "", text)
@classmethod
def _ensure_share_connected(cls, root: str) -> None:
"""
尝试用配置的账号密码建立共享盘会话。
账号密码只从环境变量读取,避免把敏感信息写进仓库。
"""
username = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_USERNAME').strip()
password = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_PASSWORD')
if not username or not password:
return
share_root = cls._extract_server_share_root(root)
if not share_root:
return
global _LAST_CONNECT_AT
now = time.time()
if now - _LAST_CONNECT_AT < _CONNECT_COOLDOWN_SECONDS:
return
with _CONNECT_LOCK:
if time.time() - _LAST_CONNECT_AT < _CONNECT_COOLDOWN_SECONDS:
return
try:
subprocess.run(
[
"net",
"use",
share_root,
password,
f"/user:{username}",
"/persistent:no",
],
check=False,
capture_output=True,
text=True,
timeout=8,
)
except Exception:
return
_LAST_CONNECT_AT = time.time()
@staticmethod
def _extract_server_share_root(path_value: str) -> str:
normalized = str(path_value or "").strip().replace("/", "\\")
if not normalized.startswith("\\\\"):
return ""
parts = [part for part in normalized[2:].split("\\") if part]
if len(parts) < 2:
return ""
return f"\\\\{parts[0]}\\{parts[1]}"