diff --git a/app.py b/app.py index 58a0e1c..377c46c 100644 --- a/app.py +++ b/app.py @@ -1,345 +1,507 @@ from flask import Flask, render_template, jsonify, request import sqlite3 import json -from datetime import datetime import os - -app = Flask(__name__) - -# 数据库文件路径 -DB_PATH = 'data.sqlite' +from tools import TimeUtils, now, from_string, from_datetime, format_timestamp -def get_db_connection(): - """获取数据库连接""" - conn = sqlite3.connect(DB_PATH) - conn.row_factory = sqlite3.Row - return conn +class DatabaseManager: + """数据库管理类""" + + def __init__(self, db_path='db/data.sqlite'): + self.db_path = db_path + + def get_connection(self): + """获取数据库连接""" + conn = sqlite3.connect(self.db_path) + conn.row_factory = sqlite3.Row + return conn + + def execute_query(self, query, params=None, fetch_all=True): + """执行查询并返回结果""" + conn = self.get_connection() + cursor = conn.cursor() + + try: + if params: + cursor.execute(query, params) + else: + cursor.execute(query) + + if fetch_all: + result = cursor.fetchall() + else: + result = cursor.fetchone() + + conn.close() + return result + except Exception as e: + print(e) + conn.close() + raise e -@app.route('/') -def index(): - """主页面 - 聊天界面""" - return render_template('index.html') +class MessageRender: + """消息处理类""" + + @staticmethod + def format_timestamp(timestamp_str): + """格式化时间戳""" + if not timestamp_str: + return '未知时间' + + try: + timestamp = int(timestamp_str[:-3]) + return format_timestamp(timestamp) + except ValueError: + return '未知时间' + + @staticmethod + def process_message_content(message_data): + """处理消息内容""" + content = message_data['content'] + msg_type = message_data['type'] + + if msg_type == 'text': + message_data['display_content'] = content + elif msg_type in ['image', 'file', 'video', 'voice']: + message_data['display_content'] = f'[{msg_type}] {content}' + elif msg_type == 'mixed': + try: + mixed_content = json.loads(content) + display_parts = [] + for item in mixed_content: + msg_type, item_content = item + if msg_type == 'text': + display_parts.append(item_content) + else: + display_parts.append(f'[{msg_type}]') + message_data['display_content'] = ' '.join(display_parts) + except: + message_data['display_content'] = '[混合消息]' + elif msg_type == 'chatrecord': + try: + chatrecord_data = json.loads(content) + if 'chatrecord' in chatrecord_data and 'title' in chatrecord_data['chatrecord']: + message_data['display_content'] = f'[聊天记录] {chatrecord_data["chatrecord"]["title"]}' + message_data['chatrecord_data'] = chatrecord_data + else: + message_data['display_content'] = '[聊天记录]' + except: + message_data['display_content'] = '[聊天记录]' + else: + message_data['display_content'] = f'[{msg_type}] {content}' + + return message_data -@app.route('/api/messages_by_ids', methods=['POST']) -def get_messages_by_ids(): - """根据消息ID列表获取消息内容""" - try: - data = request.get_json() - message_ids = data.get('message_ids', []) +class ReportService(DatabaseManager): + """报告服务类""" + # 数据查询方法 (原ReportData功能) + def get_message_count_by_time_range(self, start_timestamp, end_timestamp): + """获取指定时间范围内的消息数量""" + result = self.execute_query(''' + SELECT COUNT(*) as count + FROM message + WHERE time >= ? + AND time <= ? + ''', (f"{start_timestamp}000", f"{end_timestamp}999"), fetch_all=False) + return result["count"] + + def get_active_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(''' + SELECT COUNT(*) as count + FROM qa + WHERE start_time >= ? + AND start_time <= ? + ''', (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(''' + SELECT g.id, g.name, COUNT(m.id) as message_count + FROM "group" g + LEFT JOIN message m ON g.id = m.receiver AND m.time >= ? AND m.time <= ? + GROUP BY g.id, g.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(''' + SELECT content + FROM message + WHERE time >= ? + AND time <= ? + AND type NOT IN ('disagree', 'agree', 'weapp', 'link') + ORDER BY time + LIMIT ? + ''', (f"{start_timestamp}000", f"{end_timestamp}999", limit)) + + def get_hourly_activity_data(self, start_timestamp, end_timestamp): + """获取按小时统计的消息量""" + return self.execute_query(''' + SELECT strftime('%H', + datetime(substr(time, 0, 11), 'unixepoch', 'localtime')) as hour, + COUNT(*) as count + FROM message + WHERE time >= ? + AND time <= ? + GROUP BY hour + ORDER BY hour + ''', (f"{start_timestamp}000", f"{end_timestamp}999")) + + def get_group_count(self): + """获取群组总数""" + result = self.execute_query('SELECT COUNT(*) as count FROM "group"', fetch_all=False) + return result["count"] + + def get_member_count(self): + """获取成员总数""" + result = self.execute_query('SELECT COUNT(*) as count FROM member', fetch_all=False) + return result["count"] + + def get_qa_count(self): + """获取QA记录总数""" + result = self.execute_query('SELECT COUNT(*) as count FROM qa', fetch_all=False) + return result["count"] + + def get_weekly_messages(self, start_timestamp, end_timestamp, limit=200): + """获取本周消息用于分类分析""" + return self.execute_query(''' + SELECT content + FROM message + WHERE time >= ? + AND time <= ? + AND type NOT IN ('disagree', 'agree', 'weapp', 'link') + ORDER BY time + LIMIT ? + ''', (f"{start_timestamp}000", f"{end_timestamp}999", limit)) + + # 通用数据查询方法 (整合剩余数据库查询) + def get_messages_by_ids(self, message_ids): + """根据消息ID列表获取消息内容""" if not message_ids: - return jsonify({ - 'success': True, - 'messages': [] - }) + return [] - conn = get_db_connection() - cursor = conn.cursor() - - # 构建IN查询的占位符 placeholders = ','.join(['?'] * len(message_ids)) - query = f"SELECT id, content, type,sender,receiver,datetime(substr(time,0,11), 'unixepoch','localtime') as formatted_time FROM message WHERE id IN ({placeholders}) order by time" + query = f""" + SELECT id, content, type, sender, receiver, + datetime(substr(time,0,11), 'unixepoch','localtime') as formatted_time + FROM message + WHERE id IN ({placeholders}) + AND type NOT IN ('disagree', 'agree', 'weapp', 'link') + ORDER BY formatted_time + """ + return self.execute_query(query, message_ids) - cursor.execute(query, message_ids) - messages_data = cursor.fetchall() - - messages = [dict(msg) for msg in messages_data] - - conn.close() - - return jsonify({ - 'success': True, - 'messages': messages - }) - - except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 - - -@app.route('/api/messages') -def get_messages(): - """获取消息列表API""" - try: - conn = get_db_connection() - cursor = conn.cursor() - - # 获取查询参数 - limit = request.args.get('limit', 100, type=int) - offset = request.args.get('offset', 0, type=int) - group_id = request.args.get('group_id', type=str) - - # 构建查询条件 + def get_messages(self, limit=100, offset=0, group_id=None): + """获取消息列表""" query = ''' - SELECT m.*, u.name as sender_name, g.name as group_name + SELECT m.*, + u.name as sender_name, + g.name as group_name, + datetime(substr(time, 0, 11), 'unixepoch', 'localtime') as formatted_time FROM message m LEFT JOIN user u ON m.sender = u.id LEFT JOIN "group" g ON m.receiver = g.id - where m.type NOT IN ('disagree', 'agree', 'webapp', 'link') \ + WHERE m.type NOT IN ('disagree', 'agree', 'weapp', 'link') + AND m.toType = 1 ''' params = [] if group_id: - query += ' AND g.id = ?' + query += ' AND m.receiver = ?' params.append(group_id) - query += ' ORDER BY m.time ASC LIMIT ? OFFSET ?' + query += ' ORDER BY formatted_time DESC LIMIT ? OFFSET ?' params.extend([limit, offset]) - # 查询消息数据 - cursor.execute(query, params) - messages = cursor.fetchall() - # 格式化消息数据 - formatted_messages = [] - for msg in messages: - message_data = dict(msg) + return self.execute_query(query, params) - # 处理时间戳 - if message_data['time']: - try: - timestamp = int(message_data['time'][:-3]) - message_data['formatted_time'] = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') - except: - message_data['formatted_time'] = '未知时间' + def get_all_users(self): + """获取所有用户""" + return self.execute_query('SELECT * FROM user ORDER BY name') - # 处理消息内容 - content = message_data['content'] - if message_data['type'] == 'text': - message_data['display_content'] = content - elif message_data['type'] in ['image', 'file', 'video', 'voice']: - message_data['display_content'] = f'[{message_data["type"]}] {content}' - elif message_data['type'] == 'mixed': - try: - mixed_content = json.loads(content) - display_parts = [] - for item in mixed_content: - msg_type, item_content = item - if msg_type == 'text': - display_parts.append(item_content) - else: - display_parts.append(f'[{msg_type}]') - message_data['display_content'] = ' '.join(display_parts) - except: - message_data['display_content'] = '[混合消息]' - elif message_data['type'] == 'chatrecord': - try: - chatrecord_data = json.loads(content) - if 'chatrecord' in chatrecord_data and 'title' in chatrecord_data['chatrecord']: - message_data['display_content'] = f'[聊天记录] {chatrecord_data["chatrecord"]["title"]}' - message_data['chatrecord_data'] = chatrecord_data # 保存完整数据供前端使用 - else: - message_data['display_content'] = '[聊天记录]' - except: - message_data['display_content'] = '[聊天记录]' - else: - message_data['display_content'] = f'[{message_data["type"]}] {content}' + def get_all_groups(self): + """获取所有群组""" + return self.execute_query('SELECT * FROM "group" ORDER BY id') - formatted_messages.append(message_data) - - conn.close() - - return jsonify({ - 'success': True, - 'messages': formatted_messages, - 'total': len(formatted_messages) - }) - - except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 - - -@app.route('/api/users') -def get_users(): - """获取用户列表API""" - try: - conn = get_db_connection() - cursor = conn.cursor() - - cursor.execute('SELECT * FROM user ORDER BY name') - users = cursor.fetchall() - - user_list = [dict(user) for user in users] - - conn.close() - - return jsonify({ - 'success': True, - 'users': user_list - }) - - except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 - - -@app.route('/api/groups') -def get_groups(): - """获取群组列表API""" - try: - conn = get_db_connection() - cursor = conn.cursor() - - cursor.execute('SELECT * FROM "group" ORDER BY id') - groups = cursor.fetchall() - - group_list = [dict(group) for group in groups] - - conn.close() - - return jsonify({ - 'success': True, - 'groups': group_list - }) - - except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 - - -@app.route('/api/group_messages') -def get_group_messages(): - """获取按群组分组的消息统计API""" - try: - conn = get_db_connection() - cursor = conn.cursor() - - # 获取每个群组的消息统计 - cursor.execute(''' - SELECT g.id as group_id, - g.name as group_name, - COUNT(m.id) as message_count, - MAX(m.time) as latest_message_time, - COUNT(DISTINCT m.sender) as member_count - FROM "group" g - LEFT JOIN message m ON g.id = m.receiver - WHERE m.toType = 1 - GROUP BY g.id, g.name - ORDER BY latest_message_time DESC - ''') - - groups = cursor.fetchall() - group_list = [] - for group in groups: - group_data = dict(group) - - # 处理最新消息时间 - if group_data['latest_message_time']: - try: - timestamp = int(group_data['latest_message_time'][:-3]) - group_data['latest_message_time_formatted'] = datetime.fromtimestamp(timestamp).strftime( - '%Y-%m-%d %H:%M:%S') - - except Exception as e: - print(f"时间转换错误: {e}") - group_data['latest_message_time_formatted'] = '未知时间' - else: - group_data['latest_message_time_formatted'] = '暂无消息' - - group_list.append(group_data) - - conn.close() - - return jsonify({ - 'success': True, - 'groups': group_list - }) - - except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 - - -@app.route('/api/statistics') -def get_statistics(): - """获取统计信息API""" - try: - conn = get_db_connection() - cursor = conn.cursor() - - # 获取用户数量 - cursor.execute('SELECT COUNT(*) as count FROM user') - user_count = cursor.fetchone()['count'] - - # 获取群组数量 - cursor.execute('SELECT COUNT(*) as count FROM "group"') - group_count = cursor.fetchone()['count'] - - # 获取消息数量 - cursor.execute('SELECT COUNT(*) as count FROM message') - message_count = cursor.fetchone()['count'] - - # 获取文件数量 - cursor.execute('SELECT COUNT(*) as count FROM file') - file_count = cursor.fetchone()['count'] - - # 获取最新消息时间 - cursor.execute('SELECT MAX(time) as latest_time FROM message') - latest_time_result = cursor.fetchone() - latest_time = latest_time_result['latest_time'] if latest_time_result['latest_time'] else None - - if latest_time: - try: - latest_time_formatted = datetime.fromtimestamp(int(latest_time)).strftime('%Y-%m-%d %H:%M:%S') - except: - latest_time_formatted = '未知时间' + 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', 'localtime') 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 + LIMIT ? OFFSET ? \ + ''' + return self.execute_query(query, (limit, offset)) else: - latest_time_formatted = '暂无消息' + query = ''' + SELECT m.*, + u.name as sender_name, + datetime(substr(m.time, 0, 11), 'unixepoch', 'localtime') 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 + LIMIT ? OFFSET ? \ + ''' + return self.execute_query(query, (group_id, limit, offset)) - conn.close() + def get_group_message_count(self, group_id): + """获取指定群组的消息""" - return jsonify({ - 'success': True, - 'statistics': { - 'user_count': user_count, - 'group_count': group_count, - 'message_count': message_count, - 'file_count': file_count, - 'latest_message_time': latest_time_formatted - } - }) + group_messages_total = self.execute_query(''' + SELECT COUNT(*) as count + FROM message + WHERE receiver = ? + AND type NOT IN ('disagree', 'agree', 'weapp', 'link') + ''', (group_id,), fetch_all=False)['count'] + print(group_messages_total) + lastest_time = self.execute_query(''' + SELECT datetime(substr(time, 0, 11), 'unixepoch', 'localtime') as formatted_time + FROM message + WHERE receiver = ? + AND type NOT IN ('disagree', 'agree', 'weapp', 'link') + ORDER BY formatted_time DESC + LIMIT 1 + ''', (group_id,), fetch_all=False) + lastest_time = lastest_time['formatted_time'] if lastest_time else "" + return {'total': group_messages_total, 'lastest_time': lastest_time} - except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 + def get_statistics(self): + """获取统计数据""" + user_count = self.execute_query('SELECT COUNT(*) as count FROM user', fetch_all=False)['count'] + group_count = self.execute_query('SELECT COUNT(*) as count FROM "group"', fetch_all=False)['count'] + message_count = self.execute_query('SELECT COUNT(*) as count FROM message', fetch_all=False)['count'] + file_count = self.execute_query('SELECT COUNT(*) as count FROM file', 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': group_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: + query = ''' + SELECT m.*, + u.name as sender_name, + g.name as group_name, + datetime(substr(m.time, 0, 11), 'unixepoch', 'localtime') as formatted_time + FROM message m + LEFT JOIN user u ON m.sender = u.id + LEFT JOIN "group" g ON m.receiver = g.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}%', group_id, limit)) + else: + query = ''' + SELECT m.*, + u.name as sender_name, + g.name as group_name, + datetime(substr(m.time, 0, 11), 'unixepoch', 'localtime') as formatted_time + FROM message m + LEFT JOIN user u ON m.sender = u.id + LEFT JOIN "group" g ON m.receiver = g.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') + + def get_qa_by_id(self, qa_id): + """根据ID获取QA记录""" + return self.execute_query('SELECT * FROM qa WHERE id = ?', (qa_id,), fetch_all=False) + + def check_qa_exists(self, qa_id): + """检查QA记录是否存在""" + result = self.execute_query('SELECT id FROM qa WHERE id = ?', (qa_id,), fetch_all=False) + return result is not None + + # 报告生成方法 (原ReportGenerator功能) + @staticmethod + def get_date_range(date_str): + """获取日期范围""" + target_date = from_string(date_str).to_datetime() + start_timestamp = int(from_string(date_str).start_of_day().to_timestamp()) + end_timestamp = int(from_string(date_str).end_of_day().to_timestamp()) + return target_date, start_timestamp, end_timestamp + + @staticmethod + def get_previous_day_range(target_date): + """获取前一天日期范围""" + yesterday_date = from_datetime(target_date).days_ago(1) + yesterday_start = int(yesterday_date.start_of_day().to_timestamp()) + yesterday_end = int(yesterday_date.end_of_day().to_timestamp()) + return yesterday_start, yesterday_end + + @staticmethod + def calculate_change_rate(current, previous): + """计算变化率""" + if previous > 0: + return (current - previous) / previous * 100 + return 0 + + @staticmethod + def analyze_hot_topics(messages): + """分析热点话题""" + keyword_patterns = ['季度报告', 'ESG', '股东大会', '披露', '系统', '操作', '政策'] + topic_counts = {} + + for msg in messages: + content = msg['content'] + for keyword in keyword_patterns: + if keyword in content: + topic_counts[keyword] = topic_counts.get(keyword, 0) + 1 + + # 排序并取前3个热点 + sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True) + return [f"{topic} (提及{count}次)" for topic, count in sorted_topics[:3]] + + @staticmethod + def analyze_category_breakdown(messages): + """分析问题分类""" + category_counts = { + '信息披露类': 0, + '公司治理与法规': 0, + '业务操作与系统': 0, + '其他': 0 + } + + category_keywords = { + '信息披露类': ['披露', '报告', '公告', '季报', '年报', 'ESG'], + '公司治理与法规': ['法规', '合规', '治理', '政策', '规定', '要求'], + '业务操作与系统': ['系统', '操作', '填报', '上传', '下载', '登录'] + } + + for msg in messages: + content = msg['content'] + categorized = False + for category, keywords in category_keywords.items(): + for keyword in keywords: + if keyword in content: + category_counts[category] += 1 + categorized = True + break + if categorized: + break + if not categorized: + category_counts['其他'] += 1 + + # 计算百分比 + total_categorized = sum(category_counts.values()) + if total_categorized > 0: + for category in category_counts: + category_counts[category] = round(category_counts[category] / total_categorized * 100, 1) + + return category_counts + + @staticmethod + def generate_group_activity_chart(group_activity_data): + """生成分群活跃度直方图""" + if not group_activity_data: + return "暂无数据" + + # 获取前10个群组的数据 + top_groups = group_activity_data[:10] + max_count = max(group['message_count'] for group in top_groups) if top_groups else 1 + + chart = "" + for group in top_groups: + group_name = group['name'] # 限制名称长度 + count = group['message_count'] + # 计算柱状图长度(最大50个字符) + bar_length = int((count / max_count) * 50) if max_count > 0 else 0 + bar = "█" * bar_length + chart += f"{group_name:<15} | {bar} {count}\n" + + return chart + + def generate_hourly_activity_chart(self, start_timestamp, end_timestamp): + """生成活跃时段直方图""" + # 获取按小时统计的消息量 + hourly_data = self.get_hourly_activity_data(start_timestamp, end_timestamp) + + if not hourly_data: + return "暂无数据" + + # 创建24小时的完整数据 + hour_counts = {str(i).zfill(2): 0 for i in range(24)} + for data in hourly_data: + hour_counts[data['hour']] = data['count'] + + max_count = max(hour_counts.values()) if hour_counts else 1 + + chart = "" + for hour in sorted(hour_counts.keys()): + count = hour_counts[hour] + # 计算柱状图长度(最大30个字符) + bar_length = int((count / max_count) * 30) if max_count > 0 else 0 + bar = "█" * bar_length + chart += f"{hour}:00 | {bar} {count}\n" + + return chart -def init_qa_table(): - """初始化qa表""" - try: - conn = get_db_connection() - cursor = conn.cursor() - - # 检查qa表是否存在,如果不存在则创建 - cursor.execute(""" - CREATE TABLE IF NOT EXISTS qa ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - groupId TEXT, - question JSON DEFAULT '[]' NOT NULL, - answer JSON DEFAULT '[]' NOT NULL - ) - """) - - conn.commit() - conn.close() - print("qa表初始化完成") - except Exception as e: - print(f"初始化qa表时出错: {e}") +app = Flask(__name__) +app.template_folder = 'templates' +# 初始化管理器 +db_manager = DatabaseManager() +report_service = ReportService() +message_processor = MessageRender() + + +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) + return jsonify(response), status_code + + +# 页面路由 +@app.route('/') +def index(): + """主页面 - 聊天界面""" + return render_template('index.html') @app.route('/qa') @@ -348,82 +510,186 @@ def qa_page(): return render_template('qa.html') +@app.route('/weekly_report') +def weekly_report_page(): + """周报页面""" + return render_template('weekly_report.html') + + +@app.route('/daily_report') +def daily_report_page(): + """日报页面""" + return render_template('daily_report.html') + + +# API路由 - 消息相关 +@app.route('/api/messages_by_ids', methods=['POST']) +def get_messages_by_ids(): + """根据消息ID列表获取消息内容""" + try: + data = request.get_json() + message_ids = data.get('message_ids', []) + + if not message_ids: + return api_response(data={'messages': []}) + + messages_data = report_service.get_messages_by_ids(message_ids) + 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}) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +@app.route('/api/messages') +def get_messages(): + """获取消息列表API""" + try: + limit = request.args.get('limit', 100, type=int) + offset = request.args.get('offset', 0, type=int) + group_id = request.args.get('group_id', type=str) + + messages_data = report_service.get_messages(limit, offset, 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, + 'total': len(formatted_messages) + }) + + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +# API路由 - 用户和群组 +@app.route('/api/users') +def get_users(): + """获取用户列表API""" + try: + users_data = report_service.get_all_users() + users = [dict(user) for user in users_data] + return api_response(data={'users': users}) + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +@app.route('/api/groups') +def get_groups(): + """获取群组列表API""" + try: + groups_data = report_service.get_all_groups() + groups = [dict(group) for group in groups_data] + return api_response(data={'groups': groups}) + except Exception as e: + return api_response(success=False, error=e, status_code=500) + + +@app.route('/api/group_messages') +def get_group_messages(): + """获取指定群组的消息API""" + 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_group_messages(group_id, limit, offset) + print(group_id) + group_messages_info = report_service.get_group_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: + print(e) + return api_response(success=False, error=e, status_code=500) + + +# API路由 - 统计信息 +@app.route('/api/statistics') +def get_statistics(): + """获取统计数据API""" + try: + statistics = report_service.get_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(): + """搜索消息API""" + try: + keyword = request.args.get('keyword', '') + limit = request.args.get('limit', 100, type=int) + + 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) + 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}) + + 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: - conn = get_db_connection() - cursor = conn.cursor() - - cursor.execute('SELECT * FROM qa ORDER BY id DESC') - qa_list = cursor.fetchall() - - result = [] - for qa in qa_list: - qa_data = dict(qa) - - # 解析JSON字段 - 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'] = [] - - result.append(qa_data) - - conn.close() - - return jsonify({ - 'success': True, - 'qa_list': result - }) - + qa_data = report_service.get_all_qa() + qa_list = [dict(qa) for qa in qa_data] + return api_response(data={'qa_list': qa_list}) except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 + return api_response(success=False, error=e, status_code=500) @app.route('/api/qa/') def get_qa_detail(qa_id): """获取单个QA详情API""" try: - conn = get_db_connection() - cursor = conn.cursor() - - cursor.execute('SELECT * FROM qa WHERE id = ?', (qa_id,)) - qa = cursor.fetchone() - - if not qa: - return jsonify({ - 'success': False, - 'error': 'QA记录不存在' - }), 404 - - qa_data = dict(qa) - - # 解析JSON字段 + 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'] = [] - - conn.close() - - return jsonify({ - 'success': True, - 'qa': qa_data - }) - + + return api_response(data={'qa': qa_data}) + except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 + return api_response(success=False, error=e, status_code=500) @app.route('/api/qa', methods=['POST']) @@ -431,34 +697,29 @@ def create_qa(): """创建QA记录API""" try: data = request.get_json() - group_id = data.get('groupId', '') question_ids = data.get('question', []) answer_ids = data.get('answer', []) - - conn = get_db_connection() + + 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) + VALUES (?, ?, ?) + ''', (group_id, json.dumps(question_ids), json.dumps(answer_ids))) + conn.commit() qa_id = cursor.lastrowid conn.close() - - return jsonify({ - 'success': True, + + return api_response(data={ 'id': qa_id, 'message': 'QA记录创建成功' }) - + except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 + return api_response(success=False, error=e, status_code=500) @app.route('/api/qa/', methods=['PUT']) @@ -466,140 +727,272 @@ def update_qa(qa_id): """更新QA记录API""" try: data = request.get_json() - group_id = data.get('groupId', '') question_ids = data.get('question', []) answer_ids = data.get('answer', []) - - conn = get_db_connection() - cursor = conn.cursor() - + # 检查记录是否存在 - cursor.execute('SELECT id FROM qa WHERE id = ?', (qa_id,)) - if not cursor.fetchone(): - return jsonify({ - 'success': False, - 'error': 'QA记录不存在' - }), 404 - + 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(''' - UPDATE qa - SET groupId = ?, question = ?, answer = ? - WHERE id = ? - ''', (group_id, json.dumps(question_ids), json.dumps(answer_ids), qa_id)) - + 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 jsonify({ - 'success': True, - 'message': 'QA记录更新成功' - }) - + + return api_response(data={'message': 'QA记录更新成功'}) + except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 + return api_response(success=False, error=e, status_code=500) @app.route('/api/qa/', methods=['DELETE']) def delete_qa(qa_id): """删除QA记录API""" try: - conn = get_db_connection() - cursor = conn.cursor() - # 检查记录是否存在 - cursor.execute('SELECT id FROM qa WHERE id = ?', (qa_id,)) - if not cursor.fetchone(): - return jsonify({ - 'success': False, - 'error': 'QA记录不存在' - }), 404 - + 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 jsonify({ - 'success': True, - 'message': 'QA记录删除成功' - }) - + + return api_response(data={'message': 'QA记录删除成功'}) + except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 + return api_response(success=False, error=e, status_code=500) -@app.route('/api/search_messages') -def search_messages(): - """搜索消息API""" +# API路由 - 报告生成 +@app.route('/api/reports/daily') +def generate_daily_report(): + """生成日报API""" try: - keyword = request.args.get('keyword', '') - limit = request.args.get('limit', 50, type=int) - group_id = request.args.get('groupId', '') - if not keyword: - return jsonify({ - 'success': True, - 'messages': [] - }) - - conn = get_db_connection() - cursor = conn.cursor() - - cursor.execute(''' - SELECT id, content, type, time, sender, receiver - FROM message - WHERE content LIKE ? - AND type NOT IN ('disagree', 'agree', 'webapp', 'link') - ORDER BY time DESC - LIMIT ? - ''', (f'%{keyword}%', limit)) - - messages = cursor.fetchall() - - result = [] - for msg in messages: - message_data = dict(msg) - - # 处理时间戳 - if message_data['time']: - try: - timestamp = int(message_data['time'][:-3]) - message_data['formatted_time'] = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') - except: - message_data['formatted_time'] = '未知时间' - - result.append(message_data) - - conn.close() - - return jsonify({ - 'success': True, - 'messages': result + 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_users_by_time_range(start_timestamp, end_timestamp) + yesterday_active_users = report_service.get_active_users_by_time_range(yesterday_start, yesterday_end) + + user_change_rate = report_service.calculate_change_rate( + today_active_users, yesterday_active_users + ) + + # 获取群组和成员数量 + group_count = report_service.get_group_count() + member_count = report_service.get_member_count() + + # 获取QA记录数量 + today_qa_count = report_service.get_qa_count_by_time_range(start_timestamp, end_timestamp) + yesterday_qa_count = report_service.get_qa_count_by_time_range(yesterday_start, yesterday_end) + + qa_change_rate = report_service.calculate_change_rate( + today_qa_count, yesterday_qa_count + ) + + # 获取群组活跃度 + group_activity_data = report_service.get_group_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) + + # 生成直方图 + group_activity_chart = report_service.generate_group_activity_chart(group_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} +**覆盖范围**:{group_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. 分群活跃度对比** +``` +{group_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. 待办事项** +* 关注活跃群组的后续讨论,确保所有疑问被解答。 +* 明日重点关注:根据今日热点预测明日可能的问题。 +""" + + 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, + 'group_count': group_count, + 'member_count': member_count + } }) - + except Exception as e: - return jsonify({ - 'success': False, - 'error': str(e) - }), 500 + return api_response(success=False, error=e, status_code=500) + + +@app.route('/api/reports/weekly') +def generate_weekly_report(): + """生成周报API""" + try: + week_str = request.args.get('week', now().format_custom('%Y-%W')) + + # 简化周计算(实际应该使用更精确的周计算) + base_date = now() + start_date = base_date.days_ago(base_date.to_datetime().weekday()).start_of_day().to_datetime() + end_date = base_date.days_after(6 - base_date.to_datetime().weekday()).end_of_day().to_datetime() + + start_timestamp = int(from_datetime(start_date).to_timestamp()) + end_timestamp = int(from_datetime(end_date).to_timestamp()) + + # 获取上周同期数据 + last_week_start = from_datetime(start_date).days_ago(7).to_datetime() + last_week_end = from_datetime(end_date).days_ago(7).to_datetime() + last_week_start_ts = int(from_datetime(last_week_start).start_of_day().to_timestamp()) + last_week_end_ts = int(from_datetime(last_week_end).end_of_day().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_users_by_time_range(start_timestamp, end_timestamp) + + # 获取群组和成员数量 + group_count = report_service.get_group_count() + member_count = report_service.get_member_count() + + # 获取QA记录数量 + qa_count = report_service.get_qa_count() + + # 获取本周消息用于分类分析 + 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}条**,知识沉淀效果显著。 + +**2. 深度洞察:上市公司提问分类** +*(此处插入一个环形图)* +""" + + # 添加问题分类信息 + for category, percentage in category_breakdown.items(): + weekly_report += f"* {category}:{percentage}%\n" + + weekly_report += f"""* 洞察:问题集中在信披和法规,说明成员对合规性高度重视。 + +**3. 内容价值与知识沉淀** +* **本周高价值问答**:系统自动识别并记录了{qa_count}条有价值的问答记录。 +* **建议**:将高频问答整理至知识库,便于后续参考。 + +**4. 总结与建议** +* **总结**:本周运营状况良好,有效支撑了成员的信息需求。 +* **建议**: +1. **内容优化**:根据本周热点问题,下周可准备相关专题解读。 +2. **流程优化**:继续完善问答记录和知识沉淀流程。 +3. **数据分析**:加强数据监控,及时发现运营问题。 +""" + + return api_response(data={ + 'report': weekly_report, + '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': group_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) if __name__ == '__main__': # 检查数据库文件是否存在 - if not os.path.exists(DB_PATH): - print(f"错误: 数据库文件 {DB_PATH} 不存在") + if not os.path.exists('db/data.sqlite'): + print(f"错误: 数据库文件 db/data.sqlite 不存在") print("请确保data.sqlite文件在当前目录下") else: - # 初始化qa表 - init_qa_table() - print("启动聊天网页服务...") print("访问地址: http://127.0.0.1:5000") print("问答页面: http://127.0.0.1:5000/qa") - app.run(debug=True, host='127.0.0.1', port=5000) \ No newline at end of file + print("周报页面: http://127.0.0.1:5000/weekly_report") + print("日报页面: http://127.0.0.1:5000/daily_report") + app.run(debug=True, host='127.0.0.1', port=5000) diff --git a/chat_session.py b/chat_session.py index 77ebbb8..1d1770f 100644 --- a/chat_session.py +++ b/chat_session.py @@ -3,7 +3,12 @@ import json import os.path import sqlite3 from typing import List, Tuple +import logging +import os +import requests +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry import pytz from file import ObjectFileManager, LocalFileManager @@ -27,6 +32,133 @@ def convert_to_utc(time_str, time_format='%Y-%m-%d %H:%M:%S', source_timezone=No return utc_dt +class AIAgent: + """AI代理类,整合了各种AI功能""" + + def __init__(self, deepseek_api_key: str = "sk-c2f04b4d635b4df0aace0432f3c6d6f4", + max_retries: int = 3, timeout: int = 30): + """初始化AI助手 + + Args: + deepseek_api_key: DeepSeek API密钥 + max_retries: 最大重试次数 + timeout: 请求超时时间(秒) + """ + self.deepseek_api_key = deepseek_api_key + self.timeout = timeout + + # 配置日志 + self._setup_logging() + + # 创建带重试机制的会话 + self.session = self._create_session(max_retries) + + # 配置常量 + self.BASE_REPORT_URL = "https://a.cmdp.cn/basiceg/v1/json/tpldev" + self.CACHE_DIR = "cache" + + def _setup_logging(self): + """配置日志""" + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' + ) + self.logger = logging.getLogger(__name__) + + @staticmethod + def _create_session(max_retries: int) -> requests.Session: + """创建带重试机制的会话 + + Args: + max_retries: 最大重试次数 + + Returns: + 配置好的会话对象 + """ + session = requests.Session() + + # 配置重试策略 + retry_strategy = Retry( + total=max_retries, + status_forcelist=[429, 500, 502, 503, 504], + backoff_factor=1 + ) + + # 为HTTP和HTTPS适配器添加重试机制 + adapter = HTTPAdapter(max_retries=retry_strategy) + session.mount("http://", adapter) + session.mount("https://", adapter) + + return session + + def _make_request(self, method: str, url: str, **kwargs): + """发送HTTP请求(带错误处理) + + Args: + method: HTTP方法 + url: 请求URL + **kwargs: 其他请求参数 + + Returns: + JSON响应或None + """ + try: + # 设置默认超时 + if 'timeout' not in kwargs: + kwargs['timeout'] = self.timeout + + response = self.session.request(method, url, **kwargs) + response.raise_for_status() + + self.logger.info(f"请求成功: {url}") + return response.json() + + except requests.exceptions.RequestException as e: + self.logger.error(f"请求失败: {url} - {str(e)}") + return {} + except json.JSONDecodeError as e: + self.logger.error(f"JSON解析失败: {url} - {str(e)}") + return {} + + def chat_deepseek(self, message: str, role: str = "", model: str = "deepseek-chat") -> str: + """与DeepSeek聊天 + + Args: + message: 用户消息 + role: 系统角色 + model: 使用的模型 + + Returns: + AI回复内容 + """ + url = "https://api.deepseek.com/chat/completions" + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {self.deepseek_api_key}" + } + + messages = [] + if role: + messages.append({"role": "system", "content": role}) + messages.append({"role": "user", "content": message}) + + body = { + "model": model, + "messages": messages, + "stream": False + } + + result = self._make_request("POST", url, json=body, headers=headers) + if result and "choices" in result: + return result.get('choices', [{}])[0]['message']['content'] + + self.logger.warning("DeepSeek API调用失败或返回空结果") + return "" + + +agent = AIAgent(max_retries=1, timeout=180) + + class ChatSessionManager: """聊天会话管理器类""" @@ -40,7 +172,7 @@ class ChatSessionManager: self.chat_history_dir = chat_history_dir self.files_dir = os.path.join(chat_history_dir, "files") self.messages_dir = os.path.join(chat_history_dir, "messages") - self.db_path = os.path.join("", "data.sqlite") + self.db_path = os.path.join("db", "data.sqlite") self.cache_path = None # 初始化文件管理器 self.obj = ObjectFileManager() @@ -293,13 +425,6 @@ class ChatSessionManager: def save_all_to_sqlite(self) -> None: """ 保存所有聊天数据到SQLite数据库 - - Args: - users: 用户列表 - groups: 群组列表 - members: 成员映射 - messages: 消息列表 - files: 文件映射 """ # 保存文件信息 file_data = [] @@ -425,50 +550,106 @@ class ChatSessionManager: res = cursor.fetchall() return res - def get_history(self, start_time_str: str, end_time_str: str) -> list: + @staticmethod + def analyze_qa_content(group_messages) -> dict: + group_qa = {} + for group_id in group_messages: + print(f"群ID: {group_id}") + print(f"消息数量: {len(group_messages[group_id])}") + content = "" + if len(group_messages[group_id]) <= 2: + continue + else: + for msg in sorted(group_messages[group_id], key=lambda i: i[1]): + content += json.dumps({ + "user": msg[1], + "time": msg[2], + "content": msg[3], + "message_id": msg[4] + }, ensure_ascii=False) + ",\n" + + template = f""" + 以下是群中的消息记录 + + ```json + [ + {content} + ] + ``` + """ + """ + 找到其中的问题和回答,如果没有回答就只整理问题,问题是与产品填报系统,上市公司,证券政策相关的问题 + 问题可能不只由一句话构成,回答也可能不只由一句话构成 + 多个问题需要分开放置 + 输出格式 + + ```json + [ + { + "question": ["message_id",...], + "answer": ["message_id",...] + } + ] + ``` + """ + answer = agent.chat_deepseek(template) + answer = answer.replace("```json", "").replace("```", "") if "```json" in answer else answer + try: + answer = json.loads(answer) + except: + print(answer) + answer = [] + group_qa[group_id] = answer + return group_qa + + def save_qa_to_sqlite(self, group_qa: dict): """ - 获取指定时间的聊天历史记录 + 将问答数据保存到 SQLite 数据库 + + Args: + group_qa: 问答数据字典,键为群ID,值为问答列表 + """ + data = [] + cursor = self.conn.cursor() + for r in group_qa: + qas = group_qa.get(r, {}) + for qa in qas: + Q = qa["question"] + A = qa["answer"] + data.append((r, json.dumps(Q, ensure_ascii=False), json.dumps(A, ensure_ascii=False))) + cursor.executemany(''' + insert into qa (groupId, question, answer) + values (?, ?, ?) + ''', data) + self.conn.commit() + + def update_qa_data(self, start_time_str: str, end_time_str: str): + """ + 更新指定时间范围内的问答内容 Args: start_time_str: 开始时间,格式为 "YYYY-MM-DD HH:MM:SS" end_time_str: 结束时间,格式为 "YYYY-MM-DD HH:MM:SS" - - Returns: - 聊天历史记录列表 """ start_time = convert_to_utc(start_time_str, source_timezone="Asia/Shanghai").timestamp() end_time = convert_to_utc(end_time_str, source_timezone="Asia/Shanghai").timestamp() cursor = self.conn.cursor() cursor.execute(''' - SELECT count(1) as count + SELECT receiver, sender, time, content, id FROM message WHERE message.time >= ? AND message.time <= ? - + AND toType = 1 + AND type in ('text', 'mixed', 'chatrecord') ''', (str(start_time).replace(".0", "000"), str(end_time).replace(".0", "000"))) - res = cursor.fetchall() - print(f"总消息数量: {res[0][0]}") - cursor.execute(''' - SELECT 1 as count - FROM message - WHERE message.time >= ? - AND message.time <= ? - group by message.sender - ''', (str(start_time).replace(".0", "000"), str(end_time).replace(".0", "000"))) - res = cursor.fetchall() - print(f"发送者数量: {len(res)}") - cursor.execute(''' - SELECT * - FROM message - - WHERE message.type in ('text', 'mixed', 'chatrecord') - AND message.time >= ? - AND message.time <= ? - AND message.toType == 1 - - ''', (str(start_time).replace(".0", "000"), str(end_time).replace(".0", "000"))) - res = cursor.fetchall() - return res + data = cursor.fetchall() + group_messages = {} + for i in data: + group_id = i[0] + if group_id not in group_messages: + group_messages[group_id] = [] + group_messages[group_id].append(i) + group_qa = self.analyze_qa_content(group_messages) + self.analyze_qa_content(group_qa) def close(self) -> None: """关闭数据库连接""" @@ -482,116 +663,6 @@ class ChatSessionManager: if __name__ == '__main__': chat_session = ChatSessionManager() - # for day in range(22, 30+1): - # for hour in range(0, 24): - # chat_session.process_chat_session(2025, 9, day, hour) - # for day in range(1, 29+1): - # for hour in range(0, 24): - # chat_session.process_chat_session(2025, 10, day, hour) - # start = "2025-10-15 00:00:00" - # end = "2025-10-30 23:59:59" - # data = chat_session.get_history(start, end) - # group_messages = {} - # for i in data: - # group_id = i[-1] - # if group_id not in group_messages: - # group_messages[group_id] = [] - # group_messages[group_id].append((i[5], i[2], i[3])) - # group_qa = {} - # for group_id in group_messages: - # print(f"群ID: {group_id}") - # print(f"消息数量: {len(group_messages[group_id])}") - # content = "" - # if len(group_messages[group_id]) < 2: - # continue - # elif len(group_messages[group_id]) == 2: - # print(group_messages[group_id]) - # else: - # for msg in sorted(group_messages[group_id], key=lambda i: i[1]): - # content += json.dumps({ - # "user": msg[0], - # "time": msg[1], - # "content": msg[2] - # },ensure_ascii=False) + ",\n" - # - # template = f""" - # 以下是群中的消息记录 - # - # ```json - # [ - # {content} - # ] - # ``` - # """ + """ - # 找到其中的问题和回答,如果没有回答就只整理问题,问题是与产品填报系统,上市公司,证券政策相关的问题 - # 问题可能不只由一句话构成,回答也可能不只由一句话构成 - # 多个问题需要分开放置 - # 输出格式 - # - # ```json - # [ - # { - # "question": [{ - # "user": "用户1", - # "time": "时间戳", - # "content": "问题" - # }], - # "answer": [ - # { - # "user": "用户1", - # "time": "时间戳", - # "content": "回答" - # } - # ] - # } - # ] - # ``` - # """ - # answer = agent.chat_deepseek(template) - # answer = answer.replace("```json", "").replace("```", "") if "```json" in answer else answer - # try: - # answer = json.loads(answer) - # except: - # print(answer) - # answer = [] - # group_qa[group_id] = answer - # print(group_qa) - # with open(f"group_qa-{start.split(' ')[0]}-{end.split(' ')[0]}.json", "w", encoding="utf-8") as f: - # f.write(json.dumps(group_qa, ensure_ascii=False)) - # push_message(f"群聊问答-{start.split(' ')[0]}-{end.split(' ')[0]}", "问题提取完成", "") - with open(f"group_qa.json", "r", encoding="utf-8") as f: - data = json.load(f) - cursor = chat_session.conn.cursor() - a = cursor.execute(''' - select * - from message - ''').fetchall() - - mapping = {} - for i in a: - mapping[i[2] + "-" + i[5]] = i[0] - dar = [] - for r in data: - qas = data.get(r) - - for qa in qas: - Q = [] - A = [] - q = qa["question"] - for qq in q: - if qq["time"] + "-" + qq["user"] not in mapping: - print(qq) - else: - Q.append(mapping[qq["time"] + "-" + qq["user"]]) - a = qa["answer"] - for aa in a: - if aa["time"] + "-" + aa["user"] not in mapping: - print(aa) - else: - A.append(mapping[aa["time"] + "-" + aa["user"]]) - dar.append((r, json.dumps(Q, ensure_ascii=False), json.dumps(A, ensure_ascii=False))) - a = cursor.executemany(''' - insert into qa (groupId, question, answer) - values (?, ?, ?) - ''', dar) - chat_session.conn.commit() + start = "2025-10-15 00:00:00" + end = "2025-10-15 23:59:59" + chat_session.update_qa_data(start, end) diff --git a/db/data.sqlite b/db/data.sqlite index 5465925..aa196e5 100644 Binary files a/db/data.sqlite and b/db/data.sqlite differ diff --git a/requirements.txt b/requirements.txt index 2215f6b..68c41fc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ Flask==2.3.3 -Werkzeug==2.3.7 \ No newline at end of file +Werkzeug==2.3.7 +pytz \ No newline at end of file diff --git a/static/css/daily_report.css b/static/css/daily_report.css new file mode 100644 index 0000000..d3c19c2 --- /dev/null +++ b/static/css/daily_report.css @@ -0,0 +1,170 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + line-height: 1.6; + color: #333; + background-color: #f5f5f5; +} + +.container { + max-width: 1200px; + margin: 0 auto; + padding: 20px; +} + +.header { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; + padding: 30px; + border-radius: 10px; + margin-bottom: 30px; + text-align: center; +} + +.header h1 { + font-size: 2.5em; + margin-bottom: 10px; +} + +.header p { + font-size: 1.2em; + opacity: 0.9; +} + +.controls { + background: white; + padding: 20px; + border-radius: 10px; + margin-bottom: 20px; + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); +} + +.control-group { + display: flex; + gap: 20px; + align-items: center; + flex-wrap: wrap; +} + +.control-group label { + font-weight: bold; + color: #555; +} + +.control-group input { + padding: 8px 12px; + border: 1px solid #ddd; + border-radius: 5px; + font-size: 14px; +} + +.btn { + background: #667eea; + color: white; + border: none; + padding: 10px 20px; + border-radius: 5px; + cursor: pointer; + font-size: 14px; + transition: background 0.3s; +} + +.btn:hover { + background: #5a6fd8; +} + +.btn:disabled { + background: #ccc; + cursor: not-allowed; +} + +.report-container { + background: white; + border-radius: 10px; + padding: 30px; + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); + margin-bottom: 20px; +} + +.report-content { + white-space: pre-wrap; + font-family: 'Courier New', monospace; + line-height: 1.8; + font-size: 14px; +} + +.loading { + text-align: center; + padding: 40px; + color: #666; +} + +.error { + background: #ffe6e6; + color: #d63031; + padding: 15px; + border-radius: 5px; + margin: 10px 0; + border-left: 4px solid #d63031; +} + +.statistics { + background: #f8f9fa; + padding: 20px; + border-radius: 8px; + margin-top: 20px; +} + +.stat-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 15px; + margin-top: 15px; +} + +.stat-item { + background: white; + padding: 15px; + border-radius: 8px; + text-align: center; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); +} + +.stat-value { + font-size: 1.8em; + font-weight: bold; + color: #667eea; +} + +.stat-label { + font-size: 0.9em; + color: #666; + margin-top: 5px; +} + +.nav { + display: flex; + gap: 10px; + margin-bottom: 20px; +} + +.nav-btn { + padding: 8px 16px; + background: #f8f9fa; + border: 1px solid #ddd; + border-radius: 5px; + text-decoration: none; + color: #333; + transition: all 0.3s; +} + +.nav-btn:hover { + background: #667eea; + color: white; + border-color: #667eea; +} \ No newline at end of file diff --git a/static/css/index.css b/static/css/index.css new file mode 100644 index 0000000..ed1e321 --- /dev/null +++ b/static/css/index.css @@ -0,0 +1,492 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + background-color: #f5f5f5; + color: #333; +} + +.container { + max-width: 1200px; + margin: 0 auto; + padding: 20px; +} + +.header { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; + padding: 30px; + border-radius: 15px; + margin-bottom: 30px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1); +} + +.header h1 { + font-size: 2.5em; + margin-bottom: 10px; +} + +.header p { + font-size: 1.1em; + opacity: 0.9; + margin-bottom: 15px; +} + +.nav-links { + display: flex; + gap: 15px; + margin-top: 10px; +} + +.nav-btn { + padding: 8px 16px; + background: #f8f9fa; + border: 1px solid #ddd; + border-radius: 5px; + text-decoration: none; + color: #333; + transition: all 0.3s; +} + +.nav-btn:hover { + background: #667eea; + color: white; + border-color: #667eea; +} + +.nav-btn.active { + background: #667eea; + color: white; + border-color: #667eea; +} + +.nav-link { + background: rgba(255, 255, 255, 0.2); + color: white; + padding: 8px 16px; + border-radius: 20px; + text-decoration: none; + font-size: 0.9em; + transition: all 0.3s ease; + border: 1px solid rgba(255, 255, 255, 0.3); +} + +.nav-link:hover { + background: rgba(255, 255, 255, 0.3); + transform: translateY(-2px); + box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); +} + +.stats-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 20px; + margin-bottom: 30px; +} + +.stat-card { + background: white; + padding: 25px; + border-radius: 12px; + box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08); + text-align: center; + transition: transform 0.3s ease; +} + +.stat-card:hover { + transform: translateY(-5px); +} + +.stat-number { + font-size: 2.5em; + font-weight: bold; + color: #667eea; + margin-bottom: 5px; +} + +.stat-label { + color: #666; + font-size: 0.9em; +} + +.view-switcher { + display: flex; + gap: 10px; + margin-bottom: 20px; +} + +.view-btn { + padding: 10px 20px; + border: 2px solid #667eea; + background: white; + color: #667eea; + border-radius: 25px; + cursor: pointer; + transition: all 0.3s ease; + font-weight: bold; +} + +.view-btn.active { + background: #667eea; + color: white; +} + +.view-btn:hover { + transform: translateY(-2px); + box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3); +} + +.chat-container { + display: grid; + grid-template-columns: 300px 1fr; + gap: 20px; + height: 70vh; +} + +.sidebar { + background: white; + border-radius: 12px; + padding: 20px; + box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08); + overflow-y: auto; +} + +.sidebar h3 { + margin-bottom: 15px; + color: #333; + border-bottom: 2px solid #667eea; + padding-bottom: 10px; +} + +.group-list { + list-style: none; + margin-bottom: 20px; +} + +.group-item { + padding: 15px; + margin-bottom: 10px; + background: #f8f9fa; + border-radius: 8px; + cursor: pointer; + transition: all 0.3s ease; + border-left: 4px solid transparent; +} + +.group-item:hover { + background: #e9ecef; + transform: translateX(5px); +} + +.group-item.active { + background: #667eea; + color: white; + border-left-color: #764ba2; +} + +.group-name { + font-weight: bold; + margin-bottom: 5px; +} + +.group-info { + font-size: 0.8em; + color: #666; + display: flex; + justify-content: space-between; +} + +.group-item.active .group-info { + color: rgba(255, 255, 255, 0.8); +} + +.chat-area { + background: white; + border-radius: 12px; + box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08); + display: flex; + flex-direction: column; +} + +.chat-header { + padding: 20px; + border-bottom: 1px solid #eee; + background: #f8f9fa; + border-radius: 12px 12px 0 0; + display: flex; + justify-content: space-between; + align-items: center; +} + +.current-group { + font-size: 1.2em; + font-weight: bold; + color: #333; +} + +.group-stats { + font-size: 0.9em; + color: #666; +} + +.chat-messages { + flex: 1; + overflow-y: auto; + overflow-x: hidden; + padding: 20px; +} + +.message { + margin-bottom: 20px; + display: flex; + align-items: flex-start; +} + +.message.own { + flex-direction: row-reverse; +} + +.avatar { + width: 40px; + height: 40px; + border-radius: 50%; + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + display: flex; + align-items: center; + justify-content: center; + color: white; + font-weight: bold; + margin: 0 10px; +} + +.message-content { + max-width: 70%; + padding: 12px 16px; + border-radius: 18px; + background: #f1f3f5; + position: relative; + word-wrap: break-word; + overflow-wrap: break-word; + white-space: normal; +} + +.message.own .message-content { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; +} + +.message-sender { + font-weight: bold; + margin-bottom: 5px; + font-size: 0.9em; +} + +.message-time { + font-size: 0.8em; + color: #999; + margin-top: 5px; +} + +.message.own .message-time { + 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; + color: #666; +} + +.error { + background: #ffe6e6; + color: #d63031; + padding: 10px; + border-radius: 8px; + margin: 10px 0; + text-align: center; +} + +@media (max-width: 768px) { + .chat-container { + grid-template-columns: 1fr; + } + + .sidebar { + display: none; + } + + .message-content { + max-width: 85%; + } +} + +body, .container { + overflow-x: hidden; +} + +/* 聊天记录按钮样式 */ +.chatrecord-btn { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; + border: none; + padding: 8px 16px; + border-radius: 15px; + cursor: pointer; + font-size: 0.9em; + transition: all 0.3s ease; + text-align: left; + max-width: 100%; + word-wrap: break-word; + overflow-wrap: break-word; + white-space: normal; +} + +.chatrecord-btn:hover { + transform: scale(1.05); + box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3); +} + +/* 模态框样式 */ +.modal { + display: none; + position: fixed; + z-index: 1000; + left: 0; + top: 0; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, 0.5); + animation: fadeIn 0.3s; +} + +.modal-content { + background-color: white; + margin: 5% auto; + padding: 0; + border-radius: 15px; + width: 80%; + max-width: 800px; + max-height: 80vh; + overflow: hidden; + box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2); + animation: slideIn 0.3s; +} + +.modal-header { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; + padding: 20px; + display: flex; + justify-content: space-between; + align-items: center; +} + +.modal-header h3 { + margin: 0; + font-size: 1.3em; +} + +.close { + color: white; + font-size: 28px; + font-weight: bold; + cursor: pointer; + transition: opacity 0.3s; +} + +.close:hover { + opacity: 0.7; +} + +.modal-body { + padding: 0; + max-height: calc(80vh - 80px); + overflow-y: auto; +} + +.chat-record-content { + padding: 20px; +} + +.chat-record-item { + margin-bottom: 15px; + padding: 15px; + background: #f8f9fa; + border-radius: 10px; + border-left: 4px solid #667eea; +} + +.chat-record-sender { + font-weight: bold; + margin-bottom: 5px; + color: #333; +} + +.chat-record-text { + margin-bottom: 5px; + line-height: 1.4; +} + +.chat-record-time { + font-size: 0.8em; + color: #666; + text-align: right; +} + +.chat-record-image { + max-width: 200px; + max-height: 200px; + border-radius: 8px; + margin: 5px 0; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes slideIn { + from { + transform: translateY(-50px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } +} + +.container { + max-width: 100%; + overflow-x: hidden; +} \ No newline at end of file diff --git a/static/css/qa.css b/static/css/qa.css new file mode 100644 index 0000000..d717dc4 --- /dev/null +++ b/static/css/qa.css @@ -0,0 +1,506 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #f5f5f5; + color: #333; + line-height: 1.6; +} + +.container { + max-width: 1200px; + margin: 0 auto; + padding: 20px; +} + +.header { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; + padding: 30px 0; + text-align: center; + border-radius: 10px; + margin-bottom: 30px; + box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1); +} + +.header h1 { + font-size: 2.5em; + margin-bottom: 10px; +} + +.header p { + font-size: 1.1em; + opacity: 0.9; +} + +.controls { + background: white; + padding: 20px; + border-radius: 10px; + margin-bottom: 20px; + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); +} + +.search-box { + display: flex; + gap: 10px; + margin-bottom: 15px; +} + +.search-box input { + flex: 1; + padding: 10px; + border: 1px solid #ddd; + border-radius: 5px; + font-size: 14px; +} + +.btn { + padding: 10px 20px; + border: none; + border-radius: 5px; + cursor: pointer; + font-size: 14px; + transition: all 0.3s ease; +} + +.btn-primary { + background: #667eea; + color: white; +} + +.btn-primary:hover { + background: #5a6fd8; + transform: translateY(-2px); +} + +.btn-success { + background: #28a745; + color: white; +} + +.btn-success:hover { + background: #218838; +} + +.btn-danger { + background: #dc3545; + color: white; +} + +.btn-danger:hover { + background: #c82333; +} + +.qa-list { + background: white; + border-radius: 10px; + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); + overflow: hidden; +} + +.qa-item { + padding: 20px; + border-bottom: 1px solid #eee; + transition: background-color 0.3s ease; +} + +.qa-item:hover { + background-color: #f8f9fa; +} + +.qa-item:last-child { + border-bottom: none; +} + +.qa-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 15px; +} + +.qa-id { + font-weight: bold; + color: #667eea; + font-size: 1.2em; +} + +.qa-group { + background: #e9ecef; + padding: 5px 10px; + border-radius: 15px; + font-size: 0.9em; +} + +.qa-content { + margin-bottom: 15px; +} + +.nav-btn { + padding: 8px 16px; + background: #f8f9fa; + border: 1px solid #ddd; + border-radius: 5px; + text-decoration: none; + color: #333; + transition: all 0.3s; +} + +.nav-btn:hover { + background: #667eea; + color: white; + border-color: #667eea; +} + +.nav-btn.active { + background: #667eea; + color: white; + border-color: #667eea; +} + +.qa-section { + margin-bottom: 10px; +} + +.qa-section h4 { + color: #495057; + margin-bottom: 5px; + font-size: 1em; +} + +.message-list { + background: #f8f9fa; + padding: 10px; + border-radius: 5px; + max-height: 150px; + overflow-y: auto; +} + +.message-item { + padding: 5px; + margin-bottom: 5px; + background: white; + border-radius: 3px; + font-size: 0.9em; + border-left: 3px solid #667eea; +} + +.qa-actions { + display: flex; + gap: 10px; +} + +.modal { + display: none; + position: fixed; + z-index: 1000; + left: 0; + top: 0; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, 0.5); +} + +.modal-content { + background-color: white; + margin: 5% auto; + padding: 30px; + border-radius: 10px; + width: 80%; + max-width: 800px; + max-height: 80vh; + overflow-y: auto; +} + +.modal-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 20px; +} + +.close { + font-size: 28px; + font-weight: bold; + cursor: pointer; + color: #aaa; +} + +.close:hover { + color: #000; +} + +.form-group { + margin-bottom: 20px; +} + +.form-group label { + display: block; + margin-bottom: 5px; + font-weight: bold; +} + +.form-group input, +.form-group textarea { + width: 100%; + padding: 10px; + border: 1px solid #ddd; + border-radius: 5px; + font-size: 14px; +} + +.message-selector { + border: 1px solid #ddd; + border-radius: 5px; + padding: 15px; + margin-bottom: 15px; +} + +.search-results { + max-height: 200px; + overflow-y: auto; + border: 1px solid #ddd; + border-radius: 5px; + margin-top: 10px; +} + +.search-result-item { + padding: 10px; + border-bottom: 1px solid #eee; + cursor: pointer; + transition: background-color 0.2s; +} + +.search-result-item:hover { + background-color: #f0f0f0; +} + +.selected-messages { + background: #f8f9fa; + padding: 10px; + border-radius: 5px; + margin-top: 10px; +} + +.selected-message { + display: flex; + justify-content: space-between; + align-items: center; + padding: 5px; + margin-bottom: 5px; + background: white; + border-radius: 3px; +} + +.loading { + text-align: center; + padding: 20px; + color: #666; +} + +.empty-state { + text-align: center; + padding: 40px; + color: #666; +} + +.empty-state i { + font-size: 48px; + margin-bottom: 10px; + opacity: 0.5; +} + +/* 聊天记录预览样式 */ +.chat-preview { + background: white; + border-radius: 10px; + overflow: hidden; +} + +.chat-header { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; + padding: 20px; + text-align: center; +} + +.chat-header h3 { + margin: 0 0 10px 0; + font-size: 1.5em; +} + +.chat-info { + opacity: 0.9; + font-size: 0.9em; +} + +.chat-container { + padding: 20px; + max-height: 400px; + overflow-y: auto; + background: #f8f9fa; +} + +.chat-message { + display: flex; + margin-bottom: 15px; + animation: fadeIn 0.3s ease; +} + +.chat-message.question { + flex-direction: row; +} + +.chat-message.answer { + flex-direction: row-reverse; +} + +.chat-message.other { + flex-direction: row; + opacity: 0.7; +} + +.message-avatar { + width: 40px; + height: 40px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + font-size: 18px; + margin: 0 10px; + flex-shrink: 0; +} + +.chat-message.question .message-avatar { + background: #e3f2fd; + color: #1976d2; +} + +.chat-message.answer .message-avatar { + background: #f3e5f5; + color: #7b1fa2; +} + +.chat-message.other .message-avatar { + background: #f5f5f5; + color: #757575; +} + +.message-content { + flex: 1; + max-width: 70%; +} + +.message-header { + display: flex; + align-items: center; + margin-bottom: 5px; + gap: 10px; +} + +.sender { + font-weight: bold; + color: #333; +} + +.time { + font-size: 0.8em; + color: #666; +} + +.message-type-badge { + padding: 2px 8px; + border-radius: 12px; + font-size: 0.7em; + font-weight: bold; +} + +.message-type-badge.question { + background: #e3f2fd; + color: #1976d2; +} + +.message-type-badge.answer { + background: #f3e5f5; + color: #7b1fa2; +} + +.message-type-badge.other { + background: #f5f5f5; + color: #757575; +} + +.message-text { + background: white; + padding: 12px 15px; + border-radius: 18px; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + line-height: 1.4; + word-wrap: break-word; +} + +.chat-message.question .message-text { + background: #e3f2fd; + border-bottom-left-radius: 5px; +} + +.chat-message.answer .message-text { + background: #f3e5f5; + border-bottom-right-radius: 5px; +} + +.chat-message.other .message-text { + background: #f5f5f5; + border-radius: 18px; +} + +.message-meta { + display: flex; + justify-content: space-between; + margin-top: 5px; + font-size: 0.7em; + color: #999; +} + +.chat-summary { + background: white; + padding: 15px 20px; + border-top: 1px solid #eee; + display: flex; + justify-content: space-around; +} + +.summary-item { + text-align: center; +} + +.summary-label { + display: block; + font-size: 0.8em; + color: #666; + margin-bottom: 5px; +} + +.summary-value { + display: block; + font-size: 1.2em; + font-weight: bold; + color: #667eea; +} + +@keyframes fadeIn { + from { + opacity: 0; + transform: translateY(10px); + } + to { + opacity: 1; + transform: translateY(0); + } +} \ No newline at end of file diff --git a/static/css/weekly_report.css b/static/css/weekly_report.css new file mode 100644 index 0000000..266573e --- /dev/null +++ b/static/css/weekly_report.css @@ -0,0 +1,212 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + line-height: 1.6; + color: #333; + background-color: #f5f5f5; +} + +.container { + max-width: 1200px; + margin: 0 auto; + padding: 20px; +} + +.header { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; + padding: 30px; + border-radius: 10px; + margin-bottom: 30px; + text-align: center; +} + +.header h1 { + font-size: 2.5em; + margin-bottom: 10px; +} + +.header p { + font-size: 1.2em; + opacity: 0.9; +} + +.controls { + background: white; + padding: 20px; + border-radius: 10px; + margin-bottom: 20px; + box-shadow: 0 2px 10px rgba(0,0,0,0.1); +} + +.control-group { + display: flex; + gap: 20px; + align-items: center; + flex-wrap: wrap; +} + +.control-group label { + font-weight: bold; + color: #555; +} + +.control-group input { + padding: 8px 12px; + border: 1px solid #ddd; + border-radius: 5px; + font-size: 14px; +} + +.btn { + background: #667eea; + color: white; + border: none; + padding: 10px 20px; + border-radius: 5px; + cursor: pointer; + font-size: 14px; + transition: background 0.3s; +} + +.btn:hover { + background: #5a6fd8; +} + +.btn:disabled { + background: #ccc; + cursor: not-allowed; +} + +.report-container { + background: white; + border-radius: 10px; + padding: 30px; + box-shadow: 0 2px 10px rgba(0,0,0,0.1); + margin-bottom: 20px; +} + +.report-content { + white-space: pre-wrap; + font-family: 'Courier New', monospace; + line-height: 1.8; + font-size: 14px; +} + +.loading { + text-align: center; + padding: 40px; + color: #666; +} + +.error { + background: #ffe6e6; + color: #d63031; + padding: 15px; + border-radius: 5px; + margin: 10px 0; + border-left: 4px solid #d63031; +} + +.statistics { + background: #f8f9fa; + padding: 20px; + border-radius: 8px; + margin-top: 20px; +} + +.stat-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 15px; + margin-top: 15px; +} + +.stat-item { + background: white; + padding: 15px; + border-radius: 8px; + text-align: center; + box-shadow: 0 1px 3px rgba(0,0,0,0.1); +} + +.stat-value { + font-size: 1.8em; + font-weight: bold; + color: #667eea; +} + +.stat-label { + font-size: 0.9em; + color: #666; + margin-top: 5px; +} + +.category-chart { + margin: 20px 0; +} + +.category-item { + display: flex; + align-items: center; + margin: 10px 0; + padding: 10px; + background: #f8f9fa; + border-radius: 5px; +} + +.category-bar { + height: 20px; + background: linear-gradient(90deg, #667eea, #764ba2); + border-radius: 10px; + margin: 0 10px; + min-width: 50px; +} + +.nav { + display: flex; + gap: 10px; + margin-bottom: 20px; +} + +.nav-btn { + padding: 8px 16px; + background: #f8f9fa; + border: 1px solid #ddd; + border-radius: 5px; + text-decoration: none; + color: #333; + transition: all 0.3s; +} + +.nav-btn:hover { + background: #667eea; + color: white; + border-color: #667eea; +} + +.nav-btn.active { + background: #667eea; + color: white; + border-color: #667eea; +} + +.export-btn { + background: #28a745; + color: white; + border: none; + padding: 8px 16px; + border-radius: 5px; + cursor: pointer; + font-size: 14px; + margin-left: auto; +} + +.export-btn:hover { + background: #218838; +} \ No newline at end of file diff --git a/static/js/daily_report.js b/static/js/daily_report.js new file mode 100644 index 0000000..2cd407f --- /dev/null +++ b/static/js/daily_report.js @@ -0,0 +1,86 @@ +// 设置默认日期为今天 +document.getElementById('date').value = new Date().toISOString().split('T')[0]; + +function showLoading() { + document.getElementById('loading').style.display = 'block'; + document.getElementById('report-container').style.display = 'none'; + document.getElementById('error').style.display = 'none'; +} + +function hideLoading() { + document.getElementById('loading').style.display = 'none'; +} + +function showError(message) { + document.getElementById('error').style.display = 'block'; + document.getElementById('error').textContent = message; +} + +function generateTodayReport() { + document.getElementById('date').value = new Date().toISOString().split('T')[0]; + generateReport(); +} + +function generateReport() { + const date = document.getElementById('date').value; + if (!date) { + showError('请选择日期'); + return; + } + + showLoading(); + + fetch(`/api/reports/daily?date=${date}`) + .then(response => response.json()) + .then(data => { + hideLoading(); + + if (data.success) { + document.getElementById('report-content').textContent = data.report; + document.getElementById('report-container').style.display = 'block'; + + // 显示统计数据 + if (data.statistics) { + displayStatistics(data.statistics); + document.getElementById('statistics').style.display = 'block'; + } + } else { + showError('生成日报失败:' + data.error); + } + }) + .catch(error => { + hideLoading(); + showError('网络错误:' + error.message); + }); +} + +function displayStatistics(stats) { + const statGrid = document.getElementById('stat-grid'); + statGrid.innerHTML = ''; + + const statistics = [ + {label: '今日消息量', value: stats.today_message_count, unit: '条'}, + {label: '昨日消息量', value: stats.yesterday_message_count, unit: '条'}, + {label: '消息变化率', value: stats.message_change_rate.toFixed(1), unit: '%'}, + {label: '今日活跃用户', value: stats.today_active_users, unit: '人'}, + {label: '昨日活跃用户', value: stats.yesterday_active_users, unit: '人'}, + {label: '用户变化率', value: stats.user_change_rate.toFixed(1), unit: '%'}, + {label: '群组数量', value: stats.group_count, unit: '个'}, + {label: '成员总数', value: stats.member_count, unit: '人'} + ]; + + statistics.forEach(stat => { + const statItem = document.createElement('div'); + statItem.className = 'stat-item'; + statItem.innerHTML = ` +
${stat.value}${stat.unit}
+
${stat.label}
+ `; + statGrid.appendChild(statItem); + }); +} + +// 页面加载时自动生成今日日报 +window.addEventListener('load', function () { + generateTodayReport(); +}); \ No newline at end of file diff --git a/static/js/index.js b/static/js/index.js new file mode 100644 index 0000000..529b03b --- /dev/null +++ b/static/js/index.js @@ -0,0 +1,309 @@ +let currentOffset = 0; +const limit = 50; +let currentView = 'groups'; +let currentGroupId = null; +// 页面加载时初始化 +document.addEventListener('DOMContentLoaded', function () { + loadStatistics(); + loadGroupMessages(); + loadMessages(); +}); + +// 加载统计信息 +async function loadStatistics() { + try { + const response = await fetch('/api/statistics'); + const data = await response.json(); + if (data) { + const stats = data; + document.getElementById('userCount').textContent = stats.user_count; + document.getElementById('groupCount').textContent = stats.group_count; + document.getElementById('messageCount').textContent = stats.message_count; + document.getElementById('fileCount').textContent = stats.file_count; + } + } catch (error) { + console.error('加载统计信息失败:', error); + } +} + +// 加载按群组分组的消息统计 +async function loadGroupMessages() { + try { + const response = await fetch('/api/groups'); + const data = await response.json(); + const groupList = document.getElementById('groupList'); + + if (data.success) { + const groups = data.groups || []; + groupList.innerHTML = ''; + + if (groups.length === 0) { + groupList.innerHTML = '
  • 暂无群组
  • '; + return; + } else { + currentGroupId = groups[0].id; + } + + groups.forEach(group => { + const li = document.createElement('li'); + li.className = 'group-item'; + li.setAttribute('data-group-id', group.id); + li.onclick = () => selectGroup(group.id); + + const groupName = document.createElement('div'); + groupName.className = 'group-name'; + groupName.textContent = group.name || group.id; + + const groupInfo = document.createElement('div'); + groupInfo.className = 'group-info'; + groupInfo.innerHTML = ` + 创建者: ${group.owner || '未知'} + `; + + li.appendChild(groupName); + li.appendChild(groupInfo); + groupList.appendChild(li); + }); + + // 默认选择第一个群组 + if (currentView === 'groups' && groups.length > 0) { + selectGroup(groups[0].id); + } + } else { + groupList.innerHTML = '
  • 加载失败
  • '; + } + } catch (error) { + console.error('加载群组消息失败:', error); + } +} + +// 选择群组 +function selectGroup(groupId) { + currentGroupId = groupId; + currentOffset = 0; + + // 更新选中状态 + document.querySelectorAll('.group-item').forEach(item => { + item.classList.remove('active'); + }); + + // 找到对应的群组项并添加选中状态 + document.querySelectorAll('.group-item').forEach(item => { + // 使用data-group-id属性来准确匹配群组 + if (item.getAttribute('data-group-id') === groupId) { + item.classList.add('active'); + + // 更新群组信息 + document.getElementById('currentGroup').textContent = item.querySelector('.group-name').textContent; + document.getElementById('messageCountDisplay').textContent = '消息数量: 加载中...'; + document.getElementById('latestTime').textContent = '最新消息: 加载中...'; + } + }); + + // 加载该群组的消息 + loadMessages(); + + // 加载统计信息 + loadStatistics(); +} + + +// 加载更多消息 +async function loadMoreMessages() { + await loadMessages(); + currentOffset += limit; +} + +// 关闭聊天记录模态框 +function closeChatRecordModal() { + document.getElementById('chatRecordModal').style.display = 'none'; +} + +// 显示聊天记录模态框 +function showChatRecordModal(chatrecordData) { + const modal = document.getElementById('chatRecordModal'); + const title = document.getElementById('modalTitle'); + const content = document.getElementById('chatRecordContent'); + + // 设置模态框标题 + if (chatrecordData.chatrecord && chatrecordData.chatrecord.title) { + title.textContent = chatrecordData.chatrecord.title; + } else { + title.textContent = '聊天记录'; + } + + // 渲染聊天记录内容 + renderChatRecordContent(chatrecordData, content); + + modal.style.display = 'block'; +} + +// 渲染聊天记录内容 +function renderChatRecordContent(chatrecordData, contentElement) { + try { + if (!chatrecordData.chatrecord || !chatrecordData.chatrecord.item) { + contentElement.innerHTML = '
    聊天记录数据格式错误
    '; + return; + } + + const chatItems = chatrecordData.chatrecord.item; + + if (!Array.isArray(chatItems) || chatItems.length === 0) { + contentElement.innerHTML = '
    暂无聊天记录内容
    '; + return; + } + + let html = ''; + chatItems.forEach(item => { + // 处理不同类型的聊天记录项 + let contentHtml = ''; + + if (item.type === 'ChatRecordText') { + // 文本消息 + try { + const contentData = JSON.parse(item.content); + contentHtml = contentData.content || item.content || ''; + } catch (e) { + contentHtml = item.content || ''; + } + } else if (item.type === 'ChatRecordImage') { + // 图片消息 + contentHtml = '
    [图片消息]
    '; + } else { + // 其他类型消息 + contentHtml = `[${item.type}] ${item.content || ''}`; + } + + html += ` +
    +
    ${item.from_chatroom ? '群聊' : '私聊'}
    +
    ${contentHtml}
    +
    ${new Date(item.msgtime * 1000).toLocaleString()}
    +
    + `; + }); + + contentElement.innerHTML = html; + } catch (error) { + console.error('渲染聊天记录失败:', error); + contentElement.innerHTML = '
    渲染聊天记录失败: ' + error.message + '
    '; + } +} + +// 加载消息 +async function loadMessages() { + try { + const chatMessages = document.getElementById('chatMessages'); + if (!currentGroupId) { + chatMessages.innerHTML = '
    暂无消息
    '; + return; + } + let url = `/api/group_messages?limit=${limit}&offset=${currentOffset}&group_id=${currentGroupId}`; + + + const response = await fetch(url); + const data = await response.json(); + + if (data.success) { + const messages = data.messages || []; + + 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); + } + }); + currentOffset += limit; + + + document.getElementById('messageCountDisplay').textContent = `消息数量: ${data.total || 0}`; + document.getElementById('latestTime').textContent = `最新消息: ${data.lastest_time || '暂无'}`; + + + } else { + chatMessages.innerHTML = '
    加载消息失败
    '; + } + } catch (error) { + console.error('加载消息失败:', error); + document.getElementById('chatMessages').innerHTML = '
    加载消息失败: ' + error.message + '
    '; + } +} + +// 创建消息元素 +function createMessageElement(message) { + const messageDiv = document.createElement('div'); + messageDiv.className = 'message'; + + // 判断是否为自己的消息 + if (message.is_own) { + messageDiv.classList.add('own'); + } + + const avatar = document.createElement('div'); + avatar.className = 'avatar'; + avatar.textContent = message.sender_name ? message.sender_name.charAt(0).toUpperCase() : 'U'; + + const contentDiv = document.createElement('div'); + contentDiv.className = 'message-content'; + + const senderDiv = document.createElement('div'); + senderDiv.className = 'message-sender'; + senderDiv.textContent = message.sender_name || '未知用户'; + + const textDiv = document.createElement('div'); + textDiv.className = 'message-text'; + + // 处理消息内容 + if (message.content) { + if (message.type === 'chatrecord' && message.chatrecord_data) { + const chatrecordBtn = document.createElement('button'); + chatrecordBtn.className = 'chatrecord-btn'; + chatrecordBtn.textContent = message.display_content || '[聊天记录]'; + chatrecordBtn.onclick = () => showChatRecordModal(message.chatrecord_data); + textDiv.appendChild(chatrecordBtn); + } else { + textDiv.textContent = message.display_content; + } + } else { + textDiv.textContent = '[空消息]'; + } + + const timeDiv = document.createElement('div'); + timeDiv.className = 'message-time'; + timeDiv.textContent = message.formatted_time; + + contentDiv.appendChild(senderDiv); + contentDiv.appendChild(textDiv); + contentDiv.appendChild(timeDiv); + + messageDiv.appendChild(avatar); + messageDiv.appendChild(contentDiv); + + return messageDiv; +} + + +// 点击模态框外部关闭 +window.onclick = function (event) { + const modal = document.getElementById('chatRecordModal'); + if (event.target === modal) { + modal.style.display = 'none'; + } +} \ No newline at end of file diff --git a/static/js/qa.js b/static/js/qa.js new file mode 100644 index 0000000..0737a6f --- /dev/null +++ b/static/js/qa.js @@ -0,0 +1,567 @@ +let currentQA = null; +let selectedQuestions = []; +let selectedAnswers = []; + +// 页面加载时获取QA列表 +document.addEventListener('DOMContentLoaded', function () { + loadQAList(); +}); + +// 加载QA列表 +async function loadQAList() { + try { + const response = await fetch('/api/qa'); + const result = await response.json(); + if (result.success) { + // 根据后端API返回的数据结构,data字段包含qa_list + const qaList = result.qa_list || []; + displayQAList(qaList); + } else { + alert('加载QA列表失败: ' + result.error); + } + } catch (error) { + alert('加载QA列表时出错: ' + error.message); + } +} + +// 显示QA列表 +async function displayQAList(qaList) { + const qaListContainer = document.getElementById('qaList'); + + if (qaList.length === 0) { + qaListContainer.innerHTML = ` +
    +
    📝
    +

    暂无QA记录

    +

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

    +
    + `; + return; + } + + // 获取所有消息的详细内容 + let allMessageIds = []; + qaList.forEach(qa => { + // 解析JSON格式的question和answer字段 + let questionIds = []; + let answerIds = []; + + try { + questionIds = typeof qa.question === 'string' ? JSON.parse(qa.question) : qa.question || []; + answerIds = typeof qa.answer === 'string' ? JSON.parse(qa.answer) : qa.answer || []; + } catch (e) { + console.error('解析QA数据时出错:', e); + questionIds = []; + answerIds = []; + } + + allMessageIds = [...allMessageIds, ...questionIds, ...answerIds]; + }); + + let messageMap = {}; + if (allMessageIds.length > 0) { + try { + const response = await fetch('/api/messages_by_ids', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({message_ids: allMessageIds}) + }); + const result = await response.json(); + if (result.success) { + result.messages.forEach(msg => { + messageMap[msg.id] = msg; + }); + } + } catch (error) { + console.error('获取消息详情时出错:', error); + } + } + + qaListContainer.innerHTML = qaList.map(qa => { + // 解析JSON格式的question和answer字段 + let questionIds = []; + let answerIds = []; + + try { + questionIds = typeof qa.question === 'string' ? JSON.parse(qa.question) : qa.question || []; + answerIds = typeof qa.answer === 'string' ? JSON.parse(qa.answer) : qa.answer || []; + } catch (e) { + console.error('解析QA数据时出错:', e); + questionIds = []; + answerIds = []; + } + + // 获取第一个问题的内容作为显示 + let questionContent = '暂无问题内容'; + if (questionIds.length > 0) { + const firstQuestionId = questionIds[0]; + const message = messageMap[firstQuestionId]; + if (message && message.content) { + questionContent = message.content; + } else { + questionContent = `问题消息ID: ${firstQuestionId}`; + } + } + + // 截取问题内容,超过30个字用省略号 + if (questionContent.length > 30) { + questionContent = questionContent.substring(0, 30) + '...'; + } + + return ` +
    +
    +
    QA #${qa.id}
    +
    ${qa.groupId || '无群组'}
    +
    + +
    +
    + 问题: ${questionContent} +
    +
    + 问题: ${questionIds.length}条 + 答案: ${answerIds.length}条 +
    +
    + +
    + + + +
    +
    + `; + }).join(''); +} + +// 搜索消息 +async function searchMessages() { + const keyword = document.getElementById('searchInput').value.trim(); + if (!keyword) { + alert('请输入搜索关键词'); + return; + } + + try { + const response = await fetch(`/api/search_messages?keyword=${encodeURIComponent(keyword)}`); + const result = await response.json(); + + if (result.success) { + displaySearchResults(result.messages); + } else { + alert('搜索失败: ' + result.error); + } + } catch (error) { + alert('搜索时出错: ' + error.message); + } +} + +// 显示搜索结果 +function displaySearchResults(messages) { + const qaListContainer = document.getElementById('qaList'); + + if (messages.length === 0) { + qaListContainer.innerHTML = ` +
    +
    🔍
    +

    未找到相关消息

    +

    请尝试其他搜索关键词

    +
    + `; + return; + } + + qaListContainer.innerHTML = messages.map(msg => ` +
    +
    +
    消息ID: ${msg.id}
    +
    ${msg.formatted_time || '未知时间'}
    +
    + +
    +
    + 类型: ${msg.type} | + 发送者: ${msg.sender || '未知'} | + 接收者: ${msg.receiver || '未知'} +
    +
    + 内容: ${msg.content || '无内容'} +
    +
    + +
    + + +
    +
    + `).join(''); +} + +// 打开创建模态框 +function openCreateModal() { + currentQA = null; + selectedQuestions = []; + selectedAnswers = []; + + document.getElementById('modalTitle').textContent = '创建QA记录'; + document.getElementById('groupId').value = ''; + updateSelectedMessages(); + + document.getElementById('qaModal').style.display = 'block'; +} + +// 编辑QA +async function editQA(qaId) { + try { + const response = await fetch(`/api/qa/${qaId}`); + const result = await response.json(); + + if (result.success) { + currentQA = result.qa; + selectedQuestions = [...currentQA.question_list]; + selectedAnswers = [...currentQA.answer_list]; + + document.getElementById('modalTitle').textContent = '编辑QA记录'; + document.getElementById('groupId').value = currentQA.groupId || ''; + updateSelectedMessages(); + + document.getElementById('qaModal').style.display = 'block'; + } else { + alert('加载QA详情失败: ' + result.error); + } + } catch (error) { + alert('加载QA详情时出错: ' + error.message); + } +} + +// 搜索问题消息 +async function searchQuestionMessages() { + const keyword = document.getElementById('questionSearch').value.trim(); + if (!keyword) { + document.getElementById('questionResults').innerHTML = ''; + return; + } + const groupId = document.getElementById('groupId').value.trim(); + try { + 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) { + displayQuestionResults(result.messages); + } + } catch (error) { + console.error('搜索问题消息时出错:', error); + } +} + +// 显示问题搜索结果 +function displayQuestionResults(messages) { + const resultsContainer = document.getElementById('questionResults'); + console.log(messages); + resultsContainer.innerHTML = messages.map(msg => ` +
    +
    ID: ${msg.id}
    +
    内容: ${msg.content ? msg.content.substring(0, 100) + (msg.content.length > 100 ? '...' : '') : '无内容'}
    +
    时间: ${msg.formatted_time || '未知'}
    +
    + `).join(''); +} + +// 搜索答案消息 +async function searchAnswerMessages() { + const keyword = document.getElementById('answerSearch').value.trim(); + if (!keyword) { + document.getElementById('answerResults').innerHTML = ''; + return; + } + const groupId = document.getElementById('groupId').value.trim(); + + try { + 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) { + displayAnswerResults(result.messages); + } + } catch (error) { + console.error('搜索答案消息时出错:', error); + } +} + +// 显示答案搜索结果 +function displayAnswerResults(messages) { + const resultsContainer = document.getElementById('answerResults'); + + resultsContainer.innerHTML = messages.map(msg => ` +
    +
    ID: ${msg.id}
    +
    内容: ${msg.content ? msg.content.substring(0, 100) + (msg.content.length > 100 ? '...' : '') : '无内容'}
    +
    时间: ${msg.formatted_time || '未知'}
    +
    + `).join(''); +} + +// 选择问题消息 +function selectQuestion(messageId, content) { + if (!selectedQuestions.includes(messageId)) { + selectedQuestions.push(messageId); + updateSelectedMessages(); + } +} + +// 选择答案消息 +function selectAnswer(messageId, content) { + if (!selectedAnswers.includes(messageId)) { + selectedAnswers.push(messageId); + updateSelectedMessages(); + } +} + +// 从搜索结果添加为问题 +function addToQuestion(messageId) { + if (!selectedQuestions.includes(messageId)) { + selectedQuestions.push(messageId); + alert('已添加到问题列表'); + } +} + +// 从搜索结果添加为答案 +function addToAnswer(messageId) { + if (!selectedAnswers.includes(messageId)) { + selectedAnswers.push(messageId); + alert('已添加到答案列表'); + } +} + +// 更新已选择的消息显示 +function updateSelectedMessages() { + document.getElementById('selectedQuestions').innerHTML = selectedQuestions.map(id => ` +
    + 消息ID: ${id} + +
    + `).join(''); + + document.getElementById('selectedAnswers').innerHTML = selectedAnswers.map(id => ` +
    + 消息ID: ${id} + +
    + `).join(''); +} + +// 移除问题消息 +function removeQuestion(messageId) { + selectedQuestions = selectedQuestions.filter(id => id !== messageId); + updateSelectedMessages(); +} + +// 移除答案消息 +function removeAnswer(messageId) { + selectedAnswers = selectedAnswers.filter(id => id !== messageId); + updateSelectedMessages(); +} + +// 保存QA记录 +async function saveQA() { + const groupId = document.getElementById('groupId').value.trim(); + + if (selectedQuestions.length === 0) { + alert('请至少选择一个问题消息'); + return; + } + + if (selectedAnswers.length === 0) { + alert('请至少选择一个答案消息'); + return; + } + + const qaData = { + groupId: groupId, + question: selectedQuestions, + answer: selectedAnswers + }; + + try { + const url = currentQA ? `/api/qa/${currentQA.id}` : '/api/qa'; + const method = currentQA ? 'PUT' : 'POST'; + + const response = await fetch(url, { + method: method, + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(qaData) + }); + + const result = await response.json(); + + if (result.success) { + alert(currentQA ? 'QA记录更新成功' : 'QA记录创建成功'); + closeModal(); + loadQAList(); + } else { + alert('保存失败: ' + result.error); + } + } catch (error) { + alert('保存时出错: ' + error.message); + } +} + +// 预览QA +async function previewQA(qaId) { + try { + const response = await fetch(`/api/qa/${qaId}`); + const result = await response.json(); + if (result.success) { + displayPreview(result.qa); + } else { + alert('加载QA详情失败: ' + result.error); + } + } catch (error) { + alert('加载QA详情时出错: ' + error.message); + } +} + +// 显示预览 +async function displayPreview(qa) { + const previewContent = document.getElementById('previewContent'); + // 获取所有消息的详细内容 + let allMessages = []; + const allMessageIds = [...qa.question_list, ...qa.answer_list]; + + if (allMessageIds.length > 0) { + try { + const response = await fetch('/api/messages_by_ids', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({message_ids: allMessageIds}) + }); + const result = await response.json(); + if (result.success) { + allMessages = result.messages; + } + } catch (error) { + console.error('获取消息详情时出错:', error); + } + } + + // 创建消息映射 + const messageMap = {}; + allMessages.forEach(msg => { + messageMap[msg.id] = msg; + }); + + // 按时间排序所有消息 + const sortedMessages = allMessages.sort((a, b) => { + return new Date(a.time) - new Date(b.time); + }); + + previewContent.innerHTML = ` +
    +
    +

    QA #${qa.id} - 聊天记录预览

    +
    群组: ${qa.groupId || '无群组'} | 消息数量: ${sortedMessages.length}
    +
    + +
    + ${sortedMessages.map(msg => { + + const isQuestion = qa.question_list.includes(msg.id); + const isAnswer = qa.answer_list.includes(msg.id); + const messageType = isQuestion ? 'question' : (isAnswer ? 'answer' : 'other'); + + return ` +
    +
    + ${messageType === 'question' ? '❓' : (messageType === 'answer' ? '💬' : '📝')} +
    +
    +
    + ${msg.sender || '未知用户'} + ${msg.formatted_time || '未知时间'} + ${messageType === 'question' ? '问题' : (messageType === 'answer' ? '答案' : '其他')} +
    +
    ${msg.content || '无内容'}
    +
    + 消息ID: ${msg.id} + 类型: ${msg.type || '未知'} +
    +
    +
    + `; + }).join('')} +
    + +
    +
    + 问题数量: + ${qa.question_list.length} +
    +
    + 答案数量: + ${qa.answer_list.length} +
    +
    + 总消息数: + ${sortedMessages.length} +
    +
    +
    + `; + + document.getElementById('previewModal').style.display = 'block'; +} + +// 删除QA +async function deleteQA(qaId) { + if (!confirm('确定要删除这个QA记录吗?此操作不可恢复。')) { + return; + } + + try { + const response = await fetch(`/api/qa/${qaId}`, { + method: 'DELETE' + }); + + const result = await response.json(); + + if (result.success) { + alert('QA记录删除成功'); + loadQAList(); + } else { + alert('删除失败: ' + result.error); + } + } catch (error) { + alert('删除时出错: ' + error.message); + } +} + +// 关闭模态框 +function closeModal() { + document.getElementById('qaModal').style.display = 'none'; +} + +// 关闭预览模态框 +function closePreviewModal() { + document.getElementById('previewModal').style.display = 'none'; +} + +// 点击模态框外部关闭 +window.onclick = function (event) { + const modal = document.getElementById('qaModal'); + const previewModal = document.getElementById('previewModal'); + + if (event.target === modal) { + modal.style.display = 'none'; + } + if (event.target === previewModal) { + previewModal.style.display = 'none'; + } +} \ No newline at end of file diff --git a/static/js/weekly_report.js b/static/js/weekly_report.js new file mode 100644 index 0000000..cf3ca58 --- /dev/null +++ b/static/js/weekly_report.js @@ -0,0 +1,146 @@ +// 设置默认周次为当前周 +function getCurrentWeek() { + const now = new Date(); + const startOfYear = new Date(now.getFullYear(), 0, 1); + const days = Math.floor((now - startOfYear) / (24 * 60 * 60 * 1000)); + const weekNumber = Math.ceil((days + 1) / 7); + return `${now.getFullYear()}-W${weekNumber.toString().padStart(2, '0')}`; +} + +// 页面加载时设置默认周次 +document.addEventListener('DOMContentLoaded', function() { + document.getElementById('week').value = getCurrentWeek(); +}); + +function showLoading() { + document.getElementById('loading').style.display = 'block'; + document.getElementById('report-container').style.display = 'none'; + document.getElementById('error').style.display = 'none'; +} + +function hideLoading() { + document.getElementById('loading').style.display = 'none'; +} + +function showError(message) { + document.getElementById('error').style.display = 'block'; + document.getElementById('error').textContent = message; +} + +function generateCurrentWeekReport() { + document.getElementById('week').value = getCurrentWeek(); + generateReport(); +} + +function generateReport() { + const week = document.getElementById('week').value; + if (!week) { + showError('请选择周次'); + return; + } + + // 转换格式:YYYY-WWW 到 YYYY-WW + const weekFormatted = week.replace('W', '-W'); + + showLoading(); + + fetch(`/api/reports/weekly?week=${weekFormatted}`) + .then(response => response.json()) + .then(data => { + hideLoading(); + + if (data.success) { + document.getElementById('report-content').textContent = data.report; + document.getElementById('report-container').style.display = 'block'; + + // 显示统计数据 + if (data.statistics) { + displayStatistics(data.statistics); + document.getElementById('statistics').style.display = 'block'; + + // 显示分类图表 + if (data.statistics.category_breakdown) { + displayCategoryChart(data.statistics.category_breakdown); + document.getElementById('category-chart').style.display = 'block'; + } + } + } else { + showError('生成周报失败:' + data.error); + } + }) + .catch(error => { + hideLoading(); + showError('网络错误:' + error.message); + }); +} + +function displayStatistics(stats) { + const statGrid = document.getElementById('stat-grid'); + statGrid.innerHTML = ''; + + const statistics = [ + { label: '本周消息量', value: stats.week_message_count, unit: '条' }, + { label: '上周消息量', value: stats.last_week_message_count, unit: '条' }, + { label: '消息变化率', value: stats.message_change_rate.toFixed(1), unit: '%' }, + { label: '本周活跃用户', value: stats.week_active_users, unit: '人' }, + { label: '群组数量', value: stats.group_count, unit: '个' }, + { label: '成员总数', value: stats.member_count, unit: '人' }, + { label: '问答记录数', value: stats.qa_count, unit: '条' } + ]; + + statistics.forEach(stat => { + const statItem = document.createElement('div'); + statItem.className = 'stat-item'; + statItem.innerHTML = ` +
    ${stat.value}${stat.unit}
    +
    ${stat.label}
    + `; + statGrid.appendChild(statItem); + }); +} + +function displayCategoryChart(categories) { + const categoryItems = document.getElementById('category-items'); + categoryItems.innerHTML = ''; + + Object.entries(categories).forEach(([category, percentage]) => { + const categoryItem = document.createElement('div'); + categoryItem.className = 'category-item'; + categoryItem.innerHTML = ` + ${category} +
    + ${percentage}% + `; + categoryItems.appendChild(categoryItem); + }); +} + +function exportReport() { + const reportContent = document.getElementById('report-content').textContent; + if (!reportContent) { + showError('请先生成周报'); + return; + } + + const blob = new Blob([reportContent], { type: 'text/markdown' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `运营周报_${document.getElementById('week').value}.md`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +} + +// 页面加载时自动生成本周周报 +window.addEventListener('load', function() { + generateCurrentWeekReport(); +}); + +// 支持回车键生成报告 +document.getElementById('week').addEventListener('keypress', function(e) { + if (e.key === 'Enter') { + generateReport(); + } +}); \ No newline at end of file diff --git a/templates/daily_report.html b/templates/daily_report.html new file mode 100644 index 0000000..7e09030 --- /dev/null +++ b/templates/daily_report.html @@ -0,0 +1,50 @@ + + + + + + 运营日报 - 致远速联 + + + + +
    + + +
    +

    运营日报生成器

    +

    致远速联高端社群运营数据分析

    +
    + +
    +
    + + + + +
    +
    + + + + + + +
    + + + + \ No newline at end of file diff --git a/templates/index.html b/templates/index.html index 7d95d6b..8925a7a 100644 --- a/templates/index.html +++ b/templates/index.html @@ -4,884 +4,89 @@ 企业微信聊天记录查看器 - + -
    -
    -

    企业微信聊天记录查看器

    -

    基于企业微信会话数据库的实时聊天记录展示

    - -
    - -
    -
    -
    0
    -
    用户数量
    -
    -
    -
    0
    -
    群组数量
    -
    -
    -
    0
    -
    消息总数
    -
    -
    -
    0
    -
    文件数量
    -
    -
    - -
    - -
    - -
    - - -
    -
    -
    全部聊天记录
    -
    - 消息数量: 加载中... - 最新消息: 加载中... -
    -
    - -
    -
    正在加载消息...
    -
    - -
    - -
    -
    -
    +
    + - - - - - +
    + +
    +
    +
    0
    +
    用户数量
    +
    +
    +
    0
    +
    群组数量
    +
    +
    +
    0
    +
    消息总数
    +
    +
    +
    0
    +
    文件数量
    +
    +
    + +
    + +
    + +
    + + +
    +
    +
    全部聊天记录
    +
    + 消息数量: 加载中... + 最新消息: 加载中... +
    +
    + +
    +
    正在加载消息...
    +
    + +
    + +
    +
    +
    +
    + + + + + \ No newline at end of file diff --git a/templates/qa.html b/templates/qa.html index ebe74ee..6361e98 100644 --- a/templates/qa.html +++ b/templates/qa.html @@ -4,500 +4,20 @@ 问答管理系统 - + -
    +

    问答管理系统

    管理问题和答案的关联关系

    -
    +
    - - // 页面加载时获取QA列表 - document.addEventListener('DOMContentLoaded', function () { - loadQAList(); - }); - - // 加载QA列表 - async function loadQAList() { - try { - const response = await fetch('/api/qa'); - const result = await response.json(); - - if (result.success) { - displayQAList(result.qa_list); - } else { - alert('加载QA列表失败: ' + result.error); - } - } catch (error) { - alert('加载QA列表时出错: ' + error.message); - } - } - - // 显示QA列表 - async function displayQAList(qaList) { - const qaListContainer = document.getElementById('qaList'); - - if (qaList.length === 0) { - qaListContainer.innerHTML = ` -
    -
    📝
    -

    暂无QA记录

    -

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

    -
    - `; - return; - } - - // 获取所有消息的详细内容 - let allMessageIds = []; - qaList.forEach(qa => { - allMessageIds = [...allMessageIds, ...qa.question_list, ...qa.answer_list]; - }); - - let messageMap = {}; - if (allMessageIds.length > 0) { - try { - const response = await fetch('/api/messages_by_ids', { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({message_ids: allMessageIds}) - }); - const result = await response.json(); - if (result.success) { - result.messages.forEach(msg => { - messageMap[msg.id] = msg; - }); - } - } catch (error) { - console.error('获取消息详情时出错:', error); - } - } - - qaListContainer.innerHTML = qaList.map(qa => { - // 获取第一个问题的内容作为显示 - let questionContent = '暂无问题内容'; - if (qa.question_list && qa.question_list.length > 0) { - const firstQuestionId = qa.question_list[0]; - const message = messageMap[firstQuestionId]; - if (message && message.content) { - questionContent = message.content; - } else { - questionContent = `问题消息ID: ${firstQuestionId}`; - } - } - - // 截取问题内容,超过30个字用省略号 - if (questionContent.length > 30) { - questionContent = questionContent.substring(0, 30) + '...'; - } - - return ` -
    -
    -
    QA #${qa.id}
    -
    ${qa.groupId || '无群组'}
    -
    - -
    -
    - 问题: ${questionContent} -
    -
    - 问题: ${qa.question_list.length}条 - 答案: ${qa.answer_list.length}条 -
    -
    - -
    - - - -
    -
    - `; - }).join(''); - } - - // 搜索消息 - async function searchMessages() { - const keyword = document.getElementById('searchInput').value.trim(); - if (!keyword) { - alert('请输入搜索关键词'); - return; - } - - try { - const response = await fetch(`/api/search_messages?keyword=${encodeURIComponent(keyword)}`); - const result = await response.json(); - - if (result.success) { - displaySearchResults(result.messages); - } else { - alert('搜索失败: ' + result.error); - } - } catch (error) { - alert('搜索时出错: ' + error.message); - } - } - - // 显示搜索结果 - function displaySearchResults(messages) { - const qaListContainer = document.getElementById('qaList'); - - if (messages.length === 0) { - qaListContainer.innerHTML = ` -
    -
    🔍
    -

    未找到相关消息

    -

    请尝试其他搜索关键词

    -
    - `; - return; - } - - qaListContainer.innerHTML = messages.map(msg => ` -
    -
    -
    消息ID: ${msg.id}
    -
    ${msg.formatted_time || '未知时间'}
    -
    - -
    -
    - 类型: ${msg.type} | - 发送者: ${msg.sender || '未知'} | - 接收者: ${msg.receiver || '未知'} -
    -
    - 内容: ${msg.content || '无内容'} -
    -
    - -
    - - -
    -
    - `).join(''); - } - - // 打开创建模态框 - function openCreateModal() { - currentQA = null; - selectedQuestions = []; - selectedAnswers = []; - - document.getElementById('modalTitle').textContent = '创建QA记录'; - document.getElementById('groupId').value = ''; - updateSelectedMessages(); - - document.getElementById('qaModal').style.display = 'block'; - } - - // 编辑QA - async function editQA(qaId) { - try { - const response = await fetch(`/api/qa/${qaId}`); - const result = await response.json(); - - if (result.success) { - currentQA = result.qa; - selectedQuestions = [...currentQA.question_list]; - selectedAnswers = [...currentQA.answer_list]; - - document.getElementById('modalTitle').textContent = '编辑QA记录'; - document.getElementById('groupId').value = currentQA.groupId || ''; - updateSelectedMessages(); - - document.getElementById('qaModal').style.display = 'block'; - } else { - alert('加载QA详情失败: ' + result.error); - } - } catch (error) { - alert('加载QA详情时出错: ' + error.message); - } - } - - // 搜索问题消息 - async function searchQuestionMessages() { - const keyword = document.getElementById('questionSearch').value.trim(); - if (!keyword) { - document.getElementById('questionResults').innerHTML = ''; - return; - } - - try { - const response = await fetch(`/api/search_messages?keyword=${encodeURIComponent(keyword)}&limit=20`); - const result = await response.json(); - - if (result.success) { - displayQuestionResults(result.messages); - } - } catch (error) { - console.error('搜索问题消息时出错:', error); - } - } - - // 显示问题搜索结果 - function displayQuestionResults(messages) { - const resultsContainer = document.getElementById('questionResults'); - - resultsContainer.innerHTML = messages.map(msg => ` -
    -
    ID: ${msg.id}
    -
    内容: ${msg.content ? msg.content.substring(0, 100) + (msg.content.length > 100 ? '...' : '') : '无内容'}
    -
    时间: ${msg.formatted_time || '未知'}
    -
    - `).join(''); - } - - // 搜索答案消息 - async function searchAnswerMessages() { - const keyword = document.getElementById('answerSearch').value.trim(); - if (!keyword) { - document.getElementById('answerResults').innerHTML = ''; - return; - } - - try { - const response = await fetch(`/api/search_messages?keyword=${encodeURIComponent(keyword)}&limit=20`); - const result = await response.json(); - - if (result.success) { - displayAnswerResults(result.messages); - } - } catch (error) { - console.error('搜索答案消息时出错:', error); - } - } - - // 显示答案搜索结果 - function displayAnswerResults(messages) { - const resultsContainer = document.getElementById('answerResults'); - - resultsContainer.innerHTML = messages.map(msg => ` -
    -
    ID: ${msg.id}
    -
    内容: ${msg.content ? msg.content.substring(0, 100) + (msg.content.length > 100 ? '...' : '') : '无内容'}
    -
    时间: ${msg.formatted_time || '未知'}
    -
    - `).join(''); - } - - // 选择问题消息 - function selectQuestion(messageId, content) { - if (!selectedQuestions.includes(messageId)) { - selectedQuestions.push(messageId); - updateSelectedMessages(); - } - } - - // 选择答案消息 - function selectAnswer(messageId, content) { - if (!selectedAnswers.includes(messageId)) { - selectedAnswers.push(messageId); - updateSelectedMessages(); - } - } - - // 从搜索结果添加为问题 - function addToQuestion(messageId) { - if (!selectedQuestions.includes(messageId)) { - selectedQuestions.push(messageId); - alert('已添加到问题列表'); - } - } - - // 从搜索结果添加为答案 - function addToAnswer(messageId) { - if (!selectedAnswers.includes(messageId)) { - selectedAnswers.push(messageId); - alert('已添加到答案列表'); - } - } - - // 更新已选择的消息显示 - function updateSelectedMessages() { - document.getElementById('selectedQuestions').innerHTML = selectedQuestions.map(id => ` -
    - 消息ID: ${id} - -
    - `).join(''); - - document.getElementById('selectedAnswers').innerHTML = selectedAnswers.map(id => ` -
    - 消息ID: ${id} - -
    - `).join(''); - } - - // 移除问题消息 - function removeQuestion(messageId) { - selectedQuestions = selectedQuestions.filter(id => id !== messageId); - updateSelectedMessages(); - } - - // 移除答案消息 - function removeAnswer(messageId) { - selectedAnswers = selectedAnswers.filter(id => id !== messageId); - updateSelectedMessages(); - } - - // 保存QA记录 - async function saveQA() { - const groupId = document.getElementById('groupId').value.trim(); - - if (selectedQuestions.length === 0) { - alert('请至少选择一个问题消息'); - return; - } - - if (selectedAnswers.length === 0) { - alert('请至少选择一个答案消息'); - return; - } - - const qaData = { - groupId: groupId, - question: selectedQuestions, - answer: selectedAnswers - }; - - try { - const url = currentQA ? `/api/qa/${currentQA.id}` : '/api/qa'; - const method = currentQA ? 'PUT' : 'POST'; - - const response = await fetch(url, { - method: method, - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(qaData) - }); - - const result = await response.json(); - - if (result.success) { - alert(currentQA ? 'QA记录更新成功' : 'QA记录创建成功'); - closeModal(); - loadQAList(); - } else { - alert('保存失败: ' + result.error); - } - } catch (error) { - alert('保存时出错: ' + error.message); - } - } - - // 预览QA - async function previewQA(qaId) { - try { - const response = await fetch(`/api/qa/${qaId}`); - const result = await response.json(); - - if (result.success) { - displayPreview(result.qa); - } else { - alert('加载QA详情失败: ' + result.error); - } - } catch (error) { - alert('加载QA详情时出错: ' + error.message); - } - } - - // 显示预览 - async function displayPreview(qa) { - const previewContent = document.getElementById('previewContent'); - - // 获取所有消息的详细内容 - let allMessages = []; - const allMessageIds = [...qa.question_list, ...qa.answer_list]; - - if (allMessageIds.length > 0) { - try { - const response = await fetch('/api/messages_by_ids', { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({message_ids: allMessageIds}) - }); - const result = await response.json(); - if (result.success) { - allMessages = result.messages; - } - } catch (error) { - console.error('获取消息详情时出错:', error); - } - } - - // 创建消息映射 - const messageMap = {}; - allMessages.forEach(msg => { - messageMap[msg.id] = msg; - }); - - // 按时间排序所有消息 - const sortedMessages = allMessages.sort((a, b) => { - return new Date(a.time) - new Date(b.time); - }); - - previewContent.innerHTML = ` -
    -
    -

    QA #${qa.id} - 聊天记录预览

    -
    群组: ${qa.groupId || '无群组'} | 消息数量: ${sortedMessages.length}
    -
    - -
    - ${sortedMessages.map(msg => { - - const isQuestion = qa.question_list.includes(msg.id); - const isAnswer = qa.answer_list.includes(msg.id); - const messageType = isQuestion ? 'question' : (isAnswer ? 'answer' : 'other'); - - return ` -
    -
    - ${messageType === 'question' ? '❓' : (messageType === 'answer' ? '💬' : '📝')} -
    -
    -
    - ${msg.sender || '未知用户'} - ${msg.formatted_time || '未知时间'} - ${messageType === 'question' ? '问题' : (messageType === 'answer' ? '答案' : '其他')} -
    -
    ${msg.content || '无内容'}
    -
    - 消息ID: ${msg.id} - 类型: ${msg.type || '未知'} -
    -
    -
    - `; - }).join('')} -
    - -
    -
    - 问题数量: - ${qa.question_list.length} -
    -
    - 答案数量: - ${qa.answer_list.length} -
    -
    - 总消息数: - ${sortedMessages.length} -
    -
    -
    - `; - - document.getElementById('previewModal').style.display = 'block'; - } - - // 删除QA - async function deleteQA(qaId) { - if (!confirm('确定要删除这个QA记录吗?此操作不可恢复。')) { - return; - } - - try { - const response = await fetch(`/api/qa/${qaId}`, { - method: 'DELETE' - }); - - const result = await response.json(); - - if (result.success) { - alert('QA记录删除成功'); - loadQAList(); - } else { - alert('删除失败: ' + result.error); - } - } catch (error) { - alert('删除时出错: ' + error.message); - } - } - - // 关闭模态框 - function closeModal() { - document.getElementById('qaModal').style.display = 'none'; - } - - // 关闭预览模态框 - function closePreviewModal() { - document.getElementById('previewModal').style.display = 'none'; - } - - // 点击模态框外部关闭 - window.onclick = function (event) { - const modal = document.getElementById('qaModal'); - const previewModal = document.getElementById('previewModal'); - - if (event.target === modal) { - modal.style.display = 'none'; - } - if (event.target === previewModal) { - previewModal.style.display = 'none'; - } - } - \ No newline at end of file diff --git a/templates/template.md b/templates/template.md deleted file mode 100644 index 2f45565..0000000 --- a/templates/template.md +++ /dev/null @@ -1,39 +0,0 @@ -以下是群中的消息记录 - -```json -[ -{"user": "wmAHzSCAAAheHVxal-lGkJVN7H2rLCyg", "time": "1761102279795", "content": "各位老师,这条规定来源哪个文件,有了解的吗,大家一般是严格按这个标准写原因吗"} , -{"user": "wmAHzSCAAAeOuRy3QGoK7g7ACTquBLqQ", "time": "1761102335857", "content": "公告格式里有季报的格式要求"} , -{"user": "wmAHzSCAAAHDp8njcrAkkOPLbaS2B0tw", "time": "1761102409786", "content": "不是写了“主要”两个字[憨笑]"} , -{"user": "wmAHzSCAAAheHVxal-lGkJVN7H2rLCyg", "time": "1761102612486", "content": "好嘞懂了,谢谢各位[抱拳]"} , -{"user": "wmAHzSCAAAheHVxal-lGkJVN7H2rLCyg", "time": "1761119889355", "content": "各位老师,三季报中这块选否的话是不是不用填下边的表了"} , -{"user": "wmAHzSCAAAMUW-BIILUWQpZtE5Pc5xoQ", "time": "1761130830609", "content": "请教一下,在公告编制系统填写股东会通知,股东会召集人没有董事会选项怎么整?"} , -{"user": "wmAHzSCAAArhe26Lm6YQb7Dai0zkZdjQ", "time": "1761131499914", "content": "我之前看是有的"} , -{"user": "wmAHzSCAAAMUW-BIILUWQpZtE5Pc5xoQ", "time": "1761131937412", "content": "今天没了[捂脸]"} , -{"user": "wmAHzSCAAAo1A0E7Lox5KQpNm--NfDjA", "time": "1761132189834", "content": "「300322 张利容:[图片]」\n- - - - - - - - - - - - - - -\n@300174 兰靖 证代 创建公告的这里,需要选择这个。"} , -] -``` - -找到其中的问题和回答,如果没有回答就只整理问题,问题是与产品填报系统,上市公司,证券政策相关的问题 -问题可能不只由一句话构成,回答也可能不只由一句话构成 -多个问题需要分开放置 -输出格式 - -```json -[ - { - "question": [{ - "user": "用户1", - "time": "时间戳", - "content": "问题" - }], - "answer": [ - { - "user": "用户1", - "time": "时间戳", - "content": "回答" - } - ] - } -] -``` \ No newline at end of file diff --git a/templates/weekly_report.html b/templates/weekly_report.html new file mode 100644 index 0000000..07ede2d --- /dev/null +++ b/templates/weekly_report.html @@ -0,0 +1,54 @@ + + + + + + 运营周报 - 致远速联 + + + +
    + + +
    +

    运营周报生成器

    +

    致远速联高端社群运营周度数据分析

    +
    + +
    +
    + + + + + +
    +
    + + + + + + +
    + + + + \ No newline at end of file diff --git a/tools.py b/tools.py new file mode 100644 index 0000000..9db60f3 --- /dev/null +++ b/tools.py @@ -0,0 +1,329 @@ +import time +import datetime +from typing import Union, Optional + + +class TimeUtils: + """ + 时间工具类 + 支持时间戳、时间字符串等多种格式的时间处理,以及相互转换和时间计算 + """ + + # 常用时间格式 + FORMAT_DATETIME = "%Y-%m-%d %H:%M:%S" + FORMAT_DATE = "%Y-%m-%d" + FORMAT_TIME = "%H:%M:%S" + FORMAT_DATETIME_COMPACT = "%Y%m%d%H%M%S" + FORMAT_DATE_COMPACT = "%Y%m%d" + + def __init__(self, time_input: Optional[Union[str, int, float, datetime.datetime]] = None): + """ + 初始化时间工具 + + Args: + time_input: 时间输入,可以是: + - 时间戳(整数或浮点数) + - 时间字符串(支持多种格式) + - datetime对象 + - None(使用当前时间) + """ + if time_input is None: + self.datetime_obj = datetime.datetime.now() + elif isinstance(time_input, (int, float)): + self.datetime_obj = datetime.datetime.fromtimestamp(time_input) + elif isinstance(time_input, str): + self.datetime_obj = self._parse_string(time_input) + elif isinstance(time_input, datetime.datetime): + self.datetime_obj = time_input + else: + raise ValueError(f"不支持的时间输入类型: {type(time_input)}") + + def _parse_string(self, time_str: str) -> datetime.datetime: + """ + 解析时间字符串,支持多种格式 + + Args: + time_str: 时间字符串 + + Returns: + datetime对象 + """ + # 尝试多种格式进行解析 + formats = [ + self.FORMAT_DATETIME, # 2023-01-01 12:00:00 + self.FORMAT_DATE, # 2023-01-01 + self.FORMAT_DATETIME_COMPACT, # 20230101120000 + self.FORMAT_DATE_COMPACT, # 20230101 + "%Y/%m/%d %H:%M:%S", # 2023/01/01 12:00:00 + "%Y/%m/%d", # 2023/01/01 + "%Y年%m月%d日 %H时%M分%S秒", # 2023年01月01日 12时00分00秒 + "%Y年%m月%d日", # 2023年01月01日 + ] + + for fmt in formats: + try: + return datetime.datetime.strptime(time_str, fmt) + except ValueError: + continue + + # 如果所有格式都失败,尝试自动解析 + try: + return datetime.datetime.fromisoformat(time_str.replace('Z', '+00:00')) + except ValueError: + raise ValueError(f"无法解析时间字符串: {time_str}") + + def to_timestamp(self) -> float: + """ + 转换为时间戳 + + Returns: + 时间戳(浮点数) + """ + return self.datetime_obj.timestamp() + + def to_string(self, fmt: str = FORMAT_DATETIME) -> str: + """ + 转换为字符串格式 + + Args: + fmt: 时间格式字符串 + + Returns: + 格式化后的时间字符串 + """ + return self.datetime_obj.strftime(fmt) + + def to_datetime(self) -> datetime.datetime: + """ + 转换为datetime对象 + + Returns: + datetime对象 + """ + return self.datetime_obj + + def add_days(self, days: int) -> 'TimeUtils': + """ + 添加天数 + + Args: + days: 天数(可以为负数) + + Returns: + 新的TimeUtils对象 + """ + new_datetime = self.datetime_obj + datetime.timedelta(days=days) + return TimeUtils(new_datetime) + + def add_hours(self, hours: int) -> 'TimeUtils': + """ + 添加小时数 + + Args: + hours: 小时数(可以为负数) + + Returns: + 新的TimeUtils对象 + """ + new_datetime = self.datetime_obj + datetime.timedelta(hours=hours) + return TimeUtils(new_datetime) + + def add_minutes(self, minutes: int) -> 'TimeUtils': + """ + 添加分钟数 + + Args: + minutes: 分钟数(可以为负数) + + Returns: + 新的TimeUtils对象 + """ + new_datetime = self.datetime_obj + datetime.timedelta(minutes=minutes) + return TimeUtils(new_datetime) + + def add_seconds(self, seconds: int) -> 'TimeUtils': + """ + 添加秒数 + + Args: + seconds: 秒数(可以为负数) + + Returns: + 新的TimeUtils对象 + """ + new_datetime = self.datetime_obj + datetime.timedelta(seconds=seconds) + return TimeUtils(new_datetime) + + def days_ago(self, days: int) -> 'TimeUtils': + """ + 计算n天前的日期时间 + + Args: + days: 天数 + + Returns: + 新的TimeUtils对象 + """ + return self.add_days(-days) + + def days_after(self, days: int) -> 'TimeUtils': + """ + 计算n天后的日期时间 + + Args: + days: 天数 + + Returns: + 新的TimeUtils对象 + """ + return self.add_days(days) + + def start_of_day(self) -> 'TimeUtils': + """ + 获取当天的开始时间(00:00:00) + + Returns: + 新的TimeUtils对象 + """ + new_datetime = self.datetime_obj.replace(hour=0, minute=0, second=0, microsecond=0) + return TimeUtils(new_datetime) + + def end_of_day(self) -> 'TimeUtils': + """ + 获取当天的结束时间(23:59:59) + + Returns: + 新的TimeUtils对象 + """ + new_datetime = self.datetime_obj.replace(hour=23, minute=59, second=59, microsecond=999999) + return TimeUtils(new_datetime) + + def diff_seconds(self, other: 'TimeUtils') -> float: + """ + 计算两个时间的秒数差 + + Args: + other: 另一个TimeUtils对象 + + Returns: + 秒数差(self - other) + """ + return (self.datetime_obj - other.datetime_obj).total_seconds() + + def diff_days(self, other: 'TimeUtils') -> float: + """ + 计算两个时间的天数差 + + Args: + other: 另一个TimeUtils对象 + + Returns: + 天数差(self - other) + """ + return (self.datetime_obj - other.datetime_obj).days + + def is_after(self, other: 'TimeUtils') -> bool: + """ + 判断是否在另一个时间之后 + + Args: + other: 另一个TimeUtils对象 + + Returns: + bool值 + """ + return self.datetime_obj > other.datetime_obj + + def is_before(self, other: 'TimeUtils') -> bool: + """ + 判断是否在另一个时间之前 + + Args: + other: 另一个TimeUtils对象 + + Returns: + bool值 + """ + return self.datetime_obj < other.datetime_obj + + def is_same_day(self, other: 'TimeUtils') -> bool: + """ + 判断是否在同一天 + + Args: + other: 另一个TimeUtils对象 + + Returns: + bool值 + """ + return (self.datetime_obj.year == other.datetime_obj.year and + self.datetime_obj.month == other.datetime_obj.month and + self.datetime_obj.day == other.datetime_obj.day) + + def format_custom(self, fmt: str) -> str: + """ + 自定义格式化输出 + + Args: + fmt: 格式化字符串 + + Returns: + 格式化后的字符串 + """ + return self.datetime_obj.strftime(fmt) + + def __str__(self) -> str: + """字符串表示""" + return self.to_string() + + def __repr__(self) -> str: + """repr表示""" + return f"TimeUtils('{self.to_string()}')" + + +# 工具函数 +def now() -> TimeUtils: + """获取当前时间的TimeUtils对象""" + return TimeUtils() + + +def from_timestamp(timestamp: Union[int, float]) -> TimeUtils: + """从时间戳创建TimeUtils对象""" + return TimeUtils(timestamp) + + +def from_string(time_str: str) -> TimeUtils: + """从时间字符串创建TimeUtils对象""" + return TimeUtils(time_str) + + +def from_datetime(dt: datetime.datetime) -> TimeUtils: + """从datetime对象创建TimeUtils对象""" + return TimeUtils(dt) + + +def get_timestamp() -> float: + """获取当前时间戳""" + return time.time() + + +def format_timestamp(timestamp: Union[int, float], fmt: str = TimeUtils.FORMAT_DATETIME) -> str: + """格式化时间戳""" + return TimeUtils(timestamp).to_string(fmt) + + +def parse_string(time_str: str) -> datetime.datetime: + """解析时间字符串为datetime对象""" + return TimeUtils(time_str).to_datetime() + + +def days_ago(days: int, base_time: Optional[Union[str, int, float, datetime.datetime]] = None) -> TimeUtils: + """计算n天前的日期时间""" + base = TimeUtils(base_time) if base_time else now() + return base.days_ago(days) + + +def days_after(days: int, base_time: Optional[Union[str, int, float, datetime.datetime]] = None) -> TimeUtils: + """计算n天后的日期时间""" + base = TimeUtils(base_time) if base_time else now() + return base.days_after(days)