agent请假推申请单到OA

This commit is contained in:
runny committed 2026-05-15 17:16:54 +08:00
1 parent aeb6b66513
commit 367c20eb09
15 files changed
+1833 -143

No files matched your search

+342
View File
@@ -0,0 +1,342 @@
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
from app.services.oa_sqlserver import OASQLServerService
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 = '652'
OA_USER_MAP = {
'26030025': {'user_id': '21784', 'name': '梁春艳'},
'26040006': {'user_id': '21823', 'name': '刘义亮'},
}
# 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,
}
try:
response = requests.post(
cls._get_service_url(),
data=payload,
headers=headers,
timeout=cls._request_timeout(),
)
response.raise_for_status()
except requests.RequestException as exc:
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
try:
return ET.fromstring(response.text)
except ET.ParseError as exc:
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
@classmethod
def resolve_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
employee_id = (employee_id or '').strip()
if not employee_id:
raise OALeaveWorkflowError('缺少员工工号,无法匹配 OA 用户。')
matched = cls.OA_USER_MAP.get(employee_id)
if not matched:
raise OALeaveWorkflowError(f'工号 {employee_id} 暂未配置 OA userid 映射。')
return {
'employee_id': employee_id,
'user_id': matched['user_id'],
'name': (real_name or matched.get('name') or '').strip() or matched['name'],
}
@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:
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'],
}
@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)
@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]]:
creator_name = (
form_data.get('applicantName')
or getattr(current_user, 'real_name', None)
or getattr(current_user, 'username', None)
or '当前用户'
)
creator = cls.resolve_creator_oa_user(
form_data.get('employeeId') or getattr(current_user, 'employee_id', None),
creator_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, creator['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(creator['name'], start_dt)
cls._set_text(request_info, 'wf:creatorId', creator['user_id'])
cls._set_text(request_info, 'wf:creatorName', creator['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=creator['employee_id'])
cls._set_field(request_info, 'sqrgh', value=creator['employee_id'])
cls._set_field(request_info, 'tdrxm', value=creator['user_id'], show_value=creator['name'])
cls._set_field(request_info, 'sqrxm', value=creator['user_id'], show_value=creator['name'])
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'])
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)
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')))
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())
return request_info, creator, 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, creator, agent = cls.build_request_info(form_data, current_user)
action = 'urn:weaver.workflow.webservices.WorkflowService.doCreateWorkflowRequest'
root = cls._post_soap(action, cls._build_create_body(request_info, creator['user_id']))
request_id = cls._parse_create_response(root)
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': creator,
'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),
}
+132
View File
@@ -0,0 +1,132 @@
import os
import pyodbc
from flask import current_app
class OASQLServerService:
@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()
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};"
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
FROM (
SELECT id, workcode, lastname, ROW_NUMBER() OVER(ORDER BY id) as rn
FROM userInfo_view
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),
"employeeId": str(row.workcode),
"name": str(row.lastname)
})
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 id, workcode, lastname
FROM userInfo_view
WHERE workcode = ? AND lastname = ?
ORDER BY id
"""
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
row = cursor.fetchone()
if not row:
return None
return {
"uid": str(row.id),
"employeeId": str(row.workcode),
"name": str(row.lastname),
}
finally:
try:
cursor.close()
finally:
connection.close()