更改总计逻辑
This commit is contained in:
@@ -8,7 +8,7 @@ from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill
|
||||
import pytz
|
||||
|
||||
from lib.db import execute_query, execute_insert
|
||||
from lib.db import execute_query, execute_insert, execute_update
|
||||
from lib.field_mapping import get_field_display_name
|
||||
from lib.logger import log_info, log_error, log_warning
|
||||
|
||||
@@ -328,6 +328,10 @@ def generate_daily_report(config_id, start_time=None, end_time=None):
|
||||
log_info(f" 时间范围: {start_time_str} 至 {end_time_str}", 'report')
|
||||
log_info(f" 选择字段: {len(selected_fields)} 个", 'report')
|
||||
|
||||
# 删除同一配置、同一日期、同一拆分的旧数据(覆盖)
|
||||
report_date = start_time.strftime('%Y-%m-%d')
|
||||
delete_old_history(config_id, report_date, config['split_type'], config['split_value'])
|
||||
|
||||
# 构建查询SQL - 过滤掉虚拟字段(时段电量等)
|
||||
# 虚拟字段不是数据库表中的实际字段,需要动态计算
|
||||
TIME_PERIOD_FIELDS = {'sharp_electricity', 'peak_electricity', 'flat_electricity', 'valley_electricity'}
|
||||
@@ -835,19 +839,25 @@ def generate_excel(orders, selected_fields, sum_fields, sum_results,
|
||||
config_id=config_id,
|
||||
month=month,
|
||||
split_type=split_type,
|
||||
split_value=split_value
|
||||
split_value=split_value,
|
||||
end_date=report_date
|
||||
)
|
||||
|
||||
if monthly_result['success'] and monthly_result['data']:
|
||||
total_degree = monthly_result['data']['total_degree']
|
||||
total_days = monthly_result['data']['total_days']
|
||||
today_degree_from_table = monthly_result['data'].get('today_degree', 0)
|
||||
missing_dates = monthly_result['data'].get('missing_dates', [])
|
||||
expected_days = monthly_result['data'].get('expected_days', 0)
|
||||
|
||||
# 如果当天的数据还没采集进 sum_data 表,手动加上当天的
|
||||
today_charge_degree = sum_results.get('charge_degree', 0)
|
||||
if today_degree_from_table == 0 and today_charge_degree > 0:
|
||||
total_degree = round(total_degree + today_charge_degree, 3)
|
||||
total_days = total_days + 1
|
||||
# 加上当天后,缺失日期也相应减少一天
|
||||
if report_date in missing_dates:
|
||||
missing_dates = [d for d in missing_dates if d != report_date]
|
||||
|
||||
# 月度总计行(在合计行下面空一行)
|
||||
monthly_row = sum_row + 2 if sum_fields else sum_row + 1
|
||||
@@ -860,10 +870,19 @@ def generate_excel(orders, selected_fields, sum_fields, sum_results,
|
||||
break
|
||||
|
||||
# 第一列显示标题
|
||||
ws.cell(row=monthly_row, column=1).value = f'当月累计充电量(共{total_days}天)'
|
||||
title_text = f'当月累计充电量(共{total_days}天,截止{report_date})'
|
||||
if missing_dates and len(missing_dates) > 0:
|
||||
# 最多显示5个缺失日期,超过的用"...共N天"表示
|
||||
if len(missing_dates) <= 5:
|
||||
missing_str = '、'.join([d[5:] for d in missing_dates]) # 只显示月-日
|
||||
else:
|
||||
missing_str = '、'.join([d[5:] for d in missing_dates[:5]]) + f'...共{len(missing_dates)}天'
|
||||
title_text += f'\n(缺:{missing_str})'
|
||||
|
||||
ws.cell(row=monthly_row, column=1).value = title_text
|
||||
ws.cell(row=monthly_row, column=1).font = monthly_font
|
||||
ws.cell(row=monthly_row, column=1).fill = monthly_fill
|
||||
ws.cell(row=monthly_row, column=1).alignment = Alignment(horizontal='center', vertical='center')
|
||||
ws.cell(row=monthly_row, column=1).alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
|
||||
ws.cell(row=monthly_row, column=1).border = thin_border
|
||||
|
||||
# 其他列也填充背景色
|
||||
@@ -882,7 +901,11 @@ def generate_excel(orders, selected_fields, sum_fields, sum_results,
|
||||
cell.alignment = Alignment(horizontal='right', vertical='center')
|
||||
cell.number_format = '0.000'
|
||||
|
||||
ws.row_dimensions[monthly_row].height = 25
|
||||
# 如果有缺失日期,行高加大一点
|
||||
if missing_dates and len(missing_dates) > 0:
|
||||
ws.row_dimensions[monthly_row].height = 40
|
||||
else:
|
||||
ws.row_dimensions[monthly_row].height = 25
|
||||
except Exception as e:
|
||||
log_error(f"[日报生成] 写入月度总计时出错: {e}", 'report')
|
||||
|
||||
@@ -978,4 +1001,83 @@ def save_report_history(report_date, start_time, end_time, split_type, split_val
|
||||
result = execute_insert(sql, params)
|
||||
log_info(f"[保存历史] 插入完成,返回ID: {result}", 'report')
|
||||
|
||||
return history_id
|
||||
return history_id
|
||||
|
||||
|
||||
def delete_old_history(config_id, report_date, split_type, split_value):
|
||||
"""
|
||||
删除同一配置、同一日期、同一拆分的旧历史记录,包括:
|
||||
1. 旧的报表文件
|
||||
2. 旧的求和数据(自动采集的)
|
||||
3. 旧的历史记录
|
||||
|
||||
Args:
|
||||
config_id: 配置ID
|
||||
report_date: 报表日期(YYYY-MM-DD)
|
||||
split_type: 拆分方式
|
||||
split_value: 拆分值
|
||||
"""
|
||||
try:
|
||||
log_info(f"[删除旧数据] 检查是否有旧数据,配置ID={config_id}, 日期={report_date}, 拆分={split_type}={split_value}", 'report')
|
||||
|
||||
# 查询旧的历史记录
|
||||
old_histories = execute_query(
|
||||
'''SELECT id, file_path FROM t_daily_report_history
|
||||
WHERE config_id = %s AND report_date = %s AND split_type = %s AND split_value = %s''',
|
||||
(config_id, report_date, split_type, split_value)
|
||||
)
|
||||
|
||||
if not old_histories:
|
||||
log_info("[删除旧数据] 没有找到旧数据", 'report')
|
||||
return
|
||||
|
||||
log_info(f"[删除旧数据] 找到 {len(old_histories)} 条旧记录", 'report')
|
||||
|
||||
reports_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'public', 'reports')
|
||||
|
||||
for history in old_histories:
|
||||
history_id = history['id']
|
||||
file_path = history.get('file_path', '')
|
||||
|
||||
# 删除报表文件
|
||||
if file_path:
|
||||
try:
|
||||
if file_path.startswith('/reports/'):
|
||||
filename = file_path.replace('/reports/', '')
|
||||
elif file_path.startswith('/public/reports/'):
|
||||
filename = file_path.replace('/public/reports/', '')
|
||||
else:
|
||||
filename = os.path.basename(file_path)
|
||||
|
||||
full_path = os.path.join(reports_dir, filename)
|
||||
if os.path.exists(full_path):
|
||||
os.remove(full_path)
|
||||
log_info(f"[删除旧数据] 已删除文件: {full_path}", 'report')
|
||||
except Exception as e:
|
||||
log_warning(f"[删除旧数据] 删除文件失败: {e}", 'report')
|
||||
|
||||
# 删除求和数据(自动采集的)
|
||||
try:
|
||||
execute_update(
|
||||
'''DELETE FROM t_daily_report_sum_data
|
||||
WHERE report_date = %s AND config_id = %s
|
||||
AND split_type = %s AND split_value = %s AND data_source = 'auto' ''',
|
||||
(report_date, config_id, split_type, split_value)
|
||||
)
|
||||
log_info(f"[删除旧数据] 已删除旧的求和数据", 'report')
|
||||
except Exception as e:
|
||||
log_warning(f"[删除旧数据] 删除求和数据失败: {e}", 'report')
|
||||
|
||||
# 删除历史记录
|
||||
try:
|
||||
execute_update(
|
||||
'DELETE FROM t_daily_report_history WHERE id = %s',
|
||||
(history_id,)
|
||||
)
|
||||
log_info(f"[删除旧数据] 已删除历史记录 ID={history_id}", 'report')
|
||||
except Exception as e:
|
||||
log_warning(f"[删除旧数据] 删除历史记录失败: {e}", 'report')
|
||||
|
||||
log_info("[删除旧数据] 旧数据清理完成", 'report')
|
||||
except Exception as e:
|
||||
log_error(f"[删除旧数据] 异常: {e}", 'report')
|
||||
Reference in New Issue
Block a user