""" backend/app/services/fixed_assets_snapshot.py 用途:提供固定资产快照同步、本地结构化落地、Excel 导出与本地查询能力。 依赖:Flask current_app、openpyxl、sqlite3、Text2SQLService(延迟导入)、ERP Oracle。 逻辑:同步主循环由独立进程 workers/worker_fixed_assets.py 运行;Web 进程不再起线程。 text2sql 固资场景优先查本地快照。 """ from __future__ import annotations import json import os import re import shutil import sqlite3 import threading import time from datetime import datetime, timedelta from pathlib import Path from typing import Any from zoneinfo import ZoneInfo from flask import current_app, has_app_context from openpyxl import Workbook from app.path_utils import backend_dir _sync_lock = threading.Lock() class FixedAssetsSnapshotService: """固定资产快照同步与本地查询服务。""" SNAPSHOT_SQL_MARKER = "SNAPSHOT://FIXED_ASSETS" SNAPSHOT_KIND = "fixed_assets_snapshot_preview" PREVIEW_COLUMNS = ( "序号", "资产编号", "资产名称", "保管人", "保管部门", "图片", "账套", "供应商", "资产状态", "数量", "取得时间", ) VISIBLE_COLUMNS = ( "资产编号", "资产名称", "规格型号", "账套", "保管人姓名", "保管部门名称", "存放位置名称", "资产状态", "预留残值", "供应厂商", "资产性质", "本币单价", "数量", "计量单位", "取得日期", "入账日期", ) NATURE_MAP = { "1": "有形资产", "2": "无形资产", "3": "土地", "4": "递耗资产", "5": "费用", } STATUS_MAP = { "0": "取得", "1": "资本化", "2": "折旧中", "3": "外送", "4": "折毕", "5": "出售", "6": "销账", "7": "折旧再提", "8": "改良", "9": "重估", "X": "被资本", "Z": "停用", } ACCOUNT_BOOK_MAP = { "HXJM": "和信精密", "HTT": "和泰科技", "HTE": "和泰电子", } STOPWORDS_PATTERN = re.compile( r"(固定资产|固资|资产编号|财产编号|资产编码|编号|资产名称|设备名称|资产|设备|请问|帮我|看下|查下|查询|统计|核对|看看|我想知道|有多少台?|有多少|多少台?|多少|明细|列表|数据|结果|并且|以及|还有|和|按|根据|生成图表|生成excel|生成表单|导出excel|导出表单|导出)", re.IGNORECASE, ) @classmethod def _storage_root(cls) -> Path: path_value = current_app.config.get("FIXED_ASSETS_STORAGE_ROOT") return Path(str(path_value)).resolve() @classmethod def _docs_export_root(cls) -> Path: path_value = current_app.config.get("FIXED_ASSETS_DOCS_EXPORT_ROOT") return Path(str(path_value)).resolve() @classmethod def _snapshots_dir(cls) -> Path: return cls._storage_root() / "snapshots" @classmethod def _latest_dir(cls) -> Path: return cls._storage_root() / "latest" @classmethod def _manifest_path(cls) -> Path: return cls._storage_root() / "manifest.json" @classmethod def _ensure_storage_dirs(cls) -> None: for path in (cls._storage_root(), cls._snapshots_dir(), cls._latest_dir()): path.mkdir(parents=True, exist_ok=True) @classmethod def _latest_db_path(cls) -> Path: return cls._latest_dir() / "FixedAssets_latest.db" @classmethod def _latest_xlsx_path(cls) -> Path: return cls._latest_dir() / "FixedAssets_latest.xlsx" @staticmethod def _stringify(value: Any) -> str: if value is None: return "" return str(value).strip() @classmethod def _build_preview_row( cls, row_map: dict[str, Any], *, row_number: int, ) -> tuple[Any, ...]: """ 用途:把固资快照原始查询结果收敛成聊天/预览统一使用的展示行。 核心逻辑:按前端固定列顺序输出,并补充“序号”和“图片=查看”两个展示列。 参数约束:row_map 必须包含资产编号等基础字段;当资产编号为空时,“图片”列保持为空,避免误导用户点击。 """ asset_no = cls._stringify(row_map.get("资产编号")) return ( row_number, asset_no, cls._stringify(row_map.get("资产名称")), cls._stringify(row_map.get("保管人姓名")), cls._stringify(row_map.get("保管部门名称")), "查看" if asset_no else "", cls._stringify(row_map.get("账套")), cls._stringify(row_map.get("供应厂商")), cls._stringify(row_map.get("资产状态")), cls._stringify(row_map.get("数量")), cls._stringify(row_map.get("取得日期")), ) @classmethod def _normalize_search_text(cls, text: str) -> str: cleaned = str(text or "").upper() cleaned = re.sub(r"[\s\-_|,::;;,。()()/\\]+", "", cleaned) return cleaned @classmethod def _build_remark(cls, row: dict[str, str]) -> str: parts = [ f"资产编号:{row.get('资产编号', '')}", f"资产名称:{row.get('资产名称', '')}", f"规格型号:{row.get('规格型号', '')}", f"账套:{row.get('账套', '')}({row.get('营运中心代码', '')})", f"保管人姓名:{row.get('保管人姓名', '')}", f"保管部门名称:{row.get('保管部门名称', '')}", f"存放位置名称:{row.get('存放位置名称', '')}", f"资产状态:{row.get('资产状态', '')}", f"供应厂商:{row.get('供应厂商', '')}", f"资产性质:{row.get('资产性质', '')}", ] return " | ".join(parts) @classmethod def _snapshot_identity_key(cls, row: dict[str, str], fallback_index: int) -> str: """生成快照去重键,优先使用资产编号。""" asset_no = cls._stringify(row.get("资产编号")) if asset_no: return asset_no.upper() return f"__ROW_{fallback_index}" @classmethod def _snapshot_row_score(cls, row: dict[str, str]) -> tuple[int, int]: """为重复资产选择信息更完整的一条记录。""" preferred_fields = ( "资产名称", "规格型号", "保管人姓名", "保管部门名称", "存放位置名称", "资产状态", "供应厂商", "资产性质", "本币单价", "数量", "计量单位", "取得日期", "入账日期", ) filled_count = sum(1 for key in preferred_fields if cls._stringify(row.get(key))) text_length = sum(len(cls._stringify(row.get(key))) for key in preferred_fields) return filled_count, text_length @classmethod def _dedupe_snapshot_rows(cls, rows: list[dict[str, str]]) -> list[dict[str, str]]: """按资产编号对快照结果去重,避免联表重复导致同一资产多次入库。""" deduped: dict[str, dict[str, str]] = {} for index, row in enumerate(rows): dedupe_key = cls._snapshot_identity_key(row, index) existing = deduped.get(dedupe_key) if existing is None: deduped[dedupe_key] = row continue if cls._snapshot_row_score(row) > cls._snapshot_row_score(existing): deduped[dedupe_key] = row return list(deduped.values()) @classmethod def _snapshot_sql(cls) -> str: return """ SELECT DISTINCT faj.faj02 AS "资产编号", faj.faj06 AS "资产名称", faj.faj061 AS "资产名称2", faj.faj08 AS "规格型号", gen.gen01 AS "保管人工号", gen.gen02 AS "保管人姓名", gem.gem01 AS "保管部门编号", gem.gem02 AS "保管部门名称", faf.faf02 AS "存放位置名称", faj.faj43 AS "资产状态代码", faj.faj31 AS "预留残值", pmc.pmc03 AS "供应厂商", faj.faj09 AS "资产性质代码", faj.faj13 AS "本币单价", faj.faj17 AS "数量", faj.faj18 AS "计量单位", TO_CHAR(faj.faj25, 'YYYY-MM-DD HH24:MI:SS') AS "取得日期", TO_CHAR(faj.faj26, 'YYYY-MM-DD HH24:MI:SS') AS "入账日期", TRIM(NVL(faj.faj22, '')) AS "营运中心代码", TRIM(NVL(faj.site, '')) AS "站点代码" FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen ON gen.gen01 = faj.faj19 AND gen.site = faj.site LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem ON gem.gem01 = faj.faj20 AND gem.site = faj.site LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf ON faf.faf01 = faj.faj21 AND faf.site = faj.site LEFT JOIN ERP_VIEW_USER.ERP_PMC_FILE_V pmc ON pmc.pmc01 = faj.faj10 AND pmc.site = faj.site WHERE UPPER(TRIM(NVL(faj.faj22, ''))) IN ('HXJM', 'HTT', 'HTE') ORDER BY faj.faj02 """.strip() @classmethod def _oracle_credentials(cls) -> tuple[str, str, str]: username = str(current_app.config.get("FIXED_ASSETS_ERP_USERNAME") or "EXT_VIEW_USER").strip() password = str(current_app.config.get("FIXED_ASSETS_ERP_PASSWORD") or "extviewuser").strip() dsn = str(current_app.config.get("FIXED_ASSETS_ERP_DSN") or os.getenv("ERP_DB_DSN") or "192.168.8.24:1521/topprod").strip() return username, password, dsn @classmethod def _fetch_snapshot_rows(cls, timeout_seconds: int) -> list[dict[str, str]]: """从 ERP Oracle 拉取固定资产全量快照。""" import oracledb from app.services.integrations.text2sql import Text2SQLService username, password, dsn = cls._oracle_credentials() Text2SQLService._init_oracle_client(oracledb) connection = None cursor = None try: connection = oracledb.connect(user=username, password=password, dsn=dsn) connection.call_timeout = max(1, int(timeout_seconds)) * 1000 cursor = connection.cursor() cursor.execute(cls._snapshot_sql()) columns = [str(col[0] or "").strip() for col in cursor.description] rows = cursor.fetchall() normalized_rows: list[dict[str, str]] = [] for raw_row in rows: item = { columns[idx]: cls._stringify(value) for idx, value in enumerate(raw_row) } item["账套"] = cls.ACCOUNT_BOOK_MAP.get( item.get("营运中心代码", "").strip().upper(), item.get("营运中心代码", ""), ) item["资产状态"] = cls.STATUS_MAP.get(item.get("资产状态代码", "").upper(), item.get("资产状态代码", "")) item["资产性质"] = cls.NATURE_MAP.get(item.get("资产性质代码", ""), item.get("资产性质代码", "")) item["备注"] = cls._build_remark(item) item["备注标准化"] = cls._normalize_search_text(item["备注"]) normalized_rows.append(item) return cls._dedupe_snapshot_rows(normalized_rows) finally: if cursor is not None: try: cursor.close() except Exception: pass if connection is not None: try: connection.close() except Exception: pass @classmethod def _snapshot_db_schema_sql(cls) -> list[str]: return [ """ CREATE TABLE IF NOT EXISTS fixed_assets ( asset_no TEXT, asset_name TEXT, asset_name2 TEXT, specification TEXT, custodian_id TEXT, custodian_name TEXT, department_code TEXT, department_name TEXT, location_name TEXT, asset_status TEXT, asset_status_code TEXT, residual_value TEXT, vendor_name TEXT, asset_nature TEXT, asset_nature_code TEXT, unit_price TEXT, quantity TEXT, unit TEXT, acquisition_date TEXT, accounting_date TEXT, operating_center_code TEXT, site_code TEXT, remark TEXT, remark_normalized TEXT, snapshot_version TEXT, snapshot_date TEXT ) """.strip(), "CREATE INDEX IF NOT EXISTS idx_fixed_assets_no ON fixed_assets(asset_no)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_name ON fixed_assets(asset_name)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_name2 ON fixed_assets(asset_name2)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_spec ON fixed_assets(specification)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_custodian ON fixed_assets(custodian_name)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_department ON fixed_assets(department_name)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_location ON fixed_assets(location_name)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_status ON fixed_assets(asset_status)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_vendor ON fixed_assets(vendor_name)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_nature ON fixed_assets(asset_nature)", "CREATE INDEX IF NOT EXISTS idx_fixed_assets_remark_norm ON fixed_assets(remark_normalized)", ] @classmethod def _write_snapshot_db(cls, db_path: Path, rows: list[dict[str, str]], version: str, snapshot_date: str) -> None: """将快照数据写入 SQLite。""" if db_path.exists(): db_path.unlink() conn = sqlite3.connect(db_path) try: cursor = conn.cursor() for statement in cls._snapshot_db_schema_sql(): cursor.execute(statement) insert_sql = """ INSERT INTO fixed_assets ( asset_no, asset_name, asset_name2, specification, custodian_id, custodian_name, department_code, department_name, location_name, asset_status, asset_status_code, residual_value, vendor_name, asset_nature, asset_nature_code, unit_price, quantity, unit, acquisition_date, accounting_date, operating_center_code, site_code, remark, remark_normalized, snapshot_version, snapshot_date ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """.strip() payload = [] for item in rows: payload.append( ( item.get("资产编号", ""), item.get("资产名称", ""), item.get("资产名称2", ""), item.get("规格型号", ""), item.get("保管人工号", ""), item.get("保管人姓名", ""), item.get("保管部门编号", ""), item.get("保管部门名称", ""), item.get("存放位置名称", ""), item.get("资产状态", ""), item.get("资产状态代码", ""), item.get("预留残值", ""), item.get("供应厂商", ""), item.get("资产性质", ""), item.get("资产性质代码", ""), item.get("本币单价", ""), item.get("数量", ""), item.get("计量单位", ""), item.get("取得日期", ""), item.get("入账日期", ""), item.get("营运中心代码", ""), item.get("站点代码", ""), item.get("备注", ""), item.get("备注标准化", ""), version, snapshot_date, ) ) cursor.executemany(insert_sql, payload) conn.commit() finally: conn.close() @classmethod def _export_snapshot_excel(cls, excel_path: Path, rows: list[dict[str, str]]) -> None: """导出快照 Excel 文件。""" workbook = Workbook() sheet = workbook.active sheet.title = "FixedAssets" header = list(cls.VISIBLE_COLUMNS) + ["备注"] sheet.append(header) for item in rows: sheet.append([ item.get("资产编号", ""), item.get("资产名称", ""), item.get("规格型号", ""), item.get("账套", ""), item.get("保管人姓名", ""), item.get("保管部门名称", ""), item.get("存放位置名称", ""), item.get("资产状态", ""), item.get("预留残值", ""), item.get("供应厂商", ""), item.get("资产性质", ""), item.get("本币单价", ""), item.get("数量", ""), item.get("计量单位", ""), item.get("取得日期", ""), item.get("入账日期", ""), item.get("备注", ""), ]) workbook.save(excel_path) @classmethod def _write_manifest(cls, payload: dict[str, Any]) -> None: cls._ensure_storage_dirs() cls._manifest_path().write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") @classmethod def _load_manifest(cls) -> dict[str, Any]: path = cls._manifest_path() if not path.exists(): return {} try: return json.loads(path.read_text(encoding="utf-8")) except Exception: return {} @classmethod def _promote_snapshot(cls, version: str, db_path: Path, excel_path: Path) -> dict[str, str]: cls._ensure_storage_dirs() latest_db = cls._latest_db_path() latest_xlsx = cls._latest_xlsx_path() shutil.copy2(db_path, latest_db) shutil.copy2(excel_path, latest_xlsx) docs_exports: dict[str, str] = {} if current_app.config.get("FIXED_ASSETS_EXPORT_TO_DOCS", True): docs_root = cls._docs_export_root() docs_root.mkdir(parents=True, exist_ok=True) docs_latest = docs_root / "FixedAssets_latest.xlsx" docs_versioned = docs_root / f"FixedAssets_{version}.xlsx" shutil.copy2(excel_path, docs_latest) shutil.copy2(excel_path, docs_versioned) docs_exports = { "docs_latest_xlsx": str(docs_latest), "docs_versioned_xlsx": str(docs_versioned), } return { "latest_db": str(latest_db), "latest_xlsx": str(latest_xlsx), **docs_exports, } @classmethod def _cleanup_temp_snapshot_files(cls, directory: Path) -> None: """清理 Excel 打开时遗留的临时锁文件。""" if not directory.exists(): return for temp_file in directory.glob("~$FixedAssets*.xlsx"): try: temp_file.unlink() except OSError as exc: cls._log("warning", f"Failed to remove temp snapshot file {temp_file}: {exc}") @classmethod def _cleanup_versioned_files( cls, directory: Path, *, patterns: tuple[str, ...], keep_count: int, ) -> None: """按版本号仅保留最近 N 份历史文件,跳过 latest 固定别名文件。""" if not directory.exists(): return version_files: dict[str, list[Path]] = {} for pattern in patterns: for file_path in directory.glob(pattern): if file_path.name.startswith("~$"): continue match = re.fullmatch(r"FixedAssets_(\d{8}_\d{6})", file_path.stem) if not match: continue version_files.setdefault(match.group(1), []).append(file_path) version_keys = sorted(version_files.keys(), reverse=True) obsolete_keys = version_keys[keep_count:] for version_key in obsolete_keys: for file_path in version_files.get(version_key, []): try: file_path.unlink() except OSError as exc: cls._log("warning", f"Failed to remove obsolete snapshot file {file_path}: {exc}") @classmethod def _cleanup_history_snapshots(cls, keep_count: int | None = None) -> None: """仅保留最新 N 份历史快照,额外旧文件自动清理。""" cls._ensure_storage_dirs() snapshots_dir = cls._snapshots_dir() cls._cleanup_temp_snapshot_files(snapshots_dir) safe_keep_count = max(1, int(keep_count or current_app.config.get("FIXED_ASSETS_HISTORY_KEEP_COUNT", 3) or 3)) cls._cleanup_versioned_files( snapshots_dir, patterns=("FixedAssets_*.db", "FixedAssets_*.xlsx"), keep_count=safe_keep_count, ) if current_app.config.get("FIXED_ASSETS_EXPORT_TO_DOCS", True): docs_root = cls._docs_export_root() cls._cleanup_temp_snapshot_files(docs_root) cls._cleanup_versioned_files( docs_root, patterns=("FixedAssets_*.xlsx",), keep_count=safe_keep_count, ) @classmethod def is_snapshot_available(cls) -> bool: return cls._latest_db_path().exists() @classmethod def sync_once(cls, *, reason: str = "manual", attempt: int = 1) -> dict[str, Any]: """执行一次固资快照同步。""" with _sync_lock: cls._ensure_storage_dirs() timeout_seconds = int(current_app.config.get("FIXED_ASSETS_SYNC_TIMEOUT_SECONDS", 600) or 600) started_at = datetime.utcnow() version = started_at.strftime("%Y%m%d_%H%M%S") snapshot_date = started_at.strftime("%Y-%m-%d") version_db = cls._snapshots_dir() / f"FixedAssets_{version}.db" version_xlsx = cls._snapshots_dir() / f"FixedAssets_{version}.xlsx" try: rows = cls._fetch_snapshot_rows(timeout_seconds) cls._write_snapshot_db(version_db, rows, version, snapshot_date) cls._export_snapshot_excel(version_xlsx, rows) promoted_paths = cls._promote_snapshot(version, version_db, version_xlsx) cls._cleanup_history_snapshots() manifest = { "status": "success", "last_reason": reason, "last_attempt": attempt, "last_started_at": started_at.isoformat(), "last_finished_at": datetime.utcnow().isoformat(), "last_success_at": datetime.utcnow().isoformat(), "current_version": version, "snapshot_date": snapshot_date, "row_count": len(rows), "files": { "versioned_db": str(version_db), "versioned_xlsx": str(version_xlsx), **promoted_paths, }, } cls._write_manifest(manifest) cls._log("info", f"Fixed assets snapshot synced successfully version={version} row_count={len(rows)}") return manifest except Exception as exc: manifest = cls._load_manifest() manifest.update({ "status": "failed", "last_reason": reason, "last_attempt": attempt, "last_started_at": started_at.isoformat(), "last_finished_at": datetime.utcnow().isoformat(), "last_error": str(exc), }) cls._write_manifest(manifest) cls._log("warning", f"Fixed assets snapshot sync failed attempt={attempt}: {exc}") raise @classmethod def sync_with_retry(cls, *, reason: str = "schedule") -> dict[str, Any]: """按配置执行同步与重试。""" max_attempts = max(1, int(current_app.config.get("FIXED_ASSETS_SYNC_MAX_ATTEMPTS", 4) or 4)) retry_interval_seconds = max( 60, int(current_app.config.get("FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES", 30) or 30) * 60, ) last_error: Exception | None = None for attempt in range(1, max_attempts + 1): try: return cls.sync_once(reason=reason, attempt=attempt) except Exception as exc: # pragma: no cover - runtime branch last_error = exc if attempt >= max_attempts: break cls._log( "warning", f"Fixed assets snapshot will retry after {retry_interval_seconds}s, attempt={attempt}, error={exc}", ) time.sleep(retry_interval_seconds) if last_error is not None: raise last_error raise RuntimeError("Fixed assets snapshot sync failed without explicit error") @classmethod def _tokenize_query(cls, query: str) -> list[str]: cleaned = cls.STOPWORDS_PATTERN.sub(" ", str(query or "")) tokens = re.findall(r"[A-Za-z0-9\u4e00-\u9fff()()_-]{2,40}", cleaned) normalized_tokens: list[str] = [] for token in tokens: normalized = cls._normalize_search_text(token) if normalized and normalized not in normalized_tokens: normalized_tokens.append(normalized) return normalized_tokens[:5] @classmethod def _build_generic_keyword_match_clause(cls, keyword: str) -> tuple[str, list[str]]: """为宽泛资产关键词查询构造更严格的直连字段匹配条件。 AI 触发时机:当用户只输入“资讯有哪些资产”“电脑有哪些资产”这类宽泛关键词时, 不能再把 `remark_normalized` 这类兜底字段也纳入匹配,否则容易把仅备注命中的低质量记录一起带出。 Args: keyword: 已抽取的资产关键词。 Returns: tuple[str, list[str]]: SQL 条件片段与对应参数。 """ like_keyword = f"%{keyword.upper()}%" clause = ( "(" "UPPER(COALESCE(asset_name, '')) LIKE ? " "OR UPPER(COALESCE(asset_name2, '')) LIKE ? " "OR UPPER(COALESCE(specification, '')) LIKE ? " "OR UPPER(COALESCE(location_name, '')) LIKE ? " "OR UPPER(COALESCE(custodian_name, '')) LIKE ? " "OR UPPER(COALESCE(department_name, '')) LIKE ? " "OR UPPER(COALESCE(vendor_name, '')) LIKE ?" ")" ) return clause, [like_keyword] * 7 @classmethod def _generic_result_quality_guard_sql(cls) -> str: """过滤仅命中名称但关键业务列几乎全空的低质量快照记录。 AI 触发时机:宽泛关键词查询会返回很多候选记录,其中一部分只有资产名称, 其余关键字段(编号、保管人、部门、账套、供应商、状态、数量、取得日期)全部为空。 这类记录即使展示出来也无法支撑业务判断,应在快照层直接剔除。 """ informative_fields = ( "asset_no", "custodian_name", "department_name", "operating_center_code", "vendor_name", "asset_status", "quantity", "acquisition_date", ) checks = [f"TRIM(COALESCE({field}, '')) <> ''" for field in informative_fields] return "(" + " OR ".join(checks) + ")" @classmethod def _generic_result_quality_score_sql(cls) -> str: """为宽泛关键词查询生成字段完整度评分,便于优先展示高质量记录。""" informative_fields = ( "asset_no", "custodian_name", "department_name", "operating_center_code", "vendor_name", "asset_status", "quantity", "acquisition_date", ) return " + ".join( f"CASE WHEN TRIM(COALESCE({field}, '')) <> '' THEN 1 ELSE 0 END" for field in informative_fields ) @classmethod def _build_where_clause( cls, query: str, user_context: dict[str, Any] | None = None, ) -> tuple[str, list[str], dict[str, Any]]: """根据用户问句生成本地快照过滤条件。""" from app.services.integrations.text2sql import Text2SQLService clauses: list[str] = [] params: list[str] = [] query_profile = {"uses_generic_keyword_search": False} advanced_conds = Text2SQLService._extract_advanced_asset_conditions(query) asset_code = advanced_conds.get("asset_code") or Text2SQLService._extract_asset_code(query) asset_name = advanced_conds.get("asset_name") or Text2SQLService._extract_asset_name_keyword(query) asset_nature_code = Text2SQLService._extract_asset_nature_code(query) explicit_scope = Text2SQLService._extract_asset_scope(query) has_explicit_location = bool(advanced_conds.get("location")) has_explicit_vendor = bool(advanced_conds.get("vendor")) has_explicit_spec = bool(advanced_conds.get("spec")) has_explicit_status = bool(advanced_conds.get("status")) has_explicit_person = bool(explicit_scope.get("person")) has_explicit_department = bool(explicit_scope.get("department")) should_use_generic_keyword_search = bool( asset_name and not asset_code and not has_explicit_location and not has_explicit_vendor and not has_explicit_spec and not has_explicit_status and not has_explicit_person and not has_explicit_department and not asset_nature_code ) if asset_code: clauses.append("UPPER(COALESCE(asset_no, '')) LIKE ?") params.append(f"%{asset_code.upper()}%") if asset_name and not should_use_generic_keyword_search: clauses.append("(UPPER(COALESCE(asset_name, '')) LIKE ? OR UPPER(COALESCE(asset_name2, '')) LIKE ?)") params.extend([f"%{asset_name.upper()}%", f"%{asset_name.upper()}%"]) if "spec" in advanced_conds: clauses.append("UPPER(COALESCE(specification, '')) LIKE ?") params.append(f"%{advanced_conds['spec'].upper()}%") if "status" in advanced_conds: clauses.append("UPPER(COALESCE(asset_status, '')) LIKE ?") params.append(f"%{advanced_conds['status'].upper()}%") if "vendor" in advanced_conds: clauses.append("UPPER(COALESCE(vendor_name, '')) LIKE ?") params.append(f"%{advanced_conds['vendor'].upper()}%") if "location" in advanced_conds: clauses.append("UPPER(COALESCE(location_name, '')) LIKE ?") params.append(f"%{advanced_conds['location'].upper()}%") if asset_nature_code: asset_nature = cls.NATURE_MAP.get(asset_nature_code, asset_nature_code) clauses.append("UPPER(COALESCE(asset_nature, '')) = ?") params.append(asset_nature.upper()) explicit_person = explicit_scope.get("person") if explicit_person: clauses.append("UPPER(COALESCE(custodian_name, '')) LIKE ?") params.append(f"%{explicit_person.upper()}%") explicit_department = explicit_scope.get("department") if explicit_department: clauses.append("UPPER(COALESCE(department_name, '')) LIKE ?") params.append(f"%{explicit_department.upper()}%") if should_use_generic_keyword_search: generic_clause, generic_params = cls._build_generic_keyword_match_clause(asset_name) clauses.append(generic_clause) params.extend(generic_params) query_profile["uses_generic_keyword_search"] = True normalized_user = user_context or {} if Text2SQLService._is_self_asset_query(query): self_clauses = [] for candidate in (normalized_user.get("employee_id"), normalized_user.get("username")): value = cls._stringify(candidate) if not value: continue self_clauses.append("UPPER(COALESCE(custodian_id, '')) = ?") params.append(value.upper()) real_name = cls._stringify(normalized_user.get("real_name")) if real_name: self_clauses.append("UPPER(COALESCE(custodian_name, '')) = ?") params.append(real_name.upper()) if self_clauses: clauses.append("(" + " OR ".join(self_clauses) + ")") if not clauses and not Text2SQLService._is_company_asset_detail_query(query): tokens = cls._tokenize_query(query) for token in tokens: clauses.append("UPPER(COALESCE(remark_normalized, '')) LIKE ?") params.append(f"%{token}%") where_sql = " AND ".join(clauses) if clauses else "1=1" return where_sql, params, query_profile @classmethod def query_assets( cls, query: str, *, limit: int = 10, offset: int = 0, user_context: dict[str, Any] | None = None, ) -> tuple[list[str], list[tuple], int]: """查询最新固资快照。""" if not cls.is_snapshot_available(): return ["Error"], [("固定资产快照尚未生成,请稍后重试。",)], 0 where_sql, params, query_profile = cls._build_where_clause(query, user_context=user_context) deduped_assets_cte = """ WITH deduped_assets AS ( SELECT * FROM ( SELECT fixed_assets.*, ROW_NUMBER() OVER ( PARTITION BY CASE WHEN TRIM(COALESCE(asset_no, '')) = '' THEN '__ROW_' || rowid ELSE UPPER(TRIM(asset_no)) END ORDER BY rowid ) AS dedupe_rn FROM fixed_assets ) WHERE dedupe_rn = 1 ) """.strip() filtered_assets_cte = "" result_source_name = "deduped_assets" order_by_sql = "asset_no" if query_profile.get("uses_generic_keyword_search"): filtered_assets_cte = f""" , filtered_assets AS ( SELECT *, {cls._generic_result_quality_score_sql()} AS quality_score FROM deduped_assets WHERE {cls._generic_result_quality_guard_sql()} ) """.rstrip() result_source_name = "filtered_assets" order_by_sql = ( "quality_score DESC, " "CASE WHEN TRIM(COALESCE(asset_no, '')) = '' THEN 1 ELSE 0 END, " "asset_no, asset_name" ) visible_select = """ asset_no AS "资产编号", asset_name AS "资产名称", specification AS "规格型号", operating_center_code AS "账套", custodian_name AS "保管人姓名", department_name AS "保管部门名称", location_name AS "存放位置名称", asset_status AS "资产状态", residual_value AS "预留残值", vendor_name AS "供应厂商", asset_nature AS "资产性质", unit_price AS "本币单价", quantity AS "数量", unit AS "计量单位", acquisition_date AS "取得日期", accounting_date AS "入账日期" """.strip() list_sql = f""" {deduped_assets_cte} {filtered_assets_cte} SELECT {visible_select} FROM {result_source_name} WHERE {where_sql} ORDER BY {order_by_sql} LIMIT ? OFFSET ? """.strip() count_sql = f""" {deduped_assets_cte} {filtered_assets_cte} SELECT COUNT(*) FROM {result_source_name} WHERE {where_sql} """.strip() conn = sqlite3.connect(cls._latest_db_path()) try: cursor = conn.cursor() cursor.execute(count_sql, params) total_count = int(cursor.fetchone()[0] or 0) cursor.execute(list_sql, [*params, max(1, int(limit)), max(0, int(offset))]) raw_columns = [str(item[0] or "").strip() for item in cursor.description] raw_rows = [tuple(row) for row in cursor.fetchall()] rows = [] for index, row in enumerate(raw_rows, start=max(0, int(offset)) + 1): row_map = { raw_columns[column_index]: row[column_index] for column_index in range(min(len(raw_columns), len(row))) } rows.append(cls._build_preview_row(row_map, row_number=index)) return list(cls.PREVIEW_COLUMNS), rows, total_count finally: conn.close() @classmethod def get_snapshot_preview_payload( cls, query: str, columns: list[str], rows: list[tuple], total_count: int, ) -> dict[str, Any]: return { "kind": "text2sql_result_preview", "previewable": total_count > len(rows or []), "query": query, "sql": cls.SNAPSHOT_SQL_MARKER, "total_count": total_count, "preview_row_count": len(rows or []), "display_columns": list(columns or []), "data_source": cls.SNAPSHOT_KIND, } @classmethod def is_snapshot_sql(cls, sql: str) -> bool: return str(sql or "").strip().startswith(cls.SNAPSHOT_SQL_MARKER) @classmethod def snapshot_sql_label(cls) -> str: manifest = cls._load_manifest() version = str(manifest.get("current_version") or "").strip() if version: return f"固定资产快照查询(版本 {version})" return "固定资产快照查询" @classmethod def _should_run_bootstrap(cls) -> bool: return bool(current_app.config.get("FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING", True)) and not cls.is_snapshot_available() @classmethod def _local_now(cls, timezone_name: str) -> datetime: return datetime.now(ZoneInfo(timezone_name)) @classmethod def _next_run_at(cls, now_local: datetime, hour: int, minute: int) -> datetime: scheduled = now_local.replace(hour=hour, minute=minute, second=0, microsecond=0) if now_local >= scheduled: scheduled = scheduled + timedelta(days=1) return scheduled @classmethod def run_worker_forever(cls, app) -> None: """ 在独立进程中运行固资快照同步主循环(阻塞)。 核心逻辑:若本地无快照且开启 boot 补齐则先 bootstrap;之后按配置时区每日定点 sync_with_retry。 参数: app: Flask 应用(须已 create_app);本方法内部进入 app_context。 """ cls._worker_loop(app) @classmethod def _worker_loop(cls, app) -> None: with app.app_context(): if not bool(app.config.get("FIXED_ASSETS_SYNC_ENABLED", True)): cls._log("info", "Fixed assets snapshot worker disabled by config; exiting") return timezone_name = str(app.config.get("FIXED_ASSETS_SYNC_TIMEZONE") or "Asia/Shanghai").strip() schedule_hour = int(app.config.get("FIXED_ASSETS_SYNC_HOUR", 3) or 3) schedule_minute = int(app.config.get("FIXED_ASSETS_SYNC_MINUTE", 0) or 0) poll_seconds = max(30, int(app.config.get("FIXED_ASSETS_SYNC_POLL_SECONDS", 60) or 60)) cls._log( "info", f"Fixed assets snapshot worker loop started tz={timezone_name} " f"daily={schedule_hour:02d}:{schedule_minute:02d} poll={poll_seconds}s", ) if cls._should_run_bootstrap(): try: cls.sync_with_retry(reason="bootstrap") except Exception as exc: # pragma: no cover - runtime branch cls._log("warning", f"Bootstrap fixed assets snapshot failed: {exc}") next_run = cls._next_run_at(cls._local_now(timezone_name), schedule_hour, schedule_minute) while True: # pragma: no cover - runtime branch now_local = cls._local_now(timezone_name) if now_local >= next_run: try: cls.sync_with_retry(reason="schedule") except Exception as exc: cls._log("warning", f"Scheduled fixed assets snapshot failed: {exc}") next_run = cls._next_run_at(cls._local_now(timezone_name), schedule_hour, schedule_minute) time.sleep(poll_seconds) @classmethod def start_worker(cls, app) -> None: """ 已废弃:请使用独立进程 workers/worker_fixed_assets.py。 保留方法签名以免外部脚本误调崩溃;仅打日志,不再在 Web 进程起线程。 """ app.logger.warning( "FixedAssetsSnapshotService.start_worker is deprecated; " "run workers/worker_fixed_assets.py instead (no in-process thread)" ) @staticmethod def _log(level: str, message: str) -> None: if has_app_context(): getattr(current_app.logger, level, current_app.logger.info)(message)