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

+113 -17
View File
@@ -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():