def get(reg_id):
        """GET method handler, returns device details."""
        if 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"))

        schema = DeviceDetailsSchema()
        try:
            reg_device = RegDevice.get_device_by_registration_id(reg_id)
            response = schema.dump(reg_device).data if reg_device else {}
            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()
Ejemplo n.º 2
0
    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 get(reg_id):
        """GET method handler, returns request documents."""
        if 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:
            schema = RegistrationDocumentsSchema()
            documents = RegDocuments.get_by_reg_id(reg_id)
            documents = schema.dump(documents, many=True).data
            '''if doc_id:
                if not doc_id.isdigit():
                    documents = DOC_NOT_FOUND_MSG
                else:
                    documents = list(filter(lambda doc: int(doc['id']) == int(doc_id), documents))
                    documents = documents[0] if documents else DOC_NOT_FOUND_MSG
            '''
            return Response(json.dumps(documents),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        except Exception as e:  # pragma: no cover
            app.logger.exception(e)
            data = {
                "message": [_("Error retrieving results. Please try later.")]
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get("BAD_REQUEST"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        finally:
            db.session.close()
Ejemplo n.º 4
0
    def get(reg_id=None):
        """GET method handler, returns registration requests."""
        try:
            schema = RegistrationDetailsSchema()
            if reg_id:
                if not reg_id.isdigit() or not RegDetails.exists(reg_id):
                    return Response(
                        json.dumps(REG_NOT_FOUND_MSG),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))

                response = RegDetails.get_by_id(reg_id)
                response = schema.dump(response).data
            else:
                response = RegDetails.get_all()
                response = schema.dump(response, many=True).data
            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:
            app.logger.exception(e)
            error = {
                'message': ['Failed to retrieve response, please try later']
            }
            return Response(json.dumps(error),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
    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 post():
        """POST method handler, creates registration documents."""
        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:
            schema = RegistrationDocumentsSchema()
            time = datetime.now().strftime('%Y%m%d%H%M%S')
            args = request.form.to_dict()
            args = Utilities.update_args_with_file(request.files, args)
            reg_details = RegDetails.get_by_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"))

            tracking_id = reg_details.tracking_id
            created = RegDocuments.bulk_create(request.files, reg_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"))
            reg_details.update_status('Pending Review')
            message = schema.dump(created, many=True).data
            db.session.commit()
            return Response(json.dumps(message),
                            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 document addition failed, check for valid formats.')
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
Ejemplo n.º 7
0
    def get(self, **kwargs):
        """GET method handler, return registration report."""
        for key, value in kwargs.items():
            if value is None:
                res = {'error': ['{0} is required'.format(key)]}
                return Response(json.dumps(ErrorResponse().dump(res).data),
                                status=422, mimetype='application/json')
        user_type = kwargs.get('user_type')
        request_type = kwargs.get('request_type')
        request_id = kwargs.get('request_id')
        user_id = kwargs.get('user_id')
        if request_type == 'registration_request':
            if not request_id.isdigit() or not RegDetails.exists(request_id):
                return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            req = RegDetails.get_by_id(request_id)
            if not req.report:
                return Response(app.json_encoder.encode(REPORT_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            report_allowed = True if user_type == 'reviewer' or \
                                     (req.user_id == user_id and req.report_allowed) else False
            if report_allowed:
                if user_type == 'reviewer':
                    report_name = req.report
                else:
                    report_name = 'user_report-{}'.format(req.report)
                report = os.path.join(app.config['DRS_UPLOADS'], req.tracking_id, report_name)
                return send_file(report)
            else:
                return Response(app.json_encoder.encode(REPORT_NOT_ALLOWED_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        else:
            if not request_id.isdigit() or not DeRegDetails.exists(request_id):
                return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            req = DeRegDetails.get_by_id(request_id)
            if not req.report:
                return Response(app.json_encoder.encode(REPORT_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            report_allowed = True if user_type == 'reviewer' or \
                                     (req.user_id == user_id and req.report_allowed) else False
            if report_allowed:
                if user_type == 'reviewer':
                    report_name = req.report
                else:
                    report_name = 'user_report-{}'.format(req.report)
                report = os.path.join(app.config['DRS_UPLOADS'], req.tracking_id, report_name)
                return send_file(report)
            else:
                return Response(app.json_encoder.encode(REPORT_NOT_ALLOWED_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
Ejemplo n.º 8
0
    def post():
        """POST method handler, creates a new 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(json.dumps(REG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        try:
            args = request.form.to_dict()
            schema = DeviceDetailsSchema()
            reg_details = RegDetails.get_by_id(reg_id)
            if reg_details:
                args.update({'reg_details_id': reg_details.id})
            else:
                args.update({'reg_details_id': ''})

            validation_errors = schema.validate(args)
            if validation_errors:
                response = Response(
                    json.dumps(validation_errors),
                    status=CODES.get("UNPROCESSABLE_ENTITY"),
                    mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                return response
            reg_device = RegDevice.create(args)
            reg_device.technologies = DeviceTechnology.create(
                reg_device.id, args.get('technologies'))
            response = schema.dump(reg_device, many=False).data
            response['reg_details_id'] = reg_details.id
            reg_details.update_status('Awaiting Documents')
            db.session.commit()
            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:
            db.session.rollback()
            app.logger.exception(e)

            data = {'message': 'request device addition failed'}

            return Response(json.dumps(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
Ejemplo n.º 9
0
    def post(self, **kwargs):
        """Post method handler, set report permissions."""
        for key, value in kwargs.items():
            if value is None:
                res = {'error': ['{0} is required'.format(key)]}
                return Response(json.dumps(ErrorResponse().dump(res).data),
                                status=422, mimetype='application/json')
        user_type = kwargs.get('user_type')
        request_type = kwargs.get('request_type')
        request_id = kwargs.get('request_id')
        user_id = kwargs.get('user_id')
        if request_type == 'registration_request':
            if not request_id.isdigit() or not RegDetails.exists(request_id):
                return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            req = RegDetails.get_by_id(request_id)
            if not req.report:
                return Response(app.json_encoder.encode(REPORT_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if user_type == 'reviewer' and req.reviewer_id == user_id:
                response = RegDetails.toggle_permission(req)
                response = {'message': 'The permission to view report is changed', 'value': response}
                return Response(json.dumps(response), status=CODES.get("OK"),
                                 mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                return Response(app.json_encoder.encode(REPORT_NOT_ALLOWED_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        else:
            if not request_id.isdigit() or not DeRegDetails.exists(request_id):
                return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            req = DeRegDetails.get_by_id(request_id)
            if not req.report:
                return Response(app.json_encoder.encode(REPORT_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if user_type == 'reviewer' and req.reviewer_id == user_id:
                response = DeRegDetails.toggle_permission(req)
                response = {'message': 'The permission to view report is changed', 'value': response}
                return Response(json.dumps(response), status=CODES.get("OK"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                return Response(app.json_encoder.encode(REPORT_NOT_ALLOWED_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
Ejemplo n.º 10
0
    def get(reg_id):
        """GET method handler, return registration sections."""
        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)
            reg_schema = RegistrationDetailsSchema()
            doc_schema = RegistrationDocumentsSchema()
            device_schema = DeviceDetailsSchema()

            reg_device = RegDevice.get_device_by_registration_id(reg_id)
            reg_documents = RegDocuments.get_by_reg_id(reg_id)

            registration_data = reg_schema.dump(reg_details).data
            device_data = device_schema.dump(
                reg_device).data if reg_device else {}
            document_data = doc_schema.dump(reg_documents, many=True).data

            response = {
                'reg_details': registration_data,
                'reg_device': device_data,
                'reg_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': [
                    _('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()
Ejemplo n.º 11
0
    def put():
        """PUT method handler, updates registration requests."""
        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"))

        args = RegDetails.curate_args(request)
        schema = RegistrationDetailsUpdateSchema()
        file = request.files.get('file')
        reg_details = RegDetails.get_by_id(reg_id)
        try:
            tracking_id = reg_details.tracking_id
            if reg_details:
                args.update({
                    'status': reg_details.status,
                    'reg_id': reg_details.id,
                    'processing_status': reg_details.processing_status,
                    'report_status': reg_details.report_status
                })
            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"))
            if args.get('close_request', None) == 'True':
                response = RegDetails.close(reg_details)
                if isinstance(response, dict):
                    return Response(
                        app.json_encoder.encode(response),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                else:
                    response = schema.dump(response, many=False).data
                    return Response(
                        json.dumps(response),
                        status=CODES.get("OK"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if file:
                Utilities.remove_file(reg_details.file, tracking_id)
                response = Utilities.store_file(file, tracking_id)
                if response:
                    return Response(
                        json.dumps(response),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                response = Utilities.process_reg_file(file.filename,
                                                      tracking_id, args)
                if isinstance(response, list):
                    response = RegDetails.update(args, reg_details, True)
                else:
                    return Response(
                        app.json_encoder.encode(response),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                response = RegDetails.update(args, reg_details, False)
            db.session.commit()
            response = schema.dump(response, many=False).data
            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': [
                    _('Registration update 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()
Ejemplo n.º 12
0
    def put(self):
        """PUT method handler, updates existing registration request. """
        try:

            # get the posted data
            args = RegDetails.curate_args(request)

            # create Marshmallow object
            schema = UssdDeleteSchema()

            # validate posted data
            validation_errors = schema.validate(args)

            if validation_errors:

                for key, value in validation_errors.items():
                    messages = {
                        'from': 'DRS-USSD',
                        'to': args['msisdn'],
                        'content': key + ':' + value[0]
                    }
                    self.messages_list.append(messages.copy())

                jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network'])
                print("Jasmin API response: " + str(jasmin_send_response.status_code))
                return Response(app.json_encoder.encode(validation_errors), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:

                dereg_id = args['device_id']

                if dereg_id and dereg_id.isdigit() and RegDetails.exists(dereg_id):

                    # if record matches with the passed MSISDN
                    device_info = UssdModel.get_by_id(dereg_id)

                    if device_info.msisdn != args['msisdn']:
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': "Your MSISDN does not match with the record."
                        }
                        self.messages_list.append(messages.copy())

                        jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network'])
                        print("Jasmin API response: " + str(jasmin_send_response.status_code))

                        data = {'message': [_("Your MSISDN does not match with the record.")]}
                        return Response(app.json_encoder.encode(data),
                                        status=CODES.get("RECORD_MISMATCH"),
                                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                    else:
                        dreg_details = RegDetails.get_by_id(dereg_id)
                else:

                    messages = {
                        'from': 'DRS-USSD',
                        'to': args['msisdn'],
                        'content': 'Delete Request not found.'
                    }
                    self.messages_list.append(messages.copy())

                    jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network'])
                    print("Printing the jasmin send response")
                    print(jasmin_send_response)

                    if jasmin_send_response:
                        print("Jasmin API response: " + str(jasmin_send_response.status_code))
                    else:
                        print("Jasmin API response: " + str(jasmin_send_response))
                    return Response(app.json_encoder.encode({'message': [_('Delete Request not found.')]}),
                                    status=CODES.get("UNPROCESSABLE_ENTITY"),
                                    mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                if dreg_details:
                    normalized_imeis = Ussd_helper.get_normalized_imeis(dreg_details.imeis)
                    Utilities.de_register_imeis(normalized_imeis)
                    args.update({'status': dreg_details.status, 'processing_status': dreg_details.processing_status,
                                 'report_status': dreg_details.report_status})
                validation_errors = schema.validate(args)
                if validation_errors:
                    for key, value in validation_errors.items():
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': key + ':' + value[0]
                        }
                        self.messages_list.append(messages.copy())

                    jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network'])
                    print("Jasmin API response: " + str(jasmin_send_response.status_code))
                    return Response(app.json_encoder.encode(validation_errors),
                                    status=CODES.get("UNPROCESSABLE_ENTITY"),
                                    mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                if args.get('close_request', None) == 'True':

                    response = DeRegDetails.close(dreg_details)

                    if isinstance(response, dict):

                        # let the user know about the deregistration
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': str(response['message'])
                        }

                        self.messages_list.append(messages.copy())

                        jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network'])

                        print("Jasmin API response: " + str(jasmin_send_response.status_code))
                        print(str(response['message']))

                        return Response(app.json_encoder.encode(response), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                    else:
                        log = EsLog.new_request_serialize(dreg_details, 'USSD De-Registration', method='Put')
                        EsLog.insert_log(log)

                        response = schema.dump(response, many=False).data
                        # let the user know about the deregistration
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': str("Device with ID: " + str(dereg_id) + " has been DeRegistered")
                        }

                        self.messages_list.append(messages.copy())

                        jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network'])
                        print("Jasmin API response: " + str(jasmin_send_response.status_code))
                        response['response'] = messages['content']

                        return Response(json.dumps(response), status=CODES.get("OK"),
                                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))

                response = DeRegDetails.update(args, dreg_details, file=False)

                response = schema.dump(response, many=False).data

                # let the user know about the deregistration
                messages = {
                    'from': 'DRS-USSD',
                    'to': args['msisdn'],
                    'content': str(response['message'])
                }

                jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network'])
                self.messages_list.append(messages.copy())

                print("Jasmin API response: " + str(jasmin_send_response.status_code))
                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': [_('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 put():
        """PUT method handler, updates documents."""
        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:
            schema = RegistrationDocumentsUpdateSchema()
            time = datetime.now().strftime('%Y%m%d%H%M%S')
            args = request.form.to_dict()
            args = Utilities.update_args_with_file(request.files, args)
            reg_details = RegDetails.get_by_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"))

            tracking_id = reg_details.tracking_id
            updated = RegDocuments.bulk_update(request.files, reg_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 reg_details.status == Status.get_status_id(
                    'Information Requested'):
                reg_details.update_status('In Review')
                message = 'The request {id} has been updated.'.format(
                    id=reg_details.id)
                notification = Notification(reg_details.reviewer_id,
                                            reg_details.id,
                                            'registration_request',
                                            reg_details.status, message)
                notification.add()
            else:
                reg_details.update_status('Pending Review')
            response = schema.dump(updated, many=True).data
            message = schema.dump(updated, many=True).data

            log = EsLog.new_doc_serialize(
                message,
                request_type="Update Registration Documents",
                regdetails=reg_details,
                reg_status="Pending Review",
                method='Put',
                request='Registration')

            db.session.commit()
            EsLog.insert_log(log)

            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 document updation failed, please try again later.')
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()