Passed
Push — master ( 5b2513...456fb9 )
by Guangyu
02:12 queued 11s
created

excelexporters.virtualmetercost   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 346
Duplicated Lines 93.06 %

Importance

Changes 0
Metric Value
eloc 248
dl 322
loc 346
rs 9.84
c 0
b 0
f 0
wmc 32

2 Functions

Rating   Name   Duplication   Size   Complexity  
F generate_excel() 285 285 24
B export() 37 37 8

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.chart import (
5
    BarChart,
6
    Reference,
7
    Series
8
)
9
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
10
from openpyxl.drawing.image import Image
11
from openpyxl import Workbook
12
from openpyxl.chart.label import DataLabelList
13
14
15
####################################################################################################################
16
# PROCEDURES
17
# Step 1: Validate the report data
18
# Step 2: Generate excelexporters file
19
# Step 3: Encode the excelexporters file to Base64
20
####################################################################################################################
21
22 View Code Duplication
def export(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
23
    ####################################################################################################################
24
    # Step 1: Validate the report data
25
    ####################################################################################################################
26
    if report is None:
27
        return None
28
29
    if "reporting_period" not in report.keys() or \
30
            "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
31
        return None
32
    ####################################################################################################################
33
    # Step 2: Generate excel file from the report data
34
    ####################################################################################################################
35
    filename = generate_excel(report,
36
                              name,
37
                              reporting_start_datetime_local,
38
                              reporting_end_datetime_local,
39
                              period_type)
40
    ####################################################################################################################
41
    # Step 3: Encode the excel file to Base64
42
    ####################################################################################################################
43
    try:
44
        with open(filename, 'rb') as binary_file:
45
            binary_file_data = binary_file.read()
46
    except IOError as ex:
47
        pass
48
49
    # Base64 encode the bytes
50
    base64_encoded_data = base64.b64encode(binary_file_data)
0 ignored issues
show
introduced by
The variable binary_file_data does not seem to be defined for all execution paths.
Loading history...
51
    # get the Base64 encoded data using human-readable characters.
52
    base64_message = base64_encoded_data.decode('utf-8')
53
    # delete the file from server
54
    try:
55
        os.remove(filename)
56
    except NotImplementedError as ex:
57
        pass
58
    return base64_message
59
60
61 View Code Duplication
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
62
63
    wb = Workbook()
64
65
    # todo
66
    ws = wb.active
67
68
    # Row height
69
    ws.row_dimensions[1].height = 118
70
    for i in range(2, 11 + 1):
71
        ws.row_dimensions[i].height = 30
72
73
    for i in range(12, 43 + 1):
74
        ws.row_dimensions[i].height = 30
75
76
    # Col width
77
    ws.column_dimensions['A'].width = 1.5
78
79
    for i in range(ord('B'), ord('I')):
80
        ws.column_dimensions[chr(i)].width = 15.0
81
82
    # Font
83
    name_font = Font(name='Constantia', size=15, bold=True)
84
    title_font = Font(name='宋体', size=15, bold=True)
85
    data_font = Font(name='Franklin Gothic Book', size=11)
86
87
    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
88
    f_border = Border(left=Side(border_style='medium', color='00000000'),
89
                      right=Side(border_style='medium', color='00000000'),
90
                      bottom=Side(border_style='medium', color='00000000'),
91
                      top=Side(border_style='medium', color='00000000')
92
                      )
93
    b_border = Border(
94
        bottom=Side(border_style='medium', color='00000000'),
95
    )
96
97
    b_c_alignment = Alignment(vertical='bottom',
98
                              horizontal='center',
99
                              text_rotation=0,
100
                              wrap_text=False,
101
                              shrink_to_fit=False,
102
                              indent=0)
103
    c_c_alignment = Alignment(vertical='center',
104
                              horizontal='center',
105
                              text_rotation=0,
106
                              wrap_text=False,
107
                              shrink_to_fit=False,
108
                              indent=0)
109
    b_r_alignment = Alignment(vertical='bottom',
110
                              horizontal='right',
111
                              text_rotation=0,
112
                              wrap_text=False,
113
                              shrink_to_fit=False,
114
                              indent=0)
115
    c_r_alignment = Alignment(vertical='bottom',
116
                              horizontal='center',
117
                              text_rotation=0,
118
                              wrap_text=False,
119
                              shrink_to_fit=False,
120
                              indent=0)
121
122
    # Img
123
    img = Image("excelexporters/myems.png")
124
    ws.add_image(img, 'B1')
125
126
    # Title
127
    ws['B3'].font = name_font
128
    ws['B3'].alignment = b_r_alignment
129
    ws['B3'] = 'Name:'
130
    ws['C3'].border = b_border
131
    ws['C3'].alignment = b_c_alignment
132
    ws['C3'].font = name_font
133
    ws['C3'] = name
134
135
    ws['D3'].font = name_font
136
    ws['D3'].alignment = b_r_alignment
137
    ws['D3'] = 'Period:'
138
    ws['E3'].border = b_border
139
    ws['E3'].alignment = b_c_alignment
140
    ws['E3'].font = name_font
141
    ws['E3'] = period_type
142
143
    ws['F3'].font = name_font
144
    ws['F3'].alignment = b_r_alignment
145
    ws['F3'] = 'Date:'
146
    ws.merge_cells("G3:H3")
147
    ws['G3'].border = b_border
148
    ws['G3'].alignment = b_c_alignment
149
    ws['G3'].font = name_font
150
    ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
151
152
    if "reporting_period" not in report.keys() or \
153
            "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
154
        filename = str(uuid.uuid4()) + '.xlsx'
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable str does not seem to be defined.
Loading history...
155
        wb.save(filename)
156
157
        return filename
158
159
    ###############################
160
161
    has_cost_data_flag = True
162
163
    if "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
164
        has_cost_data_flag = False
165
166
    if has_cost_data_flag:
167
        ws['B6'].font = title_font
168
        ws['B6'] = name + '报告期成本'
169
170
        reporting_period_data = report['reporting_period']
171
        category = report['virtual_meter']['energy_category_name']
172
        ca_len = len(category)
173
174
        ws['B7'].fill = table_fill
175
176
        ws['B8'].font = title_font
177
        ws['B8'].alignment = c_c_alignment
178
        ws['B8'] = '成本'
179
        ws['B8'].border = f_border
180
181
        ws['B9'].font = title_font
182
        ws['B9'].alignment = c_c_alignment
183
        ws['B9'] = '环比'
184
        ws['B9'].border = f_border
185
186
        col = 'B'
187
188
        for i in range(0, ca_len):
189
            col = chr(ord('C') + i)
190
191
            ws[col + '7'].fill = table_fill
192
            ws[col + '7'].font = name_font
193
            ws[col + '7'].alignment = c_c_alignment
194
            ws[col + '7'] = report['virtual_meter']['energy_category_name'] + \
195
                " (" + report['virtual_meter']['unit_of_measure'] + ")"
196
            ws[col + '7'].border = f_border
197
198
            ws[col + '8'].font = name_font
199
            ws[col + '8'].alignment = c_c_alignment
200
            ws[col + '8'] = round(reporting_period_data['total_in_category'], 0)
201
            ws[col + '8'].border = f_border
202
203
            ws[col + '9'].font = name_font
204
            ws[col + '9'].alignment = c_c_alignment
205
            ws[col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
206
                if reporting_period_data['increment_rate'] is not None else "-"
207
            ws[col + '9'].border = f_border
208
209
        # TCE TCO2E
210
        end_col = col
211
        # TCE
212
        tce_col = chr(ord(end_col) + 1)
213
        ws[tce_col + '7'].fill = table_fill
214
        ws[tce_col + '7'].font = name_font
215
        ws[tce_col + '7'].alignment = c_c_alignment
216
        ws[tce_col + '7'] = "TCE"
217
        ws[tce_col + '7'].border = f_border
218
219
        ws[tce_col + '8'].font = name_font
220
        ws[tce_col + '8'].alignment = c_c_alignment
221
        ws[tce_col + '8'] = round(reporting_period_data['total_in_kgce'], 0)
222
        ws[tce_col + '8'].border = f_border
223
224
        ws[tce_col + '9'].font = name_font
225
        ws[tce_col + '9'].alignment = c_c_alignment
226
        ws[tce_col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
227
            if reporting_period_data['increment_rate'] is not None else "-"
228
        ws[tce_col + '9'].border = f_border
229
230
        # TCO2E
231
        tco2e_col = chr(ord(end_col) + 2)
232
        ws[tco2e_col + '7'].fill = table_fill
233
        ws[tco2e_col + '7'].font = name_font
234
        ws[tco2e_col + '7'].alignment = c_c_alignment
235
        ws[tco2e_col + '7'] = "TCO2E"
236
        ws[tco2e_col + '7'].border = f_border
237
238
        ws[tco2e_col + '8'].font = name_font
239
        ws[tco2e_col + '8'].alignment = c_c_alignment
240
        ws[tco2e_col + '8'] = round(reporting_period_data['total_in_kgco2e'], 0)
241
        ws[tco2e_col + '8'].border = f_border
242
243
        ws[tco2e_col + '9'].font = name_font
244
        ws[tco2e_col + '9'].alignment = c_c_alignment
245
        ws[tco2e_col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
246
            if reporting_period_data['increment_rate'] is not None else "-"
247
        ws[tco2e_col + '9'].border = f_border
248
249
    else:
250
        for i in range(6, 9 + 1):
251
            ws.rows_dimensions[i].height = 0.1
252
253
    ######################################
254
255
    has_cost_detail_flag = True
256
    reporting_period_data = report['reporting_period']
257
    category = report['virtual_meter']['energy_category_name']
258
    ca_len = len(category)
259
    times = reporting_period_data['timestamps']
260
261
    if "values" not in reporting_period_data.keys() or len(reporting_period_data['values']) == 0:
262
        has_cost_detail_flag = False
263
264
    if has_cost_detail_flag:
265
        ws['B11'].font = title_font
266
        ws['B11'] = name + '详细数据'
267
268
        ws['B18'].fill = table_fill
269
        ws['B18'].font = title_font
270
        ws['B18'].border = f_border
271
        ws['B18'].alignment = c_c_alignment
272
        ws['B18'] = '日期时间'
273
        time = times
274
        has_data = False
275
        max_row = 0
276
        if len(time) > 0:
277
            has_data = True
278
            max_row = 18 + len(time)
279
280
        if has_data:
281
282
            end_data_flag = 19
283
284
            for i in range(0, len(time)):
285
                col = 'B'
286
                end_data_flag = 19 + i
287
                row = str(end_data_flag)
288
289
                ws[col + row].font = title_font
290
                ws[col + row].alignment = c_c_alignment
291
                ws[col + row] = time[i]
292
                ws[col + row].border = f_border
293
294
            ws['B' + str(end_data_flag + 1)].font = title_font
295
            ws['B' + str(end_data_flag + 1)].alignment = c_c_alignment
296
            ws['B' + str(end_data_flag + 1)] = '总计'
297
            ws['B' + str(end_data_flag + 1)].border = f_border
298
299
            bar = BarChart()
300
301
            for i in range(0, ca_len):
302
303
                col = chr(ord('C') + i)
304
305
                ws[col + '18'].fill = table_fill
306
                ws[col + '18'].font = title_font
307
                ws[col + '18'].alignment = c_c_alignment
308
                ws[col + '18'] = report['virtual_meter']['energy_category_name'] + \
309
                    " (" + report['virtual_meter']['unit_of_measure'] + ")"
310
                ws[col + '18'].border = f_border
311
312
                time = times
313
                time_len = len(time)
314
315
                for j in range(0, time_len):
316
                    row = str(19 + j)
317
318
                    ws[col + row].font = title_font
319
                    ws[col + row].alignment = c_c_alignment
320
                    ws[col + row] = round(reporting_period_data['values'][j], 0)
321
                    ws[col + row].border = f_border
322
323
                ws[col + str(end_data_flag + 1)].font = title_font
324
                ws[col + str(end_data_flag + 1)].alignment = c_c_alignment
325
                ws[col + str(end_data_flag + 1)] = round(reporting_period_data['total_in_category'], 0)
326
                ws[col + str(end_data_flag + 1)].border = f_border
327
328
                bar_data = Reference(ws, min_col=3 + i, min_row=18, max_row=max_row)
329
                bar.series.append(Series(bar_data, title_from_data=True))
330
331
            labels = Reference(ws, min_col=2, min_row=19, max_row=max_row)
332
            bar.set_categories(labels)
333
            bar.dLbls = DataLabelList()
334
            bar.dLbls.showVal = True
335
            bar.height = 5.25
336
            bar.width = len(time)
337
            ws.add_chart(bar, "B12")
338
    else:
339
        for i in range(11, 43 + 1):
340
            ws.row_dimensions[i].height = 0.0
341
342
    filename = str(uuid.uuid4()) + '.xlsx'
343
    wb.save(filename)
344
345
    return filename
346