Passed
Push — master ( 7483d8...3b73d1 )
by Guangyu
02:33 queued 12s
created

excelexporters.tenantcost   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 559
Duplicated Lines 37.92 %

Importance

Changes 0
Metric Value
eloc 409
dl 212
loc 559
rs 9.0399
c 0
b 0
f 0
wmc 42

2 Functions

Rating   Name   Duplication   Size   Complexity  
B export() 0 39 5
F generate_excel() 212 495 37

How to fix   Duplicated Code    Complexity   

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:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like excelexporters.tenantcost often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import base64
2
import uuid
3
import os
4
from openpyxl.chart import (
5
        PieChart,
6
        LineChart,
7
        BarChart,
8
        Reference,
9
    )
10
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
11
from openpyxl.drawing.image import Image
12
from openpyxl import Workbook
13
from openpyxl.chart.label import DataLabelList
14
15
####################################################################################################################
16
# PROCEDURES
17
# Step 1: Validate the report data
18
# Step 2: Generate excel file
19
# Step 3: Encode the excel file bytes to Base64
20
####################################################################################################################
21
22
23
def export(report,
24
           name,
25
           reporting_start_datetime_local,
26
           reporting_end_datetime_local,
27
           period_type):
28
    ####################################################################################################################
29
    # Step 1: Validate the report data
30
    ####################################################################################################################
31
    if report is None:
32
        return None
33
    print(report)
34
35
    ####################################################################################################################
36
    # Step 2: Generate excel file from the report data
37
    ####################################################################################################################
38
    filename = generate_excel(report,
39
                              name,
40
                              reporting_start_datetime_local,
41
                              reporting_end_datetime_local,
42
                              period_type)
43
    ####################################################################################################################
44
    # Step 3: Encode the excel file to Base64
45
    ####################################################################################################################
46
    try:
47
        with open(filename, 'rb') as binary_file:
48
            binary_file_data = binary_file.read()
49
    except IOError as ex:
50
        pass
51
52
    # Base64 encode the bytes
53
    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...
54
    # get the Base64 encoded data using human-readable characters.
55
    base64_message = base64_encoded_data.decode('utf-8')
56
    # delete the file from server
57
    try:
58
        os.remove(filename)
59
    except NotImplementedError as ex:
60
        pass
61
    return base64_message
62
63
64
def generate_excel(report,
65
                   name,
66
                   reporting_start_datetime_local,
67
                   reporting_end_datetime_local,
68
                   period_type):
69
70
    wb = Workbook()
71
    ws = wb.active
72
73
    # Row height
74
    ws.row_dimensions[1].height = 102
75
    for i in range(2, 2000 + 1):
76
        ws.row_dimensions[i].height = 42
77
78
    # for i in range(2, 37 + 1):
79
    #     ws.row_dimensions[i].height = 30
80
    #
81
    # for i in range(38, 90 + 1):
82
    #     ws.row_dimensions[i].height = 30
83
84
    # Col width
85
    ws.column_dimensions['A'].width = 1.5
86
87
    ws.column_dimensions['B'].width = 25.0
88
89
    for i in range(ord('C'), ord('L')):
90
        ws.column_dimensions[chr(i)].width = 15.0
91
92
    # Font
93
    name_font = Font(name='Constantia', size=15, bold=True)
94
    title_font = Font(name='宋体', size=15, bold=True)
95
    data_font = Font(name='Franklin Gothic Book', size=11)
96
97
    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
98
    f_border = Border(left=Side(border_style='medium', color='00000000'),
99
                      right=Side(border_style='medium', color='00000000'),
100
                      bottom=Side(border_style='medium', color='00000000'),
101
                      top=Side(border_style='medium', color='00000000')
102
                      )
103
    b_border = Border(
104
        bottom=Side(border_style='medium', color='00000000'),
105
    )
106
107
    b_c_alignment = Alignment(vertical='bottom',
108
                              horizontal='center',
109
                              text_rotation=0,
110
                              wrap_text=True,
111
                              shrink_to_fit=False,
112
                              indent=0)
113
    c_c_alignment = Alignment(vertical='center',
114
                              horizontal='center',
115
                              text_rotation=0,
116
                              wrap_text=True,
117
                              shrink_to_fit=False,
118
                              indent=0)
119
    b_r_alignment = Alignment(vertical='bottom',
120
                              horizontal='right',
121
                              text_rotation=0,
122
                              wrap_text=True,
123
                              shrink_to_fit=False,
124
                              indent=0)
125
    c_r_alignment = Alignment(vertical='bottom',
126
                              horizontal='center',
127
                              text_rotation=0,
128
                              wrap_text=True,
129
                              shrink_to_fit=False,
130
                              indent=0)
131
132
    # Img
133
    img = Image("excelexporters/myems.png")
134
    img.width = img.width * 0.85
135
    img.height = img.height * 0.85
136
    # img = Image("myems.png")
137
    ws.add_image(img, 'B1')
138
139
    # Title
140
    ws.row_dimensions[3].height = 60
141
142
    ws['B3'].font = name_font
143
    ws['B3'].alignment = b_r_alignment
144
    ws['B3'] = 'Name:'
145
    ws['C3'].border = b_border
146
    ws['C3'].alignment = b_c_alignment
147
    ws['C3'].font = name_font
148
    ws['C3'] = name
149
150
    ws['D3'].font = name_font
151
    ws['D3'].alignment = b_r_alignment
152
    ws['D3'] = 'Period:'
153
    ws['E3'].border = b_border
154
    ws['E3'].alignment = b_c_alignment
155
    ws['E3'].font = name_font
156
    ws['E3'] = period_type
157
158
    ws['F3'].font = name_font
159
    ws['F3'].alignment = b_r_alignment
160
    ws['F3'] = 'Date:'
161
    ws['G3'].alignment = b_c_alignment
162
    ws['G3'].font = name_font
163
    ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
164
    ws.merge_cells("G3:H3")
165
166
    if "reporting_period" not in report.keys() or \
167
            "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0:
168
        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...
169
        wb.save(filename)
170
171
        return filename
172
173
    #################################################
174
175
    reporting_period_data = report['reporting_period']
176
177
    has_energy_data_flag = True
178
    if "names" not in reporting_period_data.keys() or \
179
            reporting_period_data['names'] is None or \
180
            len(reporting_period_data['names']) == 0:
181
        has_energy_data_flag = False
182
183 View Code Duplication
    if has_energy_data_flag:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
184
        ws['B6'].font = title_font
185
        ws['B6'] = name+' 报告期成本'
186
187
        category = reporting_period_data['names']
188
        ca_len = len(category)
189
190
        ws.row_dimensions[7].height = 60
191
        ws['B7'].fill = table_fill
192
        ws['B7'].border = f_border
193
194
        ws['B8'].font = title_font
195
        ws['B8'].alignment = c_c_alignment
196
        ws['B8'] = '成本'
197
        ws['B8'].border = f_border
198
199
        ws['B9'].font = title_font
200
        ws['B9'].alignment = c_c_alignment
201
        ws['B9'] = '单位面积能耗'
202
        ws['B9'].border = f_border
203
204
        ws['B10'].font = title_font
205
        ws['B10'].alignment = c_c_alignment
206
        ws['B10'] = '环比'
207
        ws['B10'].border = f_border
208
209
        col = 'B'
210
211
        for i in range(0, ca_len):
212
            col = chr(ord('C') + i)
213
            ws[col + '7'].fill = table_fill
214
            ws[col + '7'].font = name_font
215
            ws[col + '7'].alignment = c_c_alignment
216
            ws[col + '7'] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
217
            ws[col + '7'].border = f_border
218
219
            ws[col + '8'].font = name_font
220
            ws[col + '8'].alignment = c_c_alignment
221
            ws[col + '8'] = round(reporting_period_data['subtotals'][i], 2)
222
            ws[col + '8'].border = f_border
223
224
            ws[col + '9'].font = name_font
225
            ws[col + '9'].alignment = c_c_alignment
226
            ws[col + '9'] = round(reporting_period_data['subtotals_per_unit_area'][i], 2)
227
            ws[col + '9'].border = f_border
228
229
            ws[col + '10'].font = name_font
230
            ws[col + '10'].alignment = c_c_alignment
231
            ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \
232
                if reporting_period_data['increment_rates'][i] is not None else "-"
233
            ws[col + '10'].border = f_border
234
235
        end_col = chr(ord(col)+1)
236
        ws[end_col + '7'].fill = table_fill
237
        ws[end_col + '7'].font = name_font
238
        ws[end_col + '7'].alignment = c_c_alignment
239
        ws[end_col + '7'] = "总计 (" + reporting_period_data['total_unit'] + ")"
240
        ws[end_col + '7'].border = f_border
241
242
        ws[end_col + '8'].font = name_font
243
        ws[end_col + '8'].alignment = c_c_alignment
244
        ws[end_col + '8'] = round(reporting_period_data['total'], 2)
245
        ws[end_col + '8'].border = f_border
246
247
        ws[end_col + '9'].font = name_font
248
        ws[end_col + '9'].alignment = c_c_alignment
249
        ws[end_col + '9'] = round(reporting_period_data['total_per_unit_area'], 2)
250
        ws[end_col + '9'].border = f_border
251
252
        ws[end_col + '10'].font = name_font
253
        ws[end_col + '10'].alignment = c_c_alignment
254
        ws[end_col + '10'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \
255
            if reporting_period_data['total_increment_rate'] is not None else "-"
256
        ws[end_col + '10'].border = f_border
257
258
    else:
259
        for i in range(6, 10 + 1):
260
            ws.row_dimensions[i].height = 0.1
261
262
    #################################################
263
264
    has_ele_peak_flag = True
265
    if "toppeaks" not in reporting_period_data.keys() or \
266
            reporting_period_data['toppeaks'] is None or \
267
            len(reporting_period_data['toppeaks']) == 0:
268
        has_ele_peak_flag = False
269
270 View Code Duplication
    if has_ele_peak_flag:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
271
        ws['B12'].font = title_font
272
        ws['B12'] = name+' 分时电耗'
273
274
        ws['B13'].fill = table_fill
275
        ws['B13'].font = name_font
276
        ws['B13'].alignment = c_c_alignment
277
        ws['B13'].border = f_border
278
279
        ws['C13'].fill = table_fill
280
        ws['C13'].font = name_font
281
        ws['C13'].alignment = c_c_alignment
282
        ws['C13'].border = f_border
283
        ws['C13'] = '分时电耗'
284
285
        ws['B14'].font = title_font
286
        ws['B14'].alignment = c_c_alignment
287
        ws['B14'] = '尖'
288
        ws['B14'].border = f_border
289
290
        ws['C14'].font = title_font
291
        ws['C14'].alignment = c_c_alignment
292
        ws['C14'].border = f_border
293
        ws['C14'] = round(reporting_period_data['toppeaks'][0], 2)
294
295
        ws['B15'].font = title_font
296
        ws['B15'].alignment = c_c_alignment
297
        ws['B15'] = '峰'
298
        ws['B15'].border = f_border
299
300
        ws['C15'].font = title_font
301
        ws['C15'].alignment = c_c_alignment
302
        ws['C15'].border = f_border
303
        ws['C15'] = round(reporting_period_data['onpeaks'][0], 2)
304
305
        ws['B16'].font = title_font
306
        ws['B16'].alignment = c_c_alignment
307
        ws['B16'] = '平'
308
        ws['B16'].border = f_border
309
310
        ws['C16'].font = title_font
311
        ws['C16'].alignment = c_c_alignment
312
        ws['C16'].border = f_border
313
        ws['C16'] = round(reporting_period_data['midpeaks'][0], 2)
314
315
        ws['B17'].font = title_font
316
        ws['B17'].alignment = c_c_alignment
317
        ws['B17'] = '谷'
318
        ws['B17'].border = f_border
319
320
        ws['C17'].font = title_font
321
        ws['C17'].alignment = c_c_alignment
322
        ws['C17'].border = f_border
323
        ws['C17'] = round(reporting_period_data['offpeaks'][0], 2)
324
325
        pie = PieChart()
326
        pie.title = name+' 分时电耗'
327
        labels = Reference(ws, min_col=2, min_row=14, max_row=17)
328
        pie_data = Reference(ws, min_col=3, min_row=13, max_row=17)
329
        pie.add_data(pie_data, titles_from_data=True)
330
        pie.set_categories(labels)
331
        pie.height = 6.6
332
        pie.width = 9
333
        s1 = pie.series[0]
334
        s1.dLbls = DataLabelList()
335
        s1.dLbls.showCatName = False
336
        s1.dLbls.showVal = True
337
        s1.dLbls.showPercent = True
338
        ws.add_chart(pie, "D13")
339
340
    else:
341
        for i in range(12, 18 + 1):
342
            ws.row_dimensions[i].height = 0.1
343
344
    ################################################
345
346
    current_row_number = 19
347
348
    has_subtotals_data_flag = True
349
    if "subtotals" not in reporting_period_data.keys() or \
350
            reporting_period_data['subtotals'] is None or \
351
            len(reporting_period_data['subtotals']) == 0:
352
        has_subtotals_data_flag = False
353
354 View Code Duplication
    if has_subtotals_data_flag:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
355
        ws['B' + str(current_row_number)].font = title_font
356
        ws['B' + str(current_row_number)] = name + ' 成本占比'
357
358
        current_row_number += 1
359
360
        table_start_row_number = current_row_number
361
362
        ws['B' + str(current_row_number)].fill = table_fill
363
        ws['B' + str(current_row_number)].font = name_font
364
        ws['B' + str(current_row_number)].alignment = c_c_alignment
365
        ws['B' + str(current_row_number)].border = f_border
366
367
        ws['C' + str(current_row_number)].fill = table_fill
368
        ws['C' + str(current_row_number)].font = name_font
369
        ws['C' + str(current_row_number)].alignment = c_c_alignment
370
        ws['C' + str(current_row_number)].border = f_border
371
        ws['C' + str(current_row_number)] = '成本占比'
372
373
        current_row_number += 1
374
375
        ca_len = len(reporting_period_data['names'])
376
377
        for i in range(0, ca_len):
378
            ws['B' + str(current_row_number)].font = title_font
379
            ws['B' + str(current_row_number)].alignment = c_c_alignment
380
            ws['B' + str(current_row_number)] = reporting_period_data['names'][i]
381
            ws['B' + str(current_row_number)].border = f_border
382
383
            ws['C' + str(current_row_number)].font = title_font
384
            ws['C' + str(current_row_number)].alignment = c_c_alignment
385
            ws['C' + str(current_row_number)].border = f_border
386
            ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
387
388
            current_row_number += 1
389
390
        table_end_row_number = current_row_number - 1
391
392
        pie = PieChart()
393
        pie.title = name + ' 成本占比'
394
        labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
395
        pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number)
396
        pie.add_data(pie_data, titles_from_data=True)
397
        pie.set_categories(labels)
398
        pie.height = 6.6
399
        pie.width = 9
400
        s1 = pie.series[0]
401
        s1.dLbls = DataLabelList()
402
        s1.dLbls.showCatName = False
403
        s1.dLbls.showVal = True
404
        s1.dLbls.showPercent = True
405
        table_cell = 'D' + str(table_start_row_number)
406
        ws.add_chart(pie, table_cell)
407
408
        if ca_len < 4:
409
            current_row_number = current_row_number - ca_len + 4
410
411
    else:
412
        for i in range(21, 29 + 1):
413
            current_row_number = 30
414
            ws.row_dimensions[i].height = 0.1
415
416
    ###############################################
417
418
    current_row_number += 1
419
420
    has_detail_data_flag = True
421
422
    table_start_draw_flag = current_row_number + 1
423
424
    if "timestamps" not in reporting_period_data.keys() or \
425
            reporting_period_data['timestamps'] is None or \
426
            len(reporting_period_data['timestamps']) == 0:
427
        has_detail_data_flag = False
428
429
    if has_detail_data_flag:
430
        reporting_period_data = report['reporting_period']
431
        times = reporting_period_data['timestamps']
432
        ca_len = len(report['reporting_period']['names'])
433
434
        ws['B' + str(current_row_number)].font = title_font
435
        ws['B' + str(current_row_number)] = name+' 详细数据'
436
437
        table_start_row_number = (current_row_number + 1) + ca_len * 6
438
        current_row_number = table_start_row_number
439
440
        time = times[0]
441
        has_data = False
442
443
        if len(time) > 0:
444
            has_data = True
445
446
        if has_data:
447
448
            ws.row_dimensions[current_row_number].height = 60
449
            ws['B' + str(current_row_number)].fill = table_fill
450
            ws['B' + str(current_row_number)].border = f_border
451
            ws['B' + str(current_row_number)].font = title_font
452
            ws['B' + str(current_row_number)].alignment = c_c_alignment
453
            ws['B' + str(current_row_number)] = '日期时间'
454
455
            col = 'B'
456
457
            for i in range(0, ca_len):
458
                col = chr(ord('C') + i)
459
460
                ws[col + str(current_row_number)].fill = table_fill
461
                ws[col + str(current_row_number)].font = title_font
462
                ws[col + str(current_row_number)].alignment = c_c_alignment
463
                ws[col + str(current_row_number)] = reporting_period_data['names'][i] + \
464
                    " (" + reporting_period_data['units'][i] + ")"
465
                ws[col + str(current_row_number)].border = f_border
466
467
            end_col = chr(ord(col) + 1)
468
469
            ws[end_col + str(current_row_number)].fill = table_fill
470
            ws[end_col + str(current_row_number)].font = title_font
471
            ws[end_col + str(current_row_number)].alignment = c_c_alignment
472
            ws[end_col + str(current_row_number)] = "总计 (" + reporting_period_data['total_unit'] + ")"
473
            ws[end_col + str(current_row_number)].border = f_border
474
475
            current_row_number += 1
476
477
            for i in range(0, len(time)):
478
                ws['B' + str(current_row_number)].font = title_font
479
                ws['B' + str(current_row_number)].alignment = c_c_alignment
480
                ws['B' + str(current_row_number)] = time[i]
481
                ws['B' + str(current_row_number)].border = f_border
482
483
                col = 'B'
484
485
                every_day_total = 0
486
487
                for j in range(0, ca_len):
488
                    col = chr(ord('C') + j)
489
490
                    ws[col + str(current_row_number)].font = title_font
491
                    ws[col + str(current_row_number)].alignment = c_c_alignment
492
                    value = round(reporting_period_data['values'][j][i], 2)
493
                    every_day_total += value
494
                    ws[col + str(current_row_number)] = value
495
                    ws[col + str(current_row_number)].border = f_border
496
497
                end_col = chr(ord(col) + 1)
498
                ws[end_col + str(current_row_number)].font = title_font
499
                ws[end_col + str(current_row_number)].alignment = c_c_alignment
500
                ws[end_col + str(current_row_number)] = round(every_day_total, 2)
501
                ws[end_col + str(current_row_number)].border = f_border
502
503
                current_row_number += 1
504
505
            table_end_row_number = current_row_number - 1
506
507
            ws['B' + str(current_row_number)].font = title_font
508
            ws['B' + str(current_row_number)].alignment = c_c_alignment
509
            ws['B' + str(current_row_number)] = '小计'
510
            ws['B' + str(current_row_number)].border = f_border
511
512
            col = 'B'
513
514
            for i in range(0, ca_len):
515
                col = chr(ord('C') + i)
516
                ws[col + str(current_row_number)].font = title_font
517
                ws[col + str(current_row_number)].alignment = c_c_alignment
518
                ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
519
                ws[col + str(current_row_number)].border = f_border
520
521
                # line
522
                line = LineChart()
523
                line.title = '报告期成本 - ' + ws.cell(column=3+i, row=table_start_row_number).value
524
                labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
525
                line_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number)
526
                line.add_data(line_data, titles_from_data=True)
527
                line.set_categories(labels)
528
                line_data = line.series[0]
529
                line_data.marker.symbol = "circle"
530
                line_data.smooth = True
531
                line.x_axis.crosses = 'min'
532
                line.height = 8.25
533
                line.width = 24
534
                line.dLbls = DataLabelList()
535
                line.dLbls.dLblPos = 't'
536
                line.dLbls.showVal = True
537
                line.dLbls.showPercent = False
538
                chart_col = 'B'
539
                chart_cell = chart_col + str(table_start_draw_flag + 6 * i)
540
                ws.add_chart(line, chart_cell)
541
542
            end_col = chr(ord(col) + 1)
543
            ws[end_col + str(current_row_number)].font = title_font
544
            ws[end_col + str(current_row_number)].alignment = c_c_alignment
545
            ws[end_col + str(current_row_number)] = round(reporting_period_data['total'], 2)
546
            ws[end_col + str(current_row_number)].border = f_border
547
548
            current_row_number += 1
549
550
    else:
551
        for i in range(30, 69 + 1):
552
            current_row_number = 70
553
            ws.row_dimensions[i].height = 0.1
554
555
    filename = str(uuid.uuid4()) + '.xlsx'
556
    wb.save(filename)
557
558
    return filename
559