Passed
Push — master ( 7266b4...2706fb )
by Guangyu
09:48 queued 13s
created

excelexporters.storebatch   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 207
Duplicated Lines 16.91 %

Importance

Changes 0
Metric Value
wmc 15
eloc 146
dl 35
loc 207
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
B export() 35 35 5
D generate_excel() 0 153 10

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
import base64
2
import uuid
3
import os
4
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
5
from openpyxl.drawing.image import Image
6
from openpyxl import Workbook
7
import gettext
8
9
10
########################################################################################################################
11
# PROCEDURES
12
# Step 1: Validate the report data
13
# Step 2: Generate excel file from the report data
14
# Step 3: Encode the excel file to Base64
15
########################################################################################################################
16
17 View Code Duplication
def export(result, space_name, reporting_start_datetime_local, reporting_end_datetime_local, language):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
18
    ####################################################################################################################
19
    # Step 1: Validate the report data
20
    ####################################################################################################################
21
    if result is None:
22
        return None
23
24
    ####################################################################################################################
25
    # Step 2: Generate excel file from the report data
26
    ####################################################################################################################
27
    filename = generate_excel(result,
28
                              space_name,
29
                              reporting_start_datetime_local,
30
                              reporting_end_datetime_local,
31
                              language)
32
    ####################################################################################################################
33
    # Step 3: Encode the excel file to Base64
34
    ####################################################################################################################
35
    binary_file_data = b''
36
    try:
37
        with open(filename, 'rb') as binary_file:
38
            binary_file_data = binary_file.read()
39
    except IOError as ex:
40
        pass
41
42
    # Base64 encode the bytes
43
    base64_encoded_data = base64.b64encode(binary_file_data)
44
    # get the Base64 encoded data using human-readable characters.
45
    base64_message = base64_encoded_data.decode('utf-8')
46
    # delete the file from server
47
    try:
48
        os.remove(filename)
49
    except NotImplementedError as ex:
50
        pass
51
    return base64_message
52
53
54
def generate_excel(report, space_name, reporting_start_datetime_local, reporting_end_datetime_local, language):
55
56
57
    locale_path = './i18n/'
58
    if language == 'zh_CN':
59
        trans = gettext.translation('myems', locale_path, languages=['zh_CN'])
60
    elif language == 'de':
61
        trans = gettext.translation('myems', locale_path, languages=['de'])
62
    elif language == 'en':
63
        trans = gettext.translation('myems', locale_path, languages=['en'])
64
    else:
65
        trans = gettext.translation('myems', locale_path, languages=['en'])
66
    trans.install()
67
    _ = trans.gettext
68
69
    wb = Workbook()
70
    ws = wb.active
71
    ws.title = "StoreBatch"
72
73
    # Row height
74
    ws.row_dimensions[1].height = 102
75
    for i in range(2, 5 + 1):
76
        ws.row_dimensions[i].height = 42
77
78
    for i in range(6, len(report['stores']) + 15):
79
        ws.row_dimensions[i].height = 60
80
81
    # Col width
82
    ws.column_dimensions['A'].width = 1.5
83
84
    ws.column_dimensions['B'].width = 25.0
85
86
    for i in range(ord('C'), ord('L')):
87
        ws.column_dimensions[chr(i)].width = 15.0
88
89
    # Font
90
    name_font = Font(name='Arial', size=15, bold=True)
91
    title_font = Font(name='Arial', size=15, bold=True)
92
    data_font = Font(name='Franklin Gothic Book', size=11)
93
94
    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
95
    f_border = Border(left=Side(border_style='medium', color='00000000'),
96
                      right=Side(border_style='medium', color='00000000'),
97
                      bottom=Side(border_style='medium', color='00000000'),
98
                      top=Side(border_style='medium', color='00000000')
99
                      )
100
    b_border = Border(
101
        bottom=Side(border_style='medium', color='00000000'),
102
    )
103
104
    b_c_alignment = Alignment(vertical='bottom',
105
                              horizontal='center',
106
                              text_rotation=0,
107
                              wrap_text=True,
108
                              shrink_to_fit=False,
109
                              indent=0)
110
    c_c_alignment = Alignment(vertical='center',
111
                              horizontal='center',
112
                              text_rotation=0,
113
                              wrap_text=True,
114
                              shrink_to_fit=False,
115
                              indent=0)
116
    b_r_alignment = Alignment(vertical='bottom',
117
                              horizontal='right',
118
                              text_rotation=0,
119
                              wrap_text=True,
120
                              shrink_to_fit=False,
121
                              indent=0)
122
123
    # Img
124
    img = Image("excelexporters/myems.png")
125
    ws.add_image(img, 'A1')
126
127
    # Title
128
    ws['B3'].alignment = b_r_alignment
129
    ws['B3'] = _('Space') + ':'
130
    ws['C3'].border = b_border
131
    ws['C3'].alignment = b_c_alignment
132
    ws['C3'] = space_name
133
134
    ws['B4'].alignment = b_r_alignment
135
    ws['B4'] = _('Reporting Start Datetime') + ':'
136
    ws['C4'].border = b_border
137
    ws['C4'].alignment = b_c_alignment
138
    ws['C4'] = reporting_start_datetime_local
139
140
    ws['B5'].alignment = b_r_alignment
141
    ws['B5'] = _('Reporting End Datetime') + ':'
142
    ws['C5'].border = b_border
143
    ws['C5'].alignment = b_c_alignment
144
    ws['C5'] = reporting_end_datetime_local
145
146
    # Title
147
    ws['B6'].border = f_border
148
    ws['B6'].font = name_font
149
    ws['B6'].alignment = c_c_alignment
150
    ws['B6'].fill = table_fill
151
    ws['B6'] = _('ID')
152
153
    ws['C6'].border = f_border
154
    ws['C6'].font = name_font
155
    ws['C6'].alignment = c_c_alignment
156
    ws['C6'].fill = table_fill
157
    ws['C6'] = _('Name')
158
159
    ws['D6'].border = f_border
160
    ws['D6'].alignment = c_c_alignment
161
    ws['D6'].font = name_font
162
    ws['D6'].fill = table_fill
163
    ws['D6'] = _('Space')
164
165
    ca_len = len(report['energycategories'])
166
167
    for i in range(0, ca_len):
168
        col = chr(ord('E') + i)
169
        ws[col + '6'].fill = table_fill
170
        ws[col + '6'].font = name_font
171
        ws[col + '6'].alignment = c_c_alignment
172
        ws[col + '6'] = report['energycategories'][i]['name'] + \
173
            " (" + report['energycategories'][i]['unit_of_measure'] + ")"
174
        ws[col + '6'].border = f_border
175
176
    current_row_number = 7
177
    for i in range(0, len(report['stores'])):
178
        ws['B' + str(current_row_number)].font = title_font
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable str does not seem to be defined.
Loading history...
179
        ws['B' + str(current_row_number)].border = f_border
180
        ws['B' + str(current_row_number)].alignment = c_c_alignment
181
        ws['B' + str(current_row_number)] = report['stores'][i]['id']
182
183
        ws['C' + str(current_row_number)].font = title_font
184
        ws['C' + str(current_row_number)].border = f_border
185
        ws['C' + str(current_row_number)].alignment = c_c_alignment
186
        ws['C' + str(current_row_number)] = report['stores'][i]['store_name']
187
188
        ws['D' + str(current_row_number)].font = title_font
189
        ws['D' + str(current_row_number)].border = f_border
190
        ws['D' + str(current_row_number)].alignment = c_c_alignment
191
        ws['D' + str(current_row_number)] = report['stores'][i]['space_name']
192
193
        ca_len = len(report['stores'][i]['values'])
194
        for j in range(0, ca_len):
195
            col = chr(ord('E') + j)
196
            ws[col + str(current_row_number)].font = data_font
197
            ws[col + str(current_row_number)].border = f_border
198
            ws[col + str(current_row_number)].alignment = c_c_alignment
199
            ws[col + str(current_row_number)] = round(report['stores'][i]['values'][j], 2)
200
201
        current_row_number += 1
202
203
    filename = str(uuid.uuid4()) + '.xlsx'
204
    wb.save(filename)
205
206
    return filename
207