From dea3b39048c40820de6e60722d76b3908b019010 Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Tue, 12 May 2026 14:33:48 +0800 Subject: [PATCH] youhua --- backend/app/api/chat.py | 69 +++++++++-- backend/app/services/dify.py | 32 ++++- backend/app/services/integration_api.py | 13 ++ backend/app/services/text2sql.py | 152 ++++++++++++++++++++---- backend/requirements.txt | 2 + frontend/src/views/ChatView.vue | 5 +- 6 files changed, 240 insertions(+), 33 deletions(-) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index ebdfc260..0344972b 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -62,7 +62,7 @@ def _is_allowed_preview_url(target_url: str) -> bool: return False -def _fetch_preview_source_bytes(file_url: str): +def _fetch_preview_source_bytes(file_url: str, max_size: int = 15 * 1024 * 1024): """ 从上游文件 URL 拉取二进制内容(供预览接口复用)。 如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。 @@ -178,7 +178,6 @@ def _fetch_preview_source_bytes(file_url: str): return None, None, (f'upstream returned status {upstream.status_code}', 502) content = upstream.content or b'' - max_size = 15 * 1024 * 1024 if len(content) > max_size: return None, None, ('file too large for online preview', 413) @@ -281,6 +280,58 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: raise Exception("PDF output not found after conversion") +def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes: + """ + 使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。 + """ + normalized_ext = (ext or '').strip().lower() + if normalized_ext != 'xls': + return content + + with tempfile.TemporaryDirectory() as temp_dir: + input_path = os.path.join(temp_dir, "input.xls") + output_path = os.path.join(temp_dir, "input.xlsx") + with open(input_path, 'wb') as f: + f.write(content) + + commands = [ + 'soffice', + 'libreoffice', + r'C:\Program Files\LibreOffice\program\soffice.exe', + r'C:\Program Files (x86)\LibreOffice\program\soffice.exe' + ] + + errors = [] + for cmd in commands: + try: + process = subprocess.run( + [cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=60 + ) + except (FileNotFoundError, subprocess.TimeoutExpired) as e: + errors.append(f"{cmd}: {e}") + continue + + if process.returncode == 0 and os.path.exists(output_path): + with open(output_path, 'rb') as f: + return f.read() + + stderr = process.stderr.decode('utf-8', errors='ignore').strip() + errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}") + + joined = "; ".join(errors) if errors else "no converter attempted" + raise RuntimeError(f"failed to convert xls to xlsx: {joined}") + + +def _load_excel_workbook(content: bytes, ext: str): + normalized_ext = (ext or '').strip().lower() + if normalized_ext == 'xls': + content = _convert_excel_to_xlsx(content, normalized_ext) + return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True) + + @chat_bp.route('/sessions', methods=['GET']) @require_agent_permission def get_chat_sessions(): @@ -579,8 +630,8 @@ def preview_excel(): """ 内网 Excel 预览接口(简版可上线)。 说明: - - 当前仅支持 xlsx; - - xls 返回 415,由前端走下载兜底。 + - xlsx 直接解析; + - xls 先转为 xlsx 后再解析。 """ file_url = (request.args.get('url') or '').strip() if not file_url: @@ -603,13 +654,13 @@ def preview_excel(): limit = 100 limit = max(1, min(limit, 300)) - content, _, err = _fetch_preview_source_bytes(file_url) + content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024) if err: msg, code = err return jsonify({'error': msg}), code try: - wb = load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True) + wb = _load_excel_workbook(content, ext) except Exception as e: current_app.logger.warning("[excel-preview] parse workbook failed: %s", e) return jsonify({'error': 'failed to parse excel file'}), 422 @@ -674,7 +725,8 @@ def preview_text(): if ext and ext not in allowed: return jsonify({'error': f'unsupported text extension: {ext}'}), 415 - content, content_type, err = _fetch_preview_source_bytes(file_url) + max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024 + content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size) if err: msg, code = err return jsonify({'error': msg}), code @@ -717,7 +769,8 @@ def preview_file_raw(): name = (request.args.get('name') or '').strip() name_ext = (name.split('.')[-1] if '.' in name else '').lower() ext = url_path_ext or name_ext - content, content_type, err = _fetch_preview_source_bytes(file_url) + max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024 + content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size) if err: msg, code = err return jsonify({'error': msg}), code diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 804cb051..d41b79af 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -37,6 +37,35 @@ from app.services.integration_api import IntegrationApiService class DifyService: """Dify service wrapper.""" + @staticmethod + def _build_chat_messages_url(base_url: str) -> str: + """ + Build the Dify chat-messages endpoint URL from a base URL. + + Our config/agent base_url may be: + - https://api.dify.ai/v1 + - http://host:port + - http://host:port/v1 + - (user mistake) http://host:port/v1/chat-messages + + This helper normalizes common mistakes and prevents duplicate `/v1/v1/...`. + """ + base = str(base_url or "").strip().rstrip("/") + if not base: + # Keep old behavior: downstream will fail with a request error. + return "/v1/chat-messages" + + # User mistake hardening: strip endpoint suffix if someone stored it as base_url. + if base.endswith("/v1/chat-messages"): + base = base[: -len("/v1/chat-messages")].rstrip("/") + elif base.endswith("/chat-messages"): + base = base[: -len("/chat-messages")].rstrip("/") + + # Config.DIFY_API_BASE defaults to ".../v1". Avoid double "/v1". + if base.endswith("/v1"): + return f"{base}/chat-messages" + return f"{base}/v1/chat-messages" + @staticmethod def stream_chat(query: str, user_id: int, agent, conversation_id: str = None): """ @@ -60,8 +89,7 @@ class DifyService: """ # Prefer agent-specific base URL; fallback to global config. base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE - base_url = base_url.rstrip('/') - url = f"{base_url}/v1/chat-messages" + url = DifyService._build_chat_messages_url(base_url) headers = { 'Authorization': f'Bearer {agent.dify_api_key}', diff --git a/backend/app/services/integration_api.py b/backend/app/services/integration_api.py index f5654940..c6f3f54f 100644 --- a/backend/app/services/integration_api.py +++ b/backend/app/services/integration_api.py @@ -3,6 +3,7 @@ Integration API client for resolving original source-file download links. """ from datetime import datetime from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import urlparse import requests from flask import current_app, has_app_context, has_request_context, request @@ -13,6 +14,11 @@ from app.config import Config class IntegrationApiService: _cache: Dict[Tuple[str, str], Dict[str, Any]] = {} + @staticmethod + def _is_loopback_url(url: str) -> bool: + host = (urlparse(str(url or "").strip()).hostname or "").strip().lower() + return host in {"127.0.0.1", "localhost", "::1"} + @staticmethod def get_api_key() -> str: if has_app_context(): @@ -32,6 +38,13 @@ class IntegrationApiService: public_base = "" if mode != "external": + # For server-side lookups inside containers/workers, an explicit integration + # endpoint is more reliable than a public loopback URL like 127.0.0.1:5002. + if configured and ( + not has_request_context() + or IntegrationApiService._is_loopback_url(public_base) + ): + return configured if public_base: return public_base if has_request_context(): diff --git a/backend/app/services/text2sql.py b/backend/app/services/text2sql.py index 91d0db2d..3ca0a323 100644 --- a/backend/app/services/text2sql.py +++ b/backend/app/services/text2sql.py @@ -2,10 +2,13 @@ import json import os import re import time +from pathlib import Path from flask import current_app class Text2SQLService: _schema_text = None + _oracle_client_initialized = False + _jdbc_driver_url = "https://repo1.maven.org/maven2/com/oracle/database/jdbc/ojdbc8/19.25.0.0/ojdbc8-19.25.0.0.jar" @staticmethod def _backend_dir() -> str: @@ -33,6 +36,122 @@ class Text2SQLService: return client_dirs[0] return None + @classmethod + def _get_oracle_client_dir(cls) -> str | None: + env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip() + if env_dir and os.path.exists(env_dir): + return env_dir + + linux_candidates = [ + "/opt/oracle/instantclient", + "/opt/oracle/instantclient_19_28", + "/opt/oracle/instantclient_19_27", + ] + for path in linux_candidates: + if os.path.exists(path): + return path + + return cls._find_oracle_client_dir() + + @classmethod + def _init_oracle_client(cls, oracledb) -> None: + if cls._oracle_client_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)(): + return + + import platform + import shutil + import tempfile + + target_lib_dir = cls._get_oracle_client_dir() + + if platform.system() == 'Windows' and target_lib_dir: + # OCI C-library fails to load if path contains non-ASCII. + if not target_lib_dir.isascii(): + temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client') + safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir)) + if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir): + os.makedirs(temp_dir, exist_ok=True) + shutil.copytree(target_lib_dir, safe_lib_dir) + target_lib_dir = safe_lib_dir + + if target_lib_dir: + oracledb.init_oracle_client(lib_dir=target_lib_dir) + else: + oracledb.init_oracle_client() + cls._oracle_client_initialized = True + + @classmethod + def _jdbc_dir(cls) -> Path: + return Path(cls._backend_dir()) / "jdbc" + + @classmethod + def _ensure_jdbc_driver_jar(cls) -> str: + env_path = (os.getenv("ERP_JDBC_JAR") or "").strip() + if env_path and os.path.exists(env_path): + return env_path + + jar_dir = cls._jdbc_dir() + jar_dir.mkdir(parents=True, exist_ok=True) + jar_path = jar_dir / "ojdbc8-19.25.0.0.jar" + if jar_path.exists(): + return str(jar_path) + + import requests + + driver_url = os.getenv("ERP_JDBC_JAR_URL", cls._jdbc_driver_url).strip() or cls._jdbc_driver_url + with requests.get(driver_url, stream=True, timeout=120) as resp: + resp.raise_for_status() + with open(jar_path, "wb") as f: + for chunk in resp.iter_content(chunk_size=1024 * 256): + if chunk: + f.write(chunk) + return str(jar_path) + + @staticmethod + def _dsn_to_jdbc_url(dsn: str) -> str: + dsn = (dsn or "").strip() + if not dsn: + raise ValueError("ERP_DB_DSN is empty") + if dsn.startswith("jdbc:oracle:thin:@"): + return dsn + if dsn.startswith("("): + return f"jdbc:oracle:thin:@{dsn}" + match = re.match(r"^(?P[^:/]+)(?::(?P\d+))?/(?P.+)$", dsn) + if match: + host = match.group("host") + port = match.group("port") or "1521" + service = match.group("service") + return f"jdbc:oracle:thin:@//{host}:{port}/{service}" + return f"jdbc:oracle:thin:@{dsn}" + + @classmethod + def _execute_sql_via_jdbc(cls, sql: str, user: str, password: str, dsn: str): + import jaydebeapi + + jar_path = cls._ensure_jdbc_driver_jar() + jdbc_url = cls._dsn_to_jdbc_url(dsn) + connection = jaydebeapi.connect( + "oracle.jdbc.OracleDriver", + jdbc_url, + { + "user": user, + "password": password, + "oracle.jdbc.timezoneAsRegion": "false", + }, + jar_path, + ) + cursor = connection.cursor() + try: + cursor.execute(sql) + columns = [col[0] for col in cursor.description] if cursor.description else [] + rows = cursor.fetchall() if columns else [] + return columns, rows + finally: + try: + cursor.close() + finally: + connection.close() + @classmethod def get_schema(cls): if cls._schema_text is None: @@ -211,27 +330,8 @@ class Text2SQLService: dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod") try: - # Enable thick mode to support older Oracle versions - import platform - import tempfile - import shutil - if platform.system() == 'Windows': - target_lib_dir = cls._find_oracle_client_dir() - - # Fix for OCI path issue with Chinese characters (like "HX工作目录") - # OCI C-library fails to load if path contains non-ASCII - if target_lib_dir and not target_lib_dir.isascii(): - temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client') - safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir)) - if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir): - os.makedirs(temp_dir, exist_ok=True) - shutil.copytree(target_lib_dir, safe_lib_dir) - target_lib_dir = safe_lib_dir - - if target_lib_dir: - oracledb.init_oracle_client(lib_dir=target_lib_dir) - else: - oracledb.init_oracle_client() + # 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}") @@ -249,7 +349,15 @@ class Text2SQLService: return columns, rows except Exception as e: - return ["Error"], [[str(e)]] + error_text = str(e) + if current_app: + current_app.logger.warning(f"Oracle direct query failed, trying JDBC fallback: {error_text}") + if "DPY-3010" in error_text or "DPI-1047" in error_text: + try: + return cls._execute_sql_via_jdbc(sql, user, password, dsn) + except Exception as jdbc_error: + return ["Error"], [[f"{error_text} | JDBC fallback failed: {jdbc_error}"]] + return ["Error"], [[error_text]] @classmethod def format_result(cls, columns, rows, sql, original_query): diff --git a/backend/requirements.txt b/backend/requirements.txt index 49c4772f..9553425c 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -16,6 +16,8 @@ pycryptodome PyJWT cryptography oracledb +jaydebeapi +JPype1 pywin32; sys_platform == "win32" # File Parsing & edkb_system dependencies from xinxin2 diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 59b2a1c9..b878cae2 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -571,7 +571,10 @@ const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\ const isLeaveIntent = (content: string) => { const normalized = getLeaveIntentNormalized(content); - return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|我要走请假流程|请假流程)/.test(normalized); + // 弱意图(咨询流程/步骤)应走正常问答,不触发表单分流。 + const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定)/; + if (weakConsultationIntent.test(normalized)) return false; + return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|帮我请假|代我请假|提交请假)/.test(normalized); }; const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => (