Passed
Push — master ( c52799...376802 )
by Guangyu
09:06 queued 11s
created

CostCenterTariffCollection.on_post()   C

Complexity

Conditions 8

Size

Total Lines 58
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 43
dl 0
loc 58
rs 6.9813
c 0
b 0
f 0
cc 8
nop 3

How to fix   Long Method   

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:

1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
import uuid
6
from core.useractivity import user_logger, access_control
7
8
9
class CostCenterCollection:
10
    @staticmethod
11
    def __init__():
12
        """"Initializes CostCenterCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    @staticmethod
20
    def on_get(req, resp):
21
        """Handles GET requests"""
22
        cnx = mysql.connector.connect(**config.myems_system_db)
23
        cursor = cnx.cursor()
24
25
        query = (" SELECT id, name, uuid, external_id "
26
                 " FROM tbl_cost_centers "
27
                 " ORDER BY id")
28
        cursor.execute(query)
29
        rows = cursor.fetchall()
30
        cursor.close()
31
        cnx.disconnect()
32
33
        result = list()
34
        if rows is not None and len(rows) > 0:
35
            for row in rows:
36
                meta_result = {"id": row[0], "name": row[1], "uuid": row[2], "external_id": row[3]}
37
                result.append(meta_result)
38
39
        resp.text = json.dumps(result)
40
41
    @staticmethod
42
    @user_logger
43
    def on_post(req, resp):
44
        """Handles POST requests"""
45
        access_control(req)
46
        try:
47
            raw_json = req.stream.read().decode('utf-8')
48
49
        except Exception as ex:
50
            raise falcon.HTTPError(falcon.HTTP_400, 'API.ERROR', ex)
51
52
        new_values = json.loads(raw_json)
53
54
        if 'name' not in new_values['data'].keys() or len(new_values['data']['name']) <= 0:
55
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
56
                                   description='API.INVALID_NAME_VALUE')
57
        name = str.strip(new_values['data']['name'])
58
59
        if 'external_id' in new_values['data'].keys() and \
60
                new_values['data']['external_id'] is not None and \
61
                len(str(new_values['data']['external_id'])) > 0:
62
            external_id = str.strip(new_values['data']['external_id'])
63
        else:
64
            external_id = None
65
66
        cnx = mysql.connector.connect(**config.myems_system_db)
67
        cursor = cnx.cursor()
68
69
        cursor.execute(" SELECT name "
70
                       " FROM tbl_cost_centers "
71
                       " WHERE name = %s ", (name, ))
72
        if cursor.fetchone() is not None:
73
            cursor.close()
74
            cnx.disconnect()
75
            raise falcon.HTTPError(falcon.HTTP_400,
76
                                   title='API.BAD_REQUEST',
77
                                   description='API.COST_CENTER_NAME_EXISTS')
78
        if external_id is not None:
79
            cursor.execute(" SELECT name "
80
                           " FROM tbl_cost_centers "
81
                           " WHERE external_id = %s ", (external_id, ))
82
            if cursor.fetchone() is not None:
83
                cursor.close()
84
                cnx.disconnect()
85
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
86
                                       description='API.COST_CENTER_EXTERNAL_ID_EXISTS')
87
88
        add_row = (" INSERT INTO tbl_cost_centers "
89
                   "     (name, uuid, external_id) "
90
                   " VALUES (%s, %s, %s) ")
91
        cursor.execute(add_row, (name,
92
                                 str(uuid.uuid4()),
93
                                 external_id,))
94
        new_id = cursor.lastrowid
95
        cnx.commit()
96
        cursor.close()
97
        cnx.disconnect()
98
99
        resp.status = falcon.HTTP_201
100
        resp.location = '/costcenters/' + str(new_id)
101
102
103
class CostCenterItem:
104
    @staticmethod
105
    def __init__():
106
        """"Initializes CostCenterItem"""
107
        pass
108
109
    @staticmethod
110
    def on_options(req, resp, id_):
111
        resp.status = falcon.HTTP_200
112
113
    @staticmethod
114
    def on_get(req, resp, id_):
115
        """Handles GET requests"""
116
        if not id_.isdigit() or int(id_) <= 0:
117
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
118
                                   description='API.INVALID_COST_CENTER_ID')
119
120
        cnx = mysql.connector.connect(**config.myems_system_db)
121
        cursor = cnx.cursor()
122
123
        query = (" SELECT id, name, uuid, external_id "
124
                 " FROM tbl_cost_centers "
125
                 " WHERE id = %s ")
126
        cursor.execute(query, (id_,))
127
        row = cursor.fetchone()
128
        cursor.close()
129
        cnx.disconnect()
130
131
        if row is None:
132
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
133
                                   description='API.COST_CENTER_NOT_FOUND')
134
135
        result = {"id": row[0], "name": row[1], "uuid": row[2], "external_id": row[3]}
136
        resp.text = json.dumps(result)
137
138 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
139
    @user_logger
140
    def on_delete(req, resp, id_):
141
        """Handles DELETE requests"""
142
        access_control(req)
143
        if not id_.isdigit() or int(id_) <= 0:
144
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
145
                                   description='API.INVALID_COST_CENTER_ID')
146
147
        cnx = mysql.connector.connect(**config.myems_system_db)
148
        cursor = cnx.cursor()
149
150
        cursor.execute(" SELECT name "
151
                       " FROM tbl_cost_centers "
152
                       " WHERE id = %s ", (id_,))
153
        if cursor.fetchone() is None:
154
            cursor.close()
155
            cnx.disconnect()
156
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
157
                                   description='API.COST_CENTER_NOT_FOUND')
158
159
        # check relation with equipments
160
        cursor.execute(" SELECT id "
161
                       " FROM tbl_equipments "
162
                       " WHERE cost_center_id = %s ", (id_,))
163
        rows_equipments = cursor.fetchall()
164
        if rows_equipments is not None and len(rows_equipments) > 0:
165
            cursor.close()
166
            cnx.disconnect()
167
            raise falcon.HTTPError(falcon.HTTP_400,
168
                                   title='API.BAD_REQUEST',
169
                                   description='API.THERE_IS_RELATION_WITH_EQUIPMENTS')
170
171
        # check relation with combined equipments
172
        cursor.execute(" SELECT id "
173
                       " FROM tbl_combined_equipments "
174
                       " WHERE cost_center_id = %s ", (id_,))
175
        rows_combined_equipments = cursor.fetchall()
176
        if rows_combined_equipments is not None and len(rows_combined_equipments) > 0:
177
            cursor.close()
178
            cnx.disconnect()
179
            raise falcon.HTTPError(falcon.HTTP_400,
180
                                   title='API.BAD_REQUEST',
181
                                   description='API.THERE_IS_RELATION_WITH_COMBINED_EQUIPMENTS')
182
183
        # check relation with tariffs
184
        cursor.execute(" SELECT id "
185
                       " FROM tbl_cost_centers_tariffs "
186
                       " WHERE cost_center_id = %s ", (id_,))
187
        rows_tariffs = cursor.fetchall()
188
        if rows_tariffs is not None and len(rows_tariffs) > 0:
189
            cursor.close()
190
            cnx.disconnect()
191
            raise falcon.HTTPError(falcon.HTTP_400,
192
                                   title='API.BAD_REQUEST',
193
                                   description='API.THERE_IS_RELATION_WITH_TARIFFS')
194
195
        # check relation with meters
196
        cursor.execute(" SELECT id "
197
                       " FROM tbl_meters "
198
                       " WHERE cost_center_id = %s ", (id_,))
199
        rows_meters = cursor.fetchall()
200
        if rows_meters is not None and len(rows_meters) > 0:
201
            cursor.close()
202
            cnx.disconnect()
203
            raise falcon.HTTPError(falcon.HTTP_400,
204
                                   title='API.BAD_REQUEST',
205
                                   description='API.THERE_IS_RELATION_WITH_METERS')
206
207
        # check relation with offline meters
208
        cursor.execute(" SELECT id "
209
                       " FROM tbl_offline_meters "
210
                       " WHERE cost_center_id = %s ", (id_,))
211
        rows_offline_meters = cursor.fetchall()
212
        if rows_offline_meters is not None and len(rows_offline_meters) > 0:
213
            cursor.close()
214
            cnx.disconnect()
215
            raise falcon.HTTPError(falcon.HTTP_400,
216
                                   title='API.BAD_REQUEST',
217
                                   description='API.THERE_IS_RELATION_WITH_OFFLINE_METERS')
218
219
        # check relation with virtual meters
220
        cursor.execute(" SELECT id "
221
                       " FROM tbl_virtual_meters "
222
                       " WHERE cost_center_id = %s ", (id_,))
223
        rows_virtual_meters = cursor.fetchall()
224
        if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
225
            cursor.close()
226
            cnx.disconnect()
227
            raise falcon.HTTPError(falcon.HTTP_400,
228
                                   title='API.BAD_REQUEST',
229
                                   description='API.THERE_IS_RELATION_WITH_OFFLINE_METERS')
230
231
        # check relation with tenants
232
        cursor.execute(" SELECT id "
233
                       " FROM tbl_tenants "
234
                       " WHERE cost_center_id = %s ", (id_,))
235
        rows_tenants = cursor.fetchall()
236
        if rows_tenants is not None and len(rows_tenants) > 0:
237
            cursor.close()
238
            cnx.disconnect()
239
            raise falcon.HTTPError(falcon.HTTP_400,
240
                                   title='API.BAD_REQUEST',
241
                                   description='API.THERE_IS_RELATION_WITH_TENANTS')
242
243
        # check relation with stores
244
        cursor.execute(" SELECT id "
245
                       " FROM tbl_stores "
246
                       " WHERE cost_center_id = %s ", (id_,))
247
        rows_stores = cursor.fetchall()
248
        if rows_stores is not None and len(rows_stores) > 0:
249
            cursor.close()
250
            cnx.disconnect()
251
            raise falcon.HTTPError(falcon.HTTP_400,
252
                                   title='API.BAD_REQUEST',
253
                                   description='API.THERE_IS_RELATION_WITH_STORES')
254
255
        # check relation with spaces
256
        cursor.execute(" SELECT id "
257
                       " FROM tbl_spaces "
258
                       " WHERE cost_center_id = %s ", (id_,))
259
        rows_factories = cursor.fetchall()
260
        if rows_factories is not None and len(rows_factories) > 0:
261
            cursor.close()
262
            cnx.disconnect()
263
            raise falcon.HTTPError(falcon.HTTP_400,
264
                                   title='API.BAD_REQUEST',
265
                                   description='API.THERE_IS_RELATION_WITH_SPACES')
266
267
        # check relation with shopfloors
268
        cursor.execute(" SELECT id "
269
                       " FROM tbl_shopfloors "
270
                       " WHERE cost_center_id = %s ", (id_,))
271
        rows_shopfloors = cursor.fetchall()
272
        if rows_shopfloors is not None and len(rows_shopfloors) > 0:
273
            cursor.close()
274
            cnx.disconnect()
275
            raise falcon.HTTPError(falcon.HTTP_400,
276
                                   title='API.BAD_REQUEST',
277
                                   description='API.THERE_IS_RELATION_WITH_SHOPFLOORS')
278
279
        cursor.execute(" DELETE FROM tbl_cost_centers WHERE id = %s ", (id_,))
280
        cnx.commit()
281
282
        cursor.close()
283
        cnx.disconnect()
284
        resp.status = falcon.HTTP_204
285
286
    @staticmethod
287
    @user_logger
288
    def on_put(req, resp, id_):
289
        """Handles PUT requests"""
290
        access_control(req)
291
        try:
292
            raw_json = req.stream.read().decode('utf-8')
293
        except Exception as ex:
294
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex)
295
296
        if not id_.isdigit() or int(id_) <= 0:
297
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
298
                                   description='API.INVALID_COST_CENTER_ID')
299
300
        new_values = json.loads(raw_json)
301
302
        if 'name' not in new_values['data'].keys() or len(new_values['data']['name']) <= 0:
303
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
304
                                   description='API.INVALID_NAME_VALUE')
305
        name = str.strip(new_values['data']['name'])
306
307
        if 'external_id' in new_values['data'].keys() and \
308
                new_values['data']['external_id'] is not None and \
309
                len(str(new_values['data']['external_id'])) > 0:
310
            external_id = str.strip(new_values['data']['external_id'])
311
        else:
312
            external_id = None
313
314
        cnx = mysql.connector.connect(**config.myems_system_db)
315
        cursor = cnx.cursor()
316
317
        cursor.execute(" SELECT name "
318
                       " FROM tbl_cost_centers "
319
                       " WHERE id = %s ", (id_,))
320
        if cursor.fetchone() is None:
321
            cursor.close()
322
            cnx.disconnect()
323
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
324
                                   description='API.COST_CENTER_NOT_FOUND')
325
326
        cursor.execute(" SELECT name "
327
                       " FROM tbl_cost_centers "
328
                       " WHERE name = %s AND id != %s ",
329
                       (name, id_, ))
330
        if cursor.fetchone() is not None:
331
            cursor.close()
332
            cnx.disconnect()
333
            raise falcon.HTTPError(falcon.HTTP_400,
334
                                   title='API.BAD_REQUEST',
335
                                   description='API.COST_CENTER_NAME_EXISTS')
336
        if external_id is not None:
337
            cursor.execute(" SELECT name "
338
                           " FROM tbl_cost_centers "
339
                           " WHERE external_id = %s AND id != %s ",
340
                           (external_id, id_, ))
341
            if cursor.fetchone() is not None:
342
                cursor.close()
343
                cnx.disconnect()
344
                raise falcon.HTTPError(falcon.HTTP_400,
345
                                       title='API.BAD_REQUEST',
346
                                       description='API.COST_CENTER_EXTERNAL_ID_EXISTS')
347
348
        cursor.execute(" SELECT name "
349
                       " FROM tbl_cost_centers "
350
                       " WHERE id = %s ", (id_,))
351
        if cursor.fetchone() is None:
352
            cursor.close()
353
            cnx.disconnect()
354
            raise falcon.HTTPError(falcon.HTTP_404,
355
                                   title='API.NOT_FOUND',
356
                                   description='API.COST_CENTER_NOT_FOUND')
357
358
        update_row = (" UPDATE tbl_cost_centers "
359
                      " SET name = %s, external_id = %s "
360
                      " WHERE id = %s ")
361
362
        cursor.execute(update_row, (name,
363
                                    external_id,
364
                                    id_,))
365
        cnx.commit()
366
367
        cursor.close()
368
        cnx.disconnect()
369
370
        resp.status = falcon.HTTP_200
371
372
373
class CostCenterTariffCollection:
374
    @staticmethod
375
    def __init__():
376
        """"Initializes CostCenterTariffCollection"""
377
        pass
378
379
    @staticmethod
380
    def on_options(req, resp, id_):
381
        resp.status = falcon.HTTP_200
382
383 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
384
    def on_get(req, resp, id_):
385
        """Handles GET requests"""
386
        if not id_.isdigit() or int(id_) <= 0:
387
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
388
                                   description='API.INVALID_COST_CENTER_ID')
389
390
        cnx = mysql.connector.connect(**config.myems_system_db)
391
        cursor = cnx.cursor()
392
393
        query = (" SELECT t.id, t.name, t.uuid, "
394
                 "        t.tariff_type, t.unit_of_price "
395
                 " FROM tbl_tariffs t, tbl_cost_centers_tariffs ct "
396
                 " WHERE t.id = ct.tariff_id AND ct.cost_center_id = %s "
397
                 " ORDER BY t.name ")
398
        cursor.execute(query, (id_,))
399
        rows = cursor.fetchall()
400
401
        cursor.close()
402
        cnx.disconnect()
403
404
        result = list()
405
        if rows is not None and len(rows) > 0:
406
            for row in rows:
407
                meta_result = {"id": row[0],
408
                               "name": row[1],
409
                               "uuid": row[2],
410
                               "tariff_type": row[3],
411
                               "unit_of_price": row[4]}
412
                result.append(meta_result)
413
414
        resp.text = json.dumps(result)
415
416
    @staticmethod
417
    @user_logger
418
    def on_post(req, resp, id_):
419
        """Handles POST requests"""
420
        access_control(req)
421
        try:
422
            raw_json = req.stream.read().decode('utf-8')
423
        except Exception as ex:
424
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
425
426
        if not id_.isdigit() or int(id_) <= 0:
427
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
428
                                   description='API.INVALID_COST_CENTER_ID')
429
430
        new_values = json.loads(raw_json)
431
432
        cnx = mysql.connector.connect(**config.myems_system_db)
433
        cursor = cnx.cursor()
434
435
        cursor.execute(" SELECT name "
436
                       " FROM tbl_cost_centers "
437
                       " WHERE id = %s ", (id_,))
438
        if cursor.fetchone() is None:
439
            cursor.close()
440
            cnx.disconnect()
441
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
442
                                   description='API.COST_CENTER_NOT_FOUND')
443
444
        cursor.execute(" SELECT name "
445
                       " FROM tbl_tariffs "
446
                       " WHERE id = %s ", (new_values['data']['tariff_id'],))
447
        if cursor.fetchone() is None:
448
            cursor.close()
449
            cnx.disconnect()
450
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
451
                                   description='API.TARIFF_NOT_FOUND')
452
453
        cursor.execute(" SELECT id "
454
                       " FROM tbl_cost_centers_tariffs "
455
                       " WHERE cost_center_id = %s AND tariff_id = %s ", (id_, new_values['data']['tariff_id']))
456
        rows = cursor.fetchall()
457
        if rows is not None and len(rows) > 0:
458
            cursor.close()
459
            cnx.disconnect()
460
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
461
                                   description='API.TARIFF_IS_ALREADY_ASSOCIATED_WITH_COST_CENTER')
462
463
        add_row = (" INSERT INTO tbl_cost_centers_tariffs "
464
                   "             (cost_center_id, tariff_id) "
465
                   " VALUES (%s, %s) ")
466
        cursor.execute(add_row, (id_, new_values['data']['tariff_id'],))
467
        cnx.commit()
468
469
        cursor.close()
470
        cnx.disconnect()
471
472
        resp.status = falcon.HTTP_201
473
        resp.location = '/costcenters/' + str(id_) + '/tariffs/' + str(new_values['data']['tariff_id'])
474
475
476 View Code Duplication
class CostCenterTariffItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
477
    @staticmethod
478
    def __init__():
479
        """"Initializes CostCenterTariffItem"""
480
        pass
481
482
    @staticmethod
483
    def on_options(req, resp, id_, tid):
484
        resp.status = falcon.HTTP_200
485
486
    @staticmethod
487
    @user_logger
488
    def on_delete(req, resp, id_, tid):
489
        """Handles DELETE requests"""
490
        access_control(req)
491
        if not id_.isdigit() or int(id_) <= 0:
492
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
493
                                   description='API.INVALID_COST_CENTER_ID')
494
495
        if not tid.isdigit() or int(tid) <= 0:
496
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
497
                                   description='API.INVALID_TARIFF_ID')
498
499
        cnx = mysql.connector.connect(**config.myems_system_db)
500
        cursor = cnx.cursor()
501
502
        cursor.execute(" SELECT name "
503
                       " FROM tbl_cost_centers "
504
                       " WHERE id = %s ", (id_,))
505
        if cursor.fetchone() is None:
506
            cursor.close()
507
            cnx.disconnect()
508
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
509
                                   description='API.COST_CENTER_NOT_FOUND')
510
511
        cursor.execute(" SELECT name "
512
                       " FROM tbl_tariffs "
513
                       " WHERE id = %s ", (tid,))
514
        if cursor.fetchone() is None:
515
            cursor.close()
516
            cnx.disconnect()
517
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
518
                                   description='API.TARIFF_NOT_FOUND')
519
520
        cursor.execute(" SELECT id "
521
                       " FROM tbl_cost_centers_tariffs "
522
                       " WHERE cost_center_id = %s AND tariff_id = %s ", (id_, tid))
523
        if cursor.fetchone() is None:
524
            cursor.close()
525
            cnx.disconnect()
526
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
527
                                   description='API.TARIFF_IS_NOT_ASSOCIATED_WITH_COST_CENTER')
528
529
        cursor.execute(" DELETE FROM tbl_cost_centers_tariffs "
530
                       " WHERE cost_center_id = %s AND tariff_id = %s ", (id_, tid))
531
        cnx.commit()
532
533
        cursor.close()
534
        cnx.disconnect()
535
536
        resp.status = falcon.HTTP_204
537