refactor(backend): dify, minio等迁移到integration,清除无效文件

This commit is contained in:
sophie committed 2026-09-21 09:24:45 +08:00
1 parent 7fe7a39384
commit faa554ade4
90 files changed
+7540 -9649

No files matched your search

@@ -1,2 +1,446 @@
"""OA 请假 Workflow SOAP 适配(Wave 4 自 oa_leave_workflow.py 迁入)。"""
from app.services import oa_leave_workflow # noqa: F401
"""
backend/app/services/integrations/oa/leave_workflow.py
用途:OA 请假流程 SOAP 适配(创建/查询请假单)。
依赖:requests、SOAP XML、OA WorkflowService、integrations.oa.sqlserver。
逻辑:由 HR 请假聊天意图或相关服务调用;组装 WorkflowRequestInfo 并提交 OA。
"""
from __future__ import annotations
from copy import deepcopy
from datetime import datetime
from typing import Any
import os
import xml.etree.ElementTree as ET
import requests
from flask import current_app
SOAP_ENV_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
SERVICE_NS = 'webservices.services.weaver.com.cn'
WORKFLOW_NS = 'http://webservices.workflow.weaver'
XSI_NS = 'http://www.w3.org/2001/XMLSchema-instance'
NS = {
'soapenv': SOAP_ENV_NS,
'svc': SERVICE_NS,
'wf': WORKFLOW_NS,
'xsi': XSI_NS,
}
ET.register_namespace('soapenv', SOAP_ENV_NS)
ET.register_namespace('svc', SERVICE_NS)
ET.register_namespace('wf', WORKFLOW_NS)
ET.register_namespace('xsi', XSI_NS)
class OALeaveWorkflowError(RuntimeError):
"""Raised when OA leave workflow submission fails."""
class OALeaveWorkflowService:
WORKFLOW_ID = '879'
# Keep backend leave labels aligned with the chat form options so OA browser
# fields always receive the expected showValue instead of a raw code.
LEAVE_TYPE_LABELS = {
'005': '事假(小时)',
'006': '病假(小时)',
'007': '丧假(天)',
'010': '年假(天)',
'021': '因公出差(小时)',
'025': '调休假(小时)',
'035': '其他假(小时)',
'401': '产假(天)',
'402': '陪产假(天)',
'403': '婚假(天)',
'405': '住院病假(小时)',
'406': '工伤假(天)',
'408': '育儿假(小时)',
'ZZ01': '返乡假(小时)',
'ZZ04': '事假(经理专用小时)',
'ZZ05': '病假(经理专用小时)',
'ZZ07': '丧假(经理专用天)',
'ZZ08': '产假(经理专用天)',
'ZZ09': '陪产假(经理专用天)',
'ZZ10': '婚假(经理专用天)',
}
ERROR_MESSAGES = {
'-1': '创建流程失败',
'-2': '用户没有流程创建权限',
'-3': '创建流程基本信息失败',
'-4': '保存表单主表信息失败',
'-5': '更新紧急程度失败',
'-6': '流程操作者失败',
'-7': '流转至下一节点失败',
'-8': '节点附加操作失败',
}
@classmethod
def _get_wsdl_url(cls) -> str:
return (
current_app.config.get('OA_WORKFLOW_WSDL_URL')
or os.getenv('OA_WORKFLOW_WSDL_URL')
or 'http://oa.well-trust.com:8888/services/WorkflowService?wsdl'
).strip()
@classmethod
def _get_service_url(cls) -> str:
wsdl_url = cls._get_wsdl_url()
return wsdl_url[:-5] if wsdl_url.lower().endswith('?wsdl') else wsdl_url
@classmethod
def _request_timeout(cls) -> tuple[int, int]:
return (5, 25)
@classmethod
def _post_soap(cls, action: str, body_el: ET.Element) -> ET.Element:
envelope = ET.Element(f'{{{SOAP_ENV_NS}}}Envelope')
ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Header')
body = ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Body')
body.append(body_el)
payload = ET.tostring(envelope, encoding='utf-8', xml_declaration=True)
headers = {
'Content-Type': 'text/xml; charset=utf-8',
'SOAPAction': action,
}
max_retries = 3
last_exc = None
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
cls._get_service_url(),
data=payload,
headers=headers,
timeout=cls._request_timeout(),
)
response.raise_for_status()
return ET.fromstring(response.text)
except requests.RequestException as exc:
last_exc = exc
status_code = getattr(getattr(exc, 'response', None), 'status_code', None)
retryable = status_code in (502, 503, 504) if status_code else True
if retryable and attempt < max_retries:
import time
wait = attempt * 2
current_app.logger.warning(
'[oa-leave] SOAP request failed (attempt %d/%d, status=%s), retrying in %ds: %s',
attempt, max_retries, status_code, wait, exc,
)
time.sleep(wait)
continue
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
except ET.ParseError as exc:
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
@classmethod
def resolve_creator_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='请假人')
@classmethod
def resolve_agent_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='代理人')
@classmethod
def _resolve_runtime_oa_user(
cls,
employee_id: str | None,
real_name: str | None = None,
*,
role_label: str,
) -> dict[str, str]:
employee_id = (employee_id or '').strip()
real_name = (real_name or '').strip()
if not employee_id:
raise OALeaveWorkflowError(f'缺少{role_label}工号,无法匹配 OA 用户。')
if not real_name:
raise OALeaveWorkflowError(f'缺少{role_label}姓名,无法匹配 OA 用户。')
try:
from app.services.oa_sqlserver import OASQLServerService
matched = OASQLServerService.get_employee_by_name_and_workcode(real_name, employee_id)
except Exception as exc:
raise OALeaveWorkflowError(f'查询{role_label} OA 用户失败:{exc}') from exc
if not matched:
raise OALeaveWorkflowError(f'未找到{role_label} OA 用户:{real_name}({employee_id})。')
return {
'employee_id': matched['employeeId'],
'user_id': matched['uid'],
'name': matched['name'],
'jobtitle': matched.get('jobtitle', ''),
'jobtitleName': matched.get('jobtitleName', ''),
'departmentid': matched.get('departmentid', ''),
'departmentName': matched.get('departmentName', ''),
'subcompanyid1': matched.get('subcompanyid1', ''),
'subcompanyName': matched.get('subcompanyName', ''),
}
@staticmethod
def _pick_browser_field_value(*values: Any) -> str:
for value in values:
text = ('' if value is None else str(value)).strip()
if text:
return text
return ''
@classmethod
def _build_get_template_body(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
root = ET.Element(f'{{{SERVICE_NS}}}getCreateWorkflowRequestInfo')
ET.SubElement(root, f'{{{SERVICE_NS}}}in0').text = str(workflow_id)
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
return root
@classmethod
def _get_template_request_info(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
action = 'urn:weaver.workflow.webservices.WorkflowService.getCreateWorkflowRequestInfo'
root = cls._post_soap(action, cls._build_get_template_body(workflow_id, oa_user_id))
out = root.find('.//svc:out', NS)
if out is None or out.attrib.get(f'{{{XSI_NS}}}nil') == 'true' or len(list(out)) == 0:
raise OALeaveWorkflowError('OA 未返回建单模板,请确认 workflowId 与 OA userid 是否正确。')
return deepcopy(out)
@classmethod
def _find_field(cls, request_info: ET.Element, field_name: str) -> ET.Element | None:
for field in request_info.findall('.//wf:WorkflowRequestTableField', NS):
if (field.findtext('wf:fieldName', default='', namespaces=NS) or '').strip() == field_name:
return field
return None
@classmethod
def _set_field(
cls,
request_info: ET.Element,
field_name: str,
*,
value: str | None,
show_value: str | None = None,
) -> None:
field = cls._find_field(request_info, field_name)
if field is None:
current_app.logger.warning('[oa-leave] field not found in template: %s', field_name)
return
value_node = field.find('wf:fieldValue', NS)
if value_node is None:
value_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldValue')
value_node.text = '' if value is None else str(value)
if show_value is not None:
show_node = field.find('wf:fieldShowValue', NS)
if show_node is None:
show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue')
show_node.text = str(show_value)
field_html_type = (field.findtext('wf:fieldHtmlType', default='', namespaces=NS) or '').strip()
if field_html_type == '3':
filed_html_node = field.find('wf:filedHtmlShow', NS)
if filed_html_node is not None:
filed_html_node.text = str(show_value)
for tag in ['edit', 'view']:
node = field.find(f'wf:{tag}', NS)
if node is not None:
node.text = 'true'
else:
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
node.text = 'true'
@classmethod
def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None:
node = parent.find(xpath, NS)
if node is not None:
node.text = value
@classmethod
def _parse_frontend_datetime(cls, raw: str, field_name: str) -> datetime:
text = (raw or '').strip().replace('T', ' ')
try:
return datetime.strptime(text, '%Y-%m-%d %H:%M')
except ValueError as exc:
raise OALeaveWorkflowError(f'{field_name} 格式不正确,应为 YYYY-MM-DD HH:MM。') from exc
@classmethod
def _build_request_name(cls, creator_name: str, start_dt: datetime) -> str:
return f'请假申请单-{creator_name}-{start_dt.strftime("%Y-%m-%d")}'
@classmethod
def _normalize_duration(cls, value: Any) -> str:
try:
hours = float(value)
except (TypeError, ValueError) as exc:
raise OALeaveWorkflowError('请假时长格式不正确。') from exc
if hours <= 0:
raise OALeaveWorkflowError('请假时长必须大于 0。')
return f'{hours:.2f}'.rstrip('0').rstrip('.')
@classmethod
def build_request_info(cls, form_data: dict[str, Any], current_user: Any) -> tuple[ET.Element, dict[str, str], dict[str, str], dict[str, str]]:
filler_name = (
form_data.get('fillerName')
or getattr(current_user, 'real_name', None)
or getattr(current_user, 'username', None)
or '当前用户'
)
filler = cls._resolve_runtime_oa_user(
getattr(current_user, 'employee_id', None),
filler_name,
role_label='填单人'
)
applicant_name = (
form_data.get('applicantName')
or getattr(current_user, 'real_name', None)
or getattr(current_user, 'username', None)
or '当前用户'
)
applicant = cls.resolve_creator_oa_user(
form_data.get('employeeId') or getattr(current_user, 'employee_id', None),
applicant_name,
)
agent = cls.resolve_agent_oa_user(form_data.get('agentEmployeeId'), form_data.get('agentName'))
workflow_id = str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID)
request_info = cls._get_template_request_info(workflow_id, filler['user_id'])
start_dt = cls._parse_frontend_datetime(form_data.get('startTime'), '开始时间')
end_dt = cls._parse_frontend_datetime(form_data.get('endTime'), '结束时间')
if end_dt <= start_dt:
raise OALeaveWorkflowError('结束时间必须晚于开始时间。')
leave_type_code = (form_data.get('leaveType') or '').strip()
if not leave_type_code:
raise OALeaveWorkflowError('缺少假别编码。')
leave_type_label = cls.LEAVE_TYPE_LABELS.get(leave_type_code, leave_type_code)
request_name = cls._build_request_name(applicant['name'], start_dt)
cls._set_text(request_info, 'wf:creatorId', filler['user_id'])
cls._set_text(request_info, 'wf:creatorName', filler['name'])
cls._set_text(request_info, 'wf:requestLevel', '0')
cls._set_text(request_info, 'wf:requestName', request_name)
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'])
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'])
filler_jobtitle = cls._pick_browser_field_value(filler.get('jobtitle'), form_data.get('fillerJobTitle'))
filler_jobtitle_name = cls._pick_browser_field_value(filler.get('jobtitleName'))
filler_department = cls._pick_browser_field_value(filler.get('departmentid'), form_data.get('fillerDepartmentId'))
filler_department_name = cls._pick_browser_field_value(filler.get('departmentName'))
filler_subcompany = cls._pick_browser_field_value(filler.get('subcompanyid1'), form_data.get('fillerSubCompanyId1'))
filler_subcompany_name = cls._pick_browser_field_value(filler.get('subcompanyName'))
applicant_jobtitle = cls._pick_browser_field_value(applicant.get('jobtitle'), form_data.get('applicantJobTitle'))
applicant_jobtitle_name = cls._pick_browser_field_value(applicant.get('jobtitleName'))
applicant_department = cls._pick_browser_field_value(applicant.get('departmentid'), form_data.get('applicantDepartmentId'))
applicant_department_name = cls._pick_browser_field_value(applicant.get('departmentName'))
applicant_subcompany = cls._pick_browser_field_value(applicant.get('subcompanyid1'), form_data.get('applicantSubCompanyId1'))
applicant_subcompany_name = cls._pick_browser_field_value(applicant.get('subcompanyName'))
try:
from app.services.oa_sqlserver import OASQLServerService
if filler_jobtitle and not filler_jobtitle_name:
filler_jobtitle_name = OASQLServerService.get_jobtitle_name(filler_jobtitle)
if filler_department and not filler_department_name:
filler_department_name = OASQLServerService.get_department_name(filler_department)
if filler_subcompany and not filler_subcompany_name:
filler_subcompany_name = OASQLServerService.get_subcompany_name(filler_subcompany)
if applicant_jobtitle and not applicant_jobtitle_name:
applicant_jobtitle_name = OASQLServerService.get_jobtitle_name(applicant_jobtitle)
if applicant_department and not applicant_department_name:
applicant_department_name = OASQLServerService.get_department_name(applicant_department)
if applicant_subcompany and not applicant_subcompany_name:
applicant_subcompany_name = OASQLServerService.get_subcompany_name(applicant_subcompany)
except Exception:
pass
cls._set_field(request_info, 'tdrzw', value=filler_jobtitle, show_value=filler_jobtitle_name or filler_jobtitle or '暂无')
cls._set_field(request_info, 'tdrbm', value=filler_department, show_value=filler_department_name or filler_department or '暂无')
cls._set_field(request_info, 'tdrgs', value=filler_subcompany, show_value=filler_subcompany_name or filler_subcompany or '暂无')
cls._set_field(request_info, 'sqrzw', value=applicant_jobtitle, show_value=applicant_jobtitle_name or applicant_jobtitle or '暂无')
cls._set_field(request_info, 'sqrbm', value=applicant_department, show_value=applicant_department_name or applicant_department or '暂无')
cls._set_field(request_info, 'sqrgs', value=applicant_subcompany, show_value=applicant_subcompany_name or applicant_subcompany or '暂无')
current_app.logger.info(
'[oa-leave] field values: tdrzw=%s/%s tdrbm=%s/%s tdrgs=%s/%s sqrzw=%s/%s sqrbm=%s/%s sqrgs=%s/%s',
filler_jobtitle, filler_jobtitle_name or filler_jobtitle or '暂无',
filler_department, filler_department_name or filler_department or '暂无',
filler_subcompany, filler_subcompany_name or filler_subcompany or '暂无',
applicant_jobtitle, applicant_jobtitle_name or applicant_jobtitle or '暂无',
applicant_department, applicant_department_name or applicant_department or '暂无',
applicant_subcompany, applicant_subcompany_name or applicant_subcompany or '暂无',
)
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)
cls._set_field(request_info, 'jbbh', value=leave_type_code, show_value=leave_type_code)
cls._set_field(request_info, 'kssj', value=start_dt.strftime('%Y-%m-%d'), show_value=start_dt.strftime('%Y-%m-%d'))
cls._set_field(request_info, 'kssk', value=start_dt.strftime('%H:%M'), show_value=start_dt.strftime('%H:%M'))
cls._set_field(request_info, 'jssj', value=end_dt.strftime('%Y-%m-%d'), show_value=end_dt.strftime('%Y-%m-%d'))
cls._set_field(request_info, 'jssk', value=end_dt.strftime('%H:%M'), show_value=end_dt.strftime('%H:%M'))
cls._set_field(request_info, 'qjsc', value=cls._normalize_duration(form_data.get('durationHours')), show_value=cls._normalize_duration(form_data.get('durationHours')))
cls._set_field(request_info, 'sfwgs', value=str(form_data.get('isWorkInjury')), show_value='是' if str(form_data.get('isWorkInjury')) == '0' else '否')
cls._set_field(request_info, 'sfwc', value=str(form_data.get('isOutOfOffice')), show_value='是' if str(form_data.get('isOutOfOffice')) == '0' else '否')
cls._set_field(request_info, 'bz', value=(form_data.get('remark') or '').strip(), show_value=(form_data.get('remark') or '').strip())
return request_info, filler, applicant, agent
@classmethod
def _build_create_body(cls, request_info: ET.Element, oa_user_id: str) -> ET.Element:
root = ET.Element(f'{{{SERVICE_NS}}}doCreateWorkflowRequest')
in0 = deepcopy(request_info)
in0.tag = f'{{{SERVICE_NS}}}in0'
root.append(in0)
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
return root
@classmethod
def _parse_create_response(cls, root: ET.Element) -> str:
out = root.findtext('.//svc:out', default='', namespaces=NS)
out = (out or '').strip()
if not out:
raise OALeaveWorkflowError('OA 未返回单据编号。')
if out in cls.ERROR_MESSAGES:
raise OALeaveWorkflowError(cls.ERROR_MESSAGES[out])
if out.startswith('-'):
raise OALeaveWorkflowError(f'OA 创建流程失败,返回码:{out}')
return out
@classmethod
def serialize_request_xml(cls, request_info: ET.Element) -> str:
return ET.tostring(request_info, encoding='unicode')
@classmethod
def submit_leave_request(cls, form_data: dict[str, Any], current_user: Any) -> dict[str, Any]:
request_info, filler, applicant, agent = cls.build_request_info(form_data, current_user)
log_fields = ['tdrzw', 'tdrbm', 'tdrgs', 'sqrzw', 'sqrbm', 'sqrgs', 'qjsc', 'tdrgh', 'sqrgh']
for fn in log_fields:
f = cls._find_field(request_info, fn)
if f is not None:
fv = f.findtext('wf:fieldValue', default='', namespaces=NS)
fsv = f.findtext('wf:fieldShowValue', default='', namespaces=NS)
fe = f.findtext('wf:edit', default='(removed)', namespaces=NS)
current_app.logger.info('[oa-leave] PUSH field %s: value=%s showValue=%s edit=%s', fn, fv, fsv, fe)
action = 'urn:weaver.workflow.webservices.WorkflowService.doCreateWorkflowRequest'
root = cls._post_soap(action, cls._build_create_body(request_info, filler['user_id']))
request_id = cls._parse_create_response(root)
current_app.logger.info('[oa-leave] OA response request_id=%s', request_id)
return {
'ok': True,
'request_id': request_id,
'request_name': request_info.findtext('wf:requestName', default='', namespaces=NS),
'submitted_at': datetime.now().strftime('%Y-%m-%d %H:%M'),
'creator': applicant,
'filler': filler,
'agent': agent,
'workflow_id': str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID),
'request_xml': cls.serialize_request_xml(request_info),
}
@@ -1,2 +1,258 @@
"""OA SQL Server 适配(Wave 4 自 oa_sqlserver.py 迁入)。"""
from app.services import oa_sqlserver # noqa: F401
"""
backend/app/services/integrations/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()
@@ -1,2 +1,473 @@
"""OA 与企微同步适配(Wave 4 自 oa_wecom_sync.py 迁入)。"""
from app.services import oa_wecom_sync # noqa: F401
"""
backend/app/services/integrations/oa/wecom_sync.py
用途:从 OA SQL Server userInfo_view 按本地工号回填 users.wecom_userid。
依赖:OASQLServerService、SQLAlchemy db、User 模型。
逻辑:先查本地有 employee_id 的用户,再按工号 IN 查询 OA;供 admin 绑定管理预览/写入。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import User
from app.services.integrations.oa.sqlserver import OASQLServerService
_PREVIEW_LIMIT = 20
_OA_VIEW = 'userInfo_view'
_OA_IN_BATCH_SIZE = 500
def _clean_str(value) -> str | None:
"""
规范化字符串;空值返回 None。
@param value: 任意输入
Returns:
去首尾空白后的字符串,或 None
"""
if value is None:
return None
text = str(value).strip()
return text or None
def _load_local_users_with_employee_id() -> list[tuple[User, str]]:
"""
加载本地含有效工号的用户列表。
核心逻辑:查询 employee_id 非空记录,trim 后过滤空串。
Returns:
(User, employee_id) 元组列表
"""
rows: list[tuple[User, str]] = []
for user in db.session.query(User).filter(User.employee_id.isnot(None)).all():
employee_id = _clean_str(user.employee_id)
if not employee_id:
continue
rows.append((user, employee_id))
return rows
def fetch_oa_wecom_bindings_for_workcodes(workcodes: list[str]) -> list[dict[str, str | None]]:
"""
按工号批量查询 OA userInfo_view 中的企微 userid 映射。
核心逻辑:工号去重后分批 IN 查询,避免全表扫描。
@param workcodes: 本地 users.employee_id 列表
Returns:
每项含 workcode、wecom_userid、name
Raises:
RuntimeError: ODBC 连接或查询失败
"""
unique_codes: list[str] = []
seen: set[str] = set()
for code in workcodes:
cleaned = _clean_str(code)
if not cleaned or cleaned in seen:
continue
seen.add(cleaned)
unique_codes.append(cleaned)
if not unique_codes:
return []
connection = OASQLServerService._connect()
cursor = connection.cursor()
rows: list[dict[str, str | None]] = []
try:
for offset in range(0, len(unique_codes), _OA_IN_BATCH_SIZE):
batch = unique_codes[offset : offset + _OA_IN_BATCH_SIZE]
placeholders = ','.join('?' for _ in batch)
cursor.execute(
f"""
SELECT id, workcode, lastname
FROM userInfo_view
WHERE workcode IN ({placeholders})
AND id IS NOT NULL
""",
batch,
)
for row in cursor.fetchall():
workcode = _clean_str(row.workcode)
wecom_userid = _clean_str(row.id)
if not workcode or not wecom_userid:
continue
rows.append(
{
'workcode': workcode,
'wecom_userid': wecom_userid,
'name': _clean_str(row.lastname),
}
)
return rows
finally:
try:
cursor.close()
finally:
connection.close()
def sync_wecom_userids_from_oa(*, apply: bool) -> dict[str, Any]:
"""
执行 OA 工号 → wecom_userid 同步(本地用户驱动)。
核心逻辑:读本地工号 → 按 IN 查 OA → 匹配并 dry-run 或写入 wecom_userid。
@param apply: True 时提交数据库;存在 conflicts 时不写入
Returns:
统计摘要 dict(结构与企微通讯录同步兼容,便于前端复用)
Raises:
RuntimeError: OA 未配置、连接失败或 apply 时存在冲突
"""
local_users = _load_local_users_with_employee_id()
workcodes = [employee_id for _, employee_id in local_users]
oa_rows = fetch_oa_wecom_bindings_for_workcodes(workcodes)
summary: dict[str, Any] = {
'apply': apply,
'employee_id_source': f'oa:{_OA_VIEW}.workcode',
'department_ids': [],
'local_candidates': len(local_users),
'wecom_users': 0,
'wecom_without_employee_id': 0,
'local_matched': 0,
'would_update': 0,
'updated': 0,
'already_bound': 0,
'local_missing': 0,
'conflicts': [],
'missing_samples': [],
'pending_updates': [],
}
oa_by_workcode: dict[str, dict[str, str | None]] = {}
duplicate_workcodes: set[str] = set()
for row in oa_rows:
workcode = row['workcode']
if not workcode:
continue
if workcode in oa_by_workcode:
duplicate_workcodes.add(workcode)
summary['conflicts'].append(
{
'employee_id': workcode,
'username': '',
'new_wecom_userid': row['wecom_userid'],
'reason': 'duplicate_workcode_in_oa',
}
)
continue
oa_by_workcode[workcode] = row
summary['wecom_users'] = len(oa_by_workcode)
for local_user, employee_id in local_users:
if employee_id in duplicate_workcodes:
continue
oa_row = oa_by_workcode.get(employee_id)
if not oa_row:
summary['local_missing'] += 1
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
summary['missing_samples'].append(
{
'employee_id': employee_id,
'username': local_user.username,
}
)
continue
wecom_userid = oa_row['wecom_userid']
name = oa_row.get('name')
if not wecom_userid:
summary['wecom_without_employee_id'] += 1
continue
summary['local_matched'] += 1
if local_user.wecom_userid == wecom_userid:
summary['already_bound'] += 1
continue
conflict = None
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'old_wecom_userid': local_user.wecom_userid,
'new_wecom_userid': wecom_userid,
}
else:
occupied = (
db.session.query(User)
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
.first()
)
if occupied:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'new_wecom_userid': wecom_userid,
'occupied_by_user_id': occupied.id,
'occupied_by_username': occupied.username,
}
if conflict:
summary['conflicts'].append(conflict)
continue
summary['would_update'] += 1
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
summary['pending_updates'].append(
{
'employee_id': employee_id,
'username': local_user.username,
'wecom_userid': wecom_userid,
'name': name,
}
)
if apply:
local_user.wecom_userid = wecom_userid
summary['updated'] += 1
if summary['conflicts'] and apply:
db.session.rollback()
raise RuntimeError('Conflicts detected; resolve manually before apply')
if apply and summary['updated'] > 0:
db.session.commit()
elif apply:
db.session.rollback()
return summary