from flask import Blueprint, request, jsonify from flask_login import login_required from ldap_utils import search_ldap_principals, search_ldap_groups api_bp = Blueprint('api', __name__, url_prefix='/api') @api_bp.route('/ldap-search', methods=['GET']) @login_required def ldap_search(): """ API endpoint for searching LDAP principals. Returns JSON data for Tom Select dropdown. """ search_term = request.args.get('q', '').strip() print(f"[DEBUG] LDAP API 搜尋請求: '{search_term}'") if not search_term or len(search_term) < 2: print(f"[DEBUG] 搜尋詞太短,返回空結果") return jsonify([]) try: print(f"[DEBUG] 開始 LDAP 搜尋: '{search_term}'") # 搜尋使用者 user_results = search_ldap_principals(search_term, limit=15) print(f"[DEBUG] LDAP 使用者搜尋結果數量: {len(user_results)}") # 搜尋群組 group_results = search_ldap_groups(search_term, limit=5) print(f"[DEBUG] LDAP 群組搜尋結果數量: {len(group_results)}") # Format results for Tom Select formatted_results = [] # 加入使用者結果 for result in user_results: formatted_result = { 'value': result['email'], 'text': f"👤 {result['name']} ({result['email']})", 'type': 'user' } formatted_results.append(formatted_result) print(f"[DEBUG] 格式化使用者結果: {result['name']} - {result['email']}") # 加入群組結果 for result in group_results: # 對群組,使用群組名稱作為 value,在發送郵件時再展開成員 formatted_result = { 'value': f"group:{result['name']}", # 特殊前綴表示這是群組 'text': f"👥 {result['name']} ({result['member_count']} 成員)", 'type': 'group' } formatted_results.append(formatted_result) print(f"[DEBUG] 格式化群組結果: {result['name']} - {result['member_count']} 成員") print(f"[DEBUG] 返回 {len(formatted_results)} 個搜尋結果") return jsonify(formatted_results) except Exception as e: print(f"[DEBUG] LDAP search API error: {e}") import traceback traceback.print_exc() return jsonify({'error': 'Search failed'}), 500 @api_bp.route('/debug-form', methods=['POST']) @login_required def debug_form(): """接收前端表單除錯資訊""" try: data = request.get_json() print(f"[FRONTEND DEBUG] 收到前端除錯資料:") print(f"[FRONTEND DEBUG] selectedValues: {data.get('selectedValues')}") print(f"[FRONTEND DEBUG] recipientValue: {data.get('recipientValue')}") print(f"[FRONTEND DEBUG] hiddenFieldValue: {data.get('hiddenFieldValue')}") print(f"[FRONTEND DEBUG] tomSelectValue: {data.get('tomSelectValue')}") return jsonify({'status': 'received'}) except Exception as e: print(f"[FRONTEND DEBUG] 錯誤: {e}") return jsonify({'error': str(e)}), 400