Issues (1577)

myems-api/excelexporters/metertracking.py (2 issues)

1
import base64
2
from core.utilities import get_translation
3
import os
4
import uuid
5
from decimal import Decimal
6
from openpyxl import Workbook
7
from openpyxl.drawing.image import Image
8
from openpyxl.styles import Alignment, Font
9
from core.utilities import round2
10
11
12
########################################################################################################################
13
# PROCEDURES
14
# Step 1: Validate the report data
15
# Step 2: Generate excelexporters file
16
# Step 3: Encode the excelexporters file to Base64
17
########################################################################################################################
18 View Code Duplication
def export(result, space_name, energy_category_name, reporting_start_datetime_local, reporting_end_datetime_local,
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
19
           language):
20
    ####################################################################################################################
21
    # Step 1: Validate the report data
22
    ####################################################################################################################
23
    if result is None:
24
        return None
25
26
    ####################################################################################################################
27
    # Step 2: Generate excel file from the report data
28
    ####################################################################################################################
29
    filename = generate_excel(result,
30
                              space_name,
31
                              energy_category_name,
32
                              reporting_start_datetime_local,
33
                              reporting_end_datetime_local,
34
                              language)
35
    ####################################################################################################################
36
    # Step 3: Encode the excel file to Base64
37
    ####################################################################################################################
38
    binary_file_data = b''
39
    try:
40
        with open(filename, 'rb') as binary_file:
41
            binary_file_data = binary_file.read()
42
    except IOError as ex:
43
        print(str(ex))
44
45
    # Base64 encode the bytes
46
    base64_encoded_data = base64.b64encode(binary_file_data)
47
    # get the Base64 encoded data using human-readable characters.
48
    base64_message = base64_encoded_data.decode('utf-8')
49
    # delete the file from server
50
    try:
51
        os.remove(filename)
52
    except NotImplementedError as ex:
53
        print(str(ex))
54
    return base64_message
55
56
57
def generate_excel(report, space_name, energy_category_name, reporting_start_datetime_local,
58
                   reporting_end_datetime_local, language):
59
60
    trans = get_translation(language)
61
    trans.install()
62
    _ = trans.gettext
63
64
    wb = Workbook()
65
    ws = wb.active
66
    ws.title = "MeterTracking"
67
68
    # Column width
69
    for i in range(ord('A'), ord('I')):
70
        ws.column_dimensions[chr(i)].width = 25.0
71
72
    # Head image
73
    ws.row_dimensions[1].height = 105
74
    img = Image("excelexporters/myems.png")
75
    ws.add_image(img, 'A1')
76
77
    # Query Parameters
78
    b_r_alignment = Alignment(vertical='bottom',
79
                              horizontal='right',
80
                              text_rotation=0,
81
                              wrap_text=True,
82
                              shrink_to_fit=False,
83
                              indent=0)
84
    ws['A3'].alignment = b_r_alignment
85
    ws['A3'] = _('Space') + ':'
86
    ws['B3'] = space_name
87
    ws['A4'].alignment = b_r_alignment
88
    ws['A4'] = _('Start Datetime') + ':'
89
    ws['B4'] = reporting_start_datetime_local
90
    ws['A5'].alignment = b_r_alignment
91
    ws['A5'] = _('End Datetime') + ':'
92
    ws['B5'] = reporting_end_datetime_local
93
    ws['A6'].alignment = b_r_alignment
94
    ws['A6'] = _('Start Integrity Rate') + ':'
95
    ws['B6'] = (str(round2(report['start_integrity_rate'] * Decimal(100.0), 2)) + '%') \
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable str does not seem to be defined.
Loading history...
96
        if report['start_integrity_rate'] is not None else None
97
    ws['A7'].alignment = b_r_alignment
98
    ws['A7'] = _('End Integrity Rate') + ':'
99
    ws['B7'] = (str(round2(report['end_integrity_rate'] * Decimal(100.0), 2)) + '%') \
100
        if report['end_integrity_rate'] is not None else None
101
    ws['A8'].alignment = b_r_alignment
102
    ws['A8'] = _('Full Integrity Rate') + ':'
103
    ws['B8'] = (str(round2(report['full_integrity_rate'] * Decimal(100.0), 2)) + '%') \
104
        if report['full_integrity_rate'] is not None else None
105
    ws['A9'].alignment = b_r_alignment
106
    ws['A9'] = _('Energy Category') + ':'
107
    ws['B9'] = energy_category_name if energy_category_name is not None else _('All')
108
109
    # Title
110
    title_font = Font(size=12, bold=True)
111
    ws['A10'].font = title_font
112
    ws['A10'] = _('ID')
113
    ws['B10'].font = title_font
114
    ws['B10'] = _('Name')
115
    ws['C10'].font = title_font
116
    ws['C10'] = _('Space')
117
    ws['D10'].font = title_font
118
    ws['D10'] = _('Cost Center')
119
    ws['E10'].font = title_font
120
    ws['E10'] = _('Energy Category')
121
    ws['F10'].font = title_font
122
    ws['F10'] = _('Description')
123
    ws['G10'].font = title_font
124
    ws['G10'] = _('Start Value')
125
    ws['H10'].font = title_font
126
    ws['H10'] = _('End Value')
127
    ws['I10'].font = title_font
128
    ws['I10'] = _('Difference Value')
129
130
    current_row_number = 11
131
    for i in range(0, len(report['meters'])):
132
        ws['A' + str(current_row_number)] = report['meters'][i]['id']
133
        ws['B' + str(current_row_number)] = report['meters'][i]['meter_name']
134
        ws['C' + str(current_row_number)] = report['meters'][i]['space_name']
135
        ws['D' + str(current_row_number)] = report['meters'][i]['cost_center_name']
136
        ws['E' + str(current_row_number)] = report['meters'][i]['energy_category_name']
137
        ws['F' + str(current_row_number)] = report['meters'][i]['description']
138
        ws['G' + str(current_row_number)] = report['meters'][i]['start_value']
139
        ws['H' + str(current_row_number)] = report['meters'][i]['end_value']
140
        ws['I' + str(current_row_number)] = report['meters'][i]['difference_value']
141
        current_row_number += 1
142
143
    filename = str(uuid.uuid4()) + '.xlsx'
144
    wb.save(filename)
145
146
    return filename
147