agent请假推申请单到OA
This commit is contained in:
1 parent
aeb6b66513
commit
367c20eb09
15 files changed
+1833
-143
No files matched your search
+113
-17
@@ -18,6 +18,7 @@ from sqlalchemy import func, desc
|
||||
from openpyxl import load_workbook
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
from app.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, Feedback
|
||||
from app import db
|
||||
@@ -332,6 +333,28 @@ def _load_excel_workbook(content: bytes, ext: str):
|
||||
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
|
||||
|
||||
|
||||
@chat_bp.route('/oa/employees', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_oa_employees():
|
||||
"""
|
||||
获取 OA 系统中的员工列表(分页/搜索)
|
||||
"""
|
||||
keyword = request.args.get('keyword', '').strip()
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
page_size = int(request.args.get('page_size', 20))
|
||||
except ValueError:
|
||||
page = 1
|
||||
page_size = 20
|
||||
|
||||
try:
|
||||
result = OASQLServerService.search_employees(keyword, page, page_size)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"[OA-Employees] Query failed: {e}")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_sessions():
|
||||
@@ -344,13 +367,8 @@ def get_chat_sessions():
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
# 聚合查询:按 conversation_id 分组,获取最新时间
|
||||
# 注意:这里简化处理,直接取最新一条记录的 query 作为标题(或者第一条,取决于需求)
|
||||
# 为了性能,这里我们取 max(created_at) 和 max(query) - 这只是一个近似值
|
||||
# 更严谨的做法是先查出 conversation_ids,再查详情。
|
||||
# 这里为了简单,我们假设 query 不为空
|
||||
|
||||
# 修正逻辑:先查出最近的 20 个 conversation_id
|
||||
# 先查出最近活跃的会话,再为每个会话回溯最近一条非空 query 作为标题。
|
||||
# 这样本地表单/确认等“无 query 的助手消息”不会把原始用户问题覆盖成 New Chat。
|
||||
subquery = db.session.query(
|
||||
ChatLog.conversation_id,
|
||||
func.max(ChatLog.created_at).label('last_active')
|
||||
@@ -359,25 +377,27 @@ def get_chat_sessions():
|
||||
agent_id=agent.id
|
||||
).group_by(ChatLog.conversation_id).subquery()
|
||||
|
||||
# 联表查询获取详细信息,按时间倒序
|
||||
results = db.session.query(
|
||||
subquery.c.conversation_id,
|
||||
subquery.c.last_active,
|
||||
ChatLog.query
|
||||
).join(
|
||||
ChatLog,
|
||||
(ChatLog.conversation_id == subquery.c.conversation_id) &
|
||||
(ChatLog.created_at == subquery.c.last_active)
|
||||
).order_by(desc(subquery.c.last_active)).limit(20).all()
|
||||
|
||||
sessions = []
|
||||
for row in results:
|
||||
if not row.conversation_id:
|
||||
continue
|
||||
latest_query_row = db.session.query(ChatLog.query).filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
ChatLog.conversation_id == row.conversation_id,
|
||||
ChatLog.query.isnot(None),
|
||||
ChatLog.query != '',
|
||||
).order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first()
|
||||
title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip()
|
||||
sessions.append({
|
||||
'id': 0, # 前端需要 id key
|
||||
'conversation_id': row.conversation_id,
|
||||
'title': row.query[:30] + ('...' if len(row.query) > 30 else '') if row.query else 'New Chat',
|
||||
'title': title[:30] + ('...' if len(title) > 30 else '') if title else '',
|
||||
'created_at': row.last_active.isoformat()
|
||||
})
|
||||
|
||||
@@ -453,18 +473,94 @@ def get_chat_messages():
|
||||
|
||||
messages = []
|
||||
for log in logs:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
messages.append({
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or []
|
||||
})
|
||||
}
|
||||
if log.message_type:
|
||||
assistant_msg['type'] = log.message_type
|
||||
if log.payload:
|
||||
assistant_msg['payload'] = log.payload
|
||||
|
||||
messages.append(assistant_msg)
|
||||
|
||||
return jsonify(messages)
|
||||
|
||||
|
||||
@chat_bp.route('/messages/local', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def save_local_message():
|
||||
"""
|
||||
保存前端本地生成的聊天记录(如表单、确认弹窗、提交结果等)
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
data = request.get_json() or {}
|
||||
conversation_id = data.get('conversation_id')
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
|
||||
if not conversation_id:
|
||||
import uuid
|
||||
conversation_id = str(uuid.uuid4())
|
||||
|
||||
if not message_type:
|
||||
return jsonify({'error': 'type is required'}), 400
|
||||
|
||||
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
|
||||
# 这样能保证前端表单状态(例如已确认)被持久化
|
||||
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
|
||||
|
||||
chat_log = None
|
||||
if local_id:
|
||||
# 在 payload 中查找是否已存在相同 formId 的同类型消息
|
||||
# SQLite / Postgres 对 JSON 过滤有差异,为了简单,我们可以取出当前会话的所有该类型消息并在内存中匹配
|
||||
logs = db.session.query(ChatLog).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=conversation_id,
|
||||
message_type=message_type
|
||||
).order_by(ChatLog.created_at.desc()).limit(20).all()
|
||||
|
||||
for log in logs:
|
||||
if log.payload and isinstance(log.payload, dict) and log.payload.get('formId') == local_id:
|
||||
chat_log = log
|
||||
break
|
||||
|
||||
if chat_log:
|
||||
chat_log.content = content
|
||||
chat_log.answer = content
|
||||
chat_log.payload = payload
|
||||
if user_query and not chat_log.query:
|
||||
chat_log.query = user_query
|
||||
else:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=conversation_id,
|
||||
query=user_query,
|
||||
answer=content,
|
||||
message_type=message_type,
|
||||
payload=payload
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
||||
|
||||
|
||||
@chat_bp.route('/completions', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_completions():
|
||||
|
||||
@@ -3,6 +3,7 @@ from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
@@ -521,6 +522,15 @@ def _clean_str(value):
|
||||
return str(value).strip() or None
|
||||
|
||||
|
||||
def _parse_leave_int_flag(value, field_label: str):
|
||||
if value in (0, 1):
|
||||
return int(value)
|
||||
text = _clean_str(value)
|
||||
if text in ('0', '1'):
|
||||
return int(text)
|
||||
raise OALeaveWorkflowError(f'{field_label} 取值无效,应为 0 或 1。')
|
||||
|
||||
|
||||
def _normalize_mobile(mobile: str):
|
||||
mobile = _clean_str(mobile)
|
||||
if not mobile:
|
||||
@@ -1557,6 +1567,64 @@ def wecom_task_complete():
|
||||
return jsonify(result), 200 if result.get('ok') else 202
|
||||
|
||||
|
||||
@user_bp.route('/leave-workflow/submit', methods=['POST'])
|
||||
def submit_leave_workflow():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
form_data = {
|
||||
'applicantName': _clean_str(data.get('applicantName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)),
|
||||
'employeeId': _clean_str(data.get('employeeId')) or _clean_str(getattr(user, 'employee_id', None)) or _clean_str(getattr(user, 'username', None)),
|
||||
'applyTime': _clean_str(data.get('applyTime')),
|
||||
'fillerName': _clean_str(data.get('fillerName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)),
|
||||
'agentUid': _clean_str(data.get('agentUid')),
|
||||
'agentEmployeeId': _clean_str(data.get('agentEmployeeId')),
|
||||
'agentName': _clean_str(data.get('agentName')),
|
||||
'leaveType': _clean_str(data.get('leaveType')),
|
||||
'startTime': _clean_str(data.get('startTime')),
|
||||
'endTime': _clean_str(data.get('endTime')),
|
||||
'durationHours': data.get('durationHours'),
|
||||
'isOutOfOffice': _parse_leave_int_flag(data.get('isOutOfOffice'), '是否外出'),
|
||||
'isWorkInjury': _parse_leave_int_flag(data.get('isWorkInjury'), '是否为工伤'),
|
||||
'remark': _clean_str(data.get('remark')) or '',
|
||||
}
|
||||
|
||||
required_fields = {
|
||||
'applicantName': '申请人',
|
||||
'employeeId': '工号',
|
||||
'fillerName': '填单人',
|
||||
'agentUid': '代理人UID',
|
||||
'agentEmployeeId': '代理人工号',
|
||||
'agentName': '代理人姓名',
|
||||
'leaveType': '假别',
|
||||
'startTime': '开始时间',
|
||||
'endTime': '结束时间',
|
||||
}
|
||||
for key, label in required_fields.items():
|
||||
if not form_data.get(key):
|
||||
return jsonify({'error': f'{label}不能为空。'}), 400
|
||||
|
||||
try:
|
||||
result = OALeaveWorkflowService.submit_leave_request(form_data, user)
|
||||
except OALeaveWorkflowError as exc:
|
||||
current_app.logger.warning('[oa-leave] submit failed user_id=%s employee_id=%s err=%s', getattr(user, 'id', None), form_data.get('employeeId'), exc)
|
||||
return jsonify({'error': str(exc)}), 400
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[oa-leave] unexpected submit failure user_id=%s', getattr(user, 'id', None))
|
||||
return jsonify({'error': f'OA 请假提交失败:{exc}'}), 500
|
||||
|
||||
current_app.logger.info(
|
||||
'[oa-leave] submit success user_id=%s employee_id=%s request_id=%s workflow_id=%s',
|
||||
getattr(user, 'id', None),
|
||||
form_data.get('employeeId'),
|
||||
result.get('request_id'),
|
||||
result.get('workflow_id'),
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@user_bp.route('/wecom/callback', methods=['GET', 'POST'])
|
||||
def wecom_callback():
|
||||
"""
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
backend/app/config.py
|
||||
配置类,区分开发/生产环境
|
||||
"""
|
||||
@@ -38,6 +38,11 @@ class Config:
|
||||
)
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE', 'http://127.0.0.1:5001/v1')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||
'OA_WORKFLOW_WSDL_URL',
|
||||
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '652')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
|
||||
@@ -192,6 +192,8 @@ class ChatLog(Base):
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
latency: Mapped[int] = mapped_column(default=0)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||
# Persist citation/source metadata so history messages can still show sources.
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user