Exemple #1
0
def create_dummy_devices(data,
                         request_type,
                         request,
                         db=None,
                         file_path=None,
                         file_content=None):
    """Helper method to create a dummy request with devices and assign it to a dummy reviewer.
    based on request_type.
    """
    if request_type == 'Registration':
        data.update({'reg_details_id': request.id})
        device = RegDevice.create(data)
        device.technologies = DeviceTechnology.create(device.id,
                                                      data.get('technologies'))
        Device.create(RegDetails.get_by_id(request.id), device.id)
    else:  # De-registration
        # creating sample file
        if not os.path.exists(os.path.dirname(file_path)):
            os.makedirs(os.path.dirname(file_path))
        with open(file_path, 'w') as f:
            for content in file_content:
                f.write(content)
                f.write('\n')

        data = DeRegDevice.curate_args(data, request)
        imei_tac_map = Utilities.extract_imeis_tac_map(data, request)
        created = DeRegDevice.bulk_create(data, request)
        device_id_tac_map = Utilities.get_id_tac_map(created)
        for device in device_id_tac_map:
            device_imeis = imei_tac_map.get(device.get('tac'))
            dereg_imei_list = DeRegImei.get_deregimei_list(
                device.get('id'), device_imeis)
            db.session.execute(DeRegImei.__table__.insert(), dereg_imei_list)
    return request
Exemple #2
0
    def index_dereg_device(self, conn):
        """Method to index the De-Registration Device table."""

        try:
            DeRegDevice.create_index(conn)
            return "De-Registration Device indexed successfully"
        except SQLAlchemyError as e:
            raise e
 def post():
     """POST method handler, creates new devices for request."""
     dereg_id = request.form.to_dict().get('dereg_id', None)
     if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
             dereg_id):
         return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                         status=CODES.get("UNPROCESSABLE_ENTITY"),
                         mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     try:
         schema_request = DeRegRequestSchema()
         device_schema = DeRegDeviceSchema()
         dereg = DeRegDetails.get_by_id(dereg_id)
         args = request.form.to_dict()
         args = DeRegDevice.curate_args(args, dereg)
         validation_errors = schema_request.validate(args)
         if validation_errors:
             return Response(app.json_encoder.encode(validation_errors),
                             status=CODES.get("UNPROCESSABLE_ENTITY"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
         imei_tac_map = Utilities.extract_imeis_tac_map(args, dereg)
         imeis_list = Utilities.extract_imeis(imei_tac_map)
         not_registered_imeis = Utilities.get_not_registered_imeis(
             imeis_list)
         if not_registered_imeis:
             error = {'not_registered_imeis': not_registered_imeis}
             return Response(json.dumps(error),
                             status=CODES.get("UNPROCESSABLE_ENTITY"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
         else:
             old_devices = list(map(lambda x: x.id, dereg.devices))
             created = DeRegDevice.bulk_create(args, dereg)
             device_id_tac_map = Utilities.get_id_tac_map(created)
             devices = device_schema.dump(created, many=True)
             dereg.update_status('Awaiting Documents')
             db.session.commit()
             DeRegDevice.bulk_insert_imeis(device_id_tac_map, imei_tac_map,
                                           old_devices, imeis_list, dereg)
             response = {'devices': devices.data, 'dreg_id': dereg.id}
             return Response(json.dumps(response),
                             status=CODES.get("OK"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     except Exception as e:  # pragma: no cover
         app.logger.exception(e)
         error = {
             'message':
             [_('Failed to retrieve response, please try later')]
         }
         return Response(app.json_encoder.encode(error),
                         status=CODES.get('INTERNAL_SERVER_ERROR'),
                         mimetype=MIME_TYPES.get('APPLICATION_JSON'))
     finally:
         db.session.close()
Exemple #4
0
    def post(dereg_id):
        """POST method handler, restarts processing of a request."""
        if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
                dereg_id):
            return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        try:
            dereg = DeRegDetails.get_by_id(dereg_id)
            # day_passed = (datetime.now() - dereg.updated_at) > timedelta(1)
            failed_status_id = Status.get_status_id('Failed')
            processing_failed = dereg.processing_status in [failed_status_id]
            report_failed = dereg.report_status in [failed_status_id]
            # report_timeout = dereg.report_status == Status.get_status_id('Processing') and day_passed
            processing_required = processing_failed or report_failed
            if processing_required:  # pragma: no cover
                dereg_devices = DeRegDevice.get_devices_by_dereg_id(dereg.id)
                dereg_devices_data = DeRegDeviceSchema().dump(dereg_devices,
                                                              many=True).data
                dereg_devices_ids = list(
                    map(lambda x: x['id'], dereg_devices_data))
                args = {'devices': dereg_devices_data}
                imei_tac_map = Utilities.extract_imeis_tac_map(args, dereg)
                imeis_list = Utilities.extract_imeis(imei_tac_map)
                created = DeRegDevice.bulk_create(args, dereg)
                device_id_tac_map = Utilities.get_id_tac_map(created)
                DeRegDevice.bulk_insert_imeis(device_id_tac_map, imei_tac_map,
                                              dereg_devices_ids, imeis_list,
                                              dereg)
                response = {'message': 'Request performed successfully.'}
            else:
                response = app.json_encoder.encode(
                    {'message': _('This request cannot be processed')})

            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)

            data = {'message': _('failed to restart process')}

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
Exemple #5
0
    def get(dereg_id):
        """GET method handler, to return all section of a request."""
        try:
            if not dereg_id.isdigit() or not DeRegDetails.exists(dereg_id):
                return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            dereg_details = DeRegDetails.get_by_id(dereg_id)
            dereg_schema = DeRegDetailsSchema()
            doc_schema = DeRegDocumentsSchema()
            device_schema = DeRegDeviceSchema()

            dereg_devices = DeRegDevice.get_devices_by_dereg_id(dereg_id)
            dereg_documents = DeRegDocuments.get_by_reg_id(dereg_id)

            deregistration_data = dereg_schema.dump(dereg_details).data
            device_data = device_schema.dump(dereg_devices, many=True).data
            document_data = doc_schema.dump(dereg_documents, many=True).data

            response = {
                'dereg_details': deregistration_data,
                'dereg_device': device_data,
                'dereg_docs': document_data
            }

            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            app.logger.exception(e)

            data = {
                'message': [
                    _('De-Registration request failed, check upload path or database connection'
                      )
                ]
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
 def get(dereg_id):
     """GET method handler, returns device of a request."""
     if not dereg_id.isdigit() or not DeRegDetails.exists(dereg_id):
         return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                         mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     try:
         schema = DeRegDeviceSchema()
         dereg_devices = DeRegDevice.get_devices_by_dereg_id(dereg_id)
         response = schema.dump(dereg_devices, many=True).data
         return Response(json.dumps(response), status=CODES.get("OK"),
                         mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     except Exception as e:  # pragma: no cover
         app.logger.exception(e)
         error = {
             'message': [_('Failed to retrieve response, please try later')]
         }
         return Response(app.json_encoder.encode(error), status=CODES.get('INTERNAL_SERVER_ERROR'),
                         mimetype=MIME_TYPES.get('APPLICATION_JSON'))
     finally:
         db.session.close()
 def put():
     """PUT method handler, updates devices of the request."""
     dereg_id = request.form.to_dict().get('dereg_id', None)
     if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
             dereg_id):
         return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                         status=CODES.get("UNPROCESSABLE_ENTITY"),
                         mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     try:
         schema_request = DeRegRequestUpdateSchema()
         device_schema = DeRegDeviceSchema()
         dereg = DeRegDetails.get_by_id(dereg_id)
         args = request.form.to_dict()
         args = DeRegDevice.curate_args(args, dereg)
         validation_errors = schema_request.validate(args)
         if validation_errors:
             return Response(app.json_encoder.encode(validation_errors),
                             status=CODES.get("UNPROCESSABLE_ENTITY"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
         imei_tac_map = Utilities.extract_imeis_tac_map(args, dereg)
         imeis_list = Utilities.extract_imeis(imei_tac_map)
         not_registered_imeis = Utilities.get_not_registered_imeis(
             imeis_list)
         if not_registered_imeis:
             error = {'not_registered_imeis': not_registered_imeis}
             return Response(json.dumps(error),
                             status=CODES.get("UNPROCESSABLE_ENTITY"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
         else:
             # day_passed = (datetime.now() - dereg.updated_at) > timedelta(1)
             processing_failed = dereg.processing_status in [
                 Status.get_status_id('Failed'),
                 Status.get_status_id('New Request')
             ]
             report_failed = dereg.report_status == Status.get_status_id(
                 'Failed')
             # report_timeout = dereg.report_status == Status.get_status_id('Processing') and day_passed
             processing_required = processing_failed or report_failed
             if processing_required:
                 old_devices = list(map(lambda x: x.id, dereg.devices))
                 created = DeRegDevice.bulk_create(args, dereg)
                 device_id_tac_map = Utilities.get_id_tac_map(created)
                 devices = device_schema.dump(created, many=True)
                 db.session.commit()
                 DeRegDevice.bulk_insert_imeis(device_id_tac_map,
                                               imei_tac_map, old_devices,
                                               imeis_list, dereg)
                 response = {'devices': devices.data, 'dreg_id': dereg.id}
             else:
                 response = {'devices': [], 'dreg_id': dereg.id}
             return Response(json.dumps(response),
                             status=CODES.get("OK"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     except Exception as e:  # pragma: no cover
         app.logger.exception(e)
         error = {
             'message':
             [_('Failed to retrieve response, please try later')]
         }
         return Response(app.json_encoder.encode(error),
                         status=CODES.get('INTERNAL_SERVER_ERROR'),
                         mimetype=MIME_TYPES.get('APPLICATION_JSON'))
     finally:
         db.session.close()