Merge branch 'dev' into test
This commit is contained in:
commit
89616179db
5 files changed
+627
-56
No files matched your search
@@ -983,6 +983,60 @@ def save_local_message():
|
|||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
||||||
|
|
||||||
|
@chat_bp.route('/query-preview/<int:chat_log_id>', methods=['GET'])
|
||||||
|
@require_agent_permission
|
||||||
|
def get_chat_query_preview(chat_log_id: int):
|
||||||
|
page = request.args.get('page', type=int) or 1
|
||||||
|
page_size = request.args.get('page_size', type=int) or 100
|
||||||
|
page = max(1, page)
|
||||||
|
page_size = max(1, min(200, page_size))
|
||||||
|
|
||||||
|
log = db.session.query(ChatLog).filter(
|
||||||
|
ChatLog.id == chat_log_id,
|
||||||
|
ChatLog.user_id == getattr(g.current_user, 'id', 0),
|
||||||
|
ChatLog.agent_id == getattr(g.current_agent, 'id', 0),
|
||||||
|
).first()
|
||||||
|
if not log:
|
||||||
|
raise NotFoundError('query preview not found')
|
||||||
|
|
||||||
|
payload = log.payload if isinstance(log.payload, dict) else {}
|
||||||
|
if payload.get('kind') != 'text2sql_result_preview':
|
||||||
|
raise ValidationError('current message does not support query preview')
|
||||||
|
|
||||||
|
sql = str(payload.get('sql') or '').strip()
|
||||||
|
query = str(payload.get('query') or log.query or '').strip()
|
||||||
|
if not sql:
|
||||||
|
raise ValidationError('query preview sql is missing')
|
||||||
|
|
||||||
|
from app.services.text2sql import Text2SQLService
|
||||||
|
total_count = payload.get('total_count')
|
||||||
|
try:
|
||||||
|
total_count = int(total_count) if total_count is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
total_count = None
|
||||||
|
|
||||||
|
columns, rows, resolved_total = Text2SQLService.get_preview_page(
|
||||||
|
sql=sql,
|
||||||
|
query=query,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
agent=g.current_agent,
|
||||||
|
total_count=total_count,
|
||||||
|
)
|
||||||
|
if columns == ["Error"]:
|
||||||
|
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
|
||||||
|
|
||||||
|
total = resolved_total if resolved_total is not None else len(rows)
|
||||||
|
return jsonify({
|
||||||
|
'columns': columns,
|
||||||
|
'rows': [list(row) for row in rows],
|
||||||
|
'page': page,
|
||||||
|
'page_size': page_size,
|
||||||
|
'total': total,
|
||||||
|
'has_more': page * page_size < total,
|
||||||
|
'query': query,
|
||||||
|
})
|
||||||
|
|
||||||
@chat_bp.route('/completions', methods=['POST'])
|
@chat_bp.route('/completions', methods=['POST'])
|
||||||
@require_agent_permission
|
@require_agent_permission
|
||||||
def chat_completions():
|
def chat_completions():
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ class Text2SQLService:
|
|||||||
_oracle_client_initialized = False
|
_oracle_client_initialized = False
|
||||||
_oracle_dll_handles = []
|
_oracle_dll_handles = []
|
||||||
_ASSET_AGENT_NAMES = {"固资管理"}
|
_ASSET_AGENT_NAMES = {"固资管理"}
|
||||||
|
_ASSET_ALLOWED_OPERATING_CENTER_CODES = ("HXJM", "HTT", "HTE")
|
||||||
_ASSET_TABLE_MARKERS = (
|
_ASSET_TABLE_MARKERS = (
|
||||||
"ERP_VIEW_USER.ERP_FAJ_FILE_V",
|
"ERP_VIEW_USER.ERP_FAJ_FILE_V",
|
||||||
"ERP_VIEW_USER.ERP_FAB_FILE_V",
|
"ERP_VIEW_USER.ERP_FAB_FILE_V",
|
||||||
@@ -63,6 +64,7 @@ class Text2SQLService:
|
|||||||
"FAJ22": "存放营运中心",
|
"FAJ22": "存放营运中心",
|
||||||
"FAJ25": "取得日期",
|
"FAJ25": "取得日期",
|
||||||
"FAJ26": "入账日期",
|
"FAJ26": "入账日期",
|
||||||
|
"FAJ43": "资产状态",
|
||||||
"FAB02": "类型名称",
|
"FAB02": "类型名称",
|
||||||
"FAF02": "存放位置名称",
|
"FAF02": "存放位置名称",
|
||||||
"GEN01": "员工编号",
|
"GEN01": "员工编号",
|
||||||
@@ -70,6 +72,36 @@ class Text2SQLService:
|
|||||||
"GEM01": "部门编号",
|
"GEM01": "部门编号",
|
||||||
"GEM02": "部门名称",
|
"GEM02": "部门名称",
|
||||||
}
|
}
|
||||||
|
_ASSET_VALUE_MAPPINGS = {
|
||||||
|
"资产性质": {
|
||||||
|
"1": "有形资产",
|
||||||
|
"2": "无形资产",
|
||||||
|
"3": "土地",
|
||||||
|
"4": "递耗资产",
|
||||||
|
"5": "费用",
|
||||||
|
},
|
||||||
|
"资产状态": {
|
||||||
|
"0": "取得",
|
||||||
|
"1": "资本化",
|
||||||
|
"2": "折旧中",
|
||||||
|
"3": "外送",
|
||||||
|
"4": "折毕",
|
||||||
|
"5": "出售",
|
||||||
|
"6": "销账",
|
||||||
|
"7": "折旧再提",
|
||||||
|
"8": "改良",
|
||||||
|
"9": "重估",
|
||||||
|
"X": "被资本",
|
||||||
|
"Z": "停用",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
_ASSET_FALLBACK_NAME_COLUMNS = {
|
||||||
|
"保管人": ("保管人姓名", "员工姓名"),
|
||||||
|
"保管人工号": ("保管人姓名", "员工姓名"),
|
||||||
|
"保管部门": ("保管部门名称", "部门名称"),
|
||||||
|
"存放位置": ("存放位置名称",),
|
||||||
|
"资产类型": ("资产类型名称", "类型名称"),
|
||||||
|
}
|
||||||
_ASSET_PERSON_PATTERN = re.compile(
|
_ASSET_PERSON_PATTERN = re.compile(
|
||||||
r"(?:保管人|员工|人员|姓名|用户|使用人|归属人)\s*(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff_-]{2,20})"
|
r"(?:保管人|员工|人员|姓名|用户|使用人|归属人)\s*(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff_-]{2,20})"
|
||||||
)
|
)
|
||||||
@@ -547,8 +579,64 @@ class Text2SQLService:
|
|||||||
return ""
|
return ""
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _build_asset_name_detail_sql(cls, keyword: str) -> str:
|
def _extract_asset_nature_code(cls, query: str) -> str:
|
||||||
|
text = cls._strip_asset_query_prefix(query)
|
||||||
|
if not text:
|
||||||
|
return ""
|
||||||
|
if "无形资产" in text:
|
||||||
|
return "2"
|
||||||
|
if "有形资产" in text:
|
||||||
|
return "1"
|
||||||
|
if "土地" in text:
|
||||||
|
return "3"
|
||||||
|
if "递耗资产" in text:
|
||||||
|
return "4"
|
||||||
|
if "费用" in text:
|
||||||
|
return "5"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _build_asset_nature_condition(cls, base_alias: str, query: str) -> str:
|
||||||
|
nature_code = cls._extract_asset_nature_code(query)
|
||||||
|
if not nature_code:
|
||||||
|
return ""
|
||||||
|
return f"TRIM(NVL({base_alias}.faj09, '')) = '{nature_code}'"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _build_asset_person_condition(cls, base_alias: str, query: str) -> str:
|
||||||
|
explicit_person = cls._extract_explicit_asset_person(query)
|
||||||
|
if not explicit_person:
|
||||||
|
return ""
|
||||||
|
literal = cls._escape_sql_literal(re.sub(r"\s+", "", explicit_person))
|
||||||
|
return (
|
||||||
|
"EXISTS ("
|
||||||
|
"SELECT 1 FROM ERP_VIEW_USER.ERP_GEN_FILE_V gen_scope "
|
||||||
|
f"WHERE gen_scope.gen01 = {base_alias}.faj19 "
|
||||||
|
f"AND gen_scope.site = {base_alias}.site "
|
||||||
|
f"AND REGEXP_REPLACE(TRIM(gen_scope.gen02), '\\s+', '') = '{literal}'"
|
||||||
|
")"
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _build_asset_department_condition(cls, base_alias: str, query: str) -> str:
|
||||||
|
explicit_department = cls._extract_explicit_asset_department(query)
|
||||||
|
if not explicit_department:
|
||||||
|
return ""
|
||||||
|
literal = cls._escape_sql_literal(re.sub(r"\s+", "", explicit_department))
|
||||||
|
return (
|
||||||
|
"EXISTS ("
|
||||||
|
"SELECT 1 FROM ERP_VIEW_USER.ERP_GEM_FILE_V gem_scope "
|
||||||
|
f"WHERE gem_scope.gem01 = {base_alias}.faj20 "
|
||||||
|
f"AND gem_scope.site = {base_alias}.site "
|
||||||
|
f"AND REGEXP_REPLACE(TRIM(gem_scope.gem02), '\\s+', '') = '{literal}'"
|
||||||
|
")"
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _build_asset_name_detail_sql(cls, keyword: str, query: str = "") -> str:
|
||||||
literal = cls._escape_sql_literal(keyword)
|
literal = cls._escape_sql_literal(keyword)
|
||||||
|
nature_condition = cls._build_asset_nature_condition("faj", query)
|
||||||
|
nature_sql = f"\n AND {nature_condition}" if nature_condition else ""
|
||||||
return f"""
|
return f"""
|
||||||
SELECT DISTINCT
|
SELECT DISTINCT
|
||||||
faj.faj02 AS "财产编号",
|
faj.faj02 AS "财产编号",
|
||||||
@@ -574,8 +662,11 @@ LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem
|
|||||||
LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
|
LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
|
||||||
ON faf.faf01 = faj.faj21
|
ON faf.faf01 = faj.faj21
|
||||||
AND faf.site = faj.site
|
AND faf.site = faj.site
|
||||||
WHERE UPPER(NVL(faj.faj06, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
WHERE (
|
||||||
|
UPPER(NVL(faj.faj06, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
||||||
OR UPPER(NVL(faj.faj061, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
OR UPPER(NVL(faj.faj061, ' ')) LIKE '%' || UPPER('{literal}') || '%'
|
||||||
|
)
|
||||||
|
{nature_sql}
|
||||||
ORDER BY faj.faj02
|
ORDER BY faj.faj02
|
||||||
""".strip()
|
""".strip()
|
||||||
|
|
||||||
@@ -591,8 +682,10 @@ ORDER BY faj.faj02
|
|||||||
return bool(re.search(r"(明细|列表|有哪些|有什么)", text))
|
return bool(re.search(r"(明细|列表|有哪些|有什么)", text))
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _build_company_asset_detail_sql(cls) -> str:
|
def _build_company_asset_detail_sql(cls, query: str = "") -> str:
|
||||||
return """
|
nature_condition = cls._build_asset_nature_condition("faj", query)
|
||||||
|
nature_sql = f"WHERE {nature_condition}\n" if nature_condition else ""
|
||||||
|
return f"""
|
||||||
SELECT DISTINCT
|
SELECT DISTINCT
|
||||||
faj.faj02 AS "财产编号",
|
faj.faj02 AS "财产编号",
|
||||||
faj.faj06 AS "中文名称",
|
faj.faj06 AS "中文名称",
|
||||||
@@ -619,6 +712,7 @@ LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem
|
|||||||
LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
|
LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
|
||||||
ON faf.faf01 = faj.faj21
|
ON faf.faf01 = faj.faj21
|
||||||
AND faf.site = faj.site
|
AND faf.site = faj.site
|
||||||
|
{nature_sql}\
|
||||||
ORDER BY faj.faj02
|
ORDER BY faj.faj02
|
||||||
""".strip()
|
""".strip()
|
||||||
|
|
||||||
@@ -627,11 +721,11 @@ ORDER BY faj.faj02
|
|||||||
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query)):
|
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query)):
|
||||||
return None
|
return None
|
||||||
if cls._is_company_asset_detail_query(query):
|
if cls._is_company_asset_detail_query(query):
|
||||||
return cls._build_company_asset_detail_sql()
|
return cls._build_company_asset_detail_sql(query)
|
||||||
keyword = cls._extract_asset_name_keyword(query)
|
keyword = cls._extract_asset_name_keyword(query)
|
||||||
if not keyword:
|
if not keyword:
|
||||||
return None
|
return None
|
||||||
return cls._build_asset_name_detail_sql(keyword)
|
return cls._build_asset_name_detail_sql(keyword, query)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _build_asset_prompt_constraints(cls, query: str, user_context: dict | None, agent) -> str:
|
def _build_asset_prompt_constraints(cls, query: str, user_context: dict | None, agent) -> str:
|
||||||
@@ -646,6 +740,8 @@ ORDER BY faj.faj02
|
|||||||
explicit_person = explicit_scope.get("person")
|
explicit_person = explicit_scope.get("person")
|
||||||
explicit_department = explicit_scope.get("department")
|
explicit_department = explicit_scope.get("department")
|
||||||
self_query = cls._is_self_asset_query(query)
|
self_query = cls._is_self_asset_query(query)
|
||||||
|
asset_nature_code = cls._extract_asset_nature_code(query)
|
||||||
|
asset_nature_name = cls._ASSET_VALUE_MAPPINGS.get("资产性质", {}).get(asset_nature_code, "")
|
||||||
|
|
||||||
if explicit_person:
|
if explicit_person:
|
||||||
filters.append(f"- 用户已明确指定查询人:{explicit_person}。本次必须以该指定人作为保管人查询固定资产,不能回退到当前登录用户。")
|
filters.append(f"- 用户已明确指定查询人:{explicit_person}。本次必须以该指定人作为保管人查询固定资产,不能回退到当前登录用户。")
|
||||||
@@ -665,6 +761,8 @@ ORDER BY faj.faj02
|
|||||||
filters.append(
|
filters.append(
|
||||||
f"- 如需联表保管人姓名,请通过 ERP_VIEW_USER.ERP_GEN_FILE_V `gen`,并使用 `gen.gen01 = faj.faj19 AND gen.site = faj.site AND TRIM(gen.gen02) = '{real_name}'`。"
|
f"- 如需联表保管人姓名,请通过 ERP_VIEW_USER.ERP_GEN_FILE_V `gen`,并使用 `gen.gen01 = faj.faj19 AND gen.site = faj.site AND TRIM(gen.gen02) = '{real_name}'`。"
|
||||||
)
|
)
|
||||||
|
if asset_nature_code and asset_nature_name:
|
||||||
|
filters.append(f"- 用户已明确指定资产性质为“{asset_nature_name}”,必须增加 `TRIM(NVL(faj.faj09, '')) = '{asset_nature_code}'` 过滤,不能返回其他资产性质。")
|
||||||
|
|
||||||
return "\n".join(
|
return "\n".join(
|
||||||
[
|
[
|
||||||
@@ -672,6 +770,7 @@ ORDER BY faj.faj02
|
|||||||
"- 固定资产查询优先使用 ERP_VIEW_USER.ERP_FAJ_FILE_V,表别名建议使用 `faj`。",
|
"- 固定资产查询优先使用 ERP_VIEW_USER.ERP_FAJ_FILE_V,表别名建议使用 `faj`。",
|
||||||
"- 如需资产类型、保管人姓名、部门名称或存放位置名称,可联表 ERP_VIEW_USER.ERP_FAB_FILE_V `fab`、ERP_VIEW_USER.ERP_GEN_FILE_V `gen`、ERP_VIEW_USER.ERP_GEM_FILE_V `gem`、ERP_VIEW_USER.ERP_FAF_FILE_V `faf`。",
|
"- 如需资产类型、保管人姓名、部门名称或存放位置名称,可联表 ERP_VIEW_USER.ERP_FAB_FILE_V `fab`、ERP_VIEW_USER.ERP_GEN_FILE_V `gen`、ERP_VIEW_USER.ERP_GEM_FILE_V `gem`、ERP_VIEW_USER.ERP_FAF_FILE_V `faf`。",
|
||||||
"- 固资相关联表必须同时补齐 `site` 条件,例如 `gen.site = faj.site`、`gem.site = faj.site`、`faf.site = faj.site`、`fab.site = faj.site`,避免同编码跨营运中心造成重复记录。",
|
"- 固资相关联表必须同时补齐 `site` 条件,例如 `gen.site = faj.site`、`gem.site = faj.site`、`faf.site = faj.site`、`fab.site = faj.site`,避免同编码跨营运中心造成重复记录。",
|
||||||
|
"- 固资数据只允许保留 `faj22`(存放营运中心)属于 `HXJM`、`HTT`、`HTE` 的记录;生成 SQL 时必须显式加上 `UPPER(TRIM(NVL(faj.faj22, ''))) IN ('HXJM', 'HTT', 'HTE')` 过滤。",
|
||||||
"- 查询固定资产明细列表时优先使用 `SELECT DISTINCT`;如果是统计资产数量,优先使用 `COUNT(DISTINCT faj.faj02)`。",
|
"- 查询固定资产明细列表时优先使用 `SELECT DISTINCT`;如果是统计资产数量,优先使用 `COUNT(DISTINCT faj.faj02)`。",
|
||||||
"- 返回结果所有列必须使用中文别名,例如 `faj.faj02 AS \"财产编号\"`、`faj.faj06 AS \"资产名称\"`、`faj.faj08 AS \"规格型号\"`。",
|
"- 返回结果所有列必须使用中文别名,例如 `faj.faj02 AS \"财产编号\"`、`faj.faj06 AS \"资产名称\"`、`faj.faj08 AS \"规格型号\"`。",
|
||||||
"- 日期时间字段展示时不要去掉时分秒;若使用 TO_CHAR 格式化,必须保留为 `YYYY-MM-DD HH24:MI:SS`,不能只输出日期。",
|
"- 日期时间字段展示时不要去掉时分秒;若使用 TO_CHAR 格式化,必须保留为 `YYYY-MM-DD HH24:MI:SS`,不能只输出日期。",
|
||||||
@@ -689,6 +788,43 @@ ORDER BY faj.faj02
|
|||||||
localized.append(cls._ASSET_COLUMN_LABELS.get(raw_name.upper(), raw_name))
|
localized.append(cls._ASSET_COLUMN_LABELS.get(raw_name.upper(), raw_name))
|
||||||
return localized
|
return localized
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _translate_asset_display_value(cls, display_name: str, value) -> str:
|
||||||
|
text = cls._stringify_value(value)
|
||||||
|
mapping = cls._ASSET_VALUE_MAPPINGS.get(str(display_name or "").strip())
|
||||||
|
if not mapping:
|
||||||
|
return text
|
||||||
|
return mapping.get(text.strip().upper(), mapping.get(text.strip(), text))
|
||||||
|
|
||||||
|
@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)):
|
||||||
|
return rows
|
||||||
|
display_columns = cls._localize_asset_columns(columns, query, sql, agent=agent)
|
||||||
|
index_map = {str(name or "").strip(): idx for idx, name in enumerate(display_columns)}
|
||||||
|
localized_rows = []
|
||||||
|
for row in rows or []:
|
||||||
|
row_values = list(row)
|
||||||
|
display_values = []
|
||||||
|
for idx, display_name in enumerate(display_columns):
|
||||||
|
raw_value = row_values[idx] if idx < len(row_values) else None
|
||||||
|
fallback_columns = cls._ASSET_FALLBACK_NAME_COLUMNS.get(display_name, ())
|
||||||
|
fallback_value = None
|
||||||
|
for fallback_column in fallback_columns:
|
||||||
|
fallback_idx = index_map.get(fallback_column)
|
||||||
|
if fallback_idx is None or fallback_idx >= len(row_values):
|
||||||
|
continue
|
||||||
|
candidate = cls._stringify_value(row_values[fallback_idx]).strip()
|
||||||
|
if candidate and candidate != "NULL":
|
||||||
|
fallback_value = candidate
|
||||||
|
break
|
||||||
|
if fallback_value:
|
||||||
|
display_values.append(fallback_value)
|
||||||
|
continue
|
||||||
|
display_values.append(cls._translate_asset_display_value(display_name, raw_value))
|
||||||
|
localized_rows.append(display_values)
|
||||||
|
return localized_rows
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _is_aggregate_sql(sql: str) -> bool:
|
def _is_aggregate_sql(sql: str) -> bool:
|
||||||
return bool(re.search(r"(?is)\b(count|sum|avg|min|max)\s*\(", sql or ""))
|
return bool(re.search(r"(?is)\b(count|sum|avg|min|max)\s*\(", sql or ""))
|
||||||
@@ -706,6 +842,23 @@ ORDER BY faj.faj02
|
|||||||
text = str(sql or "").strip().rstrip(";")
|
text = str(sql or "").strip().rstrip(";")
|
||||||
return re.sub(r"(?is)\border\s+by\b[\s\S]*$", "", text).strip()
|
return re.sub(r"(?is)\border\s+by\b[\s\S]*$", "", text).strip()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _build_asset_operating_center_condition(cls, base_alias: str) -> str:
|
||||||
|
allowed_codes = ", ".join(f"'{code}'" for code in cls._ASSET_ALLOWED_OPERATING_CENTER_CODES)
|
||||||
|
return f"UPPER(TRIM(NVL({base_alias}.faj22, ''))) IN ({allowed_codes})"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _append_sql_predicate(sql: str, predicate: str) -> str:
|
||||||
|
text = str(sql or "").strip().rstrip(";")
|
||||||
|
anchor = re.search(r"(?is)\b(group\s+by|order\s+by|having)\b", text)
|
||||||
|
if re.search(r"(?is)\bwhere\b", text):
|
||||||
|
if anchor:
|
||||||
|
return f"{text[:anchor.start()].rstrip()} AND {predicate} {text[anchor.start():].lstrip()}"
|
||||||
|
return f"{text} AND {predicate}"
|
||||||
|
if anchor:
|
||||||
|
return f"{text[:anchor.start()].rstrip()} WHERE {predicate} {text[anchor.start():].lstrip()}"
|
||||||
|
return f"{text} WHERE {predicate}"
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _build_asset_total_count_sql(cls, sql: str) -> str | None:
|
def _build_asset_total_count_sql(cls, sql: str) -> str | None:
|
||||||
if cls._is_aggregate_sql(sql):
|
if cls._is_aggregate_sql(sql):
|
||||||
@@ -753,6 +906,69 @@ ORDER BY faj.faj02
|
|||||||
"- 异常提醒:当前结果未体现明显异常。"
|
"- 异常提醒:当前结果未体现明显异常。"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _sanitize_sql_text(cls, sql: str) -> str:
|
||||||
|
return str(sql or "").strip().rstrip(";")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _build_paged_query_sql(cls, sql: str, limit: int, offset: int = 0) -> str:
|
||||||
|
safe_sql = cls._sanitize_sql_text(sql)
|
||||||
|
upper_bound = max(0, int(offset)) + max(1, int(limit))
|
||||||
|
lower_bound = max(0, int(offset))
|
||||||
|
return (
|
||||||
|
"SELECT * FROM ("
|
||||||
|
"SELECT preview_data__.*, ROWNUM AS preview_rownum__ "
|
||||||
|
f"FROM ({safe_sql}) preview_data__ "
|
||||||
|
f"WHERE ROWNUM <= {upper_bound}"
|
||||||
|
f") WHERE preview_rownum__ > {lower_bound}"
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _build_generic_total_count_sql(cls, sql: str) -> str:
|
||||||
|
safe_sql = cls._sanitize_sql_text(sql)
|
||||||
|
return f"SELECT COUNT(*) AS total_count FROM ({safe_sql}) preview_total__"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _execute_sql_internal(cls, sql: str):
|
||||||
|
try:
|
||||||
|
import oracledb
|
||||||
|
except ImportError:
|
||||||
|
return None, None, ["Error"], [["oracledb is not installed"]]
|
||||||
|
|
||||||
|
user = "EXT_VIEW_USER"
|
||||||
|
password = "extviewuser"
|
||||||
|
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||||
|
|
||||||
|
try:
|
||||||
|
cls._init_oracle_client(oracledb)
|
||||||
|
except Exception as e:
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.warning(f"Failed to init thick mode: {e}")
|
||||||
|
|
||||||
|
connection = None
|
||||||
|
cursor = None
|
||||||
|
try:
|
||||||
|
connection = oracledb.connect(user=user, password=password, dsn=dsn)
|
||||||
|
cursor = connection.cursor()
|
||||||
|
cursor.execute(sql)
|
||||||
|
columns = [col[0] for col in cursor.description]
|
||||||
|
return connection, cursor, columns, None
|
||||||
|
except Exception as e:
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
cursor.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if connection:
|
||||||
|
try:
|
||||||
|
connection.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
error_text = str(e)
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.warning(f"Oracle direct query failed: {error_text}")
|
||||||
|
return None, None, ["Error"], [[error_text]]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _ensure_asset_join_site(cls, sql: str, base_alias: str, table_name: str) -> str:
|
def _ensure_asset_join_site(cls, sql: str, base_alias: str, table_name: str) -> str:
|
||||||
join_pattern = re.compile(
|
join_pattern = re.compile(
|
||||||
@@ -771,6 +987,28 @@ ORDER BY faj.faj02
|
|||||||
|
|
||||||
return join_pattern.sub(_replace, sql)
|
return join_pattern.sub(_replace, sql)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _ensure_asset_operating_center_filter(cls, sql: str, base_alias: str) -> str:
|
||||||
|
predicate = cls._build_asset_operating_center_condition(base_alias)
|
||||||
|
return cls._append_sql_predicate(sql, predicate)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _ensure_asset_nature_filter(cls, sql: str, base_alias: str, query: str) -> str:
|
||||||
|
predicate = cls._build_asset_nature_condition(base_alias, query)
|
||||||
|
if not predicate:
|
||||||
|
return sql
|
||||||
|
return cls._append_sql_predicate(sql, predicate)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _ensure_asset_scope_filter(cls, sql: str, base_alias: str, query: str) -> str:
|
||||||
|
department_predicate = cls._build_asset_department_condition(base_alias, query)
|
||||||
|
if department_predicate:
|
||||||
|
return cls._append_sql_predicate(sql, department_predicate)
|
||||||
|
person_predicate = cls._build_asset_person_condition(base_alias, query)
|
||||||
|
if person_predicate:
|
||||||
|
return cls._append_sql_predicate(sql, person_predicate)
|
||||||
|
return sql
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _ensure_asset_select_distinct(cls, sql: str) -> str:
|
def _ensure_asset_select_distinct(cls, sql: str) -> str:
|
||||||
if cls._is_aggregate_sql(sql):
|
if cls._is_aggregate_sql(sql):
|
||||||
@@ -807,6 +1045,9 @@ ORDER BY faj.faj02
|
|||||||
for table_name in ("ERP_GEN_FILE_V", "ERP_GEM_FILE_V", "ERP_FAF_FILE_V", "ERP_FAB_FILE_V"):
|
for table_name in ("ERP_GEN_FILE_V", "ERP_GEM_FILE_V", "ERP_FAF_FILE_V", "ERP_FAB_FILE_V"):
|
||||||
normalized_sql = cls._ensure_asset_join_site(normalized_sql, base_alias, table_name)
|
normalized_sql = cls._ensure_asset_join_site(normalized_sql, base_alias, table_name)
|
||||||
|
|
||||||
|
normalized_sql = cls._ensure_asset_scope_filter(normalized_sql, base_alias, query)
|
||||||
|
normalized_sql = cls._ensure_asset_nature_filter(normalized_sql, base_alias, query)
|
||||||
|
normalized_sql = cls._ensure_asset_operating_center_filter(normalized_sql, base_alias)
|
||||||
normalized_sql = cls._ensure_asset_datetime_precision(normalized_sql)
|
normalized_sql = cls._ensure_asset_datetime_precision(normalized_sql)
|
||||||
return cls._ensure_asset_select_distinct(normalized_sql)
|
return cls._ensure_asset_select_distinct(normalized_sql)
|
||||||
|
|
||||||
@@ -880,7 +1121,7 @@ ORDER BY faj.faj02
|
|||||||
def generate_sql(cls, query: str, user_context: dict | None = None, agent=None) -> str:
|
def generate_sql(cls, query: str, user_context: dict | None = None, agent=None) -> str:
|
||||||
special_sql = cls._build_special_asset_sql(query, agent=agent)
|
special_sql = cls._build_special_asset_sql(query, agent=agent)
|
||||||
if special_sql:
|
if special_sql:
|
||||||
return special_sql
|
return cls._rewrite_asset_sql(special_sql, query, agent=agent)
|
||||||
|
|
||||||
schema = cls.get_schema()
|
schema = cls.get_schema()
|
||||||
asset_constraints = cls._build_asset_prompt_constraints(query, user_context, agent)
|
asset_constraints = cls._build_asset_prompt_constraints(query, user_context, agent)
|
||||||
@@ -920,7 +1161,7 @@ ORDER BY faj.faj02
|
|||||||
def repair_sql(cls, query: str, failed_sql: str, error_message: str, user_context: dict | None = None, agent=None) -> str:
|
def repair_sql(cls, query: str, failed_sql: str, error_message: str, user_context: dict | None = None, agent=None) -> str:
|
||||||
special_sql = cls._build_special_asset_sql(query, agent=agent)
|
special_sql = cls._build_special_asset_sql(query, agent=agent)
|
||||||
if special_sql:
|
if special_sql:
|
||||||
return special_sql
|
return cls._rewrite_asset_sql(special_sql, query, agent=agent)
|
||||||
|
|
||||||
schema = cls.get_schema()
|
schema = cls.get_schema()
|
||||||
invalid_identifier = cls._extract_invalid_identifier(error_message)
|
invalid_identifier = cls._extract_invalid_identifier(error_message)
|
||||||
@@ -964,40 +1205,49 @@ ORDER BY faj.faj02
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def execute_sql(cls, sql: str):
|
def execute_sql(cls, sql: str):
|
||||||
|
connection, cursor, columns, error_rows = cls._execute_sql_internal(sql)
|
||||||
|
if columns == ["Error"]:
|
||||||
|
return columns, error_rows
|
||||||
try:
|
try:
|
||||||
import oracledb
|
|
||||||
except ImportError:
|
|
||||||
return ["Error"], [["oracledb is not installed"]]
|
|
||||||
|
|
||||||
user = "EXT_VIEW_USER"
|
|
||||||
password = "extviewuser"
|
|
||||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Old ERP Oracle versions require python-oracledb thick mode.
|
|
||||||
cls._init_oracle_client(oracledb)
|
|
||||||
except Exception as e:
|
|
||||||
if current_app:
|
|
||||||
current_app.logger.warning(f"Failed to init thick mode: {e}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
connection = oracledb.connect(user=user, password=password, dsn=dsn)
|
|
||||||
cursor = connection.cursor()
|
|
||||||
cursor.execute(sql)
|
|
||||||
|
|
||||||
columns = [col[0] for col in cursor.description]
|
|
||||||
# Use fetchmany(50) instead of LLM-generated FETCH FIRST to support older Oracle versions
|
|
||||||
rows = cursor.fetchmany(50)
|
rows = cursor.fetchmany(50)
|
||||||
|
return columns, rows
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
cursor.close()
|
cursor.close()
|
||||||
|
finally:
|
||||||
connection.close()
|
connection.close()
|
||||||
|
|
||||||
return columns, rows
|
@classmethod
|
||||||
except Exception as e:
|
def execute_sql_page(cls, sql: str, *, page: int = 1, page_size: int = 100):
|
||||||
error_text = str(e)
|
safe_page = max(1, int(page or 1))
|
||||||
if current_app:
|
safe_page_size = max(1, min(200, int(page_size or 100)))
|
||||||
current_app.logger.warning(f"Oracle direct query failed: {error_text}")
|
offset = (safe_page - 1) * safe_page_size
|
||||||
return ["Error"], [[error_text]]
|
paged_sql = cls._build_paged_query_sql(sql, safe_page_size, offset=offset)
|
||||||
|
connection, cursor, columns, error_rows = cls._execute_sql_internal(paged_sql)
|
||||||
|
if columns == ["Error"]:
|
||||||
|
return columns, error_rows
|
||||||
|
try:
|
||||||
|
raw_columns = [name for name in columns if str(name).upper() != "PREVIEW_ROWNUM__"]
|
||||||
|
visible_len = len(raw_columns)
|
||||||
|
raw_rows = cursor.fetchall()
|
||||||
|
rows = [tuple(list(row)[:visible_len]) for row in raw_rows]
|
||||||
|
return raw_columns, rows
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
cursor.close()
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_total_count_for_sql(cls, sql: str) -> int | None:
|
||||||
|
count_sql = cls._build_generic_total_count_sql(sql)
|
||||||
|
columns, rows = cls.execute_sql_page(count_sql, page=1, page_size=1)
|
||||||
|
if columns == ["Error"] or not rows or not rows[0]:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return int(rows[0][0])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def format_result(cls, columns, rows, sql, original_query, agent=None):
|
def format_result(cls, columns, rows, sql, original_query, agent=None):
|
||||||
@@ -1013,17 +1263,47 @@ ORDER BY faj.faj02
|
|||||||
return f"{summary_text}\n\n{sql_details}"
|
return f"{summary_text}\n\n{sql_details}"
|
||||||
|
|
||||||
display_columns = cls._localize_asset_columns(columns, original_query, sql, agent=agent)
|
display_columns = cls._localize_asset_columns(columns, original_query, sql, agent=agent)
|
||||||
|
display_rows = cls._localize_asset_rows(columns, rows, original_query, sql, agent=agent)
|
||||||
header = "| " + " | ".join(display_columns) + " |"
|
header = "| " + " | ".join(display_columns) + " |"
|
||||||
separator = "| " + " | ".join(["---"] * len(display_columns)) + " |"
|
separator = "| " + " | ".join(["---"] * len(display_columns)) + " |"
|
||||||
|
|
||||||
body = []
|
body = []
|
||||||
for row in rows:
|
for row in display_rows:
|
||||||
body.append("| " + " | ".join([cls._stringify_value(val) for val in row]) + " |")
|
body.append("| " + " | ".join([cls._stringify_value(val) for val in row]) + " |")
|
||||||
|
|
||||||
table_str = "\n".join([header, separator] + body)
|
table_str = "\n".join([header, separator] + body)
|
||||||
|
|
||||||
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
|
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def build_query_preview_payload(cls, columns, rows, sql, original_query, agent=None):
|
||||||
|
if columns == ["Error"] or not columns:
|
||||||
|
return None
|
||||||
|
total_count = cls._query_asset_total_count(original_query, sql, agent=agent)
|
||||||
|
if total_count is None:
|
||||||
|
total_count = len(rows or [])
|
||||||
|
preview_row_count = len(rows or [])
|
||||||
|
previewable = total_count > preview_row_count
|
||||||
|
return {
|
||||||
|
"kind": "text2sql_result_preview",
|
||||||
|
"previewable": previewable,
|
||||||
|
"query": original_query,
|
||||||
|
"sql": cls._sanitize_sql_text(sql),
|
||||||
|
"total_count": total_count,
|
||||||
|
"preview_row_count": preview_row_count,
|
||||||
|
"display_columns": cls._localize_asset_columns(columns, original_query, sql, agent=agent),
|
||||||
|
}
|
||||||
|
|
||||||
|
@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)
|
||||||
|
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)
|
||||||
|
display_columns = cls._localize_asset_columns(raw_columns, query, sql, agent=agent)
|
||||||
|
display_rows = cls._localize_asset_rows(raw_columns, raw_rows, query, sql, agent=agent)
|
||||||
|
return display_columns, display_rows, resolved_total
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def stream_chat(query: str, user, agent, conversation_id: str = None, session_id: str | None = None):
|
def stream_chat(query: str, user, agent, conversation_id: str = None, session_id: str | None = None):
|
||||||
"""Yields SSE events to frontend just like DifyService"""
|
"""Yields SSE events to frontend just like DifyService"""
|
||||||
@@ -1090,6 +1370,7 @@ ORDER BY faj.faj02
|
|||||||
yield f"data: {json.dumps({'event': 'message', 'answer': '📝 数据检索完成,正在生成最终业务报告...\n'})}\n\n"
|
yield f"data: {json.dumps({'event': 'message', 'answer': '📝 数据检索完成,正在生成最终业务报告...\n'})}\n\n"
|
||||||
stage_start = time.time()
|
stage_start = time.time()
|
||||||
result_text = Text2SQLService.format_result(columns, rows, sql, query, agent=agent)
|
result_text = Text2SQLService.format_result(columns, rows, sql, query, agent=agent)
|
||||||
|
result_preview_payload = Text2SQLService.build_query_preview_payload(columns, rows, sql, query, agent=agent)
|
||||||
format_result_ms = int((time.time() - stage_start) * 1000)
|
format_result_ms = int((time.time() - stage_start) * 1000)
|
||||||
latency = int((time.time() - start_time) * 1000)
|
latency = int((time.time() - start_time) * 1000)
|
||||||
if current_app:
|
if current_app:
|
||||||
@@ -1125,6 +1406,7 @@ ORDER BY faj.faj02
|
|||||||
session_id=session_id,
|
session_id=session_id,
|
||||||
query=query,
|
query=query,
|
||||||
answer=result_text,
|
answer=result_text,
|
||||||
|
payload=result_preview_payload,
|
||||||
tokens_used=0,
|
tokens_used=0,
|
||||||
latency=latency,
|
latency=latency,
|
||||||
)
|
)
|
||||||
@@ -1141,6 +1423,7 @@ ORDER BY faj.faj02
|
|||||||
'answer': result_text,
|
'answer': result_text,
|
||||||
'replace_answer': True,
|
'replace_answer': True,
|
||||||
'chat_log_id': chat_log_id,
|
'chat_log_id': chat_log_id,
|
||||||
'conversation_id': final_conversation_id
|
'conversation_id': final_conversation_id,
|
||||||
|
'payload': result_preview_payload,
|
||||||
}
|
}
|
||||||
yield f"data: {json.dumps(end_data)}\n\n"
|
yield f"data: {json.dumps(end_data)}\n\n"
|
||||||
@@ -43,6 +43,16 @@ export interface ChatUploadResult {
|
|||||||
type?: 'image' | 'document' | 'audio' | 'video' | 'custom';
|
type?: 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ChatQueryPreviewPage {
|
||||||
|
columns: string[];
|
||||||
|
rows: any[][];
|
||||||
|
page: number;
|
||||||
|
page_size: number;
|
||||||
|
total: number;
|
||||||
|
has_more: boolean;
|
||||||
|
query?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export const listChatSessions = (agentId: number) =>
|
export const listChatSessions = (agentId: number) =>
|
||||||
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
|
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
|
||||||
|
|
||||||
@@ -98,3 +108,16 @@ export const uploadChatFile = (agentId: number, file: File) => {
|
|||||||
headers: getAuthHeaders(),
|
headers: getAuthHeaders(),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getChatQueryPreviewPage = (
|
||||||
|
agentId: number,
|
||||||
|
chatLogId: number,
|
||||||
|
query: { page?: number; page_size?: number } = {},
|
||||||
|
) => {
|
||||||
|
const qs = new URLSearchParams({
|
||||||
|
agent_id: String(agentId),
|
||||||
|
page: String(query.page ?? 1),
|
||||||
|
page_size: String(query.page_size ?? 100),
|
||||||
|
});
|
||||||
|
return requestJson<ChatQueryPreviewPage>(`/api/chat/query-preview/${chatLogId}?${qs.toString()}`, auth());
|
||||||
|
};
|
||||||
@@ -131,6 +131,9 @@ const applyEventMetadata = (msg: ChatMessage, data: any) => {
|
|||||||
addAttributionParts(msg, metadata?.annotation_reply);
|
addAttributionParts(msg, metadata?.annotation_reply);
|
||||||
addAttributionParts(msg, data?.citation);
|
addAttributionParts(msg, data?.citation);
|
||||||
addAttributionParts(msg, metadata?.citation);
|
addAttributionParts(msg, metadata?.citation);
|
||||||
|
if (data?.payload && typeof data.payload === 'object') {
|
||||||
|
msg.payload = data.payload;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useChat() {
|
export function useChat() {
|
||||||
|
|||||||
+225
-17
@@ -35,6 +35,7 @@ import {
|
|||||||
deleteChatSession,
|
deleteChatSession,
|
||||||
listChatMessages,
|
listChatMessages,
|
||||||
saveLocalChatMessage,
|
saveLocalChatMessage,
|
||||||
|
getChatQueryPreviewPage,
|
||||||
resolveChatSourceFile,
|
resolveChatSourceFile,
|
||||||
listOaEmployees,
|
listOaEmployees,
|
||||||
uploadChatFile,
|
uploadChatFile,
|
||||||
@@ -92,6 +93,103 @@ const DEFAULT_KB = '企业知识库';
|
|||||||
const ERP_KB = 'ERP知识库';
|
const ERP_KB = 'ERP知识库';
|
||||||
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
|
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
|
||||||
|
|
||||||
|
type QueryPreviewPayload = {
|
||||||
|
kind: 'text2sql_result_preview';
|
||||||
|
previewable?: boolean;
|
||||||
|
total_count?: number;
|
||||||
|
preview_row_count?: number;
|
||||||
|
query?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const showQueryPreviewDialog = ref(false);
|
||||||
|
const queryPreviewLoading = ref(false);
|
||||||
|
const queryPreviewError = ref('');
|
||||||
|
const queryPreviewState = ref({
|
||||||
|
chatLogId: 0,
|
||||||
|
title: '',
|
||||||
|
query: '',
|
||||||
|
columns: [] as string[],
|
||||||
|
rows: [] as any[][],
|
||||||
|
page: 1,
|
||||||
|
pageSize: 100,
|
||||||
|
total: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const getQueryPreviewPayload = (msg: any): QueryPreviewPayload | null => {
|
||||||
|
const payload = msg?.payload;
|
||||||
|
if (!payload || typeof payload !== 'object') return null;
|
||||||
|
if ((payload as any).kind !== 'text2sql_result_preview') return null;
|
||||||
|
return payload as QueryPreviewPayload;
|
||||||
|
};
|
||||||
|
|
||||||
|
const canOpenQueryPreview = (msg: any) => {
|
||||||
|
const payload = getQueryPreviewPayload(msg);
|
||||||
|
return !!(payload?.previewable && Number(msg?.chat_log_id) > 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getQueryPreviewSummary = (msg: any) => {
|
||||||
|
const payload = getQueryPreviewPayload(msg);
|
||||||
|
const total = Number(payload?.total_count || 0);
|
||||||
|
if (total > 0) return `查看全部预览(共 ${total} 条)`;
|
||||||
|
return '查看全部预览';
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeQueryPreviewDialog = () => {
|
||||||
|
showQueryPreviewDialog.value = false;
|
||||||
|
queryPreviewError.value = '';
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadQueryPreviewPage = async (chatLogId: number, page = 1) => {
|
||||||
|
if (!currentAgentId.value) {
|
||||||
|
queryPreviewError.value = '当前 Agent 未就绪,请稍后重试';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
queryPreviewLoading.value = true;
|
||||||
|
queryPreviewError.value = '';
|
||||||
|
try {
|
||||||
|
const result = await getChatQueryPreviewPage(currentAgentId.value, chatLogId, { page, page_size: queryPreviewState.value.pageSize });
|
||||||
|
queryPreviewState.value = {
|
||||||
|
...queryPreviewState.value,
|
||||||
|
chatLogId,
|
||||||
|
title: String(result.query || queryPreviewState.value.title || '查询结果全量预览').trim() || '查询结果全量预览',
|
||||||
|
query: String(result.query || '').trim(),
|
||||||
|
columns: Array.isArray(result.columns) ? result.columns : [],
|
||||||
|
rows: Array.isArray(result.rows) ? result.rows : [],
|
||||||
|
page: Number(result.page || page || 1),
|
||||||
|
pageSize: Number(result.page_size || queryPreviewState.value.pageSize || 100),
|
||||||
|
total: Number(result.total || 0),
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
queryPreviewError.value = error?.message || '加载全量预览失败';
|
||||||
|
} finally {
|
||||||
|
queryPreviewLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openQueryPreviewDialog = async (msgObj: any) => {
|
||||||
|
const chatLogId = Number(msgObj?.chat_log_id || 0);
|
||||||
|
if (!chatLogId) return;
|
||||||
|
const payload = getQueryPreviewPayload(msgObj);
|
||||||
|
queryPreviewState.value = {
|
||||||
|
...queryPreviewState.value,
|
||||||
|
chatLogId,
|
||||||
|
title: String(payload?.query || msgObj?.content || '查询结果全量预览').trim() || '查询结果全量预览',
|
||||||
|
query: String(payload?.query || '').trim(),
|
||||||
|
page: 1,
|
||||||
|
total: Number(payload?.total_count || 0),
|
||||||
|
};
|
||||||
|
showQueryPreviewDialog.value = true;
|
||||||
|
await loadQueryPreviewPage(chatLogId, 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const changeQueryPreviewPage = async (delta: number) => {
|
||||||
|
const nextPage = queryPreviewState.value.page + delta;
|
||||||
|
if (nextPage < 1) return;
|
||||||
|
const totalPages = Math.max(1, Math.ceil((queryPreviewState.value.total || 0) / (queryPreviewState.value.pageSize || 100)));
|
||||||
|
if (nextPage > totalPages) return;
|
||||||
|
await loadQueryPreviewPage(queryPreviewState.value.chatLogId, nextPage);
|
||||||
|
};
|
||||||
|
|
||||||
const selectedKb = ref(DEFAULT_KB);
|
const selectedKb = ref(DEFAULT_KB);
|
||||||
const showKbDropdown = ref(false);
|
const showKbDropdown = ref(false);
|
||||||
const kbMenuRef = ref<HTMLElement | null>(null);
|
const kbMenuRef = ref<HTMLElement | null>(null);
|
||||||
@@ -251,7 +349,11 @@ const renderMarkdown = (text: string) => {
|
|||||||
const displayText = sanitizeShippingConversationText(stripReasoningPrelude(stripped));
|
const displayText = sanitizeShippingConversationText(stripReasoningPrelude(stripped));
|
||||||
try {
|
try {
|
||||||
// 把 # 标题、代码块、[链接](url) 等 Markdown 解析成 HTML
|
// 把 # 标题、代码块、[链接](url) 等 Markdown 解析成 HTML
|
||||||
return marked.parse(displayText);
|
const rendered = marked.parse(displayText);
|
||||||
|
const html = typeof rendered === 'string' ? rendered : displayText;
|
||||||
|
return html.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml: string) => (
|
||||||
|
`<div class="chat-table-scroll"><div class="chat-table-inner">${tableHtml}</div></div>`
|
||||||
|
));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return displayText;
|
return displayText;
|
||||||
}
|
}
|
||||||
@@ -891,7 +993,11 @@ const selectKb = (option: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
watch(canSelectErpKnowledgeBase, (allowed) => {
|
watch(canSelectErpKnowledgeBase, (allowed) => {
|
||||||
if (!allowed && selectedKb.value === ERP_KB) {
|
if (allowed) {
|
||||||
|
selectedKb.value = ERP_KB;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (selectedKb.value === ERP_KB) {
|
||||||
selectedKb.value = DEFAULT_KB;
|
selectedKb.value = DEFAULT_KB;
|
||||||
}
|
}
|
||||||
if (!allowed) {
|
if (!allowed) {
|
||||||
@@ -2223,10 +2329,6 @@ const normalizeBrowserInput = (value: string) => {
|
|||||||
return '';
|
return '';
|
||||||
};
|
};
|
||||||
|
|
||||||
const toggleBrowserPanel = () => {
|
|
||||||
browserPanelOpen.value = !browserPanelOpen.value;
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadBrowserPage = () => {
|
const loadBrowserPage = () => {
|
||||||
const normalized = normalizeBrowserInput(browserDraftUrl.value);
|
const normalized = normalizeBrowserInput(browserDraftUrl.value);
|
||||||
if (!normalized) {
|
if (!normalized) {
|
||||||
@@ -4015,6 +4117,8 @@ const resetChatStateForAgentChange = () => {
|
|||||||
currentAgent.value = null;
|
currentAgent.value = null;
|
||||||
copiedIndex.value = null;
|
copiedIndex.value = null;
|
||||||
showAttachmentMenu.value = false;
|
showAttachmentMenu.value = false;
|
||||||
|
browserPanelOpen.value = false;
|
||||||
|
closeQueryPreviewDialog();
|
||||||
filePreviewVisible.value = false;
|
filePreviewVisible.value = false;
|
||||||
previewFile.value = null;
|
previewFile.value = null;
|
||||||
};
|
};
|
||||||
@@ -4808,10 +4912,23 @@ const showChatRating = ref(false);
|
|||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-else
|
v-else
|
||||||
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-table:w-full prose-table:border-collapse prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
|
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
|
||||||
@click="handleChatMarkdownClick"
|
@click="handleChatMarkdownClick"
|
||||||
v-html="renderMarkdown(msg.content)"
|
v-html="renderMarkdown(msg.content)"
|
||||||
></div>
|
></div>
|
||||||
|
<div
|
||||||
|
v-if="msg.role === 'assistant' && canOpenQueryPreview(msg)"
|
||||||
|
class="mt-4"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
|
||||||
|
@click="openQueryPreviewDialog(msg)"
|
||||||
|
>
|
||||||
|
<LayoutGrid class="h-3.5 w-3.5" />
|
||||||
|
{{ getQueryPreviewSummary(msg) }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="isShippingNoticeAgent && msg.shipping_actions?.length"
|
v-if="isShippingNoticeAgent && msg.shipping_actions?.length"
|
||||||
class="mt-4 space-y-2 border-t border-default pt-4"
|
class="mt-4 space-y-2 border-t border-default pt-4"
|
||||||
@@ -5126,13 +5243,6 @@ const showChatRating = ref(false);
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button
|
|
||||||
@click="toggleBrowserPanel"
|
|
||||||
class="flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
|
|
||||||
>
|
|
||||||
<Globe class="h-3.5 w-3.5 text-brand-500" />
|
|
||||||
{{ browserPanelOpen ? $t('chat.collapseBrowser') : $t('chat.openBrowser') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
@click="handleSend"
|
@click="handleSend"
|
||||||
@@ -5262,6 +5372,85 @@ const showChatRating = ref(false);
|
|||||||
showGeneralFeedbackDialog = false;
|
showGeneralFeedbackDialog = false;
|
||||||
}"
|
}"
|
||||||
/>
|
/>
|
||||||
|
<div
|
||||||
|
v-if="showQueryPreviewDialog"
|
||||||
|
class="dialog-overlay z-[120] items-center"
|
||||||
|
@click.self="closeQueryPreviewDialog"
|
||||||
|
>
|
||||||
|
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,1280px)] max-w-[1280px] flex-col">
|
||||||
|
<div class="dialog-header">
|
||||||
|
<div>
|
||||||
|
<h3 class="section-title">查询结果全量预览</h3>
|
||||||
|
<p class="section-desc mt-1">{{ queryPreviewState.query || queryPreviewState.title }}</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="closeQueryPreviewDialog">
|
||||||
|
<X class="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-default bg-surface-soft px-4 py-3 text-sm text-secondary">
|
||||||
|
<div>共 {{ queryPreviewState.total || 0 }} 条,当前第 {{ queryPreviewState.page }} / {{ Math.max(1, Math.ceil((queryPreviewState.total || 0) / (queryPreviewState.pageSize || 100))) }} 页</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-lg border border-default px-3 py-1.5 text-xs transition-colors hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
:disabled="queryPreviewLoading || queryPreviewState.page <= 1"
|
||||||
|
@click="changeQueryPreviewPage(-1)"
|
||||||
|
>
|
||||||
|
上一页
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-lg border border-default px-3 py-1.5 text-xs transition-colors hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
:disabled="queryPreviewLoading || queryPreviewState.page >= Math.max(1, Math.ceil((queryPreviewState.total || 0) / (queryPreviewState.pageSize || 100)))"
|
||||||
|
@click="changeQueryPreviewPage(1)"
|
||||||
|
>
|
||||||
|
下一页
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="queryPreviewError" class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||||
|
{{ queryPreviewError }}
|
||||||
|
</div>
|
||||||
|
<div class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
|
||||||
|
<div v-if="queryPreviewLoading" class="flex h-56 items-center justify-center">
|
||||||
|
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
|
||||||
|
</div>
|
||||||
|
<div v-else-if="!queryPreviewState.columns.length" class="flex h-56 items-center justify-center text-sm text-muted">
|
||||||
|
暂无可预览数据
|
||||||
|
</div>
|
||||||
|
<table v-else class="min-w-full border-collapse text-sm">
|
||||||
|
<thead class="sticky top-0 z-10 bg-slate-50">
|
||||||
|
<tr>
|
||||||
|
<th
|
||||||
|
v-for="column in queryPreviewState.columns"
|
||||||
|
:key="`query-preview-col-${column}`"
|
||||||
|
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
|
||||||
|
>
|
||||||
|
{{ column }}
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr
|
||||||
|
v-for="(row, rowIndex) in queryPreviewState.rows"
|
||||||
|
:key="`query-preview-row-${rowIndex}`"
|
||||||
|
class="odd:bg-white even:bg-slate-50/50"
|
||||||
|
>
|
||||||
|
<td
|
||||||
|
v-for="(cell, cellIndex) in row"
|
||||||
|
:key="`query-preview-cell-${rowIndex}-${cellIndex}`"
|
||||||
|
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
|
||||||
|
>
|
||||||
|
<div class="whitespace-pre-wrap break-all">{{ cell ?? '-' }}</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="showLeaveAgentDialog"
|
v-if="showLeaveAgentDialog"
|
||||||
class="dialog-overlay z-[100] items-center"
|
class="dialog-overlay z-[100] items-center"
|
||||||
@@ -5467,10 +5656,28 @@ const showChatRating = ref(false);
|
|||||||
|
|
||||||
</template>
|
</template>
|
||||||
<style scoped>
|
<style scoped>
|
||||||
:deep(.chat-markdown table) {
|
:deep(.chat-markdown) {
|
||||||
width: 100%;
|
max-width: 100%;
|
||||||
border-collapse: collapse;
|
}
|
||||||
|
|
||||||
|
:deep(.chat-markdown .chat-table-scroll) {
|
||||||
|
max-width: 100%;
|
||||||
|
overflow-x: auto;
|
||||||
|
overflow-y: hidden;
|
||||||
margin: 0.75rem 0;
|
margin: 0.75rem 0;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.chat-markdown .chat-table-inner) {
|
||||||
|
width: max-content;
|
||||||
|
min-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.chat-markdown table) {
|
||||||
|
width: max-content;
|
||||||
|
min-width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
margin: 0;
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5480,6 +5687,7 @@ const showChatRating = ref(false);
|
|||||||
padding: 0.5rem 0.75rem;
|
padding: 0.5rem 0.75rem;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
vertical-align: top;
|
vertical-align: top;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
:deep(.chat-markdown th) {
|
:deep(.chat-markdown th) {
|
||||||
|
|||||||
Reference in new issue
Block a user