""" backend/app/api/user/handlers.py 用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。 依赖:sqlalchemy(and_/or_、exc)、app.core.errors、models、wecom/dify 相关 services。 逻辑:薄路由层鉴权与参数校验;Casdoor/企微 OAuth 委托 services/auth/*。 """ from flask import Blueprint, request, jsonify, current_app from sqlalchemy import and_, or_ from sqlalchemy.exc import DatabaseError, OperationalError from app import db from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, ChatLog from app.services.feedback_notify import send_feedback_group_notification from app.services.agent_category import serialize_agent_list_item, sort_agent_rows from app.services.agent_registry.serialization import serialize_registry_fields from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message import re import ast from app.core.errors import ( AppError, ForbiddenError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError, ) from .auth import ( _clean_str, _get_current_user, _parse_leave_int_flag, _run_db_with_retry, ) user_bp = Blueprint('user', __name__) @user_bp.route('/wecom/deeplink-opened', methods=['POST']) def mark_wecom_deeplink_opened(): user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') data = request.get_json() or {} trace_id = _clean_str(data.get('trace_id')) if not trace_id: raise ValidationError('trace_id is required') ok = mark_wecom_message_opened(trace_id) if not ok: raise NotFoundError('trace_id not found') db.session.commit() return jsonify({'status': 'ok'}) @user_bp.route('/wecom/task-complete', methods=['POST']) def wecom_task_complete(): """ Lightweight endpoint for sending task completion WeCom message. Can be called by frontend after long-running task is done. """ user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') data = request.get_json() or {} title = _clean_str(data.get('title')) or 'AI 任务已完成' content = _clean_str(data.get('content')) or '你发起的 AI 任务已完成,点击查看详情。' agent_id = data.get('agent_id') jump_path = '/workspace' jump_params = {} if agent_id: jump_path = f'/chat/{int(agent_id)}' result = send_wecom_event_message(event_type='task_completed', user=user, title=title, content=content, jump_path=jump_path, jump_params=jump_params) db.session.commit() return (jsonify(result), 200 if result.get('ok') else 202) @user_bp.route('/leave-balance', methods=['GET']) def get_leave_balance(): user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') leave_type_code = _clean_str(request.args.get('leave_type')) if leave_type_code not in ('010', '408'): raise ValidationError('仅支持查询年假(010)和育儿假(408)的余额') try: from app.services.hr_leave_sqlserver import HRLeaveSQLServerService employee_code = HRLeaveSQLServerService._get_employee_code(user) now_year = datetime.now().year if leave_type_code == '010': _, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D044', year_column='D044001', total_column='D044005', used_column='D044006', remaining_column='D044007', employee_code=employee_code, year=now_year) label = '年假' else: _, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D072', year_column='d072001', total_column='d072002', used_column='d072003', remaining_column='d072004', employee_code=employee_code, year=now_year) label = '育儿假' remaining = record.get('remaining_hours') if record else None try: has_balance = remaining is not None and float(remaining) > 0 except (TypeError, ValueError): has_balance = False return jsonify({'leave_type_code': leave_type_code, 'leave_type_label': label, 'year': record.get('leave_year', now_year) if record else now_year, 'total_hours': record.get('total_hours') if record else None, 'used_hours': record.get('used_hours') if record else None, 'remaining_hours': remaining, 'has_balance': has_balance}) except Exception as exc: current_app.logger.exception('[leave-balance] query failed user_id=%s', getattr(user, 'id', None)) raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'假期余额查询失败:{exc}', http_status=500) @user_bp.route('/leave-workflow/submit', methods=['POST']) def submit_leave_workflow(): user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') 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)), 'applicantJobTitle': _clean_str(data.get('applicantJobTitle')), 'applicantDepartmentId': _clean_str(data.get('applicantDepartmentId')), 'applicantSubCompanyId1': _clean_str(data.get('applicantSubCompanyId1')), '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')), 'agentJobTitle': _clean_str(data.get('agentJobTitle')), 'agentDepartmentId': _clean_str(data.get('agentDepartmentId')), 'agentSubCompanyId1': _clean_str(data.get('agentSubCompanyId1')), '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): raise ValidationError(f'{label}不能为空。') try: from app.services.integrations.oa.leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError 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) raise ValidationError(str(exc)) except Exception as exc: current_app.logger.exception('[oa-leave] unexpected submit failure user_id=%s', getattr(user, 'id', None)) raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'OA 请假提交失败:{exc}', http_status=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('/feedback', methods=['POST']) def submit_general_feedback(): """ 通用意见反馈接口(与 /api/chat/feedback 的对话评分接口不同 """ user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') data = request.get_json() or {} feedback_type = _clean_str(data.get('feedback_type')) feedback_module = _clean_str(data.get('feedback_module')) content = _clean_str(data.get('content')) source_page = _clean_str(data.get('source_page')) raw_chat_log_id = data.get('chat_log_id') chat_log_id = None if raw_chat_log_id not in (None, ''): try: chat_log_id = int(raw_chat_log_id) except (TypeError, ValueError): raise ValidationError('chat_log_id must be an integer') if chat_log_id <= 0: raise ValidationError('chat_log_id must be a positive integer') if not feedback_type: raise ValidationError('feedback_type is required') if not feedback_module: raise ValidationError('feedback_module is required') if len(feedback_type) > 32: raise ValidationError('feedback_type is too long') if len(feedback_module) > 32: raise ValidationError('feedback_module is too long') if not content: raise ValidationError('content is required') if len(content) > 2000: raise ValidationError('content is too long') if source_page != 'chat': chat_log_id = None if chat_log_id is not None: chat_log = db.session.get(ChatLog, chat_log_id) if not chat_log: raise ValidationError('chat_log_id not found') if chat_log.user_id != user.id: raise ForbiddenError('chat_log_id is not owned by current user') row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id) db.session.add(row) db.session.commit() notify_result = send_feedback_group_notification(row, user) if notify_result.get('ok'): current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id) elif not notify_result.get('skipped'): current_app.logger.warning( '[feedback] group notification failed feedback_id=%s reason=%s', row.id, notify_result.get('reason'), ) return jsonify({'status': 'ok', 'id': row.id}) @user_bp.route('/home', methods=['GET']) def home(): """ Get user homepage data """ user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') def _load_home_payload(): if user.is_platform_admin(): agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all() else: agent_rows = [agent for agent in user.agents if agent.is_active] agent_rows = sort_agent_rows(agent_rows) favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all() favorite_ids = [f.agent_id for f in favorites] qqs = db.session.query(QuickQuestion).filter( or_( QuickQuestion.user_id == user.id, and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)), ) ).all() layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first() layout = layout_config.layout if layout_config else {} embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all() embedded_agents = [] for rel in embedded_rel: agent = db.session.get(Agent, rel.agent_id) if agent: registry = serialize_registry_fields(agent) embedded_agents.append({ 'id': agent.id, 'name': agent.name, 'iframe_url': registry.get('iframe_url'), 'runtime_provider': registry.get('runtime_provider'), 'conversation_mode': registry.get('conversation_mode'), }) return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout}) try: return _run_db_with_retry(_load_home_payload, label='user.home') except (OperationalError, DatabaseError) as exc: current_app.logger.warning('user.home retry failed: %s', exc) raise ServiceUnavailableError('Database connection failed') @user_bp.route('/favorites/', methods=['POST', 'DELETE']) def toggle_favorite(agent_id: int): user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') if request.method == 'POST': exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first() if not exists: fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id) db.session.add(fav) else: db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).delete() db.session.commit() return jsonify({'status': 'ok'}) @user_bp.route('/quick-questions', methods=['POST']) def add_quick_question(): user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') data = request.get_json() or {} if not data.get('title') or not data.get('question') or (not data.get('agent_id')): raise ValidationError('Missing fields') qq = QuickQuestion(user_id=user.id, title=data['title'], question=data['question'], agent_id=data['agent_id']) db.session.add(qq) db.session.commit() return (jsonify({'message': 'Added', 'id': qq.id}), 201) @user_bp.route('/quick-questions/', methods=['PUT', 'DELETE']) def update_quick_question(qq_id: int): user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first() if not qq: raise NotFoundError('QuickQuestion not found or permission denied') if request.method == 'DELETE': db.session.delete(qq) db.session.commit() return jsonify({'status': 'ok'}) data = request.get_json() or {} if 'title' in data: qq.title = data['title'] if 'question' in data: qq.question = data['question'] if 'agent_id' in data: qq.agent_id = data['agent_id'] db.session.commit() return jsonify({'status': 'ok'}) @user_bp.route('/homepage-layout', methods=['PUT']) def update_layout(): user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') data = request.get_json() or {} layout = data.get('layout', {}) config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first() if not config: config = UserHomepageConfig(user_id=user.id, layout=layout) db.session.add(config) else: config.layout = layout db.session.commit() return jsonify({'status': 'ok'}) @user_bp.route('/profile', methods=['GET', 'PUT']) def user_profile(): """ User profile management GET: Get details PUT: Update basic info """ user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') if request.method == 'GET': return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()}) data = request.get_json() or {} def _update_profile(): if 'real_name' in data: user.real_name = data['real_name'] if 'phone_number' in data: user.phone_number = data['phone_number'] if 'language' in data: user.language = data['language'] if 'theme_preference' in data: if data['theme_preference'] not in ['light', 'dark', 'system']: raise ValidationError('Invalid theme preference') user.theme_preference = data['theme_preference'] if 'email' in data: if data['email']: existing = db.session.query(User).filter_by(email=data['email']).first() if existing and existing.id != user.id: raise ValidationError('Email already exists') user.email = data['email'] if 'employee_id' in data: if data['employee_id']: existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first() if existing and existing.id != user.id: raise ValidationError('Employee ID already exists') user.employee_id = data['employee_id'] if 'department' in data: user.department = data['department'] db.session.commit() return jsonify({'message': 'Profile updated successfully'}) try: return _run_db_with_retry(_update_profile, label='user.profile.update') except (OperationalError, DatabaseError) as exc: db.session.rollback() current_app.logger.warning('user.profile.update retry failed: %s', exc) raise ServiceUnavailableError('Database connection failed') except Exception as e: db.session.rollback() raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500) @user_bp.route('/agents/', methods=['GET']) def get_agent_details(id): """ Get agent details with permission check """ user = _get_current_user() if not user: raise UnauthorizedError('Unauthorized') agent = db.session.get(Agent, id) if not agent: raise NotFoundError('Not found') if not user.is_platform_admin(): has_permission = agent in user.agents if not has_permission: raise ForbiddenError('Access denied') from app.services.agent_registry.resolver import resolve_runtime_provider from app.services.agent_registry.serialization import serialize_agent_for_user_detail dify_parameters = None if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None): from app.services.integrations.dify import DifyService try: params = DifyService.get_app_parameters(agent) if isinstance(params, dict): dify_parameters = { 'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {}, 'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {}, } except Exception as exc: current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc) return jsonify(serialize_agent_for_user_detail( agent, dify_parameters=dify_parameters, )) @user_bp.route('/db', methods=['GET']) def get_db(): from app.models import User from app import db u = db.session.query(User).filter_by(username='26040006').first() return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})