Compare commits
3 Commits
7458fe688f
...
bf7ec6737d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf7ec6737d | ||
|
|
8ff1b80be6 | ||
|
|
37c6ae9457 |
174
app.py
174
app.py
@@ -1,13 +1,16 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import Flask, render_template, jsonify, request
|
||||
import requests
|
||||
from flask import Flask, jsonify, request, render_template
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from chat_session import agent, ChatSessionManager
|
||||
from tools import TimeUtils, now, from_string, from_datetime, format_timestamp, DatabaseManager
|
||||
from file import ObjectFileManager
|
||||
from tools import TimeUtils, now, from_string, from_datetime, format_timestamp, DatabaseManager, transform_template, \
|
||||
report_template_render
|
||||
|
||||
|
||||
class MessageRender:
|
||||
@@ -138,8 +141,8 @@ class ReportService:
|
||||
"""获取按小时统计的消息量"""
|
||||
return self.execute_query('''
|
||||
SELECT strftime('%H',
|
||||
datetime(substr(time, 0, 11), 'unixepoch', 'localtime')) as hour,
|
||||
COUNT(*) as count
|
||||
datetime(substr(time, 0, 11), 'unixepoch', '+8 hours')) as hour,
|
||||
COUNT(*) as count
|
||||
FROM message
|
||||
WHERE time >= ?
|
||||
AND time <= ?
|
||||
@@ -187,7 +190,7 @@ class ReportService:
|
||||
placeholders = ','.join(['?'] * len(message_ids))
|
||||
query = f"""
|
||||
SELECT m.id, m.content, m.type, m.sender, m.receiver,u.name as sender_name,
|
||||
datetime(substr(time,0,11), 'unixepoch','localtime') as formatted_time
|
||||
datetime(substr(time,0,11), 'unixepoch','+8 hours') as formatted_time
|
||||
FROM message m
|
||||
left join user u on m.sender = u.id
|
||||
WHERE m.id IN ({placeholders})
|
||||
@@ -200,9 +203,9 @@ class ReportService:
|
||||
"""获取消息列表"""
|
||||
query = '''
|
||||
SELECT m.*,
|
||||
u.name as sender_name,
|
||||
g.name as group_name,
|
||||
datetime(substr(time, 0, 11), 'unixepoch', 'localtime') as formatted_time
|
||||
u.name as sender_name,
|
||||
g.name as group_name,
|
||||
datetime(substr(time, 0, 11), 'unixepoch', '+8 hours') as formatted_time
|
||||
FROM message m
|
||||
LEFT JOIN user u ON m.sender = u.id
|
||||
LEFT JOIN "group" g ON m.receiver = g.id
|
||||
@@ -233,8 +236,8 @@ class ReportService:
|
||||
if not group_id:
|
||||
query = '''
|
||||
SELECT m.*,
|
||||
u.name as sender_name,
|
||||
datetime(substr(m.time, 0, 11), 'unixepoch', 'localtime') as formatted_time
|
||||
u.name as sender_name,
|
||||
datetime(substr(m.time, 0, 11), 'unixepoch', '+8 hours') as formatted_time
|
||||
FROM message m
|
||||
LEFT JOIN user u ON m.sender = u.id
|
||||
WHERE m.toType = 1
|
||||
@@ -246,8 +249,8 @@ class ReportService:
|
||||
else:
|
||||
query = '''
|
||||
SELECT m.*,
|
||||
u.name as sender_name,
|
||||
datetime(substr(m.time, 0, 11), 'unixepoch', 'localtime') as formatted_time
|
||||
u.name as sender_name,
|
||||
datetime(substr(m.time, 0, 11), 'unixepoch', '+8 hours') as formatted_time
|
||||
FROM message m
|
||||
LEFT JOIN user u ON m.sender = u.id
|
||||
WHERE m.receiver = ?
|
||||
@@ -267,7 +270,7 @@ class ReportService:
|
||||
AND type NOT IN ('disagree', 'agree', 'weapp', 'link')
|
||||
''', (group_id,), fetch_all=False)['count']
|
||||
lastest_time = self.execute_query('''
|
||||
SELECT datetime(substr(time, 0, 11), 'unixepoch', 'localtime') as formatted_time
|
||||
SELECT datetime(substr(time, 0, 11), 'unixepoch', '+8 hours') as formatted_time
|
||||
FROM message
|
||||
WHERE receiver = ?
|
||||
AND type NOT IN ('disagree', 'agree', 'weapp', 'link')
|
||||
@@ -299,9 +302,9 @@ class ReportService:
|
||||
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
|
||||
u.name as sender_name,
|
||||
g.name as group_name,
|
||||
datetime(substr(m.time, 0, 11), 'unixepoch', '+8 hours') as formatted_time
|
||||
FROM message m
|
||||
LEFT JOIN user u ON m.sender = u.id
|
||||
LEFT JOIN "group" g ON m.receiver = g.id
|
||||
@@ -315,9 +318,9 @@ class ReportService:
|
||||
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
|
||||
u.name as sender_name,
|
||||
g.name as group_name,
|
||||
datetime(substr(m.time, 0, 11), 'unixepoch', '+8 hours') as formatted_time
|
||||
FROM message m
|
||||
LEFT JOIN user u ON m.sender = u.id
|
||||
LEFT JOIN "group" g ON m.receiver = g.id
|
||||
@@ -469,19 +472,22 @@ class ReportService:
|
||||
app = Flask(__name__)
|
||||
app.template_folder = 'templates'
|
||||
# 初始化管理器
|
||||
ofm = ObjectFileManager()
|
||||
db_manager = DatabaseManager('db/data', online_db_uri="zysl-log/wework/chat_msg/db/data.db")
|
||||
report_service = ReportService(db_manager)
|
||||
message_processor = MessageRender()
|
||||
chat_session = ChatSessionManager(db_manager)
|
||||
|
||||
|
||||
def api_response(success=True, data=None, error = None, status_code=200):
|
||||
def api_response(success=True, data=None, error=None, status_code=200, content=None):
|
||||
"""统一的API响应格式"""
|
||||
response = {'success': success}
|
||||
if error:
|
||||
response['error'] = str(error)
|
||||
if data:
|
||||
response.update(data)
|
||||
if content:
|
||||
response["data"] = content
|
||||
return jsonify(response), status_code
|
||||
|
||||
|
||||
@@ -510,6 +516,12 @@ def daily_report_page():
|
||||
return render_template('daily_report.html')
|
||||
|
||||
|
||||
@app.route('/markdown')
|
||||
def markdown_page():
|
||||
"""markdown页面"""
|
||||
return render_template('markdown.html')
|
||||
|
||||
|
||||
@app.route('/api/db/datetime')
|
||||
def db_status():
|
||||
return api_response(success=True, data={'message': chat_session.status()})
|
||||
@@ -666,21 +678,21 @@ def search_messages():
|
||||
return api_response(success=False, error='请输入搜索关键词', status_code=400)
|
||||
|
||||
group_id = request.args.get('group_id', type=str)
|
||||
|
||||
|
||||
# 智能搜索:支持模糊匹配和精确匹配
|
||||
messages_data = report_service.search_messages(keyword, limit, group_id)
|
||||
|
||||
|
||||
# 根据搜索类型过滤消息
|
||||
if search_type == 'question':
|
||||
messages_data = [msg for msg in messages_data if msg.get('type') in ['text', 'mixed']]
|
||||
elif search_type == 'answer':
|
||||
messages_data = [msg for msg in messages_data if msg.get('type') in ['text', 'mixed']]
|
||||
|
||||
|
||||
formatted_messages = []
|
||||
for msg in messages_data:
|
||||
message = dict(msg)
|
||||
message = message_processor.process_message_content(message)
|
||||
|
||||
|
||||
# 添加搜索关键词高亮
|
||||
if keyword:
|
||||
content = message.get('content', '')
|
||||
@@ -688,7 +700,7 @@ def search_messages():
|
||||
# 简单的关键词高亮(前端可以进一步处理)
|
||||
highlighted_content = content.replace(keyword, f'<mark>{keyword}</mark>')
|
||||
message['highlighted_content'] = highlighted_content
|
||||
|
||||
|
||||
formatted_messages.append(message)
|
||||
|
||||
return api_response(data={'messages': formatted_messages, 'total': len(formatted_messages)})
|
||||
@@ -703,13 +715,13 @@ def search_suggestions():
|
||||
"""搜索建议API"""
|
||||
try:
|
||||
keyword = request.args.get('keyword', '')
|
||||
|
||||
|
||||
if not keyword:
|
||||
return api_response(data={'suggestions': []})
|
||||
|
||||
|
||||
# 获取热门搜索关键词
|
||||
suggestions = []
|
||||
|
||||
|
||||
# 1. 从消息内容中提取相关关键词
|
||||
try:
|
||||
messages = report_service.search_messages(keyword, 10, None)
|
||||
@@ -727,7 +739,7 @@ def search_suggestions():
|
||||
break
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
# 2. 添加常见搜索关键词
|
||||
common_keywords = ['信息披露', '公司治理', '业务操作', '系统填报', '政策法规', '季度报告', '股东大会']
|
||||
for kw in common_keywords:
|
||||
@@ -735,9 +747,9 @@ def search_suggestions():
|
||||
suggestions.append(kw)
|
||||
if len(suggestions) >= 8:
|
||||
break
|
||||
|
||||
|
||||
return api_response(data={'suggestions': suggestions[:8]})
|
||||
|
||||
|
||||
except Exception as e:
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
@@ -752,34 +764,34 @@ def get_qa_list():
|
||||
keyword = request.args.get('keyword', '')
|
||||
start_time = request.args.get('start_time', '')
|
||||
end_time = request.args.get('end_time', '')
|
||||
|
||||
|
||||
# 构建查询条件
|
||||
query_conditions = []
|
||||
query_params = []
|
||||
|
||||
|
||||
if group_id:
|
||||
query_conditions.append("groupId LIKE ?")
|
||||
query_params.append(f"%{group_id}%")
|
||||
|
||||
|
||||
if start_time and end_time:
|
||||
query_conditions.append("start_time >= ? AND end_time <= ?")
|
||||
query_params.extend([f"{start_time}000", f"{end_time}999"])
|
||||
|
||||
|
||||
# 构建查询语句
|
||||
base_query = "SELECT * FROM qa"
|
||||
if query_conditions:
|
||||
base_query += " WHERE " + " AND ".join(query_conditions)
|
||||
base_query += " ORDER BY id DESC"
|
||||
|
||||
|
||||
# 执行查询
|
||||
conn = db_manager.get_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(base_query, query_params)
|
||||
qa_data = cursor.fetchall()
|
||||
conn.close()
|
||||
|
||||
|
||||
qa_list = [dict(qa) for qa in qa_data]
|
||||
|
||||
|
||||
# 如果有关键词搜索,进行内容过滤
|
||||
if keyword:
|
||||
filtered_qa_list = []
|
||||
@@ -788,7 +800,7 @@ def get_qa_list():
|
||||
if keyword.lower() in (qa.get('groupId') or '').lower():
|
||||
filtered_qa_list.append(qa)
|
||||
continue
|
||||
|
||||
|
||||
# 检查问题内容是否匹配
|
||||
try:
|
||||
question_ids = json.loads(qa.get('question', '[]'))
|
||||
@@ -801,9 +813,9 @@ def get_qa_list():
|
||||
break
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
qa_list = filtered_qa_list
|
||||
|
||||
|
||||
return api_response(data={'qa_list': qa_list, 'total': len(qa_list)})
|
||||
except Exception as e:
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
@@ -844,7 +856,8 @@ def create_qa():
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO qa (groupId, question, answer,start_time,end_time) VALUES (?,?,?,?,?)
|
||||
INSERT INTO qa (groupId, question, answer, start_time, end_time)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
''', (group_id, json.dumps(question_ids), json.dumps(answer_ids),
|
||||
data.get('start_time', ''), data.get('end_time', '')))
|
||||
|
||||
@@ -914,28 +927,29 @@ def delete_qa(qa_id):
|
||||
except Exception as e:
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
|
||||
@app.route('/api/qa/batch', methods=['DELETE'])
|
||||
def batch_delete_qa():
|
||||
"""批量删除QA记录API"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
qa_ids = data.get('qa_ids', [])
|
||||
|
||||
|
||||
if not qa_ids:
|
||||
return api_response(success=False, error='请提供要删除的QA记录ID列表', status_code=400)
|
||||
|
||||
|
||||
# 检查所有记录是否存在
|
||||
for qa_id in qa_ids:
|
||||
if not report_service.check_qa_exists(qa_id):
|
||||
return api_response(success=False, error=f'QA记录 {qa_id} 不存在', status_code=404)
|
||||
|
||||
|
||||
conn = db_manager.get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
|
||||
# 构建批量删除语句
|
||||
placeholders = ','.join(['?'] * len(qa_ids))
|
||||
query = f'DELETE FROM qa WHERE id IN ({placeholders})'
|
||||
|
||||
|
||||
cursor.execute(query, qa_ids)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
@@ -989,7 +1003,6 @@ def generate_daily_report():
|
||||
# 获取热点话题
|
||||
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)
|
||||
@@ -1163,6 +1176,61 @@ def generate_weekly_report():
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
|
||||
@app.route('/api/render/template', methods=['POST'])
|
||||
def report_render_template():
|
||||
data = request.get_json()
|
||||
template = data.get('template', '')
|
||||
origin_path = data.get('path', '')
|
||||
file = ofm.get_file(origin_path)
|
||||
with open("a.docx", 'wb') as f:
|
||||
f.write(file)
|
||||
|
||||
if file:
|
||||
template_content = transform_template(file)
|
||||
response = ofm.upload_file(f"tpldev/render/{template}.template", template_content.encode('utf-8'))
|
||||
print(response)
|
||||
if response:
|
||||
return api_response(success=True,
|
||||
data={"template_name": template, "template_path": f"tpldev/render/{template}.template"},
|
||||
status_code=200)
|
||||
return api_response(success=False, error="上传模板失败", status_code=500)
|
||||
|
||||
|
||||
@app.route('/api/render/insight', methods=['GET', 'POST'])
|
||||
def report_render():
|
||||
"""获取统计数据API"""
|
||||
try:
|
||||
if request.method == 'GET':
|
||||
security_code = request.args.get('security_code', '')
|
||||
else:
|
||||
data = request.get_json()
|
||||
security_code = data.get('security_code', '')
|
||||
url = "http://10.0.0.39/cloud/in/api/online/run/cache"
|
||||
body = {
|
||||
"pid": "1988527857586081794",
|
||||
"fid": "1988527857586081794",
|
||||
"secCode": security_code
|
||||
}
|
||||
resp = requests.post(url=url, json=body)
|
||||
if resp.status_code != 200:
|
||||
return api_response(success=False, error=resp.text, status_code=500)
|
||||
else:
|
||||
data_info = resp.json().get('data', {}).get('data', '')
|
||||
data_info = data_info.replace("data:application/json,", "")
|
||||
data_info = json.loads(data_info)
|
||||
data_path = data_info.get('url', '')
|
||||
|
||||
data = requests.get(data_path)
|
||||
template_content = ofm.get_file("tpldev/render/insight.template")
|
||||
html = report_template_render(template_content.decode("utf-8"), data=data.json())
|
||||
if request.method == 'GET':
|
||||
return html
|
||||
else:
|
||||
return api_response(success=False, content=html, status_code=200)
|
||||
except Exception as e:
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 检查数据库文件是否存在
|
||||
if not os.path.exists('db/data'):
|
||||
@@ -1172,8 +1240,8 @@ if __name__ == '__main__':
|
||||
print("下载完成")
|
||||
|
||||
print("启动聊天网页服务...")
|
||||
print("访问地址: http://0.0.0.0:9000")
|
||||
print("问答页面: http://0.0.0.0:9000/qa")
|
||||
print("周报页面: http://0.0.0.0:9000/weekly_report")
|
||||
print("日报页面: http://0.0.0.0:9000/daily_report")
|
||||
app.run(debug=True, host='0.0.0.0', port=9000)
|
||||
print("访问地址: http://localhost:9000")
|
||||
print("问答页面: http://localhost:9000/qa")
|
||||
print("周报页面: http://localhost:9000/weekly_report")
|
||||
print("日报页面: http://localhost:9000/daily_report")
|
||||
app.run(debug=True, host='0.0.0.0', port=9000)
|
||||
|
||||
@@ -558,13 +558,13 @@ class ChatSessionManager:
|
||||
end_time = convert_to_utc(end_time_str, source_timezone="Asia/Shanghai").timestamp()
|
||||
|
||||
res = self.dbm.execute_query('''
|
||||
SELECT message.time, message.content
|
||||
FROM message
|
||||
WHERE (message.type = 'text'
|
||||
or message.type = 'mixed')
|
||||
AND message.time >= ?
|
||||
AND message.time <= ?
|
||||
''', (str(start_time).replace(".0", "000"), str(end_time).replace(".0", "000")))
|
||||
SELECT message.time, message.content
|
||||
FROM message
|
||||
WHERE (message.type = 'text'
|
||||
or message.type = 'mixed')
|
||||
AND message.time >= ?
|
||||
AND message.time <= ?
|
||||
''', (str(start_time).replace(".0", "000"), str(end_time).replace(".0", "000")))
|
||||
return res
|
||||
|
||||
@staticmethod
|
||||
@@ -636,7 +636,7 @@ class ChatSessionManager:
|
||||
group_qa: 问答数据字典,键为群ID,值为问答列表
|
||||
"""
|
||||
data = []
|
||||
index_id = self.execute_query(f"SELECT id FROM qa order by id desc limit 1",fetch_all=False)[0]
|
||||
index_id = self.execute_query(f"SELECT id FROM qa order by id desc limit 1", fetch_all=False)[0]
|
||||
|
||||
for r in group_qa:
|
||||
qas = group_qa.get(r, {})
|
||||
|
||||
2
file.py
2
file.py
@@ -25,7 +25,7 @@ class BaseFileManager(ABC):
|
||||
if headers is None:
|
||||
headers = {}
|
||||
resp = requests.put(url, data=raw, headers=headers)
|
||||
if resp.status_code != 201 or resp.status_code != 200:
|
||||
if resp.status_code not in [201, 200]:
|
||||
return {}
|
||||
return resp.json()
|
||||
|
||||
|
||||
274
static/css/markdown.css
Normal file
274
static/css/markdown.css
Normal file
@@ -0,0 +1,274 @@
|
||||
|
||||
:root {
|
||||
--primary-color: #2c3e50;
|
||||
--secondary-color: #3498db;
|
||||
--accent-color: #e74c3c;
|
||||
--light-bg: #f8f9fa;
|
||||
--dark-bg: #2c3e50;
|
||||
--text-color: #333;
|
||||
--border-color: #e0e0e0;
|
||||
--shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
* {
|
||||
margin: 5px;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
line-height: 1.6;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 10px;
|
||||
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.header p {
|
||||
font-size: 1.1rem;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
padding: 30px;
|
||||
box-shadow: var(--shadow);
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.container {
|
||||
display: flex;
|
||||
gap: 30px;
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
.editor, .preview {
|
||||
flex: 1;
|
||||
border: 2px solid var(--border-color);
|
||||
padding: 25px;
|
||||
border-radius: 10px;
|
||||
background: white;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.editor:hover, .preview:hover {
|
||||
border-color: var(--secondary-color);
|
||||
box-shadow: 0 4px 15px rgba(52, 152, 219, 0.2);
|
||||
}
|
||||
|
||||
.editor h3, .preview h3 {
|
||||
color: var(--primary-color);
|
||||
margin-bottom: 15px;
|
||||
font-size: 1.3rem;
|
||||
border-bottom: 2px solid var(--secondary-color);
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
height: 400px;
|
||||
font-family: 'Fira Code', 'Courier New', monospace;
|
||||
font-size: 14px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
resize: vertical;
|
||||
transition: all 0.3s ease;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--secondary-color);
|
||||
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
|
||||
background: white;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
margin-top: 20px;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 12px 24px;
|
||||
background: linear-gradient(135deg, var(--secondary-color), #2980b9);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
|
||||
}
|
||||
|
||||
button:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
#htmlPreview {
|
||||
min-height: 400px;
|
||||
padding: 15px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
background: #fafafa;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
#htmlPreview::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.syntax-guide {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.guide-card {
|
||||
background: var(--light-bg);
|
||||
padding: 20px;
|
||||
border-radius: 10px;
|
||||
border-left: 4px solid var(--secondary-color);
|
||||
}
|
||||
|
||||
.guide-card h3 {
|
||||
color: var(--primary-color);
|
||||
margin-bottom: 15px;
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
.syntax {
|
||||
background: #2c3e50;
|
||||
color: white;
|
||||
padding: 8px 12px;
|
||||
border-radius: 5px;
|
||||
font-family: 'Fira Code', monospace;
|
||||
font-size: 13px;
|
||||
margin: 5px 0;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateY(-10px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Blockquote 样式 - 注释样式,字体变小,颜色变灰 */
|
||||
blockquote {
|
||||
background: linear-gradient(135deg, #f8f9fa, #e9ecef);
|
||||
border-left: 4px solid #6c757d;
|
||||
margin: 20px 0;
|
||||
padding: 15px 20px;
|
||||
font-size: 0.9em;
|
||||
color: #6c757d;
|
||||
font-style: italic;
|
||||
border-radius: 0 8px 8px 0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
blockquote::before {
|
||||
content: "❝";
|
||||
font-size: 2em;
|
||||
color: #adb5bd;
|
||||
position: absolute;
|
||||
left: 10px;
|
||||
top: 5px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
blockquote p {
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* CodeBlock 样式 - 更鲜艳的样式 */
|
||||
pre {
|
||||
background: linear-gradient(135deg, #2d3748, #4a5568);
|
||||
border: 1px solid #4a5568;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
margin: 20px 0;
|
||||
overflow-x: auto;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
|
||||
position: relative;
|
||||
white-space: pre;
|
||||
font-family: 'Fira Code', monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
pre::before {
|
||||
content: "</>";
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 15px;
|
||||
color: #81e6d9;
|
||||
font-size: 0.8em;
|
||||
font-weight: bold;
|
||||
opacity: 0.7;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/* 行内代码样式 */
|
||||
:not(pre) > code {
|
||||
background: linear-gradient(135deg, #fed7e2, #fbb6ce);
|
||||
color: #702459;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
line-height: 1.4;
|
||||
border: 1px solid #fbb6ce;
|
||||
}
|
||||
|
||||
.footer {
|
||||
text-align: center;
|
||||
color: white;
|
||||
margin-top: 30px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.container {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.syntax-guide {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 2rem;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,30 @@
|
||||
togglePreview = function (mode) {
|
||||
const previewBtn = document.getElementById('preview-toggle');
|
||||
const sourceBtn = document.getElementById('source-toggle');
|
||||
const reportContent = document.getElementById('report-content');
|
||||
const markdownSource = document.getElementById('markdown-source');
|
||||
const sourceContent = document.getElementById('source-content');
|
||||
|
||||
if (mode === 'preview') {
|
||||
previewBtn.classList.add('active');
|
||||
sourceBtn.classList.remove('active');
|
||||
reportContent.style.display = 'block';
|
||||
markdownSource.style.display = 'none';
|
||||
} else {
|
||||
previewBtn.classList.remove('active');
|
||||
sourceBtn.classList.add('active');
|
||||
reportContent.style.display = 'none';
|
||||
markdownSource.style.display = 'block';
|
||||
|
||||
// 显示原始Markdown源代码
|
||||
const markdown = reportContent.getAttribute('data-markdown');
|
||||
sourceContent.textContent = markdown;
|
||||
}
|
||||
};
|
||||
// 设置默认日期为今天
|
||||
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';
|
||||
@@ -38,14 +62,14 @@ function generateReport() {
|
||||
if (data.success) {
|
||||
// 保存原始Markdown内容到data属性
|
||||
document.getElementById('report-content').setAttribute('data-markdown', data.report);
|
||||
|
||||
// 将Markdown转换为HTML并显示
|
||||
const htmlContent = markdownToHtml(data.report);
|
||||
|
||||
// 使用专业的Markdown解析器将Markdown转换为HTML并显示
|
||||
const htmlContent = parseMarkdownWithTables(data.report);
|
||||
document.getElementById('report-content').innerHTML = htmlContent;
|
||||
|
||||
|
||||
// 重置为预览模式
|
||||
togglePreview('preview');
|
||||
|
||||
|
||||
document.getElementById('report-container').style.display = 'block';
|
||||
|
||||
// 显示统计数据
|
||||
@@ -95,8 +119,8 @@ function exportReport() {
|
||||
showError('请先生成日报');
|
||||
return;
|
||||
}
|
||||
|
||||
const blob = new Blob([reportContent], { type: 'text/markdown' });
|
||||
|
||||
const blob = new Blob([reportContent], {type: 'text/markdown'});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
@@ -110,4 +134,15 @@ function exportReport() {
|
||||
// 页面加载时自动生成今日日报
|
||||
window.addEventListener('load', function () {
|
||||
generateTodayReport();
|
||||
});
|
||||
});
|
||||
|
||||
// 使用专业的Markdown解析器解析Markdown文本,支持表格
|
||||
function parseMarkdownWithTables(markdown) {
|
||||
if (typeof MarkdownParser !== 'undefined' && typeof MergeTableParser !== 'undefined') {
|
||||
const parser = new MarkdownParser();
|
||||
return parser.parseFull(markdown);
|
||||
} else {
|
||||
// 回退到简单的markdown渲染
|
||||
return markdownToHtml(markdown);
|
||||
}
|
||||
}
|
||||
301
static/js/markdown-parser.js
Normal file
301
static/js/markdown-parser.js
Normal file
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* 基础Markdown解析器
|
||||
* 支持标题、粗体、斜体、列表、链接、图片、代码、引用等基础语法
|
||||
*/
|
||||
class MarkdownParser {
|
||||
constructor() {
|
||||
this.patterns = {
|
||||
heading: /^(#{1,6})\s+(.+)$/gm,
|
||||
bold: /\*\*(.*?)\*\*/g,
|
||||
italic: /\*(.*?)\*/g,
|
||||
inlineCode: /`(.*?)`/g,
|
||||
image: /!\[(.*?)]\((.*?)\)/g,
|
||||
base64Image: /!\[(.*?)]\((data:image\/[^;]+;base64,[^\)]+)\)/gi,
|
||||
imageLink: /\[(.*?)]\((.*?\.(?:jpg|jpeg|png|gif|bmp|webp|svg))\s*(?:"(.*?)")?\)/gi,
|
||||
link: /\[(.*?)]\((?!.*\.(?:jpg|jpeg|png|gif|bmp|webp|svg))(.*?)\)/g,
|
||||
blockquote: /^>\s+(.+)$/gm,
|
||||
unorderedList: /^\s*[-*+]\s+(.+)$/gm,
|
||||
orderedList: /^\d+\.\s+(.+)$/gm,
|
||||
codeBlock: /```.*?\n([\s\S]*?)```/g,
|
||||
horizontalRule: /^---$/gm,
|
||||
comment: /<!--([\s\S]*?)-->/g
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析Markdown文本为HTML
|
||||
* @param {string} markdown - Markdown文本
|
||||
* @returns {string} - HTML文本
|
||||
*/
|
||||
parse(markdown) {
|
||||
let html = markdown;
|
||||
|
||||
// 处理代码块(先处理,避免其他语法干扰)
|
||||
html = html.replace(this.patterns.codeBlock, (match, code) => {
|
||||
// 保留代码内部的换行符,只去除首尾空白
|
||||
let codeLines = code.split('\n');
|
||||
let result = '<pre>';
|
||||
for (let i in codeLines) {
|
||||
if (codeLines[i].trim() === '') {
|
||||
continue;
|
||||
} else {
|
||||
result += `<code>${codeLines[i]}</code><br>`;
|
||||
}
|
||||
|
||||
}
|
||||
result += '</pre>';
|
||||
return result;
|
||||
});
|
||||
|
||||
|
||||
// 处理块引用
|
||||
html = html.replace(this.patterns.blockquote, (match, text) => {
|
||||
return `<blockquote>${this.parseInline(text)}</blockquote>`;
|
||||
});
|
||||
|
||||
// 处理水平分割线
|
||||
html = html.replace(this.patterns.horizontalRule, '<hr>');
|
||||
|
||||
// 处理注释(保留HTML注释)
|
||||
html = html.replace(this.patterns.comment, '<!--$1-->');
|
||||
|
||||
// 处理列表(先处理有序列表,再处理无序列表,避免冲突)
|
||||
html = this.processLists(html);
|
||||
|
||||
// 处理段落(将连续文本包装为段落)
|
||||
html = this.wrapParagraphs(html);
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析行内元素
|
||||
* @param {string} text - 文本内容
|
||||
* @returns {string} - 解析后的HTML
|
||||
*/
|
||||
parseInline(text) {
|
||||
let html = text;
|
||||
|
||||
// 处理粗体
|
||||
html = html.replace(this.patterns.bold, '<strong>$1</strong>');
|
||||
|
||||
// 处理斜体
|
||||
html = html.replace(this.patterns.italic, '<em>$1</em>');
|
||||
|
||||
// 处理行内代码
|
||||
html = html.replace(this.patterns.inlineCode, '<code>$1</code>');
|
||||
|
||||
// 处理普通图片格式 
|
||||
html = html.replace(this.patterns.image, '<img width="100%" src="$2" alt="$1">');
|
||||
|
||||
// 处理base64图片格式 
|
||||
html = html.replace(this.patterns.base64Image, '<img width="100%" src="$2" alt="$1">');
|
||||
|
||||
// 处理图片链接格式 [alt](image.jpg "title")
|
||||
html = html.replace(this.patterns.imageLink, (match, alt, src, title) => {
|
||||
const titleAttr = title ? ` title="${title}"` : '';
|
||||
return `<img width="100%" src="${src}" alt="${alt}"${titleAttr}>`;
|
||||
});
|
||||
|
||||
// 处理链接
|
||||
html = html.replace(this.patterns.link, '<a href="$2">$1</a>');
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理所有列表,先识别列表类型再处理列表项
|
||||
* @param {string} html - HTML文本
|
||||
* @returns {string} - 处理后的HTML
|
||||
*/
|
||||
processLists(html) {
|
||||
// 先识别并标记列表类型
|
||||
const lines = html.split('\n');
|
||||
let result = '';
|
||||
let currentListType = '';
|
||||
let listItems = [];
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i].trim();
|
||||
|
||||
if (line.match(/^\d+\.\s/)) {
|
||||
// 有序列表项
|
||||
if (currentListType !== 'ol') {
|
||||
// 结束前一个列表
|
||||
if (listItems.length > 0) {
|
||||
result += this.wrapListItems(listItems, currentListType);
|
||||
listItems = [];
|
||||
}
|
||||
currentListType = 'ol';
|
||||
}
|
||||
const content = line.replace(/^\d+\.\s+/, '');
|
||||
listItems.push(`<li>${this.parseInline(content)}</li>`);
|
||||
} else if (line.match(/^[-*+]\s/)) {
|
||||
// 无序列表项
|
||||
if (currentListType !== 'ul') {
|
||||
// 结束前一个列表
|
||||
if (listItems.length > 0) {
|
||||
result += this.wrapListItems(listItems, currentListType);
|
||||
listItems = [];
|
||||
}
|
||||
currentListType = 'ul';
|
||||
}
|
||||
const content = line.replace(/^[-*+]\s+/, '');
|
||||
listItems.push(`<li>${this.parseInline(content)}</li>`);
|
||||
} else {
|
||||
// 非列表项
|
||||
if (listItems.length > 0) {
|
||||
result += this.wrapListItems(listItems, currentListType);
|
||||
listItems = [];
|
||||
currentListType = '';
|
||||
}
|
||||
result += lines[i] + '\n';
|
||||
}
|
||||
}
|
||||
|
||||
// 处理最后一个列表
|
||||
if (listItems.length > 0) {
|
||||
result += this.wrapListItems(listItems, currentListType);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 包装列表项
|
||||
* @param {Array} listItems - 列表项数组
|
||||
* @param {string} listType - 列表类型(ul或ol)
|
||||
* @returns {string} - 包装后的HTML列表
|
||||
*/
|
||||
wrapListItems(listItems, listType) {
|
||||
if (listItems.length === 0) return '';
|
||||
|
||||
const listTag = listType === 'ol' ? 'ol' : 'ul';
|
||||
return `<${listTag}>\n${listItems.join('\n')}\n</${listTag}>\n`;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 包装段落,保留Markdown原有换行
|
||||
* @param {string} html - HTML文本
|
||||
* @returns {string} - 包装后的HTML
|
||||
*/
|
||||
wrapParagraphs(html) {
|
||||
const lines = html.split('\n');
|
||||
let result = '';
|
||||
let currentParagraph = '';
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const trimmedLine = line.trim();
|
||||
|
||||
if (!trimmedLine) {
|
||||
// 空行,结束当前段落
|
||||
if (currentParagraph) {
|
||||
// 检查当前段落是否已经是块级元素
|
||||
if (!currentParagraph.match(/^<(h[1-6]|blockquote|ul|ol|li|pre|hr)/)) {
|
||||
result += `<p>${this.parseInline(currentParagraph)}</p>`;
|
||||
} else {
|
||||
result += currentParagraph;
|
||||
}
|
||||
currentParagraph = '';
|
||||
}
|
||||
result += '\n';
|
||||
} else if (trimmedLine.match(/^<(h[1-6]|blockquote|ul|ol|li|pre|hr)/)) {
|
||||
// 已经是块级元素,直接添加
|
||||
if (currentParagraph) {
|
||||
if (!currentParagraph.match(/^<(h[1-6]|blockquote|ul|ol|li|pre|hr)/)) {
|
||||
result += `<p>${this.parseInline(currentParagraph)}</p>`;
|
||||
} else {
|
||||
result += currentParagraph;
|
||||
}
|
||||
currentParagraph = '';
|
||||
}
|
||||
result += line + '\n';
|
||||
} else {
|
||||
// 保留原有换行,不合并为一行
|
||||
if (currentParagraph) {
|
||||
currentParagraph += '\n' + line;
|
||||
} else {
|
||||
currentParagraph = line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理最后一个段落
|
||||
if (currentParagraph) {
|
||||
if (!currentParagraph.match(/^<(h[1-6]|blockquote|ul|ol|li|pre|hr)/)) {
|
||||
result += `<p>${this.parseInline(currentParagraph)}</p>`;
|
||||
} else {
|
||||
result += currentParagraph;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML转义
|
||||
* @param {string} text - 原始文本
|
||||
* @returns {string} - 转义后的文本
|
||||
*/
|
||||
escapeHTML(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
/**
|
||||
* 专门解析表格(与MergeTableParser配合使用)
|
||||
* @param {string} markdown - Markdown表格文本
|
||||
* @returns {string} - HTML表格
|
||||
*/
|
||||
parseTable(markdown) {
|
||||
// 使用MergeTableParser处理表格
|
||||
if (typeof MergeTableParser !== 'undefined') {
|
||||
const tableParser = new MergeTableParser();
|
||||
return tableParser.parseMarkdownTable(markdown);
|
||||
}
|
||||
return markdown;
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整解析Markdown,包含表格处理
|
||||
* @param {string} markdown - 完整Markdown文本
|
||||
* @returns {string} - 完整HTML
|
||||
*/
|
||||
parseFull(markdown) {
|
||||
let html = markdown;
|
||||
|
||||
// 先处理标题,避免表格干扰
|
||||
html = html.replace(this.patterns.heading, (match, hashes, text) => {
|
||||
const level = hashes.length;
|
||||
return `<h${level}>${this.parseInline(text)}</h${level}>`;
|
||||
});
|
||||
|
||||
// 再提取并处理表格
|
||||
const tableRegex = /(\|.*?\|\s*\n)+/g;
|
||||
html = html.replace(tableRegex, (match) => {
|
||||
// 检查是否是有效的表格格式
|
||||
const lines = match.trim().split('\n');
|
||||
if (lines.length >= 2 && lines.every(line => line.trim().startsWith('|') && line.trim().endsWith('|'))) {
|
||||
return this.parseTable(match);
|
||||
}
|
||||
return match;
|
||||
});
|
||||
|
||||
// 然后处理其他Markdown语法
|
||||
return this.parse(html);
|
||||
}
|
||||
}
|
||||
|
||||
// 导出为全局变量
|
||||
if (typeof window !== 'undefined') {
|
||||
window.MarkdownParser = MarkdownParser;
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = MarkdownParser;
|
||||
}
|
||||
263
static/js/markdown-plugin-table.js
Normal file
263
static/js/markdown-plugin-table.js
Normal file
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* 支持合并单元格的Markdown表格解析器
|
||||
* 语法说明:
|
||||
* ^n# - 向上合并n个单元格
|
||||
* >n# - 向左合并n个单元格
|
||||
* ^n>m# - 同时向上合并n个单元格,向左合并m个单元格
|
||||
*/
|
||||
|
||||
class MergeTableParser {
|
||||
constructor() {
|
||||
this.patterns = {
|
||||
mergeUp: /\^(\d+)#/, // ^2#
|
||||
mergeLeft: />(\d+)#/, // >3#
|
||||
mergeBoth: /\^(\d+)>(\d+)#/, // ^2>3#
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析Markdown表格并转换为HTML表格
|
||||
* @param {string} markdown - Markdown表格文本
|
||||
* @returns {string} - HTML表格
|
||||
*/
|
||||
parseMarkdownTable(markdown) {
|
||||
const lines = markdown.trim().split('\n');
|
||||
const tableData = this.parseTableLines(lines);
|
||||
return this.generateHTMLTable(tableData);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析表格行数据
|
||||
* @param {string[]} lines - 表格行数组
|
||||
* @returns {Object} - 表格数据对象
|
||||
*/
|
||||
parseTableLines(lines) {
|
||||
const rows = [];
|
||||
let headers = [];
|
||||
let separatorIndex = -1;
|
||||
|
||||
// 解析表头和分隔符
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i].trim();
|
||||
if (line.startsWith('|') && line.endsWith('|')) {
|
||||
const cells = line.slice(1, -1).split('|').map(cell => cell.trim());
|
||||
|
||||
if (line.includes('---') || line.includes('===')) {
|
||||
separatorIndex = i;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (separatorIndex === -1) {
|
||||
headers = cells;
|
||||
} else {
|
||||
rows.push(cells);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { headers, rows, separatorIndex };
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成HTML表格
|
||||
* @param {Object} tableData - 表格数据
|
||||
* @returns {string} - HTML表格字符串
|
||||
*/
|
||||
generateHTMLTable(tableData) {
|
||||
const { headers, rows } = tableData;
|
||||
const skipMap = new Map(); // 用于标记需要跳过的单元格
|
||||
|
||||
let html = '<table border="1" style="border-collapse: collapse; width: 100%;">\n';
|
||||
|
||||
// 生成表头(支持合并单元格)
|
||||
if (headers.length > 0) {
|
||||
html += ' <thead>\n <tr>\n';
|
||||
|
||||
// 处理表头合并单元格
|
||||
headers.forEach((header, colIndex) => {
|
||||
// 检查当前单元格是否应该被跳过
|
||||
const key = `-1,${colIndex}`; // 表头行索引为-1
|
||||
if (skipMap.has(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const mergeInfo = this.parseMergeSyntax(header);
|
||||
let cellHtml = '';
|
||||
|
||||
if (mergeInfo.rowspan > 1 || mergeInfo.colspan > 1) {
|
||||
cellHtml = ` <th rowspan="${mergeInfo.rowspan}" colspan="${mergeInfo.colspan}">${this.escapeHTML(mergeInfo.content)}</th>\n`;
|
||||
// 标记被合并的表头单元格
|
||||
this.markMergedCells(-1, colIndex, mergeInfo, skipMap);
|
||||
} else {
|
||||
cellHtml = ` <th>${this.escapeHTML(header)}</th>\n`;
|
||||
}
|
||||
|
||||
html += cellHtml;
|
||||
});
|
||||
html += ' </tr>\n </thead>\n';
|
||||
}
|
||||
|
||||
// 生成表格主体
|
||||
html += ' <tbody>\n';
|
||||
|
||||
// 第一遍:标记所有需要合并的单元格
|
||||
rows.forEach((row, rowIndex) => {
|
||||
row.forEach((cell, colIndex) => {
|
||||
const mergeInfo = this.parseMergeSyntax(cell);
|
||||
if (mergeInfo.rowspan > 1 || mergeInfo.colspan > 1) {
|
||||
this.markMergedCells(rowIndex, colIndex, mergeInfo, skipMap);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 第二遍:生成HTML,跳过被合并的单元格
|
||||
rows.forEach((row, rowIndex) => {
|
||||
html += ' <tr>\n';
|
||||
|
||||
let colOffset = 0; // 列偏移量,用于处理被跳过的单元格
|
||||
row.forEach((cell, colIndex) => {
|
||||
// 检查当前单元格是否应该被跳过
|
||||
const key = `${rowIndex},${colIndex}`;
|
||||
if (skipMap.has(key)) {
|
||||
colOffset++;
|
||||
return;
|
||||
}
|
||||
|
||||
const mergeInfo = this.parseMergeSyntax(cell);
|
||||
let cellHtml = '';
|
||||
|
||||
if (mergeInfo.rowspan > 1 || mergeInfo.colspan > 1) {
|
||||
cellHtml = ` <td rowspan="${mergeInfo.rowspan}" colspan="${mergeInfo.colspan}">${this.escapeHTML(mergeInfo.content)}</td>\n`;
|
||||
} else {
|
||||
cellHtml = ` <td>${this.escapeHTML(cell)}</td>\n`;
|
||||
}
|
||||
|
||||
html += cellHtml;
|
||||
});
|
||||
html += ' </tr>\n';
|
||||
});
|
||||
html += ' </tbody>\n</table>';
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析合并语法
|
||||
* @param {string} cell - 单元格内容
|
||||
* @returns {Object} - 合并信息
|
||||
*/
|
||||
parseMergeSyntax(cell) {
|
||||
const result = {
|
||||
content: cell,
|
||||
rowspan: 1,
|
||||
colspan: 1,
|
||||
shouldSkip: false
|
||||
};
|
||||
|
||||
// 检查合并语法
|
||||
const bothMatch = cell.match(this.patterns.mergeBoth);
|
||||
const upMatch = cell.match(this.patterns.mergeUp);
|
||||
const leftMatch = cell.match(this.patterns.mergeLeft);
|
||||
|
||||
if (bothMatch) {
|
||||
result.rowspan = parseInt(bothMatch[1]) + 1;
|
||||
result.colspan = parseInt(bothMatch[2]) + 1;
|
||||
result.content = cell.replace(this.patterns.mergeBoth, '').trim();
|
||||
} else if (upMatch) {
|
||||
result.rowspan = parseInt(upMatch[1]) + 1;
|
||||
result.content = cell.replace(this.patterns.mergeUp, '').trim();
|
||||
} else if (leftMatch) {
|
||||
result.colspan = parseInt(leftMatch[1]) + 1;
|
||||
result.content = cell.replace(this.patterns.mergeLeft, '').trim();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记被合并的单元格
|
||||
* @param {number} rowIndex - 行索引
|
||||
* @param {number} colIndex - 列索引
|
||||
* @param {Object} mergeInfo - 合并信息
|
||||
* @param {Map} skipMap - 跳过映射
|
||||
*/
|
||||
markMergedCells(rowIndex, colIndex, mergeInfo, skipMap) {
|
||||
for (let r = 0; r < mergeInfo.rowspan; r++) {
|
||||
for (let c = 0; c < mergeInfo.colspan; c++) {
|
||||
if (r === 0 && c === 0) continue; // 跳过主单元格
|
||||
|
||||
// 处理表头合并(行索引为-1)
|
||||
const targetRow = rowIndex === -1 ? -1 : rowIndex + r;
|
||||
const key = `${targetRow},${colIndex + c}`;
|
||||
skipMap.set(key, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML转义
|
||||
* @param {string} text - 原始文本
|
||||
* @returns {string} - 转义后的文本
|
||||
*/
|
||||
escapeHTML(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将HTML表格转换回Markdown格式
|
||||
* @param {string} html - HTML表格
|
||||
* @returns {string} - Markdown表格
|
||||
*/
|
||||
htmlToMarkdown(html) {
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, 'text/html');
|
||||
const table = doc.querySelector('table');
|
||||
|
||||
if (!table) return '';
|
||||
|
||||
let markdown = '';
|
||||
const rows = table.querySelectorAll('tr');
|
||||
|
||||
rows.forEach((row, rowIndex) => {
|
||||
const cells = row.querySelectorAll('th, td');
|
||||
let rowMarkdown = '|';
|
||||
|
||||
cells.forEach(cell => {
|
||||
const rowspan = parseInt(cell.getAttribute('rowspan') || '1');
|
||||
const colspan = parseInt(cell.getAttribute('colspan') || '1');
|
||||
let content = cell.textContent.trim();
|
||||
|
||||
// 添加合并语法
|
||||
if (rowspan > 1) {
|
||||
content += ` ^${rowspan - 1}`;
|
||||
}
|
||||
if (colspan > 1) {
|
||||
content += ` >${colspan - 1}`;
|
||||
}
|
||||
|
||||
rowMarkdown += ` ${content} |`;
|
||||
});
|
||||
|
||||
markdown += rowMarkdown + '\n';
|
||||
|
||||
// 添加分隔符行(仅在第一行后)
|
||||
if (rowIndex === 0) {
|
||||
markdown += '|' + cells.map(() => '---').join('|') + '|\n';
|
||||
}
|
||||
});
|
||||
|
||||
return markdown;
|
||||
}
|
||||
}
|
||||
|
||||
// 导出为全局变量
|
||||
if (typeof window !== 'undefined') {
|
||||
window.MergeTableParser = MergeTableParser;
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = MergeTableParser;
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
// Markdown转HTML的简单实现
|
||||
function markdownToHtml(markdown) {
|
||||
// 替换标题
|
||||
let html = markdown
|
||||
.replace(/^# (.*$)/gm, '<h1>$1</h1>')
|
||||
.replace(/^## (.*$)/gm, '<h2>$1</h2>')
|
||||
.replace(/^### (.*$)/gm, '<h3>$1</h3>')
|
||||
.replace(/^#### (.*$)/gm, '<h4>$1</h4>')
|
||||
.replace(/^##### (.*$)/gm, '<h5>$1</h5>')
|
||||
.replace(/^###### (.*$)/gm, '<h6>$1</h6>');
|
||||
|
||||
// 替换粗体
|
||||
html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
|
||||
|
||||
// 替换斜体
|
||||
html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
|
||||
|
||||
// 替换代码块
|
||||
html = html.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
|
||||
|
||||
// 替换行内代码
|
||||
html = html.replace(/`(.*?)`/g, '<code>$1</code>');
|
||||
|
||||
// 替换无序列表
|
||||
html = html.replace(/^\s*[-*] (.*$)/gm, '<li>$1</li>');
|
||||
html = html.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>');
|
||||
|
||||
// 替换有序列表
|
||||
html = html.replace(/^\s*\d+\. (.*$)/gm, '<li>$1</li>');
|
||||
html = html.replace(/(<li>.*<\/li>)/s, '<ol>$1</ol>');
|
||||
|
||||
// 替换引用块
|
||||
html = html.replace(/^> (.*$)/gm, '<blockquote>$1</blockquote>');
|
||||
|
||||
// 替换链接
|
||||
html = html.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>');
|
||||
|
||||
// 替换图片
|
||||
html = html.replace(/!\[(.*?)\]\((.*?)\)/g, '<img src="$2" alt="$1" style="max-width: 100%;">');
|
||||
|
||||
// 替换表格(增强实现)
|
||||
html = html.replace(/\|(.+)\|\n\|([-|: ]+)\|\n((?:\|.+\|\n)*)/g, function(match, headerRow, separatorRow, bodyRows) {
|
||||
// 解析表头
|
||||
const headers = headerRow.split('|').filter(cell => cell.trim());
|
||||
|
||||
// 解析分隔行,确定对齐方式
|
||||
const separators = separatorRow.split('|').filter(cell => cell.trim());
|
||||
const alignments = separators.map(sep => {
|
||||
if (sep.startsWith(':') && sep.endsWith(':')) return 'center';
|
||||
if (sep.endsWith(':')) return 'right';
|
||||
return 'left';
|
||||
});
|
||||
|
||||
// 构建表头HTML
|
||||
let tableHtml = '<table style="border-collapse: collapse; width: 100%; margin: 10px 0; border: 1px solid #ddd;">';
|
||||
tableHtml += '<thead><tr style="background-color: #f5f5f5;">';
|
||||
headers.forEach((header, index) => {
|
||||
const alignment = alignments[index] || 'left';
|
||||
tableHtml += `<th style="border: 1px solid #ddd; padding: 8px; text-align: ${alignment}; font-weight: bold;">${header.trim()}</th>`;
|
||||
});
|
||||
tableHtml += '</tr></thead>';
|
||||
|
||||
// 解析表格主体
|
||||
const bodyRowsArray = bodyRows.trim().split('\n');
|
||||
if (bodyRowsArray.length > 0) {
|
||||
tableHtml += '<tbody>';
|
||||
bodyRowsArray.forEach(row => {
|
||||
const cells = row.split('|').filter(cell => cell.trim());
|
||||
if (cells.length > 0) {
|
||||
tableHtml += '<tr>';
|
||||
cells.forEach((cell, index) => {
|
||||
const alignment = alignments[index] || 'left';
|
||||
tableHtml += `<td style="border: 1px solid #ddd; padding: 8px; text-align: ${alignment};">${cell.trim()}</td>`;
|
||||
});
|
||||
tableHtml += '</tr>';
|
||||
}
|
||||
});
|
||||
tableHtml += '</tbody>';
|
||||
}
|
||||
|
||||
tableHtml += '</table>';
|
||||
return tableHtml;
|
||||
});
|
||||
|
||||
// 处理简单的单行表格(向后兼容)
|
||||
html = html.replace(/^\|(.+)\|$/gm, function(match) {
|
||||
const cells = match.split('|').filter(cell => cell.trim());
|
||||
if (cells.length > 0) {
|
||||
return '<table style="border-collapse: collapse; width: 100%; margin: 10px 0; border: 1px solid #ddd;"><tr>' +
|
||||
cells.map(cell => `<td style="border: 1px solid #ddd; padding: 8px;">${cell.trim()}</td>`).join('') +
|
||||
'</tr></table>';
|
||||
}
|
||||
return match;
|
||||
});
|
||||
|
||||
// 替换水平分隔线(---、***、___)
|
||||
html = html.replace(/^\s*[-*_]{3,}\s*$/gm, '<hr>');
|
||||
|
||||
// 将连续的空行转换为段落
|
||||
html = html.replace(/\n\n+/g, '</p><p>');
|
||||
html = '<p>' + html.replace(/\n/g, '<br>') + '</p>';
|
||||
|
||||
// 清理多余的段落标签
|
||||
html = html.replace(/<p><\/p>/g, '');
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
// 切换预览模式函数
|
||||
togglePreview = function(mode) {
|
||||
const previewBtn = document.getElementById('preview-toggle');
|
||||
const sourceBtn = document.getElementById('source-toggle');
|
||||
const reportContent = document.getElementById('report-content');
|
||||
const markdownSource = document.getElementById('markdown-source');
|
||||
const sourceContent = document.getElementById('source-content');
|
||||
|
||||
if (mode === 'preview') {
|
||||
previewBtn.classList.add('active');
|
||||
sourceBtn.classList.remove('active');
|
||||
reportContent.style.display = 'block';
|
||||
markdownSource.style.display = 'none';
|
||||
} else {
|
||||
previewBtn.classList.remove('active');
|
||||
sourceBtn.classList.add('active');
|
||||
reportContent.style.display = 'none';
|
||||
markdownSource.style.display = 'block';
|
||||
|
||||
// 显示原始Markdown源代码
|
||||
const markdown = reportContent.getAttribute('data-markdown');
|
||||
sourceContent.textContent = markdown;
|
||||
}
|
||||
};
|
||||
@@ -1,3 +1,27 @@
|
||||
togglePreview = function (mode) {
|
||||
const previewBtn = document.getElementById('preview-toggle');
|
||||
const sourceBtn = document.getElementById('source-toggle');
|
||||
const reportContent = document.getElementById('report-content');
|
||||
const markdownSource = document.getElementById('markdown-source');
|
||||
const sourceContent = document.getElementById('source-content');
|
||||
|
||||
if (mode === 'preview') {
|
||||
previewBtn.classList.add('active');
|
||||
sourceBtn.classList.remove('active');
|
||||
reportContent.style.display = 'block';
|
||||
markdownSource.style.display = 'none';
|
||||
} else {
|
||||
previewBtn.classList.remove('active');
|
||||
sourceBtn.classList.add('active');
|
||||
reportContent.style.display = 'none';
|
||||
markdownSource.style.display = 'block';
|
||||
|
||||
// 显示原始Markdown源代码
|
||||
const markdown = reportContent.getAttribute('data-markdown');
|
||||
sourceContent.textContent = markdown;
|
||||
}
|
||||
};
|
||||
|
||||
// 设置默认周次为当前周
|
||||
function getCurrentWeek() {
|
||||
const now = new Date();
|
||||
@@ -8,7 +32,7 @@ function getCurrentWeek() {
|
||||
}
|
||||
|
||||
// 页面加载时设置默认周次
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
document.getElementById('week').value = getCurrentWeek();
|
||||
});
|
||||
|
||||
@@ -33,42 +57,41 @@ function generateCurrentWeekReport() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
function generateReport() {
|
||||
const week = document.getElementById('week').value;
|
||||
if (!week) {
|
||||
showError('请选择周次');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// 转换格式:YYYY-WWW 到 YYYY-WW
|
||||
const weekFormatted = week.replace('W', '');
|
||||
|
||||
|
||||
showLoading();
|
||||
|
||||
|
||||
fetch(`/api/reports/weekly?week=${weekFormatted}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
hideLoading();
|
||||
|
||||
|
||||
if (data.success) {
|
||||
// 保存原始Markdown内容到data属性
|
||||
document.getElementById('report-content').setAttribute('data-markdown', data.report);
|
||||
|
||||
// 将Markdown转换为HTML并显示
|
||||
const htmlContent = markdownToHtml(data.report);
|
||||
|
||||
// 使用专业的Markdown解析器将Markdown转换为HTML并显示
|
||||
const htmlContent = parseMarkdownWithTables(data.report);
|
||||
document.getElementById('report-content').innerHTML = htmlContent;
|
||||
|
||||
|
||||
// 重置为预览模式
|
||||
togglePreview('preview');
|
||||
|
||||
|
||||
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);
|
||||
@@ -88,17 +111,17 @@ function generateReport() {
|
||||
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: '条' }
|
||||
{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';
|
||||
@@ -113,7 +136,7 @@ function displayStatistics(stats) {
|
||||
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';
|
||||
@@ -132,8 +155,8 @@ function exportReport() {
|
||||
showError('请先生成周报');
|
||||
return;
|
||||
}
|
||||
|
||||
const blob = new Blob([reportContent], { type: 'text/markdown' });
|
||||
|
||||
const blob = new Blob([reportContent], {type: 'text/markdown'});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
@@ -145,13 +168,24 @@ function exportReport() {
|
||||
}
|
||||
|
||||
// 页面加载时自动生成本周周报
|
||||
window.addEventListener('load', function() {
|
||||
window.addEventListener('load', function () {
|
||||
generateCurrentWeekReport();
|
||||
});
|
||||
|
||||
// 支持回车键生成报告
|
||||
document.getElementById('week').addEventListener('keypress', function(e) {
|
||||
document.getElementById('week').addEventListener('keypress', function (e) {
|
||||
if (e.key === 'Enter') {
|
||||
generateReport();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 使用专业的Markdown解析器解析Markdown文本,支持表格
|
||||
function parseMarkdownWithTables(markdown) {
|
||||
if (typeof MarkdownParser !== 'undefined' && typeof MergeTableParser !== 'undefined') {
|
||||
const parser = new MarkdownParser();
|
||||
return parser.parseFull(markdown);
|
||||
} else {
|
||||
// 回退到简单的markdown渲染
|
||||
return markdownToHtml(markdown);
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,8 @@
|
||||
<div id="error" class="error" style="display: none;"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/js/markdown-render.js"></script>
|
||||
<script src="/static/js/markdown-parser.js"></script>
|
||||
<script src="/static/js/markdown-plugin-table.js"></script>
|
||||
<script src="/static/js/daily_report.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
241
templates/markdown.html
Normal file
241
templates/markdown.html
Normal file
File diff suppressed because one or more lines are too long
@@ -56,7 +56,8 @@
|
||||
<div id="error" class="error" style="display: none;"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/js/markdown-render.js"></script>
|
||||
<script src="/static/js/markdown-parser.js"></script>
|
||||
<script src="/static/js/markdown-plugin-table.js"></script>
|
||||
<script src="/static/js/weekly_report.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
62
tools.py
62
tools.py
@@ -5,6 +5,68 @@ from typing import Union, Optional
|
||||
import sqlite3
|
||||
|
||||
from file import ObjectFileManager, LocalFileManager
|
||||
import re
|
||||
from io import BytesIO
|
||||
import jinja2
|
||||
import mammoth
|
||||
|
||||
|
||||
def transform_template(file_bytes: bytes):
|
||||
html_head = """
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
<style>
|
||||
table, th, td {
|
||||
border: 1px solid #000000;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>"""
|
||||
html_tail = """
|
||||
</body>
|
||||
</html>"""
|
||||
file_obj = BytesIO(file_bytes)
|
||||
result = mammoth.convert_to_html(file_obj)
|
||||
html = result.value
|
||||
html = re.sub('<img.*?>', '', html)
|
||||
c = re.compile(r'{(.*?)}')
|
||||
ll = c.findall(html)
|
||||
ta_list = []
|
||||
for i in ll:
|
||||
lc = i.split('+')
|
||||
item_type = lc[1]
|
||||
if item_type in ["TS", "TN", "TD"]:
|
||||
if lc[0].split(".")[0] not in ta_list:
|
||||
html = html.replace('{' + i + '}', '{{data["' + lc[0] + '"]}}')
|
||||
else:
|
||||
html = html.replace('{' + i + '}', '{{' + lc[0] + '}}')
|
||||
elif item_type == "TP":
|
||||
html = html.replace('{' + i + '}', '<img width="70%" src="data:image/jpeg;base64,{{data.' + lc[0] + '}}">')
|
||||
elif item_type == "TC":
|
||||
if lc[4] == "end":
|
||||
html = html.replace('{' + i + '}', '\n{% endif %}\n')
|
||||
if lc[4] == "start":
|
||||
html = html.replace('{' + i + '}', '\n{% if data.' + lc[0] + '=="' + lc[3] + '" %}\n')
|
||||
elif item_type == "TA":
|
||||
ta_list.append(lc[0])
|
||||
if lc[2] == "end":
|
||||
html = html.replace('{' + i + '}</p></td></tr>', '\n</p></td></tr>{% endfor %}\n')
|
||||
if lc[2] == "start":
|
||||
html = html.replace('<tr><td><p>{' + i + '}',
|
||||
'\n{% for ' + lc[0] + ' in data.' + lc[0] + ' %}\n<tr><td><p>')
|
||||
else:
|
||||
print(lc[0], lc)
|
||||
return html_head + html + html_tail
|
||||
|
||||
|
||||
def report_template_render(template: str, data: dict):
|
||||
html = jinja2.Template(template).render(data=data)
|
||||
return html
|
||||
|
||||
|
||||
class DatabaseManager:
|
||||
|
||||
Reference in New Issue
Block a user