259 lines
10 KiB
Python
259 lines
10 KiB
Python
"""
|
|
backend/app/services/oa_sqlserver.py
|
|
|
|
用途:封装 OA SQL Server 的员工检索与组织信息查询能力,供请假代理人/申请人选择等场景复用。
|
|
依赖:pyodbc、OA ecology 数据库视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
|
|
逻辑:通过只读 SQL 查询返回 OA 用户与组织字段;对于 OA 中夹带的多语言包装串,统一在服务层清洗成可直接展示的中文文本。
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
|
|
import pyodbc
|
|
from flask import current_app
|
|
|
|
_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
|
|
r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
|
|
)
|
|
|
|
class OASQLServerService:
|
|
@staticmethod
|
|
def _normalize_oa_text(value) -> str:
|
|
"""
|
|
清洗 OA 多语言包装字段。
|
|
|
|
AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
|
|
`~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
|
|
可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
|
|
|
|
Args:
|
|
value: 来自 OA SQL Server 的原始字段值。
|
|
|
|
Returns:
|
|
优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
|
|
"""
|
|
text = str(value or "").strip()
|
|
if not text:
|
|
return ""
|
|
matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
|
|
if not matched:
|
|
return text
|
|
simplified, english, traditional = (
|
|
segment.strip().strip("`").strip()
|
|
for segment in matched.groups()
|
|
)
|
|
return simplified or english or traditional or text
|
|
|
|
@staticmethod
|
|
def _pick_driver():
|
|
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):
|
|
driver = os.getenv("OA_SQLSERVER_DRIVER", "").strip() or cls._pick_driver()
|
|
available_drivers = pyodbc.drivers()
|
|
if driver not in available_drivers:
|
|
driver = cls._pick_driver()
|
|
server = os.getenv("OA_SQLSERVER_HOST", "192.168.100.225").strip()
|
|
port = os.getenv("OA_SQLSERVER_PORT", "1433").strip()
|
|
database = os.getenv("OA_SQLSERVER_DATABASE", "ecology").strip()
|
|
username = os.getenv("OA_SQLSERVER_USERNAME", "AI_Knowledge_Base_OA").strip()
|
|
password = os.getenv("OA_SQLSERVER_PASSWORD", "hoo-thai@123_AI_OA").strip()
|
|
encrypt = os.getenv("OA_SQLSERVER_ENCRYPT", "no").strip().lower()
|
|
trust_cert = os.getenv("OA_SQLSERVER_TRUST_CERT", "yes").strip().lower()
|
|
timeout = int(os.getenv("OA_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)
|
|
|
|
@classmethod
|
|
def search_employees(cls, keyword: str, page: int, page_size: int):
|
|
connection = cls._connect()
|
|
cursor = connection.cursor()
|
|
try:
|
|
offset = (page - 1) * page_size
|
|
params = []
|
|
|
|
# Count total
|
|
count_sql = "SELECT COUNT(1) FROM userInfo_view WHERE 1=1"
|
|
if keyword:
|
|
count_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
|
like_kw = f"%{keyword}%"
|
|
params.extend([like_kw, like_kw])
|
|
|
|
cursor.execute(count_sql, params)
|
|
total = cursor.fetchone()[0]
|
|
|
|
# Fetch page
|
|
# Compatible with older SQL Server versions (2008/2012)
|
|
query_sql = """
|
|
SELECT id, workcode, lastname, jobtitle, departmentid, subcompanyid1,
|
|
departmentname, subcompanyname, jobtitlename
|
|
FROM (
|
|
SELECT v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
|
|
d.departmentname, s.subcompanyname, j.jobtitlename,
|
|
ROW_NUMBER() OVER(ORDER BY v.id) as rn
|
|
FROM userInfo_view v
|
|
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
|
|
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
|
|
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
|
|
WHERE 1=1
|
|
"""
|
|
if keyword:
|
|
query_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
|
|
|
query_sql += """
|
|
) as T
|
|
WHERE rn > ? AND rn <= ?
|
|
"""
|
|
|
|
page_params = params + [offset, offset + page_size]
|
|
cursor.execute(query_sql, page_params)
|
|
|
|
items = []
|
|
for row in cursor.fetchall():
|
|
items.append({
|
|
"uid": str(row.id) if row.id is not None else "",
|
|
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
|
"name": cls._normalize_oa_text(row.lastname),
|
|
"jobtitle": cls._normalize_oa_text(row.jobtitle),
|
|
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
|
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
|
"departmentName": cls._normalize_oa_text(row.departmentname),
|
|
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
|
|
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
|
|
})
|
|
|
|
return {
|
|
"items": items,
|
|
"total": total,
|
|
"page": page,
|
|
"page_size": page_size
|
|
}
|
|
finally:
|
|
try:
|
|
cursor.close()
|
|
finally:
|
|
connection.close()
|
|
|
|
@classmethod
|
|
def get_employee_by_name_and_workcode(cls, real_name: str, employee_id: str):
|
|
connection = cls._connect()
|
|
cursor = connection.cursor()
|
|
try:
|
|
normalized_name = (real_name or "").strip()
|
|
normalized_employee_id = (employee_id or "").strip()
|
|
if not normalized_name or not normalized_employee_id:
|
|
raise RuntimeError("缺少姓名或工号,无法查询 OA 用户")
|
|
|
|
query_sql = """
|
|
SELECT TOP 1 v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
|
|
d.departmentname, s.subcompanyname, j.jobtitlename
|
|
FROM userInfo_view v
|
|
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
|
|
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
|
|
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
|
|
WHERE v.workcode = ? AND v.lastname = ?
|
|
ORDER BY v.id
|
|
"""
|
|
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
|
|
row = cursor.fetchone()
|
|
if not row:
|
|
return None
|
|
|
|
return {
|
|
"uid": str(row.id) if row.id is not None else "",
|
|
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
|
"name": cls._normalize_oa_text(row.lastname),
|
|
"jobtitle": cls._normalize_oa_text(row.jobtitle),
|
|
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
|
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
|
"departmentName": cls._normalize_oa_text(row.departmentname),
|
|
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
|
|
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
|
|
}
|
|
finally:
|
|
try:
|
|
cursor.close()
|
|
finally:
|
|
connection.close()
|
|
|
|
@classmethod
|
|
def get_department_name(cls, department_id: str) -> str:
|
|
if not department_id or not department_id.strip():
|
|
return ""
|
|
connection = cls._connect()
|
|
cursor = connection.cursor()
|
|
try:
|
|
cursor.execute(
|
|
"SELECT TOP 1 departmentname FROM HrmDepartment WHERE id = ?",
|
|
[department_id.strip()],
|
|
)
|
|
row = cursor.fetchone()
|
|
return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
|
|
finally:
|
|
try:
|
|
cursor.close()
|
|
finally:
|
|
connection.close()
|
|
|
|
@classmethod
|
|
def get_subcompany_name(cls, subcompany_id: str) -> str:
|
|
if not subcompany_id or not subcompany_id.strip():
|
|
return ""
|
|
connection = cls._connect()
|
|
cursor = connection.cursor()
|
|
try:
|
|
cursor.execute(
|
|
"SELECT TOP 1 subcompanyname FROM HrmSubCompany WHERE id = ?",
|
|
[subcompany_id.strip()],
|
|
)
|
|
row = cursor.fetchone()
|
|
return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
|
|
finally:
|
|
try:
|
|
cursor.close()
|
|
finally:
|
|
connection.close()
|
|
|
|
@classmethod
|
|
def get_jobtitle_name(cls, jobtitle_id: str) -> str:
|
|
if not jobtitle_id or not jobtitle_id.strip():
|
|
return ""
|
|
connection = cls._connect()
|
|
cursor = connection.cursor()
|
|
try:
|
|
cursor.execute(
|
|
"SELECT TOP 1 jobtitlename FROM HrmJobTitles WHERE id = ?",
|
|
[jobtitle_id.strip()],
|
|
)
|
|
row = cursor.fetchone()
|
|
return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
|
|
finally:
|
|
try:
|
|
cursor.close()
|
|
finally:
|
|
connection.close()
|