diff --git a/app.py b/app.py index cb19dd4..107360d 100644 --- a/app.py +++ b/app.py @@ -1,5 +1,6 @@ -from asyncio import timeout from datetime import datetime, timedelta +from typing import Any + from flask import Flask, render_template, jsonify, request import json import os @@ -45,7 +46,7 @@ class MessageRender: else: display_parts.append(f'[{msg_type}]') message_data['display_content'] = ' '.join(display_parts) - except: + except ValueError: message_data['display_content'] = '[混合消息]' elif msg_type == 'chatrecord': try: @@ -55,7 +56,7 @@ class MessageRender: message_data['chatrecord_data'] = chatrecord_data else: message_data['display_content'] = '[聊天记录]' - except: + except ValueError: message_data['display_content'] = '[聊天记录]' else: message_data['display_content'] = f'[{msg_type}] {content}' @@ -384,10 +385,10 @@ class ReportService: def analyze_category_breakdown(messages): """分析问题分类""" category_counts = { - '信息披露类': 0, - '公司治理与法规': 0, - '业务操作与系统': 0, - '其他': 0 + '信息披露类': 0.0, + '公司治理与法规': 0.0, + '业务操作与系统': 0.0, + '其他': 0.0 } category_keywords = { @@ -474,43 +475,47 @@ message_processor = MessageRender() chat_session = ChatSessionManager(db_manager) -def api_response(success=True, data=None, error=None, status_code=200): +def api_response(success=True, data=None, error = None, status_code=200): """统一的API响应格式""" response = {'success': success} - if data: - response.update(data) if error: response['error'] = str(error) + if data: + response.update(data) return jsonify(response), status_code # 页面路由 -@app.route('/', defaults={'timeout': 60}) +@app.route('/') def index(): """主页面 - 聊天界面""" return render_template('index.html') -@app.route('/qa', defaults={'timeout': 60}) +@app.route('/qa') def qa_page(): """问答管理页面""" return render_template('qa.html') -@app.route('/weekly_report', defaults={'timeout': 60}) +@app.route('/weekly_report') def weekly_report_page(): """周报页面""" return render_template('weekly_report.html') -@app.route('/daily_report', defaults={'timeout': 60}) +@app.route('/daily_report') def daily_report_page(): """日报页面""" return render_template('daily_report.html') -@app.route('/api/db/datetime', defaults={'timeout': 60}) + + +@app.route('/api/db/datetime') def db_status(): return api_response(success=True, data={'message': chat_session.status()}) -@app.route('/api/db/update', defaults={'timeout': 60}) + + +@app.route('/api/db/update') def db_update(): current_time = time.localtime(time.time() - 24 * 60 * 60) day = current_time.tm_mday @@ -528,7 +533,7 @@ def db_update(): return api_response(success=True, data={'message': '数据库更新成功'}) -@app.route('/api/db/upload', defaults={'timeout': 60}) +@app.route('/api/db/upload') def db_upload(): db_manager.upload_db() return api_response(success=True, data={'message': '数据库上传成功'}) @@ -655,32 +660,151 @@ def search_messages(): try: keyword = request.args.get('keyword', '') limit = request.args.get('limit', 100, type=int) + search_type = request.args.get('search_type', 'all') # all, question, answer if not keyword: return api_response(success=False, error='请输入搜索关键词', status_code=400) group_id = request.args.get('group_id', type=str) + + # 智能搜索:支持模糊匹配和精确匹配 messages_data = report_service.search_messages(keyword, limit, group_id) + + # 根据搜索类型过滤消息 + if search_type == 'question': + messages_data = [msg for msg in messages_data if msg.get('type') in ['text', 'mixed']] + elif search_type == 'answer': + messages_data = [msg for msg in messages_data if msg.get('type') in ['text', 'mixed']] + formatted_messages = [] for msg in messages_data: message = dict(msg) message = message_processor.process_message_content(message) + + # 添加搜索关键词高亮 + if keyword: + content = message.get('content', '') + if keyword.lower() in content.lower(): + # 简单的关键词高亮(前端可以进一步处理) + highlighted_content = content.replace(keyword, f'{keyword}') + message['highlighted_content'] = highlighted_content + formatted_messages.append(message) - return api_response(data={'messages': formatted_messages}) + return api_response(data={'messages': formatted_messages, 'total': len(formatted_messages)}) except Exception as e: return api_response(success=False, error=e, status_code=500) +# API路由 - 搜索建议 +@app.route('/api/search_suggestions') +def search_suggestions(): + """搜索建议API""" + try: + keyword = request.args.get('keyword', '') + + if not keyword: + return api_response(data={'suggestions': []}) + + # 获取热门搜索关键词 + suggestions = [] + + # 1. 从消息内容中提取相关关键词 + try: + messages = report_service.search_messages(keyword, 10, None) + for msg in messages: + content = msg.get('content', '') + # 简单的关键词提取逻辑 + words = content.split() + for word in words: + if len(word) > 2 and keyword.lower() in word.lower(): + if word not in suggestions: + suggestions.append(word) + if len(suggestions) >= 5: + break + if len(suggestions) >= 5: + break + except: + pass + + # 2. 添加常见搜索关键词 + common_keywords = ['信息披露', '公司治理', '业务操作', '系统填报', '政策法规', '季度报告', '股东大会'] + for kw in common_keywords: + if keyword.lower() in kw.lower() and kw not in suggestions: + suggestions.append(kw) + if len(suggestions) >= 8: + break + + return api_response(data={'suggestions': suggestions[:8]}) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + # API路由 - QA管理 @app.route('/api/qa') def get_qa_list(): """获取QA列表API""" try: - qa_data = report_service.get_all_qa() + # 获取查询参数 + group_id = request.args.get('group_id', '') + keyword = request.args.get('keyword', '') + start_time = request.args.get('start_time', '') + end_time = request.args.get('end_time', '') + + # 构建查询条件 + query_conditions = [] + query_params = [] + + if group_id: + query_conditions.append("groupId LIKE ?") + query_params.append(f"%{group_id}%") + + if start_time and end_time: + query_conditions.append("start_time >= ? AND end_time <= ?") + query_params.extend([f"{start_time}000", f"{end_time}999"]) + + # 构建查询语句 + base_query = "SELECT * FROM qa" + if query_conditions: + base_query += " WHERE " + " AND ".join(query_conditions) + base_query += " ORDER BY id DESC" + + # 执行查询 + conn = db_manager.get_connection() + cursor = conn.cursor() + cursor.execute(base_query, query_params) + qa_data = cursor.fetchall() + conn.close() + qa_list = [dict(qa) for qa in qa_data] - return api_response(data={'qa_list': qa_list}) + + # 如果有关键词搜索,进行内容过滤 + if keyword: + filtered_qa_list = [] + for qa in qa_list: + # 检查群组ID是否匹配 + if keyword.lower() in (qa.get('groupId') or '').lower(): + filtered_qa_list.append(qa) + continue + + # 检查问题内容是否匹配 + try: + question_ids = json.loads(qa.get('question', '[]')) + if question_ids: + # 获取问题消息内容进行匹配 + messages = report_service.get_messages_by_ids(question_ids) + for msg in messages: + if keyword.lower() in (msg.get('content') or '').lower(): + filtered_qa_list.append(qa) + break + except: + pass + + qa_list = filtered_qa_list + + return api_response(data={'qa_list': qa_list, 'total': len(qa_list)}) except Exception as e: return api_response(success=False, error=e, status_code=500) @@ -716,14 +840,13 @@ def create_qa(): group_id = data.get('groupId', '') question_ids = data.get('question', []) answer_ids = data.get('answer', []) - conn = db_manager.get_connection() cursor = conn.cursor() cursor.execute(''' - INSERT INTO qa (groupId, question, answer) - VALUES (?, ?, ?) - ''', (group_id, json.dumps(question_ids), json.dumps(answer_ids))) + INSERT INTO qa (groupId, question, answer,start_time,end_time) VALUES (?,?,?,?,?) + ''', (group_id, json.dumps(question_ids), json.dumps(answer_ids), + data.get('start_time', ''), data.get('end_time', ''))) conn.commit() qa_id = cursor.lastrowid @@ -773,7 +896,7 @@ def update_qa(qa_id): @app.route('/api/qa/', methods=['DELETE']) def delete_qa(qa_id): - """删除QA记录API""" + """删除单个QA记录API""" try: # 检查记录是否存在 if not report_service.check_qa_exists(qa_id): @@ -791,9 +914,40 @@ def delete_qa(qa_id): except Exception as e: return api_response(success=False, error=e, status_code=500) +@app.route('/api/qa/batch', methods=['DELETE']) +def batch_delete_qa(): + """批量删除QA记录API""" + try: + data = request.get_json() + qa_ids = data.get('qa_ids', []) + + if not qa_ids: + return api_response(success=False, error='请提供要删除的QA记录ID列表', status_code=400) + + # 检查所有记录是否存在 + for qa_id in qa_ids: + if not report_service.check_qa_exists(qa_id): + return api_response(success=False, error=f'QA记录 {qa_id} 不存在', status_code=404) + + conn = db_manager.get_connection() + cursor = conn.cursor() + + # 构建批量删除语句 + placeholders = ','.join(['?'] * len(qa_ids)) + query = f'DELETE FROM qa WHERE id IN ({placeholders})' + + cursor.execute(query, qa_ids) + conn.commit() + conn.close() + + return api_response(status_code=404) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + # API路由 - 报告生成 -@app.route('/api/reports/daily', defaults={'timeout': 60}) +@app.route('/api/reports/daily') def generate_daily_report(): """生成日报API""" try: @@ -877,7 +1031,7 @@ def generate_daily_report(): ## **4. 待办事项** -{"有"+str(non_qa_count)+"条未被回答的问题,关注活跃群组的后续讨论,确保所有疑问被解答。" if non_qa_count > 0 else "无未被回答的问题,继续保持活跃群组的讨论。"} +{"有" + str(non_qa_count) + "条未被回答的问题,关注活跃群组的后续讨论,确保所有疑问被解答。" if non_qa_count > 0 else "无未被回答的问题,继续保持活跃群组的讨论。"} 明日重点关注:根据今日热点预测明日可能的问题。 """ @@ -904,7 +1058,7 @@ def generate_daily_report(): return api_response(success=False, error=e, status_code=500) -@app.route('/api/reports/weekly', defaults={'timeout': 60}) +@app.route('/api/reports/weekly') def generate_weekly_report(): """生成周报API""" try: diff --git a/db/data b/db/data index 7845226..7d88d7c 100644 Binary files a/db/data and b/db/data differ diff --git a/static/css/qa.css b/static/css/qa.css index f9a6574..8ec41d5 100644 --- a/static/css/qa.css +++ b/static/css/qa.css @@ -45,6 +45,155 @@ body { box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); } +/* 过滤区域样式 */ +.filter-section { + margin-bottom: 20px; + background: #f8f9fa; + border-radius: 8px; + padding: 20px; + border: 1px solid #e9ecef; +} + +.filter-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 20px; + padding-bottom: 15px; + border-bottom: 1px solid #dee2e6; +} + +.filter-header h3 { + font-size: 18px; + color: #495057; + margin: 0; + font-weight: 600; +} + +.filter-actions { + display: flex; + gap: 10px; +} + +.filter-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); + gap: 15px; +} + +.filter-item { + display: flex; + flex-direction: column; +} + +.filter-item label { + font-weight: 600; + margin-bottom: 8px; + font-size: 14px; + color: #495057; +} + +.filter-item input, +.filter-item select { + padding: 10px 12px; + border: 1px solid #ced4da; + border-radius: 6px; + font-size: 14px; + transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; +} + +.filter-item input:focus, +.filter-item select:focus { + outline: none; + border-color: #667eea; + box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); +} + +.action-section { + display: flex; + justify-content: space-between; + align-items: center; + padding: 20px; + background: white; + border-radius: 8px; + border: 1px solid #e9ecef; + margin-top: 20px; +} + +.stats-section { + flex: 1; +} + +.stats-info { + font-size: 15px; + color: #6c757d; + font-weight: 600; + padding: 8px 0; +} + +.create-section { + display: flex; + gap: 10px; +} + +/* 批量操作区域样式 */ +.batch-actions { + background: #f8f9fa; + border: 1px solid #dee2e6; + border-radius: 5px; + padding: 15px; + margin-bottom: 20px; +} + +.batch-header { + display: flex; + align-items: center; + justify-content: space-between; +} + +.batch-select { + display: flex; + align-items: center; + gap: 10px; +} + +.batch-select input[type="checkbox"] { + width: 18px; + height: 18px; +} + +.batch-select label { + font-weight: bold; + color: #495057; + margin: 0; +} + +.batch-info { + font-size: 14px; + color: #6c757d; + font-weight: bold; +} + +.batch-buttons { + display: flex; + gap: 10px; +} + +/* QA项目选中状态 */ +.qa-item.selected { + background-color: #e3f2fd; + border-color: #2196f3; +} + +.qa-checkbox { + margin-right: 10px; +} + +.qa-checkbox input[type="checkbox"] { + width: 16px; + height: 16px; +} + .search-box { display: flex; gap: 10px; @@ -96,6 +245,17 @@ body { background: #c82333; } +.btn-outline { + background: transparent; + color: #6c757d; + border: 1px solid #6c757d; +} + +.btn-outline:hover { + background: #6c757d; + color: white; +} + .qa-list { background: white; border-radius: 10px; @@ -104,24 +264,51 @@ body { } .qa-item { + background: white; + border: 1px solid #ddd; + border-radius: 8px; padding: 20px; - border-bottom: 1px solid #eee; - transition: background-color 0.3s ease; + margin-bottom: 15px; + box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); + transition: all 0.3s ease; + display: flex; + flex-direction: column; } .qa-item:hover { - background-color: #f8f9fa; + box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15); + transform: translateY(-2px); } -.qa-item:last-child { - border-bottom: none; +.qa-item.selected { + background-color: #e3f2fd; + border-color: #2196f3; + box-shadow: 0 4px 15px rgba(33, 150, 243, 0.2); } .qa-header { display: flex; - justify-content: space-between; align-items: center; margin-bottom: 15px; + gap: 15px; +} + +.qa-checkbox { + flex-shrink: 0; +} + +.qa-id { + font-weight: bold; + color: #667eea; + font-size: 16px; +} + +.qa-group { + background: #f0f0f0; + padding: 4px 8px; + border-radius: 4px; + font-size: 12px; + color: #666; } .qa-id { @@ -316,6 +503,160 @@ body { opacity: 0.5; } +/* 搜索相关样式 */ +.search-container { + position: relative; +} + +.search-input-wrapper { + position: relative; +} + +.search-suggestions { + position: absolute; + top: 100%; + left: 0; + right: 0; + background: white; + border: 1px solid #ddd; + border-top: none; + border-radius: 0 0 5px 5px; + box-shadow: 0 2px 8px rgba(0,0,0,0.1); + z-index: 1000; + display: none; +} + +.search-suggestion-item { + padding: 10px 15px; + cursor: pointer; + border-bottom: 1px solid #f0f0f0; + transition: background-color 0.2s; +} + +.search-suggestion-item:hover { + background-color: #f8f9fa; +} + +.search-suggestion-item:last-child { + border-bottom: none; +} + +.search-history { + margin-top: 10px; + border: 1px solid #ddd; + border-radius: 5px; + background: white; + display: none; +} + +.search-history-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px 15px; + border-bottom: 1px solid #eee; + background: #f8f9fa; +} + +.search-history-header span { + font-weight: bold; + color: #495057; +} + +.btn-clear-history { + background: none; + border: none; + color: #6c757d; + cursor: pointer; + font-size: 12px; + text-decoration: underline; +} + +.btn-clear-history:hover { + color: #495057; +} + +.search-history-items { + max-height: 200px; + overflow-y: auto; +} + +.search-history-item { + padding: 8px 15px; + cursor: pointer; + border-bottom: 1px solid #f8f9fa; + transition: background-color 0.2s; +} + +.search-history-item:hover { + background-color: #f8f9fa; +} + +.search-history-item:last-child { + border-bottom: none; +} + +/* 按钮样式增强 */ +.btn-secondary { + background-color: #6c757d; + border-color: #6c757d; +} + +.btn-secondary:hover { + background-color: #5a6268; + border-color: #545b62; +} + +.btn-info { + background-color: #17a2b8; + border-color: #17a2b8; +} + +.btn-info:hover { + background-color: #138496; + border-color: #117a8b; +} + +/* 搜索结果样式 */ +.search-results-header { + background: #f8f9fa; + padding: 15px 20px; + border-radius: 5px; + margin-bottom: 15px; + border-left: 4px solid #667eea; +} + +.search-results-header h3 { + margin: 0 0 5px 0; + color: #495057; +} + +.search-summary { + color: #6c757d; + font-size: 0.9em; +} + +.search-result-item { + border-left: 3px solid #28a745; + background: #f8fff9; +} + +.message-content { + background: white; + padding: 10px; + border-radius: 3px; + border: 1px solid #e9ecef; + margin-top: 5px; + line-height: 1.5; +} + +.message-content mark { + background-color: #fff3cd; + padding: 2px 4px; + border-radius: 2px; + font-weight: bold; +} + /* 聊天记录预览样式 */ .chat-preview { background: white; diff --git a/static/js/qa.js b/static/js/qa.js index 54005eb..b8bf80e 100644 --- a/static/js/qa.js +++ b/static/js/qa.js @@ -1,26 +1,141 @@ let currentQA = null; let selectedQuestions = []; let selectedAnswers = []; +let selectedQAs = new Set(); // 用于批量操作 +let groupList = []; // 存储群组列表 + +// 加载群组列表 +async function loadGroupList() { + try { + const response = await fetch('/api/groups'); + const result = await response.json(); + + if (result.success) { + groupList = result.groups || []; + + // 更新过滤区域的群组下拉框 + const groupFilter = document.getElementById('groupFilter'); + if (groupFilter) { + updateGroupSelect(groupFilter); + } + + // 更新模态框中的群组下拉框 + const groupIdSelect = document.getElementById('groupId'); + if (groupIdSelect) { + updateGroupSelect(groupIdSelect); + } + } else { + console.error('加载群组列表失败:', result.error); + } + } catch (error) { + console.error('加载群组列表时出错:', error); + } +} + +// 更新群组下拉框 +function updateGroupSelect(selectElement) { + if (!selectElement) return; + + // 保存当前选中的值 + const currentValue = selectElement.value; + + // 清空下拉框,保留第一个选项 + selectElement.innerHTML = ''; + + // 添加群组选项 + groupList.forEach(group => { + const option = document.createElement('option'); + option.value = group.id; + option.textContent = group.name ? `${group.name} (${group.id})` : group.id; + selectElement.appendChild(option); + }); + + // 恢复之前选中的值 + if (currentValue) { + selectElement.value = currentValue; + } +} // 页面加载时获取QA列表 document.addEventListener('DOMContentLoaded', function () { loadQAList(); + loadGroupList(); + updateSearchHistory(); + + // 添加点击外部关闭搜索建议的事件 + document.addEventListener('click', function(e) { + const suggestionsContainer = document.getElementById('searchSuggestions'); + const searchInput = document.getElementById('searchInput'); + + if (suggestionsContainer && searchInput && + !suggestionsContainer.contains(e.target) && + e.target !== searchInput) { + suggestionsContainer.style.display = 'none'; + } + }); + + // 添加回车键搜索功能 + const searchInput = document.getElementById('searchInput'); + if (searchInput) { + searchInput.addEventListener('keypress', function(e) { + if (e.key === 'Enter') { + advancedSearch(); + } + }); + } }); // 加载QA列表 async function loadQAList() { try { - const response = await fetch('/api/qa'); + // 获取搜索参数 + const searchInput = document.getElementById('searchInput'); + const groupFilter = document.getElementById('groupFilter'); + const startDateFilter = document.getElementById('startDateFilter'); + const endDateFilter = document.getElementById('endDateFilter'); + + const keyword = searchInput ? searchInput.value.trim() : ''; + const groupId = groupFilter ? groupFilter.value.trim() : ''; + const startTime = startDateFilter ? startDateFilter.value : ''; + const endTime = endDateFilter ? endDateFilter.value : ''; + + // 构建查询URL + let url = '/api/qa'; + const params = new URLSearchParams(); + + if (keyword) params.append('keyword', keyword); + if (groupId) params.append('group_id', groupId); + if (startTime) params.append('start_time', startTime); + if (endTime) params.append('end_time', endTime); + + if (params.toString()) { + url += '?' + params.toString(); + } + + const response = await fetch(url); const result = await response.json(); if (result.success) { // 根据后端API返回的数据结构,data字段包含qa_list const qaList = result.qa_list || []; displayQAList(qaList); + + // 更新统计信息 + updateStats(result.total || qaList.length); } else { alert('加载QA列表失败: ' + result.error); } } catch (error) { - alert('加载QA列表时出错: ' + error.message); + // 修复错误:确保error.message存在,避免"Cannot read properties of undefined"错误 + const errorMessage = error?.message || error?.toString() || '未知错误'; + alert('加载QA列表时出错: ' + errorMessage); + } +} + +// 更新统计信息 +function updateStats(total) { + const statsElement = document.getElementById('statsInfo'); + if (statsElement) { + statsElement.textContent = `共找到 ${total} 条QA记录`; } } @@ -36,9 +151,16 @@ async function displayQAList(qaList) {

点击"创建新QA"按钮开始创建第一个问答记录

`; + // 隐藏批量操作按钮 + const batchActions = document.getElementById('batchActions'); + if (batchActions) batchActions.style.display = 'none'; return; } + // 显示批量操作按钮 + const batchActions = document.getElementById('batchActions'); + if (batchActions) batchActions.style.display = 'block'; + // 获取所有消息的详细内容 let allMessageIds = []; qaList.forEach(qa => { @@ -110,9 +232,14 @@ async function displayQAList(qaList) { questionContent = questionContent.substring(0, 30) + '...'; } + const isSelected = selectedQAs.has(qa.id); + return ` -
+
+
+ +
QA #${qa.id}
${qa.groupId || '无群组'}
@@ -135,6 +262,9 @@ async function displayQAList(qaList) {
`; }).join(''); + + // 更新批量操作按钮状态 + updateBatchActions(); } // 搜索消息 @@ -146,36 +276,191 @@ async function searchMessages() { } try { + // 显示搜索中状态 + const qaListContainer = document.getElementById('qaList'); + qaListContainer.innerHTML = '
搜索中...
'; + const response = await fetch(`/api/search_messages?keyword=${encodeURIComponent(keyword)}`); const result = await response.json(); if (result.success) { displaySearchResults(result.messages); + // 保存搜索历史 + saveSearchHistory(keyword); } else { alert('搜索失败: ' + result.error); } } catch (error) { - alert('搜索时出错: ' + error.message); + // 修复错误:确保error.message存在,避免"Cannot read properties of undefined"错误 + const errorMessage = error?.message || error?.toString() || '未知错误'; + alert('搜索时出错: ' + errorMessage); } } +// 高级搜索 +async function advancedSearch() { + const keyword = document.getElementById('searchInput').value.trim(); + const groupFilter = document.getElementById('groupFilter').value.trim(); + const startDate = document.getElementById('startDateFilter').value; + const endDate = document.getElementById('endDateFilter').value; + + if (!keyword && !groupFilter && !startDate && !endDate) { + alert('请输入至少一个搜索条件'); + return; + } + + try { + // 显示搜索中状态 + const qaListContainer = document.getElementById('qaList'); + qaListContainer.innerHTML = '
搜索中...
'; + + // 构建查询参数 + const params = new URLSearchParams(); + if (keyword) params.append('keyword', keyword); + if (groupFilter) params.append('group_id', groupFilter); + if (startDate) params.append('start_time', startDate); + if (endDate) params.append('end_time', endDate); + + const response = await fetch(`/api/qa?${params.toString()}`); + const result = await response.json(); + + if (result.success) { + displayQAList(result.qa_list || []); + // 保存搜索历史 + if (keyword) saveSearchHistory(keyword); + } else { + alert('搜索失败: ' + result.error); + } + } catch (error) { + const errorMessage = error?.message || error?.toString() || '未知错误'; + alert('搜索时出错: ' + errorMessage); + } +} + +// 保存搜索历史 +function saveSearchHistory(keyword) { + let searchHistory = JSON.parse(localStorage.getItem('qa_search_history') || '[]'); + + // 移除重复项 + searchHistory = searchHistory.filter(item => item !== keyword); + + // 添加到开头 + searchHistory.unshift(keyword); + + // 限制历史记录数量 + if (searchHistory.length > 10) { + searchHistory = searchHistory.slice(0, 10); + } + + localStorage.setItem('qa_search_history', JSON.stringify(searchHistory)); + + // 更新搜索历史显示 + updateSearchHistory(); +} + +// 更新搜索历史显示 +function updateSearchHistory() { + const searchHistory = JSON.parse(localStorage.getItem('qa_search_history') || '[]'); + const historyContainer = document.getElementById('searchHistory'); + + if (!historyContainer) return; + + if (searchHistory.length === 0) { + historyContainer.style.display = 'none'; + return; + } + + historyContainer.style.display = 'block'; + historyContainer.innerHTML = ` +
+ 搜索历史 + +
+
+ ${searchHistory.map(item => ` +
+ ${item} +
+ `).join('')} +
+ `; +} + +// 填充搜索输入框 +function fillSearchInput(keyword) { + document.getElementById('searchInput').value = keyword; +} + +// 清空搜索历史 +function clearSearchHistory() { + if (confirm('确定要清空搜索历史吗?')) { + localStorage.removeItem('qa_search_history'); + updateSearchHistory(); + } +} + +// 智能搜索建议 +async function showSearchSuggestions() { + const keyword = document.getElementById('searchInput').value.trim(); + const suggestionsContainer = document.getElementById('searchSuggestions'); + + if (!keyword) { + suggestionsContainer.style.display = 'none'; + return; + } + + try { + // 调用后端API获取搜索建议 + const response = await fetch(`/api/search_suggestions?keyword=${encodeURIComponent(keyword)}`); + const result = await response.json(); + + if (result.success && result.suggestions.length > 0) { + suggestionsContainer.innerHTML = result.suggestions.map(item => ` +
+ ${item} +
+ `).join(''); + suggestionsContainer.style.display = 'block'; + } else { + suggestionsContainer.style.display = 'none'; + } + } catch (error) { + suggestionsContainer.style.display = 'none'; + } +} + +// 选择搜索建议 +function selectSearchSuggestion(suggestion) { + document.getElementById('searchInput').value = suggestion; + document.getElementById('searchSuggestions').style.display = 'none'; + searchMessages(); +} + // 显示搜索结果 function displaySearchResults(messages) { const qaListContainer = document.getElementById('qaList'); + const keyword = document.getElementById('searchInput').value.trim(); if (messages.length === 0) { qaListContainer.innerHTML = `
🔍

未找到相关消息

-

请尝试其他搜索关键词

+

请尝试其他搜索关键词或调整搜索条件

`; return; } - qaListContainer.innerHTML = messages.map(msg => ` -
+ qaListContainer.innerHTML = ` +
+

搜索结果 (${messages.length} 条)

+
+ 搜索关键词: "${keyword}" +
+
+ ${messages.map(msg => ` +
消息ID: ${msg.id}
${msg.formatted_time || '未知时间'}
@@ -188,16 +473,27 @@ function displaySearchResults(messages) { 接收者: ${msg.receiver || '未知'}
- 内容: ${msg.display_content || '无内容'} + 内容: +
+ ${msg.highlighted_content ? msg.highlighted_content : (msg.display_content || '无内容')} +
+
- `).join(''); + `).join('')} + `; +} + +// 查看消息详情 +function viewMessageDetail(messageId) { + // 这里可以打开一个模态框显示消息的完整详情 + alert(`查看消息详情: ${messageId}\n此功能可以进一步扩展显示完整消息内容`); } // 打开创建模态框 @@ -233,7 +529,129 @@ async function editQA(qaId) { alert('加载QA详情失败: ' + result.error); } } catch (error) { - alert('加载QA详情时出错: ' + error.message); + // 修复错误:确保error.message存在,避免"Cannot read properties of undefined"错误 + const errorMessage = error?.message || error?.toString() || '未知错误'; + alert('加载QA详情时出错: ' + errorMessage); + } +} + +// 清空过滤器 +function clearFilters() { + document.getElementById('searchInput').value = ''; + document.getElementById('groupFilter').value = ''; + document.getElementById('startDateFilter').value = ''; + document.getElementById('endDateFilter').value = ''; + loadQAList(); +} + +// 切换QA选择状态 +function toggleQASelection(qaId, isSelected) { + if (isSelected) { + selectedQAs.add(qaId); + } else { + selectedQAs.delete(qaId); + } + + // 更新UI + const qaItem = document.querySelector(`[data-qa-id="${qaId}"]`); + if (qaItem) { + if (isSelected) { + qaItem.classList.add('selected'); + } else { + qaItem.classList.remove('selected'); + } + } + + updateBatchActions(); +} + +// 全选/取消全选 +function toggleSelectAll() { + const selectAllCheckbox = document.getElementById('selectAll'); + const qaItems = document.querySelectorAll('.qa-item'); + + if (selectAllCheckbox.checked) { + // 全选 + qaItems.forEach(item => { + const qaId = parseInt(item.getAttribute('data-qa-id')); + selectedQAs.add(qaId); + item.classList.add('selected'); + const checkbox = item.querySelector('.qa-select'); + if (checkbox) checkbox.checked = true; + }); + } else { + // 取消全选 + selectedQAs.clear(); + qaItems.forEach(item => { + item.classList.remove('selected'); + const checkbox = item.querySelector('.qa-select'); + if (checkbox) checkbox.checked = false; + }); + } + + updateBatchActions(); +} + +// 更新批量操作按钮状态 +function updateBatchActions() { + const selectedCount = selectedQAs.size; + const batchInfo = document.getElementById('batchInfo'); + const batchDeleteBtn = document.getElementById('batchDeleteBtn'); + + if (batchInfo) { + batchInfo.textContent = `已选择 ${selectedCount} 条记录`; + } + + if (batchDeleteBtn) { + batchDeleteBtn.disabled = selectedCount === 0; + } +} + +// 批量删除QA记录 +async function batchDeleteQA() { + const selectedCount = selectedQAs.size; + if (selectedCount === 0) { + alert('请先选择要删除的QA记录'); + return; + } + + if (!confirm(`确定要删除选中的 ${selectedCount} 条QA记录吗?此操作不可恢复。`)) { + return; + } + + try { + const response = await fetch('/api/qa/batch', { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({qa_ids: Array.from(selectedQAs)}) + }); + + if (response.status === 404) { + // 404状态码表示删除成功 + alert('批量删除成功'); + selectedQAs.clear(); + loadQAList(); + } else if (response.status === 500) { + // 500状态码表示删除失败 + const result = await response.json(); + alert('批量删除失败: ' + (result.error || '服务器内部错误')); + } else { + // 其他状态码处理 + const result = await response.json(); + if (result.success) { + alert(result.data.message); + selectedQAs.clear(); + loadQAList(); + } else { + alert('批量删除失败: ' + result.error); + } + } + } catch (error) { + // 修复错误:确保error.message存在,避免"Cannot read properties of undefined"错误 + const errorMessage = error?.message || error?.toString() || '未知错误'; + alert('批量删除时出错: ' + errorMessage); } } @@ -244,7 +662,8 @@ async function searchQuestionMessages() { document.getElementById('questionResults').innerHTML = ''; return; } - const groupId = document.getElementById('groupId').value.trim(); + const groupIdSelect = document.getElementById('groupId'); + const groupId = groupIdSelect.value; try { const url = `/api/search_messages?keyword=${encodeURIComponent(keyword)}&limit=20${groupId ? `&group_id=${groupId}` : ''}`; const response = await fetch(url); @@ -257,6 +676,27 @@ async function searchQuestionMessages() { } } +// 添加回车键搜索功能 +document.addEventListener('DOMContentLoaded', function() { + const searchInput = document.getElementById('searchInput'); + if (searchInput) { + searchInput.addEventListener('keypress', function(e) { + if (e.key === 'Enter') { + loadQAList(); + } + }); + } + + const groupFilter = document.getElementById('groupFilter'); + if (groupFilter) { + groupFilter.addEventListener('keypress', function(e) { + if (e.key === 'Enter') { + loadQAList(); + } + }); + } +}); + // 显示问题搜索结果 function displayQuestionResults(messages) { const resultsContainer = document.getElementById('questionResults'); @@ -277,7 +717,8 @@ async function searchAnswerMessages() { document.getElementById('answerResults').innerHTML = ''; return; } - const groupId = document.getElementById('groupId').value.trim(); + const groupIdSelect = document.getElementById('groupId'); + const groupId = groupIdSelect.value; try { const url = `/api/search_messages?keyword=${encodeURIComponent(keyword)}&limit=20${groupId ? `&group_id=${groupId}` : ''}`; @@ -368,7 +809,8 @@ function removeAnswer(messageId) { // 保存QA记录 async function saveQA() { - const groupId = document.getElementById('groupId').value.trim(); + const groupIdSelect = document.getElementById('groupId'); + const groupId = groupIdSelect.value; if (selectedQuestions.length === 0) { alert('请至少选择一个问题消息'); @@ -408,7 +850,9 @@ async function saveQA() { alert('保存失败: ' + result.error); } } catch (error) { - alert('保存时出错: ' + error.message); + // 修复错误:确保error.message存在,避免"Cannot read properties of undefined"错误 + const errorMessage = error?.message || error?.toString() || '未知错误'; + alert('保存时出错: ' + errorMessage); } } @@ -423,7 +867,9 @@ async function previewQA(qaId) { alert('加载QA详情失败: ' + result.error); } } catch (error) { - alert('加载QA详情时出错: ' + error.message); + // 修复错误:确保error.message存在,避免"Cannot read properties of undefined"错误 + const errorMessage = error?.message || error?.toString() || '未知错误'; + alert('加载QA详情时出错: ' + errorMessage); } } @@ -539,7 +985,9 @@ async function deleteQA(qaId) { alert('删除失败: ' + result.error); } } catch (error) { - alert('删除时出错: ' + error.message); + // 修复错误:确保error.message存在,避免"Cannot read properties of undefined"错误 + const errorMessage = error?.message || error?.toString() || '未知错误'; + alert('删除时出错: ' + errorMessage); } } diff --git a/templates/qa.html b/templates/qa.html index 420974c..7a0cd81 100644 --- a/templates/qa.html +++ b/templates/qa.html @@ -20,13 +20,70 @@
- + + +
加载中...
@@ -43,7 +100,9 @@
- +