Code Duplication    Length = 387-393 lines in 2 locations

myems-api/core/equipment.py 1 location

@@ 944-1330 (lines=387) @@
941
        resp.location = '/equipments/' + str(id_) + 'parameters/' + str(new_id)
942
943
944
class EquipmentParameterItem:
945
    @staticmethod
946
    @user_logger
947
    def __init__():
948
        """Initializes EquipmentParameterItem"""
949
        pass
950
951
    @staticmethod
952
    def on_options(req, resp, id_, pid):
953
        _ = req
954
        resp.status = falcon.HTTP_200
955
        _ = id_
956
        _ = pid
957
958
    @staticmethod
959
    def on_get(req, resp, id_, pid):
960
        if 'API-KEY' not in req.headers or \
961
                not isinstance(req.headers['API-KEY'], str) or \
962
                len(str.strip(req.headers['API-KEY'])) == 0:
963
            access_control(req)
964
        else:
965
            api_key_control(req)
966
        if not id_.isdigit() or int(id_) <= 0:
967
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
968
                                   description='API.INVALID_EQUIPMENT_ID')
969
970
        if not pid.isdigit() or int(pid) <= 0:
971
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
972
                                   description='API.INVALID_EQUIPMENT_PARAMETER_ID')
973
974
        cnx = mysql.connector.connect(**config.myems_system_db)
975
        cursor = cnx.cursor()
976
977
        query = (" SELECT id, name "
978
                 " FROM tbl_points ")
979
        cursor.execute(query)
980
        rows_points = cursor.fetchall()
981
982
        point_dict = dict()
983
        if rows_points is not None and len(rows_points) > 0:
984
            for row in rows_points:
985
                point_dict[row[0]] = {"id": row[0],
986
                                      "name": row[1]}
987
988
        query = (" SELECT id, name, uuid "
989
                 " FROM tbl_meters ")
990
        cursor.execute(query)
991
        rows_meters = cursor.fetchall()
992
993
        meter_dict = dict()
994
        if rows_meters is not None and len(rows_meters) > 0:
995
            for row in rows_meters:
996
                meter_dict[row[2]] = {"type": 'meter',
997
                                      "id": row[0],
998
                                      "name": row[1],
999
                                      "uuid": row[2]}
1000
1001
        query = (" SELECT id, name, uuid "
1002
                 " FROM tbl_offline_meters ")
1003
        cursor.execute(query)
1004
        rows_offline_meters = cursor.fetchall()
1005
1006
        offline_meter_dict = dict()
1007
        if rows_offline_meters is not None and len(rows_offline_meters) > 0:
1008
            for row in rows_offline_meters:
1009
                offline_meter_dict[row[2]] = {"type": 'offline_meter',
1010
                                              "id": row[0],
1011
                                              "name": row[1],
1012
                                              "uuid": row[2]}
1013
1014
        query = (" SELECT id, name, uuid "
1015
                 " FROM tbl_virtual_meters ")
1016
        cursor.execute(query)
1017
        rows_virtual_meters = cursor.fetchall()
1018
1019
        virtual_meter_dict = dict()
1020
        if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
1021
            for row in rows_virtual_meters:
1022
                virtual_meter_dict[row[2]] = {"type": 'virtual_meter',
1023
                                              "id": row[0],
1024
                                              "name": row[1],
1025
                                              "uuid": row[2]}
1026
1027
        query = (" SELECT id, name, parameter_type, "
1028
                 "        constant, point_id, numerator_meter_uuid, denominator_meter_uuid "
1029
                 " FROM tbl_equipments_parameters "
1030
                 " WHERE equipment_id = %s AND id = %s ")
1031
        cursor.execute(query, (id_, pid))
1032
        row = cursor.fetchone()
1033
        cursor.close()
1034
        cnx.close()
1035
1036
        if row is None:
1037
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1038
                                   description='API.EQUIPMENT_PARAMETER_NOT_FOUND_OR_NOT_MATCH')
1039
        else:
1040
            constant = None
1041
            point = None
1042
            numerator_meter = None
1043
            denominator_meter = None
1044
            if row[2] == 'point':
1045
                point = point_dict.get(row[4], None)
1046
                constant = None
1047
                numerator_meter = None
1048
                denominator_meter = None
1049
            elif row[2] == 'constant':
1050
                constant = row[3]
1051
                point = None
1052
                numerator_meter = None
1053
                denominator_meter = None
1054
            elif row[2] == 'fraction':
1055
                constant = None
1056
                point = None
1057
                # find numerator meter by uuid
1058
                numerator_meter = meter_dict.get(row[5], None)
1059
                if numerator_meter is None:
1060
                    numerator_meter = virtual_meter_dict.get(row[5], None)
1061
                if numerator_meter is None:
1062
                    numerator_meter = offline_meter_dict.get(row[5], None)
1063
                # find denominator meter by uuid
1064
                denominator_meter = meter_dict.get(row[6], None)
1065
                if denominator_meter is None:
1066
                    denominator_meter = virtual_meter_dict.get(row[6], None)
1067
                if denominator_meter is None:
1068
                    denominator_meter = offline_meter_dict.get(row[6], None)
1069
1070
            meta_result = {"id": row[0],
1071
                           "name": row[1],
1072
                           "parameter_type": row[2],
1073
                           "constant": constant,
1074
                           "point": point,
1075
                           "numerator_meter": numerator_meter,
1076
                           "denominator_meter": denominator_meter}
1077
1078
        resp.text = json.dumps(meta_result)
1079
1080
    @staticmethod
1081
    @user_logger
1082
    def on_delete(req, resp, id_, pid):
1083
        admin_control(req)
1084
        if not id_.isdigit() or int(id_) <= 0:
1085
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1086
                                   description='API.INVALID_EQUIPMENT_ID')
1087
1088
        if not pid.isdigit() or int(pid) <= 0:
1089
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1090
                                   description='API.INVALID_EQUIPMENT_PARAMETER_ID')
1091
1092
        cnx = mysql.connector.connect(**config.myems_system_db)
1093
        cursor = cnx.cursor()
1094
1095
        cursor.execute(" SELECT name "
1096
                       " FROM tbl_equipments "
1097
                       " WHERE id = %s ",
1098
                       (id_,))
1099
        row = cursor.fetchone()
1100
        if row is None:
1101
            cursor.close()
1102
            cnx.close()
1103
            raise falcon.HTTPError(status=falcon.HTTP_400,
1104
                                   title='API.NOT_FOUND',
1105
                                   description='API.EQUIPMENT_NOT_FOUND')
1106
1107
        cursor.execute(" SELECT name "
1108
                       " FROM tbl_equipments_parameters "
1109
                       " WHERE equipment_id = %s AND id = %s ",
1110
                       (id_, pid,))
1111
        row = cursor.fetchone()
1112
        if row is None:
1113
            cursor.close()
1114
            cnx.close()
1115
            raise falcon.HTTPError(status=falcon.HTTP_400,
1116
                                   title='API.NOT_FOUND',
1117
                                   description='API.EQUIPMENT_PARAMETER_NOT_FOUND_OR_NOT_MATCH')
1118
1119
        cursor.execute(" DELETE FROM tbl_equipments_parameters "
1120
                       " WHERE id = %s ", (pid, ))
1121
        cnx.commit()
1122
1123
        cursor.close()
1124
        cnx.close()
1125
1126
        resp.status = falcon.HTTP_204
1127
1128
    @staticmethod
1129
    @user_logger
1130
    def on_put(req, resp, id_, pid):
1131
        """Handles PUT requests"""
1132
        admin_control(req)
1133
        if not id_.isdigit() or int(id_) <= 0:
1134
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1135
                                   description='API.INVALID_EQUIPMENT_ID')
1136
1137
        if not pid.isdigit() or int(pid) <= 0:
1138
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1139
                                   description='API.INVALID_EQUIPMENT_PARAMETER_ID')
1140
1141
        try:
1142
            raw_json = req.stream.read().decode('utf-8')
1143
        except Exception as ex:
1144
            print(str(ex))
1145
            raise falcon.HTTPError(status=falcon.HTTP_400,
1146
                                   title='API.BAD_REQUEST',
1147
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1148
1149
        new_values = json.loads(raw_json)
1150
1151
        if 'name' not in new_values['data'].keys() or \
1152
                not isinstance(new_values['data']['name'], str) or \
1153
                len(str.strip(new_values['data']['name'])) == 0:
1154
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1155
                                   description='API.INVALID_EQUIPMENT_PARAMETER_NAME')
1156
        name = str.strip(new_values['data']['name'])
1157
1158
        if 'parameter_type' not in new_values['data'].keys() or \
1159
                not isinstance(new_values['data']['parameter_type'], str) or \
1160
                len(str.strip(new_values['data']['parameter_type'])) == 0:
1161
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1162
                                   description='API.INVALID_EQUIPMENT_PARAMETER_TYPE')
1163
1164
        parameter_type = str.strip(new_values['data']['parameter_type'])
1165
1166
        if parameter_type not in ('constant', 'point', 'fraction'):
1167
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1168
                                   description='API.INVALID_EQUIPMENT_PARAMETER_TYPE')
1169
1170
        constant = None
1171
        if 'constant' in new_values['data'].keys():
1172
            if new_values['data']['constant'] is not None and \
1173
                    isinstance(new_values['data']['constant'], str) and \
1174
                    len(str.strip(new_values['data']['constant'])) > 0:
1175
                constant = str.strip(new_values['data']['constant'])
1176
1177
        point_id = None
1178
        if 'point_id' in new_values['data'].keys():
1179
            if new_values['data']['point_id'] is not None and \
1180
                    new_values['data']['point_id'] <= 0:
1181
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1182
                                       description='API.INVALID_POINT_ID')
1183
            point_id = new_values['data']['point_id']
1184
1185
        numerator_meter_uuid = None
1186
        if 'numerator_meter_uuid' in new_values['data'].keys():
1187
            if new_values['data']['numerator_meter_uuid'] is not None and \
1188
                    isinstance(new_values['data']['numerator_meter_uuid'], str) and \
1189
                    len(str.strip(new_values['data']['numerator_meter_uuid'])) > 0:
1190
                numerator_meter_uuid = str.strip(new_values['data']['numerator_meter_uuid'])
1191
1192
        denominator_meter_uuid = None
1193
        if 'denominator_meter_uuid' in new_values['data'].keys():
1194
            if new_values['data']['denominator_meter_uuid'] is not None and \
1195
                    isinstance(new_values['data']['denominator_meter_uuid'], str) and \
1196
                    len(str.strip(new_values['data']['denominator_meter_uuid'])) > 0:
1197
                denominator_meter_uuid = str.strip(new_values['data']['denominator_meter_uuid'])
1198
1199
        cnx = mysql.connector.connect(**config.myems_system_db)
1200
        cursor = cnx.cursor()
1201
1202
        cursor.execute(" SELECT name "
1203
                       " FROM tbl_equipments "
1204
                       " WHERE id = %s ", (id_,))
1205
        if cursor.fetchone() is None:
1206
            cursor.close()
1207
            cnx.close()
1208
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.NOT_FOUND',
1209
                                   description='API.EQUIPMENT_NOT_FOUND')
1210
1211
        cursor.execute(" SELECT name "
1212
                       " FROM tbl_equipments_parameters "
1213
                       " WHERE equipment_id = %s AND id = %s ",
1214
                       (id_, pid,))
1215
        row = cursor.fetchone()
1216
        if row is None:
1217
            cursor.close()
1218
            cnx.close()
1219
            raise falcon.HTTPError(status=falcon.HTTP_400,
1220
                                   title='API.NOT_FOUND',
1221
                                   description='API.EQUIPMENT_PARAMETER_NOT_FOUND_OR_NOT_MATCH')
1222
1223
        cursor.execute(" SELECT name "
1224
                       " FROM tbl_equipments_parameters "
1225
                       " WHERE name = %s AND equipment_id = %s  AND id != %s ", (name, id_, pid))
1226
        row = cursor.fetchone()
1227
        if row is not None:
1228
            cursor.close()
1229
            cnx.close()
1230
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1231
                                   description='API.EQUIPMENT_PARAMETER_NAME_IS_ALREADY_IN_USE')
1232
1233
        # validate by parameter type
1234
        if parameter_type == 'point':
1235
            if point_id is None:
1236
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1237
                                       description='API.INVALID_POINT_ID')
1238
1239
            query = (" SELECT id, name "
1240
                     " FROM tbl_points "
1241
                     " WHERE id = %s ")
1242
            cursor.execute(query, (point_id, ))
1243
            row = cursor.fetchone()
1244
            if row is None:
1245
                cursor.close()
1246
                cnx.close()
1247
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1248
                                       description='API.POINT_NOT_FOUND')
1249
1250
        elif parameter_type == 'constant':
1251
            if constant is None:
1252
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1253
                                       description='API.INVALID_CONSTANT_VALUE')
1254
1255
        elif parameter_type == 'fraction':
1256
1257
            query = (" SELECT id, name, uuid "
1258
                     " FROM tbl_meters ")
1259
            cursor.execute(query)
1260
            rows_meters = cursor.fetchall()
1261
1262
            meter_dict = dict()
1263
            if rows_meters is not None and len(rows_meters) > 0:
1264
                for row in rows_meters:
1265
                    meter_dict[row[2]] = {"type": 'meter',
1266
                                          "id": row[0],
1267
                                          "name": row[1],
1268
                                          "uuid": row[2]}
1269
1270
            query = (" SELECT id, name, uuid "
1271
                     " FROM tbl_offline_meters ")
1272
            cursor.execute(query)
1273
            rows_offline_meters = cursor.fetchall()
1274
1275
            offline_meter_dict = dict()
1276
            if rows_offline_meters is not None and len(rows_offline_meters) > 0:
1277
                for row in rows_offline_meters:
1278
                    offline_meter_dict[row[2]] = {"type": 'offline_meter',
1279
                                                  "id": row[0],
1280
                                                  "name": row[1],
1281
                                                  "uuid": row[2]}
1282
1283
            query = (" SELECT id, name, uuid "
1284
                     " FROM tbl_virtual_meters ")
1285
            cursor.execute(query)
1286
            rows_virtual_meters = cursor.fetchall()
1287
1288
            virtual_meter_dict = dict()
1289
            if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
1290
                for row in rows_virtual_meters:
1291
                    virtual_meter_dict[row[2]] = {"type": 'virtual_meter',
1292
                                                  "id": row[0],
1293
                                                  "name": row[1],
1294
                                                  "uuid": row[2]}
1295
1296
            # validate numerator meter uuid
1297
            if meter_dict.get(numerator_meter_uuid) is None and \
1298
                    virtual_meter_dict.get(numerator_meter_uuid) is None and \
1299
                    offline_meter_dict.get(numerator_meter_uuid) is None:
1300
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1301
                                       description='API.INVALID_NUMERATOR_METER_UUID')
1302
1303
            # validate denominator meter uuid
1304
            if denominator_meter_uuid == numerator_meter_uuid:
1305
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1306
                                       description='API.INVALID_DENOMINATOR_METER_UUID')
1307
1308
            if denominator_meter_uuid not in meter_dict and \
1309
                    denominator_meter_uuid not in virtual_meter_dict and \
1310
                    denominator_meter_uuid not in offline_meter_dict:
1311
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1312
                                       description='API.INVALID_DENOMINATOR_METER_UUID')
1313
1314
        add_values = (" UPDATE tbl_equipments_parameters "
1315
                      " SET name = %s , parameter_type = %s, constant = %s, "
1316
                      "     point_id = %s, numerator_meter_uuid = %s, denominator_meter_uuid = %s "
1317
                      " WHERE id = %s ")
1318
        cursor.execute(add_values, (name,
1319
                                    parameter_type,
1320
                                    constant,
1321
                                    point_id,
1322
                                    numerator_meter_uuid,
1323
                                    denominator_meter_uuid,
1324
                                    pid))
1325
        cnx.commit()
1326
1327
        cursor.close()
1328
        cnx.close()
1329
1330
        resp.status = falcon.HTTP_200
1331
1332
1333
class EquipmentMeterCollection:

myems-api/core/combinedequipment.py 1 location

@@ 1120-1512 (lines=393) @@
1117
        resp.location = '/combinedequipments/' + str(id_) + 'parameters/' + str(new_id)
1118
1119
1120
class CombinedEquipmentParameterItem:
1121
    def __init__(self):
1122
        """"Initializes CombinedEquipmentParameterItem"""
1123
        pass
1124
1125
    @staticmethod
1126
    def on_options(req, resp, id_, pid):
1127
        _ = req
1128
        resp.status = falcon.HTTP_200
1129
        _ = id_
1130
1131
    @staticmethod
1132
    def on_get(req, resp, id_, pid):
1133
        if 'API-KEY' not in req.headers or \
1134
                not isinstance(req.headers['API-KEY'], str) or \
1135
                len(str.strip(req.headers['API-KEY'])) == 0:
1136
            access_control(req)
1137
        else:
1138
            api_key_control(req)
1139
        if not id_.isdigit() or int(id_) <= 0:
1140
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1141
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
1142
1143
        if not pid.isdigit() or int(pid) <= 0:
1144
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1145
                                   description='API.INVALID_COMBINED_EQUIPMENT_PARAMETER_ID')
1146
1147
        cnx = mysql.connector.connect(**config.myems_system_db)
1148
        cursor = cnx.cursor()
1149
1150
        query = (" SELECT id, name "
1151
                 " FROM tbl_points ")
1152
        cursor.execute(query)
1153
        rows_points = cursor.fetchall()
1154
1155
        point_dict = dict()
1156
        if rows_points is not None and len(rows_points) > 0:
1157
            for row in rows_points:
1158
                point_dict[row[0]] = {"id": row[0],
1159
                                      "name": row[1]}
1160
1161
        query = (" SELECT id, name, uuid "
1162
                 " FROM tbl_meters ")
1163
        cursor.execute(query)
1164
        rows_meters = cursor.fetchall()
1165
1166
        meter_dict = dict()
1167
        if rows_meters is not None and len(rows_meters) > 0:
1168
            for row in rows_meters:
1169
                meter_dict[row[2]] = {"type": 'meter',
1170
                                      "id": row[0],
1171
                                      "name": row[1],
1172
                                      "uuid": row[2]}
1173
1174
        query = (" SELECT id, name, uuid "
1175
                 " FROM tbl_offline_meters ")
1176
        cursor.execute(query)
1177
        rows_offline_meters = cursor.fetchall()
1178
1179
        offline_meter_dict = dict()
1180
        if rows_offline_meters is not None and len(rows_offline_meters) > 0:
1181
            for row in rows_offline_meters:
1182
                offline_meter_dict[row[2]] = {"type": 'offline_meter',
1183
                                              "id": row[0],
1184
                                              "name": row[1],
1185
                                              "uuid": row[2]}
1186
1187
        query = (" SELECT id, name, uuid "
1188
                 " FROM tbl_virtual_meters ")
1189
        cursor.execute(query)
1190
        rows_virtual_meters = cursor.fetchall()
1191
1192
        virtual_meter_dict = dict()
1193
        if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
1194
            for row in rows_virtual_meters:
1195
                virtual_meter_dict[row[2]] = {"type": 'virtual_meter',
1196
                                              "id": row[0],
1197
                                              "name": row[1],
1198
                                              "uuid": row[2]}
1199
1200
        query = (" SELECT id, name, parameter_type, "
1201
                 "        constant, point_id, numerator_meter_uuid, denominator_meter_uuid "
1202
                 " FROM tbl_combined_equipments_parameters "
1203
                 " WHERE combined_equipment_id = %s AND id = %s ")
1204
        cursor.execute(query, (id_, pid))
1205
        row = cursor.fetchone()
1206
        cursor.close()
1207
        cnx.close()
1208
1209
        if row is None:
1210
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1211
                                   description='API.COMBINED_EQUIPMENT_PARAMETER_NOT_FOUND_OR_NOT_MATCH')
1212
        else:
1213
            constant = None
1214
            point = None
1215
            numerator_meter = None
1216
            denominator_meter = None
1217
            if row[2] == 'point':
1218
                point = point_dict.get(row[4], None)
1219
                constant = None
1220
                numerator_meter = None
1221
                denominator_meter = None
1222
            elif row[2] == 'constant':
1223
                constant = row[3]
1224
                point = None
1225
                numerator_meter = None
1226
                denominator_meter = None
1227
            elif row[2] == 'fraction':
1228
                constant = None
1229
                point = None
1230
                # find numerator meter by uuid
1231
                numerator_meter = meter_dict.get(row[5], None)
1232
                if numerator_meter is None:
1233
                    numerator_meter = virtual_meter_dict.get(row[5], None)
1234
                if numerator_meter is None:
1235
                    numerator_meter = offline_meter_dict.get(row[5], None)
1236
                # find denominator meter by uuid
1237
                denominator_meter = meter_dict.get(row[6], None)
1238
                if denominator_meter is None:
1239
                    denominator_meter = virtual_meter_dict.get(row[6], None)
1240
                if denominator_meter is None:
1241
                    denominator_meter = offline_meter_dict.get(row[6], None)
1242
1243
            meta_result = {"id": row[0],
1244
                           "name": row[1],
1245
                           "parameter_type": row[2],
1246
                           "constant": constant,
1247
                           "point": point,
1248
                           "numerator_meter": numerator_meter,
1249
                           "denominator_meter": denominator_meter}
1250
1251
        resp.text = json.dumps(meta_result)
1252
1253
    @staticmethod
1254
    @user_logger
1255
    def on_delete(req, resp, id_, pid):
1256
        admin_control(req)
1257
        if not id_.isdigit() or int(id_) <= 0:
1258
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1259
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
1260
1261
        if not pid.isdigit() or int(pid) <= 0:
1262
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1263
                                   description='API.INVALID_COMBINED_EQUIPMENT_PARAMETER_ID')
1264
1265
        cnx = mysql.connector.connect(**config.myems_system_db)
1266
        cursor = cnx.cursor()
1267
1268
        cursor.execute(" SELECT name "
1269
                       " FROM tbl_combined_equipments "
1270
                       " WHERE id = %s ",
1271
                       (id_,))
1272
        row = cursor.fetchone()
1273
        if row is None:
1274
            cursor.close()
1275
            cnx.close()
1276
            raise falcon.HTTPError(status=falcon.HTTP_400,
1277
                                   title='API.NOT_FOUND',
1278
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
1279
1280
        cursor.execute(" SELECT name "
1281
                       " FROM tbl_combined_equipments_parameters "
1282
                       " WHERE combined_equipment_id = %s AND id = %s ",
1283
                       (id_, pid,))
1284
        row = cursor.fetchone()
1285
        if row is None:
1286
            cursor.close()
1287
            cnx.close()
1288
            raise falcon.HTTPError(status=falcon.HTTP_400,
1289
                                   title='API.NOT_FOUND',
1290
                                   description='API.COMBINED_EQUIPMENT_PARAMETER_NOT_FOUND_OR_NOT_MATCH')
1291
1292
        cursor.execute(" DELETE FROM tbl_combined_equipments_parameters "
1293
                       " WHERE id = %s ", (pid,))
1294
        cnx.commit()
1295
1296
        cursor.close()
1297
        cnx.close()
1298
1299
        resp.status = falcon.HTTP_204
1300
1301
    @staticmethod
1302
    @user_logger
1303
    def on_put(req, resp, id_, pid):
1304
        """Handles PUT requests"""
1305
        admin_control(req)
1306
        if not id_.isdigit() or int(id_) <= 0:
1307
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1308
                                   description='API.INVALID_COMBINED_EQUIPMENT_ID')
1309
1310
        if not pid.isdigit() or int(pid) <= 0:
1311
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1312
                                   description='API.INVALID_COMBINED_EQUIPMENT_PARAMETER_ID')
1313
1314
        try:
1315
            raw_json = req.stream.read().decode('utf-8')
1316
        except Exception as ex:
1317
            print(ex)
1318
            raise falcon.HTTPError(status=falcon.HTTP_400,
1319
                                   title='API.BAD_REQUEST',
1320
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1321
1322
        new_values = json.loads(raw_json)
1323
1324
        if 'name' not in new_values['data'].keys() or \
1325
                not isinstance(new_values['data']['name'], str) or \
1326
                len(str.strip(new_values['data']['name'])) == 0:
1327
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1328
                                   description='API.INVALID_COMBINED_EQUIPMENT_PARAMETER_NAME')
1329
        name = str.strip(new_values['data']['name'])
1330
1331
        if 'parameter_type' not in new_values['data'].keys() or \
1332
                not isinstance(new_values['data']['parameter_type'], str) or \
1333
                len(str.strip(new_values['data']['parameter_type'])) == 0:
1334
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1335
                                   description='API.INVALID_COMBINED_EQUIPMENT_PARAMETER_TYPE')
1336
1337
        parameter_type = str.strip(new_values['data']['parameter_type'])
1338
1339
        if parameter_type not in ('constant', 'point', 'fraction'):
1340
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1341
                                   description='API.INVALID_COMBINED_EQUIPMENT_PARAMETER_TYPE')
1342
1343
        constant = None
1344
        if 'constant' in new_values['data'].keys():
1345
            if new_values['data']['constant'] is not None and \
1346
                    isinstance(new_values['data']['constant'], str) and \
1347
                    len(str.strip(new_values['data']['constant'])) > 0:
1348
                constant = str.strip(new_values['data']['constant'])
1349
1350
        point_id = None
1351
        if 'point_id' in new_values['data'].keys():
1352
            if new_values['data']['point_id'] is not None and \
1353
                    new_values['data']['point_id'] <= 0:
1354
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1355
                                       description='API.INVALID_POINT_ID')
1356
            point_id = new_values['data']['point_id']
1357
1358
        numerator_meter_uuid = None
1359
        if 'numerator_meter_uuid' in new_values['data'].keys():
1360
            if new_values['data']['numerator_meter_uuid'] is not None and \
1361
                    isinstance(new_values['data']['numerator_meter_uuid'], str) and \
1362
                    len(str.strip(new_values['data']['numerator_meter_uuid'])) > 0:
1363
                numerator_meter_uuid = str.strip(new_values['data']['numerator_meter_uuid'])
1364
1365
        denominator_meter_uuid = None
1366
        if 'denominator_meter_uuid' in new_values['data'].keys():
1367
            if new_values['data']['denominator_meter_uuid'] is not None and \
1368
                    isinstance(new_values['data']['denominator_meter_uuid'], str) and \
1369
                    len(str.strip(new_values['data']['denominator_meter_uuid'])) > 0:
1370
                denominator_meter_uuid = str.strip(new_values['data']['denominator_meter_uuid'])
1371
1372
        cnx = mysql.connector.connect(**config.myems_system_db)
1373
        cursor = cnx.cursor()
1374
1375
        cursor.execute(" SELECT name "
1376
                       " FROM tbl_combined_equipments "
1377
                       " WHERE id = %s ", (id_,))
1378
        if cursor.fetchone() is None:
1379
            cursor.close()
1380
            cnx.close()
1381
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.NOT_FOUND',
1382
                                   description='API.COMBINED_EQUIPMENT_NOT_FOUND')
1383
1384
        cursor.execute(" SELECT name "
1385
                       " FROM tbl_combined_equipments_parameters "
1386
                       " WHERE combined_equipment_id = %s AND id = %s ",
1387
                       (id_, pid,))
1388
        row = cursor.fetchone()
1389
        if row is None:
1390
            cursor.close()
1391
            cnx.close()
1392
            raise falcon.HTTPError(status=falcon.HTTP_400,
1393
                                   title='API.NOT_FOUND',
1394
                                   description='API.COMBINED_EQUIPMENT_PARAMETER_NOT_FOUND_OR_NOT_MATCH')
1395
1396
        cursor.execute(" SELECT name "
1397
                       " FROM tbl_combined_equipments_parameters "
1398
                       " WHERE name = %s AND combined_equipment_id = %s  AND id != %s ", (name, id_, pid))
1399
        row = cursor.fetchone()
1400
        if row is not None:
1401
            cursor.close()
1402
            cnx.close()
1403
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1404
                                   description='API.COMBINED_EQUIPMENT_PARAMETER_NAME_IS_ALREADY_IN_USE')
1405
1406
        # validate by parameter type
1407
        if parameter_type == 'point':
1408
            if point_id is None:
1409
                cursor.close()
1410
                cnx.close()
1411
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1412
                                       description='API.INVALID_POINT_ID')
1413
1414
            query = (" SELECT id, name "
1415
                     " FROM tbl_points "
1416
                     " WHERE id = %s ")
1417
            cursor.execute(query, (point_id,))
1418
            row = cursor.fetchone()
1419
            if row is None:
1420
                cursor.close()
1421
                cnx.close()
1422
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1423
                                       description='API.POINT_NOT_FOUND')
1424
1425
        elif parameter_type == 'constant':
1426
            if constant is None:
1427
                cursor.close()
1428
                cnx.close()
1429
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1430
                                       description='API.INVALID_CONSTANT_VALUE')
1431
1432
        elif parameter_type == 'fraction':
1433
1434
            query = (" SELECT id, name, uuid "
1435
                     " FROM tbl_meters ")
1436
            cursor.execute(query)
1437
            rows_meters = cursor.fetchall()
1438
1439
            meter_dict = dict()
1440
            if rows_meters is not None and len(rows_meters) > 0:
1441
                for row in rows_meters:
1442
                    meter_dict[row[2]] = {"type": 'meter',
1443
                                          "id": row[0],
1444
                                          "name": row[1],
1445
                                          "uuid": row[2]}
1446
1447
            query = (" SELECT id, name, uuid "
1448
                     " FROM tbl_offline_meters ")
1449
            cursor.execute(query)
1450
            rows_offline_meters = cursor.fetchall()
1451
1452
            offline_meter_dict = dict()
1453
            if rows_offline_meters is not None and len(rows_offline_meters) > 0:
1454
                for row in rows_offline_meters:
1455
                    offline_meter_dict[row[2]] = {"type": 'offline_meter',
1456
                                                  "id": row[0],
1457
                                                  "name": row[1],
1458
                                                  "uuid": row[2]}
1459
1460
            query = (" SELECT id, name, uuid "
1461
                     " FROM tbl_virtual_meters ")
1462
            cursor.execute(query)
1463
            rows_virtual_meters = cursor.fetchall()
1464
1465
            virtual_meter_dict = dict()
1466
            if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
1467
                for row in rows_virtual_meters:
1468
                    virtual_meter_dict[row[2]] = {"type": 'virtual_meter',
1469
                                                  "id": row[0],
1470
                                                  "name": row[1],
1471
                                                  "uuid": row[2]}
1472
1473
            # validate numerator meter uuid
1474
            if meter_dict.get(numerator_meter_uuid) is None and \
1475
                    virtual_meter_dict.get(numerator_meter_uuid) is None and \
1476
                    offline_meter_dict.get(numerator_meter_uuid) is None:
1477
                cursor.close()
1478
                cnx.close()
1479
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1480
                                       description='API.INVALID_NUMERATOR_METER_UUID')
1481
1482
            # validate denominator meter uuid
1483
            if denominator_meter_uuid == numerator_meter_uuid:
1484
                cursor.close()
1485
                cnx.close()
1486
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1487
                                       description='API.INVALID_DENOMINATOR_METER_UUID')
1488
1489
            if denominator_meter_uuid not in meter_dict and \
1490
                    denominator_meter_uuid not in virtual_meter_dict and \
1491
                    denominator_meter_uuid not in offline_meter_dict:
1492
                cursor.close()
1493
                cnx.close()
1494
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1495
                                       description='API.INVALID_DENOMINATOR_METER_UUID')
1496
1497
        add_values = (" UPDATE tbl_combined_equipments_parameters "
1498
                      " SET name = %s , parameter_type = %s, constant = %s, "
1499
                      "     point_id = %s, numerator_meter_uuid = %s, denominator_meter_uuid = %s "
1500
                      " WHERE id = %s ")
1501
        cursor.execute(add_values, (name,
1502
                                    parameter_type,
1503
                                    constant,
1504
                                    point_id,
1505
                                    numerator_meter_uuid,
1506
                                    denominator_meter_uuid,
1507
                                    pid))
1508
        cnx.commit()
1509
1510
        cursor.close()
1511
        cnx.close()
1512
1513
        resp.status = falcon.HTTP_200
1514
1515