import json import os import re import time from datetime import datetime from flask import current_app class HRLeaveSQLServerService: """HR 假期查询服务。 用途:为“通用入口 / 人事规章”中的假期余额、明细类问题提供 SQL Server 查询。 依赖:chat.py 在识别到假期类意图后会调用本服务,查询结果再回写 ChatLog。 逻辑:先判断是否是假期查询,再识别是否为“查询他人假期”;若是则直接返回限制提示, 否则继续按当前登录用户的工号查询 HR 假期数据。 """ _LEAVE_KEYWORDS = ("年假", "育儿假", "假期", "休假", "请假") _PROCESS_KEYWORDS = ( "流程", "如何", "怎么办", "怎么", "申请", "审批", "制度", "规则", "办法", "政策", "指引", "规范", "是什么", ) _SELF_KEYWORDS = ("我", "我的", "本人", "自己") _BALANCE_KEYWORDS = ( "还剩", "还有", "剩余", "多少", "余额", "可休", "未休", "已休", "总时数", "情况", "记录", "明细", "查询", ) _STRONG_BALANCE_PATTERNS = ( r"(?:假期|年假|育儿假|休假).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少)", r"(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:假期|年假|育儿假|休假)", ) _OTHER_PERSON_PRONOUN_PATTERNS = ( r"(?:他|她|他们|她们|别人|其他人|同事).{0,8}(?:假期|年假|育儿假|休假)", r"(?:查询|查下|查一下|帮我查|帮忙查|看看|核对).{0,8}(?:他|她|他们|她们|别人|其他人|同事)", ) _PERSON_NAME_PATTERNS = ( r"(?:查询|查下|查一下|帮我查|帮忙查|看看|核对|想知道|统计).{0,4}(?P[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假)", r"(?P[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假).{0,8}(?:还剩|还有|剩余|可休|已休|未休|多少|情况|记录|明细|查询)", r"(?P[\u4e00-\u9fa5]{2,4}).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)", ) _PERSON_NAME_STOPWORDS = { "我的", "我", "本人", "自己", "假期", "年假", "育儿", "育儿假", "休假", "请假", "多少", "还有", "还剩", "剩余", "可休", "已休", "未休", "情况", "记录", "明细", "查询", "帮我", "帮忙", "今年", "去年", "本年", "公司", "部门", } _OTHER_PERSON_QUERY_MESSAGE = "暂时不支持查询其他人假期" @classmethod def supports(cls, query: str) -> bool: """判断是否应由 HR 假期模块接管。 AI 触发时机:用户问“我还有多少假期/年假/育儿假”,或试图查询他人假期时触发。 这样即使是“查张三还有多少假期”这类问句,也会先进入本服务统一拦截, 避免落回 Dify 产生不一致回答。 """ text = (query or "").strip() if not text: return False if not any(keyword in text for keyword in cls._LEAVE_KEYWORDS): return False if any(keyword in text for keyword in cls._PROCESS_KEYWORDS): return False if any(re.search(pattern, text) for pattern in cls._STRONG_BALANCE_PATTERNS): return True if cls._looks_like_other_person_leave_query(text): return True if not any(keyword in text for keyword in cls._SELF_KEYWORDS): return False if any(keyword in text for keyword in cls._BALANCE_KEYWORDS): return True return bool(re.search(r"(20\d{2}|今年|去年|本年)", text)) @classmethod def _looks_like_other_person_leave_query(cls, query: str) -> bool: """粗判是否在询问他人假期。 用途:让“查张三假期”“其他人假期还有多少”这类问句优先进入本服务。 约束:这里只做路由级粗判,不能依赖当前登录人身份;最终是否判定为“查他人” 仍由 `_is_querying_other_person_leave()` 基于当前用户信息做二次确认。 """ text = (query or "").strip() if not text: return False if any(keyword in text for keyword in cls._SELF_KEYWORDS): return False if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS): return True return bool(cls._extract_candidate_person_names(text)) @classmethod def _extract_candidate_person_names(cls, query: str) -> list[str]: """提取问句中疑似“被查询人姓名”的候选词。 用途:识别“张三的年假还有多少”这类显式姓名问句。 约束:只返回 2-4 位中文候选词,并过滤常见假期业务词,避免把“多少/今年”等噪音误识别成姓名。 """ text = (query or "").strip() candidates: list[str] = [] for pattern in cls._PERSON_NAME_PATTERNS: for match in re.finditer(pattern, text): name = (match.groupdict().get("name") or "").strip() if not name or name in cls._PERSON_NAME_STOPWORDS: continue if any(keyword in name for keyword in cls._SELF_KEYWORDS): continue if any(keyword in name for keyword in cls._BALANCE_KEYWORDS): continue if any(keyword in name for keyword in cls._LEAVE_KEYWORDS): continue candidates.append(name) # 去重并保持原有顺序,避免重复命中同一个人名。 return list(dict.fromkeys(candidates)) @classmethod def _is_querying_other_person_leave(cls, query: str, user) -> bool: """判断本次假期查询是否在查询他人。 AI 触发时机:当问句已经被识别为假期查询时调用。 核心逻辑:先识别“他/她/其他人/同事”等代词,再识别显式姓名; 若候选姓名与当前登录人的姓名/工号/用户名都不一致,则视为查询他人。 """ text = (query or "").strip() if not text: return False if any(keyword in text for keyword in cls._SELF_KEYWORDS): return False if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS): return True self_identifiers = { str(getattr(user, "real_name", None) or "").strip(), str(getattr(user, "username", None) or "").strip(), str(getattr(user, "employee_id", None) or "").strip(), } self_identifiers = {value for value in self_identifiers if value} for candidate in cls._extract_candidate_person_names(text): if candidate not in self_identifiers: return True return False @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) available_drivers = pyodbc.drivers() if driver not in available_drivers: driver = 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};" ) if driver != "SQL Server": conn_str += ( 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, unit: str = "天") -> str: formatted = cls._format_number(value) if formatted == "暂无数据": return formatted return f"{formatted}{unit}" @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, quota_unit: str = "天") -> 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'), quota_unit) used = cls._format_quota(record.get('used_hours'), quota_unit) 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( [ "", "如需继续查询其他假期明细或历史休假记录,请告诉我,我继续帮您核对。", "", '如需发起请假,可点击 【点我请假】 或输入 “我要请假”。', ] ) return "\n".join(sections) @classmethod def stream_chat(cls, query: str, user, agent, conversation_id: str = None, session_id: str | None = None): start_time = time.time() final_conversation_id = conversation_id or f"hr_{int(time.time())}" try: if cls._is_querying_other_person_leave(query, user): end_data = { "event": "message_end", "answer": cls._OTHER_PERSON_QUERY_MESSAGE, "replace_answer": True, "chat_log_id": None, "conversation_id": final_conversation_id, } yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n" return 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, session_id=session_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"