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():
|
||||
"""
|
||||
|
||||
Reference in new issue
Block a user