diff --git a/.env.dev b/.env.dev index b57a392f..a1a31558 100644 --- a/.env.dev +++ b/.env.dev @@ -3,16 +3,16 @@ # Casdoor 做法 A:与 test/prod 共用同一 Casdoor 地址,但使用独立 Application「hxops-dev」 # 在 Casdoor 新建 Application,Redirect URLs 填入本环境实际会出现的前端 origin + /casdoor-callback # ============================================================================= -DATABASE_URL=postgresql://postgres:123456@8.152.207.171/hxops_db +DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops FLASK_APP=run.py FLASK_ENV=development # 是否启用 JWT 认证 AUTH_JWT_REQUIRED=true -AUTH_LOGIN_MODE=casdoor +AUTH_LOGIN_MODE=password # 如果需要用户密码登录,修改该值为password -#AUTH_LOGIN_MODE=password +#AUTH_LOGIN_MODE=casdoor AUTH_JWT_ISSUER=http://192.168.100.192:8870 AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 @@ -30,3 +30,6 @@ CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback CASDOOR_SCOPE=openid profile email # Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可) CASDOOR_WECOM_PROVIDER_HINT=wecom + +# Gunicorn配置 +GUNICORN_WORKERS=2 \ No newline at end of file diff --git a/.env.prod b/.env.prod index 73dcbb01..4728f383 100644 --- a/.env.prod +++ b/.env.prod @@ -31,3 +31,5 @@ CASDOOR_SCOPE=openid profile email # Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo CASDOOR_WECOM_PROVIDER_HINT=wecom +# Gunicorn配置 +GUNICORN_WORKERS=2 \ No newline at end of file diff --git a/.env.shared b/.env.shared index 2368d585..5bd20005 100644 --- a/.env.shared +++ b/.env.shared @@ -62,3 +62,11 @@ HR_SQLSERVER_DRIVER=SQL Server HR_SQLSERVER_ENCRYPT=no HR_SQLSERVER_TRUST_CERT=yes HR_SQLSERVER_TIMEOUT=10 + +# PLM Oracle +PLM_ORACLE_HOST=192.168.0.11 +PLM_ORACLE_PORT=1521 +PLM_ORACLE_SID=orcl +PLM_ORACLE_USERNAME=PLM +PLM_ORACLE_PASSWORD=PLM +ORACLE_CLIENT_LIB_DIR=oracle_client\instantclient_19_30 diff --git a/.env.test b/.env.test index a6c72df2..a216b431 100644 --- a/.env.test +++ b/.env.test @@ -30,3 +30,5 @@ CASDOOR_SCOPE=openid profile email # Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo CASDOOR_WECOM_PROVIDER_HINT=wecom +# Gunicorn配置 +GUNICORN_WORKERS=2 \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile index 76bae2d1..d3351a7e 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -215,13 +215,13 @@ pipeline { stage('Deploy Test') { when { expression { - // test 分支部署到 test 环境 / test branch deploys to test environment - (env.BRANCH_NAME == 'test') && + // test / env 分支均部署到 test 环境主机;代码与当前构建分支一致(不再强制 origin/test) + (env.BRANCH_NAME == 'test' || env.BRANCH_NAME == 'env') && (env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true') } } steps { - echo "[Deploy Test] start host=${env.TEST_DEPLOY_HOST}" + echo "[Deploy Test] start branch=${env.BRANCH_NAME} host=${env.TEST_DEPLOY_HOST}" // 使用Jenkins中的SSH_TEST_DEPLOY私钥部署到测试服务器 // Use SSH_TEST_DEPLOY credential to deploy to test server @@ -233,8 +233,8 @@ pipeline { cd ${TEST_DEPLOY_ROOT} git fetch origin git reset --hard HEAD - git checkout -B test origin/test - git reset --hard origin/test + git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME} + git reset --hard "origin/${BRANCH_NAME}" chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh ./scripts/deploy_compose.sh test "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED} ' diff --git a/backend/Dockerfile b/backend/Dockerfile index 1de91a49..f84434e6 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,4 +1,5 @@ -ARG PYTHON_BASE_IMAGE=python:3.12-slim +# syntax=docker/dockerfile:1.4 +ARG PYTHON_BASE_IMAGE=python:3.12-slim-bookworm FROM ${PYTHON_BASE_IMAGE} ARG APT_MIRROR=https://mirrors.aliyun.com @@ -9,7 +10,9 @@ ARG PIP_RETRIES=15 WORKDIR /app -RUN set -eux; \ +RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ + --mount=type=cache,target=/var/lib/apt,sharing=locked \ + set -eux; \ if [ -f /etc/apt/sources.list.d/debian.sources ]; then \ sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list.d/debian.sources; \ sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list.d/debian.sources; \ @@ -18,20 +21,31 @@ RUN set -eux; \ sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list; \ sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list; \ fi; \ - apt-get update && apt-get install -y \ + apt-get update && apt-get install -y --no-install-recommends \ libgl1 \ libglib2.0-0 \ libxcb1 \ libx11-6 \ libxext6 \ - libreoffice \ + libreoffice-nogui \ fonts-noto-cjk \ + curl \ + ca-certificates \ + gnupg \ + unixodbc-dev \ + && install -d -m 0755 /etc/apt/keyrings \ + && curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor -o /etc/apt/keyrings/microsoft-prod.gpg \ + && chmod a+r /etc/apt/keyrings/microsoft-prod.gpg \ + && echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/microsoft-prod.gpg] https://packages.microsoft.com/debian/12/prod bookworm main" > /etc/apt/sources.list.d/mssql-release.list \ + && apt-get update \ + && ACCEPT_EULA=Y apt-get install -y --no-install-recommends msodbcsql18 \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY backend/requirements.txt . -RUN set -eux; \ - PIP_ARGS="--no-cache-dir --retries ${PIP_RETRIES} --timeout ${PIP_TIMEOUT}"; \ +RUN --mount=type=cache,target=/root/.cache/pip \ + set -eux; \ + PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \ if [ -n "${PIP_INDEX_URL:-}" ]; then \ PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \ fi; \ @@ -57,4 +71,3 @@ EXPOSE 5000 # Start Gunicorn # Using the config file we created earlier CMD ["gunicorn", "-c", "deploy/gunicorn_config.py", "run:app"] - diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 7c3c8ac5..7ba509f4 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -604,8 +604,11 @@ def chat_completions(): return jsonify({'error': 'Missing user or agent context'}), 500 from app.services.dify import DifyService + from app.services.plm_oracle import PLMOracleService - if kb_type == 'ERP知识库': + if PLMOracleService.supports(query, agent): + generator = PLMOracleService.stream_chat(query, user, agent, conversation_id) + elif kb_type == 'ERP知识库': from app.services.hr_leave_sqlserver import HRLeaveSQLServerService from app.services.text2sql import Text2SQLService diff --git a/backend/app/services/hr_leave_sqlserver.py b/backend/app/services/hr_leave_sqlserver.py index 5c0f9145..611fb81e 100644 --- a/backend/app/services/hr_leave_sqlserver.py +++ b/backend/app/services/hr_leave_sqlserver.py @@ -40,6 +40,10 @@ class HRLeaveSQLServerService: "明细", "查询", ) + _STRONG_BALANCE_PATTERNS = ( + r"(?:假期|年假|育儿假|休假).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少)", + r"(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:假期|年假|育儿假|休假)", + ) @staticmethod def supports(query: str) -> bool: @@ -50,6 +54,8 @@ class HRLeaveSQLServerService: return False if any(keyword in text for keyword in HRLeaveSQLServerService._PROCESS_KEYWORDS): return False + if any(re.search(pattern, text) for pattern in HRLeaveSQLServerService._STRONG_BALANCE_PATTERNS): + return True if not any(keyword in text for keyword in HRLeaveSQLServerService._SELF_KEYWORDS): return False if any(keyword in text for keyword in HRLeaveSQLServerService._BALANCE_KEYWORDS): @@ -198,22 +204,14 @@ WHERE c002001 = ? return str(datetime.now().year) @classmethod - def _render_section(cls, title: str, record: dict | None, requested_year: int | None) -> str: + def _render_table_row(cls, index: int, title: str, record: dict | None, requested_year: int | None) -> str: response_year = cls._resolve_response_year(record, requested_year) if not record: - return ( - f"### {title}\n\n" - f"暂未查询到您 {response_year} 年度的{title}记录。" - ) - remaining = cls._format_quota(record.get("remaining_hours")) - return ( - f"### {title}\n\n" - f"您当前{title}剩余额度为 {remaining}。\n" - f"- 年度:{response_year}\n" - f"- 年度可休:{cls._format_quota(record.get('total_hours'))}\n" - f"- 已休:{cls._format_quota(record.get('used_hours'))}\n" - f"- 当前剩余:{remaining}" - ) + return f"| {index} | {title} | {response_year} | 暂无数据 | 暂无数据 | 暂无数据 |" + total = cls._format_quota(record.get('total_hours')) + used = cls._format_quota(record.get('used_hours')) + remaining = cls._format_quota(record.get('remaining_hours')) + return f"| {index} | {title} | {response_year} | {total} | {used} | {remaining} |" @classmethod def _build_result_text(cls, leave_type: str, requested_year: int | None, annual_result, childcare_result): @@ -235,11 +233,19 @@ WHERE c002001 = ? ) sections = [ f"您好,已为您查询到 {intro_year} 年度假期情况:", + "", + "| 序号 | 假别 | 年度 | 可休 | 已休 | 当前剩余 |", + "| :---: | :---: | :---: | :---: | :---: | :---: |", ] + + index = 1 if leave_type in ("annual", "all"): - sections.extend(["", cls._render_section("年假", annual_record, requested_year)]) + sections.append(cls._render_table_row(index, "年假", annual_record, requested_year)) + index += 1 if leave_type in ("childcare", "all"): - sections.extend(["", cls._render_section("育儿假", childcare_record, requested_year)]) + sections.append(cls._render_table_row(index, "育儿假", childcare_record, requested_year)) + index += 1 + sections.extend( [ "", diff --git a/backend/app/services/oa_leave_workflow.py b/backend/app/services/oa_leave_workflow.py index 0c4d0dcf..190deb4b 100644 --- a/backend/app/services/oa_leave_workflow.py +++ b/backend/app/services/oa_leave_workflow.py @@ -214,6 +214,13 @@ class OALeaveWorkflowService: if show_node is None: show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue') show_node.text = str(show_value) + + # 强制将字段设为可编辑和可见,防止OA流程节点中被配置为只读导致无法写入 + for tag in ['edit', 'view']: + node = field.find(f'wf:{tag}', NS) + if node is None: + node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}') + node.text = 'true' @classmethod def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None: @@ -290,11 +297,11 @@ class OALeaveWorkflowService: cls._set_text(request_info, './/wf:workflowBaseInfo/wf:workflowId', workflow_id) cls._set_field(request_info, 'requestname', value=request_name, show_value=request_name) - cls._set_field(request_info, 'tdrgh', value=filler['employee_id'], show_value=filler['employee_id']) - cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'], show_value=applicant['employee_id']) + cls._set_field(request_info, 'tdrgh', value=filler['employee_id']) + cls._set_field(request_info, 'sqrgh', value=applicant['employee_id']) cls._set_field(request_info, 'tdrxm', value=filler['user_id'], show_value=filler['name']) cls._set_field(request_info, 'sqrxm', value=applicant['user_id'], show_value=applicant['name']) - cls._set_field(request_info, 'dlrgh', value=agent['employee_id'], show_value=agent['employee_id']) + cls._set_field(request_info, 'dlrgh', value=agent['employee_id']) cls._set_field(request_info, 'dlrxm', value=agent['user_id'], show_value=agent['name']) cls._set_field(request_info, 'dlrlogid', value=agent['user_id'], show_value=agent['user_id']) cls._set_field(request_info, 'jb', value=leave_type_code, show_value=leave_type_label) diff --git a/backend/app/services/plm_oracle.py b/backend/app/services/plm_oracle.py new file mode 100644 index 00000000..0ebfbf3a --- /dev/null +++ b/backend/app/services/plm_oracle.py @@ -0,0 +1,280 @@ +import json +import os +import re +import time +from datetime import datetime + +from flask import current_app + +from app.models import ChatLog, db +from app.services.text2sql import Text2SQLService + + +class PLMOracleService: + _ALLOWED_AGENT_NAMES = {"通用入口", "生产sop"} + _MAX_RESULT_ROWS = 50 + _MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE) + _EXPLICIT_LABEL_PATTERN = re.compile( + r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})", + re.IGNORECASE, + ) + _RELATIONAL_SQL = """ +select * + from bi_file endb + where endb.revisionguid in ( + select bb.revisionguid + from ( + select v.end1, b.* + from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b + where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$') + and str.viewfk = v.guid + and str.end2$master = cad.masterfk + and cad.latestrevision like '%m%' + and b.revisionguid = cad.guid + union + select v.end1, b.* + from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b + where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$') + and str.viewfk = v.guid + and str.end2$master = cad.masterfk + and cad.latestrevision like '%m%' + and b.revisionguid = cad.guid + union + select v.end1, b.* + from viewobject_0 v, + StructureObject_0 str, + document_0 doc, + bi_file b + where v.name in ('RelatedDoc') + and str.viewfk = v.guid + and str.end2$master = doc.masterfk + and doc.latestrevision like '%m%' + and b.revisionguid = doc.guid + ) bb, + item_0 i + where bb.end1 = i.guid + and i.id = :item_id + and i.latestrevision like '%m%' + ) + and endb.lastaccesstime is not null +""" + _FILENAME_SQL = """ +select * + from bi_file + where upper(name) like :name_pattern + and lastaccesstime is not null + order by lastaccesstime desc nulls last +""" + + @classmethod + def supports(cls, query: str, agent) -> bool: + return bool(cls.extract_material_no(query) and cls._is_supported_agent(agent)) + + @classmethod + def extract_material_no(cls, query: str) -> str | None: + text = str(query or "").strip().upper() + if not text: + return None + + explicit = cls._EXPLICIT_LABEL_PATTERN.search(text) + if explicit: + return explicit.group(1).strip().upper() + + direct_match = cls._MATERIAL_PATTERN.fullmatch(text) + if direct_match: + return direct_match.group(0).upper() + + for match in cls._MATERIAL_PATTERN.finditer(text): + candidate = match.group(0).upper() + if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate): + return candidate + return None + + @classmethod + def _is_supported_agent(cls, agent) -> bool: + name = str(getattr(agent, "name", "") or "").strip().lower().replace(" ", "") + return name in cls._ALLOWED_AGENT_NAMES + + @staticmethod + def _get_connect_kwargs() -> dict: + dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip() + host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip() + port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip()) + service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip() + sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip() + + kwargs = { + "user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(), + "password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(), + } + if dsn: + kwargs["dsn"] = dsn + return kwargs + + import oracledb + + if service_name: + kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name) + else: + kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid) + return kwargs + + @classmethod + def _connect(cls): + try: + import oracledb + except ImportError as exc: + raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc + + oracle_client_dir = Text2SQLService._get_oracle_client_dir() + Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir) + Text2SQLService._init_oracle_client(oracledb) + return oracledb.connect(**cls._get_connect_kwargs()) + + @classmethod + def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]: + connection = cls._connect() + cursor = connection.cursor() + try: + cursor.execute(sql, params) + columns = [col[0] for col in cursor.description] if cursor.description else [] + rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1) + return columns, rows + finally: + try: + cursor.close() + finally: + connection.close() + + @classmethod + def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]: + try: + columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no) + if rows: + return columns, rows, "relational" + except Exception as exc: + if current_app: + current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc) + + columns, rows = cls._execute_query( + cls._FILENAME_SQL, + name_pattern=f"{material_no.upper()}%", + ) + return columns, rows, "filename_fallback" + + @staticmethod + def _format_datetime(value) -> str: + if value is None: + return "-" + if isinstance(value, datetime): + return value.strftime("%Y-%m-%d %H:%M:%S") + return str(value) + + @staticmethod + def _format_size(value) -> str: + if value in (None, ""): + return "-" + try: + size = int(value) + except (TypeError, ValueError): + return str(value) + if size < 1024: + return f"{size} B" + if size < 1024 * 1024: + return f"{size / 1024:.1f} KB" + return f"{size / 1024 / 1024:.2f} MB" + + @classmethod + def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str: + if not rows: + return f"已在 PLM 中查询料号 `{material_no}`,未找到符合条件的相关资料。" + + overflow = len(rows) > cls._MAX_RESULT_ROWS + visible_rows = rows[: cls._MAX_RESULT_ROWS] + index_map = {name.upper(): idx for idx, name in enumerate(columns)} + + def pick(row: tuple, column_name: str, default: str = "-") -> str: + idx = index_map.get(column_name.upper()) + if idx is None or idx >= len(row): + return default + value = row[idx] + if column_name.upper() in {"CREATETIME", "LASTACCESSTIME"}: + return cls._format_datetime(value) + if column_name.upper() == "FILESIZE": + return cls._format_size(value) + return "-" if value in (None, "") else str(value) + + lines = [ + f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录" + + ("(仅展示前 50 条)" if overflow else "。"), + "", + "| 序号 | 文件名 | 扩展名 | 文件类型 | 文件大小 | 相对路径 | 最后访问时间 |", + "| --- | --- | --- | --- | --- | --- | --- |", + ] + for idx, row in enumerate(visible_rows, start=1): + lines.append( + f"| {idx} | {pick(row, 'NAME')} | {pick(row, 'EXTENTIONNAME')} | {pick(row, 'FILETYPE')} | " + f"{pick(row, 'FILESIZE')} | {pick(row, 'RELATIVEPATH')} | {pick(row, 'LASTACCESSTIME')} |" + ) + + if overflow: + lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"]) + return "\n".join(lines) + + @classmethod + def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None): + start_time = time.time() + final_conversation_id = conversation_id or f"plm_{int(time.time())}" + material_no = cls.extract_material_no(query) + + try: + if not material_no: + raise RuntimeError("未识别到有效料号,请输入类似 F3-A12M290000019 的料号。") + + yield f"data: {json.dumps({'event': 'message', 'answer': f'已识别料号 `{material_no}`,正在查询 PLM 资料,请稍候...\\n'}, ensure_ascii=False)}\n\n" + + columns, rows, query_mode = cls._query_files(material_no) + answer = cls._build_answer(material_no, columns, rows) + latency = int((time.time() - start_time) * 1000) + + chat_log_id = None + try: + chat_log = ChatLog( + user_id=user.id, + agent_id=agent.id, + conversation_id=final_conversation_id, + query=query, + answer=answer, + tokens_used=0, + latency=latency, + payload={ + "material_no": material_no, + "row_count": min(len(rows), cls._MAX_RESULT_ROWS), + "query_mode": query_mode, + }, + ) + db.session.add(chat_log) + db.session.commit() + chat_log_id = chat_log.id + except Exception as exc: + if current_app: + current_app.logger.error("Failed to log PLM chat: %s", exc) + db.session.rollback() + + end_data = { + "event": "message_end", + "answer": answer, + "replace_answer": True, + "chat_log_id": chat_log_id, + "conversation_id": final_conversation_id, + } + yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n" + except Exception as exc: + if current_app: + current_app.logger.exception("[plm-oracle] stream_chat failed query=%s", query) + error_data = { + "event": "error", + "message": str(exc) or "PLM 查询失败", + "conversation_id": final_conversation_id, + } + yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n" diff --git a/backend/app/services/text2sql.py b/backend/app/services/text2sql.py index d4347835..0a4af12c 100644 --- a/backend/app/services/text2sql.py +++ b/backend/app/services/text2sql.py @@ -2,13 +2,11 @@ import json import os import re import time -from pathlib import Path from flask import current_app, has_app_context 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: @@ -18,12 +16,19 @@ class Text2SQLService: def _project_root(cls) -> str: return os.path.dirname(cls._backend_dir()) + @classmethod + def _resolve_project_path(cls, path_value: str) -> str: + normalized = os.path.normpath(path_value) + if os.path.isabs(normalized): + return normalized + return os.path.normpath(os.path.join(cls._project_root(), normalized)) + @classmethod def _find_oracle_client_dir(cls) -> str | None: env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip() candidate_roots = [] if env_dir: - candidate_roots.append(env_dir) + candidate_roots.append(cls._resolve_project_path(env_dir)) candidate_roots.extend([ os.path.join(cls._backend_dir(), 'oracle_client'), os.path.join(cls._project_root(), 'oracle_client'), @@ -154,8 +159,10 @@ class Text2SQLService: @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 + if env_dir: + resolved_env_dir = cls._resolve_project_path(env_dir) + if os.path.exists(resolved_env_dir): + return resolved_env_dir linux_candidates = [ "/opt/oracle/instantclient", @@ -195,78 +202,6 @@ class Text2SQLService: 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: @@ -532,12 +467,7 @@ class Text2SQLService: except Exception as 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}"]] + current_app.logger.warning(f"Oracle direct query failed: {error_text}") return ["Error"], [[error_text]] @classmethod diff --git a/backend/deploy/gunicorn_config.py b/backend/deploy/gunicorn_config.py index 361b2a15..cafe96ba 100644 --- a/backend/deploy/gunicorn_config.py +++ b/backend/deploy/gunicorn_config.py @@ -15,7 +15,8 @@ worker_class = "gevent" # 进程数 # 公式: 2 * CPU核心数 + 1 -workers = multiprocessing.cpu_count() * 2 + 1 +# workers = multiprocessing.cpu_count() * 2 + 1 +min(int(os.getenv("GUNICORN_WORKERS", "9")), multiprocessing.cpu_count() * 2 + 1) # 每个 Worker 的最大并发连接数 worker_connections = 1000 diff --git a/backend/gunicorn_config.py b/backend/gunicorn_config.py index cc060c20..51f9a3c2 100644 --- a/backend/gunicorn_config.py +++ b/backend/gunicorn_config.py @@ -4,6 +4,7 @@ backend/gunicorn_config.py 生产环境 Gunicorn 配置 (支持高并发) """ import multiprocessing +import os # 绑定地址 bind = "0.0.0.0:8000" @@ -12,7 +13,7 @@ bind = "0.0.0.0:8000" worker_class = "gevent" # Worker 数量:通常 CPU 核数 * 2 + 1 -workers = multiprocessing.cpu_count() * 2 + 1 +workers = min(int(os.getenv("GUNICORN_WORKERS", "9")), multiprocessing.cpu_count() * 2 + 1) # 核心:每个 Worker 最大并发连接数 # Gevent 下这个值可以设置得很高,支持海量 SSE 连接 diff --git a/backend/requirements.txt b/backend/requirements.txt index 081a5eb6..7c8becdc 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -16,9 +16,8 @@ pycryptodome PyJWT cryptography oracledb -jaydebeapi -JPype1 -pyodbc +pyodbc>=5.1.0 +zeep>=4.2.1 pywin32; sys_platform == "win32" # File Parsing & edkb_system dependencies from xinxin2 diff --git a/backend/tests/test_hr_leave_sqlserver_support.py b/backend/tests/test_hr_leave_sqlserver_support.py new file mode 100644 index 00000000..14907889 --- /dev/null +++ b/backend/tests/test_hr_leave_sqlserver_support.py @@ -0,0 +1,13 @@ +from app.services.hr_leave_sqlserver import HRLeaveSQLServerService + + +def test_supports_strong_leave_balance_intent_without_self_pronoun(): + assert HRLeaveSQLServerService.supports("假期还有多少") + assert HRLeaveSQLServerService.supports("还有多少假期") + assert HRLeaveSQLServerService.supports("年假还有多少天") + assert HRLeaveSQLServerService.supports("还有多少年假") + + +def test_supports_rejects_leave_process_questions(): + assert not HRLeaveSQLServerService.supports("假期怎么申请") + assert not HRLeaveSQLServerService.supports("年假制度是什么") diff --git a/docker-compose.yml b/docker-compose.yml index 950b975a..a24c7779 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -23,7 +23,7 @@ services: context: . dockerfile: backend/Dockerfile args: - PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim} + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim-bookworm} PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} container_name: hxops-backend @@ -65,7 +65,7 @@ services: context: ./backend dockerfile: Dockerfile args: - PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim} + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim-bookworm} PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} container_name: hxops-kb-worker diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index e3b725ff..bf872e4d 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -434,15 +434,17 @@ const input = ref(''); const currentAgent = ref(null); const showGeneralFeedbackDialog = ref(false); -const OA_LOGIN_URL = 'http://192.168.100.221:8888/login/Login.jsp?logintype=1'; -const OA_VERIFY_LOGIN_URL = 'http://192.168.100.221:8888/login/VerifyLogin.jsp'; +const OA_BASE_URL = 'http://oa.well-trust.com:8888'; +const OA_LOGIN_URL = `${OA_BASE_URL}/login/Login.jsp?logintype=1`; +const OA_VERIFY_LOGIN_URL = `${OA_BASE_URL}/login/VerifyLogin.jsp`; const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid='; +const OA_REQUEST_VIEW_PATH = '/workflow/request/ViewRequest.jsp?requestid='; const OA_AUTO_LOGIN_USERNAME = '26040006'; const OA_AUTO_LOGIN_PASSWORD = '26040006'; const OA_AUTO_LOGIN_TARGET = 'hxops-oa-leave-request'; -const openOALeaveRequestDirectly = () => { - const popup = window.open(OA_LOGIN_URL, OA_AUTO_LOGIN_TARGET); +const openOAAutoLoginPage = (gopage: string, target = OA_AUTO_LOGIN_TARGET) => { + const popup = window.open(OA_LOGIN_URL, target); if (!popup) { showMessageDialog('warning', '浏览器拦截了 OA 页面,请允许弹出窗口后重试。'); return; @@ -451,13 +453,13 @@ const openOALeaveRequestDirectly = () => { const form = document.createElement('form'); form.action = OA_VERIFY_LOGIN_URL; form.method = 'POST'; - form.target = OA_AUTO_LOGIN_TARGET; + form.target = target; form.style.display = 'none'; const fields = { loginid: OA_AUTO_LOGIN_USERNAME, userpassword: OA_AUTO_LOGIN_PASSWORD, - gopage: OA_LEAVE_APPLY_PATH, + gopage, logintype: '1', }; @@ -476,6 +478,19 @@ const openOALeaveRequestDirectly = () => { }, 0); }; +const openOALeaveRequestDirectly = () => { + openOAAutoLoginPage(OA_LEAVE_APPLY_PATH); +}; + +const openOARequestDirectly = (requestId: string) => { + const normalizedRequestId = String(requestId || '').trim(); + if (!normalizedRequestId || normalizedRequestId === '-') { + showMessageDialog('warning', '当前未获取到 OA 单据编号,暂时无法打开单据详情。'); + return; + } + openOAAutoLoginPage(`${OA_REQUEST_VIEW_PATH}${encodeURIComponent(normalizedRequestId)}`, `hxops-oa-request-${normalizedRequestId}`); +}; + const activeFeedbackMessageIndex = ref(null); const browserPanelOpen = ref(false); const browserDraftUrl = ref(''); @@ -516,8 +531,6 @@ const getLeaveTypeLabel = (val: string) => { return t ? t.label : val; }; -const LEAVE_RESULT_QUERY_URL = 'http://192.168.100.221:8888/'; - interface LeaveRequestFormData { applicantName: string; employeeId: string; @@ -666,11 +679,38 @@ const formatDurationLabel = (hours: number) => { return `${hours} 小时`; }; -const createLeaveFormData = (): LeaveRequestFormData => { +const extractLeaveTypeFromIntent = (content: string) => { + if (!content) return ''; + const map: Record = { + '事假': '005', + '病假': '006', + '丧假': '007', + '年假': '010', + '因公出差': '021', + '出差': '021', + '调休': '025', + '产假': '401', + '陪产假': '402', + '婚假': '403', + '住院': '405', + '工伤': '406', + '育儿假': '408', + '返乡': 'ZZ01', + }; + for (const [key, val] of Object.entries(map)) { + if (content.includes(key)) { + return val; + } + } + return ''; +}; + +const createLeaveFormData = (content?: string): LeaveRequestFormData => { const now = new Date(); const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000); const startTime = formatDateTime(now); const endTime = formatDateTime(oneHourLater); + const initialLeaveType = extractLeaveTypeFromIntent(content || ''); return { applicantName: currentUserDisplayName.value, employeeId: currentUserEmployeeId.value, @@ -680,7 +720,7 @@ const createLeaveFormData = (): LeaveRequestFormData => { agentUid: '', agentEmployeeId: '', agentName: '', - leaveType: '', + leaveType: initialLeaveType, startTime, endTime, durationHours: calculateDurationHours(startTime, endTime), @@ -705,8 +745,8 @@ const isStrongLeaveIntent = (content: string) => { // 弱意图(咨询流程/步骤)应走正常问答,不触发表单分流。 const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定)/; if (weakConsultationIntent.test(normalized)) return false; - if (/^(请假|休假)$/.test(normalized)) return true; - return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|帮我请假|代我请假|提交请假)/.test(normalized); + if (/^(请假|休假|年假|事假|病假|调休)$/.test(normalized)) return true; + return /(我要请|申请请|发起请|请假申请|我要休|申请休|想请|帮我请|代我请|提交请)/.test(normalized); }; const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => { @@ -744,7 +784,7 @@ const startLocalLeaveFlow = async (content: string) => { const formId = newLocalMessageId('leave-form'); const payload: LeaveFormPayload = { formId, - form: createLeaveFormData(), + form: createLeaveFormData(content), submitting: false, confirmationGenerated: false, }; @@ -1132,7 +1172,7 @@ const confirmLeaveSubmission = async (msg: any) => { const resultMsg = { role: 'assistant' as const, type: 'leave-result' as const, - content: `请假单已提交到 OA,具体单据请到 ${LEAVE_RESULT_QUERY_URL} 查询。`, + content: '请假单已推送到 OA,具体单据请 【 登录OA系统查看提交】', payload: { formId: payload.formId, success: true, @@ -1736,7 +1776,17 @@ const showChatRating = ref(false); : 'border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-500/30 dark:bg-rose-500/10 dark:text-rose-100'" >
{{ getLeaveResultPayload(msg)!.success ? 'OA 提交结果' : 'OA 提交失败' }}
-
{{ msg.content }}
+
+ 请假单已推送到 OA,具体单据请 + + 【 登录OA系统查看提交】 + +
+
{{ msg.content }}
单据编号:{{ getLeaveResultPayload(msg)!.referenceNo }}
提交时间:{{ getLeaveResultPayload(msg)!.submittedAt }}
diff --git a/scripts/deploy_compose.sh b/scripts/deploy_compose.sh index 2f4bffc4..0330d98f 100755 --- a/scripts/deploy_compose.sh +++ b/scripts/deploy_compose.sh @@ -174,6 +174,9 @@ fi if [[ "${PREBUILT_MODE}" == "true" ]]; then "${DC_CMD[@]}" "${compose_args[@]}" up -d --no-build "${services[@]}" else + # Dockerfile 使用 apt/pip cache mount,需启用 BuildKit + export DOCKER_BUILDKIT=1 + export COMPOSE_DOCKER_CLI_BUILD=1 "${DC_CMD[@]}" "${compose_args[@]}" up -d --build "${services[@]}" fi