346 lines
13 KiB
Python
346 lines
13 KiB
Python
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 = (
|
|
"还剩",
|
|
"还有",
|
|
"剩余",
|
|
"多少",
|
|
"余额",
|
|
"可休",
|
|
"未休",
|
|
"已休",
|
|
"总时数",
|
|
"情况",
|
|
"记录",
|
|
"明细",
|
|
"查询",
|
|
)
|
|
_STRONG_BALANCE_PATTERNS = (
|
|
r"(?:假期|年假|育儿假|休假).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少)",
|
|
r"(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:假期|年假|育儿假|休假)",
|
|
)
|
|
|
|
@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 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):
|
|
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 "暂无数据"
|
|
if isinstance(value, float) and value.is_integer():
|
|
return str(int(value))
|
|
return str(value)
|
|
|
|
@classmethod
|
|
def _format_quota(cls, value) -> str:
|
|
formatted = cls._format_number(value)
|
|
if formatted == "暂无数据":
|
|
return formatted
|
|
return f"{formatted}天"
|
|
|
|
@staticmethod
|
|
def _resolve_response_year(record: dict | None, requested_year: int | None) -> str:
|
|
if record and record.get("leave_year") is not None:
|
|
return str(record["leave_year"])
|
|
if requested_year is not None:
|
|
return str(requested_year)
|
|
return str(datetime.now().year)
|
|
|
|
@classmethod
|
|
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"| {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):
|
|
_, annual_record = annual_result
|
|
_, childcare_record = childcare_result
|
|
displayed_records = []
|
|
if leave_type in ("annual", "all"):
|
|
displayed_records.append(annual_record)
|
|
if leave_type in ("childcare", "all"):
|
|
displayed_records.append(childcare_record)
|
|
|
|
intro_year = next(
|
|
(
|
|
cls._resolve_response_year(record, requested_year)
|
|
for record in displayed_records
|
|
if record
|
|
),
|
|
str(requested_year or datetime.now().year),
|
|
)
|
|
sections = [
|
|
f"您好,已为您查询到 {intro_year} 年度假期情况:",
|
|
"",
|
|
"| 序号 | 假别 | 年度 | 可休 | 已休 | 当前剩余 |",
|
|
"| :---: | :---: | :---: | :---: | :---: | :---: |",
|
|
]
|
|
|
|
index = 1
|
|
if leave_type in ("annual", "all"):
|
|
sections.append(cls._render_table_row(index, "年假", annual_record, requested_year))
|
|
index += 1
|
|
if leave_type in ("childcare", "all"):
|
|
sections.append(cls._render_table_row(index, "育儿假", childcare_record, requested_year))
|
|
index += 1
|
|
|
|
sections.extend(
|
|
[
|
|
"",
|
|
"如需继续查询其他假期明细或历史休假记录,请告诉我,我继续帮您核对。",
|
|
"",
|
|
'如需发起请假,可点击 <a href="#" class="leave-action-trigger" data-leave-action="start-leave-flow">【点我请假】</a> 或输入 <span class="leave-intent-highlight">“我要请假”</span>。',
|
|
]
|
|
)
|
|
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': '已识别为假期查询,正在为您核对假期明细,请稍候...\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(leave_type, year, 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"
|