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_status = 'Pending Review' if app.config['AUTOMATE_IMEI_CHECK'] else 'Awaiting Documents'
             dereg.update_status(dereg_status)
             db.session.commit()
             log = EsLog.new_device_serialize(devices.data, 'Device Deregistration Request', regdetails=dereg,
                                              imeis=imeis_list, reg_status=dereg_status, method='Post', dereg=True)
             EsLog.insert_log(log)
             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()
Esempio n. 2
0
    def post():
        """POST method handler,
        Create/Submit a new De-Registration details.
        """
        tracking_id = uuid.uuid4()
        try:
            schema = DeRegDetailsSchema()
            args = DeRegDetails.curate_args(request)
            file = request.files.get('file')
            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"))
            imei_file = Utilities.store_file(file, tracking_id)
            if imei_file:
                return Response(json.dumps(imei_file),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            imei_file = Utilities.process_de_reg_file(
                file.filename.split("/")[-1], tracking_id, args)
            errored = 'device_count' in imei_file or 'invalid_imeis' in imei_file or \
                      'duplicate_imeis' in imei_file or 'invalid_format' in imei_file

            imeis_list = Utilities.extract_imeis(imei_file)

            if not errored:
                gsma_response = Utilities.get_device_details_by_tac(imei_file)
                response = DeRegDetails.create(args, tracking_id)
                db.session.commit()
                response = schema.dump(response, many=False).data
                log = EsLog.new_request_serialize(response,
                                                  "DeRegistration",
                                                  imeis=imeis_list,
                                                  dereg=True,
                                                  method="Post")
                EsLog.insert_log(log)
                response = {'request': response, 'devices': gsma_response}
                return Response(json.dumps(response),
                                status=CODES.get("OK"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                return Response(app.json_encoder.encode(imei_file),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            db.session.rollback()
            Utilities.remove_directory(tracking_id)
            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()
Esempio n. 3
0
    def put():
        """PUT method handler,
        updates existing de registration request.
        """
        dereg_id = request.form.to_dict().get('dereg_id', None)
        try:
            schema = DeRegDetailsUpdateSchema()
            if dereg_id and dereg_id.isdigit() and DeRegDetails.exists(
                    dereg_id):
                dreg_details = DeRegDetails.get_by_id(dereg_id)
            else:
                return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            args = DeRegDetails.curate_args(request)
            file = request.files.get('file')
            tracking_id = dreg_details.tracking_id
            if dreg_details:
                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:
                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):
                    return Response(
                        app.json_encoder.encode(response),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                else:
                    log = EsLog.new_request_serialize(response,
                                                      "Close De-Registration",
                                                      method="Put")
                    EsLog.insert_log(log)
                    response = schema.dump(response, many=False).data
                    return Response(
                        json.dumps(response),
                        status=CODES.get("OK"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if file:
                response = Utilities.store_file(file, tracking_id)
                imeis_list = Utilities.extract_imeis(response)
                if response:
                    return Response(
                        json.dumps(response),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                filename = file.filename
            elif dreg_details.status == Status.get_status_id('New Request'):
                filename = dreg_details.file
                args.update({'device_count': dreg_details.device_count})
            else:
                filename = None

            if filename:
                response = Utilities.process_de_reg_file(
                    filename, tracking_id, args)
                imeis_list = Utilities.extract_imeis(response)
                errored = 'device_count' in response or 'invalid_imeis' in response or \
                          'duplicate_imeis' in response or 'invalid_format' in response
                if not errored:
                    gsma_response = Utilities.get_device_details_by_tac(
                        response)
                    response = DeRegDetails.update(args,
                                                   dreg_details,
                                                   file=True)
                    response = schema.dump(response, many=False).data
                    log = EsLog.new_request_serialize(response,
                                                      "DeRegistration",
                                                      imeis=imeis_list,
                                                      dereg=True,
                                                      method="Put")
                    EsLog.insert_log(log)
                    response = {'request': response, 'devices': gsma_response}
                    return Response(
                        json.dumps(response),
                        status=CODES.get("OK"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                else:
                    return Response(
                        app.json_encoder.encode(response),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                response = DeRegDetails.update(args, dreg_details, file=False)
                response = schema.dump(response, many=False).data
                log = EsLog.new_request_serialize(response,
                                                  "DeRegistration",
                                                  dereg=True,
                                                  method="Put")
                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': [
                    _('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()
Esempio n. 4
0
    def auto_approve(task_id, reg_details):
        # TODO: Need to remove duplicated session which throws warning
        from app.api.v1.resources.reviewer import SubmitReview
        from app.api.v1.models.devicequota import DeviceQuota as DeviceQuotaModel
        from app.api.v1.models.status import Status
        from app.api.v1.models.eslog import EsLog
        import json
        sr = SubmitReview()

        try:
            result = Utilities.check_request_status(task_id)
            section_status = 6
            sections_comment = "Auto"
            auto_approved_sections = [
                'device_quota', 'device_description', 'imei_classification',
                'imei_registration'
            ]

            if result:
                if result['non_compliant'] != 0 or result['stolen'] != 0 or result['compliant_active'] != 0 \
                        or result['provisional_non_compliant'] != 0:
                    sections_comment = sections_comment + ' Rejected, Device/s found in Non-Compliant State'
                    status = 'Rejected'
                    section_status = 7
                    message = 'Your request {id} has been rejected because Non-Compliant Device Found in it.'.format(
                        id=reg_details.id)
                else:
                    sections_comment = sections_comment + ' Approved'
                    status = 'Approved'
                    message = 'Your request {id} has been Approved'.format(
                        id=reg_details.id)

                if status == 'Approved':
                    # checkout device quota
                    imeis = DeRegDetails.get_normalized_imeis(reg_details)
                    user_quota = DeviceQuotaModel.get(reg_details.user_id)
                    current_quota = user_quota.reg_quota
                    user_quota.reg_quota = current_quota - len(imeis)
                    DeviceQuotaModel.commit_quota_changes(user_quota)
                    imeis = DeRegDetails.get_normalized_imeis(reg_details)

                    Utilities.de_register_imeis(imeis)

                    for section in auto_approved_sections:
                        DeRegDetails.add_comment(section, sections_comment,
                                                 reg_details.user_id,
                                                 'Auto Reviewed',
                                                 section_status,
                                                 reg_details.id)

                sr._SubmitReview__generate_notification(
                    user_id=reg_details.user_id,
                    request_id=reg_details.id,
                    request_type='de-registration',
                    request_status=section_status,
                    message=message)

                reg_details.summary = json.dumps({'summary': result})
                reg_details.report = result.get('compliant_report_name')
                reg_details.update_report_status('Processed')
                reg_details.update_status(status)
                reg_details.report_allowed = True
                reg_details.save()
                db.session.commit()
                # create log
                log = EsLog.auto_review(reg_details, "De-Registration Request",
                                        'Post', status)
                EsLog.insert_log(log)
                return True
            else:
                reg_details.update_processing_status('Failed')
                reg_details.update_report_status('Failed')
                reg_details.update_status('Failed')
                db.session.commit()
                log = EsLog.auto_review(
                    reg_details, "De-Registration Request", 'Post',
                    Status.get_status_type(reg_details.status))
                EsLog.insert_log(log)

        except Exception as e:  # pragma: no cover
            app.logger.exception(e)
            db.session.rollback()
            reg_details.update_processing_status('Failed')
            reg_details.update_status('Failed')
            message = 'Your request {id} has failed please re-initiate device request'.format(
                id=reg_details.id)
            sr._SubmitReview__generate_notification(
                user_id=reg_details.user_id,
                request_id=reg_details.id,
                request_type='registration',
                request_status=7,
                message=message)
            db.session.commit()
            # create log
            log = EsLog.auto_review(reg_details, "De-Registration Request",
                                    'Post',
                                    Status.get_status_type(reg_details.status))
            EsLog.insert_log(log)
Esempio n. 5
0
    def post():
        """POST method handler, creates 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(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = DeRegDocumentsSchema()
            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(app.json_encoder.encode(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            tracking_id = dereg_details.tracking_id
            created = DeRegDocuments.bulk_create(request.files, dereg_details,
                                                 time)
            response = Utilities.store_files(request.files, tracking_id, time)
            if response:
                return Response(app.json_encoder.encode(response),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            dereg_details.update_status('Pending Review')
            message = schema.dump(created, many=True).data
            log = EsLog.new_doc_serialize(message,
                                          request_type="De-Registration",
                                          regdetails=dereg_details,
                                          reg_status="Pending Review",
                                          method='Post',
                                          request='De-Registration')
            db.session.commit()
            EsLog.insert_log(log)
            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()
    def auto_approve(task_id, reg_details, flatten_imeis, app):
        from app.api.v1.resources.reviewer import SubmitReview
        from app.api.v1.models.devicequota import DeviceQuota as DeviceQuotaModel
        from app.api.v1.models.eslog import EsLog
        from app.api.v1.models.status import Status
        import json
        sr = SubmitReview()
        try:
            result = Utilities.check_request_status(task_id)
            duplicate_imeis = RegDetails.get_duplicate_imeis(reg_details)
            res = RegDetails.get_imeis_count(reg_details.user_id)
            sections_comment = "Auto"
            section_status = 6
            auto_approved_sections = [
                'device_quota', 'device_description', 'imei_classification',
                'imei_registration'
            ]

            if result:
                flatten_imeis = Utilities.bulk_normalize(flatten_imeis)

                if result['non_compliant'] != 0 or result['stolen'] != 0 or result['compliant_active'] != 0 \
                        or result['provisional_non_compliant'] != 0 or result['provisional_compliant'] != 0:
                    sections_comment = sections_comment + ' Rejected, Device/Devices found in Non-Compliant States'
                    status = 'Rejected'
                    section_status = 7
                    message = 'Your request {id} has been rejected'.format(
                        id=reg_details.id)
                else:
                    sections_comment = sections_comment + ' Approved'
                    status = 'Approved'
                    message = 'Your request {id} has been Approved'.format(
                        id=reg_details.id)

                if duplicate_imeis:
                    res.update({
                        'duplicated':
                        len(RegDetails.get_duplicate_imeis(reg_details))
                    })
                    Utilities.generate_imeis_file(duplicate_imeis,
                                                  reg_details.tracking_id,
                                                  'duplicated_imeis')
                    reg_details.duplicate_imeis_file = '{upload_dir}/{tracking_id}/{file}'.format(
                        upload_dir=app.config['DRS_UPLOADS'],
                        tracking_id=reg_details.tracking_id,
                        file='duplicated_imeis.txt')
                    sections_comment = "Auto"
                    status = 'Rejected'
                    sections_comment = sections_comment + ' Rejected, Duplicate IMEIS Found, Please check duplicate file'
                    section_status = 7
                    message = 'Your request {id} has been rejected because duplicate imeis found!'.format(
                        id=reg_details.id)

                if status == 'Approved':
                    # checkout device quota
                    imeis = RegDetails.get_normalized_imeis(reg_details)
                    user_quota = DeviceQuotaModel.get(reg_details.user_id)
                    current_quota = user_quota.reg_quota
                    user_quota.reg_quota = current_quota - len(imeis)
                    DeviceQuotaModel.commit_quota_changes(user_quota)
                    sr._SubmitReview__update_to_approved_imeis(flatten_imeis)
                else:
                    sr._SubmitReview__change_rejected_imeis_status(
                        flatten_imeis)

                for section in auto_approved_sections:
                    RegDetails.add_comment(section, sections_comment,
                                           reg_details.user_id,
                                           'Auto Reviewed', section_status,
                                           reg_details.id)

                reg_details.summary = json.dumps({'summary': result})
                reg_details.report = result.get('compliant_report_name')
                reg_details.update_report_status('Processed')
                reg_details.report_allowed = True
                reg_details.update_status(status)

                sr._SubmitReview__generate_notification(
                    user_id=reg_details.user_id,
                    request_id=reg_details.id,
                    request_type='registration',
                    request_status=section_status,
                    message=message)

                reg_details.save()
                db.session.commit()

                # create log
                log = EsLog.auto_review(reg_details, "Registration Request",
                                        'Post', status)
                EsLog.insert_log(log)

        except Exception as e:  # pragma: no cover
            db.session.rollback()
            reg_details.update_processing_status('Failed')
            reg_details.update_status('Failed')
            message = 'Your request {id} has failed please re-initiate device request'.format(
                id=reg_details.id)
            sr._SubmitReview__generate_notification(
                user_id=reg_details.user_id,
                request_id=reg_details.id,
                request_type='registration',
                request_status=7,
                message=message)
            db.session.commit()
            app.logger.exception(e)
            # create log
            log = EsLog.auto_review(reg_details, "Registration Request",
                                    'Post',
                                    Status.get_status_type(reg_details.status))
            EsLog.insert_log(log)

        return True
Esempio n. 7
0
    def post(self):
        """POST method handler, creates registration requests."""
        tracking_id = uuid.uuid4()
        try:
            # get the posted data

            args = RegDetails.curate_args(request)

            # create Marshmallow object
            schema = RegistrationDetailsSchema()

            # validate CNIC number
            if not args['cnic'] or not args['cnic'].isdigit():
                messages = {
                    'from': 'DRS-USSD',
                    'to': args['msisdn'],
                    'content': "CNIC number is mandatory and must be digits only."
                }
                self.messages_list.append(messages.copy())

                print("Printing the jasmin message")
                print(messages)

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

                return Response(app.json_encoder.encode({"message": "CNIC number is mandatory and must be digits only."}), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            # Multi SIM Validation
            response = ast.literal_eval(args['imeis'])

            message = DeviceDetailsRoutes.multi_sim_validate(response)
            if message is True:
                pass
            elif message is False:
                messages = {
                    'from': 'DRS-USSD',
                    'to': args['msisdn'],
                    'content': "Something went wrong, please try again later"
                }
                self.messages_list.append(messages.copy())

                print("Printing the jasmin message")
                print(self.messages_list)

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

                data = {'message': "Something went wrong while checking multi sim check please try again later!"}
                return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'),
                                mimetype=MIME_TYPES.get('APPLICATION_JSON'))
            else:
                # create messages for user if any
                changed_msgs = []
                for key1, val1 in message.items():
                    for key2, val2 in val1.items():
                        val2 = Ussd_helper.check_forbidden_string(val2)
                        changed_dict = {key2:val2}
                        changed_msgs.append(changed_dict)
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': val2
                        }
                        self.messages_list.append(messages.copy())
                # message = changed_msgs

                print("Printing the jasmin message")
                print(self.messages_list)

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

                data = {'message': changed_msgs}
                return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'),
                                mimetype=MIME_TYPES.get('APPLICATION_JSON'))

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

            if validation_errors:
                for key, value in validation_errors.items():

                    str_val = ''
                    if key == "imeis":
                        if isinstance(value[0], dict):
                            for k_i, v_i in value[0].items():
                                str_val = str_val + str(v_i[0] + ' ' + args['imeis'][0][k_i])+". "
                        else:
                            print(validation_errors)
                            str_val = str_val + str(value[0])
                    else:
                        if key == "msisdn":
                            if isinstance(value, list):
                                str_val = str_val + str(value[0])

                    messages = {
                        'from': 'DRS-USSD',
                        'to': args['msisdn'],
                        'content': key +':' + str(value[0]) if not dict else str(str_val)
                    }
                    self.messages_list.append(messages.copy())

                print("Printing the jasmin messages")
                print(self.messages_list)

                jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network'])
                app.logger.info("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:

                # call KeyCloak for admin Token
                admin_token_data = Key_cloak.get_admin_token()

                # call KeyCloak with token for
                user_data = Key_cloak.check_user_get_data(args, admin_token_data)

                # if user is created, a password is set for it
                arguments = Ussd_helper.set_args_dict_for_regdetails(args, user_data)

                reg_response = RegDetails.create(arguments, tracking_id)

                db.session.commit()

                # get GSMA information and make device call. we get the device id
                if reg_response.id:
                    schema2 = rdSchema()
                    response = schema2.dump(reg_response, many=False).data

                    # Todo: add logging here or below after condition check
                    log = EsLog.new_request_serialize(response, 'USSD Registration', method='Post',
                                                imeis=arguments['imeis'])
                    EsLog.insert_log(log)

                    # get the tac from an imei in the dict and search for GSMA record
                    tac = arguments['imeis'][0][0][0:8]
                    gsma_url = str(app.config['CORE_BASE_URL']+app.config['API_VERSION'])+str('/tac/'+tac)

                    # get GSMA record against each TAC and match them with IMEIs count given in list
                    gsma_response = requests.get(gsma_url).json()

                    if gsma_response["gsma"] is None:
                        # GSMA record not found for the said TAC
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': "No record found for TAC:" + str(tac)
                        }
                        self.messages_list.append(messages.copy())

                        print("Printing the jasmin messages")
                        print(self.messages_list)

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

                        data = {'message': messages['content']}

                        return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'),
                                        mimetype=MIME_TYPES.get('APPLICATION_JSON'))

                    else:

                        # set device data args
                        device_arguments = Ussd_helper.set_args_dict_for_devicedetails(reg_response, arguments, gsma_response)

                        reg_details = RegDetails.get_by_id(reg_response.id)

                        if reg_details:
                            device_arguments.update({'reg_details_id': reg_details.id})
                        else:
                            device_arguments.update({'reg_details_id': ''})

                        device_arguments.update({'device_type': 'Smartphone'})

                        reg_device = RegDevice.create(device_arguments)

                        reg_device.technologies = DeviceTechnology.create(
                            reg_device.id, device_arguments.get('technologies'), True)

                        device_status = 'Pending Review'

                        reg_details.update_status(device_status)

                        DeviceQuotaModel.get_or_create(reg_response.user_id, 'ussd')

                        Utilities.create_directory(tracking_id)

                        db.session.commit()

                        device_schema = DeviceDetailsSchema()
                        device_serialize_data = device_schema.dump(reg_device, many=False).data
                        log = EsLog.new_device_serialize(device_serialize_data, request_type="USSD Device Registration",
                                                         regdetails=reg_details,
                                                         reg_status=device_status, method='Post')
                        EsLog.insert_log(log)

                        Device.create(reg_details, reg_device.id, ussd=True)

                        # delay the process 5 seconds to complete the process
                        time.sleep(5)

                        # get the device details
                        reg_details = RegDetails.get_by_id(reg_response.id)

                        status_msg = Ussd_helper.set_message_for_user_info(reg_details.status)

                        # if reg_details.status == 6:
                        status_msg = status_msg + " Your device tracking id is: " + str(reg_details.id)

                        # send user a details about device
                        messages = {
                            'from': 'DRS-USSD',
                            'to': args['msisdn'],
                            'content': status_msg
                        }
                        self.messages_list.append(messages.copy())

                        # send username and password to the new user
                        if 'password' in user_data:
                            messages = {
                                'from': 'DRS-USSD',
                                'to': args['msisdn'],
                                'content': "New user credentials are, username: "******" and password: "******"Jasmin API response: " + str(jasmin_send_response.status_code))
                        app.logger.info("Printing the message array in CLI mode.")
                        app.logger.info(self.messages_list)
                        response = {
                            'message': 'Device registration has been processed successfully.'
                        }

                        if status_msg:
                            response['status_response'] = status_msg
                        return Response(json.dumps(response), status=CODES.get("OK"),
                                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))

                else:
                    # error in regdetails
                    messages = {
                        'from': 'DRS-USSD',
                        'to': args['msisdn'],
                        'content': "Registration request failed, check upload path or database connection"
                    }
                    self.messages_list.append(messages.copy())

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

                    # response = schema.dump(response, many=False).data
                    data = {'message': [_('Device undergone the process. Please hold your breath.')]}
                    return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'),
                                    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()
Esempio n. 8
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()
    def post():
        """POST method handler, creates registration requests."""
        tracking_id = uuid.uuid4()
        try:
            args = RegDetails.curate_args(request)
            schema = RegistrationDetailsSchema()
            file = request.files.get('file')
            validation_errors = schema.validate(args)
            imei_file = args.get('imeis')
            if validation_errors:
                return Response(app.json_encoder.encode(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if file:
                file_name = file.filename.split("/")[-1]
                imei_file = Utilities.store_file(file, tracking_id)
                if imei_file:
                    return Response(
                        json.dumps(imei_file),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                imei_file = Utilities.process_reg_file(file_name, tracking_id,
                                                       args)
                if isinstance(imei_file, list):
                    response = RegDetails.create(args, tracking_id)
                else:
                    return Response(
                        app.json_encoder.encode(imei_file),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                Utilities.create_directory(tracking_id)
                response = RegDetails.create(args, tracking_id)
            db.session.commit()
            response = schema.dump(response, many=False).data
            log = EsLog.new_request_serialize(response,
                                              "Registration",
                                              imeis=imei_file)
            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()
            Utilities.remove_directory(tracking_id)
            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'))
        except es.ElasticsearchException as e:
            Utilities.remove_directory(tracking_id)
            app.logger.exception(e)
            data = {
                'message': [
                    _('Registration request failed, check elastic search configuration'
                      )
                ]
            }
            db.session.rollback()
            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 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)
        imei_file = args.get('imeis')

        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:
                    log = EsLog.new_request_serialize(response,
                                                      "Close Registration",
                                                      imeis=imei_file,
                                                      method="Put")
                    EsLog.insert_log(log)
                    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)
                imei_file = Utilities.store_file(file, tracking_id)
                if imei_file:
                    return Response(
                        json.dumps(imei_file),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                imei_file = Utilities.process_reg_file(file.filename,
                                                       tracking_id, args)
                if isinstance(imei_file, list):
                    response = RegDetails.update(args, reg_details, True)
                else:
                    return Response(
                        app.json_encoder.encode(imei_file),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                response = RegDetails.update(args, reg_details, False)

            db.session.commit()
            log = EsLog.new_request_serialize(response,
                                              "Update Registration",
                                              imeis=imei_file,
                                              method="Put")
            EsLog.insert_log(log)

            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()