Passed
Push — master ( 72d593...a065be )
by Guangyu
01:55 queued 11s
created

excelexporters.metercost.generate_excel()   F

Complexity

Conditions 22

Size

Total Lines 229
Code Lines 167

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 167
nop 5
dl 0
loc 229
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like excelexporters.metercost.generate_excel() 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
    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
def export(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
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
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
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['G3'].border = b_border
147
    ws['G3'].alignment = b_c_alignment
148
    ws['G3'].font = name_font
149
    ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
150
    # ws.merge_cells("G3:H3")
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'
155
        wb.save(filename)
156
157
        return filename
158
159
    ###############################
160
    # First:能耗成本总览
161
    ###############################
162
    has_cost_data_flag = True
163
164
    if "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
165
        has_cost_data_flag = False
166
167
    if has_cost_data_flag:
168
        ws['B6'].font = title_font
169
        ws['B6'] = name + '能耗成本总览'
170
171
        reporting_period_data = report['reporting_period']
172
        category = report['meter']['energy_category_name']
173
        ca_len = len(category)
174
175
        ws['B7'].fill = table_fill
176
177
        ws['B8'].font = title_font
178
        ws['B8'].alignment = c_c_alignment
179
        ws['B8'] = '成本'
180
        ws['B8'].border = f_border
181
182
        ws['B9'].font = title_font
183
        ws['B9'].alignment = c_c_alignment
184
        ws['B9'] = '环比'
185
        ws['B9'].border = f_border
186
187
        for i in range(0, ca_len):
188
            col = chr(ord('C')+i)
189
190
            ws[col + '7'].fill = table_fill
191
            ws[col + '7'].font = name_font
192
            ws[col + '7'].alignment = c_c_alignment
193
            ws[col + '7'] = report['meter']['energy_category_name'] + " (" + report['meter']['unit_of_measure'] + ")"
194
            ws[col + '7'].border = f_border
195
196
            ws[col + '8'].font = name_font
197
            ws[col + '8'].alignment = c_c_alignment
198
            ws[col + '8'] = round(reporting_period_data['total_in_category'], 0)
199
            ws[col + '8'].border = f_border
200
201
            ws[col + '9'].font = name_font
202
            ws[col + '9'].alignment = c_c_alignment
203
            ws[col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
204
                if reporting_period_data['increment_rate'] is not None else "-"
205
            ws[col + '9'].border = f_border
206
207
    else:
208
        for i in range(6, 9+1):
209
            ws.rows_dimensions[i].height = 0.1
210
211
    ######################################
212
    # Second:能耗成本详情
213
    ######################################
214
215
    has_cost_datail_flag = True
216
    reporting_period_data = report['reporting_period']
217
    times = reporting_period_data['timestamps']
218
219
    if "values" not in reporting_period_data.keys() or len(reporting_period_data['values']) == 0:
220
        has_cost_datail_flag = False
221
222
    if has_cost_datail_flag:
223
        ws['B11'].font = title_font
224
        ws['B11'] = name + '能耗成本详情'
225
226
        ws['B18'].fill = table_fill
227
        ws['B18'].font = title_font
228
        ws['B18'].border = f_border
229
        ws['B18'].alignment = c_c_alignment
230
        ws['B18'] = '时间'
231
        time = times
232
        has_data = False
233
        max_row = 0
234
        if len(time) > 0:
235
            has_data = True
236
            max_row = 18 + len(time)
237
238
        if has_data:
239
            for i in range(0, len(time)):
240
                col = 'B'
241
                row = str(19+i)
242
243
                ws[col + row].font = title_font
244
                ws[col + row].alignment = c_c_alignment
245
                ws[col + row] = time[i]
246
                ws[col + row].border = f_border
247
248
            bar = BarChart()
249
250
            for i in range(0, ca_len):
0 ignored issues
show
introduced by
The variable ca_len does not seem to be defined for all execution paths.
Loading history...
251
252
                col = chr(ord('C') + i)
253
254
                ws[col + '18'].fill = table_fill
255
                ws[col + '18'].font = title_font
256
                ws[col + '18'].alignment = c_c_alignment
257
                ws[col + '18'] = report['meter']['energy_category_name'] + \
258
                    " (" + report['meter']['unit_of_measure'] + ")"
259
                ws[col + '18'].border = f_border
260
261
                time = times
262
                time_len = len(time)
263
264
                for j in range(0, time_len):
265
                    row = str(19 + j)
266
267
                    ws[col + row].font = title_font
268
                    ws[col + row].alignment = c_c_alignment
269
                    ws[col + row] = round(reporting_period_data['values'][j], 0)
270
                    ws[col + row].border = f_border
271
272
                bar_data = Reference(ws, min_col=3 + i, min_row=18, max_row=max_row + 1)
273
                bar.series.append(Series(bar_data, title_from_data=True))
274
275
            labels = Reference(ws, min_col=2, min_row=19, max_row=max_row + 1)
276
            bar.set_categories(labels)
277
            bar.dLbls = DataLabelList()
278
            bar.dLbls.showVal = True
279
            bar.height = 5.25
280
            bar.width = len(time)
281
            ws.add_chart(bar, "B12")
282
    else:
283
        for i in range(11, 43 + 1):
284
            ws.row_dimensions[i].height = 0.0
285
286
    filename = str(uuid.uuid4()) + '.xlsx'
287
    wb.save(filename)
288
289
    return filename
290