增加日志

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

@@ -5,6 +5,7 @@ import json
from datetime import datetime
from flask import request, jsonify
from lib.db import execute_query, execute_update, execute_insert
from lib.logger import log_info, log_error, log_warning
from . import config_bp
@@ -12,6 +13,7 @@ from . import config_bp
def get_configs():
"""获取所有配置"""
try:
log_info('[配置API] 获取配置列表', 'api')
configs = execute_query(
'SELECT * FROM t_daily_report_config ORDER BY sort_order ASC, id DESC'
)
@@ -22,8 +24,10 @@ def get_configs():
config['sum_fields'] = json.loads(config['sum_fields']) if config['sum_fields'] else []
config['time_periods'] = json.loads(config['time_periods']) if config.get('time_periods') else {}
log_info(f'[配置API] 获取到 {len(configs)} 条配置', 'api')
return jsonify({'success': True, 'data': configs})
except Exception as e:
log_error(f'[配置API] 获取配置列表失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -31,6 +35,7 @@ def get_configs():
def create_config():
"""创建配置"""
try:
log_info('[配置API] 创建配置', 'api')
data = request.json
config_name = data.get('config_name')
split_type = data.get('split_type')
@@ -52,9 +57,11 @@ def create_config():
custom_service_fee_name = data.get('custom_service_fee_name')
if not config_name or not split_type or not split_value:
log_warning('[配置API] 创建配置失败:缺少必填字段', 'api')
return jsonify({'success': False, 'message': '缺少必填字段'}), 400
if not selected_fields:
log_warning('[配置API] 创建配置失败:未选择字段', 'api')
return jsonify({'success': False, 'message': '请至少选择一个字段'}), 400
# 生成 ID
@@ -92,12 +99,14 @@ def create_config():
execute_insert(sql, params)
log_info(f'[配置API] 配置创建成功,ID: {config_id},名称: {config_name}', 'api')
return jsonify({
'success': True,
'message': '配置创建成功',
'data': {'id': config_id}
})
except Exception as e:
log_error(f'[配置API] 创建配置失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -105,6 +114,7 @@ def create_config():
def update_config(config_id):
"""更新配置"""
try:
log_info(f'[配置API] 更新配置,ID: {config_id}', 'api')
data = request.json
config_name = data.get('config_name')
split_type = data.get('split_type')
@@ -125,6 +135,12 @@ def update_config(config_id):
custom_service_fee_name = data.get('custom_service_fee_name')
# 查询原配置,检查拆分是否变化
old_configs = execute_query('SELECT * FROM t_daily_report_config WHERE id = %s', (config_id,))
if not old_configs:
return jsonify({'success': False, 'message': '配置不存在'}), 404
old_config = old_configs[0]
sql = """
UPDATE t_daily_report_config
SET config_name = %s, split_type = %s, split_value = %s, split_name = %s,
@@ -154,8 +170,32 @@ def update_config(config_id):
execute_update(sql, params)
# 如果拆分类型或拆分值变化了,清理旧的求和数据(以当前拆分为准)
old_split_type = old_config.get('split_type')
old_split_value = old_config.get('split_value', '')
if old_split_type != split_type or old_split_value != split_value:
new_values = set(v.strip() for v in split_value.split(',') if v.strip())
old_values = set(v.strip() for v in str(old_split_value).split(',') if v.strip())
removed_values = old_values - new_values
if removed_values:
placeholders = ','.join(['%s'] * len(removed_values))
delete_sql = f'''
DELETE FROM t_daily_report_sum_data
WHERE config_id = %s AND split_type = %s
AND split_value IN ({placeholders})
'''
delete_params = [config_id, old_split_type] + list(removed_values)
try:
from lib.db import execute_update
execute_update(delete_sql, tuple(delete_params))
log_info(f'[配置API] 拆分值变化,已清理{len(removed_values)}个旧拆分的求和数据', 'api')
except Exception as e:
log_error(f'[配置API] 清理旧求和数据失败: {e}', 'api')
log_info(f'[配置API] 配置更新成功,ID: {config_id}', 'api')
return jsonify({'success': True, 'message': '配置更新成功'})
except Exception as e:
log_error(f'[配置API] 更新配置失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -163,9 +203,18 @@ def update_config(config_id):
def delete_config(config_id):
"""删除配置"""
try:
log_info(f'[配置API] 删除配置,ID: {config_id}', 'api')
execute_update('DELETE FROM t_daily_report_config WHERE id = %s', (config_id,))
# 同时删除对应的求和数据
try:
execute_update('DELETE FROM t_daily_report_sum_data WHERE config_id = %s', (config_id,))
log_info(f'[配置API] 已清理配置对应的求和数据', 'api')
except Exception as e:
log_error(f'[配置API] 清理求和数据失败: {e}', 'api')
log_info(f'[配置API] 配置删除成功,ID: {config_id}', 'api')
return jsonify({'success': True, 'message': '配置删除成功'})
except Exception as e:
log_error(f'[配置API] 删除配置失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -236,15 +285,13 @@ def move_config(config_id):
"""移动配置排序"""
try:
direction = request.json.get('direction') # up 或 down
print(f"[move_config] 开始移动 config_id={config_id}, direction={direction}")
log_info(f"[配置API] 移动配置,ID: {config_id}, 方向: {direction}", 'api')
# 查出所有配置,按 sort_order, id 排序
all_configs = execute_query(
'SELECT id, sort_order FROM t_daily_report_config ORDER BY sort_order ASC, id ASC'
)
print(f"[move_config] 所有配置数量: {len(all_configs)}")
for idx, c in enumerate(all_configs):
print(f" [{idx}] id={c['id']}, sort_order={c['sort_order']}")
log_info(f"[配置API] 所有配置数量: {len(all_configs)}", 'api')
# 找到当前配置的索引
current_index = None
@@ -254,10 +301,10 @@ def move_config(config_id):
break
if current_index is None:
print(f"[move_config] 未找到配置 id={config_id}")
log_warning(f"[配置API] 未找到配置,ID: {config_id}", 'api')
return jsonify({'success': False, 'message': '配置不存在'}), 404
print(f"[move_config] 当前配置索引: {current_index}")
log_info(f"[配置API] 当前配置索引: {current_index}", 'api')
# 计算目标索引
if direction == 'up':
@@ -269,29 +316,24 @@ def move_config(config_id):
# 边界检查
if target_index < 0 or target_index >= len(all_configs):
print(f"[move_config] 已到边界,无法移动 target_index={target_index}")
log_info(f"[配置API] 已到边界,无法移动", 'api')
return jsonify({'success': True, 'message': '已到边界'})
# 在内存数组中交换位置
all_configs[current_index], all_configs[target_index] = all_configs[target_index], all_configs[current_index]
print(f"[move_config] 交换后顺序: {[c['id'] for c in all_configs]}")
# 全量重排:按新顺序给每个配置重新赋值 sort_order
for idx, cfg in enumerate(all_configs):
new_sort = idx + 1
print(f" 更新 id={cfg['id']}: sort_order {cfg['sort_order']} -> {new_sort}")
execute_update(
'UPDATE t_daily_report_config SET sort_order = %s WHERE id = %s',
(new_sort, cfg['id'])
)
print("[move_config] 重排完成")
log_info(f"[配置API] 配置移动成功,ID: {config_id}", 'api')
return jsonify({'success': True, 'message': '移动成功'})
except Exception as e:
import traceback
traceback.print_exc()
print(f"[move_config] 异常: {e}")
log_error(f"[配置API] 移动配置失败: {e}", 'api')
return jsonify({'success': False, 'message': str(e)}), 500

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

View File

@@ -12,6 +12,7 @@ from lib.sum_data_collector import (
get_monthly_charge_degree_total,
export_sum_data_to_excel
)
from lib.logger import log_info, log_error, log_warning
from . import sum_data_bp
@@ -21,15 +22,17 @@ def collect_sum_data():
try:
data = request.json or {}
history_id = data.get('history_id')
log_info(f'[求和数据API] 采集求和数据,历史记录ID: {history_id or "全部"}', 'api')
result = collect_sum_data_from_history(history_id)
if result['success']:
log_info(f'[求和数据API] 采集成功: {result["message"]}', 'api')
return jsonify(result)
else:
log_warning(f'[求和数据API] 采集失败: {result["message"]}', 'api')
return jsonify(result), 400
except Exception as e:
import traceback
traceback.print_exc()
log_error(f'[求和数据API] 采集异常: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -45,6 +48,7 @@ def list_sum_data():
config_name = request.args.get('config_name')
sum_field_key = request.args.get('sum_field_key')
data_source = request.args.get('data_source')
log_info(f'[求和数据API] 查询求和数据列表,第{page}页', 'api')
result = get_sum_data_list(
page=page,
@@ -58,12 +62,12 @@ def list_sum_data():
)
if result['success']:
log_info(f'[求和数据API] 查询成功,共{result["data"]["total"]}条记录', 'api')
return jsonify(result)
else:
return jsonify(result), 400
except Exception as e:
import traceback
traceback.print_exc()
log_error(f'[求和数据API] 查询求和数据列表失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -72,14 +76,15 @@ def create_sum_data():
"""手动添加求和数据"""
try:
data = request.json
log_info('[求和数据API] 手动添加求和数据', 'api')
result = add_sum_data(data)
if result['success']:
log_info(f'[求和数据API] 添加成功,ID: {result.get("id", "")}', 'api')
return jsonify(result)
else:
return jsonify(result), 400
except Exception as e:
import traceback
traceback.print_exc()
log_error(f'[求和数据API] 添加求和数据失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -88,14 +93,15 @@ def update_sum_data_api(sum_data_id):
"""更新求和数据"""
try:
data = request.json
log_info(f'[求和数据API] 更新求和数据,ID: {sum_data_id}', 'api')
result = update_sum_data(sum_data_id, data)
if result['success']:
log_info(f'[求和数据API] 更新成功,ID: {sum_data_id}', 'api')
return jsonify(result)
else:
return jsonify(result), 400
except Exception as e:
import traceback
traceback.print_exc()
log_error(f'[求和数据API] 更新求和数据失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -103,14 +109,15 @@ def update_sum_data_api(sum_data_id):
def delete_sum_data_api(sum_data_id):
"""删除求和数据"""
try:
log_info(f'[求和数据API] 删除求和数据,ID: {sum_data_id}', 'api')
result = delete_sum_data(sum_data_id)
if result['success']:
log_info(f'[求和数据API] 删除成功,ID: {sum_data_id}', 'api')
return jsonify(result)
else:
return jsonify(result), 400
except Exception as e:
import traceback
traceback.print_exc()
log_error(f'[求和数据API] 删除求和数据失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -120,17 +127,19 @@ def batch_delete_sum_data_api():
try:
data = request.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
result = batch_delete_sum_data(ids)
if result['success']:
log_info(f'[求和数据API] 批量删除成功,{result["message"]}', 'api')
return jsonify(result)
else:
return jsonify(result), 400
except Exception as e:
import traceback
traceback.print_exc()
log_error(f'[求和数据API] 批量删除求和数据失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -145,15 +154,16 @@ def monthly_charge_degree_total():
try:
config_id = request.args.get('config_id')
month = request.args.get('month')
log_info(f'[求和数据API] 查询月度累计,配置ID: {config_id or "全部"},月份: {month or "当月"}', 'api')
result = get_monthly_charge_degree_total(config_id, month)
if result['success']:
log_info(f'[求和数据API] 查询成功,累计电量: {result["data"]["total_degree"]} kWh', 'api')
return jsonify(result)
else:
return jsonify(result), 400
except Exception as e:
import traceback
traceback.print_exc()
log_error(f'[求和数据API] 查询月度累计失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500
@@ -174,6 +184,7 @@ def export_sum_data():
config_id = request.args.get('config_id')
data_source = request.args.get('data_source')
keyword = request.args.get('keyword')
log_info(f'[求和数据API] 导出求和数据,日期范围: {start_date or "开始"} ~ {end_date or "结束"}', 'api')
result = export_sum_data_to_excel(
start_date=start_date,
@@ -184,10 +195,10 @@ def export_sum_data():
)
if result['success']:
log_info(f'[求和数据API] 导出成功,共{result.get("total", 0)}条记录', 'api')
return jsonify(result)
else:
return jsonify(result), 400
except Exception as e:
import traceback
traceback.print_exc()
log_error(f'[求和数据API] 导出求和数据失败: {e}', 'api')
return jsonify({'success': False, 'message': str(e)}), 500