debug: 添加详细调试日志,诊断下载按钮不显示的问题

问题:日报生成成功后,历史记录中没有下载按钮。

改进内容:

1. lib/report_generator.py:
   - 在生成Excel文件后添加日志:显示文件路径
   - 在保存历史记录前添加日志:显示file_path值
   - 在save_report_history函数中添加详细日志:
     * 显示准备保存的信息
     * 显示file_path和status的值
     * 显示SQL执行结果

2. app.py:
   - 在历史记录API中添加调试日志
   - 显示每条记录的status和file_path
   - 确保file_path不为None(转换为空字符串)
   - 添加错误堆栈输出

3. templates/index.html:
   - 在渲染历史记录时添加console.log调试
   - 显示每条记录的详细信息
   - 显示status和file_path的类型
   - 改进下载按钮判断逻辑
   - 添加title提示显示文件路径

4. 新增文档:
   - 查看调试日志.md:详细的调试步骤和问题诊断方法

现在用户可以通过日志准确定位问题:
- 服务器控制台:查看后端日志
- 浏览器控制台:查看前端日志
- curl测试:直接查看API返回数据

Coze-Commit-Type: user
Coze-User-ID: 3722323274763196
Coze-Conversation-ID: 9894087
This commit is contained in:
user9994793890
2026-07-09 12:59:40 +08:00
parent 9fa2745daa
commit 2ad6e27131
6 changed files with 239 additions and 7 deletions

11
app.py
View File

@@ -306,9 +306,15 @@ def get_report_history():
(page_size, offset)
)
# 解析JSON字段
# 解析JSON字段并确保file_path正确
for item in history:
item['sum_results'] = json.loads(item['sum_results']) if item['sum_results'] else {}
# 确保file_path是字符串
if item['file_path'] is None:
item['file_path'] = ''
# 调试日志
print(f"[历史记录] ID: {item['id']}, status: {item['status']}, file_path: '{item['file_path']}'")
return jsonify({
'success': True,
@@ -320,6 +326,9 @@ def get_report_history():
}
})
except Exception as e:
print(f"[历史记录API] 错误: {e}")
import traceback
traceback.print_exc()
return jsonify({'success': False, 'message': str(e)}), 500

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

51
check_history.py Normal file
View File

@@ -0,0 +1,51 @@
"""
检查历史记录中的文件路径
"""
from lib.db import execute_query
print("=" * 60)
print("检查历史记录中的文件路径")
print("=" * 60)
try:
result = execute_query("""
SELECT
id,
report_date,
split_value,
total_orders,
status,
file_path,
create_time
FROM t_daily_report_history
ORDER BY create_time DESC
LIMIT 5
""")
if not result:
print("⚠ 历史记录表为空")
else:
print(f"\n找到 {len(result)} 条记录:\n")
for item in result:
print(f"ID: {item['id']}")
print(f" 日期: {item['report_date']}")
print(f" 拆分值: {item['split_value']}")
print(f" 订单数: {item['total_orders']}")
print(f" 状态: {'成功' if item['status'] == 1 else '失败'}")
print(f" 文件路径: '{item['file_path']}'")
print(f" 文件路径是否为空: {not item['file_path']}")
print(f" 创建时间: {item['create_time']}")
print("-" * 60)
# 检查文件是否存在
if item['file_path']:
import os
full_path = os.path.join('public', item['file_path'])
print(f" 完整路径: {full_path}")
print(f" 文件是否存在: {os.path.exists(full_path)}")
print()
except Exception as e:
print(f"✗ 查询失败: {e}")
import traceback
traceback.print_exc()

View File

@@ -120,10 +120,13 @@ def generate_daily_report(config_id, start_time=None, end_time=None):
end_time=end_time_str
)
print(f"[日报生成] Excel文件已生成: {file_path}")
# 计算总金额
total_amount = sum(float(order.get('total_money', 0) or 0) for order in orders)
# 保存历史记录
print(f"[日报生成] 准备保存历史记录file_path={file_path}")
history_id = save_report_history(
report_date=start_time.strftime('%Y-%m-%d'),
start_time=start_time_str,
@@ -138,6 +141,7 @@ def generate_daily_report(config_id, start_time=None, end_time=None):
file_path=file_path,
status=1
)
print(f"[日报生成] 历史记录已保存ID={history_id}")
print(f"[日报生成] ✓ 生成成功")
print(f" 订单数量: {len(orders)}")
@@ -285,6 +289,11 @@ def save_report_history(report_date, start_time, end_time, split_type, split_val
# 生成ID
history_id = int(datetime.now().timestamp() * 1000)
print(f"[保存历史] 准备保存历史记录")
print(f" ID: {history_id}")
print(f" file_path: '{file_path}'")
print(f" status: {status}")
sql = """
INSERT INTO t_daily_report_history
(id, report_date, start_time, end_time, split_type, split_value, split_name,
@@ -308,6 +317,8 @@ def save_report_history(report_date, start_time, end_time, split_type, split_val
status
)
execute_insert(sql, params)
print(f"[保存历史] 执行SQL插入...")
result = execute_insert(sql, params)
print(f"[保存历史] 插入完成返回ID: {result}")
return history_id

View File

@@ -950,7 +950,16 @@
return;
}
tbody.innerHTML = history.map(item => `
tbody.innerHTML = history.map(item => {
// 调试信息
console.log('历史记录项:', item);
console.log(' status:', item.status, '类型:', typeof item.status);
console.log(' file_path:', item.file_path, '类型:', typeof item.file_path);
console.log(' 是否有文件:', !!(item.status === 1 && item.file_path));
const hasFile = item.status === 1 && item.file_path && item.file_path.trim() !== '';
return `
<tr>
<td>${item.report_date}</td>
<td style="font-size: 12px;">${item.start_time || '-'}<br>至<br>${item.end_time || '-'}</td>
@@ -964,12 +973,12 @@
</span>
</td>
<td>
${item.status === 1 && item.file_path ?
`<a href="/api/download?path=${item.file_path}" target="_blank" class="btn btn-sm btn-success">📥 下载</a>` :
'<span style="color: #999;">-</span>'}
${hasFile ?
`<a href="/api/download?path=${encodeURIComponent(item.file_path)}" target="_blank" class="btn btn-sm btn-success">📥 下载</a>` :
`<span style="color: #999;" title="文件路径: ${item.file_path || '无'}">-</span>`}
</td>
</tr>
`).join('');
`}).join('');
}
// 渲染分页

152
查看调试日志.md Normal file
View File

@@ -0,0 +1,152 @@
# 如何查看调试日志
## 问题:生成日报后没有下载按钮
### 步骤1重启服务
停止当前服务Ctrl+C然后重新启动
```bash
python app.py
```
### 步骤2生成日报
1. 访问 http://localhost:5000
2. 切换到"日报生成"标签
3. 选择配置和时间范围
4. 点击"生成日报"
### 步骤3查看服务器控制台日志
在运行 `python app.py` 的窗口中,应该看到类似以下的日志:
```
[日报生成] 开始生成日报
配置ID: 1234567890
配置名称: 测试配置
拆分方式: company_id = 123
时间范围: 2025-01-07 08:00:00 至 2025-01-08 08:00:00
选择字段: 5 个
[日报生成] 查询到 10 条订单
[日报生成] Excel文件已生成: /reports/daily_report_xxx.xlsx
[日报生成] 准备保存历史记录file_path=/reports/daily_report_xxx.xlsx
[保存历史] 准备保存历史记录
ID: 1234567890123
file_path: '/reports/daily_report_xxx.xlsx'
status: 1
[保存历史] 执行SQL插入...
[保存历史] 插入完成返回ID: 1234567890123
[日报生成] 历史记录已保存ID=1234567890123
[日报生成] ✓ 生成成功
订单数量: 10
总金额: 100.00
文件路径: /reports/daily_report_xxx.xlsx
历史记录ID: 1234567890123
```
### 步骤4查看历史记录API日志
切换到"历史记录"标签,在服务器控制台应该看到:
```
[历史记录] ID: 1234567890123, status: 1, file_path: '/reports/daily_report_xxx.xlsx'
```
### 步骤5查看浏览器控制台
1. 按 F12 打开开发者工具
2. 切换到 "Console" 标签
3. 刷新历史记录页面
4. 应该看到调试信息:
```
历史记录项: {id: 1234567890123, status: 1, file_path: '/reports/xxx.xlsx', ...}
status: 1 类型: number
file_path: /reports/xxx.xlsx 类型: string
是否有文件: true
```
## 根据日志判断问题
### 情况1file_path 为空
如果日志显示:
```
file_path: ''
```
**原因**Excel文件生成失败或路径没有正确返回
**解决**:检查 `public/reports/` 目录是否存在,是否有写入权限
### 情况2file_path 有值,但前端显示"-"
如果服务器日志显示 file_path 有值,但浏览器控制台显示:
```
是否有文件: false
```
**原因**前端JavaScript判断逻辑有问题
**解决**:查看浏览器控制台的详细输出,检查 status 和 file_path 的类型
### 情况3数据库中没有保存记录
如果服务器日志没有显示 "[保存历史]" 相关信息
**原因**:保存历史记录的代码没有被执行
**解决**:检查 generate_daily_report 函数的流程
## 快速测试API
使用curl直接测试API
```bash
# 查看历史记录
curl http://localhost:5000/api/report/history
# 应该返回类似:
# {
# "success": true,
# "data": {
# "list": [
# {
# "id": 1234567890123,
# "status": 1,
# "file_path": "/reports/xxx.xlsx",
# ...
# }
# ],
# ...
# }
# }
```
如果 file_path 为空,说明是后端问题
如果 file_path 有值,说明是前端显示问题
## 检查文件是否存在
```bash
# Windows
dir public\reports\*.xlsx
# Linux/Mac
ls -la public/reports/*.xlsx
```
确认文件是否真的生成了。
## 联系支持
如果以上步骤都无法解决问题,请提供:
1. 服务器控制台的完整日志(从生成到查看历史)
2. 浏览器控制台的完整输出
3. curl测试API的返回结果
4. public/reports/ 目录的文件列表
---
**最后更新**: 2025-01-08