增加日志

This commit is contained in:
2026-07-15 16:01:06 +08:00
parent d34dd82bd5
commit 727f5434b2
11 changed files with 461 additions and 192 deletions

View File

@@ -7,6 +7,7 @@ from datetime import datetime
from flask import request, jsonify, send_from_directory
from lib.db import execute_query, execute_update
from lib.report_generator import generate_daily_report
from lib.logger import log_info, log_error, log_warning
from . import report_bp
@@ -16,8 +17,10 @@ def generate_report():
try:
data = request.json
config_id = data.get('config_id')
log_info(f'[报表API] 生成日报,配置ID: {config_id}', 'api')
if not config_id:
log_warning('[报表API] 生成日报失败:未选择配置', 'api')
return jsonify({'success': False, 'message': '请选择配置'}), 400
# 解析时间参数
@@ -32,10 +35,13 @@ def generate_report():
result = generate_daily_report(config_id, start_time, end_time)
if result['success']:
log_info(f'[报表API] 日报生成成功,订单数: {result.get("total_orders", 0)}', 'api')
return jsonify(result)
else:
log_warning(f'[报表API] 日报生成失败: {result.get("message", "")}', 'api')
return jsonify(result), 400
except Exception as e:
log_error(f'[报表API] 生成日报异常: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -47,6 +53,8 @@ def get_report_history():
page_size = int(request.args.get('page_size', 20))
start_date = request.args.get('start_date')
end_date = request.args.get('end_date')
log_info(f'[报表API] 获取历史记录,第{page}页,日期范围: {start_date or "开始"} ~ {end_date or "结束"}', 'api')
offset = (page - 1) * page_size
# 构建查询条件
@@ -82,10 +90,8 @@ def get_report_history():
# 确保 file_path 是字符串
if item['file_path'] is None:
item['file_path'] = ''
# 调试日志
print(f"[历史记录] ID: {item['id']}, status: {item['status']}, file_path: '{item['file_path']}'")
log_info(f'[报表API] 获取到 {len(history)} 条历史记录,共 {total} 条', 'api')
return jsonify({
'success': True,
'data': {
@@ -96,9 +102,7 @@ def get_report_history():
}
})
except Exception as e:
print(f"[历史记录 API] 错误:{e}")
import traceback
traceback.print_exc()
log_error(f'[报表API] 获取历史记录失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -106,6 +110,7 @@ def get_report_history():
def delete_report_history(history_id):
"""删除单个历史记录"""
try:
log_info(f'[报表API] 删除历史记录,ID: {history_id}', 'api')
# 先查询文件路径
result = execute_query(
'SELECT file_path FROM t_daily_report_history WHERE id = %s',
@@ -117,15 +122,15 @@ def delete_report_history(history_id):
# 删除文件
if file_path and os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'public', file_path.lstrip('/'))):
os.remove(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'public', file_path.lstrip('/')))
log_info(f'[报表API] 已删除报表文件: {file_path}', 'api')
# 删除数据库记录
execute_update('DELETE FROM t_daily_report_history WHERE id = %s', (history_id,))
log_info(f'[报表API] 历史记录删除成功,ID: {history_id}', 'api')
return jsonify({'success': True, 'message': '删除成功'})
except Exception as e:
print(f"[删除历史记录] 错误:{e}")
import traceback
traceback.print_exc()
log_error(f'[报表API] 删除历史记录失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -135,8 +140,10 @@ def batch_delete_report_history():
try:
data = request.get_json()
ids = data.get('ids', [])
log_info(f'[报表API] 批量删除历史记录,数量: {len(ids)}', 'api')
if not ids:
log_warning('[报表API] 批量删除失败:未选择记录', 'api')
return jsonify({'success': False, 'message': '请选择要删除的记录'}), 400
# 查询文件路径
@@ -146,10 +153,14 @@ def batch_delete_report_history():
)
# 删除文件
deleted_files = 0
for result in results:
file_path = result.get('file_path', '')
if file_path and os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'public', file_path.lstrip('/'))):
os.remove(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'public', file_path.lstrip('/')))
deleted_files += 1
log_info(f'[报表API] 已删除 {deleted_files} 个报表文件', 'api')
# 删除数据库记录
execute_update(
@@ -157,11 +168,10 @@ def batch_delete_report_history():
tuple(ids)
)
log_info(f'[报表API] 批量删除成功,共 {len(ids)} 条记录', 'api')
return jsonify({'success': True, 'message': f'成功删除 {len(ids)} 条记录'})
except Exception as e:
print(f"[批量删除历史记录] 错误:{e}")
import traceback
traceback.print_exc()
log_error(f'[报表API] 批量删除历史记录失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -169,6 +179,7 @@ def batch_delete_report_history():
def download_report_by_id(history_id):
"""根据 ID 下载历史记录"""
try:
log_info(f'[报表API] 下载报表,历史记录ID: {history_id}', 'api')
# 查询历史记录
result = execute_query(
'SELECT file_path, split_name, report_date FROM t_daily_report_history WHERE id = %s',
@@ -176,24 +187,26 @@ def download_report_by_id(history_id):
)
if not result:
log_warning(f'[报表API] 下载报表失败:记录不存在,ID: {history_id}', 'api')
return jsonify({'success': False, 'message': '记录不存在'}), 404
file_path = result[0]['file_path']
if not file_path:
log_warning(f'[报表API] 下载报表失败:文件路径为空,ID: {history_id}', 'api')
return jsonify({'success': False, 'message': '文件不存在'}), 404
# 构建完整路径
full_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'public', file_path.lstrip('/'))
if not os.path.exists(full_path):
log_warning(f'[报表API] 下载报表失败:文件不存在,路径: {full_path}', 'api')
return jsonify({'success': False, 'message': '文件不存在'}), 404
# 返回文件
directory = os.path.dirname(full_path)
filename = os.path.basename(full_path)
log_info(f'[报表API] 报表下载成功: {filename}', 'api')
return send_from_directory(directory, filename, as_attachment=True)
except Exception as e:
print(f"[下载历史记录] 错误:{e}")
import traceback
traceback.print_exc()
log_error(f'[报表API] 下载报表失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500