def post_process_imei(self, registration_detail): """Process imies after processing.""" if registration_detail.imeis: registration_detail.imeis = ast.literal_eval(registration_detail.imeis) registration_detail.status_label = Status.get_status_type(registration_detail.status) registration_detail.processing_status_label = Status.get_status_type(registration_detail.processing_status) registration_detail.report_status_label = Status.get_status_type(registration_detail.report_status)
def update(cls, args, reg_details, request_file): """Update current regsitration request.""" try: status = Status.get_status_type(reg_details.status) is_processing_needed = True if request_file or 'imeis' in args else False if cls.is_update_allowed(status): if 'device_count' in args: reg_details.device_count = args.get('device_count') if 'imei_per_device' in args: reg_details.imei_per_device = args.get('imei_per_device') if 'file' in args: reg_details.file = args.get('file') if 'imeis' in args: reg_details.imeis = '%s' % args.get('imeis') if 'm_location' in args: reg_details.m_location = args.get('m_location') # else: # reg_details.status = cls.get_update_status(status) or reg_details.status if is_processing_needed: new_status_id = Status.get_status_id('New Request') reg_details.processing_status = new_status_id reg_details.report_status = new_status_id reg_details.report = None reg_details.summary = None reg_details.save() return reg_details except Exception: raise Exception
def update_allow(self, data): """Check if current request is allowed to update.""" status = Status.get_status_type(data['status']) processing_status = Status.get_status_type(data['processing_status']) report_status = Status.get_status_type(data['report_status']) if 'close_request' in data: if status == 'Closed': raise ValidationError( _('The request status is already Closed'), field_names=['message']) elif status in self.closed_restricted: raise ValidationError(_( 'The request status is %(status)s, which cannot be Closed', status=_(status)), field_names=['message']) elif processing_status == 'Processing' or report_status == 'Processing': raise ValidationError( _('The request is in Progress, which cannot be updated'), field_names=['status']) elif status in self.update_restricted: raise ValidationError(_( 'The request status is %(status)s, which cannot be updated', status=_(status)), field_names=['status'])
def put(): """PUT method handler, updates a device.""" reg_id = request.form.to_dict().get('reg_id', None) if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: args = request.form.to_dict() schema = DeviceDetailsUpdateSchema() reg_details = RegDetails.get_by_id(reg_id) reg_device = RegDevice.get_device_by_registration_id(reg_id) if reg_details: args.update({ 'reg_details_id': reg_details.id, 'status': reg_details.status }) else: args.update({'reg_details_id': ''}) validation_errors = schema.validate(args) if validation_errors: return Response(app.json_encoder.encode(validation_errors), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) # day_passed = (datetime.now() - reg_details.updated_at) > timedelta(1) processing_failed = reg_details.processing_status in [ Status.get_status_id('Failed'), Status.get_status_id('New Request') ] report_failed = reg_details.report_status == Status.get_status_id( 'Failed') # report_timeout = reg_details.report_status == Status.get_status_id('Processing') and day_passed processing_required = processing_failed or report_failed reg_device = RegDevice.update(reg_device, args) response = schema.dump(reg_device, many=False).data response['reg_details_id'] = reg_details.id if processing_required: Device.create(reg_details, reg_device.id) 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': _('request device addition failed')} return Response(app.json_encoder.encode(data), status=CODES.get('INTERNAL_SERVER_ERROR'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) finally: db.session.close()
def translate_status(self, data): """ Takes De-Registration details as input and translate codes for statuses and return the object. """ data.status_label = Status.get_status_type(data.status) data.processing_status_label = Status.get_status_type( data.processing_status) data.report_status_label = Status.get_status_type(data.report_status)
def test_get_status_types(session): """Verify that the status_types() returns all the statuses in the table.""" statuses = [ Status(id=344, description='ABCD'), Status(id=888, description='BCDE'), Status(id=999, description='GHIJK') ] session.bulk_save_objects(statuses) session.commit() res = Status.get_status_types() assert res
def create(cls, args, tracking_id): """Add new request data to the table.""" reg_request = cls(args, tracking_id) status_id = Status.get_status_id('New Request') reg_request.status = status_id reg_request.save() return reg_request
def get(self): """GET method handler for server-configs.""" technologies = Technologies.get_technologies() device_types = DeviceType.get_device_types() status_types = Status.get_status_types() system_configs = { 'label': 'automate_imei_request', 'flag': app.config['AUTOMATE_IMEI_CHECK'] },\ { 'label': 'overwrite_device_info', 'flag': app.config['USE_GSMA_DEVICE_INFO'] } documents = { 'registration': Documents.get_documents('registration'), 'de_registration': Documents.get_documents('deregistration') } response = ServerConfigSchema().dump(dict(technologies=technologies, documents=documents, status_types=status_types, device_types=device_types, system_config=system_configs)).data return Response(json.dumps(response), status=200, mimetype='application/json')
def post(reg_id): """POST method handler, restarts processing of a request.""" if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: reg_details = RegDetails.get_by_id(reg_id) # day_passed = (datetime.now() - reg_details.updated_at) > timedelta(1) failed_status_id = Status.get_status_id('Failed') processing_failed = reg_details.processing_status in [failed_status_id] report_failed = reg_details.report_status in [failed_status_id] # report_timeout = reg_details.report_status == Status.get_status_id('Processing') and day_passed processing_required = processing_failed or report_failed if processing_required: # pragma: no cover reg_device = RegDevice.get_device_by_registration_id(reg_details.id) Device.create(reg_details, reg_device.id) 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'))
def update_processing_status(self, status): """Update current processing status of the request.""" try: self.processing_status = Status.get_status_id(status) self.save() except Exception: raise Exception
def update_allow(self, data): """Check if update operation is allowed.""" status = Status.get_status_type(data['status']) if status in self.update_restricted: raise ValidationError(_( 'The request status is %(status)s, which cannot be updated', status=_(status)), field_names=['status'])
def put(): """PUT method handler, updates documents.""" 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(json.dumps(DEREG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: schema = DeRegDocumentsUpdateSchema() time = datetime.now().strftime('%Y%m%d%H%M%S') args = request.form.to_dict() args = Utilities.update_args_with_file(request.files, args) dereg_details = DeRegDetails.get_by_id(dereg_id) if dereg_details: args.update({ 'dereg_details': dereg_details.id, 'status': dereg_details.status }) else: args.update({'dereg_details': ''}) validation_errors = schema.validate(args) if validation_errors: return Response(json.dumps(validation_errors), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) tracking_id = dereg_details.tracking_id updated = DeRegDocuments.bulk_update(request.files, dereg_details, time) response = Utilities.store_files(request.files, tracking_id, time) if response: return Response(json.dumps(response), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) if dereg_details.status == Status.get_status_id( 'Information Requested'): dereg_details.update_status('In Review') else: dereg_details.update_status('Pending Review') response = schema.dump(updated, many=True).data db.session.commit() return Response(json.dumps(response), status=CODES.get("OK"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) except Exception as e: db.session.rollback() app.logger.exception(e) data = { 'message': 'request document updation failed, please try again later.' } return Response(json.dumps(data), status=CODES.get('INTERNAL_SERVER_ERROR'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) finally: db.session.close()
def close(cls, reg_details): """Close a currently active registration request.""" closed = Status.get_status_id('Closed') if reg_details.status == closed: return {'message': 'The request is already closed'} else: reg_details.status = closed reg_details.save_with_commit() return reg_details
def close(cls, dereg_details): """Close currently active request.""" closed = Status.get_status_id('Closed') if dereg_details.status == closed: return {'message': _('The request is already closed')} else: dereg_details.status = closed dereg_details.save_with_commit() return dereg_details
def create(cls, args, tracking_id): try: """Add new request data to the table.""" reg_request = cls(args, tracking_id) status_id = Status.get_status_id('New Request') reg_request.status = status_id reg_request.save() return reg_request except Exception as e: app.logger.exception(e) db.session.rollback()
def __init__(self, args, tracking_id): """Constructor.""" status_id = Status.get_status_id('New Request') self.file = args.get('file') self.device_count = args.get('device_count') self.user_id = args.get('user_id') self.user_name = args.get('user_name') self.reason = args.get('reason') self.tracking_id = tracking_id self.status = status_id self.processing_status = status_id self.report_status = status_id
def check_reg_id(self, data): """Validates request id.""" reg_details_id = data['reg_details_id'] reg_details = RegDetails.get_by_id(reg_details_id) if 'user_id' in data and reg_details.user_id != data['user_id']: raise ValidationError('Permission denied for this request', field_names=['user_id']) if not reg_details: raise ValidationError('The request id provided is invalid', field_names=['reg_id']) else: status = Status.get_status_type(reg_details.status) if status != 'New Request': raise ValidationError(_('This step can only be performed for New Request'), field_names=['status'])
def check_reg_id(self, data): """Validate request id.""" dereg_details_id = data['dereg_details'] dereg_details = DeRegDetails.get_by_id(dereg_details_id) if not dereg_details: raise ValidationError('The request id provided is invalid', field_names=['dereg_id']) if 'user_id' in data and data['user_id'] != dereg_details.user_id: raise ValidationError('Permission denied for this request', field_names=['user_id']) else: status = Status.get_status_type(dereg_details.status) if status != 'Awaiting Documents': raise ValidationError(_('This step can only be performed for request with Awaiting Document status'), field_names=['status'])
def update_allow(self, data): """ This method translates statuses from codes to user readable texts. It checks if the request can be updated or is it update restricted. """ status = Status.get_status_type(data['status']) report_status = Status.get_status_type(data['report_status']) processing_status = Status.get_status_type(data['processing_status']) if 'close_request' in data: if status == 'Closed': raise ValidationError( _('The request status is already Closed').format( _(status)), field_names=['message']) elif status in self.closed_restricted: raise ValidationError(_( 'The request status is %(status)s, which cannot be Closed', status=_(status)), field_names=['message']) elif processing_status == 'Processing' or report_status == 'Processing': raise ValidationError( _('The request is in Progress, which cannot be updated'), field_names=['status']) elif status in self.update_restricted: raise ValidationError(_( 'The request status is %(status)s, which cannot be updated', status=_(status)), field_names=['status']) elif status == 'New Request' and 'file' in data: raise ValidationError(_( 'The request status is %(status)s, which cannot be updated', status=_(status)), field_names=['status']) elif status == 'New Request' and 'reason' in data: raise ValidationError(_( 'The request status is %(status)s, which cannot be updated', status=_(status)), field_names=['reason'])
def update(cls, args, dereg_details, file): """Update current request details.""" try: status = Status.get_status_type(dereg_details.status) processing_required = True if file else False if cls.is_update_allowed(status): if 'device_count' in args: dereg_details.device_count = args.get('device_count') if 'file' in args: dereg_details.file = args.get('file') if 'reason' in args: dereg_details.reason = args.get('reason') if processing_required: new_status_id = Status.get_status_id('New Request') dereg_details.processing_status = new_status_id dereg_details.report_status = new_status_id dereg_details.summary = None dereg_details.report = None # dereg_details.status = cls.get_update_status(status) or dereg_details.status dereg_details.save_with_commit() return dereg_details except Exception: raise Exception
def __init__(self, args, tracking_id): """Constructor.""" status_id = Status.get_status_id('New Request') self.user_id = args.get('user_id') self.user_name = args.get('user_name') self.device_count = args.get('device_count') self.imei_per_device = args.get('imei_per_device') self.file = args.get('file') self.import_type = 'file' if self.file else 'webpage' self.imeis = '%s' % args.get('imeis') self.m_location = args.get('m_location') self.tracking_id = tracking_id self.status = status_id self.processing_status = status_id self.report_status = status_id
def get(self): """GET method handler for server-configs.""" technologies = Technologies.get_technologies() device_types = DeviceType.get_device_types() status_types = Status.get_status_types() documents = { 'registration': Documents.get_documents('registration'), 'de_registration': Documents.get_documents('deregistration') } response = ServerConfigSchema().dump(dict(technologies=technologies, documents=documents, status_types=status_types, device_types=device_types)).data return Response(json.dumps(response), status=200, mimetype='application/json')
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'))
def check_reg_id(self, data): """Validates ID of the request.""" dereg_details_id = data['dereg_id'] dereg_details = DeRegDetails.get_by_id(dereg_details_id) if not dereg_details: raise ValidationError('The request id provided is invalid', field_names=['dereg_id']) if 'user_id' in data and data['user_id'] != dereg_details.user_id: raise ValidationError('Permission denied for this request', field_names=['user_id']) else: status = Status.get_status_type(dereg_details.status) if status in self.update_restricted: raise ValidationError( 'Update is restricted for request in status {0}'.format( status), field_names=['status'])
def test_get_status_id(session): """Verify that the get_status_id() returns correct status id provided the description. """ # create an entry in table statuses = [ Status(id=111, description='ABCD'), Status(id=112, description='BCDE'), Status(id=133, description='GHIJK') ] session.bulk_save_objects(statuses) session.commit() assert Status.get_status_id('ABCD') == 111 assert Status.get_status_id('BCDE') == 112 assert Status.get_status_id('GHIJK') == 133 assert Status.get_status_id('test') is None
def test_get_status_type(session): """Verify that the get_status_type returns correct status description provided the status id. """ # create an entry in table statuses = [ Status(id=115, description='ABCD'), Status(id=116, description='BCDE'), Status(id=122, description='GHIJK') ] session.bulk_save_objects(statuses) session.commit() assert Status.get_status_type(115) == 'ABCD' assert Status.get_status_type(116) == 'BCDE' assert Status.get_status_type(122) == 'GHIJK' assert Status.get_status_type(32424453453) is None
def test_server_config_api(flask_app, db): # pylint: disable=unused-argument """To verify that the server config apis response is correct as per data in database. """ # get data from database status_types = Status.get_status_types() device_types = DeviceType.get_device_types() technologies = Technologies.get_technologies() documents = { 'registration': Documents.get_documents('registration'), 'de_registration': Documents.get_documents('deregistration') } expected_response = ServerConfigsSchema().dump(dict(technologies=technologies, documents=documents, status_types=status_types, device_types=device_types)).data rv = flask_app.get(SERVER_CONFIGS) assert rv.status_code == 200 data = json.loads(rv.data.decode('utf-8')) assert data == expected_response
def update_status(self, status): """Update current status of the request.""" self.status = Status.get_status_id(status) self.save()
def get_update_status(cls, status): """Get updated status of request.""" if status in ['Pending Review', 'Information Requested']: return Status.get_status_id('Pending Review') else: return None
def update_report_status(self, status): """Updates report status of the requests.""" self.report_status = Status.get_status_id(status) self.save()