Passed
Push — master ( f5d1d4...0e16a1 )
by Guangyu
08:20 queued 12s
created

excelexporters.metertracking   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 154
Duplicated Lines 23.38 %

Importance

Changes 0
Metric Value
wmc 15
eloc 114
dl 36
loc 154
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
D generate_excel() 0 97 10
B export() 36 36 5

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 gettext
3
import os
4
import uuid
5
from decimal import Decimal
6
7
from openpyxl import Workbook
8
from openpyxl.drawing.image import Image
9
from openpyxl.styles import Alignment, Font
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
19 View Code Duplication
def export(result, space_name, energy_category_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...
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
        pass
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
        pass
54
    return base64_message
55
56
57
def generate_excel(report, space_name, energy_category_name, reporting_start_datetime_local, reporting_end_datetime_local, language):
58
59
    locale_path = './i18n/'
60
    if language == 'zh_CN':
61
        trans = gettext.translation('myems', locale_path, languages=['zh_CN'])
62
    elif language == 'de':
63
        trans = gettext.translation('myems', locale_path, languages=['de'])
64
    elif language == 'en':
65
        trans = gettext.translation('myems', locale_path, languages=['en'])
66
    else:
67
        trans = gettext.translation('myems', locale_path, languages=['en'])
68
    trans.install()
69
    _ = trans.gettext
70
71
    wb = Workbook()
72
    ws = wb.active
73
    ws.title = "MeterTracking"
74
75
    # Column width
76
    for i in range(ord('A'), ord('I')):
77
        ws.column_dimensions[chr(i)].width = 25.0
78
79
    # Head image
80
    ws.row_dimensions[1].height = 105
81
    img = Image("excelexporters/myems.png")
82
    ws.add_image(img, 'A1')
83
84
    # Query Parameters
85
    b_r_alignment = Alignment(vertical='bottom',
86
                              horizontal='right',
87
                              text_rotation=0,
88
                              wrap_text=True,
89
                              shrink_to_fit=False,
90
                              indent=0)
91
    ws['A3'].alignment = b_r_alignment
92
    ws['A3'] = _('Space') + ':'
93
    ws['B3'] = space_name
94
    ws['A4'].alignment = b_r_alignment
95
    ws['A4'] = _('Start Datetime') + ':'
96
    ws['B4'] = reporting_start_datetime_local
97
    ws['A5'].alignment = b_r_alignment
98
    ws['A5'] = _('End Datetime') + ':'
99
    ws['B5'] = reporting_end_datetime_local
100
    ws['A6'].alignment = b_r_alignment
101
    ws['A6'] = _('Start Integrity Rate') + ':'
102
    ws['B6'] = (str(report['start_integrity_rate'] * Decimal(100.0)) + '%') \
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable str does not seem to be defined.
Loading history...
103
        if report['start_integrity_rate'] is not None else None
104
    ws['A7'].alignment = b_r_alignment
105
    ws['A7'] = _('End Integrity Rate') + ':'
106
    ws['B7'] = (str(report['end_integrity_rate'] * Decimal(100.0)) + '%') \
107
        if report['end_integrity_rate'] is not None else None
108
    ws['A8'].alignment = b_r_alignment
109
    ws['A8'] = _('Full Integrity Rate') + ':'
110
    ws['B8'] = (str(report['full_integrity_rate'] * Decimal(100.0)) + '%') \
111
        if report['full_integrity_rate'] is not None else None
112
    ws['A9'].alignment = b_r_alignment
113
    ws['A9'] = _('Energy Category') + ':'
114
    ws['B9'] = energy_category_name if energy_category_name is not None else _('All')
115
116
    # Title
117
    title_font = Font(size=12, bold=True)
118
    ws['A10'].font = title_font
119
    ws['A10'] = _('ID')
120
    ws['B10'].font = title_font
121
    ws['B10'] = _('Name')
122
    ws['C10'].font = title_font
123
    ws['C10'] = _('Space')
124
    ws['D10'].font = title_font
125
    ws['D10'] = _('Cost Center')
126
    ws['E10'].font = title_font
127
    ws['E10'] = _('Energy Category')
128
    ws['F10'].font = title_font
129
    ws['F10'] = _('Description')
130
    ws['G10'].font = title_font
131
    ws['G10'] = _('Start Value')
132
    ws['H10'].font = title_font
133
    ws['H10'] = _('End Value')
134
    ws['I10'].font = title_font
135
    ws['I10'] = _('Difference Value')
136
137
    current_row_number = 11
138
    for i in range(0, len(report['meters'])):
139
        ws['A' + str(current_row_number)] = report['meters'][i]['id']
140
        ws['B' + str(current_row_number)] = report['meters'][i]['meter_name']
141
        ws['C' + str(current_row_number)] = report['meters'][i]['space_name']
142
        ws['D' + str(current_row_number)] = report['meters'][i]['cost_center_name']
143
        ws['E' + str(current_row_number)] = report['meters'][i]['energy_category_name']
144
        ws['F' + str(current_row_number)] = report['meters'][i]['description']
145
        ws['G' + str(current_row_number)] = report['meters'][i]['start_value']
146
        ws['H' + str(current_row_number)] = report['meters'][i]['end_value']
147
        ws['I' + str(current_row_number)] = report['meters'][i]['difference_value']
148
        current_row_number += 1
149
150
    filename = str(uuid.uuid4()) + '.xlsx'
151
    wb.save(filename)
152
153
    return filename
154