增加序号,配置导出,导入,求和采集数据导出
This commit is contained in:
@@ -272,3 +272,150 @@ def move_config(config_id):
|
||||
traceback.print_exc()
|
||||
print(f"[move_config] 异常: {e}")
|
||||
return jsonify({'success': False, 'message': str(e)}), 500
|
||||
|
||||
|
||||
@config_bp.route('/config/export', methods=['GET'])
|
||||
def export_configs():
|
||||
"""导出所有配置为JSON文件"""
|
||||
try:
|
||||
from flask import Response
|
||||
import os
|
||||
|
||||
configs = execute_query(
|
||||
'SELECT * FROM t_daily_report_config ORDER BY sort_order ASC, id ASC'
|
||||
)
|
||||
|
||||
export_list = []
|
||||
for config in configs:
|
||||
export_item = {}
|
||||
for key, value in config.items():
|
||||
if key == 'id':
|
||||
continue
|
||||
export_item[key] = value
|
||||
export_list.append(export_item)
|
||||
|
||||
export_data = {
|
||||
'version': '1.0',
|
||||
'export_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'total': len(export_list),
|
||||
'configs': export_list
|
||||
}
|
||||
|
||||
json_str = json.dumps(export_data, ensure_ascii=False, indent=2)
|
||||
filename = f'日报配置导出_{datetime.now().strftime("%Y%m%d_%H%M%S")}.json'
|
||||
|
||||
response = Response(json_str, mimetype='application/json')
|
||||
response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
|
||||
return response
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify({'success': False, 'message': f'导出失败: {str(e)}'}), 500
|
||||
|
||||
|
||||
@config_bp.route('/config/import', methods=['POST'])
|
||||
def import_configs():
|
||||
"""从JSON文件导入配置"""
|
||||
try:
|
||||
if 'file' not in request.files:
|
||||
return jsonify({'success': False, 'message': '请选择要导入的文件'}), 400
|
||||
|
||||
file = request.files['file']
|
||||
if file.filename == '':
|
||||
return jsonify({'success': False, 'message': '请选择要导入的文件'}), 400
|
||||
|
||||
if not file.filename.endswith('.json'):
|
||||
return jsonify({'success': False, 'message': '只支持 JSON 格式的配置文件'}), 400
|
||||
|
||||
file_content = file.read().decode('utf-8')
|
||||
import_data = json.loads(file_content)
|
||||
|
||||
if 'configs' not in import_data:
|
||||
return jsonify({'success': False, 'message': '文件格式不正确,缺少 configs 字段'}), 400
|
||||
|
||||
configs_to_import = import_data['configs']
|
||||
if not isinstance(configs_to_import, list) or len(configs_to_import) == 0:
|
||||
return jsonify({'success': False, 'message': '没有可导入的配置'}), 400
|
||||
|
||||
max_sort_result = execute_query('SELECT MAX(sort_order) as max_sort FROM t_daily_report_config')
|
||||
current_max_sort = max_sort_result[0]['max_sort'] or 0
|
||||
|
||||
success_count = 0
|
||||
fail_count = 0
|
||||
fail_messages = []
|
||||
|
||||
for idx, config_data in enumerate(configs_to_import):
|
||||
try:
|
||||
config_name = config_data.get('config_name', '')
|
||||
split_type = config_data.get('split_type', '')
|
||||
split_value = config_data.get('split_value', '')
|
||||
|
||||
if not config_name or not split_type or not split_value:
|
||||
fail_count += 1
|
||||
fail_messages.append(f'第{idx+1}条:缺少必填字段')
|
||||
continue
|
||||
|
||||
new_id = int(datetime.now().timestamp() * 1000) + idx
|
||||
new_name = f"{config_name}_导入"
|
||||
sort_order = current_max_sort + 1
|
||||
current_max_sort += 1
|
||||
|
||||
selected_fields = config_data.get('selected_fields', '[]')
|
||||
if isinstance(selected_fields, str):
|
||||
selected_fields = json.loads(selected_fields) if selected_fields else []
|
||||
|
||||
sum_fields = config_data.get('sum_fields', '[]')
|
||||
if isinstance(sum_fields, str):
|
||||
sum_fields = json.loads(sum_fields) if sum_fields else []
|
||||
|
||||
time_periods = config_data.get('time_periods', '{}')
|
||||
if isinstance(time_periods, str):
|
||||
time_periods = json.loads(time_periods) if time_periods else {}
|
||||
|
||||
field_custom_names = config_data.get('field_custom_names')
|
||||
if isinstance(field_custom_names, str):
|
||||
field_custom_names = json.loads(field_custom_names) if field_custom_names else None
|
||||
|
||||
sql = """
|
||||
INSERT INTO t_daily_report_config
|
||||
(id, config_name, split_type, split_value, split_name, selected_fields,
|
||||
sum_fields, time_periods, merge_telecom, telecom_vehicle_no, field_custom_names,
|
||||
show_monthly_total, is_active, sort_order, create_time, update_time)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 0, %s, NOW(), NOW())
|
||||
"""
|
||||
|
||||
params = (
|
||||
new_id,
|
||||
new_name,
|
||||
split_type,
|
||||
split_value,
|
||||
config_data.get('split_name', ''),
|
||||
json.dumps(selected_fields, ensure_ascii=False),
|
||||
json.dumps(sum_fields, ensure_ascii=False),
|
||||
json.dumps(time_periods, ensure_ascii=False),
|
||||
config_data.get('merge_telecom', 0),
|
||||
config_data.get('telecom_vehicle_no', ''),
|
||||
json.dumps(field_custom_names, ensure_ascii=False) if field_custom_names else None,
|
||||
config_data.get('show_monthly_total', 0),
|
||||
sort_order
|
||||
)
|
||||
|
||||
execute_insert(sql, params)
|
||||
success_count += 1
|
||||
except Exception as item_error:
|
||||
fail_count += 1
|
||||
fail_messages.append(f'第{idx+1}条:{str(item_error)}')
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': f'导入完成:成功 {success_count} 条,失败 {fail_count} 条',
|
||||
'data': {
|
||||
'success_count': success_count,
|
||||
'fail_count': fail_count,
|
||||
'fail_messages': fail_messages
|
||||
}
|
||||
})
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify({'success': False, 'message': f'导入失败: {str(e)}'}), 500
|
||||
|
||||
@@ -9,7 +9,8 @@ from lib.sum_data_collector import (
|
||||
update_sum_data,
|
||||
delete_sum_data,
|
||||
batch_delete_sum_data,
|
||||
get_monthly_charge_degree_total
|
||||
get_monthly_charge_degree_total,
|
||||
export_sum_data_to_excel
|
||||
)
|
||||
from . import sum_data_bp
|
||||
|
||||
@@ -38,7 +39,8 @@ def list_sum_data():
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
page_size = int(request.args.get('page_size', 20))
|
||||
report_date = request.args.get('report_date')
|
||||
start_date = request.args.get('start_date')
|
||||
end_date = request.args.get('end_date')
|
||||
config_id = request.args.get('config_id')
|
||||
config_name = request.args.get('config_name')
|
||||
sum_field_key = request.args.get('sum_field_key')
|
||||
@@ -47,7 +49,8 @@ def list_sum_data():
|
||||
result = get_sum_data_list(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
report_date=report_date,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
config_id=config_id,
|
||||
config_name=config_name,
|
||||
sum_field_key=sum_field_key,
|
||||
@@ -152,3 +155,39 @@ def monthly_charge_degree_total():
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify({'success': False, 'message': str(e)}), 500
|
||||
|
||||
|
||||
@sum_data_bp.route('/sum-data/export', methods=['GET'])
|
||||
def export_sum_data():
|
||||
"""导出求和数据为Excel
|
||||
|
||||
参数:
|
||||
start_date: 开始日期(可选)
|
||||
end_date: 结束日期(可选)
|
||||
config_id: 配置ID(可选)
|
||||
data_source: 数据来源(可选)
|
||||
keyword: 配置名称关键词(可选)
|
||||
"""
|
||||
try:
|
||||
start_date = request.args.get('start_date')
|
||||
end_date = request.args.get('end_date')
|
||||
config_id = request.args.get('config_id')
|
||||
data_source = request.args.get('data_source')
|
||||
keyword = request.args.get('keyword')
|
||||
|
||||
result = export_sum_data_to_excel(
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
config_id=config_id,
|
||||
data_source=data_source,
|
||||
keyword=keyword
|
||||
)
|
||||
|
||||
if result['success']:
|
||||
return jsonify(result)
|
||||
else:
|
||||
return jsonify(result), 400
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify({'success': False, 'message': str(e)}), 500
|
||||
|
||||
Reference in New Issue
Block a user