fix(固资): 固定资产查询去重优化

This commit is contained in:
runny committed 2026-06-10 17:24:58 +08:00
1 parent 2631f78b00
commit 25cc87fdb3
1 file changed
+127 -6
+127 -6
View File
@@ -11,6 +11,8 @@ class Text2SQLService:
_oracle_dll_handles = []
_ASSET_AGENT_NAMES = {"固资管理"}
_ASSET_ALLOWED_OPERATING_CENTER_CODES = ("HXJM", "HTT", "HTE")
_ASSET_CHAT_RESULT_LIMIT = 10
_DEFAULT_RESULT_LIMIT = 50
_ASSET_TABLE_MARKERS = (
"ERP_VIEW_USER.ERP_FAJ_FILE_V",
"ERP_VIEW_USER.ERP_FAB_FILE_V",
@@ -122,6 +124,22 @@ class Text2SQLService:
"当前登录用户",
"登录用户",
)
_ASSET_RESULT_CODE_COLUMNS = {"财产编号", "资产编码", "ASSET_NO", "FAJ02"}
_ASSET_RESULT_STATUS_COLUMNS = {"资产状态", "ASSET_STATUS", "FAJ43"}
_ASSET_STATUS_SORT_ORDER = {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"X": 10,
"Z": 11,
}
@staticmethod
def _backend_dir() -> str:
@@ -843,6 +861,81 @@ ORDER BY faj.faj02
return text
return mapping.get(text.strip().upper(), mapping.get(text.strip(), text))
@staticmethod
def _normalize_result_column_name(name: str) -> str:
return re.sub(r"\s+", "", str(name or "").strip().strip('"')).upper()
@classmethod
def _find_result_column_index(cls, columns, query: str, sql: str, agent, candidate_names: set[str]) -> int | None:
localized_columns = cls._localize_asset_columns(columns, query, sql, agent=agent)
for idx, raw_name in enumerate(columns or []):
normalized_raw = cls._normalize_result_column_name(raw_name)
normalized_localized = cls._normalize_result_column_name(localized_columns[idx] if idx < len(localized_columns) else "")
if normalized_raw in candidate_names or normalized_localized in candidate_names:
return idx
return None
@classmethod
def _get_asset_status_rank(cls, value) -> int:
token = cls._stringify_value(value).strip()
if not token or token == "NULL":
return -1
upper_token = token.upper()
if upper_token in cls._ASSET_STATUS_SORT_ORDER:
return cls._ASSET_STATUS_SORT_ORDER[upper_token]
reverse_mapping = {
str(label or "").strip(): code
for code, label in cls._ASSET_VALUE_MAPPINGS.get("资产状态", {}).items()
}
mapped_code = reverse_mapping.get(token)
if mapped_code is None:
mapped_code = reverse_mapping.get(upper_token)
if mapped_code is None:
return -1
return cls._ASSET_STATUS_SORT_ORDER.get(str(mapped_code).upper(), -1)
@classmethod
def _is_better_asset_row(cls, current_row, candidate_row, status_idx: int | None) -> bool:
if status_idx is None:
return True
current_rank = cls._get_asset_status_rank(current_row[status_idx] if status_idx < len(current_row) else None)
candidate_rank = cls._get_asset_status_rank(candidate_row[status_idx] if status_idx < len(candidate_row) else None)
return candidate_rank >= current_rank
@classmethod
def _dedupe_asset_rows(cls, columns, rows, query: str, sql: str, agent=None):
if not rows:
return rows
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
return rows
if cls._is_aggregate_sql(sql):
return rows
asset_code_idx = cls._find_result_column_index(columns, query, sql, agent, cls._ASSET_RESULT_CODE_COLUMNS)
if asset_code_idx is None:
return rows
status_idx = cls._find_result_column_index(columns, query, sql, agent, cls._ASSET_RESULT_STATUS_COLUMNS)
best_rows: dict[str, tuple] = {}
asset_order: list[str] = []
anonymous_counter = 0
for row in rows:
row_tuple = tuple(row)
asset_code = cls._stringify_value(row_tuple[asset_code_idx] if asset_code_idx < len(row_tuple) else "").strip()
if not asset_code or asset_code == "NULL":
anonymous_counter += 1
asset_key = f"__anonymous__{anonymous_counter}"
else:
asset_key = asset_code
existing_row = best_rows.get(asset_key)
if existing_row is None:
best_rows[asset_key] = row_tuple
asset_order.append(asset_key)
continue
if cls._is_better_asset_row(existing_row, row_tuple, status_idx):
best_rows[asset_key] = row_tuple
return [best_rows[key] for key in asset_order]
@classmethod
def _localize_asset_rows(cls, columns, rows, query: str, sql: str, agent=None):
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
@@ -1254,12 +1347,23 @@ ORDER BY faj.faj02
return f"SELECT '{cls._escape_sql_message(f'SQL Repair Error: {e}')}' AS error FROM DUAL"
@classmethod
def execute_sql(cls, sql: str):
def execute_sql(cls, sql: str, *, query: str = "", agent=None, limit: int | None = None):
connection, cursor, columns, error_rows = cls._execute_sql_internal(sql)
if columns == ["Error"]:
return columns, error_rows
try:
rows = cursor.fetchmany(50)
row_limit = max(1, int(limit or 0)) if limit is not None else None
is_asset_detail = (
not cls._is_aggregate_sql(sql)
and (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql))
)
if is_asset_detail:
raw_rows = cursor.fetchall()
deduped_rows = cls._dedupe_asset_rows(columns, raw_rows, query, sql, agent=agent)
result_limit = row_limit or cls._ASSET_CHAT_RESULT_LIMIT
rows = deduped_rows[:result_limit]
else:
rows = cursor.fetchmany(row_limit or cls._DEFAULT_RESULT_LIMIT)
return columns, rows
finally:
try:
@@ -1268,9 +1372,26 @@ ORDER BY faj.faj02
connection.close()
@classmethod
def execute_sql_page(cls, sql: str, *, page: int = 1, page_size: int = 100):
def execute_sql_page(cls, sql: str, *, query: str = "", page: int = 1, page_size: int = 100, agent=None):
safe_page = max(1, int(page or 1))
safe_page_size = max(1, min(200, int(page_size or 100)))
is_asset_detail = (
not cls._is_aggregate_sql(sql)
and (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql))
)
if is_asset_detail:
connection, cursor, columns, error_rows = cls._execute_sql_internal(sql)
if columns == ["Error"]:
return columns, error_rows
try:
deduped_rows = cls._dedupe_asset_rows(columns, cursor.fetchall(), query, sql, agent=agent)
offset = (safe_page - 1) * safe_page_size
return columns, deduped_rows[offset: offset + safe_page_size]
finally:
try:
cursor.close()
finally:
connection.close()
offset = (safe_page - 1) * safe_page_size
paged_sql = cls._build_paged_query_sql(sql, safe_page_size, offset=offset)
connection, cursor, columns, error_rows = cls._execute_sql_internal(paged_sql)
@@ -1346,7 +1467,7 @@ ORDER BY faj.faj02
@classmethod
def get_preview_page(cls, *, sql: str, query: str, page: int = 1, page_size: int = 100, agent=None, total_count: int | None = None):
raw_columns, raw_rows = cls.execute_sql_page(sql, page=page, page_size=page_size)
raw_columns, raw_rows = cls.execute_sql_page(sql, query=query, page=page, page_size=page_size, agent=agent)
if raw_columns == ["Error"]:
return raw_columns, raw_rows, total_count
resolved_total = total_count if total_count is not None else cls.get_total_count_for_sql(sql)
@@ -1378,7 +1499,7 @@ ORDER BY faj.faj02
# 2. Execute SQL
stage_start = time.time()
columns, rows = Text2SQLService.execute_sql(sql)
columns, rows = Text2SQLService.execute_sql(sql, query=query, agent=agent, limit=Text2SQLService._ASSET_CHAT_RESULT_LIMIT)
execute_sql_ms = int((time.time() - stage_start) * 1000)
if current_app:
current_app.logger.info(
@@ -1405,7 +1526,7 @@ ORDER BY faj.faj02
if repaired_sql and repaired_sql != sql:
sql = repaired_sql
stage_start = time.time()
columns, rows = Text2SQLService.execute_sql(sql)
columns, rows = Text2SQLService.execute_sql(sql, query=query, agent=agent, limit=Text2SQLService._ASSET_CHAT_RESULT_LIMIT)
execute_sql_ms = int((time.time() - stage_start) * 1000)
if current_app:
current_app.logger.info(