From 443fe4e56eaedfb3f700525f6e0ade7c78758e04 Mon Sep 17 00:00:00 2001 From: Caozhenhui <823914102@qq.com> Date: Fri, 16 Jul 2021 12:41:29 +0800 Subject: [PATCH] Implemented the equipmentbatch Excel Exporte --- myems-api/excelexporters/equipmentbatch.py | 188 ++++++++++++++++ myems-api/reports/equipmentbatch.py | 245 +++++++++++++++++++++ 2 files changed, 433 insertions(+) create mode 100644 myems-api/excelexporters/equipmentbatch.py create mode 100644 myems-api/reports/equipmentbatch.py diff --git a/myems-api/excelexporters/equipmentbatch.py b/myems-api/excelexporters/equipmentbatch.py new file mode 100644 index 00000000..8724b61d --- /dev/null +++ b/myems-api/excelexporters/equipmentbatch.py @@ -0,0 +1,188 @@ +import base64 +import uuid +import os +from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font +from openpyxl.drawing.image import Image +from openpyxl import Workbook + + +#################################################################################################################### +# PROCEDURES +# Step 1: Validate the report data +# Step 2: Generate excelexporters file +# Step 3: Encode the excelexporters file to Base64 +#################################################################################################################### + +def export(result, space_name, reporting_start_datetime_local, reporting_end_datetime_local): + #################################################################################################################### + # Step 1: Validate the report data + #################################################################################################################### + if result is None: + return None + + #################################################################################################################### + # Step 2: Generate excel file from the report data + #################################################################################################################### + filename = generate_excel(result, + space_name, + reporting_start_datetime_local, + reporting_end_datetime_local) + #################################################################################################################### + # Step 3: Encode the excel file to Base64 + #################################################################################################################### + try: + with open(filename, 'rb') as binary_file: + binary_file_data = binary_file.read() + except IOError as ex: + pass + + # Base64 encode the bytes + base64_encoded_data = base64.b64encode(binary_file_data) + # get the Base64 encoded data using human-readable characters. + base64_message = base64_encoded_data.decode('utf-8') + # delete the file from server + try: + os.remove(filename) + except NotImplementedError as ex: + pass + return base64_message + + +def generate_excel(report, space_name, reporting_start_datetime_local, reporting_end_datetime_local): + + wb = Workbook() + ws = wb.active + + # Row height + ws.row_dimensions[1].height = 102 + for i in range(2, 5 + 1): + ws.row_dimensions[i].height = 42 + + for i in range(6, len(report['equipments']) + 15): + ws.row_dimensions[i].height = 60 + + # Col width + ws.column_dimensions['A'].width = 1.5 + + ws.column_dimensions['B'].width = 25.0 + + for i in range(ord('C'), ord('L')): + ws.column_dimensions[chr(i)].width = 15.0 + + # Font + name_font = Font(name='Constantia', size=15, bold=True) + title_font = Font(name='宋体', size=15, bold=True) + data_font = Font(name='Franklin Gothic Book', size=11) + + table_fill = PatternFill(fill_type='solid', fgColor='1F497D') + f_border = Border(left=Side(border_style='medium', color='00000000'), + right=Side(border_style='medium', color='00000000'), + bottom=Side(border_style='medium', color='00000000'), + top=Side(border_style='medium', color='00000000') + ) + b_border = Border( + bottom=Side(border_style='medium', color='00000000'), + ) + + b_c_alignment = Alignment(vertical='bottom', + horizontal='center', + text_rotation=0, + wrap_text=True, + shrink_to_fit=False, + indent=0) + c_c_alignment = Alignment(vertical='center', + horizontal='center', + text_rotation=0, + wrap_text=True, + shrink_to_fit=False, + indent=0) + b_r_alignment = Alignment(vertical='bottom', + horizontal='right', + text_rotation=0, + wrap_text=True, + shrink_to_fit=False, + indent=0) + c_r_alignment = Alignment(vertical='bottom', + horizontal='center', + text_rotation=0, + wrap_text=True, + shrink_to_fit=False, + indent=0) + + # Img + img = Image("excelexporters/myems.png") + img.width = img.width * 0.85 + img.height = img.height * 0.85 + ws.add_image(img, 'B1') + + # Title + ws.row_dimensions[3].height = 60 + + ws['B3'].font = name_font + ws['B3'].alignment = b_r_alignment + ws['B3'] = '空间:' + ws['C3'].border = b_border + ws['C3'].alignment = b_c_alignment + ws['C3'].font = name_font + ws['C3'] = space_name + + ws['F3'].font = name_font + ws['F3'].alignment = b_r_alignment + ws['F3'] = '日期:' + ws['G3'].border = b_border + ws['G3'].alignment = b_c_alignment + ws['G3'].font = name_font + ws['G3'] = reporting_start_datetime_local + "~" + reporting_end_datetime_local + ws.merge_cells("G3:H3") + + # Title + ws['B6'].border = f_border + ws['B6'].font = name_font + ws['B6'].alignment = c_c_alignment + ws['B6'].fill = table_fill + ws['B6'] = '名称' + + ws['C6'].border = f_border + ws['C6'].alignment = c_c_alignment + ws['C6'].font = name_font + ws['C6'].fill = table_fill + ws['C6'] = '空间' + + ca_len = len(report['energycategories']) + + for i in range(0, ca_len): + col = chr(ord('D') + i) + ws[col + '6'].fill = table_fill + ws[col + '6'].font = name_font + ws[col + '6'].alignment = c_c_alignment + ws[col + '6'] = report['energycategories'][i]['name'] + \ + " (" + report['energycategories'][i]['unit_of_measure'] + ")" + ws[col + '6'].border = f_border + + current_row_number = 7 + for i in range(0, len(report['equipments'])): + + ws['B' + str(current_row_number)].font = title_font + ws['B' + str(current_row_number)].border = f_border + ws['B' + str(current_row_number)].alignment = c_c_alignment + ws['B' + str(current_row_number)] = report['equipments'][i]['equipment_name'] + + ws['C' + str(current_row_number)].font = title_font + ws['C' + str(current_row_number)].border = f_border + ws['C' + str(current_row_number)].alignment = c_c_alignment + ws['C' + str(current_row_number)] = report['equipments'][i]['space_name'] + + ca_len = len(report['equipments'][i]['values']) + for j in range(0, ca_len): + col = chr(ord('D') + j) + ws[col + str(current_row_number)].font = data_font + ws[col + str(current_row_number)].border = f_border + ws[col + str(current_row_number)].alignment = c_c_alignment + ws[col + str(current_row_number)] = round(report['equipments'][i]['values'][j], 2) + + current_row_number += 1 + + filename = str(uuid.uuid4()) + '.xlsx' + wb.save(filename) + + return filename diff --git a/myems-api/reports/equipmentbatch.py b/myems-api/reports/equipmentbatch.py new file mode 100644 index 00000000..939e654f --- /dev/null +++ b/myems-api/reports/equipmentbatch.py @@ -0,0 +1,245 @@ +import falcon +import simplejson as json +import mysql.connector +import config +from anytree import Node, AnyNode, LevelOrderIter +from datetime import datetime, timedelta, timezone +from decimal import Decimal +import excelexporters.equipmentbatch + + +class Reporting: + @staticmethod + def __init__(): + pass + + @staticmethod + def on_options(req, resp): + resp.status = falcon.HTTP_200 + + #################################################################################################################### + # PROCEDURES + # Step 1: valid parameters + # Step 2: build a space tree + # Step 3: query all equipments in the space tree + # Step 4: query energy categories + # Step 5: query reporting period energy input + # Step 6: construct the report + #################################################################################################################### + @staticmethod + def on_get(req, resp): + print(req.params) + space_id = req.params.get('spaceid') + reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime') + reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime') + + ################################################################################################################ + # Step 1: valid parameters + ################################################################################################################ + if space_id is None: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID') + else: + space_id = str.strip(space_id) + if not space_id.isdigit() or int(space_id) <= 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID') + else: + space_id = int(space_id) + + timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) + if config.utc_offset[0] == '-': + timezone_offset = -timezone_offset + + if reporting_period_start_datetime_local is None: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description="API.INVALID_REPORTING_PERIOD_START_DATETIME") + else: + reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) + try: + reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, + '%Y-%m-%dT%H:%M:%S') + except ValueError: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description="API.INVALID_REPORTING_PERIOD_START_DATETIME") + reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \ + timedelta(minutes=timezone_offset) + + if reporting_period_end_datetime_local is None: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description="API.INVALID_REPORTING_PERIOD_END_DATETIME") + else: + reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) + try: + reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, + '%Y-%m-%dT%H:%M:%S') + except ValueError: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description="API.INVALID_REPORTING_PERIOD_END_DATETIME") + reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ + timedelta(minutes=timezone_offset) + + if reporting_start_datetime_utc >= reporting_end_datetime_utc: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_REPORTING_PERIOD_END_DATETIME') + + cnx_system_db = mysql.connector.connect(**config.myems_system_db) + cursor_system_db = cnx_system_db.cursor(dictionary=True) + + cursor_system_db.execute(" SELECT name " + " FROM tbl_spaces " + " WHERE id = %s ", (space_id,)) + row = cursor_system_db.fetchone() + + if row is None: + if cursor_system_db: + cursor_system_db.close() + if cnx_system_db: + cnx_system_db.disconnect() + raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', + description='API.SPACE_NOT_FOUND') + else: + space_name = row['name'] + + ################################################################################################################ + # Step 2: build a space tree + ################################################################################################################ + + query = (" SELECT id, name, parent_space_id " + " FROM tbl_spaces " + " ORDER BY id ") + cursor_system_db.execute(query) + rows_spaces = cursor_system_db.fetchall() + node_dict = dict() + if rows_spaces is not None and len(rows_spaces) > 0: + for row in rows_spaces: + parent_node = node_dict[row['parent_space_id']] if row['parent_space_id'] is not None else None + node_dict[row['id']] = AnyNode(id=row['id'], parent=parent_node, name=row['name']) + + ################################################################################################################ + # Step 3: query all equipments in the space tree + ################################################################################################################ + equipment_dict = dict() + space_dict = dict() + + for node in LevelOrderIter(node_dict[space_id]): + space_dict[node.id] = node.name + + cursor_system_db.execute(" SELECT e.id, e.name AS equipment_name, s.name AS space_name, " + " cc.name AS cost_center_name, e.description " + " FROM tbl_spaces s, tbl_spaces_equipments se, " + " tbl_equipments e, tbl_cost_centers cc " + " WHERE s.id IN ( " + ', '.join(map(str, space_dict.keys())) + ") " + "AND se.space_id = " + "s.id AND " + "se.equipment_id = " + "e.id AND " + "e.cost_center_id = " + "cc.id ", ) + rows_equipments = cursor_system_db.fetchall() + if rows_equipments is not None and len(rows_equipments) > 0: + for row in rows_equipments: + equipment_dict[row['id']] = {"equipment_name": row['equipment_name'], + "space_name": row['space_name'], + "cost_center_name": row['cost_center_name'], + "description": row['description'], + "values": list()} + + ################################################################################################################ + # Step 4: query energy categories + ################################################################################################################ + cnx_energy_db = mysql.connector.connect(**config.myems_energy_db) + cursor_energy_db = cnx_energy_db.cursor() + + # query energy categories in reporting period + energy_category_set = set() + cursor_energy_db.execute(" SELECT DISTINCT(energy_category_id) " + " FROM tbl_equipment_input_category_hourly " + " WHERE start_datetime_utc >= %s AND start_datetime_utc < %s ", + (reporting_start_datetime_utc, reporting_end_datetime_utc)) + rows_energy_categories = cursor_energy_db.fetchall() + if rows_energy_categories is not None or len(rows_energy_categories) > 0: + for row_energy_category in rows_energy_categories: + energy_category_set.add(row_energy_category[0]) + + # query all energy categories + cursor_system_db.execute(" SELECT id, name, unit_of_measure " + " FROM tbl_energy_categories " + " ORDER BY id ", ) + rows_energy_categories = cursor_system_db.fetchall() + if rows_energy_categories is None or len(rows_energy_categories) == 0: + if cursor_system_db: + cursor_system_db.close() + if cnx_system_db: + cnx_system_db.disconnect() + + if cursor_energy_db: + cursor_energy_db.close() + if cnx_energy_db: + cnx_energy_db.disconnect() + + raise falcon.HTTPError(falcon.HTTP_404, + title='API.NOT_FOUND', + description='API.ENERGY_CATEGORY_NOT_FOUND') + energy_category_list = list() + for row_energy_category in rows_energy_categories: + if row_energy_category['id'] in energy_category_set: + energy_category_list.append({"id": row_energy_category['id'], + "name": row_energy_category['name'], + "unit_of_measure": row_energy_category['unit_of_measure']}) + + ################################################################################################################ + # Step 5: query reporting period energy input + ################################################################################################################ + for equipment_id in equipment_dict: + + cursor_energy_db.execute(" SELECT energy_category_id, SUM(actual_value) " + " FROM tbl_equipment_input_category_hourly " + " WHERE equipment_id = %s " + " AND start_datetime_utc >= %s " + " AND start_datetime_utc < %s " + " GROUP BY energy_category_id ", + (equipment_id, + reporting_start_datetime_utc, + reporting_end_datetime_utc)) + rows_equipment_energy = cursor_energy_db.fetchall() + for energy_category in energy_category_list: + subtotal = Decimal(0.0) + for rows_equipment_energy in rows_equipment_energy: + if energy_category['id'] == rows_equipment_energy[0]: + subtotal = rows_equipment_energy[1] + break + equipment_dict[equipment_id]['values'].append(subtotal) + + if cursor_system_db: + cursor_system_db.close() + if cnx_system_db: + cnx_system_db.disconnect() + + if cursor_energy_db: + cursor_energy_db.close() + if cnx_energy_db: + cnx_energy_db.disconnect() + + ################################################################################################################ + # Step 6: construct the report + ################################################################################################################ + equipment_list = list() + for equipment_id, equipment in equipment_dict.items(): + equipment_list.append({ + "id": equipment_id, + "equipment_name": equipment['equipment_name'], + "space_name": equipment['space_name'], + "cost_center_name": equipment['cost_center_name'], + "description": equipment['description'], + "values": equipment['values'], + }) + + result = {'equipments': equipment_list, + 'energycategories': energy_category_list} + + # export result to Excel file and then encode the file to base64 string + result['excel_bytes_base64'] = \ + excelexporters.equipmentbatch.export(result, + space_name, + reporting_period_start_datetime_local, + reporting_period_end_datetime_local) + resp.body = json.dumps(result)