diff --git a/app.py b/app.py index 1420293..c4cdacf 100644 --- a/app.py +++ b/app.py @@ -90,6 +90,15 @@ class ReportService: ''', (f"{start_timestamp}000", f"{end_timestamp}999"), fetch_all=False) return result["count"] + def get_active_sub_users_by_time_range(self, start_timestamp, end_timestamp): + """获取指定时间范围内的活跃用户数量""" + result = self.execute_query(''' + SELECT COUNT(DISTINCT sender) as count + FROM message + WHERE time >= ? + AND time <= ? + ''', (f"{start_timestamp}000", f"{end_timestamp}999"), fetch_all=False) + return result["count"] def get_qa_count_by_time_range(self, start_timestamp, end_timestamp): """获取指定时间范围内的QA记录数量""" result = self.execute_query(''' @@ -111,6 +120,27 @@ class ReportService: ''', (f"{start_timestamp}000", f"{end_timestamp}999"), fetch_all=False) return result["count"] + def get_qa_count_by_time_range_sub(self, start_timestamp, end_timestamp): + """获取指定时间范围内的QA记录数量""" + result = self.execute_query(''' + SELECT COUNT(*) as count + FROM qa as q inner join subscribe as s on q.groupId = s.id + WHERE start_time >= ? + AND end_time <= ? + ''', (f"{start_timestamp}000", f"{end_timestamp}999"), fetch_all=False) + return result["count"] + + def get_non_answer_qa_count_by_time_range_sub(self, start_timestamp, end_timestamp): + """获取指定时间范围内的QA记录数量""" + result = self.execute_query(''' + SELECT COUNT(*) as count + FROM qa as q inner join subscribe as s on q.groupId = s.id + WHERE start_time >= ? + AND end_time <= ? + AND answer = '[]' + ''', (f"{start_timestamp}000", f"{end_timestamp}999"), fetch_all=False) + return result["count"] + def get_group_activity_data(self, start_timestamp, end_timestamp): """获取群组活跃度数据""" return self.execute_query(''' @@ -121,6 +151,16 @@ class ReportService: ORDER BY message_count DESC ''', (f"{start_timestamp}000", f"{end_timestamp}999")) + def get_subscribe_activity_data(self, start_timestamp, end_timestamp): + """获取订阅活跃度数据""" + return self.execute_query(''' + SELECT s.id, s.name, COUNT(m.id) as message_count + FROM subscribe s + LEFT JOIN message m ON s.id = m.receiver AND m.time >= ? AND m.time <= ? + GROUP BY s.id, s.name + ORDER BY message_count DESC + ''', (f"{start_timestamp}000", f"{end_timestamp}999")) + def get_recent_messages_by_time_range(self, start_timestamp, end_timestamp, limit=100): """获取指定时间范围内的最近消息""" return self.execute_query(''' @@ -153,7 +193,17 @@ class ReportService: def get_member_count(self): """获取成员总数""" - result = self.execute_query('SELECT COUNT(*) as count FROM member', fetch_all=False) + result = self.execute_query('SELECT COUNT(*) as count FROM user', fetch_all=False) + return result["count"] + + def get_sub_member_count(self): + """获取成员总数""" + result = self.execute_query('SELECT COUNT(distinct m.userId) as count FROM member as m inner join subscribe as s on m.groupId = s.id ', fetch_all=False) + return result["count"] + + def get_subscribe_count(self): + """获取订阅总数""" + result = self.execute_query('SELECT COUNT(*) as count FROM subscribe', fetch_all=False) return result["count"] def get_qa_count(self): @@ -227,9 +277,13 @@ class ReportService: """获取所有群组""" return self.execute_query('SELECT * FROM "group" ORDER BY id') - def get_group_messages(self, group_id, limit=100, offset=0): - """获取指定群组的消息""" - if not group_id: + def get_all_subscribes(self): + """获取所有订阅""" + return self.execute_query('SELECT * FROM subscribe ORDER BY id') + + def get_subscribe_messages(self, subscribe_id, limit=100, offset=0): + """获取指定订阅的消息""" + if not subscribe_id: query = ''' SELECT m.*, u.name as sender_name, @@ -238,7 +292,7 @@ class ReportService: LEFT JOIN user u ON m.sender = u.id WHERE m.toType = 1 AND m.type NOT IN ('disagree', 'agree', 'weapp', 'link') - ORDER BY formatted_time + ORDER BY formatted_time DESC LIMIT ? OFFSET ? \ ''' return self.execute_query(query, (limit, offset)) @@ -251,7 +305,55 @@ class ReportService: LEFT JOIN user u ON m.sender = u.id WHERE m.receiver = ? AND m.type NOT IN ('disagree', 'agree', 'weapp', 'link') - ORDER BY formatted_time + ORDER BY formatted_time DESC + LIMIT ? OFFSET ? \ + ''' + return self.execute_query(query, (subscribe_id, limit, offset)) + + def get_subscribe_message_count(self, subscribe_id): + """获取指定订阅的消息统计""" + subscribe_messages_total = self.execute_query(''' + SELECT COUNT(*) as count + FROM message + WHERE receiver = ? + AND type NOT IN ('disagree', 'agree', 'weapp', 'link') + ''', (subscribe_id,), fetch_all=False)['count'] + lastest_time = self.execute_query(''' + SELECT datetime(substr(time, 0, 11), 'unixepoch', '+8 hours') as formatted_time + FROM message + WHERE receiver = ? + AND type NOT IN ('disagree', 'agree', 'weapp', 'link') + ORDER BY formatted_time DESC + LIMIT 1 + ''', (subscribe_id,), fetch_all=False) + lastest_time = lastest_time['formatted_time'] if lastest_time else "" + return {'total': subscribe_messages_total, 'lastest_time': lastest_time} + + def get_group_messages(self, group_id, limit=100, offset=0): + """获取指定群组的消息""" + if not group_id: + query = ''' + SELECT m.*, + u.name as sender_name, + datetime(substr(m.time, 0, 11), 'unixepoch', '+8 hours') as formatted_time + FROM message m + LEFT JOIN user u ON m.sender = u.id + WHERE m.toType = 1 + AND m.type NOT IN ('disagree', 'agree', 'weapp', 'link') + ORDER BY formatted_time DESC + LIMIT ? OFFSET ? \ + ''' + return self.execute_query(query, (limit, offset)) + else: + query = ''' + SELECT m.*, + u.name as sender_name, + datetime(substr(m.time, 0, 11), 'unixepoch', '+8 hours') as formatted_time + FROM message m + LEFT JOIN user u ON m.sender = u.id + WHERE m.receiver = ? + AND m.type NOT IN ('disagree', 'agree', 'weapp', 'link') + ORDER BY formatted_time DESC LIMIT ? OFFSET ? \ ''' return self.execute_query(query, (group_id, limit, offset)) @@ -293,6 +395,23 @@ class ReportService: 'latest_time': latest_time } + def get_v2_statistics(self): + """获取v2版本统计数据(包含订阅信息)""" + user_count = self.execute_query('SELECT COUNT(*) as count FROM user as u inner join member as m on u.id = m.userId inner join subscribe as s on m.groupId = s.id', fetch_all=False)['count'] + subscribe_count = self.execute_query('SELECT COUNT(*) as count FROM subscribe', fetch_all=False)['count'] + message_count = self.execute_query('SELECT COUNT(*) as count FROM message as m inner join subscribe as s on m.receiver = s.id', fetch_all=False)['count'] + file_count = self.execute_query('SELECT COUNT(*) as count FROM file as f inner join message as m on f.id = m.content inner join subscribe as s on m.receiver = s.id', fetch_all=False)['count'] + latest_time_result = self.execute_query('SELECT MAX(time) as latest_time FROM message', fetch_all=False) + latest_time = latest_time_result['latest_time'] if latest_time_result else None + + return { + 'user_count': user_count, + 'group_count': subscribe_count, + 'message_count': message_count, + 'file_count': file_count, + 'latest_time': latest_time + } + def search_messages(self, keyword, limit=100, group_id=None): """搜索消息""" if group_id: @@ -327,6 +446,40 @@ class ReportService: ''' return self.execute_query(query, (f'%{keyword}%', limit)) + def search_subscribe_messages(self, keyword, limit=100, subscribe_id=None): + """搜索订阅消息""" + if subscribe_id: + query = ''' + SELECT m.*, + u.name as sender_name, + s.name as subscribe_name, + datetime(substr(m.time, 0, 11), 'unixepoch', '+8 hours') as formatted_time + FROM message m + LEFT JOIN user u ON m.sender = u.id + LEFT JOIN subscribe s ON m.receiver = s.id + WHERE m.content LIKE ? + AND m.type NOT IN ('disagree', 'agree', 'weapp', 'link') + AND m.receiver = ? + ORDER BY formatted_time + LIMIT ? \ + ''' + return self.execute_query(query, (f'%{keyword}%', subscribe_id, limit)) + else: + query = ''' + SELECT m.*, + u.name as sender_name, + s.name as subscribe_name, + datetime(substr(m.time, 0, 11), 'unixepoch', '+8 hours') as formatted_time + FROM message m + LEFT JOIN user u ON m.sender = u.id + LEFT JOIN subscribe s ON m.receiver = s.id + WHERE m.content LIKE ? + AND m.type NOT IN ('disagree', 'agree', 'weapp', 'link') + ORDER BY formatted_time + LIMIT ? \ + ''' + return self.execute_query(query, (f'%{keyword}%', limit)) + def get_all_qa(self): """获取所有QA记录""" return self.execute_query('SELECT * FROM qa ORDER BY id DESC') @@ -489,24 +642,32 @@ def api_response(success=True, data=None, error=None, status_code=200, content=N # 页面路由 @app.route('/') +@app.route('/v1/') +@app.route('/v2/') def index(): """主页面 - 聊天界面""" return render_template('index.html') @app.route('/qa') +@app.route('/v1/qa') +@app.route('/v2/qa') def qa_page(): """问答管理页面""" return render_template('qa.html') @app.route('/weekly_report') +@app.route('/v1/weekly_report') +@app.route('/v2/weekly_report') def weekly_report_page(): """周报页面""" return render_template('weekly_report.html') @app.route('/daily_report') +@app.route('/v1/daily_report') +@app.route('/v2/daily_report') def daily_report_page(): """日报页面""" return render_template('daily_report.html') @@ -555,6 +716,8 @@ def db_download(): # API路由 - 消息相关 @app.route('/api/messages_by_ids', methods=['POST']) +@app.route('/v1/api/messages_by_ids', methods=['POST']) +@app.route('/v2/api/messages_by_ids', methods=['POST']) def get_messages_by_ids(): """根据消息ID列表获取消息内容""" try: @@ -649,6 +812,43 @@ def get_group_messages(): return api_response(success=False, error=e, status_code=500) +# v2 API路由 - 使用与v1相同命名但使用subscribe表 +@app.route('/v2/api/groups') +def get_v2_groups(): + """获取订阅列表API (v2版本,使用subscribe表)""" + try: + subscribes_data = report_service.get_all_subscribes() + groups = [dict(subscribe) for subscribe in subscribes_data] + return api_response(data={'groups': groups}) + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +@app.route('/v2/api/group_messages') +def get_v2_group_messages(): + """获取指定订阅的消息API (v2版本,使用subscribe表)""" + try: + group_id = request.args.get('group_id', type=str) + limit = request.args.get('limit', 100, type=int) + offset = request.args.get('offset', 0, type=int) + + if not group_id: + return api_response(success=False, error='缺少群组ID参数', status_code=400) + + messages_data = report_service.get_subscribe_messages(group_id, limit, offset) + group_messages_info = report_service.get_subscribe_message_count(group_id) + formatted_messages = [] + for msg in messages_data: + message = dict(msg) + message = message_processor.process_message_content(message) + formatted_messages.append(message) + + return api_response(data={'messages': formatted_messages, **group_messages_info}) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + # API路由 - 统计信息 @app.route('/api/statistics') def get_statistics(): @@ -661,6 +861,18 @@ def get_statistics(): return api_response(success=False, error=e, status_code=500) +# v2 API路由 - 统计信息 +@app.route('/v2/api/statistics') +def get_v2_statistics(): + """获取统计数据API (v2版本,使用subscribe表)""" + try: + statistics = report_service.get_v2_statistics() + return api_response(data=statistics) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + # API路由 - 搜索 @app.route('/api/search_messages') def search_messages(): @@ -705,6 +917,50 @@ def search_messages(): return api_response(success=False, error=e, status_code=500) +# v2 API路由 - 搜索 +@app.route('/v2/api/search_messages') +def search_v2_messages(): + """搜索消息API (v2版本,使用subscribe表)""" + 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_subscribe_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, '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(): @@ -766,12 +1022,19 @@ def get_qa_list(): query_params = [] if group_id: - query_conditions.append("groupId LIKE ?") - query_params.append(f"%{group_id}%") + query_conditions.append("groupId = ?") + query_params.append(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"]) + try: + # 将时间字符串转换为时间戳(毫秒级) + start_timestamp = int(TimeUtils(start_time+ ' 00:00:00').to_timestamp() * 1000) + end_timestamp = int(TimeUtils(end_time+' 23:59:59').to_timestamp() * 1000) + query_conditions.append("start_time >= ? AND end_time <= ?") + query_params.extend([start_timestamp, end_timestamp]) + except ValueError: + # 时间格式错误时,忽略时间条件 + pass # 构建查询语句 base_query = "SELECT * FROM qa" @@ -787,27 +1050,26 @@ def get_qa_list(): conn.close() qa_list = [dict(qa) for qa in qa_data] - # 如果有关键词搜索,进行内容过滤 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) + if group_id != qa.get('groupId') and group_id != "": continue # 检查问题内容是否匹配 try: - question_ids = json.loads(qa.get('question', '[]')) + question_ids = json.loads(qa.get('question', '[]')) + json.loads(qa.get('answer', '[]')) 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(): + if keyword.lower() in (msg['content'] or '').lower(): filtered_qa_list.append(qa) break - except: + except Exception as e: + print(e) pass qa_list = filtered_qa_list @@ -848,6 +1110,21 @@ def create_qa(): group_id = data.get('groupId', '') question_ids = data.get('question', []) answer_ids = data.get('answer', []) + + # 处理时间字符串,转换为时间戳(毫秒级) + start_time = data.get('start_time', '') + end_time = data.get('end_time', '') + + try: + if start_time: + start_time = int(TimeUtils(start_time).to_timestamp() * 1000) + if end_time: + end_time = int(TimeUtils(end_time).to_timestamp() * 1000) + except ValueError: + # 时间格式错误时,使用空字符串 + start_time = '' + end_time = '' + conn = db_manager.get_connection() cursor = conn.cursor() index_id = cursor.execute_query(f"SELECT id FROM qa order by id desc limit 1", fetch_all=False)[0] @@ -856,7 +1133,7 @@ def create_qa(): INSERT INTO qa ("id", "groupId", "question", "answer", "start_time", "end_time") VALUES (?, ?, ?, ?, ?, ?) ''', (index_id, group_id, json.dumps(question_ids), json.dumps(answer_ids), - data.get('start_time', ''), data.get('end_time', ''))) + start_time, end_time)) conn.commit() qa_id = cursor.lastrowid @@ -879,6 +1156,19 @@ def update_qa(qa_id): group_id = data.get('groupId', '') question_ids = data.get('question', []) answer_ids = data.get('answer', []) + + # 处理时间字符串,转换为时间戳(毫秒级) + start_time = data.get('start_time', '') + end_time = data.get('end_time', '') + + try: + if start_time: + start_time = int(TimeUtils(start_time).to_timestamp() * 1000) + if end_time: + end_time = int(TimeUtils(end_time).to_timestamp() * 1000) + except ValueError: + # 时间格式错误时,保持原值不更新 + pass # 检查记录是否存在 if not report_service.check_qa_exists(qa_id): @@ -886,14 +1176,26 @@ def update_qa(qa_id): conn = db_manager.get_connection() cursor = conn.cursor() - - cursor.execute(''' - UPDATE qa - SET groupId = ?, - question = ?, - answer = ? - WHERE id = ? - ''', (group_id, json.dumps(question_ids), json.dumps(answer_ids), qa_id)) + + # 如果提供了时间参数,则更新时间字段 + if start_time and end_time: + cursor.execute(''' + UPDATE qa + SET groupId = ?, + question = ?, + answer = ?, + start_time = ?, + end_time = ? + WHERE id = ? + ''', (group_id, json.dumps(question_ids), json.dumps(answer_ids), start_time, end_time, qa_id)) + else: + cursor.execute(''' + UPDATE qa + SET groupId = ?, + question = ?, + answer = ? + WHERE id = ? + ''', (group_id, json.dumps(question_ids), json.dumps(answer_ids), qa_id)) conn.commit() conn.close() @@ -957,6 +1259,474 @@ def batch_delete_qa(): return api_response(success=False, error=e, status_code=500) +# v2 API路由 - QA管理 (使用subscribe表) +@app.route('/v2/api/qa') +def get_v2_qa_list(): + """获取QA列表API (v2版本,使用subscribe表)""" + try: + # 获取查询参数 + 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("a.groupId = ?") + query_params.append(group_id) + + if start_time and end_time: + try: + # 将时间字符串转换为时间戳(毫秒级) + start_timestamp = int(TimeUtils(start_time+ ' 00:00:00').to_timestamp() * 1000) + end_timestamp = int(TimeUtils(end_time+' 23:59:59').to_timestamp() * 1000) + query_conditions.append("a.start_time >= ? AND a.end_time <= ?") + query_params.extend([start_timestamp, end_timestamp]) + except ValueError: + # 时间格式错误时,忽略时间条件 + pass + + # 构建查询语句 + base_query = "SELECT a.* FROM subscribe as s inner join qa as a on a.groupId = s.id" + if query_conditions: + base_query += " WHERE " + " AND ".join(query_conditions) + base_query += " ORDER BY a.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] + # 如果有关键词搜索,进行内容过滤 + if keyword: + filtered_qa_list = [] + for qa in qa_list: + # 检查群组ID是否匹配 + if group_id != qa.get('groupId') and group_id != "": + continue + + # 检查问题内容是否匹配 + try: + question_ids = json.loads(qa.get('question', '[]')) + json.loads(qa.get('answer', '[]')) + if question_ids: + # 获取问题消息内容进行匹配 + messages = report_service.get_messages_by_ids(question_ids) + for msg in messages: + if keyword.lower() in (msg['content'] or '').lower(): + filtered_qa_list.append(qa) + break + except Exception as e: + print(e) + 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) + + +@app.route('/v2/api/qa/') +def get_v2_qa_detail(qa_id): + """获取单个QA详情API (v2版本,使用subscribe表)""" + try: + qa_data = report_service.get_qa_by_id(qa_id) + + if not qa_data: + return api_response(success=False, error='QA记录不存在', status_code=404) + + qa_data = dict(qa_data) + try: + qa_data['question_list'] = json.loads(qa_data['question']) + qa_data['answer_list'] = json.loads(qa_data['answer']) + except: + qa_data['question_list'] = [] + qa_data['answer_list'] = [] + + return api_response(data={'qa': qa_data}) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +@app.route('/v2/api/qa', methods=['POST']) +def create_v2_qa(): + """创建QA记录API (v2版本,使用subscribe表)""" + try: + data = request.get_json() + group_id = data.get('groupId', '') + question_ids = data.get('question', []) + answer_ids = data.get('answer', []) + + # 处理时间字符串,转换为时间戳(毫秒级) + start_time = data.get('start_time', '') + end_time = data.get('end_time', '') + + try: + if start_time: + start_time = int(TimeUtils(start_time).to_timestamp() * 1000) + if end_time: + end_time = int(TimeUtils(end_time).to_timestamp() * 1000) + except ValueError: + # 时间格式错误时,使用空字符串 + start_time = '' + end_time = '' + + conn = db_manager.get_connection() + cursor = conn.cursor() + index_id = cursor.execute_query(f"SELECT id FROM qa order by id desc limit 1", fetch_all=False)[0] + index_id += 1 + cursor.execute(''' + INSERT INTO qa ("id", "groupId", "question", "answer", "start_time", "end_time") + VALUES (?, ?, ?, ?, ?, ?) + ''', (index_id, group_id, json.dumps(question_ids), json.dumps(answer_ids), + start_time, end_time)) + + conn.commit() + qa_id = cursor.lastrowid + conn.close() + + return api_response(data={ + 'id': qa_id, + 'message': 'QA记录创建成功' + }) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +@app.route('/v2/api/qa/', methods=['PUT']) +def update_v2_qa(qa_id): + """更新QA记录API (v2版本,使用subscribe表)""" + try: + data = request.get_json() + group_id = data.get('groupId', '') + question_ids = data.get('question', []) + answer_ids = data.get('answer', []) + + # 处理时间字符串,转换为时间戳(毫秒级) + start_time = data.get('start_time', '') + end_time = data.get('end_time', '') + + try: + if start_time: + start_time = int(TimeUtils(start_time).to_timestamp() * 1000) + if end_time: + end_time = int(TimeUtils(end_time).to_timestamp() * 1000) + except ValueError: + # 时间格式错误时,保持原值不更新 + pass + + # 检查记录是否存在 + if not report_service.check_qa_exists(qa_id): + return api_response(success=False, error='QA记录不存在', status_code=404) + + conn = db_manager.get_connection() + cursor = conn.cursor() + + # 如果提供了时间参数,则更新时间字段 + if start_time and end_time: + cursor.execute(''' + UPDATE qa + SET groupId = ?, + question = ?, + answer = ?, + start_time = ?, + end_time = ? + WHERE id = ? + ''', (group_id, json.dumps(question_ids), json.dumps(answer_ids), start_time, end_time, qa_id)) + else: + cursor.execute(''' + UPDATE qa + SET groupId = ?, + question = ?, + answer = ? + WHERE id = ? + ''', (group_id, json.dumps(question_ids), json.dumps(answer_ids), qa_id)) + + conn.commit() + conn.close() + + return api_response(data={'message': 'QA记录更新成功'}) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +@app.route('/v2/api/qa/', methods=['DELETE']) +def delete_v2_qa(qa_id): + """删除单个QA记录API (v2版本,使用subscribe表)""" + try: + # 检查记录是否存在 + if not report_service.check_qa_exists(qa_id): + return api_response(success=False, error='QA记录不存在', status_code=404) + + conn = db_manager.get_connection() + cursor = conn.cursor() + + cursor.execute('DELETE FROM qa WHERE id = ?', (qa_id,)) + conn.commit() + conn.close() + + return api_response(data={'message': 'QA记录删除成功'}) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +@app.route('/v2/api/qa/batch', methods=['DELETE']) +def batch_delete_v2_qa(): + """批量删除QA记录API (v2版本,使用subscribe表)""" + 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(data={'message': '批量删除QA记录成功'}) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +# v2 API路由 - 报告生成 +@app.route('/v2/api/reports/daily') +def generate_v2_daily_report(): + """生成日报API (v2版本,使用subscribe表)""" + try: + date_str = request.args.get('date', now().to_string(TimeUtils.FORMAT_DATE)) + target_date, start_timestamp, end_timestamp = report_service.get_date_range(date_str) + yesterday_start, yesterday_end = report_service.get_previous_day_range(target_date) + + # 使用ReportService类获取数据 + today_message_count = report_service.get_message_count_by_time_range(start_timestamp, end_timestamp) + yesterday_message_count = report_service.get_message_count_by_time_range(yesterday_start, yesterday_end) + + message_change_rate = report_service.calculate_change_rate( + today_message_count, yesterday_message_count + ) + + # 获取活跃用户数 + today_active_users = report_service.get_active_sub_users_by_time_range(start_timestamp, end_timestamp) + yesterday_active_users = report_service.get_active_sub_users_by_time_range(yesterday_start, yesterday_end) + + user_change_rate = report_service.calculate_change_rate( + today_active_users, yesterday_active_users + ) + + # 获取订阅和成员数量 + subscribe_count = report_service.get_subscribe_count() + member_count = report_service.get_member_count() + + # 获取QA记录数量 + today_qa_count = report_service.get_qa_count_by_time_range_sub(start_timestamp, end_timestamp) + yesterday_qa_count = report_service.get_qa_count_by_time_range_sub(yesterday_start, yesterday_end) + non_qa_count = report_service.get_non_answer_qa_count_by_time_range_sub(start_timestamp, end_timestamp) + qa_change_rate = report_service.calculate_change_rate_sub( + today_qa_count, yesterday_qa_count + ) + + # 获取订阅活跃度 + subscribe_activity_data = report_service.get_subscribe_activity_data(start_timestamp, end_timestamp) + + # 获取热点话题 + recent_messages = report_service.get_recent_messages_by_time_range(start_timestamp, end_timestamp, 100) + hot_topics = report_service.analyze_hot_topics(recent_messages) + # 生成直方图 + subscribe_activity_chart = report_service.generate_group_activity_chart(subscribe_activity_data) + hourly_activity_chart = report_service.generate_hourly_activity_chart(start_timestamp, end_timestamp) + + # 生成日报 + report_date = from_datetime(target_date).format_custom('%Y年%m月%d日 (%A)') + + daily_report = f"""# **致远速联高端社群运营日报** + +**报告周期**:{report_date} +**覆盖范围**:{subscribe_count}个订阅,总计成员 {member_count} 人 + +## **1. 核心数据概览** + +| 指标 | 今日数据 | 昨日数据 | 变化 | +| :--- | :--- | :--- | :--- | +| 总消息量 | {today_message_count} 条 | {yesterday_message_count} 条 | {'↑' if message_change_rate >= 0 else '↓'}{abs(message_change_rate):.1f}% | +| 活跃人数 | {today_active_users} 人 | {yesterday_active_users} 人 | {'↑' if user_change_rate >= 0 else '↓'}{abs(user_change_rate):.1f}% | +| 问题新增记录 | {today_qa_count} 条 | {yesterday_qa_count} 条 | {'↑' if qa_change_rate >= 0 else '↓'}{abs(qa_change_rate):.1f}% | + +## **2. 分订阅活跃度对比** +``` +{subscribe_activity_chart} +``` + +## **3. 今日热点与时段** + +### **热点问题TOP 3**: + +""" + + for i, topic in enumerate(hot_topics, 1): + daily_report += f" {i}. {topic}\n" + + daily_report += f"""### **活跃时段**:消息高峰分布 +``` +{hourly_activity_chart} +``` + +## **4. 待办事项** + +{"有" + str(non_qa_count) + "条未被回答的问题,关注活跃订阅的后续讨论,确保所有疑问被解答。" if non_qa_count > 0 else "无未被回答的问题,继续保持活跃订阅的讨论。"} + +明日重点关注:根据今日热点预测明日可能的问题。 +""" + + return api_response(data={ + 'report': daily_report, + 'date': date_str, + 'statistics': { + 'today_message_count': today_message_count, + 'yesterday_message_count': yesterday_message_count, + 'message_change_rate': message_change_rate, + 'today_active_users': today_active_users, + 'yesterday_active_users': yesterday_active_users, + 'user_change_rate': user_change_rate, + 'today_qa_count': today_qa_count, + 'yesterday_qa_count': yesterday_qa_count, + 'qa_change_rate': qa_change_rate, + 'subscribe_count': subscribe_count, + 'member_count': member_count + } + }) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +@app.route('/v2/api/reports/weekly') +def generate_v2_weekly_report(): + """生成周报API (v2版本,使用subscribe表)""" + try: + week_str = request.args.get('week', now().format_custom('%Y-%W')) + + # 解析week_str参数,格式为YYYY-WW + year, week_num = map(int, week_str.split('-')) + + # 根据周数计算时间范围 + # 获取指定年份的第一天 + first_day_of_year = datetime(year, 1, 1) + # 计算第一周的周一(ISO周从周一开始) + first_monday = first_day_of_year + timedelta(days=(7 - first_day_of_year.weekday()) % 7) + if first_day_of_year.weekday() <= 3: # 如果1月1日是周一到周四,则属于第一周 + first_monday = first_day_of_year - timedelta(days=first_day_of_year.weekday()) + + # 计算指定周的周一 + week_monday = first_monday + timedelta(weeks=week_num - 1) + # 计算指定周的周日 + week_sunday = week_monday + timedelta(days=6) + + start_date = week_monday.replace(hour=0, minute=0, second=0, microsecond=0) + end_date = week_sunday.replace(hour=23, minute=59, second=59, microsecond=999999) + + start_timestamp = int(from_datetime(start_date).to_timestamp()) + end_timestamp = int(from_datetime(end_date).to_timestamp()) + + # 获取上周同期数据 + last_week_start = start_date - timedelta(weeks=1) + last_week_end = end_date - timedelta(weeks=1) + last_week_start_ts = int(from_datetime(last_week_start).to_timestamp()) + last_week_end_ts = int(from_datetime(last_week_end).to_timestamp()) + # 使用ReportService类获取数据 + week_message_count = report_service.get_message_count_by_time_range(start_timestamp, end_timestamp) + last_week_message_count = report_service.get_message_count_by_time_range(last_week_start_ts, last_week_end_ts) + + message_change_rate = report_service.calculate_change_rate( + week_message_count, last_week_message_count + ) + + # 获取活跃用户数 + week_active_users = report_service.get_active_sub_users_by_time_range(start_timestamp, end_timestamp) + + # 获取订阅和成员数量 + subscribe_count = report_service.get_subscribe_count() + member_count = report_service.get_member_count() + + # 获取QA记录数量 + qa_count = report_service.get_qa_count_by_time_range(start_timestamp, end_timestamp) + non_answer_qa_count = report_service.get_non_answer_qa_count_by_time_range(start_timestamp, end_timestamp) + + # 获取本周消息用于分类分析 + week_messages = report_service.get_weekly_messages(start_timestamp, end_timestamp, 200) + + category_breakdown = report_service.analyze_category_breakdown(week_messages) + + # 生成周报 + week_period = f"{from_datetime(start_date).format_custom('%Y年%m月%d日')} - {from_datetime(end_date).format_custom('%Y年%m月%d日')} (第{week_str.split('-')[1]}周)" + + weekly_report = f"""# **致远速联高端社群运营周报** +**报告周期**:{week_period} + + +## **1. 本周摘要** +- 本周社群总消息量 **{week_message_count}条**,{'环比上升' if message_change_rate >= 0 else '环比下降'} **{abs(message_change_rate):.1f}%**。 +- 活跃用户数达到 **{week_active_users}人**,社群参与度良好。 +- 新增问题解答记录 **{qa_count}条**,知识沉淀效果显著。 +- 其中,有 **{non_answer_qa_count}条** 未被回答,值得注意。 + +## **2. 深度洞察:上市公司提问分类** +""" + + # 添加问题分类信息 + for category, percentage in category_breakdown.items(): + weekly_report += f"- {category}:{percentage}%\n" + + weekly_report += f"""\n**洞察**:问题集中在信披和法规,说明成员对合规性高度重视。 + +## **3. 内容价值与知识沉淀** +- **本周高价值问答**:系统自动识别并记录了{qa_count}条有价值的问答记录。 +- **建议**:将高频问答整理至知识库,便于后续参考。 + +""" + result = agent.chat_deepseek(weekly_report, + "根据下面的内容给出总结和建议,格式如下:\n## **4. 总结与建议**\n**总结**:\n**建议**:\n") + return api_response(data={ + 'report': weekly_report + "\n" + result, + 'week': week_str, + 'statistics': { + 'week_message_count': week_message_count, + 'last_week_message_count': last_week_message_count, + 'message_change_rate': message_change_rate, + 'week_active_users': week_active_users, + 'group_count': subscribe_count, + 'member_count': member_count, + 'qa_count': qa_count, + 'category_breakdown': category_breakdown + } + }) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + # API路由 - 报告生成 @app.route('/api/reports/daily') def generate_daily_report(): @@ -1186,4 +1956,4 @@ if __name__ == '__main__': print("问答页面: http://localhost:9000/qa") print("周报页面: http://localhost:9000/weekly_report") print("日报页面: http://localhost:9000/daily_report") - app.run(debug=True, host='0.0.0.0', port=9000) + app.run(debug=True, host='0.0.0.0', port=9000) \ No newline at end of file diff --git a/db/data b/db/data deleted file mode 100644 index 3cdfd85..0000000 Binary files a/db/data and /dev/null differ diff --git a/script.py b/script.py index 3f9e169..bbdb5f5 100644 --- a/script.py +++ b/script.py @@ -97,8 +97,8 @@ if __name__ == '__main__': chat_session = ChatSessionManager(db_manager) month = 12 - day_start = 11 - day_end = 14 + day_start = 15 + day_end = 16 for day in range(day_start, day_end): for hour in range(24): chat_session.process_chat_session(2025, month, day, hour) diff --git a/static/css/index.css b/static/css/index.css index 518b422..8eb54db 100644 --- a/static/css/index.css +++ b/static/css/index.css @@ -211,6 +211,29 @@ body { color: #666; } +.controls { + padding: 20px; + border-bottom: 1px solid #eee; + background: #f8f9fa; + border-radius: 0 0 0 0; + text-align: center; +} + +.load-more { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; + border: none; + padding: 12px 24px; + border-radius: 25px; + cursor: pointer; + font-size: 1em; + transition: transform 0.3s ease; +} + +.load-more:hover { + transform: scale(1.05); +} + .chat-messages { flex: 1; overflow-y: auto; @@ -273,28 +296,6 @@ body { color: rgba(255, 255, 255, 0.8); } -.controls { - padding: 20px; - border-top: 1px solid #eee; - background: #f8f9fa; - border-radius: 0 0 12px 12px; -} - -.load-more { - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - color: white; - border: none; - padding: 12px 24px; - border-radius: 25px; - cursor: pointer; - font-size: 1em; - transition: transform 0.3s ease; -} - -.load-more:hover { - transform: scale(1.05); -} - .loading { text-align: center; padding: 20px; diff --git a/static/js/daily_report.js b/static/js/daily_report.js index 9d290ba..e69125f 100644 --- a/static/js/daily_report.js +++ b/static/js/daily_report.js @@ -54,7 +54,7 @@ function generateReport() { showLoading(); - fetch(`/api/reports/daily?date=${date}`) + fetch(`api/reports/daily?date=${date}`) .then(response => response.json()) .then(data => { hideLoading(); diff --git a/static/js/index.js b/static/js/index.js index 529b03b..cac1e7c 100644 --- a/static/js/index.js +++ b/static/js/index.js @@ -12,7 +12,7 @@ document.addEventListener('DOMContentLoaded', function () { // 加载统计信息 async function loadStatistics() { try { - const response = await fetch('/api/statistics'); + const response = await fetch('api/statistics'); const data = await response.json(); if (data) { const stats = data; @@ -29,7 +29,7 @@ async function loadStatistics() { // 加载按群组分组的消息统计 async function loadGroupMessages() { try { - const response = await fetch('/api/groups'); + const response = await fetch('api/groups'); const data = await response.json(); const groupList = document.getElementById('groupList'); @@ -111,7 +111,6 @@ function selectGroup(groupId) { // 加载更多消息 async function loadMoreMessages() { await loadMessages(); - currentOffset += limit; } // 关闭聊天记录模态框 @@ -198,8 +197,7 @@ async function loadMessages() { chatMessages.innerHTML = '
暂无消息
'; return; } - let url = `/api/group_messages?limit=${limit}&offset=${currentOffset}&group_id=${currentGroupId}`; - + let url = `api/group_messages?limit=${limit}&offset=${currentOffset}&group_id=${currentGroupId}`; const response = await fetch(url); const data = await response.json(); @@ -207,36 +205,32 @@ async function loadMessages() { if (data.success) { const messages = data.messages || []; + if (messages.length === 0) { + if (currentOffset === 0) { + chatMessages.innerHTML = '
暂无消息
'; + } + document.getElementById('messageCountDisplay').textContent = `消息数量: ${data.total || 0}`; + document.getElementById('latestTime').textContent = `最新消息: ${data.lastest_time || '暂无'}`; + return; + } + + // 如果是第一次加载(offset=0),清空消息区域 if (currentOffset === 0) { chatMessages.innerHTML = ''; } - if (messages.length === 0) { - if (currentOffset === 0) { - chatMessages.innerHTML = '
暂无消息
'; - document.getElementById('messageCountDisplay').textContent = `消息数量: 0`; - document.getElementById('latestTime').textContent = `最新消息: 暂无`; - } - - return; - } - + // 将新消息插入到消息区域的开头(向上加载历史消息) messages.forEach(message => { const messageDiv = createMessageElement(message); - if (currentOffset === 0) { - chatMessages.appendChild(messageDiv); - } else { - // 加载更多消息时,插入到现有消息的前面 - chatMessages.insertBefore(messageDiv, chatMessages.firstChild); - } + chatMessages.insertBefore(messageDiv, chatMessages.firstChild); }); + + // 更新偏移量,用于下次加载更多 currentOffset += limit; - document.getElementById('messageCountDisplay').textContent = `消息数量: ${data.total || 0}`; document.getElementById('latestTime').textContent = `最新消息: ${data.lastest_time || '暂无'}`; - } else { chatMessages.innerHTML = '
加载消息失败
'; } diff --git a/static/js/qa.js b/static/js/qa.js index b8bf80e..4b3aff0 100644 --- a/static/js/qa.js +++ b/static/js/qa.js @@ -7,7 +7,7 @@ let groupList = []; // 存储群组列表 // 加载群组列表 async function loadGroupList() { try { - const response = await fetch('/api/groups'); + const response = await fetch('api/groups'); const result = await response.json(); if (result.success) { @@ -100,7 +100,7 @@ async function loadQAList() { const endTime = endDateFilter ? endDateFilter.value : ''; // 构建查询URL - let url = '/api/qa'; + let url = 'api/qa'; const params = new URLSearchParams(); if (keyword) params.append('keyword', keyword); @@ -183,7 +183,7 @@ async function displayQAList(qaList) { let messageMap = {}; if (allMessageIds.length > 0) { try { - const response = await fetch('/api/messages_by_ids', { + const response = await fetch('api/messages_by_ids', { method: 'POST', headers: { 'Content-Type': 'application/json' @@ -280,7 +280,7 @@ async function searchMessages() { const qaListContainer = document.getElementById('qaList'); qaListContainer.innerHTML = '
搜索中...
'; - const response = await fetch(`/api/search_messages?keyword=${encodeURIComponent(keyword)}`); + const response = await fetch(`api/search_messages?keyword=${encodeURIComponent(keyword)}`); const result = await response.json(); if (result.success) { @@ -321,7 +321,7 @@ async function advancedSearch() { if (startDate) params.append('start_time', startDate); if (endDate) params.append('end_time', endDate); - const response = await fetch(`/api/qa?${params.toString()}`); + const response = await fetch(`api/qa?${params.toString()}`); const result = await response.json(); if (result.success) { @@ -411,7 +411,7 @@ async function showSearchSuggestions() { try { // 调用后端API获取搜索建议 - const response = await fetch(`/api/search_suggestions?keyword=${encodeURIComponent(keyword)}`); + const response = await fetch(`api/search_suggestions?keyword=${encodeURIComponent(keyword)}`); const result = await response.json(); if (result.success && result.suggestions.length > 0) { @@ -512,7 +512,7 @@ function openCreateModal() { // 编辑QA async function editQA(qaId) { try { - const response = await fetch(`/api/qa/${qaId}`); + const response = await fetch(`api/qa/${qaId}`); const result = await response.json(); if (result.success) { @@ -620,7 +620,7 @@ async function batchDeleteQA() { } try { - const response = await fetch('/api/qa/batch', { + const response = await fetch('api/qa/batch', { method: 'DELETE', headers: { 'Content-Type': 'application/json' @@ -665,7 +665,7 @@ async function searchQuestionMessages() { 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 url = `api/search_messages?keyword=${encodeURIComponent(keyword)}&limit=20${groupId ? `&group_id=${groupId}` : ''}`; const response = await fetch(url); const result = await response.json(); if (result.success) { @@ -721,7 +721,7 @@ async function searchAnswerMessages() { const groupId = groupIdSelect.value; try { - const url = `/api/search_messages?keyword=${encodeURIComponent(keyword)}&limit=20${groupId ? `&group_id=${groupId}` : ''}`; + const url = `api/search_messages?keyword=${encodeURIComponent(keyword)}&limit=20${groupId ? `&group_id=${groupId}` : ''}`; const response = await fetch(url); const result = await response.json(); @@ -829,7 +829,7 @@ async function saveQA() { }; try { - const url = currentQA ? `/api/qa/${currentQA.id}` : '/api/qa'; + const url = currentQA ? `api/qa/${currentQA.id}` : '/api/qa'; const method = currentQA ? 'PUT' : 'POST'; const response = await fetch(url, { @@ -859,7 +859,7 @@ async function saveQA() { // 预览QA async function previewQA(qaId) { try { - const response = await fetch(`/api/qa/${qaId}`); + const response = await fetch(`api/qa/${qaId}`); const result = await response.json(); if (result.success) { displayPreview(result.qa); @@ -882,7 +882,7 @@ async function displayPreview(qa) { if (allMessageIds.length > 0) { try { - const response = await fetch('/api/messages_by_ids', { + const response = await fetch('api/messages_by_ids', { method: 'POST', headers: { 'Content-Type': 'application/json' @@ -972,7 +972,7 @@ async function deleteQA(qaId) { } try { - const response = await fetch(`/api/qa/${qaId}`, { + const response = await fetch(`api/qa/${qaId}`, { method: 'DELETE' }); diff --git a/static/js/weekly_report.js b/static/js/weekly_report.js index f29ccb1..8d69311 100644 --- a/static/js/weekly_report.js +++ b/static/js/weekly_report.js @@ -69,7 +69,7 @@ function generateReport() { showLoading(); - fetch(`/api/reports/weekly?week=${weekFormatted}`) + fetch(`api/reports/weekly?week=${weekFormatted}`) .then(response => response.json()) .then(data => { hideLoading(); diff --git a/templates/daily_report.html b/templates/daily_report.html index bc8a8eb..5415350 100644 --- a/templates/daily_report.html +++ b/templates/daily_report.html @@ -10,10 +10,10 @@
diff --git a/templates/index.html b/templates/index.html index 8596495..8cbcfaa 100644 --- a/templates/index.html +++ b/templates/index.html @@ -9,10 +9,10 @@

企业微信聊天记录查看器

@@ -61,12 +61,12 @@
-
-
正在加载消息...
+
+
-
- +
+
正在加载消息...
diff --git a/templates/qa.html b/templates/qa.html index 7a0cd81..6492810 100644 --- a/templates/qa.html +++ b/templates/qa.html @@ -9,10 +9,10 @@

问答管理系统

diff --git a/templates/weekly_report.html b/templates/weekly_report.html index a2189f8..e1cf5b1 100644 --- a/templates/weekly_report.html +++ b/templates/weekly_report.html @@ -9,10 +9,10 @@