对接HR系统的SQLserver数据库查数
This commit is contained in:
1 parent
964e4925c0
commit
65b7ea8fa1
6 files changed
+371
-12
No files matched your search
@@ -0,0 +1,309 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from flask import current_app
|
||||
|
||||
|
||||
class HRLeaveSQLServerService:
|
||||
_LEAVE_KEYWORDS = ("年假", "育儿假", "假期", "休假", "请假")
|
||||
_PROCESS_KEYWORDS = (
|
||||
"流程",
|
||||
"如何",
|
||||
"怎么办",
|
||||
"怎么",
|
||||
"申请",
|
||||
"审批",
|
||||
"制度",
|
||||
"规则",
|
||||
"办法",
|
||||
"政策",
|
||||
"指引",
|
||||
"规范",
|
||||
"是什么",
|
||||
)
|
||||
_SELF_KEYWORDS = ("我", "我的", "本人", "自己")
|
||||
_BALANCE_KEYWORDS = (
|
||||
"还剩",
|
||||
"还有",
|
||||
"剩余",
|
||||
"多少",
|
||||
"余额",
|
||||
"可休",
|
||||
"未休",
|
||||
"已休",
|
||||
"总时数",
|
||||
"情况",
|
||||
"记录",
|
||||
"明细",
|
||||
"查询",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def supports(query: str) -> bool:
|
||||
text = (query or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
if not any(keyword in text for keyword in HRLeaveSQLServerService._LEAVE_KEYWORDS):
|
||||
return False
|
||||
if any(keyword in text for keyword in HRLeaveSQLServerService._PROCESS_KEYWORDS):
|
||||
return False
|
||||
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):
|
||||
return True
|
||||
return bool(re.search(r"(20\d{2}|今年|去年|本年)", text))
|
||||
|
||||
@staticmethod
|
||||
def _detect_leave_type(query: str) -> str:
|
||||
text = (query or "").strip()
|
||||
if "育儿假" in text:
|
||||
return "childcare"
|
||||
if "年假" in text:
|
||||
return "annual"
|
||||
return "all"
|
||||
|
||||
@staticmethod
|
||||
def _extract_year(query: str) -> int | None:
|
||||
text = (query or "").strip()
|
||||
now_year = datetime.now().year
|
||||
explicit = re.search(r"(20\d{2})", text)
|
||||
if explicit:
|
||||
return int(explicit.group(1))
|
||||
if "今年" in text or "本年" in text:
|
||||
return now_year
|
||||
if "去年" in text:
|
||||
return now_year - 1
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _get_employee_code(user) -> str:
|
||||
employee_code = str(
|
||||
getattr(user, "employee_id", None)
|
||||
or getattr(user, "username", None)
|
||||
or ""
|
||||
).strip()
|
||||
if not employee_code:
|
||||
raise RuntimeError("当前登录用户缺少工号,无法查询 HR 假期数据")
|
||||
return employee_code
|
||||
|
||||
@staticmethod
|
||||
def _pick_driver(pyodbc) -> str:
|
||||
drivers = pyodbc.drivers()
|
||||
preferred = [
|
||||
"ODBC Driver 18 for SQL Server",
|
||||
"ODBC Driver 17 for SQL Server",
|
||||
"SQL Server",
|
||||
]
|
||||
for name in preferred:
|
||||
if name in drivers:
|
||||
return name
|
||||
if not drivers:
|
||||
raise RuntimeError("未找到可用的 SQL Server ODBC 驱动")
|
||||
return drivers[-1]
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
try:
|
||||
import pyodbc
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("pyodbc 未安装,无法连接 HR SQL Server") from exc
|
||||
|
||||
driver = os.getenv("HR_SQLSERVER_DRIVER", "").strip() or cls._pick_driver(pyodbc)
|
||||
server = os.getenv("HR_SQLSERVER_HOST", "192.168.100.191").strip()
|
||||
port = os.getenv("HR_SQLSERVER_PORT", "1433").strip()
|
||||
database = os.getenv("HR_SQLSERVER_DATABASE", "NH_N8_HEXIN").strip()
|
||||
username = os.getenv("HR_SQLSERVER_USERNAME", "AI_Knowledge_Base_Hr").strip()
|
||||
password = os.getenv("HR_SQLSERVER_PASSWORD", "hoo-thai@123_AI_HR").strip()
|
||||
encrypt = os.getenv("HR_SQLSERVER_ENCRYPT", "no").strip().lower()
|
||||
trust_cert = os.getenv("HR_SQLSERVER_TRUST_CERT", "yes").strip().lower()
|
||||
timeout = int(os.getenv("HR_SQLSERVER_TIMEOUT", "10"))
|
||||
|
||||
conn_str = (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={server},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
return pyodbc.connect(conn_str, timeout=timeout)
|
||||
|
||||
@staticmethod
|
||||
def _build_query(view_name: str, year_column: str, total_column: str, used_column: str, remaining_column: str, year: int | None):
|
||||
base_sql = f"""
|
||||
SELECT TOP 1
|
||||
c001001 AS department_code,
|
||||
c001002 AS department_name,
|
||||
a008003 AS parent_department_name,
|
||||
c002001 AS employee_id,
|
||||
c002002 AS employee_name,
|
||||
{year_column} AS leave_year,
|
||||
{total_column} AS total_hours,
|
||||
{used_column} AS used_hours,
|
||||
{remaining_column} AS remaining_hours
|
||||
FROM {view_name}
|
||||
WHERE c002001 = ?
|
||||
"""
|
||||
params = []
|
||||
if year is not None:
|
||||
base_sql += f" AND {year_column} = ?\n"
|
||||
params.append(year)
|
||||
base_sql += f"ORDER BY {year_column} DESC"
|
||||
return base_sql.strip(), params
|
||||
|
||||
@classmethod
|
||||
def _query_one(cls, view_name: str, year_column: str, total_column: str, used_column: str, remaining_column: str, employee_code: str, year: int | None):
|
||||
sql, extra_params = cls._build_query(view_name, year_column, total_column, used_column, remaining_column, year)
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
params = [employee_code] + extra_params
|
||||
cursor.execute(sql, params)
|
||||
columns = [col[0] for col in cursor.description] if cursor.description else []
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return sql, None
|
||||
return sql, {columns[idx]: row[idx] for idx in range(len(columns))}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@staticmethod
|
||||
def _format_number(value):
|
||||
if value is None:
|
||||
return "暂无数据"
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _render_section(cls, title: str, record: dict | None) -> str:
|
||||
if not record:
|
||||
return f"### {title}\n\n- 当前未查询到对应记录。"
|
||||
return (
|
||||
f"### {title}\n\n"
|
||||
f"- 员工工号:{record.get('employee_id')}\n"
|
||||
f"- 员工姓名:{record.get('employee_name')}\n"
|
||||
f"- 部门:{record.get('department_name') or '暂无数据'}\n"
|
||||
f"- 上级部门:{record.get('parent_department_name') or '暂无数据'}\n"
|
||||
f"- 年份:{cls._format_number(record.get('leave_year'))}\n"
|
||||
f"- 总时数:{cls._format_number(record.get('total_hours'))}\n"
|
||||
f"- 已休时数:{cls._format_number(record.get('used_hours'))}\n"
|
||||
f"- 剩余时数:{cls._format_number(record.get('remaining_hours'))}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _build_result_text(cls, query: str, employee_code: str, annual_result, childcare_result):
|
||||
annual_sql, annual_record = annual_result
|
||||
childcare_sql, childcare_record = childcare_result
|
||||
sections = [
|
||||
f"- 查询对象:当前登录人工号 `{employee_code}`",
|
||||
f"- 用户问题:{query}",
|
||||
"",
|
||||
cls._render_section("年假", annual_record),
|
||||
"",
|
||||
cls._render_section("育儿假", childcare_record),
|
||||
"",
|
||||
"<details>",
|
||||
"<summary class=\"cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300 mb-2\">执行的SQL</summary>",
|
||||
"",
|
||||
"```sql",
|
||||
annual_sql,
|
||||
"",
|
||||
childcare_sql,
|
||||
"```",
|
||||
"</details>",
|
||||
]
|
||||
return "\n".join(sections)
|
||||
|
||||
@classmethod
|
||||
def stream_chat(cls, query: str, user, agent, conversation_id: str = None):
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"hr_{int(time.time())}"
|
||||
try:
|
||||
employee_code = cls._get_employee_code(user)
|
||||
leave_type = cls._detect_leave_type(query)
|
||||
year = cls._extract_year(query)
|
||||
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '已识别为 HR 假期查询,正在按当前登录人工号检索 SQL Server 数据...\n'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
annual_result = ("-- 未执行年假查询", None)
|
||||
childcare_result = ("-- 未执行育儿假查询", None)
|
||||
|
||||
if leave_type in ("annual", "all"):
|
||||
annual_result = cls._query_one(
|
||||
view_name="VIEW_D044",
|
||||
year_column="D044001",
|
||||
total_column="D044005",
|
||||
used_column="D044006",
|
||||
remaining_column="D044007",
|
||||
employee_code=employee_code,
|
||||
year=year,
|
||||
)
|
||||
|
||||
if leave_type in ("childcare", "all"):
|
||||
childcare_result = cls._query_one(
|
||||
view_name="VIEW_D072",
|
||||
year_column="d072001",
|
||||
total_column="d072002",
|
||||
used_column="d072003",
|
||||
remaining_column="d072004",
|
||||
employee_code=employee_code,
|
||||
year=year,
|
||||
)
|
||||
|
||||
result_text = cls._build_result_text(query, employee_code, annual_result, childcare_result)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[hr-leave] query done user_id=%s employee_code=%s leave_type=%s year=%s latency_ms=%s",
|
||||
getattr(user, "id", None),
|
||||
employee_code,
|
||||
leave_type,
|
||||
year,
|
||||
latency,
|
||||
)
|
||||
|
||||
from app.models import ChatLog, db
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=final_conversation_id,
|
||||
query=query,
|
||||
answer=result_text,
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
)
|
||||
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 hr leave chat: %s", exc)
|
||||
db.session.rollback()
|
||||
|
||||
end_data = {
|
||||
"event": "message_end",
|
||||
"answer": result_text,
|
||||
"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("[hr-leave] stream_chat failed query=%s", query)
|
||||
error_data = {
|
||||
"event": "error",
|
||||
"message": str(exc) or "HR 假期查询失败",
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
Reference in new issue
Block a user